blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 3 264 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 5 140 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 905
values | visit_date timestamp[us]date 2015-08-09 11:21:18 2023-09-06 10:45:07 | revision_date timestamp[us]date 1997-09-14 05:04:47 2023-09-17 19:19:19 | committer_date timestamp[us]date 1997-09-14 05:04:47 2023-09-06 06:22:19 | github_id int64 3.89k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 22
values | gha_event_created_at timestamp[us]date 2012-06-07 00:51:45 2023-09-14 21:58:39 ⌀ | gha_created_at timestamp[us]date 2008-03-27 23:40:48 2023-08-21 23:17:38 ⌀ | gha_language stringclasses 141
values | src_encoding stringclasses 34
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 3 10.4M | extension stringclasses 115
values | content stringlengths 3 10.4M | authors listlengths 1 1 | author_id stringlengths 0 158 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
757c06d90d3bd1b7b8a62c779762a42bca7e62f6 | 9d364070c646239b2efad7abbab58f4ad602ef7b | /platform/external/chromium_org/extensions/browser/app_window/native_app_window.h | 260069166e93025b269d582299d5e9ef295cc922 | [
"BSD-3-Clause"
] | permissive | denix123/a32_ul | 4ffe304b13c1266b6c7409d790979eb8e3b0379c | b2fd25640704f37d5248da9cc147ed267d4771c2 | refs/heads/master | 2021-01-17T20:21:17.196296 | 2016-08-16T04:30:53 | 2016-08-16T04:30:53 | 65,786,970 | 0 | 2 | null | 2020-03-06T22:00:52 | 2016-08-16T04:15:54 | null | UTF-8 | C++ | false | false | 2,120 | h | // Copyright 2014 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef EXTENSIONS_BROWSER_APP_WINDOW_NATIVE_APP_WINDOW_H_
#define EXTENSIONS_BROWSER_APP_WINDOW_NATIVE_APP_WINDOW_H_
#include <vector>
#include "base/memory/scoped_ptr.h"
#include "components/web_modal/web_contents_modal_dialog_host.h"
#include "third_party/skia/include/core/SkColor.h"
#include "ui/base/base_window.h"
#include "ui/gfx/insets.h"
namespace content {
struct NativeWebKeyboardEvent;
}
namespace extensions {
struct DraggableRegion;
class NativeAppWindow : public ui::BaseWindow,
public web_modal::WebContentsModalDialogHost {
public:
virtual void SetFullscreen(int fullscreen_types) = 0;
virtual bool IsFullscreenOrPending() const = 0;
virtual void UpdateWindowIcon() = 0;
virtual void UpdateWindowTitle() = 0;
virtual void UpdateBadgeIcon() = 0;
virtual void UpdateDraggableRegions(
const std::vector<DraggableRegion>& regions) = 0;
virtual SkRegion* GetDraggableRegion() = 0;
virtual void UpdateShape(scoped_ptr<SkRegion> region) = 0;
virtual void HandleKeyboardEvent(
const content::NativeWebKeyboardEvent& event) = 0;
virtual bool IsFrameless() const = 0;
virtual bool HasFrameColor() const = 0;
virtual SkColor ActiveFrameColor() const = 0;
virtual SkColor InactiveFrameColor() const = 0;
virtual gfx::Insets GetFrameInsets() const = 0;
virtual void ShowWithApp() = 0;
virtual void HideWithApp() = 0;
virtual void UpdateShelfMenu() = 0;
virtual gfx::Size GetContentMinimumSize() const = 0;
virtual gfx::Size GetContentMaximumSize() const = 0;
virtual void SetContentSizeConstraints(const gfx::Size& min_size,
const gfx::Size& max_size) = 0;
virtual void SetVisibleOnAllWorkspaces(bool always_visible) = 0;
virtual bool CanHaveAlphaEnabled() const = 0;
virtual ~NativeAppWindow() {}
};
}
#endif
| [
"allegrant@mail.ru"
] | allegrant@mail.ru |
d237a73160f251e5860ea8bda3a10f42e5d7a599 | 2cd9911b83bf4a2cfe6ff8df6083f3d26af8a7ae | /Headers/PinMapper/indiv_addr_pin_mapper.h | e48cec864ca151c9821d0b6b660da21e0cadffbe | [] | no_license | abhinandmenon/MFSimStaticAStar | 784361b18f3dd9c245996bdd12443a6f77b5de59 | 775adc5c6620fb9d4dc0a3e947be236e1e4256ac | refs/heads/master | 2021-01-20T08:57:26.439644 | 2015-01-23T23:36:22 | 2015-01-23T23:36:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,357 | h | /*------------------------------------------------------------------------------*
* (c)2014, All Rights Reserved. *
* ___ ___ ___ *
* /__/\ / /\ / /\ *
* \ \:\ / /:/ / /::\ *
* \ \:\ / /:/ / /:/\:\ *
* ___ \ \:\ / /:/ ___ / /:/~/:/ *
* /__/\ \__\:\ /__/:/ / /\ /__/:/ /:/___ UCR DMFB Synthesis Framework *
* \ \:\ / /:/ \ \:\ / /:/ \ \:\/:::::/ www.microfluidics.cs.ucr.edu *
* \ \:\ /:/ \ \:\ /:/ \ \::/~~~~ *
* \ \:\/:/ \ \:\/:/ \ \:\ *
* \ \::/ \ \::/ \ \:\ *
* \__\/ \__\/ \__\/ *
*-----------------------------------------------------------------------------*/
/*------------------------------Algorithm Details-------------------------------*
* Type: Pin Mapper *
* Name: Individually-Addressable Pin Mapper *
* *
* Detailed in the following paper: *
* Authors: Dan Grissom and Philip Brisk *
* Title: Field Programmable, Pin-Constrained Digital Microfluidic Biochips *
* Publication Details: Submitted to DAC 2013 *
* *
* Details: Computes pin mapping for individually-addressable DMFBs. *
*-----------------------------------------------------------------------------*/
#ifndef INDIV_ADDR_PIN_MAPPER_H_
#define INDIV_ADDR_PIN_MAPPER_H_
#include "../Models/dmfb_arch.h"
#include "pin_mapper.h"
class IndivAddrPinMapper : public PinMapper
{
public:
// Constructors
IndivAddrPinMapper();
IndivAddrPinMapper(DmfbArch *dmfbArch);
virtual ~IndivAddrPinMapper();
// Methods
void setCustomMapping();
void setMapPreSched();
void setMapPostRoute(vector<vector<int> *> *pinActivations);
void flattenSpecialPurposePins();
void unflattenSpecialPurposePins();
// Getters/Setters
protected:
// Methods
int computeAvailResources();
int computeAvailResourcesForGrissomFixedPlacer(int horizRouteSpacing);
int computeAvailResourcesForGrissomFixedPlacer2();
// Members
DmfbArch *arch;
};
#endif /* INDIV_ADDR_PIN_MAPPER_H_ */
| [
"mohiuddin.a.qader@gmail.com"
] | mohiuddin.a.qader@gmail.com |
9f5d82c1d32cdb7c27e1c2ce65ce014e5347fe80 | dfa6ddf5fb513d553d43a028add28cdf40b46249 | /897. Increasing Order Search Tree.cpp | 88f415aab35978a4cc1e7088ca7783ba440c3a5f | [] | no_license | brucechin/Leetcode | c58eb6eedf3a940841a0ccae18d543fd88b76f65 | 798e6f1fa128982c7fd141a725b99805131361cb | refs/heads/master | 2021-11-22T14:31:53.143147 | 2021-10-08T06:50:28 | 2021-10-08T06:50:28 | 109,366,643 | 4 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,217 | cpp | /*
Given a binary search tree, rearrange the tree in in-order so that the leftmost node in the tree is now the root of the tree, and every node has no left child and only 1 right child.
Example 1:
Input: [5,3,6,2,4,null,8,1,null,null,null,7,9]
5
/ \
3 6
/ \ \
2 4 8
/ / \
1 7 9
Output: [1,null,2,null,3,null,4,null,5,null,6,null,7,null,8,null,9]
1
\
2
\
3
\
4
\
5
\
6
\
7
\
8
\
9
Note:
The number of nodes in the given tree will be between 1 and 100.
Each node will have a unique integer value from 0 to 1000.
*/
/**
* Definition for a binary tree node.
* struct TreeNode {
* int val;
* TreeNode *left;
* TreeNode *right;
* TreeNode(int x) : val(x), left(NULL), right(NULL) {}
* };
*/
class Solution {
public:
TreeNode* increasingBST(TreeNode* root, TreeNode* tail = NULL) {
if (!root) return tail;
TreeNode* res = increasingBST(root->left, root);
root->left = NULL;
root->right = increasingBST(root->right, tail);
return res;
}
}; | [
"1026193951@sjtu.edu.cn"
] | 1026193951@sjtu.edu.cn |
f13a40d5abe2c8b63a7c44a4920c9e2d401bf374 | 680440f5e59eb2157c1ecb41fd891880ac47c459 | /LUOGU/P2152/superGCD.cpp | a312d535286c3a14a72055ad6e1bf3a337504868 | [] | no_license | Skywt2003/codes | a705dc3a4f5f79d47450179fc597bd92639f3d93 | 0e09198dc84e3f6907a11b117a068f5e0f55ca68 | refs/heads/master | 2020-03-29T09:29:54.014364 | 2019-11-15T12:39:47 | 2019-11-15T12:39:47 | 149,760,952 | 6 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,945 | cpp | #include<bits/stdc++.h>
const int maxlen=10010,tt=10000;
using namespace std;
class bigint{
private:
int len,a[maxlen/4];
public:
// Constructed functions
bigint(){len=0;memset(a,0,sizeof(a));}
bigint(int x){
len=0; memset(a,0,sizeof(a));
while (x) a[++len]=x%tt,x/=tt;
for (int i=1;i<len/2;i++) swap(a[i],a[len-i+1]);
}
// Special IO functions
void set_value(int x){
len=0; memset(a,0,sizeof(a));
while (x) a[++len]=x%tt,x/=tt;
for (int i=1;i<len/2;i++) swap(a[i],a[len-i+1]);
}
void write(){
printf("%d",a[len]);
for (int i=len-1;i>=1;i--) printf("%04d",a[i]);
}
void writeln(){
write();printf("\n");
}
// Comparison operations
bool operator ==(bigint &b){
if (len!=b.len) return false;
for (int i=1;i<=len;i++) if (a[i]!=b.a[i]) return false;
return true;
}
bool operator !=(bigint &b){
return !((*this)==b);
}
bool operator ==(int b){
bigint bb(b);
return (*this)==bb;
}
bool operator !=(int b){
return !((*this)==b);
}
bool operator <(bigint &b){
if ((*this).len < b.len) return true; else if ((*this).len > b.len ) return false;
for (int i=len;i>=1;i--) if ((*this).a[i] < b.a[i]) return true; else if ((*this).a[i] > b.a[i]) return false;
return false;
}
bool operator >(bigint &b){
return !((*this)<b || (*this)==b);
}
bool operator <=(bigint &b){
return ((*this)<b || (*this)==b);
}
bool operator >=(bigint &b){
return ((*this)>b || (*this)==b);
}
// Compute operator
bigint operator +(bigint &b){
bigint c(0); c.len=max(len,b.len);
for (int i=1;i<=c.len;i++){
c.a[i]+=a[i]+b.a[i];
c.a[i+1]+=c.a[i]/tt;
c.a[i]%=tt;
}
while (c.a[c.len+1]) c.len++;
while (c.len>0 && c.a[c.len]==0) c.len--;
return c;
}
bigint operator -(bigint &b){
// printf("Start to sub: ");write();printf(" - ");b.writeln();
bigint c(0); c.len=len;
for (int i=1;i<=c.len;i++){
c.a[i]+=a[i]-b.a[i]+tt;
c.a[i+1]+=c.a[i]/tt-1;
c.a[i]%=tt;
}
while (c.a[c.len+1]) c.len++;
while (c.len>0 && c.a[c.len]==0) c.len--;
// printf(" = ");c.writeln();
return c;
}
bigint operator *(int b){
bigint c; c.len=len;
for (int i=1;i<=c.len;i++){
c.a[i]+=a[i]*b;
c.a[i+1]+=c.a[i]/tt;
c.a[i]%=tt;
}
while (c.a[c.len+1]) c.len++;
while (c.len>0 && c.a[c.len]==0) c.len--;
return c;
}
};
bigint read(){
bigint ret; char ch=getchar();
while (ch<'0'||ch>'9') ch=getchar();
while (ch>='0'&&ch<='9'){
bigint now; now=(ch-'0');
ret=ret*10; ret=ret+now;
ch=getchar();
}
return ret;
}
void swap(bigint &a,bigint &b){
bigint tmp;
tmp=a,a=b,b=tmp;
}
int gcd(int x,int y){
return y?x:gcd(y,x%y);
}
signed main(){
bigint a=read(),b=read();
if (a<b) swap(a,b);
// a.writeln(); b.writeln();
for (;;){
if (b==0){a.writeln();return 0;}
a=a-b;
if (a<b) swap(a,b);
// a.write(); printf(" "); b.writeln();
}
return 0;
} | [
"Skywt2003@gmail.com"
] | Skywt2003@gmail.com |
db4571a4825f7a4b930bfc5d11b0f411a0f1b354 | e485adc2656990bbd66e11c4d4a03508ae52d152 | /CosmicCapture/graphics/TextureAPI.h | 4e2901f56604abc9b09af47965a509598d29d8f8 | [] | no_license | ebiederstadt/CosmicCapture | 34e5d76ba9696ed293e349eade7b78df510e9f3a | fc71aaf0e8cf95f0e1224dfce5708367f1d0adfc | refs/heads/master | 2023-04-18T23:55:00.274887 | 2021-05-08T22:45:05 | 2021-05-08T22:45:05 | 363,298,269 | 2 | 0 | null | 2021-05-08T21:34:24 | 2021-05-01T01:29:10 | null | UTF-8 | C++ | false | false | 617 | h | #pragma once
#include <map>
#include <string>
#include "Texture.h"
class TextureAPI
{
public:
// No copying is allowed
TextureAPI(TextureAPI&) = delete;
// No copy assignment
void operator=(const TextureAPI&) = delete;
// Singleton method
static TextureAPI* instance();
~TextureAPI() { delete api; }
using TextureName = std::string;
void create(const TextureName&, unsigned int interpolation = GL_LINEAR, bool flip = false);
void bind(const TextureName& name) { mTextures.at(name).bind(); }
private:
TextureAPI() = default;
std::map<TextureName, Texture> mTextures;
static TextureAPI* api;
};
| [
"biederstadterik@gmail.com"
] | biederstadterik@gmail.com |
9e2312f0efe9955860763b713cd8092fbbdd06ab | 7db3921786ff6e8ac33b7b27d8c967776906b4fd | /Module05/ex02/RobotomyRequestForm.hpp | 9a95beb746daf2816da9439d7b649941a7bf4d6e | [] | no_license | ymanzi/Cpp-Bootcamp | 3fbe7ce613bf35701da19d5c416319ccf31700f1 | 98c451bf4da0b4bf3b2e675fe710274acbcd1b2d | refs/heads/main | 2023-03-28T04:33:29.186867 | 2021-03-19T10:15:14 | 2021-03-19T10:15:14 | 313,275,669 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* RobotomyRequestForm.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: ymanzi <marvin@42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/12/19 12:13:36 by ymanzi #+# #+# */
/* Updated: 2020/12/19 12:13:37 by ymanzi ### ########.fr */
/* */
/* ************************************************************************** */
# ifndef ROBOTOMYREQUESTFORM_HPP
# define ROBOTOMYREQUESTFORM_HPP
#include <fstream>
#include "Form.hpp"
#include "Bureaucrat.hpp"
class RobotomyRequestForm : public Form
{
public:
RobotomyRequestForm(std::string target = "Default Target");
RobotomyRequestForm(RobotomyRequestForm const& other);
virtual ~RobotomyRequestForm(void);
RobotomyRequestForm& operator=(RobotomyRequestForm const& other);
virtual void execute(Bureaucrat const & executor) const;
};
# endif
| [
"ymanzi@shi-r9-p7.s19.be"
] | ymanzi@shi-r9-p7.s19.be |
b173c7db95d3b1cc4e4b7f2180a818c5d52a58eb | 6f2b6e9d77fc4dd5e1dae8ba6e5a66eb7c7ae849 | /sstd_boost/sstd/boost/atomic/detail/caps_gcc_sync.hpp | ae767813fba85ad5549f6afcb4e02136a43b12c0 | [
"BSL-1.0"
] | permissive | KqSMea8/sstd_library | 9e4e622e1b01bed5de7322c2682539400d13dd58 | 0fcb815f50d538517e70a788914da7fbbe786ce1 | refs/heads/master | 2020-05-03T21:07:01.650034 | 2019-04-01T00:10:47 | 2019-04-01T00:10:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,011 | hpp | /*
* Distributed under the Boost Software License, Version 1.0.
* (See accompanying file LICENSE_1_0.txt or copy at
* http://www.boost.org/LICENSE_1_0.txt)
*
* Copyright (c) 2011 Helge Bahmann
* Copyright (c) 2013 Tim Blechmann
* Copyright (c) 2014 Andrey Semashev
*/
/*!
* \file atomic/detail/caps_gcc_sync.hpp
*
* This header defines feature capabilities macros
*/
#ifndef BOOST_ATOMIC_DETAIL_CAPS_GCC_SYNC_HPP_INCLUDED_
#define BOOST_ATOMIC_DETAIL_CAPS_GCC_SYNC_HPP_INCLUDED_
#include <sstd/boost/atomic/detail/config.hpp>
#if defined(__i386__) || defined(__x86_64__)
#include <sstd/boost/atomic/detail/hwcaps_gcc_x86.hpp>
#elif defined(__arm__)
#include <sstd/boost/atomic/detail/hwcaps_gcc_arm.hpp>
#elif defined(__POWERPC__) || defined(__PPC__)
#include <sstd/boost/atomic/detail/hwcaps_gcc_ppc.hpp>
#endif
#ifdef BOOST_HAS_PRAGMA_ONCE
#pragma once
#endif
#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_1)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
#define BOOST_ATOMIC_INT8_LOCK_FREE 2
#endif
#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_2)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
#define BOOST_ATOMIC_INT16_LOCK_FREE 2
#endif
#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_4)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
#define BOOST_ATOMIC_INT32_LOCK_FREE 2
#endif
#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_8)\
|| defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
#define BOOST_ATOMIC_INT64_LOCK_FREE 2
#endif
#if defined(__GCC_HAVE_SYNC_COMPARE_AND_SWAP_16)
#define BOOST_ATOMIC_INT128_LOCK_FREE 2
#endif
#define BOOST_ATOMIC_THREAD_FENCE 2
#define BOOST_ATOMIC_SIGNAL_FENCE 2
#endif // BOOST_ATOMIC_DETAIL_CAPS_GCC_SYNC_HPP_INCLUDED_
| [
"zhaixueqiang@hotmail.com"
] | zhaixueqiang@hotmail.com |
6dd2031365fff0958a009b7a78416efb215b26ec | 517695d12f354125adc4347141d3a0df7e399db3 | /HotelManagementSystem/Source.cpp | 7aa8938c754bd5b8f2a00afd355170560e92ecac | [] | no_license | usman-088/HotelManagementSystem | d400d4aabac8b3f311bcf00873f45d5c73820319 | a9d7ce7b570eda56ee46732d947e9f25a0562147 | refs/heads/master | 2023-06-05T03:56:25.312708 | 2021-06-22T19:11:54 | 2021-06-22T19:11:54 | 379,375,921 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 19,275 | cpp | #include<iostream>
#include<cstdlib>
#include<string>
#include<iomanip>
#include<array>
using namespace std;
void meanucard()
{
cout << "\n";
cout << "\n";
cout << '\t' << "*************************************************************** ";
cout << "\n\t\tMENUE CARD";
cout << "\n\t*************************************************************** ";
cout << "\n"; cout << "\n";
cout << "\t\t" << "I- CHINESE CUISINE \n";
cout << "\t\t" << "__________________ \n";
cout << "\t\t" << "1- Fried Rice \n";
cout << "\t\t" << "2- Chicken Shashlik \n";
cout << "\t\t" << "3- Thai Soup \n";
cout << "\t\t" << "4- Noodles \n";
cout << "\t\t" << "5- Snacks \n";
cout << "\n"; "\t***************************************************************\n\n";
cout << "\n";
cout << "\n";
cout << '\t' << " *************************************************************** ";
cout << "\n"; cout << "\n";
cout << "\t\t" << "II- BAR B-Q \n";
cout << "\t\t" << "__________ \n";
cout << "\n";
cout << "\t\t" << "6- Chicken Tikka \n";
cout << "\t\t" << "7- Kata Kut \n";
cout << "\t\t" << "8- Rashmi Kabab \n";
cout << "\n";
cout << "\t***************************************************************\n\n";
cout << "\n";
cout << "\n";
cout << '\t' << " *************************************************************** ";
cout << "\n"; cout << "\n";
cout << "\t\t" << "III- PAKISTANIS CUISINE \n";
cout << "\t\t" << "_______________________ \n";
cout << "\t\t" << "9- Chicken Kerhai \n";
cout << "\t\t" << "10- Biryani \n";
cout << "\t\t" << "11- Qourma \n";
cout << "\t\t" << "12- Nan \n";
cout << "\t\t" << "13- Taftan \n";
cout << "\n";
"\t***************************************************************\n\n";
cout << "\n";
cout << "\n";
cout << '\t' << " *************************************************************** ";
cout << "\n"; cout << "\n";
cout << "\t\t" << "IV- BEVERAGES \n";
cout << "\t\t" << "_____________ \n";
cout << "\n";
cout << "\t\t" << "14- Coke \n";
cout << "\t\t" << "15- 7-Up \n";
cout << "\t\t" << "16- Coffee \n";
cout << "\t\t" << "17- Tea \n";
cout << "\n";
"\t***************************************************************\n\n";
}
class order {
public:
int room;
int friedrice = 0;
int chickenshashlik = 0;
int thaisoup = 0;
int noodles = 0;
int snacks = 0;
int chickentikka = 0;
int katakut = 0;
int rashmikabab = 0;
int chickenkerhai = 0;
int biryani = 0;
int quorma = 0;
int nan = 0;
int taftan = 0;
int coke = 0;
int sevenup = 0;
int coffee = 0;
int tea = 0;
void display_order() {
cout << '\t' << "Room " << room << " ORDERED FOLLOWING FOODS : \n";
cout << "\n"; cout << "\n";
cout << '\t' << " *************************************************************** ";
cout << "\n"; cout << "\n";
cout << '\t' << "01- Fried Rice :" " " << friedrice << "\n"; cout << "\n";
cout << '\t' << "02- Chicken Shashlik :" " " << chickenshashlik << "\n"; cout << "\n";
cout << '\t' << "03- Thai Soup :" " " << thaisoup << "\n"; cout << "\n";
cout << '\t' << "04- Noodles :" " " << noodles << "\n"; cout << "\n";
cout << '\t' << "05- Snacks :" " " << snacks << "\n"; cout << "\n";
cout << '\t' << "06- Chicken Tikka :" " " << chickentikka << "\n"; cout << "\n";
cout << '\t' << "07- Kata Kut :" " " << katakut << "\n"; cout << "\n";
cout << '\t' << "08- Rashmi Kabab :" " " << rashmikabab << "\n"; cout << "\n";
cout << '\t' << "09- Chicken Kerhai :" << chickenkerhai << "\n"; cout << "\n";
cout << '\t' << "10- Biryani :" " " << biryani << "\n"; cout << "\n";
cout << '\t' << "11- Qourma :" " " << quorma << "\n"; cout << "\n";
cout << '\t' << "12- Nan :" " " << nan << "\n"; cout << "\n";
cout << '\t' << "13- Taftan :" " " << taftan << "\n"; cout << "\n";
cout << '\t' << "14- Coke : " " " << coke << "\n"; cout << "\n";
cout << '\t' << "15- 7-Up : " " " << sevenup << "\n"; cout << "\n";
cout << '\t' << "16- Coffee :" " " << coffee << "\n"; cout << "\n";
cout << '\t' << "17- Tea : " " " << tea << "\n"; cout << "\n";
cout << '\t' << " *************************************************************** ";
cout << "\n"; cout << "\n";
}
};
class Rooms
{
public:
int room_number;
char name[30];
char cnic[50];
char phone[15];
int bill;
bool occupied = false;
public:
void add_customer()
{
cin.ignore();
fflush(stdout);
cout << "\nEnter The Customer's name: ";
cin.getline(name, 30);
cout << "\nEnter The Customer's CNIC: ";
cin.getline(cnic, 50);
cout << "\nEnter The Customer's phone #: ";
cin.getline(phone, 10);
cout << "\t\t\n\nCustomer added Successfully...";
occupied = true;
}
void show_customer()
{
cout << "\nRoom Number: " << room_number;
cout << "\nCustomer's Name: " << name;
cout << "\nCustomer's Phone: " << phone;
cout << "\nCustomer's CNIC: " << cnic;
}
void modify_customer_record()
{
cin.ignore();
fflush(stdout);
cout << "\nModify Customer's Name : ";
cin.getline(cnic, 50);
cout << "\nModify Customer's phone #: ";
cin.getline(phone, 10);
cin.getline(name, 30);
cout << "\nModify Customer's CNIC: ";
}
void Checkout_customer_Room()
{
this->occupied = false;
memset(name, 0, 30 * (sizeof name[0]));
memset(cnic, 0, 50 * (sizeof name[0]));
memset(phone, 0, 10 * (sizeof name[0]));
bill = 0;
}
int getRoomNumber()
{
return room_number;
}
char* getName()
{
return name;
}
char* getAddress()
{
return cnic;
}
char* getPhone()
{
return phone;
}
void report()
{
cout << room_number << setw(10) << name << setw(20) << cnic << setw(20) << phone << endl;
}
};
class Hotel {
public:
Rooms room[10]; // Array Data Structure is used as the rooms re Fixed !
order queue[100];
int n = 100, front = -1, rear = -1; //Queue data structure is used to entertain orders
int count = 0;
public:
void book_room() { //Assumption : rooms are booked only for 24 hours
bool check = false;
for (int i = 0; i < 10; i++)
{
if (room[i].occupied == false)
{
cout << "\n\nRoom Number : " << i;
room[i].room_number = i;
room[i].add_customer();
check = true;
break;
}
}
if (check == false)
{
cout << "==================================================================\n";
cout << "Sorry All Rooms Are Booked ..." << "\n==================================================================\n";
}
}
void display_list() {
cout << "\n\n\t\tCUSTOMER LIST\n\n";
cout << "==================================================================\n";
for (int i = 0; i < 10; i++)
{
if (room[i].occupied == true) {
room[i].show_customer();
cout << "\n\n==================================================================\n";
}
}
}
void show_customer()
{
int Rno = 1000;
while (Rno < 0 || Rno>9) {
cout << "\n Enter Room Number to show customer Details (0-9) :";
cin >> Rno;
if (Rno < 0 || Rno>9)
{
cout << "\n\tNo Such Room Exixts !!!\n\n ";
}
else {
if (room[Rno].occupied == true) room[Rno].show_customer();
else cout << "\nThe Room is Not booked Customer Not Found !!!\n";
}
}
}
void modify_customer()
{
int Rno = 1000;
cout << "==================================================================\n";
cout << "---------------Modify Customer Information------------------------" << endl;
cout << "==================================================================\n";
while (Rno < 0 || Rno>9) {
cout << "\n\n\tEnter Room Number (0-9) of Customer :";
cin >> Rno;
if (Rno < 0 || Rno>9)
{
cout << "\n\tNo Such Room Exixts !!! ";
}
else {
if (room[Rno].occupied == true)
{
cout << "Previous Data ==> \n\n" << endl;
room[Rno].show_customer();
room[Rno].modify_customer_record();
cout << "\nCustomer Information Of Room " << Rno << " Is Modified Successfully !!!";
}
else cout << "\nThe Room is Not booked Customer Not Found !!!";
}
}
}
void Checkout_customer()
{
int Rno = 1000;
cout << "==================================================================\n";
cout << "-----------------------Check Out Customer-------------------------" << endl;
cout << "==================================================================\n";
cout << " ";
while (Rno < 0 || Rno>9) {
cout << "\n\n\tEnter Room Number (0-9) of Customer :";
cin >> Rno;
if (Rno < 0 || Rno>9)
{
cout << "\n\tNo Such Room Exixts !!! ";
}
else {
if (room[Rno].occupied == true)
{
cout << "\nCustomer Record ==> " << endl;
room[Rno].show_customer();
cout << "\n==================================================================\n";
cout << "\n==================================================================\n";
cout << "---------------Check Out Successfully-----------------------------" << endl;
cout << "==================================================================\n";
cout << "\tRoom Rent : " << 5000 << endl;
cout << "\tOrder Bills : " << room[Rno].bill << endl;
cout << "\tCustomer Total Bill : " << room[Rno].bill + 5000;
room[Rno].Checkout_customer_Room();
}
else cout << "\nThe Room is Not booked Customer Not Found !!!\n";
}
}
}
void Insert_order() {
int Rno = 1000;
while (Rno < 0 || Rno>9) {
cout << "\n Enter Room Number to show customer Details (0-9) :";
cin >> Rno;
if (Rno < 0 || Rno>9)
{
cout << "\n\tNo Such Room Exixts !!!\n\n ";
}
else {
if (room[Rno].occupied == true)
{
int val;
if (rear == n - 1)
cout << "Order Completed" << endl;
else {
if (front == -1)
front = 0;
cout << "Insert the element in queue : " << endl;
int submenu;
submenu = (1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18);
int bill = 0;
string order = "";
int friedrice = 0;
int chickenshashlik = 0;
int thaisoup = 0;
int noodles = 0;
int snacks = 0;
int chickentikka = 0;
int katakut = 0;
int rashmikabab = 0;
int chickenkerhai = 0;
int biryani = 0;
int quorma = 0;
int nan = 0;
int taftan = 0;
int coke = 0;
int sevenup = 0;
int coffee = 0;
int tea = 0;
meanucard();
while (1)
{
// INSTRUCTION FOR SUB-MENU CARD, RETURN BACK TO MAIN MENU OR INSTRUCTION TO EXIT / PRINT ORDER
cout << "\t\t" << "PRESS ( 18 ) TO EXIT AND PRINT YOUR ORDER \n";
cout << "\n";
cout << "\t\t" << "PLEASE PLACE YOUR ORDER HERE : ";
cin >> submenu;
cout << "\n"; cout << "\n";
if (submenu == 1)
{
friedrice++;
bill = bill + 150;
order = order + " friedrice (1) ";
}
else if (submenu == 2)
{
chickenshashlik++;
bill = bill + 200;
order = order + " chickenshashlik (1) ";
}
else if (submenu == 3)
{
thaisoup++;
bill = bill + 270;
order = order + " + thaisoup (1) ";
}
if (submenu == 4)
{
noodles++;
bill = bill + 300;
order = order + " + noodles (1) ";
}
else if (submenu == 5)
{
snacks++;
bill = bill + 120;
order = order + " + snaks (1) ";
}
else if (submenu == 6)
{
chickentikka++;
bill = bill + 270;
order = order + " + chickentikka (1) ";
}
else if (submenu == 7)
{
katakut++;
bill = bill + 300;
order = order + " + katakut (1) ";
}
else if (submenu == 8)
{
rashmikabab++;
bill = bill + 250;
order = order + " + sahmikabab (1) ";
}
else if (submenu == 9)
{
chickenkerhai++;
bill = bill + 1200;
order = order + " + chickenkerhai (1) ";
}
else if (submenu == 10)
{
biryani++;
bill = bill + 350;
order = order + " + biryani (1) ";
}
else if (submenu == 11)
{
quorma++;
bill = bill + 150;
order = order + " + qourma (1) ";
}
else if (submenu == 12)
{
nan++;
bill = bill + 20;
order = order + " + nan (1) ";
}
else if (submenu == 13)
{
taftan++;
bill = bill + 50;
order = order + " + taftan (1) ";
}
else if (submenu == 14)
{
coke++;
bill = bill + 100;
order = order + " + coke (1) ";
}
else if (submenu == 15)
{
sevenup++;
bill = bill + 100;
order = order + " + sevenup (1) ";
}
else if (submenu == 16)
{
coffee++;
bill = bill + 100;
order = order + " + coffee (1) ";
}
else if (submenu == 17)
{
tea++;
bill = bill + 100;
order = order + " + tea (1) ";
}
// REVALIDATE THE PROGRAM IF USER INPUT WRONG VALUE GREATER THAN 17
else if (submenu > 18)
{
cout << "\n";
cout << "\t\t" << "YOU ENTERED WRONG VALUE ... PLEASE TRY AGAIN : ";
cin >> submenu;
cout << "\n"; cout << "\n";
}
// IF INPUT = 18, EXIT AND PRINT ORDER
else if (submenu == 18)
{
cout << "\n";
cout << "\n";
cout << "\t*************************************************************** ";
cout << "\n"; cout << "\n"; cout << "\n";
cout << '\t' << "Room " << Rno << " ORDERED FOLLOWING FOODS : \n";
cout << "\n"; cout << "\n";
cout << "\t*************************************************************** ";
cout << "\n"; cout << "\n";
cout << '\t' << "01- Fried Rice :" " " << friedrice << "\n"; cout << "\n";
cout << '\t' << "02- Chicken Shashlik :" " " << chickenshashlik << "\n"; cout << "\n";
cout << '\t' << "03- Thai Soup :" " " << thaisoup << "\n"; cout << "\n";
cout << '\t' << "04- Noodles :" " " << noodles << "\n"; cout << "\n";
cout << '\t' << "05- Snacks :" " " << snacks << "\n"; cout << "\n";
cout << '\t' << "06- Chicken Tikka :" " " << chickentikka << "\n"; cout << "\n";
cout << '\t' << "07- Kata Kut :" " " << katakut << "\n"; cout << "\n";
cout << '\t' << "08- Rashmi Kabab :" " " << rashmikabab << "\n"; cout << "\n";
cout << '\t' << "09- Chicken Kerhai :" << chickenkerhai << "\n"; cout << "\n";
cout << '\t' << "10- Biryani :" " " << biryani << "\n"; cout << "\n";
cout << '\t' << "11- Qourma :" " " << quorma << "\n"; cout << "\n";
cout << '\t' << "12- Nan :" " " << nan << "\n"; cout << "\n";
cout << '\t' << "13- Taftan :" " " << taftan << "\n"; cout << "\n";
cout << '\t' << "14- Coke : " " " << coke << "\n"; cout << "\n";
cout << '\t' << "15- 7-Up : " " " << sevenup << "\n"; cout << "\n";
cout << '\t' << "16- Coffee :" " " << coffee << "\n"; cout << "\n";
cout << '\t' << "17- Tea : " " " << tea << "\n"; cout << "\n";
cout << '\t' << " *************************************************************** ";
cout << "\n"; cout << "\n";
// THANKS MESSAGE
cout << '\t' << "THANK YOU FOR YOUR ORDER - WE WILL DELIVER IT TO YOU SOON \n";
cout << "\tYour Payable Bill : " << bill;
cout << "\n"; cout << "\n";
break;
}
}
rear++;
queue[rear].biryani = biryani;
queue[rear].chickenkerhai = chickenkerhai;
queue[rear].chickenshashlik = chickenshashlik;
queue[rear].chickentikka = chickentikka;
queue[rear].coffee = coffee;
queue[rear].coke = coke;
queue[rear].friedrice = friedrice;
queue[rear].katakut = katakut;
queue[rear].nan = nan;
queue[rear].noodles = noodles;
queue[rear].quorma = quorma;
queue[rear].rashmikabab = rashmikabab;
queue[rear].sevenup = sevenup;
queue[rear].snacks = snacks;
queue[rear].taftan = taftan;
queue[rear].tea = tea;
queue[rear].thaisoup = thaisoup;
queue[rear].thaisoup = thaisoup;
queue[rear].room = Rno;
room[Rno].bill = bill;
}
}
else cout << "\nThe Room is Not booked Customer Not Found !!!\n";
}
}
}
void Delete() {
if (front == -1 || front > rear) {
cout << "Queue Underflow ";
return;
}
else {
cout << '\t' << " *************************************************************** ";
cout << "\t\t\t FOLLOW ORDER HAS HIGHEST PREORITY! ";
cout << '\t' << " *************************************************************** ";
queue[front].display_order();
front++;;
}
}
void Display_All() {
if (front == -1)
cout << "No Order in the Queue" << endl;
else {
cout << '\t' << " *************************************************************** ";
cout << "\t\t\tFOLLOWING ORDERS ARE IN THE QUEUE! ";
cout << '\t' << " *************************************************************** ";
for (int i = front; i <= rear; i++) {
queue[i].display_order();
cout << "\n";
}
cout << endl;
}
}
};
void main_menu()
{
Hotel obj;
int option;
for (;;)
{
cout << "\n\n\t\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@";
cout << "\n\t\tPress 1 to BOOK A ROOM";
cout << "\n\t\tPress 2 to DISPLAY ALL ROOMS ALLOTTED";
cout << "\n\t\tPress 3 to DISPLAY SPECIFIC CUSTOMER RECORD";
cout << "\n\t\tPress 4 to MODIFY CUSTOMER RECORD";
cout << "\n\t\tPress 5 to CHECKOUT CUSTOMER RECORD";
cout << "\n\t\tPress 6 to SEE ORDER MENUE";
cout << "\n\t\tPress 7 to ADD ORDER IN QUEUE";
cout << "\n\t\tPress 8 to FETCH ORDER";
cout << "\n\t\tPress 9 to SEE ALL ORDERS IN QUEUE";
cout << "\n\t\tPress 10 to Exit";
cout << "\n\t\t@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@@\n";
cout << "\n\t\tOption: ";
cin >> option;
switch (option)
{
case 1:
obj.book_room();
break;
case 2:
obj.display_list();
break;
case 3:
obj.show_customer();
break;
case 4:
obj.modify_customer();
break;
case 5:
obj.Checkout_customer();
break;
case 6:
meanucard();
break;
case 7:
obj.Insert_order();
break;
case 8:
obj.Delete();
break;
case 9:
obj.Display_All();
break;
case 10: exit(0);
break;
default:cout << "\a";
}
}
}
bool login()
{
char id[30] = "usman", pass[30] = "123";
char cid[30], cpass[30];
cout << "\t\t\t==================================================================\n";
cout << "\t\t\t------------------WELCOME TO MY HOTAL MANAGEMENT SYSTEM-----------" << endl;
cout << "\t\t\t==================================================================\n";
cout << "\n\nPLEASE LOGIN" << endl;
cout << "Enter your id :";
cin.getline(cid, 30);
cout << "Enter your pass :";
cin.getline(cpass, 30);
//id == cid || pass == cpass
if (strcmp(id, cid) == 0 && strcmp(pass, cpass) == 0) {
cout << "\n\t\t Login Successfull\n" << endl;
return true;
}
else
{
cout << "\n\tLogin Fail\n" << endl;
return false;
}
}
int main()
{
bool check = false;
while (check != true)
{
check = login();
}
main_menu();
system("pause");
return 0;
} | [
"usmanali14815@gmail.com"
] | usmanali14815@gmail.com |
af43d09775117d152d581d71d9a3f5502f286564 | 6cc33974557a36b6c5d8d0ec64c7284703b12037 | /Algorithm_proj/Algorithm/karatsuba.cpp | 6203688ae6cf6371d99b0897e10fa89b8af51fb8 | [] | no_license | Butter-89/BasicAlgorithm | ece905b3fe6b96636f309f80d0ebb6852ef82de6 | 0dde0fcfa2923f0c7771d941a50e7751cf91d5d3 | refs/heads/master | 2022-11-01T23:09:04.229907 | 2020-06-13T09:49:38 | 2020-06-13T09:49:38 | 271,978,796 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,607 | cpp | #include "problems.h"
#include <fstream>
#include <cmath>
void PrintVector(std::vector<int>& i_vector)
{
for (int i = 0; i < i_vector.size(); i++)
{
std::cout << i_vector[i];
}
std::cout << "\n";
}
std::vector<int> ToVector(int i_integer)
{
std::vector<int> temp_result;
std::vector<int> result;
int quotient = i_integer;
while (quotient != 0)
{
temp_result.push_back(quotient % 10);
quotient /= 10;
}
for (int i = 0; i < temp_result.size(); i++)
{
result.push_back(temp_result[temp_result.size() - 1 - i]);
//std::cout << temp_result[temp_result.size() - 1 - i];
}
if (result.size() == 0)
{
result.push_back(0);
//std::cout << result[0];
}
return result;
}
int ToInteger(std::vector<int>& i_vector)
{
int value = 0;
for (int i = 0; i < i_vector.size(); i++)
{
value += i_vector[i] * powf(10, i_vector.size() - 1 - i);
}
return value;
}
std::vector<int> SmallMultiply(std::vector<int>& i_lhs, std::vector<int>& i_rhs)
{
std::vector<int> result;
int lhs = ToInteger(i_lhs);
int rhs = ToInteger(i_rhs);
result = ToVector(lhs * rhs);
return result;
}
// Vector-represented integer sum function - done. Still needs improvement
std::vector<int> ArraySum(std::vector<int>& i_lhs, std::vector<int>& i_rhs)
{
int count = i_lhs.size() < i_rhs.size() ? i_lhs.size() : i_rhs.size(); // set the smaller one as the times of calculation loop
int carry = 0;
std::vector<int> temp_result;
std::vector<int> result; // the result to be returned should be inversed from the temp_result which uses push_back
if (i_lhs.size() <= i_rhs.size())
{
for (int i = 0; i < i_rhs.size(); i++)
{
int summed = 0;
if (i <= i_lhs.size() - 1)
summed = i_rhs[i_rhs.size() - i - 1] + i_lhs[i_lhs.size() - i - 1] + carry;
else
summed = i_rhs[i_rhs.size() - i - 1] + carry;
carry = 0;
if (summed > 9)
{
carry = summed / 10;
summed -= 10 * carry;
}
temp_result.push_back(summed);
}
if (carry != 0)
temp_result.push_back(carry);
}
else
{
for (int i = 0; i < i_lhs.size(); i++)
{
int summed = 0;
if (i <= i_rhs.size() - 1)
summed = i_lhs[i_lhs.size() - i - 1] + i_rhs[i_rhs.size() - i - 1] + carry;
else
summed = i_lhs[i_lhs.size() - i - 1] + carry;
carry = 0;
if (summed > 9)
{
carry = summed / 10;
summed -= 10 * carry;
}
temp_result.push_back(summed);
}
if (carry != 0)
temp_result.push_back(carry);
}
for (int i = temp_result.size() - 1; i >= 0; i--)
{
result.push_back(temp_result[i]);
//std::cout << temp_result[i];
}
//PrintVector(result);
return result;
}
std::vector<int> operator+(std::vector<int>& i_lhs, std::vector<int>& i_rhs)
{
return ArraySum(i_lhs, i_rhs);
}
// A tweaked subtraction function just for this case, since the minuend should always be greater than the subtracted
std::vector<int> ArraySubtract(std::vector<int> i_minuend, std::vector<int> i_subtracted)
{
int count = i_subtracted.size(); // set the size of subtracted as the times of calculation
int carry = 0;
std::vector<int> temp_result;
std::vector<int> result; // the result to be returned should be inversed from the temp_result which uses push_back
for (int i = 0; i < i_minuend.size(); i++)
{
int subtracted = 0;
if (i <= i_subtracted.size() - 1)
subtracted = i_minuend[i_minuend.size() - i - 1] - i_subtracted[i_subtracted.size() - i - 1] + carry;
else
subtracted = i_minuend[i_minuend.size() - i - 1] + carry;
carry = 0;
if (subtracted < 0)
{
carry = -1;
subtracted += 10;
}
temp_result.push_back(subtracted);
}
bool first_zeros = true;
for (int i = temp_result.size() - 1; i >= 0; i--)
{
if (temp_result[i] != 0)
first_zeros = false;
if (!first_zeros)
{
result.push_back(temp_result[i]);
//std::cout << temp_result[i];
}
}
if (result.size() == 0)
{
result.push_back(0);
//std::cout << result[0];
}
//PrintVector(result);
return result;
}
std::vector<int> operator-(std::vector<int>& i_minuend, std::vector<int>& i_subtracted)
{
return ArraySubtract(i_minuend, i_subtracted);
}
// Tweaked multiplication for this, since it only needs to pad zeros
void ArrayMultiplication(std::vector<int>& i_base, int i_size)
{
for (int i = 0; i < i_size; i++)
{
i_base.push_back(0);
}
//PrintVector(i_base);
}
void ReadInput(std::vector<int>& i_lhs, std::vector<int>& i_rhs)
{
// Read the input from a .txt file
std::fstream ifs;
ifs.open("Input.txt", std::fstream::in);
char char_lhs[100] = {};
char char_rhs[100] = {};
ifs.getline(char_lhs, 100);
ifs.getline(char_rhs, 100);
// Now convert the char into int numbers
int i = 0; // counter
while (char_lhs[i] != '\0')
{
int value = (int)(char_lhs[i] - '0');
i_lhs.push_back(value);
i++;
}
i = 0;
while (char_rhs[i] != '\0')
{
int value = (int)(char_rhs[i] - '0');
i_rhs.push_back(value);
i++;
}
}
void SubDivide(std::vector<int>& i_vector, std::vector<int>& o_lhs, std::vector<int>& o_rhs, float i_size)
{
if (i_size / 2 < i_vector.size())
{
for (int i = i_vector.size() - i_size / 2; i < i_vector.size(); i++)
{
o_rhs.push_back(i_vector[i]); // divide the first half part into a/c
}
for (int i = 0; i < i_vector.size() - i_size / 2; i++)
{
o_lhs.push_back(i_vector[i]); // divide the second half part into b/d
}
}
else
{
o_lhs.push_back(0);
for (int i = 0; i < i_vector.size(); i++)
{
o_rhs.push_back(i_vector[i]);
}
}
}
std::vector<int> Sum(std::vector<int>& i_lhs, std::vector<int>& i_rhs)
{
long int value_lhs = 0;
long int value_rhs = 0;
long int sum = 0;
for (int i = 0; i < i_lhs.size(); i++)
{
value_lhs += i_lhs[i] * powf(10, i_lhs.size() - 1 - i);
}
for (int i = 0; i < i_rhs.size(); i++)
{
value_rhs += i_rhs[i] * powf(10, i_rhs.size() - 1 - i);
}
sum = value_lhs + value_rhs;
//std::cout << "Sum is: " << sum << "\n";
std::vector<int> sum_vector;
sum_vector.push_back(sum);
return sum_vector;
}
// Cases of odd bit numbers like 12345 * 1234 are not considered yet
std::vector<int> KaratsubaMul(std::vector<int>& i_lhs, std::vector<int>& i_rhs)
{
int max_size = i_lhs.size() <= i_rhs.size() ? i_rhs.size() : i_lhs.size();
if (max_size % 2 != 0)
max_size += 1;
std::vector<int> ac;
std::vector<int> bd;
std::vector<int> combination; // (a+b)(c+d)
std::vector<int> ad_bc; // ad + bc
std::vector<int> result;
if (i_lhs.size() >= 2 && i_rhs.size() >= 2)
{
std::vector<int> a;
std::vector<int> b;
std::vector<int> c;
std::vector<int> d;
std::vector<int> sum_ab; // a+b
std::vector<int> sum_cd; // c+d
int padded_size = i_lhs.size() <= i_rhs.size() ? i_rhs.size() : i_lhs.size();
if (padded_size % 2 != 0)
padded_size++;
SubDivide(i_lhs, a, b, padded_size);
SubDivide(i_rhs, c, d, padded_size);
// Compute (a+b)(c+d)
sum_ab = ArraySum(a, b);
sum_cd = ArraySum(c, d);
combination = KaratsubaMul(sum_ab, sum_cd);
// compute a*c and b*d
ac = KaratsubaMul(a, c);
bd = KaratsubaMul(b, d);
ad_bc = combination - ac;
ad_bc = ad_bc - bd;
}
else
{
// The case with only one number multiplied with one number
result = SmallMultiply(i_lhs, i_rhs);
return result; //ToVector(i_lhs[0] * i_rhs[0]);
}
ArrayMultiplication(ac, max_size);
ArrayMultiplication(ad_bc, max_size / 2);
// Stupid operations!
result = (ac + ad_bc);
result = result + bd;
return result;
}
void Karatsuba()
{
std::cout << "This is the karatsuba multiplication sample.\n";
std::vector<int> lhs;
std::vector<int> rhs;
std::vector<int> result;
ReadInput(lhs, rhs);
result = KaratsubaMul(lhs, rhs);
PrintVector(result);
}
| [
"906672365@qq.com"
] | 906672365@qq.com |
cb7434b246692e401a5d20f8b161e281afa676f3 | bfcc84c83e092d5c4222eb7512d78e5caec87a75 | /Algorithms/Sorting/Shell Sorting/main.cpp | 3f52ceadab9e6febb32590e60119ec7c3ce32276 | [] | no_license | minahabibm/Data-Structures-Algorithms | d4cbd61760a65c6f5f250154f73df685d6d89393 | 550117f509f5e3fce6ebad87c51ac436db041314 | refs/heads/main | 2023-05-13T17:30:24.371304 | 2021-05-14T16:00:00 | 2021-06-06T02:23:15 | 323,936,857 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 770 | cpp | #include <iostream>
using namespace std;
void shellSort(int array[], int n) {
// Rearrange elements at each n/2, n/4, n/8, ... intervals
for (int interval = n / 2; interval > 0; interval /= 2) {
for (int i = interval; i < n; i += 1) {
int temp = array[i];
int j;
for (j = i; j >= interval && array[j - interval] > temp; j -= interval) {
array[j] = array[j - interval];
}
array[j] = temp;
}
}
}
void printArray(int array[], int size) {
for (int i = 0; i < size; i++)
cout << array[i] << " ";
cout << endl;
}
// Driver code
int main() {
int data[] = {9, 8, 3, 7, 5, 6, 4, 1};
int size = sizeof(data) / sizeof(data[0]);
shellSort(data, size);
cout << "Sorted array: \n";
printArray(data, size);
} | [
"mhcsc01@gmail.com"
] | mhcsc01@gmail.com |
088cf22045ca87979f8d598b04288f50a94bafd8 | 53a72208e4faa15d64fdf879c6f79e091d7e482e | /PAT_Basic/1029.cpp | 95345c79665d0178395c684b264e583b440e8f6e | [] | no_license | Cruyun/C-exercise | db0cc651127882b8818da0896862a14b52266159 | 52143a9ad80e7f2594a626315f2bb549cef44d1e | refs/heads/master | 2021-01-12T06:13:32.790732 | 2019-04-06T14:40:46 | 2019-04-06T14:40:46 | 92,933,490 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 493 | cpp | #include <iostream>
#include <string>
using namespace std;
int main() {
string real;
string input;
cin >> real >> input;
bool check[256] = {false};
int i;
for (i = 0; i < input.length(); i++) {
input[i] = toupper(input[i]);
check[input[i]] = true;
}
for (i = 0; i < real.length(); i++) {
real[i] = toupper(real[i]);
if (check[real[i]] == false)
cout << real[i];
check[real[i]] = true;
}
return 0;
} | [
"1045671796@qq.com"
] | 1045671796@qq.com |
15422a0012ed146e6987f50f407b3b1b89df7068 | c74da93da172103ccd293c9cbb86fcd4e05f11c1 | /datastructures-and-algorithms/linkedlist/3_deleteMiddleNode.cpp | e4b4155e2b28f7feec9e70864772b80d5faa898a | [] | no_license | sundarlucifer/competitive-programming | feb4ee871be5e37d07ae620207662b46ac79c8f3 | 1d95c0264f7f8fa9d79e3f60b13a2039c70cdd22 | refs/heads/master | 2020-12-23T04:41:00.339728 | 2020-04-09T10:06:45 | 2020-04-09T10:06:45 | 237,038,143 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,125 | cpp | #include <iostream>
using namespace std;
struct Node{
int data;
Node* next;
};
Node* newNode(int val){
Node* node = new Node();
node->data = val;
node->next = NULL;
return node;
}
Node* insert(Node* head, int val){
if(head==NULL) return newNode(val);
Node* tmp = head;
while(tmp->next!=NULL) tmp = tmp->next;
tmp->next = newNode(val);
return head;
}
void printList(Node* head){
Node* tmp = head;
while(tmp!=NULL){
cout << tmp->data << "->";
tmp = tmp->next;
}
cout << "NULL\n";
}
void deleteMiddleNode(Node* node){
if(node->next == NULL){
cout << "Not a middle node" << endl;
return;
}
Node* followNode = node->next;
node->data = followNode->data;
node->next = followNode->next;
free(followNode);
}
int main(){
Node* list = NULL;
list = insert(list, 1);
list = insert(list, 2);
list = insert(list, 3);
list = insert(list, 4);
list = insert(list, 5);
printList(list);
Node* ptr = list->next->next;
deleteMiddleNode(ptr);
printList(list);
return 0;
}
| [
"sundarlucifer@gmail.com"
] | sundarlucifer@gmail.com |
d28fe102c54583c8dab3cf88d9df872bc9dca24f | 466d73b3e4cc53997918d7f4eae422e7f37d48d8 | /c++/sandbox/test_int_double_add_speed.cpp | 199c4800d4fc011756cfe79d05b99227581723d6 | [] | no_license | JohnReid/STEME | 0869659d6b8bbbacd9af7ec9c72680fd5eebb1de | 08472c9440df9cc26a5e02c7a20671960be7539d | refs/heads/master | 2021-01-17T15:07:06.432555 | 2018-12-11T10:45:42 | 2018-12-11T10:45:42 | 13,090,334 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,085 | cpp | /**
* Copyright John Reid 2010
*/
#include <boost/timer.hpp>
#include <boost/foreach.hpp>
#include <iostream>
#include <vector>
template< typename Vec >
void
test_add_speed( Vec & vec, const size_t repetitions ) {
typedef typename Vec::value_type value_t;
// initialise vectors with values.
for( size_t i = 0; vec.size() != i; ++i ) {
vec[ i ] = double( i ) + 1./.3;
}
boost::timer timer;
double sum = 0;
for( size_t rep = 0; repetitions != rep; ++rep ) {
BOOST_FOREACH( value_t v, vec ) {
sum += v;
}
}
const double elapsed = timer.elapsed();
::std::cout << "Adding "<<repetitions*vec.size()<<" took "<<elapsed<<" seconds\n";
}
int
main( int argc, char * argv[] ) {
typedef std::vector< int > int_vec;
typedef std::vector< double > double_vec;
const size_t vec_size = 5000;
const size_t repetitions = 1e6;
int_vec ints( vec_size );
double_vec doubles( vec_size );
::std::cout << "Adding integers...\n";
test_add_speed( ints, repetitions );
::std::cout << "Adding doubles...\n";
test_add_speed( doubles, repetitions );
return 0;
}
| [
"johnbaronreid@netscape.net"
] | johnbaronreid@netscape.net |
254b24114590413ebfcf182f89b36865dd471468 | ad822f849322c5dcad78d609f28259031a96c98e | /SDK/GameMenuEntrySlider_parameters.h | 1de69e893a48f2d3bc568315b05f1d4d436ac3fd | [] | no_license | zH4x-SDK/zAstroneer-SDK | 1cdc9c51b60be619202c0258a0dd66bf96898ac4 | 35047f506eaef251a161792fcd2ddd24fe446050 | refs/heads/main | 2023-07-24T08:20:55.346698 | 2021-08-27T13:33:33 | 2021-08-27T13:33:33 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,143 | h | #pragma once
#include "../SDK.h"
// Name: Astroneer-SDK, Version: 1.0.0
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SetSliderValueAsNormalizedFloat
struct UGameMenuEntrySlider_C_SetSliderValueAsNormalizedFloat_Params
{
float NormalizedSliderVal; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool DidChange; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SetSliderPositionFromMousePosition
struct UGameMenuEntrySlider_C_SetSliderPositionFromMousePosition_Params
{
struct FVector2D MousePos; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
bool SliderValueChanged; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.UpdateSliderBubblePosition
struct UGameMenuEntrySlider_C_UpdateSliderBubblePosition_Params
{
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.GetSliderValue
struct UGameMenuEntrySlider_C_GetSliderValue_Params
{
float SliderValue; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.ConvertValToNormalizedSliderRangeFloat
struct UGameMenuEntrySlider_C_ConvertValToNormalizedSliderRangeFloat_Params
{
float ValueToConvert; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float NormalizedVal; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.GetSliderValueAsNormalizedFloat
struct UGameMenuEntrySlider_C_GetSliderValueAsNormalizedFloat_Params
{
float NormalizedSliderVal; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SetSliderValue
struct UGameMenuEntrySlider_C_SetSliderValue_Params
{
float SliderValue; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
bool DidChange; // (Parm, OutParm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.GetMenuFocusWidgetSize
struct UGameMenuEntrySlider_C_GetMenuFocusWidgetSize_Params
{
struct FVector2D ReturnValue; // (Parm, OutParm, ReturnParm, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.LayoutWidget
struct UGameMenuEntrySlider_C_LayoutWidget_Params
{
bool ReturnValue; // (Parm, OutParm, ZeroConstructor, ReturnParm, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnEditingItemValueIncremeneted
struct UGameMenuEntrySlider_C_OnEditingItemValueIncremeneted_Params
{
class UAstroGameMenuFocusItemWidget* FocusItemWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnEditiingItemValueDecremeneted
struct UGameMenuEntrySlider_C_OnEditiingItemValueDecremeneted_Params
{
class UAstroGameMenuFocusItemWidget* FocusItemWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnDragMoved
struct UGameMenuEntrySlider_C_OnDragMoved_Params
{
struct FVector2D MousePosition; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
struct FVector2D MousePosDelta; // (BlueprintVisible, BlueprintReadOnly, Parm, IsPlainOldData)
class UAstroGameMenuFocusItemWidget* FocusableWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnEditOrDragCommited
struct UGameMenuEntrySlider_C_OnEditOrDragCommited_Params
{
class UAstroGameMenuFocusItemWidget* FocusItemWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnEditOrDragStarted
struct UGameMenuEntrySlider_C_OnEditOrDragStarted_Params
{
struct FVector2D MousePosition; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
class UAstroGameMenuFocusItemWidget* FocusItemWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnEditOrDragCancelled
struct UGameMenuEntrySlider_C_OnEditOrDragCancelled_Params
{
class UAstroGameMenuFocusItemWidget* FocusItemWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.Construct
struct UGameMenuEntrySlider_C_Construct_Params
{
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.UpdateColors
struct UGameMenuEntrySlider_C_UpdateColors_Params
{
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SetupStylingData
struct UGameMenuEntrySlider_C_SetupStylingData_Params
{
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.HandleGameMenuResized
struct UGameMenuEntrySlider_C_HandleGameMenuResized_Params
{
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnDiscreteEditStarted
struct UGameMenuEntrySlider_C_OnDiscreteEditStarted_Params
{
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.OnDragEditStarted
struct UGameMenuEntrySlider_C_OnDragEditStarted_Params
{
struct FVector2D MousePosition; // (ConstParm, BlueprintVisible, BlueprintReadOnly, Parm, OutParm, ReferenceParm, IsPlainOldData)
class UAstroGameMenuFocusItemWidget* FocusItemWidget; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.ExecuteUbergraph_GameMenuEntrySlider
struct UGameMenuEntrySlider_C_ExecuteUbergraph_GameMenuEntrySlider_Params
{
int EntryPoint; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SliderEditValueUpdated__DelegateSignature
struct UGameMenuEntrySlider_C_SliderEditValueUpdated__DelegateSignature_Params
{
class UGameMenuEntrySlider_C* SliderEntry; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SliderEditCanceled__DelegateSignature
struct UGameMenuEntrySlider_C_SliderEditCanceled__DelegateSignature_Params
{
class UGameMenuEntrySlider_C* SliderEntry; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
float OriginalSliderValue; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
// Function GameMenuEntrySlider.GameMenuEntrySlider_C.SliderEditCompletedWithCommit__DelegateSignature
struct UGameMenuEntrySlider_C_SliderEditCompletedWithCommit__DelegateSignature_Params
{
class UGameMenuEntrySlider_C* SliderEntry; // (BlueprintVisible, BlueprintReadOnly, Parm, ZeroConstructor, IsPlainOldData)
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"zp2kshield@gmail.com"
] | zp2kshield@gmail.com |
66ac6ca9ec57ec7951a302aab0542747b454006c | 2abe698cc750417543bcbde45b8e9de5370f3ca8 | /source/Library.Shared/World.cpp | b41b23df1b54047b493b5bf4741e43464bf7786e | [] | no_license | DrScientific/Rudimentary-Game-Engine | 72780923aab666ac0beb7ecb0e67dc292a59e8b4 | 1c176f43a441b738493123c82d6e8f99193ade15 | refs/heads/master | 2021-04-24T03:21:00.397914 | 2020-06-23T06:38:49 | 2020-06-23T06:38:49 | 250,067,564 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,490 | cpp | #include "pch.h"
#include "World.h"
#include "Sector.h"
#include "Factory.h"
#include "Action.h"
using namespace std;
namespace FIEAGameEngine
{
RTTI_DEFINITIONS(World)
World::World(GameTime * time, EventQueue * eventQueue) : Attributed(World::TypeIdClass()), mEventQueue(eventQueue), mState(*time)
{
assert(mVector[mSectorsIndex]->first == mSectorsKey);
mState.mWorld = this;
}
World::World(string const& name, GameTime * time, EventQueue * eventQueue) : World(time, eventQueue)
{
mName = name;
}
void World::Adopt(Scope & child, string const& newChildKey)
{
if (newChildKey == mSectorsKey && !child.Is(Sector::TypeIdClass()))
{
throw exception(nonSectorInSectorsText.c_str());
}
Scope::Adopt(child, newChildKey);
}
string World::Name() const
{
return mName;
}
void World::SetName(string const& name)
{
mName = name;
}
Datum & World::Sectors()
{
return operator[](mSectorsIndex);
}
Datum const& World::Sectors() const
{
return operator[](mSectorsIndex);
}
Sector & World::CreateSector(string const& name)
{
Sector* newSector = new Sector();
newSector->SetWorld(this);
newSector->SetName(name);
Adopt(*newSector, mSectorsKey);
return *newSector;
}
void World::Update()
{
Datum & sectors = Sectors();
for (size_t i = 0; i < sectors.Size(); i++)
{
mState.mSector = static_cast<Sector*>(§ors[i]);
static_cast<Sector*>(§ors[i])->Update(mState);
}
mState.mSector = nullptr;
ClearGraveYard();
mEventQueue->Update(mState);
}
string World::ToString() const
{
return World::TypeName();
}
gsl::owner<Scope*> World::Clone() const
{
World * newWorld = new World(*this);
newWorld->mState.mWorld = newWorld;
newWorld->mState.mSector = nullptr;
newWorld->mState.mEntity = nullptr;
newWorld->mState.mAction = nullptr;
return newWorld;
}
void World::AddActionToGraveYard(Action * actionToDelete)
{
if (mGraveyard.Find(actionToDelete) == mGraveyard.end())
{
mGraveyard.PushBack(actionToDelete);
}
}
const FIEAGameEngine::Vector<Attributed::Signature> World::Signatures()
{
return Vector<Attributed::Signature>
{
{"Name", Datum::DatumType::String, 1, offsetof(World, mName) },
{mSectorsKey, Datum::DatumType::Scope, 0, 0 }
};
}
void World::ClearGraveYard()
{
for (size_t i = 0; i < mGraveyard.Size(); i++)
{
mGraveyard[i]->Orphan();
}
for (size_t i = 0; i < mGraveyard.Size(); i++)
{
delete mGraveyard[i];
}
mGraveyard.Clear();
}
} | [
"tmm3746@yahoo.com"
] | tmm3746@yahoo.com |
230f70848a27ea15ca9db243cfdb2f0435054b92 | be460e66f05c0259cf45e6c0cdb653fc2913972d | /acm/Online-Judge/cf/code/100460K.cpp | 5f26d8f289613ead120258966a4936ac6c4f6449 | [] | no_license | Salvare219/CodeLibrary | 3247aee350402dac3d94e059a8dc97d5d5436524 | 8961a6d1718c58d12c21a857b23e825c16bdab14 | refs/heads/master | 2021-06-16T18:38:21.693960 | 2017-05-09T12:47:36 | 2017-05-09T12:47:36 | 81,569,241 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,759 | cpp | #include <bits/stdc++.h>
using namespace std;
vector<pair<int, int> > pack;
int ans1[100010], ans2[100010];
int spell1[100010], spell2[100010];
int seri1[100010], seri2[100010];
int main()
{
int n, m;
scanf("%d", &n);
for (int i=1; i<=n; i++)
scanf("%d", &spell1[i]);
for (int i=1; i<=n; i++)
scanf("%d", &spell2[i]);
scanf("%d", &m);
for (int i=1; i<=m; i++)
scanf("%d", &seri1[i]);
for (int i=1; i<=m; i++)
scanf("%d", &seri2[i]);
int cnt;
pack.clear();
for (int i=1; i<=n; i++)
pack.push_back(make_pair(spell1[i], -i));
for (int i=1; i<=m; i++)
pack.push_back(make_pair(seri1[i], i));
sort(pack.begin(), pack.end(), greater<pair<int, int> >());
cnt = n+1;
for (int i=0; i<(int)pack.size(); i++)
{
if (pack[i].second < 0)
cnt = min(cnt, -pack[i].second);
else
ans1[pack[i].second] = cnt;
}
pack.clear();
for (int i=1; i<=n; i++)
pack.push_back(make_pair(spell2[i], -i));
for (int i=1; i<=m; i++)
pack.push_back(make_pair(seri2[i], i));
sort(pack.begin(), pack.end(), greater<pair<int, int> >());
cnt = n+1;
for (int i=0; i<(int)pack.size(); i++)
{
if (pack[i].second < 0)
cnt = min(cnt, -pack[i].second);
else
ans2[pack[i].second] = cnt;
}
for (int i=1; i<=m; i++)
if (ans1[i] > ans2[i])
printf("Constantine\n");
else if (ans1[i] < ans2[i])
printf("Mike\n");
else
printf("Draw\n");
return 0;
}
| [
"635149007@qq.com"
] | 635149007@qq.com |
84c9fbb5ef3fe53cf4441162a68d3b7a299a785f | bd525e45d16ee67b19ab83811c08930f12086b6c | /Volume15/1501.cpp | c17e0d9fd49485d4b6ede82fab9d63067c0704af | [] | no_license | face4/AOJ | fb86b3d9a05c2ea1da4819c0d253c48ca06efa56 | e869a5ab38a8ce4ecd7344fc24246da07e0a7b6e | refs/heads/master | 2021-06-10T11:56:27.591053 | 2020-11-26T12:01:35 | 2020-11-26T12:01:35 | 128,877,332 | 7 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,329 | cpp | #include<iostream>
#include<vector>
using namespace std;
typedef long long ll;
const int mod = 100000007;
struct Combination{
int n;
vector<vector<int>> dp;
Combination(int i){
n = i;
dp = vector<vector<int>>(n+1, vector<int>(n+1, 0));
constructTriangle();
}
void constructTriangle(){
dp[0][0] = 1;
for(int i = 1; i <= n; i++){
dp[i][0] = dp[i-1][0];
for(int j = 1; j <= i; j++){
dp[i][j] = (dp[i-1][j] + dp[i-1][j-1]) % mod;
}
}
}
// return aCb
int getCombination(int a, int b){
return dp[a][b];
}
};
int main(){
Combination comb(1001);
int r, c, ax, ay, bx, by;
cin >> r >> c >> ax >> ay >> bx >> by;
int mind = 1001;
for(int i = -1; i <= 1; i++){
for(int j = -1; j <= 1; j++){
int nx = bx + i*r, ny = by + j*c;
mind = min(mind, abs(nx-ax) + abs(ny-ay));
}
}
ll ans = 0;
for(int i = -1; i <= 1; i++){
for(int j = -1; j <= 1; j++){
int nx = bx + i*r, ny = by + j*c;
int x = abs(nx-ax), y = abs(ny-ay);
if(x+y != mind) continue;
ans += comb.getCombination(x+y, x);
ans %= mod;
}
}
cout << ans << endl;
return 0;
} | [
"s1611361@u.tsukuba.ac.jp"
] | s1611361@u.tsukuba.ac.jp |
9e18a3be7c63b6a957db7e08ee93a0b24589d8a3 | 20db548ee72fabb7a1234110e03521db2fadcfc7 | /lib/config/config.cpp | e9c93c49bf17539da6160c8050b28e24a82357a8 | [] | no_license | teeheee/plantiniser | 2accca53b0e5752c952c9cf4dc5a933682b1236f | ed2689d51a21d079fc9c8229d0413553f120c566 | refs/heads/master | 2021-06-17T18:37:45.156062 | 2021-03-24T20:00:33 | 2021-03-24T20:00:33 | 190,473,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,366 | cpp | #include "config.h"
#include <string>
std::string ConfigManage::get_wifi_ssid()
{
if(wifi_ssid.is_data_valid())
return wifi_ssid.read_data();
else
return std::string("");
}
std::string ConfigManage::get_wifi_passkey()
{
if(wifi_passkey.is_data_valid())
return wifi_passkey.read_data();
else
return std::string("");
}
std::string ConfigManage::get_server_address()
{
if(server_address.is_data_valid())
return server_address.read_data();
else
return std::string("");
}
int ConfigManage::get_water_valve_on_hour()
{
if(water_valve_on_hour.is_data_valid())
return water_valve_on_hour.read_data();
else
return 0;
}
int ConfigManage::get_water_valve_on_minute()
{
if(water_valve_on_minute.is_data_valid())
return water_valve_on_minute.read_data();
else
return 0;
}
int ConfigManage::get_water_valve_on_duration()
{
if(water_valve_on_duration.is_data_valid())
return water_valve_on_duration.read_data();
else
return 0;
}
bool ConfigManage::all_valid()
{
for(auto const& config_item : list_of_config_items)
{
if(config_item->is_data_valid() == false)
return false;
}
return true;
}
std::list<ConfigBaseItem*>* ConfigManage::get_config_item_list()
{
return &list_of_config_items;
} | [
"alexander.ulbrich@uni-ulm.de"
] | alexander.ulbrich@uni-ulm.de |
27eb0eecaae54d7ccf525e7d2cb5ccfeb2fa0c55 | 639285b2198e12932b29ecab97acf01086471a91 | /Essentials/pbds.cpp | b28b9c20ec936609cc79317a95565bbf8964b4dd | [] | no_license | itish-agarwal/Cp-essentials | cf22f72557046c1df24b3d62515a86bd0e92b377 | 07882688f388bfc866c3ef1caeeae7bfe7228197 | refs/heads/main | 2023-06-24T20:28:45.234987 | 2021-07-24T05:57:01 | 2021-07-24T05:57:01 | 339,648,911 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 787 | cpp |
#include <bits/stdc++.h>
#include <ext/pb_ds/assoc_container.hpp>
#include <ext/pb_ds/tree_policy.hpp>
using namespace __gnu_pbds;
using namespace std;
/*
less<int> -> acts as set
less_equal<int> -> acts as multiset
*/
/*
order_of_key (k) : Number of items strictly smaller than k .
find_by_order(k) : K-th element in a set (counting from zero).
*/
#define ordered_set tree <int, null_type, less<int>, rb_tree_tag, tree_order_statistics_node_update>
signed main() {
ios::sync_with_stdio(false);
cin.tie(0);
int tt;
cin >> tt;
while(tt--) {
int n, x, y;
cin >> n >> x;
int in = 0;
ordered_set s;
for(int i = 0; i < n; i++) {
cin >> y;
in += i - s.order_of_key(y);
s.insert(y);
}
cout << 2*in*x << '\n';
}
return 0;
}
| [
"itishagarwal2000@gmail.com"
] | itishagarwal2000@gmail.com |
1685e74f9a7d29d3b0738eb65ab8cb240613f3b5 | e17b31b573cb309757fcda0f85f1ef6d8e816bc3 | /Tarea_Corta/proceso.h | 910afcc54c4087d27192ff42e3c78c08c64091c6 | [] | no_license | MarianaVargas12/Tarea-Corta-Procesos | 1ef9e3f0922a5071f9a167c97ef5bcf29784ac38 | e5433e2a6fd95a099c7c4c8e39cf7419d5ca5f75 | refs/heads/master | 2020-05-09T18:22:34.413946 | 2019-04-14T17:15:38 | 2019-04-14T17:15:38 | 181,339,630 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 100 | h | #ifndef PROCESO_H
#define PROCESO_H
class Proceso
{
public:
Proceso();
};
#endif // PROCESO_H | [
"marianavargas1209@gmail.com"
] | marianavargas1209@gmail.com |
190f4126c3ae00f788a0ffb6d7c3d1014b714618 | 0a86d8d2f77547aa71af6d3b5c90f225a0d74717 | /MaximilianTest/Source/MainComponent.h | 643754132ed9ef67fea7f44de3ea5e66c6cd1a72 | [] | no_license | mrg498/JUCE_personal | 1d5dd59d2e5c1c67f570cf5bc0eefabf17502c7c | d0c95659443adff66d3603b74ea8e2b565af7108 | refs/heads/master | 2020-12-08T05:17:36.174877 | 2020-01-09T20:18:26 | 2020-01-09T20:18:26 | 232,895,889 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,346 | h | /*
==============================================================================
This file was auto-generated!
==============================================================================
*/
#pragma once
#include "../JuceLibraryCode/JuceHeader.h"
//==============================================================================
/*
This component lives inside our window, and this is where you should put all
your controls and content.
*/
class MainComponent : public AudioAppComponent
{
public:
//==============================================================================
MainComponent();
~MainComponent();
//==============================================================================
void prepareToPlay (int samplesPerBlockExpected, double sampleRate) override;
void getNextAudioBlock (const AudioSourceChannelInfo& bufferToFill) override;
void releaseResources() override;
//==============================================================================
void paint (Graphics& g) override;
void resized() override;
private:
//==============================================================================
// Your private member variables go here...
JUCE_DECLARE_NON_COPYABLE_WITH_LEAK_DETECTOR (MainComponent)
};
| [
"mrg498@nyu.edu"
] | mrg498@nyu.edu |
9018b66498aec2e42163a817fa7ac90864f93bf1 | 30773b649ebd89ffadd16d30fd62740b77ca7865 | /SDK/BP_Beacon_parameters.h | d0ca677baf39e4c11ddea9f388264f283b63a8ac | [] | no_license | The-Jani/Sot-SDK | 7f2772fb5df421e02b8fec237248af407cb2540b | 2a158a461c697cca8db67aa28ffe3e43677dcf11 | refs/heads/main | 2023-07-09T07:17:56.972569 | 2021-08-18T23:45:06 | 2021-08-18T23:45:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | h | #pragma once
// Name: S, Version: 2.2.1
#include "../SDK.h"
/*!!DEFINE!!*/
/*!!HELPER_DEF!!*/
/*!!HELPER_INC!!*/
#ifdef _MSC_VER
#pragma pack(push, 0x01)
#endif
namespace CG
{
//---------------------------------------------------------------------------
// Parameters
//---------------------------------------------------------------------------
// Function BP_Beacon.BP_Beacon_C.UserConstructionScript
struct ABP_Beacon_C_UserConstructionScript_Params
{
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"ploszjanos9844@gmail.com"
] | ploszjanos9844@gmail.com |
2cc9e11a87b1c9982d0cb0982417e9f6632451ec | 999dcae2e612f3dd1c01f712e8893317539a9f6c | /minimumTimeDifference.cpp | b6d6a58f8d54d2785c1d8a1fcdfa136707a2d6a9 | [] | no_license | han0305/Problem-Solving | ab1f56f07f850d639da35d06c768989dc2850a7c | 9ed98f19ec31c6b367dbce88d38fe715a08f5608 | refs/heads/master | 2023-09-01T18:51:03.160623 | 2021-11-01T14:22:09 | 2021-11-01T14:22:09 | 288,743,667 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 906 | cpp | /* Given a list of 24-hour clock time points in "HH:MM" format, return the minimum minutes difference between any two time-points in the list. */
class Solution {
public:
int getMin(string s1) {
int hr = stoi(s1.substr(0,2));
int min = stoi(s1.substr(3,2));
int minutes = hr*60 + min;
return minutes;
}
int findMinDifference(vector<string>& timePoints) {
int l = timePoints.size();
if(l>24*60) {
return 0;
}
vector<int> times;
for(int i=0;i<l;i++) {
int minutes = getMin(timePoints[i]);
times.push_back(minutes);
}
sort(times.begin(),times.end());
times.push_back(times[0]+24*60);
int minm = INT_MAX;
for(int i = 1;i<times.size();i++) {
minm = min(minm,times[i]-times[i-1]);
}
return minm;
}
}; | [
"roy.aditya1605@gmail.com"
] | roy.aditya1605@gmail.com |
d602974f401c17895293ede9c20a84b67f939b91 | 6628cd493fbe92c2079ff275d53540648314fa32 | /Onlinejudge/1078 - Multiplication Table.cpp | 0230716eb697b25af4881539eca2e77617d487ea | [] | no_license | sebicarhat/Cplusplus | e48b77162ea3989aa80612856444984f54a586b7 | 1a7999c1cb4f4ac4e7d7e25e1fb0b998d2dd75bc | refs/heads/master | 2020-04-11T00:21:36.257888 | 2019-06-12T09:18:13 | 2019-06-12T09:18:13 | 160,858,408 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 138 | cpp | #include<iostream>
using namespace std;
int main()
{
int i,n;
cin>>n;
for(i=1;i<=10;i++)
cout<<i<<" x "<<n<<" = "<<i*n<<"\n";
return 0;
}
| [
"45130729+sebicarhat@users.noreply.github.com"
] | 45130729+sebicarhat@users.noreply.github.com |
2fbe1fefa5b222e91d0603798e6533ae2f535103 | ae2ef50c74e0eed32be1f1baec117a0fe0ec356d | /sources/helloworld_ocl/src/vadd.cpp | 0a6edb959fae08eaa58b5dfe1b221b0421a5f609 | [] | no_license | cathalmccabe/awslabs | 8e56ba9823972b10b941b869eeab773af0dd9ff0 | eb917e30bc52717b1b7e5c181170ceb4e7c2a19e | refs/heads/master | 2020-04-17T04:53:25.427986 | 2019-02-19T10:19:31 | 2019-02-19T10:19:31 | 166,251,400 | 2 | 0 | null | 2019-01-17T15:47:13 | 2019-01-17T15:47:13 | null | UTF-8 | C++ | false | false | 5,436 | cpp | /*******************************************************************************
Vendor: Xilinx
Associated Filename: vadd.cpp
Purpose: SDAccel vector addition
*******************************************************************************
Copyright (C) 2017 XILINX, Inc.
This file contains confidential and proprietary information of Xilinx, Inc. and
is protected under U.S. and international copyright and other intellectual
property laws.
DISCLAIMER
This disclaimer is not a license and does not grant any rights to the materials
distributed herewith. Except as otherwise provided in a valid license issued to
you by Xilinx, and to the maximum extent permitted by applicable law:
(1) THESE MATERIALS ARE MADE AVAILABLE "AS IS" AND WITH ALL FAULTS, AND XILINX
HEREBY DISCLAIMS ALL WARRANTIES AND CONDITIONS, EXPRESS, IMPLIED, OR STATUTORY,
INCLUDING BUT NOT LIMITED TO WARRANTIES OF MERCHANTABILITY, NON-INFRINGEMENT, OR
FITNESS FOR ANY PARTICULAR PURPOSE; and (2) Xilinx shall not be liable (whether
in contract or tort, including negligence, or under any other theory of
liability) for any loss or damage of any kind or nature related to, arising under
or in connection with these materials, including for any direct, or any indirect,
special, incidental, or consequential loss or damage (including loss of data,
profits, goodwill, or any type of loss or damage suffered as a result of any
action brought by a third party) even if such damage or loss was reasonably
foreseeable or Xilinx had been advised of the possibility of the same.
CRITICAL APPLICATIONS
Xilinx products are not designed or intended to be fail-safe, or for use in any
application requiring fail-safe performance, such as life-support or safety
devices or systems, Class III medical devices, nuclear facilities, applications
related to the deployment of airbags, or any other applications that could lead
to death, personal injury, or severe property or environmental damage
(individually and collectively, "Critical Applications"). Customer assumes the
sole risk and liability of any use of Xilinx products in Critical Applications,
subject only to applicable laws and regulations governing limitations on product
liability.
THIS COPYRIGHT NOTICE AND DISCLAIMER MUST BE RETAINED AS PART OF THIS FILE AT
ALL TIMES.
*******************************************************************************/
#include <stdlib.h>
#include <fstream>
#include <iostream>
#include <numeric>
#include "vadd.h"
static const int DATA_SIZE = 4096;
int main(int argc, char* argv[]) {
if(argc != 2) {
std::cout << "Usage: " << argv[0] <<" <xclbin>" << std::endl;
return EXIT_FAILURE;
}
char* xclbinFilename = argv[1];
const char *kernel_name = "krnl_vadd"; // Open CL Kernel name
// Compute the size of array in bytes
size_t size_in_bytes = DATA_SIZE * sizeof(int);
// Creates a vector of DATA_SIZE elements with an initial value of 10 and 32
// using customized allocator for getting buffer alignment to 4k boundary
std::vector<int,aligned_allocator<int>> source_a(DATA_SIZE);
std::vector<int,aligned_allocator<int>> source_b(DATA_SIZE);
std::vector<int,aligned_allocator<int>> source_results(DATA_SIZE);
std::iota (std::begin(source_a), std::end(source_a), 0);
std::iota (std::begin(source_b), std::end(source_b), 0);
std::vector<cl::Device> devices;
cl::Device device;
std::cout << "Get Xilinx platform" << std::endl;
get_xilinx_platform(&device, &devices);
// Creating Context and Command Queue for selected device
cl::Context context(device);
cl::CommandQueue q(context, device, CL_QUEUE_PROFILING_ENABLE);
cl::Kernel krnl_vector_add;
krnl_vector_add = load_xcl_bin(kernel_name, xclbinFilename, &context, &devices);
// These commands will allocate memory on the Device. The cl::Buffer objects can
// be used to reference the memory locations on the device.
cl::Buffer buffer_a(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_in_bytes, source_a.data());
cl::Buffer buffer_b(context, CL_MEM_USE_HOST_PTR | CL_MEM_READ_ONLY,
size_in_bytes, source_b.data());
cl::Buffer buffer_result(context, CL_MEM_USE_HOST_PTR | CL_MEM_WRITE_ONLY,
size_in_bytes, source_results.data());
// Data will be transferred from host memory over PCIe to the FPGA on-board
// DDR memory.
q.enqueueMigrateMemObjects({buffer_a,buffer_b},0/* 0 means from host*/);
//set the kernel Arguments
int narg=0;
krnl_vector_add.setArg(narg++,buffer_a);
krnl_vector_add.setArg(narg++,buffer_b);
krnl_vector_add.setArg(narg++,buffer_result);
krnl_vector_add.setArg(narg++,DATA_SIZE);
//Launch the Kernel
q.enqueueTask(krnl_vector_add);
// Transfer data from FPGA DDR to host memory
// source_results vector
q.enqueueMigrateMemObjects({buffer_result},CL_MIGRATE_MEM_OBJECT_HOST);
q.finish();
//Verify the result
int match = 0;
for (int i = 0; i < DATA_SIZE; i++) {
int host_result = source_a[i] + source_b[i];
if (source_results[i] != host_result) {
printf(error_message.c_str(), i, host_result, source_results[i]);
match = 1;
break;
}
}
std::cout << "TEST " << (match ? "FAILED" : "PASSED") << std::endl;
return (match ? EXIT_FAILURE : EXIT_SUCCESS);
}
| [
"cathalmccabe@hotmail.com"
] | cathalmccabe@hotmail.com |
ec4d21a25df3184e20252ed150199d9d66851f00 | 7aa75ed5813d3778d557ccb1c1bceca9e4b14fe7 | /MatrixRecover/Experiments.h | c22d11c9c01f08077eeb1ea44968cf2a701fb026 | [] | no_license | xzhou/gnome | 8a40ad4b3269129dcb585addaeaeb9f4690dee56 | 1e9df8a380e9935e7e1455e677eb2badbb7657ed | refs/heads/master | 2021-01-10T01:20:15.174093 | 2010-11-19T03:26:03 | 2010-11-19T03:26:03 | 36,974,942 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 689 | h | /*
* Experiments.h
* Experiments do different experiments
*
* Created on: Nov 5, 2010
* Author: xzhou
*/
#ifndef EXPERIMENTS_H_
#define EXPERIMENTS_H_
#include <fstream>
#include <iostream>
#include "Solver.h"
#include "SnpMatrix.h"
#include "ExpConf.h"
class Experiments {
private:
ofstream *slnLog; //solution log
ofstream *slnCtLog; //solution count log
ExpConf conf;
public:
Experiments();
virtual ~Experiments();
void largeScaleFixRow(); //for large scale problem, we verify the difficulty
void smallScaleFixRow(int m, int n, int repeat); //
void findMultipleSolution();
void exclucde(); //find exclude code
void testCode();
};
#endif /* EXPERIMENTS_H_ */
| [
"zhou.xiaoyong@f091b60a-4754-11de-82b9-170f4fd74ac7"
] | zhou.xiaoyong@f091b60a-4754-11de-82b9-170f4fd74ac7 |
ec6e55d704e1162f156797c8229f77be1c7edba6 | 85868fd595644bf13621c878d73f36bf79f98b64 | /helpers/local/featured.FeatureLibrary.check.cc | 855d35ac270190275fd810484eb59f681e946316 | [
"BSD-3-Clause"
] | permissive | nya3jp/tast-tests | 1ff6e7deea09722589b17d038b0ed620e3a5859f | 6df7195ab510129348eca3f2b2cd2be1879c3352 | refs/heads/main | 2022-11-15T02:34:16.569851 | 2022-11-04T09:51:27 | 2022-11-13T16:34:31 | 151,897,650 | 7 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 4,872 | cc | // Copyright 2022 The ChromiumOS Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <stdio.h>
#include <memory>
#include <string>
#include <base/callback.h>
#include <base/check_op.h>
#include <base/files/file_descriptor_watcher_posix.h>
#include <base/json/json_writer.h>
#include <base/logging.h>
#include <base/run_loop.h>
#include <base/task/single_thread_task_executor.h>
#include <base/test/bind.h>
#include <base/values.h>
#include <dbus/bus.h>
#include "featured/feature_library.h"
const struct VariationsFeature kCrOSLateBootDefaultEnabled = {
.name = "CrOSLateBootTestDefaultEnabled",
.default_state = FEATURE_ENABLED_BY_DEFAULT,
};
const struct VariationsFeature kCrOSLateBootDefaultDisabled = {
.name = "CrOSLateBootTestDefaultDisabled",
.default_state = FEATURE_DISABLED_BY_DEFAULT,
};
struct TestFeatureState {
std::string feature_name;
bool enabled_callback_enabled_result;
feature::PlatformFeatures::ParamsResult params_callback_result;
};
void LogTestFeatureState(const TestFeatureState& feature_state) {
base::Value::Dict root_dict;
root_dict.Set("FeatureName", feature_state.feature_name);
root_dict.Set("EnabledCallbackEnabledResult",
feature_state.enabled_callback_enabled_result);
auto result_entry =
feature_state.params_callback_result.find(feature_state.feature_name);
CHECK(result_entry != feature_state.params_callback_result.end())
<< "Did not find expected feature";
std::string name = result_entry->first;
feature::PlatformFeatures::ParamsResultEntry feature = result_entry->second;
root_dict.Set("ParamsCallbackFeatureName", std::move(name));
root_dict.Set("ParamsCallbackEnabledResult", feature.enabled);
base::Value::Dict params;
for (const auto& [key, value] : feature.params) {
params.Set(key, value);
}
root_dict.Set("ParamsCallbackParamsResult", base::Value(std::move(params)));
std::string output_json;
base::JSONWriter::Write(root_dict, &output_json);
printf("%s\n", output_json.c_str());
}
bool IsFeatureEnabled(const VariationsFeature& feature_to_check,
feature::PlatformFeatures* feature_lib) {
bool result = false;
base::RunLoop run_loop;
feature_lib->IsEnabled(feature_to_check,
base::BindLambdaForTesting([&](bool enabled) {
result = enabled;
run_loop.Quit();
}));
LOG(INFO) << "Called IsEnabled";
run_loop.Run();
LOG(INFO) << "Successfully ran IsEnabled";
return result;
}
feature::PlatformFeatures::ParamsResult
GetParamsAndEnabled(const VariationsFeature& feature_to_check,
feature::PlatformFeatures* feature_lib) {
feature::PlatformFeatures::ParamsResult result;
base::RunLoop run_loop;
feature_lib->GetParamsAndEnabled(
{&feature_to_check},
base::BindLambdaForTesting(
[&](feature::PlatformFeatures::ParamsResult params) {
result = params;
run_loop.Quit();
}));
LOG(INFO) << "Called GetParamsAndEnabled";
run_loop.Run();
LOG(INFO) << "Successfully ran GetParamsAndEnabled";
return result;
}
TestFeatureState
GetTestFeatureStateAndParams(const VariationsFeature& feature_to_check,
feature::PlatformFeatures* feature_lib) {
TestFeatureState feature_state;
feature_state.feature_name = feature_to_check.name;
feature_state.enabled_callback_enabled_result =
IsFeatureEnabled(feature_to_check, feature_lib);
LOG(INFO) << "Successfully returned from IsFeatureEnabled.";
feature_state.params_callback_result =
GetParamsAndEnabled(feature_to_check, feature_lib);
LOG(INFO) << "Successfully returned from GetParamsAndEnabled.";
return feature_state;
}
int main(int argc, char* argv[]) {
base::SingleThreadTaskExecutor task_executor(base::MessagePumpType::IO);
base::FileDescriptorWatcher watcher(task_executor.task_runner());
dbus::Bus::Options options;
options.bus_type = dbus::Bus::SYSTEM;
scoped_refptr<dbus::Bus> bus(new dbus::Bus(options));
std::unique_ptr<feature::PlatformFeatures> feature_lib =
feature::PlatformFeatures::New(bus);
TestFeatureState enabled_feature = GetTestFeatureStateAndParams(
kCrOSLateBootDefaultEnabled, feature_lib.get());
LOG(INFO) << "Finished getting state and params for Default Enabled Feature";
TestFeatureState disabled_feature = GetTestFeatureStateAndParams(
kCrOSLateBootDefaultDisabled, feature_lib.get());
LOG(INFO) << "Finished getting state and params for Default Disabled Feature";
LogTestFeatureState(enabled_feature);
LOG(INFO) << "Finished logging Default Enabled Feature";
LogTestFeatureState(disabled_feature);
LOG(INFO) << "Finished logging Default Disabled Feature";
}
| [
"chromeos-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | chromeos-scoped@luci-project-accounts.iam.gserviceaccount.com |
a4243cef3f88e7313d44ed0dad7a63727e2cb848 | 32b268790ae6a752a1a6b795ddaf2d6f39706c75 | /3773-adv-obj-oriented-app-dev-w-c++/programs/ch6/ex6.4.expression.cpp | 5afeab0f1934a4d725a7fa052bad3b6e44bdf695 | [] | no_license | dideler/school-projects | eeb353e902be4577c8818aac06be6f95be2b7f06 | 1887d3adaa710e9db5f0be290f912a530541a2cb | refs/heads/master | 2020-04-13T17:04:57.209111 | 2015-10-11T21:59:31 | 2015-10-11T21:59:31 | 8,245,107 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,203 | cpp | // Tomasz Muldner, September 2001
// A program for the book:
// "C++ Programming with Design Patterns Revealed", published by Addison-Wesley
// File: ex6.4.expression.cpp
//
// Exercise 6-4, 1st version
// Implementation for the class Expression
#include "ex6.4.expression.h"
#include "ex6.4.valuenode.h"
#include "ex6.4.unarynode.h"
#include "ex6.4.binarynode.h"
#include <iostream>
#include <string>
using namespace std;
Expression::Expression(double num) { rep_ = new ValueNode(num); }
Expression::Expression(const string& op, const Expression& t)
{
rep_ = new UnaryNode(op, t);
}
Expression::Expression(const string& op, const Expression& t1,
const Expression& t2)
{
rep_ = new BinaryNode(op, t1, t2);
}
Expression::Expression(const Expression& t)
{
rep_ = t.rep_;
++rep_->use_;
}
Expression::~Expression() { if (--rep_->use_ == 0) delete rep_; }
Expression& Expression::operator=(const Expression& rhs)
{
if (this == &rhs) return *this;
++rhs.rep_->use_;
if (--rep_->use_ == 0) delete rep_;
rep_= rhs.rep_;
return *this;
}
void Expression::print(ostream& os) const { rep_->print(os); }
double Expression::eval() const { return rep_->eval(); }
| [
"ideler.dennis@gmail.com"
] | ideler.dennis@gmail.com |
c1ea8278235cb6298918119281cce3abacef6bfc | f4806ae67008c5b0181dafdc877b644e8cdf5e5b | /NumbersRecognition/drawer.cpp | ae71d8fccc744735588d230c6b43283a6e636209 | [] | no_license | vladisai/Machine-Learning---Numbers-Recognition | 8eb4a88eac83f55f0994f2fafeb7d866b4340d2d | 2dea8837b8f0017fc849ac514526be9b0dfbdb3d | refs/heads/master | 2021-05-28T03:49:30.032295 | 2013-06-18T11:46:23 | 2013-06-18T11:46:31 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,521 | cpp | #include "drawer.h"
Drawer::Drawer(QWidget *parent) :
QWidget(parent)
{
this->setFixedSize(300, 300);
blocks.push_back(0);
pixmap = QPixmap(300, 300);
}
void Drawer::mouseMoveEvent(QMouseEvent *e)
{
Qt::MouseButtons state = e->buttons();
bool isLeftButtonPressed = state & Qt::LeftButton;
if (isLeftButtonPressed)
{
points.push_back(make_pair(e->x(), e->y()));
blocks[blocks.size()-1] = points.size()-1;
}
this->repaint();
}
void Drawer::paintEvent(QPaintEvent *e)
{
QPainter painter(&pixmap);
painter.setRenderHint(QPainter::Antialiasing);
painter.setBrush(QBrush("#000000"));
painter.setPen(QPen(QBrush("#000000"), penSize));
painter.fillRect(QRect(-1, -1, 301, 301), QBrush("#FFFFFF"));
int curBlock = 0;
for(int i = 0; i<points.size(); i++)
{
int j = i;
while (j != blocks[curBlock])
{
painter.drawLine(QPoint(points[j].first, points[j].second), QPoint(points[j+1].first, points[j+1].second));
j++;
}
i = j;
curBlock++;
}
QPainter wPainter(this);
wPainter.drawPixmap(0, 0, 300, 300, pixmap);
}
void Drawer::mouseReleaseEvent(QMouseEvent *e)
{
blocks[blocks.size()-1] = points.size()-1;
blocks.push_back(points.size()-1);
}
void Drawer::ClearCanvas()
{
points.clear();
blocks.clear();
blocks.push_back(0);
//pixmap = QPixmap(300, 300);
repaint();
}
bool Drawer::checkRow(int k, QImage img)
{
int w = img.width();
QColor check;
check.setRgb(0, 0, 0);
for(int i = 0; i<w; i++)
if (img.pixel(i, k) == check.rgb())
return false;
return true;
}
bool Drawer::checkColumn(int k, QImage img)
{
int h = img.height();
QColor check;
check.setRgb(0, 0, 0);
for(int i = 0; i<h; i++)
{
QRgb pix = img.pixel(k, i);
if (pix == check.rgb())
return false;
}
return true;
}
int Drawer::getAverageTint(int hs, int ws, int h, int w, QImage img)
{
int sum = 0;
for(int i = hs; i<hs+h; i++)
for(int j = ws; j<ws+w; j++)
{
sum += 255 - qGray(img.pixel(j, i));
}
return (sum/(w*h));
}
vector< vector<int> > Drawer::getSimplifiedPic(int w, int h, int cols)
{
QImage img = pixmap.toImage();
QImageWriter imagefile;
imagefile.setFileName("out.png");
imagefile.setFormat("png");
imagefile.setQuality(100);
imagefile.write(img);
int up = 0;
int bottom = img.height()-1;
int left = 0;
int right = img.width()-1;
while (checkRow(up, img))
up++;
while (checkRow(bottom, img))
bottom--;
while (checkColumn(left, img))
left++;
while (checkColumn(right, img))
right--;
int marginH = w;
int marginV = h;
/*up = max(0, up - marginV);
bottom = min(img.height(), bottom - marginV);
left = max(0, left - marginH);
right = min(img.width(), right + marginH);*/
int blockWidth = max((right - left)/w + 1, 1);
int blockHeight = max((bottom - up)/h + 1, 1);
vector< vector<int> > res;
res.resize(h);
for(int i = 0; i<res.size(); i++)
{
res[i].resize(w);
}
for(int i = 0; i<h; i++)
{
for(int j = 0; j<w; j++)
{
res[i][j] = getAverageTint(up + blockHeight * i, left + blockWidth * j,
blockHeight, blockWidth, img);
}
}
return res;
}
| [
"vlad7mail@gmail.com"
] | vlad7mail@gmail.com |
7413002e246cd4f095419b74f7f389edc9a68d0d | 7785651dbb7b49a8a9ae4a2ba52601264db9c882 | /src/orbit/tle.h | 498ef1c23165c18d58f4fe26a4c3375397288bbe | [] | no_license | mfkiwl/AltiWx | d4f25b03b1264b5681e387cc6861ab5be7bb3baf | 7fcba825be6bff01d09e7aa8c02ac55b604a2e80 | refs/heads/master | 2023-04-21T17:43:54.180493 | 2021-05-11T10:30:47 | 2021-05-11T10:30:47 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 191 | h | #pragma once
#include <string>
struct TLE
{
bool valid = true;
std::string object_name;
std::string tle_line_1;
std::string tle_line_2;
};
TLE fetchCelestrakTLE(int norad); | [
"qwerty15@gmx.fr"
] | qwerty15@gmx.fr |
a1ce07ec65efd7ba423329e4e709960967c76c3f | d8309b8ae823f3ba91b6269155e79d40406d901f | /programs/01/sample.cpp | 220c4e893febb308efe63cd7851b6639ccc5e952 | [
"MIT"
] | permissive | aruneko/cpp | def503a8e03f5910150e3abe9e5a958bd190a058 | 94ab597c20d6c62c6dd406a69a8e9d3aafa9d778 | HEAD | 2016-09-06T13:16:41.472258 | 2014-12-22T11:26:13 | 2014-12-22T11:26:13 | 27,591,038 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 182 | cpp | #include <iostream>
using namespace std;
int main() {
int n;
cout << "整数を入力してください";
cin >> n;
cout << "入力した整数は" << n << "です" << endl;
}
| [
"unconfigured@null.spigotmc.org"
] | unconfigured@null.spigotmc.org |
9e21fea238cad93b3ce729adedb1d738699e6ab2 | b3058f79e079f8d3001e9f8b6b6dafda67ff641d | /src/pbrt/gpu/subsurface.cpp | b8a24fd8a3504e6c71581ed82831fa07a49b5faf | [
"Apache-2.0"
] | permissive | Innericy/pbrt-v4 | 147c6379626bbef072c07c3028b475def8eb6157 | 2a86a5370443ac2c03a09e69679c551593fe28e4 | refs/heads/master | 2023-04-11T12:36:09.177921 | 2021-04-28T16:27:37 | 2021-04-28T16:27:37 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,791 | cpp | // pbrt is Copyright(c) 1998-2020 Matt Pharr, Wenzel Jakob, and Greg Humphreys.
// The pbrt source code is licensed under the Apache License, Version 2.0.
// SPDX: Apache-2.0
#include <pbrt/pbrt.h>
#include <pbrt/bssrdf.h>
#include <pbrt/gpu/accel.h>
#include <pbrt/gpu/launch.h>
#include <pbrt/gpu/pathintegrator.h>
#include <pbrt/interaction.h>
#include <pbrt/lightsamplers.h>
#include <pbrt/samplers.h>
#include <pbrt/util/sampling.h>
#include <pbrt/util/spectrum.h>
namespace pbrt {
// GPUPathIntegrator Subsurface Scattering Methods
void GPUPathIntegrator::SampleSubsurface(int depth) {
RayQueue *rayQueue = CurrentRayQueue(depth);
RayQueue *nextRayQueue = NextRayQueue(depth);
ForAllQueued(
"Get BSSRDF and enqueue probe ray", bssrdfEvalQueue, maxQueueSize,
PBRT_GPU_LAMBDA(const GetBSSRDFAndProbeRayWorkItem w) {
using BSSRDF = typename SubsurfaceMaterial::BSSRDF;
BSSRDF bssrdf;
const SubsurfaceMaterial *material = w.material.Cast<SubsurfaceMaterial>();
MaterialEvalContext ctx = w.GetMaterialEvalContext();
SampledWavelengths lambda = w.lambda;
material->GetBSSRDF(BasicTextureEvaluator(), ctx, lambda, &bssrdf);
RaySamples raySamples = pixelSampleState.samples[w.pixelIndex];
Float uc = raySamples.subsurface.uc;
Point2f u = raySamples.subsurface.u;
pstd::optional<BSSRDFProbeSegment> probeSeg = bssrdf.SampleSp(uc, u);
if (probeSeg)
subsurfaceScatterQueue->Push(probeSeg->p0, probeSeg->p1, material, bssrdf,
lambda, w.T_hat, w.uniPathPDF,
w.mediumInterface, w.etaScale, w.pixelIndex);
});
accel->IntersectOneRandom(maxQueueSize, subsurfaceScatterQueue);
ForAllQueued(
"Handle out-scattering after SSS", subsurfaceScatterQueue, maxQueueSize,
PBRT_GPU_LAMBDA(SubsurfaceScatterWorkItem w) {
if (w.reservoirPDF == 0)
return;
using BSSRDF = TabulatedBSSRDF;
BSSRDF bssrdf = w.bssrdf;
using BxDF = typename BSSRDF::BxDF;
BxDF bxdf;
SubsurfaceInteraction &intr = w.ssi;
BSSRDFSample bssrdfSample = bssrdf.ProbeIntersectionToSample(intr, &bxdf);
if (!bssrdfSample.Sp || !bssrdfSample.pdf)
return;
SampledSpectrum T_hatp = w.T_hat * bssrdfSample.Sp;
SampledSpectrum uniPathPDF = w.uniPathPDF * w.reservoirPDF * bssrdfSample.pdf;
SampledWavelengths lambda = w.lambda;
RaySamples raySamples = pixelSampleState.samples[w.pixelIndex];
Vector3f wo = bssrdfSample.wo;
BSDF &bsdf = bssrdfSample.Sw;
Float time = 0; // TODO: pipe through
// NOTE: the remainder is copied from the Material/BSDF eval method.
// Will unify into shared fragments in the book...
// Indirect...
{
Point2f u = raySamples.indirect.u;
Float uc = raySamples.indirect.uc;
pstd::optional<BSDFSample> bsdfSample = bsdf.Sample_f<BxDF>(wo, uc, u);
if (bsdfSample) {
Vector3f wi = bsdfSample->wi;
SampledSpectrum T_hat = T_hatp * bsdfSample->f * AbsDot(wi, intr.ns);
SampledSpectrum indirUniPathPDF = uniPathPDF,
lightPathPDF = uniPathPDF;
PBRT_DBG("%s f*cos[0] %f bsdfSample->pdf %f f*cos/pdf %f\n",
BxDF::Name(), bsdfSample->f[0] * AbsDot(wi, intr.ns),
bsdfSample->pdf,
bsdfSample->f[0] * AbsDot(wi, intr.ns) / bsdfSample->pdf);
if (bsdfSample->pdfIsProportional) {
Float pdf = bsdf.PDF(wo, wi);
T_hat *= pdf / bsdfSample->pdf;
indirUniPathPDF *= pdf;
PBRT_DBG("Sampled PDF is proportional: pdf %f\n", pdf);
} else
indirUniPathPDF *= bsdfSample->pdf;
Float etaScale = w.etaScale;
if (bsdfSample->IsTransmission())
etaScale *= Sqr(bsdfSample->eta);
// Russian roulette
SampledSpectrum rrBeta = T_hat * etaScale / indirUniPathPDF.Average();
if (rrBeta.MaxComponentValue() < 1 && depth > 1) {
Float q = std::max<Float>(0, 1 - rrBeta.MaxComponentValue());
if (raySamples.indirect.rr < q) {
T_hat = SampledSpectrum(0.f);
PBRT_DBG("Path terminated with RR\n");
}
indirUniPathPDF *= 1 - q;
lightPathPDF *= 1 - q;
}
if (T_hat) {
Ray ray = SpawnRay(intr.pi, intr.n, time, wi);
if (haveMedia)
// TODO: should always just take outside in this case?
ray.medium = Dot(ray.d, intr.n) > 0
? w.mediumInterface.outside
: w.mediumInterface.inside;
// || rather than | is intentional, to avoid the read if
// possible...
bool anyNonSpecularBounces = true;
LightSampleContext ctx(intr.pi, intr.n, intr.ns);
nextRayQueue->PushIndirectRay(
ray, ctx, T_hat, indirUniPathPDF, lightPathPDF, lambda,
etaScale, bsdfSample->IsSpecular(), anyNonSpecularBounces,
w.pixelIndex);
PBRT_DBG("Spawned indirect ray at depth %d. "
"Specular %d T_Hat %f %f %f %f indirUniPathPDF %f %f %f "
"%f lightPathPDF %f "
"%f %f %f "
"T_hat/indirUniPathPDF %f %f %f %f\n",
depth + 1, int(bsdfSample->IsSpecular()), T_hat[0],
T_hat[1], T_hat[2], T_hat[3], indirUniPathPDF[0],
indirUniPathPDF[1], indirUniPathPDF[2],
indirUniPathPDF[3], lightPathPDF[0], lightPathPDF[1],
lightPathPDF[2], lightPathPDF[3],
SafeDiv(T_hat, indirUniPathPDF)[0],
SafeDiv(T_hat, indirUniPathPDF)[1],
SafeDiv(T_hat, indirUniPathPDF)[2],
SafeDiv(T_hat, indirUniPathPDF)[3]);
}
}
}
// Direct lighting...
if (bsdf.IsNonSpecular()) {
LightSampleContext ctx(intr.pi, intr.n, intr.ns);
pstd::optional<SampledLight> sampledLight =
lightSampler.Sample(ctx, raySamples.direct.uc);
if (!sampledLight)
return;
Light light = sampledLight->light;
pstd::optional<LightLiSample> ls = light.SampleLi(
ctx, raySamples.direct.u, lambda, LightSamplingMode::WithMIS);
if (!ls || !ls->L || ls->pdf == 0)
return;
Vector3f wi = ls->wi;
SampledSpectrum f = bsdf.f<BxDF>(wo, wi);
if (!f)
return;
SampledSpectrum T_hat = T_hatp * f * AbsDot(wi, intr.ns);
PBRT_DBG(
"depth %d T_hat %f %f %f %f f %f %f %f %f ls.L %f %f %f %f ls.pdf "
"%f\n",
depth, T_hat[0], T_hat[1], T_hat[2], T_hat[3], f[0], f[1], f[2], f[3],
ls->L[0], ls->L[1], ls->L[2], ls->L[3], ls->pdf);
Float lightPDF = ls->pdf * sampledLight->pdf;
// This causes uniPathPDF to be zero for the shadow ray, so that
// part of MIS just becomes a no-op.
Float bsdfPDF = IsDeltaLight(light.Type()) ? 0.f : bsdf.PDF<BxDF>(wo, wi);
SampledSpectrum lightPathPDF = uniPathPDF * lightPDF;
uniPathPDF *= bsdfPDF;
SampledSpectrum Ld = T_hat * ls->L;
PBRT_DBG(
"depth %d Ld %f %f %f %f "
"new T_hat %f %f %f %f T_hat/uni %f %f %f %f Ld/uni %f %f %f %f\n",
depth, Ld[0], Ld[1], Ld[2], Ld[3], T_hat[0], T_hat[1], T_hat[2],
T_hat[3], SafeDiv(T_hat, uniPathPDF)[0],
SafeDiv(T_hat, uniPathPDF)[1], SafeDiv(T_hat, uniPathPDF)[2],
SafeDiv(T_hat, uniPathPDF)[3], SafeDiv(Ld, uniPathPDF)[0],
SafeDiv(Ld, uniPathPDF)[1], SafeDiv(Ld, uniPathPDF)[2],
SafeDiv(Ld, uniPathPDF)[3]);
Ray ray = SpawnRayTo(intr.pi, intr.n, time, ls->pLight.pi, ls->pLight.n);
if (haveMedia)
// TODO: as above, always take outside here?
ray.medium = Dot(ray.d, intr.n) > 0 ? w.mediumInterface.outside
: w.mediumInterface.inside;
shadowRayQueue->Push(ray, 1 - ShadowEpsilon, lambda, Ld, uniPathPDF,
lightPathPDF, w.pixelIndex);
}
});
TraceShadowRays(depth);
}
} // namespace pbrt
| [
"matt@pharr.org"
] | matt@pharr.org |
6b980a1b018dc45ed48e599707060e3132515dea | e03bdbd2bbc724ff6d84739e36b059ede76fd126 | /ge/src/ge/Mesh.h | 675e22f477b9b09d0b003268786ac9e71538864c | [] | no_license | newhook/ne | 7f2e68e6ed454e4554b0d9f649e2dafeaa57c2eb | cffd99be10a6b37e6ba6636a07766847facea23c | refs/heads/main | 2023-04-02T21:15:54.923665 | 2021-04-13T18:54:59 | 2021-04-13T18:54:59 | 357,658,217 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,990 | h | /**
*
* Copyright (c) 2014 Matthew Newhook. All rights reserved.
*
*/
#pragma once
#include <ge/Config.h>
#include <ge/Bounds.h>
#include <vector>
#include <memory>
namespace ge {
class PrimitiveType {
public:
enum Type {
UNSET = -1,
TRIANGLES,
TRIANGLE_STRIP
};
private:
Type _val;
public:
PrimitiveType(int val) : _val(static_cast<Type>(val)) {
}
PrimitiveType(Type val) : _val(val) {
}
PrimitiveType() : _val(UNSET) {
}
operator Type() const { return _val; }
GLenum getGLType() const;
};
class Bounds;
class MeshGeom;
struct BoneWeight {
BoneWeight() {
index0 = 0;
index1 = 0;
index2 = 0;
index3 = 0;
weight0 = 0.0f;
weight1 = 0.0f;
weight2 = 0.0f;
weight3 = 0.0f;
}
short index0;
short index1;
short index2;
short index3;
float weight0;
float weight1;
float weight2;
float weight3;
};
class Mesh {
Bounds _bounds;
size_t _vertexCount;
PrimitiveType _mode;
std::shared_ptr<MeshGeom> _geometry;
public:
Mesh();
Mesh(const Mesh&);
Mesh& operator=(const Mesh&);
virtual ~Mesh();
std::shared_ptr<MeshGeom> getGeometry();
PrimitiveType getPrimitiveType() const {
return _mode;
}
void setPrimitiveType(PrimitiveType mode) {
_mode = mode;
}
void clear();
size_t getVertexCount() const;
void setVertexCount(size_t vertexCount);
// Get bounds in local space.
const Bounds& getBounds() const {
return _bounds;
}
void refreshBounds();
struct SubMesh {
SubMesh() : indexOffset(0), triangleCount(0) {}
int indexOffset;
int triangleCount;
};
std::vector<SubMesh> submeshes;
std::vector<unsigned int> triangles;
std::vector<glm::vec3> vertices;
std::vector<glm::vec3> normals;
std::vector<glm::vec4> colors;
std::vector<glm::vec2> uv;
std::vector<glm::vec2> uv2;
std::vector<BoneWeight> boneWeights;
// Indexed by geometry type.
std::vector<unsigned int> instances;
};
} | [
"matthew@customer.io"
] | matthew@customer.io |
6827ae4618d89b3d3c0e342eb5586cc53533e559 | d2d6aae454fd2042c39127e65fce4362aba67d97 | /build/iOS/Release/include/Fuse.Elements.PreplacementArgs.h | 986b283d4b16ba8d84b6ca44bf1077744cfd4ab5 | [] | no_license | Medbeji/Eventy | de88386ff9826b411b243d7719b22ff5493f18f5 | 521261bca5b00ba879e14a2992e6980b225c50d4 | refs/heads/master | 2021-01-23T00:34:16.273411 | 2017-09-24T21:16:34 | 2017-09-24T21:16:34 | 92,812,809 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 967 | h | // This file was generated based on '../../AppData/Local/Fusetools/Packages/Fuse.Elements/0.46.1/$.uno'.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Uno.EventArgs.h>
namespace g{namespace Fuse{namespace Elements{struct PreplacementArgs;}}}
namespace g{
namespace Fuse{
namespace Elements{
// public sealed class PreplacementArgs :1635
// {
uType* PreplacementArgs_typeof();
void PreplacementArgs__ctor_1_fn(PreplacementArgs* __this, bool* hasPrev);
void PreplacementArgs__get_HasPrev_fn(PreplacementArgs* __this, bool* __retval);
void PreplacementArgs__set_HasPrev_fn(PreplacementArgs* __this, bool* value);
void PreplacementArgs__New2_fn(bool* hasPrev, PreplacementArgs** __retval);
struct PreplacementArgs : ::g::Uno::EventArgs
{
bool _HasPrev;
void ctor_1(bool hasPrev);
bool HasPrev();
void HasPrev(bool value);
static PreplacementArgs* New2(bool hasPrev);
};
// }
}}} // ::g::Fuse::Elements
| [
"medbeji@MacBook-Pro-de-MedBeji.local"
] | medbeji@MacBook-Pro-de-MedBeji.local |
17918dbb53f6712c715c52a786406986ab7f80f9 | 67485a9037ff7c9cdb7a79b1f91e05d1f13b4d7b | /src/app/QVTKOpenGLInit.h | 1ea30f090dc099f3fc66ec24aaa989e04c08219d | [
"BSD-3-Clause"
] | permissive | ori-drs/director | 1242c77fd0ec88e0855838b873b8105371d587d4 | a619dbacfb31f192084403bafb235ef98315415a | refs/heads/master | 2023-03-21T23:11:18.430019 | 2023-03-10T08:28:30 | 2023-03-10T08:28:30 | 67,300,295 | 27 | 5 | BSD-3-Clause | 2023-03-09T18:30:00 | 2016-09-03T16:31:31 | Python | UTF-8 | C++ | false | false | 835 | h | #ifndef __QVTKOpenGLInit_h
#define __QVTKOpenGLInit_h
/*
* Initialization class that creates a valid QSurfaceFormat i.e. OpenGL context
* with the expected parameters for the QVTKOpenGLWidget.
* Typical use case is to construct the class before constructing a
* QApplication object in the main function.
*
* Typical usage for QVTKOpenGLInit is as follows:
* @code{.cpp}
*
* int main(int argc, char* argv[])
* {
* // Initialize before constructing the QApplication
* QVTKOpenGLInit init;
* // Construct the QApplication
* QApplication app(argc, argv);
* // Show the application (that uses QVTKOpenGLWidget)
* app.exec();
* return 0;
* }
*
* @endcode
*/
#include "ddAppConfigure.h"
class DD_APP_EXPORT QVTKOpenGLInit
{
public:
QVTKOpenGLInit();
};
#endif //__QVTKOpenGLInit_h
| [
"sankhesh.jhaveri@kitware.com"
] | sankhesh.jhaveri@kitware.com |
d77b67105f53fd56c15276a566eb7ff99a39ad54 | b6300ede7aa80b18db15b1ca52a9f6e9271a9ecf | /CSC3224Game/Frameworks/Sound.cpp | 37b3541749e35d772110fd2f80cd1c1ae7ca42ec | [] | no_license | AJagger/3224Game | 1da1e052bdafed5cb5f06ce024cc3741224eb74b | e50acb7d42be7617ff42d8a7645b86eac4e66264 | refs/heads/master | 2020-12-30T14:12:20.402056 | 2017-05-19T10:15:40 | 2017-05-19T10:15:40 | 91,285,160 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,736 | cpp | /* CSC3224 Code
* Author: Aidan Jagger | 130281034
* Class Description:
* This class is the class used to integrate WWise audio with the game engine
*
* The class is entirely commented out since I never fully got it working. I have left it in to show some of the progress and possibly to come back to in the future.
*/
#include "stdafx.h"
#include "Sound.h"
/* commented out for now
#include <cassert>
//#include "AK/AkPlatforms.h"
//#include "AK/AkWwiseSDKVersion.h"
//#include <AK/SoundEngine/Common/AkMemoryMgr.h>
//#include <AK/SoundEngine/Common/AkModule.h>
//#include <cassert>
//#include <AK/SoundEngine/Common/IAkStreamMgr.h> // Streaming Manager
//#include <AK/SoundEngine/Common/AkStreamMgrModule.h>
//#include <AK/MusicEngine/Common/AkMusicEngine.h>
//#include <AK/SoundEngine/Common/AkSoundEngine.h>
//#include <AK/SoundEngine/Common/AkTypes.h>
//#include <AK/SoundEngine/Common/AkSoundEngineExport.h>
//#include <AK/IBytes.h>
//#include <AK/SoundEngine/Platforms/Windows/AkTypes.h>
//#include <AK/SoundEngine/Platforms/Windows/AkSimd.h>
//#include <AK/SoundEngine/Platforms/Windows/AkWinSoundEngine.h>
#include "C:\\Program Files (x86)\\Audiokinetic\\Wwise 2016.2.3.6077\\SDK\\samples\\SoundEngine\\Win32\\AkFilePackageLowLevelIOBlocking.h"
#include <AK/SoundEngine/Common/AkMemoryMgr.h> // Memory Manager
#include <AK/SoundEngine/Common/AkModule.h> // Default memory and stream managers
#include <AK/SoundEngine/Common/IAkStreamMgr.h> // Streaming Manager
#include <AK/Tools/Common/AkPlatformFuncs.h> // Thread defines
#include <AK/SoundEngine/Common/AkSoundEngine.h> // Sound Engine
#include <AK/MusicEngine/Common/AkMusicEngine.h> // Music Engine
#include <AK/SoundEngine/Common/AkTypes.h>
#include <AK/SoundEngine/Common/AkSoundEngineExport.h>
*/
Sound::Sound()
{
}
Sound::~Sound()
{
}
bool Sound::InitSoundEngine()
{
/* Commented out for now
//Initialise Memory Manager
AkMemSettings memSettings;
memSettings.uMaxNumPools = 20;
if(AK::MemoryMgr::Init(&memSettings) != AK_Success)
{
assert(!"Could not create the WWise memory manager.");
return false;
}
////Initialise Streaming Manager
//AkStreamMgrSettings stmSettings;
//AK::StreamMgr::GetDefaultSettings(stmSettings);
//if (!AK::StreamMgr::Create(stmSettings))
//{
// assert(!"Could not create the WWise Streaming Manager");
// return false;
//}
////Create Streaming Device
//AkDeviceSettings deviceSettings;
//AK::StreamMgr::GetDefaultDeviceSettings(deviceSettings);
//if (g_lowLevelIO.Init(deviceSettings) != AK_Success)
//{
// assert(!"Could not create the streaming device and Low-Level I/O system");
// return false;
//}
////Create Sound Engine
//AkInitSettings initSettings;
//AkPlatformInitSettings platformInitSettings;
//AK::SoundEngine::GetDefaultInitSettings(initSettings);
//AK::SoundEngine::GetDefaultPlatformInitSettings(platformInitSettings);
//if (AK::SoundEngine::Init(&initSettings, &platformInitSettings) != AK_Success)
//{
// assert(!"Could not initialize the WWise Sound Engine.");
// return false;
//}
////Initialise Music Engine
//AkMusicSettings musicInit;
//AK::MusicEngine::GetDefaultInitSettings(musicInit);
//if (AK::MusicEngine::Init(&musicInit) != AK_Success)
//{
// assert(!"Could not initialize the WWise Music Engine.");
// return false;
//}
*/
return true;
}
void Sound::TerminateSoundEngine()
{
//AK::MusicEngine::Term();
//AK::SoundEngine::Term();
//g_lowLevelIO.Term();
//if (AK::IAkStreamMgr::Get())
//{
// AK::IAkStreamMgr::Get()->Destroy();
//}
//AK::MemoryMgr::Term();
}
void Sound::ProcessAudio()
{
//AK::SoundEngine::RenderAudio();
}
| [
"aidan.m.jagger@gmail.com"
] | aidan.m.jagger@gmail.com |
d48cf209fed29a39b9653010e6070ce122aa9f2a | 894f94b68bd6abceadaf7806f7da97d4e4e1cf71 | /tests/Unit/Domain/Test_EmbeddingMaps.cpp | 877d2e23fbc2f8b3bbfa28ff4fd066454a145009 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | wthrowe/spectre | 9786293d72b9901eb37a927ada6e475a45d206e1 | 0ddd6405eef1e57de1d0a765aa4f6cfbc83c9f15 | refs/heads/develop | 2023-08-24T16:26:00.521593 | 2017-06-30T23:41:30 | 2017-06-30T23:41:30 | 96,371,688 | 1 | 0 | null | 2017-07-06T00:23:14 | 2017-07-06T00:23:14 | null | UTF-8 | C++ | false | false | 865 | cpp | // Distributed under the MIT License.
// See LICENSE.txt for details.
#include <catch.hpp>
#include <random>
#include "DataStructures/Tensor/Tensor.hpp"
#include "Domain/EmbeddingMaps/Identity.hpp"
#include "Utilities/ConstantExpressions.hpp"
#include "tests/Unit/TestHelpers.hpp"
template <size_t Dim>
void test_identity() {
EmbeddingMaps::Identity<Dim> identity_map;
Point<Dim, Frame::Logical> xi(1.0);
Point<Dim, Frame::Grid> x(1.0);
CHECK(identity_map(xi) == x);
CHECK(identity_map.inverse(x) == xi);
for (size_t i = 0; i < Dim; ++i) {
for (size_t j = 0; j < Dim; ++j) {
CHECK(identity_map.inv_jacobian(xi, i, j) == (i == j ? 1.0 : 0.0));
CHECK(identity_map.jacobian(xi, i, j) == (i == j ? 1.0 : 0.0));
}
}
}
TEST_CASE("Unit.Domain.EmbeddingMaps.Identity", "[Domain][Unit]") {
test_identity<1>();
test_identity<2>();
}
| [
"edo27@cornell.edu"
] | edo27@cornell.edu |
aafc3a6c2fe1f197667233e2280e0edc5e8c874f | 971269d7280ec718888f21ab187a8980df2ebddd | /Matematyka/Programowanie/hello4.cpp | 683199a03ff504fb3e1e332356bc402c99fd4463 | [] | no_license | rekuszk/Duperele | 5fb0b21e5d8fb1de11f7b3b817688cba05bd8b2f | 97d3f0f97940f384a8555082d91355cb1596c4cc | refs/heads/master | 2023-09-01T12:54:03.159711 | 2021-11-04T11:01:51 | 2021-11-04T11:01:51 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,698 | cpp | // Zad 21
//#include <iostream>
//#include <cmath>
//
//using std::cout;
//using std::cin;
//using std::string;
//
//bool isPrime(int n) {
// if (n <= 1) return false;
// if (n == 2) return true;
// for (int i = 2; i < (int)sqrt(n); i++) {
// if (n%i == 0) return false;
// }
// return true;
//}
//
//int main() {
// int n;
// cout << "Podaj liczbę: "; cin >> n;
// cout << "Ta liczba " << ((isPrime(n))?"jest":"nie jest") << " pierwsza.\n";
// return 0;
//}
// Zad 22
//#include <iostream>
//
//using std::cout;
//using std::cin;
//
//int abs(int x) {
// return ((x >= 0) ? x : -x);
//}
//
//int fact(int n) {
// if (n == 0) return 1;
// return n * fact(n-1);
//}
//
//int newton1(int n, int k) {
// if (k == 0) return 1;
// if (k == n) return 1;
// return newton1(n-1, k-1) + newton1(n-1, k);
//}
//
//int newton2(int n, int k) {
// if (k == 0) return 1;
// if (k == n) return 1;
// int up = 1, dn = 1;
// for (int i = 0; i <= k-1; i++) {
// up *= (n - i);
// }
// return up/fact(k);
//}
//
//int main() {
// int n, k;
// cout << "SYMBOL NEWTONA!!! (n k)\n";
// cout << " n = "; cin >> n; n = abs(n);
// cout << " k = "; cin >> k; k = abs(k);
// cout << " (n k) = " << newton1(n, k) << "\n";
// cout << " (n k) = " << newton2(n, k) << "\n";
// return 0;
//}
// Zad 23
//#include <iostream>
//
//using std::cout;
//using std::cin;
//
//double f(int n) {
// return (n*1.0)/(n+1);
//}
//
//double S(int n) {
// double s = 0.0;
// for (int i = 1; i <= n; i++) s += f(i);
// return s;
//}
//
//int main() {
// int n;
// cout << "Podaj liczbę: "; cin >> n;
// cout << "Wynik: " << S(n) << "\n";
// return 0;
//}
// Zad 24
//#include <iostream>
//#include <cstdlib>
//#include <ctime>
//
//using std::cout;
//using std::cin;
//
//int main() {
// srand(time(NULL));
// int s;
// int nold, nnew;
// cout << "METODA do-while:\n";
// s = 0;
// nold = -1;
// nnew = rand()%21;
// cout << nnew << "\t";
// s += nnew;
// do {
// nold = nnew;
// nnew = rand()%21;
// cout << nnew << "\t";
// s += nnew;
// } while (nold != nnew);
// cout << "\n" << s << "\n";
//
// cout << "METODA while:\n";
// s = 0;
// nold = -1;
// while (nold != nnew) {
// nold = nnew;
// nnew = rand()%21;
// cout << nnew << "\t";
// s += nnew;
// }
// cout << "\n" << s << "\n";
//
// return 0;
//}
// Zad 25
//#include <iostream>
//
//using std::cin;
//using std::cout;
//
//
//double power(int a, int n) {
// double s = 1;
// if (n < 0) {
// for (int i = 1; i <= -n; i++) s /= a;
// } else if (n > 0) {
// for (int i = 1; i <= n; i++) s *= a;
// }
// return s;
//}
//
//int main() {
// int a, n;
// cout << "POTĘGA!!! (a^n)\n";
// cout << " a = "; cin >> a;
// cout << " n = "; cin >> n;
// cout << " a^n = " << power(a,n) << "\n";
// return 0;
//}
// Zad 26
//#include <iostream>
//
//using std::cin;
//using std::cout;
//
//int abs(int x) {
// return ((x >= 0) ? x : -x);
//}
//
//int gcd(int a, int b) {
// while (a != b) {
// if (a > b) a -= b;
// else b -= a;
// }
// return a;
//}
//
//int main() {
// int a, b;
// cout << "ALGORYTM EUKLIDESA - NWD(a, b)\n";
// cout << " a = "; cin >> a; a = abs(a);
// cout << " b = "; cin >> b; b = abs(b);
// cout << " NWD(a, b) = " << gcd(a,b) << "\n";
// return 0;
//}
// Zad 27
//#include <iostream>
//
//using std::cin;
//using std::cout;
//
//int abs(int x) {
// return ((x >= 0) ? x : -x);
//}
//
//int gcd(int a, int b) {
// while (a != b) {
// if (a > b) a -= b;
// else b -= a;
// }
// return a;
//}
//
//int lcm(int a, int b) {
// return (a*b)/(gcd(a, b));
//}
//
//int main() {
// int a, b;
// cout << " a = "; cin >> a; a = abs(a);
// cout << " b = "; cin >> b; b = abs(b);
// cout << " NWD(a, b) = " << lcm(a,b) << "\n";
// return 0;
//}
// Zad 28
#include <iostream>
#include <cmath>
using std::cin;
using std::cout;
int abs(int x) {
return ((x >= 0) ? x : -x);
}
bool isPerfect(int n) {
int suma = 0;
for (int p = sqrt(n); p > 1; p--) {
if (n % p == 0) {
suma += p;
int p1 = n/p;
if (p1 != p) {
suma += p1;
}
}
}
if (suma+1 == n) return true;
return false;
}
int main() {
int n;
cout << "Podaj liczbę: "; cin >> n; n = ((n>0)?n:0);
cout << "Ta liczba " << ((isPerfect(n))?"jest":"nie jest") << " doskonała.\n";
return 0;
}
| [
"redthreat19@gmail.com"
] | redthreat19@gmail.com |
02c2efb315c208630435760539063bd576321aa4 | 1b90be9561c10508eea59cb36c1f1665d0ef947f | /stan/math/opencl/prim/qr_thin_R.hpp | 600deb2c0ae1e3b1c4dceeeff5c19a44aa97e4e7 | [
"BSD-3-Clause",
"GPL-2.0-only",
"Apache-2.0"
] | permissive | stan-dev/math | 473e7c1eaf11f84eaf2032c2455e12ba65feef39 | bdf281f4e7f8034f47974d14dea7f09e600ac02a | refs/heads/develop | 2023-08-31T09:02:59.224115 | 2023-08-29T15:17:01 | 2023-08-29T15:17:01 | 38,388,440 | 732 | 240 | BSD-3-Clause | 2023-09-14T19:44:20 | 2015-07-01T18:40:54 | C++ | UTF-8 | C++ | false | false | 988 | hpp | #ifndef STAN_MATH_OPENCL_PRIM_QR_THIN_R_HPP
#define STAN_MATH_OPENCL_PRIM_QR_THIN_R_HPP
#ifdef STAN_OPENCL
#include <stan/math/opencl/qr_decomposition.hpp>
#include <stan/math/prim/meta.hpp>
#include <stan/math/prim/err.hpp>
namespace stan {
namespace math {
/**
* Returns the orthogonal factor of the thin QR decomposition
*
* @tparam T_m type of the matrix
* @param m Matrix.
* @return Orthogonal matrix with maximal columns
*/
template <typename T_m,
require_all_kernel_expressions_and_none_scalar_t<T_m>* = nullptr>
inline matrix_cl<double> qr_thin_R(T_m&& m) {
check_nonzero_size("qr_thin_R(OpenCL)", "m", m);
matrix_cl<double> mat_eval = std::forward<T_m>(m);
matrix_cl<double> Q, R;
qr_decomposition_cl(m, Q, R);
auto R_block
= block_zero_based(R, 0, 0, std::min(m.rows(), m.cols()), m.cols());
R = select(rowwise_broadcast(diagonal(R) < 0.0), -R_block, R_block).eval();
return R;
}
} // namespace math
} // namespace stan
#endif
#endif
| [
"tadej.c@gmail.com"
] | tadej.c@gmail.com |
a9d248dbefb6ee22647010af8338715840490d58 | d0be9a869d4631c58d09ad538b0908554d204e1c | /utf8/lib/client/kernelengine/include/CGAL3.2.1/include/CGAL/partition_y_monotone_2.h | 3330082e74422828ccc68997413ff8196e1bf761 | [] | no_license | World3D/pap | 19ec5610393e429995f9e9b9eb8628fa597be80b | de797075062ba53037c1f68cd80ee6ab3ed55cbe | refs/heads/master | 2021-05-27T08:53:38.964500 | 2014-07-24T08:10:40 | 2014-07-24T08:10:40 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,834 | h | // Copyright (c) 2000 Max-Planck-Institute Saarbruecken (Germany).
// All rights reserved.
//
// This file is part of CGAL (www.cgal.org); you may redistribute it under
// the terms of the Q Public License version 1.0.
// See the file LICENSE.QPL distributed with CGAL.
//
// Licensees holding a valid commercial license may use this file in
// accordance with the commercial license agreement provided with the software.
//
// This file is provided AS IS with NO WARRANTY OF ANY KIND, INCLUDING THE
// WARRANTY OF DESIGN, MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
//
// $URL: svn+ssh://scm.gforge.inria.fr/svn/cgal/branches/CGAL-3.2-branch/Partition_2/include/CGAL/partition_y_monotone_2.h $
// $Id: partition_y_monotone_2.h 28567 2006-02-16 14:30:13Z lsaboret $
//
//
// Author(s) : Susan Hert <hert@mpi-sb.mpg.de>
//
// Implementaion of the algorithm from pp 49--55 of "Computational Geometry
// Algorithms and Applications" by de Berg, van Kreveld, Overmars, and
// Schwarzkopf for producing a partitioning of a polygon into y-monotone
// pieces.
//
// NOTE: e_i = (v_i, v_{i+1})
//
// TREE:
// "Therefore we store the edges of P intersecting the sweep line in the
// leaves of a dynamic binary search tree T. The left-to-right order of
// the leaves of T corresponds to the left-to-right order of the edges.
// Because we are only interested in edges to the left of split and merge
// vertices we only need to store edges in T that have the interior of P
// to their right. With each edge in T we store its helper."
//
//
#ifndef CGAL_PARTITION_Y_MONOTONE_H
#define CGAL_PARTITION_Y_MONOTONE_H
#include <CGAL/Indirect_not_less_yx_2.h>
#include <CGAL/Indirect_edge_compare.h>
#include <CGAL/Segment_2_Ray_2_intersection.h>
#include <CGAL/Object.h>
#include <CGAL/Partitioned_polygon_2.h>
#include <CGAL/ch_selected_extreme_points_2.h>
#include <CGAL/IO/Tee_for_output_iterator.h>
#include <CGAL/partition_assertions.h>
#include <CGAL/partition_is_valid_2.h>
#include <CGAL/Partition_traits_2.h>
#include <map>
namespace CGAL {
enum Partition_y_mono_vertex_type {PARTITION_Y_MONO_START_VERTEX,
PARTITION_Y_MONO_SPLIT_VERTEX,
PARTITION_Y_MONO_REGULAR_VERTEX,
PARTITION_Y_MONO_COLLINEAR_VERTEX,
PARTITION_Y_MONO_MERGE_VERTEX,
PARTITION_Y_MONO_END_VERTEX};
//
// assumes CCW orientation of vertices
//
template <class BidirectionalCirculator, class Traits>
Partition_y_mono_vertex_type partition_y_mono_vertex_type(
BidirectionalCirculator c,
const Traits& traits)
{
BidirectionalCirculator previous = c;
previous--;
BidirectionalCirculator next = c;
next++;
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono__vertex_type: previous " << *previous
<< " c " << *c << " next " << *next << std::endl;
#endif
typename Traits::Compare_y_2 compare_y_2 = traits.compare_y_2_object();
if (compare_y_2(*previous, *c) == EQUAL &&
compare_y_2(*next, *c) == EQUAL)
return PARTITION_Y_MONO_COLLINEAR_VERTEX;
typename Traits::Less_yx_2 less_yx = traits.less_yx_2_object();
typename Traits::Left_turn_2 left_turn = traits.left_turn_2_object();
if (less_yx(*previous, *c))
{
if (less_yx(*next, *c)) // previous and next both less_yx
if (left_turn(*previous, *c, *next)) // interior angle less than pi
return PARTITION_Y_MONO_START_VERTEX;
else // interior angle greater than pi
return PARTITION_Y_MONO_SPLIT_VERTEX;
else // previous less_yx and next not
return PARTITION_Y_MONO_REGULAR_VERTEX;
}
else
{
if (less_yx(*c, *next)) // previous and next both not less_yx
if (left_turn(*previous, *c, *next)) // interior angle less than pi
return PARTITION_Y_MONO_END_VERTEX;
else // interior angle greater than pi
return PARTITION_Y_MONO_MERGE_VERTEX;
else // next less_yx and previous not
return PARTITION_Y_MONO_REGULAR_VERTEX;
}
}
template <class Tree>
void partition_y_mono_print_tree(Tree tree)
{
typedef typename Tree::iterator iterator;
iterator it = tree.begin();
for (; it != tree.end(); it++) {
std::cout << "edge node " << *(*it).first << " helper " << *(*it).second
<< std::endl;
}
std::cout << std::endl;
}
template <class BidirectionalCirculator, class Tree>
void partition_y_mono_handle_start_vertex(BidirectionalCirculator c,
Tree& tree)
{
typedef typename Tree::value_type ValuePair;
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *c << " is a start vertex " << std::endl;
#endif
tree.insert(ValuePair(c, c));
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_handle_start_vertex: after insert tree is "
<< std::endl;
partition_y_mono_print_tree(tree);
#endif
// insert e_i (edge from *c to *++c) into "tree" with helper(e_i) = v_i
}
template <class BidirectionalCirculator, class Tree,
class Partition_Poly, class Traits>
void partition_y_mono_handle_end_vertex(BidirectionalCirculator c, Tree& tree,
Partition_Poly& partition_poly,
const Traits& traits )
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *c << " is an end vertex " << std::endl;
#endif
typedef typename Tree::iterator tree_iterator;
tree_iterator it;
BidirectionalCirculator previous = c;
previous--;
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_end_vertex: previous " << *previous
<< std::endl;
#endif
it = tree.find(previous);
CGAL_assertion (it != tree.end());
if (partition_y_mono_vertex_type((*it).second, traits) ==
PARTITION_Y_MONO_MERGE_VERTEX)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_end_vertex: diagonal "
<< *(*it).second << " to " << *c << std::endl;
#endif
partition_poly.insert_diagonal(c, (*it).second);
}
tree.erase(it);
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_end_vertex: after erase tree is "
<< std::endl;
partition_y_mono_print_tree(tree);
#endif
// if helper(e_{i-1}) is a merge vertex
// insert diagonal connecting v_i to helper(e_{i-1})
// delete e_{i-1} from tree
}
template<class BidirectionalCirculator, class Iterator, class Tree>
inline
void partition_y_mono_edge_directly_left(BidirectionalCirculator c, Tree& tree,
Iterator& it)
{
it = tree.lower_bound(c); // edge directly to the left of v_i since the
// items in the tree are sorted from right to
// left
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
if (it != tree.end())
std::cout << "partition_y_mono_edge_directly_left: lower_bound edge node: "
<< *((*it).first) << " helper " << *((*it).second) << std::endl;
#endif
}
template <class BidirectionalCirculator, class Tree, class Partition_Poly>
void partition_y_mono_handle_split_vertex(BidirectionalCirculator c,
Tree& tree,
Partition_Poly& partition_poly)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *c << " is a split vertex " << std::endl;
#endif
typedef typename Tree::iterator tree_iterator;
typedef typename Tree::value_type ValuePair;
tree_iterator it;
partition_y_mono_edge_directly_left(c, tree, it);
if (it != tree.end())
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_split_vertex: diagonal "
<< *(*it).second << " to " << *c << std::endl;
#endif
partition_poly.insert_diagonal(c, (*it).second);
BidirectionalCirculator ej = (*it).first;
tree.erase(it);
tree.insert(ValuePair(ej, c));
}
tree.insert(ValuePair(c, c));
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_split_vertex: "
<< "after erase and inserts tree is" << std::endl;
partition_y_mono_print_tree(tree);
#endif
// 1. find the edge e_j in tree directly to the left of v_i
// 2. insert the diagonal connecting v_i to helper(e_j)
// 3. helper(e_j) = v_i
// 4. Insert e_i in tree and set helper(e_i) to v_i
}
template <class BidirectionalCirculator, class Tree,
class Partition_Poly, class Traits>
void partition_y_mono_handle_merge_vertex(BidirectionalCirculator c,
Tree& tree,
Partition_Poly& partition_poly,
const Traits& traits)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *c << " is a merge vertex " << std::endl;
#endif
typedef typename Tree::iterator tree_iterator;
typedef typename Tree::value_type ValuePair;
BidirectionalCirculator prev = c;
prev--;
tree_iterator it = tree.find(prev);
CGAL_assertion (it != tree.end());
if (partition_y_mono_vertex_type((*it).second,traits) ==
PARTITION_Y_MONO_MERGE_VERTEX)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_merge_vertex 1: diagonal "
<< *(*it).second << " to " << *c << std::endl;
#endif
partition_poly.insert_diagonal(c, (*it).second);
}
tree.erase(it);
partition_y_mono_edge_directly_left(c, tree, it);
if (it != tree.end())
{
if (partition_y_mono_vertex_type((*it).second,traits) ==
PARTITION_Y_MONO_MERGE_VERTEX)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_merge_vertex 2: diagonal "
<< *(*it).second << " to " << *c << std::endl;
#endif
partition_poly.insert_diagonal(c, (*it).second);
}
BidirectionalCirculator ej = (*it).first;
tree.erase(it);
tree.insert(ValuePair(ej,c));
}
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_merge_vertex: after erase(s) tree is "
<< std::endl;
partition_y_mono_print_tree(tree);
#endif
// 1. if helper(e_{i-1}) is a merge vertex
// insert the diagonal connecting v_i to helper(e_{i-1})
// 2. delete e_{i-1} from tree
// 3. find the edge e_j in tree directly to the left of v_i
// 4. if helper(e_j) is a merge vertex
// insert diagonal connecting v_i to helper(e_j) in polygon
// 5. helper(e_j) = v_i
}
template <class BidirectionalCirculator, class Traits>
bool partition_y_mono_interior_to_right(BidirectionalCirculator c,
const Traits& traits)
{
typename Traits::Compare_y_2 compare_y_2 = traits.compare_y_2_object();
BidirectionalCirculator previous = c; previous--;
Comparison_result cmp_y = compare_y_2(*previous, *c);
if (cmp_y == LARGER) return true;
BidirectionalCirculator next = c; next++;
if (cmp_y == EQUAL && compare_y_2(*next, *c) == SMALLER) return true;
return false;
}
template <class BidirectionalCirculator, class Tree, class Partition_Poly,
class Traits>
void partition_y_mono_handle_regular_vertex(BidirectionalCirculator c,
Tree& tree,
Partition_Poly& partition_poly,
const Traits& traits )
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *c << " is a regular vertex " << std::endl;
#endif
typedef typename Tree::iterator tree_iterator;
typedef typename Tree::value_type ValuePair;
tree_iterator it;
BidirectionalCirculator previous = c;
previous--;
if (partition_y_mono_interior_to_right(c, traits))
{
it = tree.find(previous);
CGAL_assertion( it != tree.end() );
if (partition_y_mono_vertex_type((*it).second, traits) ==
PARTITION_Y_MONO_MERGE_VERTEX)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_regular_vertex 1: diagonal "
<< *(*it).second << " to " << *c << std::endl;
#endif
partition_poly.insert_diagonal(c, (*it).second);
}
tree.erase(it);
tree.insert(ValuePair(c,c));
}
else
{
partition_y_mono_edge_directly_left(c, tree, it);
CGAL_assertion (it != tree.end());
if (partition_y_mono_vertex_type((*it).second, traits) ==
PARTITION_Y_MONO_MERGE_VERTEX)
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_regular_vertex 2: diagonal "
<< *c << " to " << *(*it).second << std::endl;
#endif
partition_poly.insert_diagonal(c, (*it).second);
}
BidirectionalCirculator ej = (*it).first;
tree.erase(it);
tree.insert(ValuePair(ej,c));
}
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_regular_vertex: "
<< "after erase and insert tree is" << std::endl;
partition_y_mono_print_tree(tree);
#endif
// if interior of polygon lies to the right of v_i
// if helper(e_{i-1}) is a merge vertex
// insert diagonal connecting v_i to helper(e_{i-1}) in polygon
// delete e_{i-1} from tree
// insert e_i in tree and set helper(e_i) to v_i
// else
// find the edge e_j in tree directly left of v_i
// if helper(e_j) is a merge vertex
// insert diagonal connecting v_i to helper(e_j) in D
// helper(e_j) = v_i
}
template <class BidirectionalCirculator, class Tree>
void partition_y_mono_handle_collinear_vertex(BidirectionalCirculator c,
Tree& tree)
{
typedef typename Tree::iterator tree_iterator;
typedef typename Tree::value_type ValuePair;
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *c << " is a collinear vertex " << std::endl;
#endif
tree_iterator it;
BidirectionalCirculator previous = c;
previous--;
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << *previous << " is the previous vertex " << std::endl;
#endif
it = tree.find(previous);
if ( it != tree.end() )
{
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "partition_y_mono_handle_collinear_vertex : removing "
<< *(*it).first << std::endl;
#endif
tree.erase(it);
}
tree.insert(ValuePair(c,c));
}
template <class InputIterator, class OutputIterator, class Traits>
OutputIterator partition_y_monotone_2(InputIterator first,
InputIterator beyond,
OutputIterator result,
const Traits& traits)
{
if (first == beyond) return result;
typedef Partitioned_polygon_2< Traits > P_Polygon_2;
typedef typename P_Polygon_2::iterator I;
typedef Circulator_from_iterator<I> Circulator;
#if defined(CGAL_PARTITION_NO_POSTCONDITIONS) || \
defined(CGAL_NO_POSTCONDITIONS) || defined(NDEBUG)
OutputIterator res(result);
#else
typedef typename Traits::Polygon_2 Polygon_2;
Tee_for_output_iterator<OutputIterator, Polygon_2> res(result);
#endif // no postcondition
P_Polygon_2 polygon(first, beyond);
CGAL_partition_precondition(
orientation_2(polygon.begin(), polygon.end(), traits) == COUNTERCLOCKWISE);
Circulator circ(polygon.begin(), polygon.end()), done = circ;
std::vector<Circulator> circulators;
CGAL_For_all(circ, done){
circulators.push_back(circ);
}
std::sort(circulators.begin(), circulators.end(), Indirect_not_less_yx_2<Traits>(traits));
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
std::cout << "Initial vertex list: "<< circulators << std::endl;
for(std::vector<Circulator>::const_iterator it = circulators.begin();
it != circulators.end();
it++){
std::cout << **it << " " ;
}
std::cout << std::endl;
#endif
typedef std::map<Circulator, Circulator,
Indirect_edge_compare<Circulator, Traits> > Tree;
Tree tree;
typename std::vector<Circulator>::iterator it = circulators.begin();
for (; it != circulators.end(); it++) {
switch (partition_y_mono_vertex_type(*it, traits))
{
case PARTITION_Y_MONO_START_VERTEX:
partition_y_mono_handle_start_vertex(*it, tree);
break;
case PARTITION_Y_MONO_SPLIT_VERTEX:
partition_y_mono_handle_split_vertex(*it, tree, polygon);
break;
case PARTITION_Y_MONO_END_VERTEX:
partition_y_mono_handle_end_vertex(*it, tree, polygon, traits);
break;
case PARTITION_Y_MONO_MERGE_VERTEX:
partition_y_mono_handle_merge_vertex(*it, tree, polygon, traits);
break;
case PARTITION_Y_MONO_REGULAR_VERTEX:
partition_y_mono_handle_regular_vertex(*it, tree, polygon, traits);
break;
case PARTITION_Y_MONO_COLLINEAR_VERTEX:
partition_y_mono_handle_collinear_vertex(*it, tree);
break;
}
}
#ifdef CGAL_PARTITION_Y_MONOTONE_DEBUG
I v_it;
for (v_it = polygon.begin(); v_it != polygon.end(); v_it++)
{
(*v_it).print_diagonals();
}
#endif
polygon.partition(res, 0);
CGAL_partition_postcondition(
y_monotone_partition_is_valid_2(polygon.begin(), polygon.end(),
res.output_so_far_begin(),
res.output_so_far_end(), traits));
#if defined(CGAL_PARTITION_NO_POSTCONDITIONS) || \
defined(CGAL_NO_POSTCONDITIONS) || defined(NDEBUG)
return res;
#else
return res.to_output_iterator();
#endif // no postconditions
}
template <class InputIterator, class OutputIterator>
inline
OutputIterator partition_y_monotone_2(InputIterator first,
InputIterator beyond,
OutputIterator result)
{
typedef typename std::iterator_traits<InputIterator>::value_type Point_2;
typedef typename Kernel_traits<Point_2>::Kernel K;
return partition_y_monotone_2(first, beyond, result,
Partition_traits_2<K>());
}
}
#endif // CGAL_PARTITION_Y_MONOTONE_H
| [
"viticm@126.com"
] | viticm@126.com |
138a0292012e6f682effd4deefc7b13af4a8f73f | c7e26dc37573e8766e472990ab09ae046f49b3ef | /third_party/gvisor_syscall_tests/gvisor/test/syscalls/linux/socket_inet_loopback.cc | 0ba88735feac69f4284df0072a1438602747ed94 | [
"BSD-2-Clause",
"MIT",
"Apache-2.0",
"LicenseRef-scancode-unknown-license-reference"
] | permissive | lambdaxymox/fuchsia | 03b72b387cbe14360868c98875ed0ed2d2bd8bf5 | 27dc297f40159d6fbd1368830b894d1299710cb5 | refs/heads/master | 2022-11-15T02:50:25.363189 | 2022-10-19T16:49:21 | 2022-10-19T16:49:21 | 296,795,562 | 1 | 2 | BSD-2-Clause | 2022-10-19T07:11:19 | 2020-09-19T05:47:00 | C++ | UTF-8 | C++ | false | false | 100,958 | cc | // Copyright 2018 The gVisor Authors.
//
// 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 <arpa/inet.h>
#include <netinet/in.h>
#include <netinet/tcp.h>
#include <poll.h>
#include <string.h>
#include <sys/socket.h>
#include <atomic>
#include <iostream>
#include <memory>
#include <string>
#include <tuple>
#include <utility>
#include <vector>
#include "gmock/gmock.h"
#include "gtest/gtest.h"
#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/time/clock.h"
#include "absl/time/time.h"
#include "test/syscalls/linux/ip_socket_test_util.h"
#include "test/syscalls/linux/socket_inet_loopback_test_params.h"
#include "test/util/file_descriptor.h"
#include "test/util/posix_error.h"
#include "test/util/save_util.h"
#include "test/util/socket_util.h"
#include "test/util/test_util.h"
#include "test/util/thread_util.h"
namespace gvisor {
namespace testing {
namespace {
using ::testing::Gt;
using SocketInetLoopbackTest = ::testing::TestWithParam<SocketInetTestParam>;
TEST(BadSocketPairArgs, ValidateErrForBadCallsToSocketPair) {
int fd[2] = {};
// Valid AF but invalid for socketpair(2) return ESOCKTNOSUPPORT.
ASSERT_THAT(socketpair(AF_INET, 0, 0, fd),
SyscallFailsWithErrno(ESOCKTNOSUPPORT));
ASSERT_THAT(socketpair(AF_INET6, 0, 0, fd),
SyscallFailsWithErrno(ESOCKTNOSUPPORT));
// Invalid AF will fail.
ASSERT_THAT(socketpair(AF_MAX, 0, 0, fd), SyscallFails());
ASSERT_THAT(socketpair(8675309, 0, 0, fd), SyscallFails());
}
enum class Operation {
Bind,
Connect,
SendTo,
};
std::string OperationToString(Operation operation) {
switch (operation) {
case Operation::Bind:
return "Bind";
case Operation::Connect:
return "Connect";
// Operation::SendTo is the default.
default:
return "SendTo";
}
}
using OperationSequence = std::vector<Operation>;
using DualStackSocketTest =
::testing::TestWithParam<std::tuple<TestAddress, OperationSequence>>;
TEST_P(DualStackSocketTest, AddressOperations) {
const FileDescriptor fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(AF_INET6, SOCK_DGRAM, 0));
const TestAddress& addr = std::get<0>(GetParam());
const OperationSequence& operations = std::get<1>(GetParam());
auto addr_in = reinterpret_cast<const sockaddr*>(&addr.addr);
// sockets may only be bound once. Both `connect` and `sendto` cause a socket
// to be bound.
bool bound = false;
for (const Operation& operation : operations) {
bool sockname = false;
bool peername = false;
switch (operation) {
case Operation::Bind: {
ASSERT_NO_ERRNO(SetAddrPort(
addr.family(), const_cast<sockaddr_storage*>(&addr.addr), 0));
int bind_ret = bind(fd.get(), addr_in, addr.addr_len);
// Dual stack sockets may only be bound to AF_INET6.
if (!bound && addr.family() == AF_INET6) {
EXPECT_THAT(bind_ret, SyscallSucceeds());
bound = true;
sockname = true;
} else {
EXPECT_THAT(bind_ret, SyscallFailsWithErrno(EINVAL));
}
break;
}
case Operation::Connect: {
ASSERT_NO_ERRNO(SetAddrPort(
addr.family(), const_cast<sockaddr_storage*>(&addr.addr), 1337));
EXPECT_THAT(RetryEINTR(connect)(fd.get(), addr_in, addr.addr_len),
SyscallSucceeds())
<< GetAddrStr(addr_in);
bound = true;
sockname = true;
peername = true;
break;
}
case Operation::SendTo: {
const char payload[] = "hello";
ASSERT_NO_ERRNO(SetAddrPort(
addr.family(), const_cast<sockaddr_storage*>(&addr.addr), 1337));
ssize_t sendto_ret = sendto(fd.get(), &payload, sizeof(payload), 0,
addr_in, addr.addr_len);
EXPECT_THAT(sendto_ret, SyscallSucceedsWithValue(sizeof(payload)));
sockname = !bound;
bound = true;
break;
}
}
if (sockname) {
sockaddr_storage sock_addr;
socklen_t addrlen = sizeof(sock_addr);
ASSERT_THAT(getsockname(fd.get(), AsSockAddr(&sock_addr), &addrlen),
SyscallSucceeds());
ASSERT_EQ(addrlen, sizeof(struct sockaddr_in6));
auto sock_addr_in6 = reinterpret_cast<const sockaddr_in6*>(&sock_addr);
if (operation == Operation::SendTo) {
EXPECT_EQ(sock_addr_in6->sin6_family, AF_INET6);
EXPECT_TRUE(IN6_IS_ADDR_UNSPECIFIED(sock_addr_in6->sin6_addr.s6_addr32))
<< OperationToString(operation)
<< " getsocknam=" << GetAddrStr(AsSockAddr(&sock_addr));
EXPECT_NE(sock_addr_in6->sin6_port, 0);
} else if (IN6_IS_ADDR_V4MAPPED(
reinterpret_cast<const sockaddr_in6*>(addr_in)
->sin6_addr.s6_addr32)) {
EXPECT_TRUE(IN6_IS_ADDR_V4MAPPED(sock_addr_in6->sin6_addr.s6_addr32))
<< OperationToString(operation)
<< " getsocknam=" << GetAddrStr(AsSockAddr(&sock_addr));
}
}
if (peername) {
sockaddr_storage peer_addr;
socklen_t addrlen = sizeof(peer_addr);
ASSERT_THAT(getpeername(fd.get(), AsSockAddr(&peer_addr), &addrlen),
SyscallSucceeds());
ASSERT_EQ(addrlen, sizeof(struct sockaddr_in6));
if (addr.family() == AF_INET ||
IN6_IS_ADDR_V4MAPPED(reinterpret_cast<const sockaddr_in6*>(addr_in)
->sin6_addr.s6_addr32)) {
EXPECT_TRUE(IN6_IS_ADDR_V4MAPPED(
reinterpret_cast<const sockaddr_in6*>(&peer_addr)
->sin6_addr.s6_addr32))
<< OperationToString(operation)
<< " getpeername=" << GetAddrStr(AsSockAddr(&peer_addr));
}
}
}
}
// TODO(gvisor.dev/issue/1556): uncomment V4MappedAny.
INSTANTIATE_TEST_SUITE_P(
All, DualStackSocketTest,
::testing::Combine(
::testing::Values(V4Any(), V4Loopback(), /*V4MappedAny(),*/
V4MappedLoopback(), V6Any(), V6Loopback()),
::testing::ValuesIn<OperationSequence>(
{{Operation::Bind, Operation::Connect, Operation::SendTo},
{Operation::Bind, Operation::SendTo, Operation::Connect},
{Operation::Connect, Operation::Bind, Operation::SendTo},
{Operation::Connect, Operation::SendTo, Operation::Bind},
{Operation::SendTo, Operation::Bind, Operation::Connect},
{Operation::SendTo, Operation::Connect, Operation::Bind}})),
[](::testing::TestParamInfo<
std::tuple<TestAddress, OperationSequence>> const& info) {
const TestAddress& addr = std::get<0>(info.param);
const OperationSequence& operations = std::get<1>(info.param);
std::string s = addr.description;
for (const Operation& operation : operations) {
absl::StrAppend(&s, OperationToString(operation));
}
return s;
});
void tcpSimpleConnectTest(TestAddress const& listener,
TestAddress const& connector, bool unbound) {
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
if (!unbound) {
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
}
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Connect to the listening socket.
const FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
// Accept the connection.
//
// We have to assign a name to the accepted socket, as unamed temporary
// objects are destructed upon full evaluation of the expression it is in,
// potentially causing the connecting socket to fail to shutdown properly.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RDWR), SyscallSucceeds());
ASSERT_THAT(shutdown(conn_fd.get(), SHUT_RDWR), SyscallSucceeds());
}
TEST_P(SocketInetLoopbackTest, TCP) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
tcpSimpleConnectTest(listener, connector, true);
}
TEST_P(SocketInetLoopbackTest, TCPListenUnbound) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
tcpSimpleConnectTest(listener, connector, false);
}
TEST_P(SocketInetLoopbackTest, TCPListenShutdownListen) {
SocketInetTestParam const& param = GetParam();
const TestAddress& listener = param.listener;
const TestAddress& connector = param.connector;
constexpr int kBacklog = 5;
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RD), SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
const uint16_t port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
// TODO(b/153489135): Remove Disable save after bug is fixed. S/R test can
// fail because the last socket may not be delivered to the accept queue
// by the time connect returns.
DisableSave ds;
for (int i = 0; i < kBacklog; i++) {
auto client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
ASSERT_THAT(RetryEINTR(connect)(client.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
}
for (int i = 0; i < kBacklog; i++) {
ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());
}
}
TEST_P(SocketInetLoopbackTest, TCPListenShutdown) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
constexpr int kBacklog = 2;
// See the comment in TCPBacklog for why this isn't kBacklog + 1.
constexpr int kFDs = kBacklog;
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
// Shutdown the write of the listener, expect to not have any effect.
ASSERT_THAT(shutdown(listen_fd.get(), SHUT_WR), SyscallSucceeds());
for (int i = 0; i < kFDs; i++) {
auto client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
ASSERT_THAT(RetryEINTR(connect)(client.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr), SyscallSucceeds());
}
// Shutdown the read of the listener, expect to fail subsequent
// server accepts, binds and client connects.
ASSERT_THAT(shutdown(listen_fd.get(), SHUT_RD), SyscallSucceeds());
ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),
SyscallFailsWithErrno(EINVAL));
// Check that shutdown did not release the port.
FileDescriptor new_listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
ASSERT_THAT(
bind(new_listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Check that subsequent connection attempts receive a RST.
auto client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
for (int i = 0; i < kFDs; i++) {
auto client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
ASSERT_THAT(RetryEINTR(connect)(client.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallFailsWithErrno(ECONNREFUSED));
}
}
TEST_P(SocketInetLoopbackTest, TCPListenClose) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
constexpr int kAcceptCount = 2;
constexpr int kBacklog = kAcceptCount + 2;
constexpr int kFDs = kBacklog * 3;
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Connect repeatedly, keeping each connection open. After kBacklog
// connections, we'll start getting EINPROGRESS.
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
std::vector<FileDescriptor> clients;
for (int i = 0; i < kFDs; i++) {
auto client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
int ret = connect(client.get(), AsSockAddr(&conn_addr), connector.addr_len);
if (ret != 0) {
EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
}
clients.push_back(std::move(client));
}
for (int i = 0; i < kAcceptCount; i++) {
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
}
}
// Test the protocol state information returned by TCPINFO.
TEST_P(SocketInetLoopbackTest, TCPInfoState) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
FileDescriptor const listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
auto state = [](int fd) -> int {
struct tcp_info opt = {};
socklen_t optLen = sizeof(opt);
EXPECT_THAT(getsockopt(fd, SOL_TCP, TCP_INFO, &opt, &optLen),
SyscallSucceeds());
return opt.tcpi_state;
};
ASSERT_EQ(state(listen_fd.get()), TCP_CLOSE);
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_EQ(state(listen_fd.get()), TCP_CLOSE);
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
ASSERT_EQ(state(listen_fd.get()), TCP_LISTEN);
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Connect to the listening socket.
FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_EQ(state(conn_fd.get()), TCP_CLOSE);
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
ASSERT_EQ(state(conn_fd.get()), TCP_ESTABLISHED);
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
ASSERT_EQ(state(accepted.get()), TCP_ESTABLISHED);
ASSERT_THAT(close(accepted.release()), SyscallSucceeds());
struct pollfd pfd = {
.fd = conn_fd.get(),
.events = POLLIN | POLLRDHUP,
};
constexpr int kTimeout = 10000;
int n = poll(&pfd, 1, kTimeout);
ASSERT_GE(n, 0) << strerror(errno);
ASSERT_EQ(n, 1);
if (IsRunningOnGvisor() && GvisorPlatform() != Platform::kFuchsia) {
// TODO(gvisor.dev/issue/6015): Notify POLLRDHUP on incoming FIN.
ASSERT_EQ(pfd.revents, POLLIN);
} else {
ASSERT_EQ(pfd.revents, POLLIN | POLLRDHUP);
}
ASSERT_THAT(state(conn_fd.get()), TCP_CLOSE_WAIT);
ASSERT_THAT(close(conn_fd.release()), SyscallSucceeds());
}
void TestHangupDuringConnect(const SocketInetTestParam& param,
void (*hangup)(FileDescriptor&)) {
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
for (int i = 0; i < 100; i++) {
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(bind(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),
listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), 0), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(
getsockname(listen_fd.get(), reinterpret_cast<sockaddr*>(&listen_addr),
&addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
// Connect asynchronously and immediately hang up the listener.
FileDescriptor client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
int ret = connect(client.get(), reinterpret_cast<sockaddr*>(&conn_addr),
connector.addr_len);
if (ret != 0) {
EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
}
hangup(listen_fd);
// Wait for the connection to close.
struct pollfd pfd = {
.fd = client.get(),
};
constexpr int kTimeout = 10000;
int n = poll(&pfd, 1, kTimeout);
ASSERT_GE(n, 0) << strerror(errno);
ASSERT_EQ(n, 1);
ASSERT_EQ(pfd.revents, POLLHUP | POLLERR);
ASSERT_EQ(close(client.release()), 0) << strerror(errno);
}
}
TEST_P(SocketInetLoopbackTest, TCPListenCloseDuringConnect) {
TestHangupDuringConnect(GetParam(), [](FileDescriptor& f) {
ASSERT_THAT(close(f.release()), SyscallSucceeds());
});
}
TEST_P(SocketInetLoopbackTest, TCPListenShutdownDuringConnect) {
TestHangupDuringConnect(GetParam(), [](FileDescriptor& f) {
ASSERT_THAT(shutdown(f.get(), SHUT_RD), SyscallSucceeds());
});
}
void TestListenHangupConnectingRead(const SocketInetTestParam& param,
void (*hangup)(FileDescriptor&)) {
constexpr int kTimeout = 10000;
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
// This test is only interested in deterministically getting a socket in
// connecting state. For that, we use a listen backlog of zero which would
// mean there is exactly one connection that gets established and is enqueued
// to the accept queue. We poll on the listener to ensure that is enqueued.
// After that the subsequent client connect will stay in connecting state as
// the accept queue is full.
constexpr int kBacklog = 0;
ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
FileDescriptor established_client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
int ret = connect(established_client.get(), AsSockAddr(&conn_addr),
connector.addr_len);
if (ret != 0) {
EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
}
// On some kernels a backlog of 0 means no backlog, while on others it means a
// backlog of 1. See commit c609e6aae4efcf383fe86b195d1b060befcb3666 for more
// explanation.
//
// If we timeout connecting to loopback, we're on a kernel with no backlog.
pollfd pfd = {
.fd = established_client.get(),
.events = POLLIN | POLLOUT,
};
if (!poll(&pfd, 1, kTimeout)) {
// We're on one of those kernels. It should be impossible to establish the
// connection, so connect will always return EALREADY.
EXPECT_THAT(connect(established_client.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallFailsWithErrno(EALREADY));
return;
}
// Ensure that the accept queue has the completed connection.
pfd = {
.fd = listen_fd.get(),
.events = POLLIN,
};
ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
ASSERT_EQ(pfd.revents, POLLIN);
FileDescriptor connecting_client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
// Keep the last client in connecting state.
ret = connect(connecting_client.get(), AsSockAddr(&conn_addr),
connector.addr_len);
if (ret != 0) {
EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
}
hangup(listen_fd);
std::array<std::pair<int, int>, 2> sockets = {
std::make_pair(established_client.get(), ECONNRESET),
std::make_pair(connecting_client.get(), ECONNREFUSED),
};
for (size_t i = 0; i < sockets.size(); i++) {
SCOPED_TRACE(absl::StrCat("i=", i));
auto [fd, expected_errno] = sockets[i];
pollfd pfd = {
.fd = fd,
};
// When the listening socket is closed, the peer would reset the connection.
EXPECT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
EXPECT_EQ(pfd.revents, POLLHUP | POLLERR);
char c;
EXPECT_THAT(read(fd, &c, sizeof(c)), SyscallFailsWithErrno(expected_errno));
}
}
TEST_P(SocketInetLoopbackTest, TCPListenCloseConnectingRead) {
TestListenHangupConnectingRead(GetParam(), [](FileDescriptor& f) {
ASSERT_THAT(close(f.release()), SyscallSucceeds());
});
}
TEST_P(SocketInetLoopbackTest, TCPListenShutdownConnectingRead) {
TestListenHangupConnectingRead(GetParam(), [](FileDescriptor& f) {
ASSERT_THAT(shutdown(f.get(), SHUT_RD), SyscallSucceeds());
});
}
// Test close of a non-blocking connecting socket.
TEST_P(SocketInetLoopbackTest, TCPNonBlockingConnectClose) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), 0), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
ASSERT_EQ(addrlen, listener.addr_len);
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
// Try many iterations to catch a race with socket close and handshake
// completion.
for (int i = 0; i < 100; ++i) {
FileDescriptor client = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
ASSERT_THAT(
connect(client.get(), AsSockAddr(&conn_addr), connector.addr_len),
SyscallFailsWithErrno(EINPROGRESS));
ASSERT_THAT(close(client.release()), SyscallSucceeds());
// Accept any connections and check if they were closed from the peer. Not
// all client connects would result in an acceptable connection as the
// client handshake might never complete if the socket close was processed
// sooner than the non-blocking connect OR the accept queue is full. We are
// only interested in the case where we do have an acceptable completed
// connection. The accept is non-blocking here, which means that at the time
// of listener close (after the loop ends), we could still have a completed
// connection (from connect of any previous iteration) in the accept queue.
// The listener close would clean up the accept queue.
int accepted_fd;
ASSERT_THAT(accepted_fd = accept(listen_fd.get(), nullptr, nullptr),
AnyOf(SyscallSucceeds(), SyscallFailsWithErrno(EWOULDBLOCK)));
if (accepted_fd < 0) {
continue;
}
FileDescriptor accepted(accepted_fd);
struct pollfd pfd = {
.fd = accepted.get(),
.events = POLLIN | POLLRDHUP,
};
// Use a large timeout to accomodate for retransmitted FINs.
constexpr int kTimeout = 30000;
int n = poll(&pfd, 1, kTimeout);
ASSERT_GE(n, 0) << strerror(errno);
ASSERT_EQ(n, 1);
if (IsRunningOnGvisor() && GvisorPlatform() != Platform::kFuchsia) {
// TODO(gvisor.dev/issue/6015): Notify POLLRDHUP on incoming FIN.
ASSERT_EQ(pfd.revents, POLLIN);
} else {
ASSERT_EQ(pfd.revents, POLLIN | POLLRDHUP);
}
ASSERT_THAT(close(accepted.release()), SyscallSucceeds());
}
}
// TODO(b/153489135): Remove once bug is fixed. Test fails w/
// random save as established connections which can't be delivered to the accept
// queue because the queue is full are not correctly delivered after restore
// causing the last accept to timeout on the restore.
TEST_P(SocketInetLoopbackTest, TCPAcceptBacklogSizes) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
std::array<int, 3> backlogs = {-1, 0, 1};
for (auto& backlog : backlogs) {
ASSERT_THAT(listen(listen_fd.get(), backlog), SyscallSucceeds());
int expected_accepts;
if (backlog < 0) {
expected_accepts = 1024;
} else {
// See the comment in TCPBacklog for why this isn't backlog + 1.
expected_accepts = backlog;
}
for (int i = 0; i < expected_accepts; i++) {
SCOPED_TRACE(absl::StrCat("i=", i));
// Connect to the listening socket.
const FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
const FileDescriptor accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
}
}
}
// TODO(b/153489135): Remove once bug is fixed. Test fails w/
// random save as established connections which can't be delivered to the accept
// queue because the queue is full are not correctly delivered after restore
// causing the last accept to timeout on the restore.
TEST_P(SocketInetLoopbackTest, TCPBacklog) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
constexpr int kBacklogSize = 2;
ASSERT_THAT(listen(listen_fd.get(), kBacklogSize), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
int i = 0;
while (1) {
SCOPED_TRACE(absl::StrCat("i=", i));
int ret;
// Connect to the listening socket.
const FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ret = connect(conn_fd.get(), AsSockAddr(&conn_addr), connector.addr_len);
if (ret != 0) {
EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
pollfd pfd = {
.fd = conn_fd.get(),
.events = POLLOUT,
};
ret = poll(&pfd, 1, 3000);
if (ret == 0) break;
EXPECT_THAT(ret, SyscallSucceedsWithValue(1));
}
EXPECT_THAT(RetryEINTR(send)(conn_fd.get(), &i, sizeof(i), 0),
SyscallSucceedsWithValue(sizeof(i)));
ASSERT_THAT(shutdown(conn_fd.get(), SHUT_RDWR), SyscallSucceeds());
i++;
}
int client_conns = i;
int accepted_conns = 0;
for (; i != 0; i--) {
SCOPED_TRACE(absl::StrCat("i=", i));
pollfd pfd = {
.fd = listen_fd.get(),
.events = POLLIN,
};
// Look for incoming connections to accept. The last connect request could
// be established from the client side, but the ACK of the handshake could
// be dropped by the listener if the accept queue was filled up by the
// previous connect.
int ret;
ASSERT_THAT(ret = poll(&pfd, 1, 3000), SyscallSucceeds());
if (ret == 0) break;
if (pfd.revents == POLLIN) {
// Accept the connection.
//
// We have to assign a name to the accepted socket, as unamed temporary
// objects are destructed upon full evaluation of the expression it is in,
// potentially causing the connecting socket to fail to shutdown properly.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
accepted_conns++;
}
}
// We should accept at least listen backlog + 1 connections. As the stack is
// enqueuing established connections to the accept queue, newer SYNs could
// still be replied to causing those client connections would be accepted as
// we start dequeuing the queue.
//
// On some kernels this can value can be off by one, so we don't add 1 to
// kBacklogSize. See commit c609e6aae4efcf383fe86b195d1b060befcb3666 for more
// explanation.
ASSERT_GE(accepted_conns, kBacklogSize);
ASSERT_GE(client_conns, accepted_conns);
}
// TODO(b/153489135): Remove once bug is fixed. Test fails w/
// random save as established connections which can't be delivered to the accept
// queue because the queue is full are not correctly delivered after restore
// causing the last accept to timeout on the restore.
TEST_P(SocketInetLoopbackTest, TCPBacklogAcceptAll) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
constexpr int kBacklog = 1;
ASSERT_THAT(listen(listen_fd.get(), kBacklog), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
// Fill up the accept queue and trigger more client connections which would be
// waiting to be accepted.
//
// See the comment in TCPBacklog for why this isn't backlog + 1.
std::array<FileDescriptor, kBacklog> established_clients;
for (auto& fd : established_clients) {
fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
ASSERT_THAT(connect(fd.get(), AsSockAddr(&conn_addr), connector.addr_len),
SyscallSucceeds());
}
std::array<FileDescriptor, kBacklog> waiting_clients;
for (auto& fd : waiting_clients) {
fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM | SOCK_NONBLOCK, IPPROTO_TCP));
int ret = connect(fd.get(), AsSockAddr(&conn_addr), connector.addr_len);
if (ret != 0) {
EXPECT_THAT(ret, SyscallFailsWithErrno(EINPROGRESS));
}
}
auto accept_connection = [&]() {
constexpr int kTimeout = 10000;
pollfd pfd = {
.fd = listen_fd.get(),
.events = POLLIN,
};
ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
ASSERT_EQ(pfd.revents, POLLIN);
// Accept the connection.
//
// We have to assign a name to the accepted socket, as unamed temporary
// objects are destructed upon full evaluation of the expression it is in,
// potentially causing the connecting socket to fail to shutdown properly.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
};
// Ensure that we accept all client connections. The waiting connections would
// get enqueued as we drain the accept queue.
for (std::size_t i = 0; i < std::size(established_clients); i++) {
SCOPED_TRACE(absl::StrCat("established clients i=", i));
accept_connection();
}
// The waiting client connections could be in one of these 2 states:
// (1) SYN_SENT: if the SYN was dropped because accept queue was full
// (2) ESTABLISHED: if the listener sent back a SYNACK, but may have dropped
// the ACK from the client if the accept queue was full (send out a data to
// re-send that ACK, to address that case).
for (std::size_t i = 0; i < std::size(waiting_clients); i++) {
SCOPED_TRACE(absl::StrCat("waiting clients i=", i));
constexpr int kTimeout = 10000;
pollfd pfd = {
.fd = waiting_clients[i].get(),
.events = POLLOUT,
};
EXPECT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
EXPECT_EQ(pfd.revents, POLLOUT);
char c;
EXPECT_THAT(RetryEINTR(send)(waiting_clients[i].get(), &c, sizeof(c), 0),
SyscallSucceedsWithValue(sizeof(c)));
accept_connection();
}
}
// TCPResetAfterClose creates a pair of connected sockets then closes
// one end to trigger FIN_WAIT2 state for the closed endpoint verifies
// that we generate RSTs for any new data after the socket is fully
// closed.
TEST_P(SocketInetLoopbackTest, TCPResetAfterClose) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Connect to the listening socket.
FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
// Accept the connection.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
// close the connecting FD to trigger FIN_WAIT2 on the connected fd.
conn_fd.reset();
int data = 1234;
// Now send data which should trigger a RST as the other end should
// have timed out and closed the socket.
EXPECT_THAT(RetryEINTR(send)(accepted.get(), &data, sizeof(data), 0),
SyscallSucceeds());
// Sleep for a shortwhile to get a RST back.
absl::SleepFor(absl::Seconds(1));
// Try writing again and we should get an EPIPE back.
EXPECT_THAT(RetryEINTR(send)(accepted.get(), &data, sizeof(data), 0),
SyscallFailsWithErrno(EPIPE));
// Trying to read should return zero as the other end did send
// us a FIN. We do it twice to verify that the RST does not cause an
// ECONNRESET on the read after EOF has been read by applicaiton.
EXPECT_THAT(RetryEINTR(recv)(accepted.get(), &data, sizeof(data), 0),
SyscallSucceedsWithValue(0));
EXPECT_THAT(RetryEINTR(recv)(accepted.get(), &data, sizeof(data), 0),
SyscallSucceedsWithValue(0));
}
TEST_P(SocketInetLoopbackTest, AcceptedInheritsTCPUserTimeout) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
const uint16_t port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Set the userTimeout on the listening socket.
constexpr int kUserTimeout = 10;
ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_USER_TIMEOUT,
&kUserTimeout, sizeof(kUserTimeout)),
SyscallSucceeds());
// Connect to the listening socket.
FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
// Accept the connection.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
// Verify that the accepted socket inherited the user timeout set on
// listening socket.
int get = -1;
socklen_t get_len = sizeof(get);
ASSERT_THAT(
getsockopt(accepted.get(), IPPROTO_TCP, TCP_USER_TIMEOUT, &get, &get_len),
SyscallSucceeds());
EXPECT_EQ(get_len, sizeof(get));
EXPECT_EQ(get, kUserTimeout);
}
TEST_P(SocketInetLoopbackTest, TCPAcceptAfterReset) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
// Get the port bound by the listening socket.
{
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(
getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
}
const uint16_t port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Connect to the listening socket.
FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
// TODO(b/153489135): Reenable Cooperative S/R once bug is fixed.
DisableSave ds;
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
// Trigger a RST by turning linger off and closing the socket.
struct linger opt = {
.l_onoff = 1,
.l_linger = 0,
};
ASSERT_THAT(
setsockopt(conn_fd.get(), SOL_SOCKET, SO_LINGER, &opt, sizeof(opt)),
SyscallSucceeds());
ASSERT_THAT(close(conn_fd.release()), SyscallSucceeds());
if (IsRunningOnGvisor()) {
// Gvisor packet procssing is asynchronous and can take a bit of time in
// some cases so we give it a bit of time to process the RST packet before
// calling accept.
//
// There is nothing to poll() on so we have no choice but to use a sleep
// here.
absl::SleepFor(absl::Milliseconds(100));
}
sockaddr_storage accept_addr;
socklen_t addrlen = sizeof(accept_addr);
auto accept_fd = ASSERT_NO_ERRNO_AND_VALUE(
Accept(listen_fd.get(), AsSockAddr(&accept_addr), &addrlen));
ASSERT_EQ(addrlen, listener.addr_len);
// Wait for accept_fd to process the RST.
constexpr int kTimeout = 10000;
pollfd pfd = {
.fd = accept_fd.get(),
.events = POLLIN,
};
ASSERT_THAT(poll(&pfd, 1, kTimeout), SyscallSucceedsWithValue(1));
ASSERT_EQ(pfd.revents, POLLIN | POLLHUP | POLLERR);
{
int err;
socklen_t optlen = sizeof(err);
ASSERT_THAT(
getsockopt(accept_fd.get(), SOL_SOCKET, SO_ERROR, &err, &optlen),
SyscallSucceeds());
// This should return ECONNRESET as the socket just received a RST packet
// from the peer.
ASSERT_EQ(optlen, sizeof(err));
ASSERT_EQ(err, ECONNRESET);
}
{
int err;
socklen_t optlen = sizeof(err);
ASSERT_THAT(
getsockopt(accept_fd.get(), SOL_SOCKET, SO_ERROR, &err, &optlen),
SyscallSucceeds());
// This should return no error as the previous getsockopt call would have
// cleared the socket error.
ASSERT_EQ(optlen, sizeof(err));
ASSERT_EQ(err, 0);
}
{
sockaddr_storage peer_addr;
socklen_t addrlen = sizeof(peer_addr);
// The socket is not connected anymore and should return ENOTCONN.
ASSERT_THAT(getpeername(accept_fd.get(), AsSockAddr(&peer_addr), &addrlen),
SyscallFailsWithErrno(ENOTCONN));
}
}
// TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
// saved. Enable S/R once issue is fixed.
TEST_P(SocketInetLoopbackTest, TCPDeferAccept) {
// TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
// saved. Enable S/R issue is fixed.
DisableSave ds;
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
const uint16_t port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Set the TCP_DEFER_ACCEPT on the listening socket.
constexpr int kTCPDeferAccept = 3;
ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,
&kTCPDeferAccept, sizeof(kTCPDeferAccept)),
SyscallSucceeds());
// Connect to the listening socket.
FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
// Set the listening socket to nonblock so that we can verify that there is no
// connection in queue despite the connect above succeeding since the peer has
// sent no data and TCP_DEFER_ACCEPT is set on the listening socket. Set the
// FD to O_NONBLOCK.
int opts;
ASSERT_THAT(opts = fcntl(listen_fd.get(), F_GETFL), SyscallSucceeds());
opts |= O_NONBLOCK;
ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),
SyscallFailsWithErrno(EWOULDBLOCK));
// Set FD back to blocking.
opts &= ~O_NONBLOCK;
ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
// Now write some data to the socket.
int data = 0;
ASSERT_THAT(RetryEINTR(write)(conn_fd.get(), &data, sizeof(data)),
SyscallSucceedsWithValue(sizeof(data)));
// This should now cause the connection to complete and be delivered to the
// accept socket.
// Accept the connection.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
// Verify that the accepted socket returns the data written.
int get = -1;
ASSERT_THAT(RetryEINTR(recv)(accepted.get(), &get, sizeof(get), 0),
SyscallSucceedsWithValue(sizeof(get)));
EXPECT_EQ(get, data);
}
// TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
// saved. Enable S/R once issue is fixed.
TEST_P(SocketInetLoopbackTest, TCPDeferAcceptTimeout) {
// TODO(gvisor.dev/issue/1688): Partially completed passive endpoints are not
// saved. Enable S/R once issue is fixed.
DisableSave ds;
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
// Create the listening socket.
const FileDescriptor listen_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage listen_addr = listener.addr;
ASSERT_THAT(
bind(listen_fd.get(), AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(listen_fd.get(), SOMAXCONN), SyscallSucceeds());
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(getsockname(listen_fd.get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
const uint16_t port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
// Set the TCP_DEFER_ACCEPT on the listening socket.
constexpr int kTCPDeferAccept = 3;
ASSERT_THAT(setsockopt(listen_fd.get(), IPPROTO_TCP, TCP_DEFER_ACCEPT,
&kTCPDeferAccept, sizeof(kTCPDeferAccept)),
SyscallSucceeds());
// Connect to the listening socket.
FileDescriptor conn_fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
sockaddr_storage conn_addr = connector.addr;
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
ASSERT_THAT(RetryEINTR(connect)(conn_fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
// Set the listening socket to nonblock so that we can verify that there is no
// connection in queue despite the connect above succeeding since the peer has
// sent no data and TCP_DEFER_ACCEPT is set on the listening socket. Set the
// FD to O_NONBLOCK.
int opts;
ASSERT_THAT(opts = fcntl(listen_fd.get(), F_GETFL), SyscallSucceeds());
opts |= O_NONBLOCK;
ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
// Verify that there is no acceptable connection before TCP_DEFER_ACCEPT
// timeout is hit.
absl::SleepFor(absl::Seconds(kTCPDeferAccept - 1));
ASSERT_THAT(accept(listen_fd.get(), nullptr, nullptr),
SyscallFailsWithErrno(EWOULDBLOCK));
// Set FD back to blocking.
opts &= ~O_NONBLOCK;
ASSERT_THAT(fcntl(listen_fd.get(), F_SETFL, opts), SyscallSucceeds());
// Now sleep for a little over the TCP_DEFER_ACCEPT duration. When the timeout
// is hit a SYN-ACK should be retransmitted by the listener as a last ditch
// attempt to complete the connection with or without data.
absl::SleepFor(absl::Seconds(2));
// Verify that we have a connection that can be accepted even though no
// data was written.
auto accepted =
ASSERT_NO_ERRNO_AND_VALUE(Accept(listen_fd.get(), nullptr, nullptr));
}
INSTANTIATE_TEST_SUITE_P(All, SocketInetLoopbackTest,
SocketInetLoopbackTestValues(),
DescribeSocketInetTestParam);
using SocketInetReusePortTest = ::testing::TestWithParam<SocketInetTestParam>;
// TODO(gvisor.dev/issue/940): Remove when portHint/stack.Seed is
// saved/restored.
TEST_P(SocketInetReusePortTest, TcpPortReuseMultiThread) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
sockaddr_storage listen_addr = listener.addr;
sockaddr_storage conn_addr = connector.addr;
constexpr int kThreadCount = 3;
constexpr int kConnectAttempts = 10000;
// Create the listening socket.
FileDescriptor listener_fds[kThreadCount];
for (int i = 0; i < kThreadCount; i++) {
listener_fds[i] = ASSERT_NO_ERRNO_AND_VALUE(
Socket(listener.family(), SOCK_STREAM, IPPROTO_TCP));
int fd = listener_fds[i].get();
ASSERT_THAT(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(bind(fd, AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(fd, 40), SyscallSucceeds());
// On the first bind we need to determine which port was bound.
if (i != 0) {
continue;
}
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(
getsockname(listener_fds[0].get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
ASSERT_NO_ERRNO(SetAddrPort(listener.family(), &listen_addr, port));
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
}
std::atomic<int> connects_received = ATOMIC_VAR_INIT(0);
std::unique_ptr<ScopedThread> listen_thread[kThreadCount];
int accept_counts[kThreadCount] = {};
// TODO(avagin): figure how to not disable S/R for the whole test.
// We need to take into account that this test executes a lot of system
// calls from many threads.
DisableSave ds;
for (int i = 0; i < kThreadCount; i++) {
listen_thread[i] = absl::make_unique<ScopedThread>(
[&listener_fds, &accept_counts, i, &connects_received]() {
do {
auto fd = Accept(listener_fds[i].get(), nullptr, nullptr);
if (!fd.ok()) {
if (connects_received >= kConnectAttempts) {
// Another thread have shutdown our read side causing the
// accept to fail.
ASSERT_EQ(errno, EINVAL);
break;
}
ASSERT_NO_ERRNO(fd);
break;
}
// Receive some data from a socket to be sure that the connect()
// system call has been completed on another side.
// Do a short read and then close the socket to trigger a RST. This
// ensures that both ends of the connection are cleaned up and no
// goroutines hang around in TIME-WAIT. We do this so that this test
// does not timeout under gotsan runs where lots of goroutines can
// cause the test to use absurd amounts of memory.
//
// See: https://tools.ietf.org/html/rfc2525#page-50 section 2.17
uint16_t data;
EXPECT_THAT(
RetryEINTR(recv)(fd.ValueOrDie().get(), &data, sizeof(data), 0),
SyscallSucceedsWithValue(sizeof(data)));
accept_counts[i]++;
} while (++connects_received < kConnectAttempts);
// Shutdown all sockets to wake up other threads.
for (int j = 0; j < kThreadCount; j++) {
shutdown(listener_fds[j].get(), SHUT_RDWR);
}
});
}
ScopedThread connecting_thread([&connector, &conn_addr]() {
for (int32_t i = 0; i < kConnectAttempts; i++) {
const FileDescriptor fd = ASSERT_NO_ERRNO_AND_VALUE(
Socket(connector.family(), SOCK_STREAM, IPPROTO_TCP));
ASSERT_THAT(RetryEINTR(connect)(fd.get(), AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceeds());
EXPECT_THAT(RetryEINTR(send)(fd.get(), &i, sizeof(i), 0),
SyscallSucceedsWithValue(sizeof(i)));
}
});
// Join threads to be sure that all connections have been counted
connecting_thread.Join();
for (int i = 0; i < kThreadCount; i++) {
listen_thread[i]->Join();
}
// Check that connections are distributed fairly between listening sockets
for (int i = 0; i < kThreadCount; i++)
EXPECT_THAT(accept_counts[i],
EquivalentWithin((kConnectAttempts / kThreadCount), 0.10));
}
TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThread) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
sockaddr_storage listen_addr = listener.addr;
sockaddr_storage conn_addr = connector.addr;
constexpr int kThreadCount = 3;
// Create the listening socket.
FileDescriptor listener_fds[kThreadCount];
for (int i = 0; i < kThreadCount; i++) {
listener_fds[i] =
ASSERT_NO_ERRNO_AND_VALUE(Socket(listener.family(), SOCK_DGRAM, 0));
int fd = listener_fds[i].get();
ASSERT_THAT(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(bind(fd, AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
// On the first bind we need to determine which port was bound.
if (i != 0) {
continue;
}
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(
getsockname(listener_fds[0].get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
ASSERT_NO_ERRNO(SetAddrPort(listener.family(), &listen_addr, port));
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
}
constexpr int kConnectAttempts = 10000;
std::atomic<int> packets_received = ATOMIC_VAR_INIT(0);
std::unique_ptr<ScopedThread> receiver_thread[kThreadCount];
int packets_per_socket[kThreadCount] = {};
// TODO(avagin): figure how to not disable S/R for the whole test.
DisableSave ds; // Too expensive.
for (int i = 0; i < kThreadCount; i++) {
receiver_thread[i] = absl::make_unique<ScopedThread>(
[&listener_fds, &packets_per_socket, i, &packets_received]() {
do {
struct sockaddr_storage addr = {};
socklen_t addrlen = sizeof(addr);
int data;
auto ret =
RetryEINTR(recvfrom)(listener_fds[i].get(), &data, sizeof(data),
0, AsSockAddr(&addr), &addrlen);
if (packets_received < kConnectAttempts) {
ASSERT_THAT(ret, SyscallSucceedsWithValue(sizeof(data)));
}
if (ret != sizeof(data)) {
// Another thread may have shutdown our read side causing the
// recvfrom to fail.
break;
}
packets_received++;
packets_per_socket[i]++;
// A response is required to synchronize with the main thread,
// otherwise the main thread can send more than can fit into receive
// queues.
EXPECT_THAT(
RetryEINTR(sendto)(listener_fds[i].get(), &data, sizeof(data),
0, AsSockAddr(&addr), addrlen),
SyscallSucceedsWithValue(sizeof(data)));
} while (packets_received < kConnectAttempts);
// Shutdown all sockets to wake up other threads.
for (int j = 0; j < kThreadCount; j++)
shutdown(listener_fds[j].get(), SHUT_RD);
});
}
ScopedThread main_thread([&connector, &conn_addr]() {
for (int i = 0; i < kConnectAttempts; i++) {
const FileDescriptor fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(connector.family(), SOCK_DGRAM, 0));
EXPECT_THAT(
RetryEINTR(sendto)(fd.get(), &i, sizeof(i), 0, AsSockAddr(&conn_addr),
connector.addr_len),
SyscallSucceedsWithValue(sizeof(i)));
int data;
EXPECT_THAT(RetryEINTR(recv)(fd.get(), &data, sizeof(data), 0),
SyscallSucceedsWithValue(sizeof(data)));
}
});
main_thread.Join();
// Join threads to be sure that all connections have been counted
for (int i = 0; i < kThreadCount; i++) {
receiver_thread[i]->Join();
}
// Check that packets are distributed fairly between listening sockets.
for (int i = 0; i < kThreadCount; i++)
EXPECT_THAT(packets_per_socket[i],
EquivalentWithin((kConnectAttempts / kThreadCount), 0.10));
}
TEST_P(SocketInetReusePortTest, UdpPortReuseMultiThreadShort) {
SocketInetTestParam const& param = GetParam();
TestAddress const& listener = param.listener;
TestAddress const& connector = param.connector;
sockaddr_storage listen_addr = listener.addr;
sockaddr_storage conn_addr = connector.addr;
constexpr int kThreadCount = 3;
// TODO(b/141211329): endpointsByNic.seed has to be saved/restored.
const DisableSave ds141211329;
// Create listening sockets.
FileDescriptor listener_fds[kThreadCount];
for (int i = 0; i < kThreadCount; i++) {
listener_fds[i] =
ASSERT_NO_ERRNO_AND_VALUE(Socket(listener.family(), SOCK_DGRAM, 0));
int fd = listener_fds[i].get();
ASSERT_THAT(setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(bind(fd, AsSockAddr(&listen_addr), listener.addr_len),
SyscallSucceeds());
// On the first bind we need to determine which port was bound.
if (i != 0) {
continue;
}
// Get the port bound by the listening socket.
socklen_t addrlen = listener.addr_len;
ASSERT_THAT(
getsockname(listener_fds[0].get(), AsSockAddr(&listen_addr), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(listener.family(), listen_addr));
ASSERT_NO_ERRNO(SetAddrPort(listener.family(), &listen_addr, port));
ASSERT_NO_ERRNO(SetAddrPort(connector.family(), &conn_addr, port));
}
constexpr int kConnectAttempts = 10;
FileDescriptor client_fds[kConnectAttempts];
// Do the first run without save/restore.
DisableSave ds;
for (int i = 0; i < kConnectAttempts; i++) {
client_fds[i] =
ASSERT_NO_ERRNO_AND_VALUE(Socket(connector.family(), SOCK_DGRAM, 0));
EXPECT_THAT(RetryEINTR(sendto)(client_fds[i].get(), &i, sizeof(i), 0,
AsSockAddr(&conn_addr), connector.addr_len),
SyscallSucceedsWithValue(sizeof(i)));
}
ds.reset();
// Check that a mapping of client and server sockets has
// not been change after save/restore.
for (int i = 0; i < kConnectAttempts; i++) {
EXPECT_THAT(RetryEINTR(sendto)(client_fds[i].get(), &i, sizeof(i), 0,
AsSockAddr(&conn_addr), connector.addr_len),
SyscallSucceedsWithValue(sizeof(i)));
}
pollfd pollfds[kThreadCount];
for (int i = 0; i < kThreadCount; i++) {
pollfds[i].fd = listener_fds[i].get();
pollfds[i].events = POLLIN;
}
std::map<uint16_t, int> portToFD;
int received = 0;
while (received < kConnectAttempts * 2) {
ASSERT_THAT(poll(pollfds, kThreadCount, -1),
SyscallSucceedsWithValue(Gt(0)));
for (int i = 0; i < kThreadCount; i++) {
if ((pollfds[i].revents & POLLIN) == 0) {
continue;
}
received++;
const int fd = pollfds[i].fd;
struct sockaddr_storage addr = {};
socklen_t addrlen = sizeof(addr);
int data;
EXPECT_THAT(RetryEINTR(recvfrom)(fd, &data, sizeof(data), 0,
AsSockAddr(&addr), &addrlen),
SyscallSucceedsWithValue(sizeof(data)));
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(connector.family(), addr));
auto prev_port = portToFD.find(port);
// Check that all packets from one client have been delivered to the
// same server socket.
if (prev_port == portToFD.end()) {
portToFD[port] = fd;
} else {
EXPECT_EQ(portToFD[port], fd);
}
}
}
}
INSTANTIATE_TEST_SUITE_P(
All, SocketInetReusePortTest,
::testing::Values(
// Listeners bound to IPv4 addresses refuse connections using IPv6
// addresses.
SocketInetTestParam{V4Any(), V4Loopback()},
SocketInetTestParam{V4Loopback(), V4MappedLoopback()},
// Listeners bound to IN6ADDR_ANY accept all connections.
SocketInetTestParam{V6Any(), V4Loopback()},
SocketInetTestParam{V6Any(), V6Loopback()},
// Listeners bound to IN6ADDR_LOOPBACK refuse connections using IPv4
// addresses.
SocketInetTestParam{V6Loopback(), V6Loopback()}),
DescribeSocketInetTestParam);
using SocketMultiProtocolInetLoopbackTest =
::testing::TestWithParam<ProtocolTestParam>;
TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedLoopbackOnlyReservesV4) {
ProtocolTestParam const& param = GetParam();
for (int i = 0; true; i++) {
// Bind the v4 loopback on a dual stack socket.
TestAddress const& test_addr_dual = V4MappedLoopback();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_dual.family(), param.type, 0));
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that we can still bind the v6 loopback on the same port.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
const FileDescriptor fd_v6 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
int ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
if (ret == -1 && errno == EADDRINUSE) {
// Port may have been in use.
ASSERT_LT(i, 100); // Give up after 100 tries.
continue;
}
ASSERT_THAT(ret, SyscallSucceeds());
// Verify that binding the v4 loopback with the same port on a v4 socket
// fails.
TestAddress const& test_addr_v4 = V4Loopback();
sockaddr_storage addr_v4 = test_addr_v4.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
const FileDescriptor fd_v4 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// No need to try again.
break;
}
}
TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedAnyOnlyReservesV4) {
ProtocolTestParam const& param = GetParam();
for (int i = 0; true; i++) {
// Bind the v4 any on a dual stack socket.
TestAddress const& test_addr_dual = V4MappedAny();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_dual.family(), param.type, 0));
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that we can still bind the v6 loopback on the same port.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
const FileDescriptor fd_v6 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
int ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
if (ret == -1 && errno == EADDRINUSE) {
// Port may have been in use.
ASSERT_LT(i, 100); // Give up after 100 tries.
continue;
}
ASSERT_THAT(ret, SyscallSucceeds());
// Verify that binding the v4 loopback with the same port on a v4 socket
// fails.
TestAddress const& test_addr_v4 = V4Loopback();
sockaddr_storage addr_v4 = test_addr_v4.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
const FileDescriptor fd_v4 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// No need to try again.
break;
}
}
TEST_P(SocketMultiProtocolInetLoopbackTest, DualStackV6AnyReservesEverything) {
ProtocolTestParam const& param = GetParam();
// Bind the v6 any on a dual stack socket.
TestAddress const& test_addr_dual = V6Any();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that binding the v6 loopback with the same port fails.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
const FileDescriptor fd_v6 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 loopback on the same port with a v6 socket
// fails.
TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped, port));
const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_mapped.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
test_addr_v4_mapped.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 loopback on the same port with a v4 socket
// fails.
TestAddress const& test_addr_v4 = V4Loopback();
sockaddr_storage addr_v4 = test_addr_v4.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
const FileDescriptor fd_v4 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 any on the same port with a v4 socket
// fails.
TestAddress const& test_addr_v4_any = V4Any();
sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_any.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
test_addr_v4_any.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
}
TEST_P(SocketMultiProtocolInetLoopbackTest,
DualStackV6AnyReuseAddrDoesNotReserveV4Any) {
ProtocolTestParam const& param = GetParam();
// Bind the v6 any on a dual stack socket.
TestAddress const& test_addr_dual = V6Any();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
ASSERT_THAT(setsockopt(fd_dual.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that binding the v4 any on the same port with a v4 socket succeeds.
TestAddress const& test_addr_v4_any = V4Any();
sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_any.family(), param.type, 0));
ASSERT_THAT(setsockopt(fd_v4_any.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
test_addr_v4_any.addr_len),
SyscallSucceeds());
}
TEST_P(SocketMultiProtocolInetLoopbackTest,
DualStackV6AnyReuseAddrListenReservesV4Any) {
ProtocolTestParam const& param = GetParam();
// Only TCP sockets are supported.
SKIP_IF((param.type & SOCK_STREAM) == 0);
// Bind the v6 any on a dual stack socket.
TestAddress const& test_addr_dual = V6Any();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
ASSERT_THAT(setsockopt(fd_dual.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(fd_dual.get(), 5), SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that binding the v4 any on the same port with a v4 socket succeeds.
TestAddress const& test_addr_v4_any = V4Any();
sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_any.family(), param.type, 0));
ASSERT_THAT(setsockopt(fd_v4_any.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
test_addr_v4_any.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
}
TEST_P(SocketMultiProtocolInetLoopbackTest,
DualStackV6AnyWithListenReservesEverything) {
ProtocolTestParam const& param = GetParam();
// Only TCP sockets are supported.
SKIP_IF((param.type & SOCK_STREAM) == 0);
// Bind the v6 any on a dual stack socket.
TestAddress const& test_addr_dual = V6Any();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_dual.family(), param.type, 0));
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
ASSERT_THAT(listen(fd_dual.get(), 5), SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that binding the v6 loopback with the same port fails.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
const FileDescriptor fd_v6 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 loopback on the same port with a v6 socket
// fails.
TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped, port));
const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_mapped.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
test_addr_v4_mapped.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 loopback on the same port with a v4 socket
// fails.
TestAddress const& test_addr_v4 = V4Loopback();
sockaddr_storage addr_v4 = test_addr_v4.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4.family(), &addr_v4, port));
const FileDescriptor fd_v4 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 any on the same port with a v4 socket
// fails.
TestAddress const& test_addr_v4_any = V4Any();
sockaddr_storage addr_v4_any = test_addr_v4_any.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_any.family(), &addr_v4_any, port));
const FileDescriptor fd_v4_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_any.family(), param.type, 0));
ASSERT_THAT(bind(fd_v4_any.get(), AsSockAddr(&addr_v4_any),
test_addr_v4_any.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
}
TEST_P(SocketMultiProtocolInetLoopbackTest, V6OnlyV6AnyReservesV6) {
ProtocolTestParam const& param = GetParam();
for (int i = 0; true; i++) {
// Bind the v6 any on a v6-only socket.
TestAddress const& test_addr_dual = V6Any();
sockaddr_storage addr_dual = test_addr_dual.addr;
const FileDescriptor fd_dual = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_dual.family(), param.type, 0));
EXPECT_THAT(setsockopt(fd_dual.get(), IPPROTO_IPV6, IPV6_V6ONLY,
&kSockOptOn, sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(
bind(fd_dual.get(), AsSockAddr(&addr_dual), test_addr_dual.addr_len),
SyscallSucceeds());
// Get the port that we bound.
socklen_t addrlen = test_addr_dual.addr_len;
ASSERT_THAT(getsockname(fd_dual.get(), AsSockAddr(&addr_dual), &addrlen),
SyscallSucceeds());
uint16_t const port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr_dual.family(), addr_dual));
// Verify that binding the v6 loopback with the same port fails.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v6.family(), &addr_v6, port));
const FileDescriptor fd_v6 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that we can still bind the v4 loopback on the same port.
TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped, port));
const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_mapped.family(), param.type, 0));
int ret = bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
test_addr_v4_mapped.addr_len);
if (ret == -1 && errno == EADDRINUSE) {
// Port may have been in use.
ASSERT_LT(i, 100); // Give up after 100 tries.
continue;
}
ASSERT_THAT(ret, SyscallSucceeds());
// No need to try again.
break;
}
}
TEST_P(SocketMultiProtocolInetLoopbackTest, V6EphemeralPortReserved) {
ProtocolTestParam const& param = GetParam();
for (int i = 0; true; i++) {
// Bind the v6 loopback on a dual stack socket.
TestAddress const& test_addr = V6Loopback();
sockaddr_storage bound_addr = test_addr.addr;
const FileDescriptor bound_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(
bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
SyscallSucceeds());
// Listen iff TCP.
if (param.type == SOCK_STREAM) {
ASSERT_THAT(listen(bound_fd.get(), SOMAXCONN), SyscallSucceeds());
}
// Get the port that we bound.
socklen_t bound_addr_len = test_addr.addr_len;
ASSERT_THAT(
getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
SyscallSucceeds());
// Connect to bind an ephemeral port.
const FileDescriptor connected_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(), AsSockAddr(&bound_addr),
bound_addr_len),
SyscallSucceeds());
// Get the ephemeral port.
sockaddr_storage connected_addr = {};
socklen_t connected_addr_len = sizeof(connected_addr);
ASSERT_THAT(getsockname(connected_fd.get(), AsSockAddr(&connected_addr),
&connected_addr_len),
SyscallSucceeds());
uint16_t const ephemeral_port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr.family(), connected_addr));
// Verify that we actually got an ephemeral port.
ASSERT_NE(ephemeral_port, 0);
// Verify that the ephemeral port is reserved.
const FileDescriptor checking_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
EXPECT_THAT(bind(checking_fd.get(), AsSockAddr(&connected_addr),
connected_addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v6 loopback with the same port fails.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v6.family(), &addr_v6, ephemeral_port));
const FileDescriptor fd_v6 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v6.family(), param.type, 0));
ASSERT_THAT(bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that we can still bind the v4 loopback on the same port.
TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped,
ephemeral_port));
const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_mapped.family(), param.type, 0));
int ret = bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
test_addr_v4_mapped.addr_len);
if (ret == -1 && errno == EADDRINUSE) {
// Port may have been in use.
ASSERT_LT(i, 100); // Give up after 100 tries.
continue;
}
EXPECT_THAT(ret, SyscallSucceeds());
// No need to try again.
break;
}
}
TEST_P(SocketMultiProtocolInetLoopbackTest, V4MappedEphemeralPortReserved) {
ProtocolTestParam const& param = GetParam();
for (int i = 0; true; i++) {
// Bind the v4 loopback on a dual stack socket.
TestAddress const& test_addr = V4MappedLoopback();
sockaddr_storage bound_addr = test_addr.addr;
const FileDescriptor bound_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(
bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
SyscallSucceeds());
// Listen iff TCP.
if (param.type == SOCK_STREAM) {
ASSERT_THAT(listen(bound_fd.get(), SOMAXCONN), SyscallSucceeds());
}
// Get the port that we bound.
socklen_t bound_addr_len = test_addr.addr_len;
ASSERT_THAT(
getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
SyscallSucceeds());
// Connect to bind an ephemeral port.
const FileDescriptor connected_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(), AsSockAddr(&bound_addr),
bound_addr_len),
SyscallSucceeds());
// Get the ephemeral port.
sockaddr_storage connected_addr = {};
socklen_t connected_addr_len = sizeof(connected_addr);
ASSERT_THAT(getsockname(connected_fd.get(), AsSockAddr(&connected_addr),
&connected_addr_len),
SyscallSucceeds());
uint16_t const ephemeral_port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr.family(), connected_addr));
// Verify that we actually got an ephemeral port.
ASSERT_NE(ephemeral_port, 0);
// Verify that the ephemeral port is reserved.
const FileDescriptor checking_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
EXPECT_THAT(bind(checking_fd.get(), AsSockAddr(&connected_addr),
connected_addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 loopback on the same port with a v4 socket
// fails.
TestAddress const& test_addr_v4 = V4Loopback();
sockaddr_storage addr_v4 = test_addr_v4.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v4.family(), &addr_v4, ephemeral_port));
const FileDescriptor fd_v4 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr_v4.family(), param.type, 0));
EXPECT_THAT(bind(fd_v4.get(), AsSockAddr(&addr_v4), test_addr_v4.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v6 any on the same port with a dual-stack socket
// fails.
TestAddress const& test_addr_v6_any = V6Any();
sockaddr_storage addr_v6_any = test_addr_v6_any.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v6_any.family(), &addr_v6_any, ephemeral_port));
const FileDescriptor fd_v6_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v6_any.family(), param.type, 0));
ASSERT_THAT(bind(fd_v6_any.get(), AsSockAddr(&addr_v6_any),
test_addr_v6_any.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// For some reason, binding the TCP v6-only any is flaky on Linux. Maybe we
// tend to run out of ephemeral ports? Regardless, binding the v6 loopback
// seems pretty reliable. Only try to bind the v6-only any on UDP and
// gVisor.
int ret = -1;
if (!IsRunningOnGvisor() && param.type == SOCK_STREAM) {
// Verify that we can still bind the v6 loopback on the same port.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v6.family(), &addr_v6, ephemeral_port));
const FileDescriptor fd_v6 = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v6.family(), param.type, 0));
ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
} else {
// Verify that we can still bind the v6 any on the same port with a
// v6-only socket.
const FileDescriptor fd_v6_only_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v6_any.family(), param.type, 0));
EXPECT_THAT(setsockopt(fd_v6_only_any.get(), IPPROTO_IPV6, IPV6_V6ONLY,
&kSockOptOn, sizeof(kSockOptOn)),
SyscallSucceeds());
ret = bind(fd_v6_only_any.get(), AsSockAddr(&addr_v6_any),
test_addr_v6_any.addr_len);
}
if (ret == -1 && errno == EADDRINUSE) {
// Port may have been in use.
ASSERT_LT(i, 100); // Give up after 100 tries.
continue;
}
EXPECT_THAT(ret, SyscallSucceeds());
// No need to try again.
break;
}
}
TEST_P(SocketMultiProtocolInetLoopbackTest, V4EphemeralPortReserved) {
ProtocolTestParam const& param = GetParam();
for (int i = 0; true; i++) {
// Bind the v4 loopback on a v4 socket.
TestAddress const& test_addr = V4Loopback();
sockaddr_storage bound_addr = test_addr.addr;
const FileDescriptor bound_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(
bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
SyscallSucceeds());
// Listen iff TCP.
if (param.type == SOCK_STREAM) {
ASSERT_THAT(listen(bound_fd.get(), SOMAXCONN), SyscallSucceeds());
}
// Get the port that we bound.
socklen_t bound_addr_len = test_addr.addr_len;
ASSERT_THAT(
getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
SyscallSucceeds());
// Connect to bind an ephemeral port.
const FileDescriptor connected_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(RetryEINTR(connect)(connected_fd.get(), AsSockAddr(&bound_addr),
bound_addr_len),
SyscallSucceeds());
// Get the ephemeral port.
sockaddr_storage connected_addr = {};
socklen_t connected_addr_len = sizeof(connected_addr);
ASSERT_THAT(getsockname(connected_fd.get(), AsSockAddr(&connected_addr),
&connected_addr_len),
SyscallSucceeds());
uint16_t const ephemeral_port =
ASSERT_NO_ERRNO_AND_VALUE(AddrPort(test_addr.family(), connected_addr));
// Verify that we actually got an ephemeral port.
ASSERT_NE(ephemeral_port, 0);
// Verify that the ephemeral port is reserved.
const FileDescriptor checking_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
EXPECT_THAT(bind(checking_fd.get(), AsSockAddr(&connected_addr),
connected_addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v4 loopback on the same port with a v6 socket
// fails.
TestAddress const& test_addr_v4_mapped = V4MappedLoopback();
sockaddr_storage addr_v4_mapped = test_addr_v4_mapped.addr;
ASSERT_NO_ERRNO(SetAddrPort(test_addr_v4_mapped.family(), &addr_v4_mapped,
ephemeral_port));
const FileDescriptor fd_v4_mapped = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v4_mapped.family(), param.type, 0));
EXPECT_THAT(bind(fd_v4_mapped.get(), AsSockAddr(&addr_v4_mapped),
test_addr_v4_mapped.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// Verify that binding the v6 any on the same port with a dual-stack socket
// fails.
TestAddress const& test_addr_v6_any = V6Any();
sockaddr_storage addr_v6_any = test_addr_v6_any.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v6_any.family(), &addr_v6_any, ephemeral_port));
const FileDescriptor fd_v6_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v6_any.family(), param.type, 0));
ASSERT_THAT(bind(fd_v6_any.get(), AsSockAddr(&addr_v6_any),
test_addr_v6_any.addr_len),
SyscallFailsWithErrno(EADDRINUSE));
// For some reason, binding the TCP v6-only any is flaky on Linux. Maybe we
// tend to run out of ephemeral ports? Regardless, binding the v6 loopback
// seems pretty reliable. Only try to bind the v6-only any on UDP and
// gVisor.
int ret = -1;
if (!IsRunningOnGvisor() && param.type == SOCK_STREAM) {
// Verify that we can still bind the v6 loopback on the same port.
TestAddress const& test_addr_v6 = V6Loopback();
sockaddr_storage addr_v6 = test_addr_v6.addr;
ASSERT_NO_ERRNO(
SetAddrPort(test_addr_v6.family(), &addr_v6, ephemeral_port));
const FileDescriptor fd_v6 = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v6.family(), param.type, 0));
ret = bind(fd_v6.get(), AsSockAddr(&addr_v6), test_addr_v6.addr_len);
} else {
// Verify that we can still bind the v6 any on the same port with a
// v6-only socket.
const FileDescriptor fd_v6_only_any = ASSERT_NO_ERRNO_AND_VALUE(
Socket(test_addr_v6_any.family(), param.type, 0));
EXPECT_THAT(setsockopt(fd_v6_only_any.get(), IPPROTO_IPV6, IPV6_V6ONLY,
&kSockOptOn, sizeof(kSockOptOn)),
SyscallSucceeds());
ret = bind(fd_v6_only_any.get(), AsSockAddr(&addr_v6_any),
test_addr_v6_any.addr_len);
}
if (ret == -1 && errno == EADDRINUSE) {
// Port may have been in use.
ASSERT_LT(i, 100); // Give up after 100 tries.
continue;
}
EXPECT_THAT(ret, SyscallSucceeds());
// No need to try again.
break;
}
}
TEST_P(SocketMultiProtocolInetLoopbackTest,
MultipleBindsAllowedNoListeningReuseAddr) {
ProtocolTestParam const& param = GetParam();
// UDP sockets are allowed to bind/listen on the port w/ SO_REUSEADDR, for TCP
// this is only permitted if there is no other listening socket.
SKIP_IF(param.type != SOCK_STREAM);
// Bind the v4 loopback on a v4 socket.
const TestAddress& test_addr = V4Loopback();
sockaddr_storage bound_addr = test_addr.addr;
FileDescriptor bound_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(setsockopt(bound_fd.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(bind(bound_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
SyscallSucceeds());
// Get the port that we bound.
socklen_t bound_addr_len = test_addr.addr_len;
ASSERT_THAT(
getsockname(bound_fd.get(), AsSockAddr(&bound_addr), &bound_addr_len),
SyscallSucceeds());
// Now create a socket and bind it to the same port, this should
// succeed since there is no listening socket for the same port.
FileDescriptor second_fd =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
ASSERT_THAT(setsockopt(second_fd.get(), SOL_SOCKET, SO_REUSEADDR, &kSockOptOn,
sizeof(kSockOptOn)),
SyscallSucceeds());
ASSERT_THAT(
bind(second_fd.get(), AsSockAddr(&bound_addr), test_addr.addr_len),
SyscallSucceeds());
}
TEST_P(SocketMultiProtocolInetLoopbackTest, PortReuseTwoSockets) {
ProtocolTestParam const& param = GetParam();
TestAddress const& test_addr = V4Loopback();
sockaddr_storage addr = test_addr.addr;
for (int i = 0; i < 2; i++) {
const int portreuse1 = i % 2;
auto s1 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
int fd1 = s1.get();
socklen_t addrlen = test_addr.addr_len;
EXPECT_THAT(
setsockopt(fd1, SOL_SOCKET, SO_REUSEPORT, &portreuse1, sizeof(int)),
SyscallSucceeds());
ASSERT_THAT(bind(fd1, AsSockAddr(&addr), addrlen), SyscallSucceeds());
ASSERT_THAT(getsockname(fd1, AsSockAddr(&addr), &addrlen),
SyscallSucceeds());
if (param.type == SOCK_STREAM) {
ASSERT_THAT(listen(fd1, 1), SyscallSucceeds());
}
// j is less than 4 to check that the port reuse logic works correctly after
// closing bound sockets.
for (int j = 0; j < 4; j++) {
const int portreuse2 = j % 2;
auto s2 =
ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
int fd2 = s2.get();
EXPECT_THAT(
setsockopt(fd2, SOL_SOCKET, SO_REUSEPORT, &portreuse2, sizeof(int)),
SyscallSucceeds());
std::cout << portreuse1 << " " << portreuse2 << std::endl;
int ret = bind(fd2, AsSockAddr(&addr), addrlen);
// Verify that two sockets can be bound to the same port only if
// SO_REUSEPORT is set for both of them.
if (!portreuse1 || !portreuse2) {
ASSERT_THAT(ret, SyscallFailsWithErrno(EADDRINUSE));
} else {
ASSERT_THAT(ret, SyscallSucceeds());
}
}
}
}
// Check that when a socket was bound to an address with REUSEPORT and then
// closed, we can bind a different socket to the same address without needing
// REUSEPORT.
TEST_P(SocketMultiProtocolInetLoopbackTest, NoReusePortFollowingReusePort) {
ProtocolTestParam const& param = GetParam();
TestAddress const& test_addr = V4Loopback();
sockaddr_storage addr = test_addr.addr;
auto s = ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
int fd = s.get();
socklen_t addrlen = test_addr.addr_len;
int portreuse = 1;
ASSERT_THAT(
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &portreuse, sizeof(portreuse)),
SyscallSucceeds());
ASSERT_THAT(bind(fd, AsSockAddr(&addr), addrlen), SyscallSucceeds());
ASSERT_THAT(getsockname(fd, AsSockAddr(&addr), &addrlen), SyscallSucceeds());
ASSERT_EQ(addrlen, test_addr.addr_len);
s.reset();
// Open a new socket and bind to the same address, but w/o REUSEPORT.
s = ASSERT_NO_ERRNO_AND_VALUE(Socket(test_addr.family(), param.type, 0));
fd = s.get();
portreuse = 0;
ASSERT_THAT(
setsockopt(fd, SOL_SOCKET, SO_REUSEPORT, &portreuse, sizeof(portreuse)),
SyscallSucceeds());
ASSERT_THAT(bind(fd, AsSockAddr(&addr), addrlen), SyscallSucceeds());
}
INSTANTIATE_TEST_SUITE_P(AllFamilies, SocketMultiProtocolInetLoopbackTest,
ProtocolTestValues(), DescribeProtocolTestParam);
} // namespace
// Check that loopback receives connections from any address in the range:
// 127.0.0.1 to 127.254.255.255. This behavior is exclusive to IPv4.
TEST_F(SocketInetLoopbackTest, LoopbackAddressRangeConnect) {
TestAddress const& listener = V4Any();
in_addr_t addresses[] = {
INADDR_LOOPBACK,
INADDR_LOOPBACK + 1, // 127.0.0.2
(in_addr_t)0x7f000101, // 127.0.1.1
(in_addr_t)0x7f010101, // 127.1.1.1
(in_addr_t)0x7ffeffff, // 127.254.255.255
};
for (const auto& address : addresses) {
TestAddress connector("V4Loopback");
connector.addr.ss_family = AF_INET;
connector.addr_len = sizeof(sockaddr_in);
reinterpret_cast<sockaddr_in*>(&connector.addr)->sin_addr.s_addr =
htonl(address);
tcpSimpleConnectTest(listener, connector, true);
}
}
} // namespace testing
} // namespace gvisor
| [
"fuchsia-internal-scoped@luci-project-accounts.iam.gserviceaccount.com"
] | fuchsia-internal-scoped@luci-project-accounts.iam.gserviceaccount.com |
2e849647259c6c4174f76ec09406d7767ddb1ad5 | dcf535c491af36d04f8d6869e6f50ed19c17a650 | /src/process/PosixSpawnFileActions.cpp | 9e8789cd2f8b162617eb5e7a35acf55b45475169 | [
"Apache-2.0",
"MIT",
"BSD-3-Clause",
"BSL-1.0",
"LicenseRef-scancode-public-domain",
"BSD-2-Clause"
] | permissive | jiaoxie83847573p/epcblock | c786cc1568e8a45034fd676187e492fe621f1d09 | 12a2430b4a7ec554aa810127475fe32a711603a2 | refs/heads/master | 2020-03-21T15:23:05.633174 | 2018-06-26T09:58:18 | 2018-06-26T09:58:18 | 138,709,198 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,693 | cpp | // Copyright 2018 epc Development Foundation and contributors. Licensed
// under the Apache License, Version 2.0. See the COPYING file at the root
// of this distribution or at http://www.apache.org/licenses/LICENSE-2.0
#ifndef _WIN32
#include "process/PosixSpawnFileActions.h"
#include "util/Logging.h"
#include <cassert>
#include <errno.h>
namespace epc
{
PosixSpawnFileActions::~PosixSpawnFileActions()
{
if (mInitialized)
{
if (auto err = posix_spawn_file_actions_destroy(&mFileActions))
{
CLOG(ERROR, "Process")
<< "posix_spawn_file_actions_destroy() failed: "
<< strerror(err);
}
}
}
void
PosixSpawnFileActions::initialize()
{
if (mInitialized)
{
return;
}
if (auto err = posix_spawn_file_actions_init(&mFileActions))
{
CLOG(ERROR, "Process")
<< "posix_spawn_file_actions_init() failed: " << strerror(err);
throw std::runtime_error("posix_spawn_file_actions_init() failed");
}
mInitialized = true;
}
void
PosixSpawnFileActions::addOpen(int fildes, std::string const& fileName,
int oflag, mode_t mode)
{
assert(!fileName.empty());
initialize();
if (auto err = posix_spawn_file_actions_addopen(
&mFileActions, fildes, fileName.c_str(), oflag, mode))
{
CLOG(ERROR, "Process")
<< "posix_spawn_file_actions_addopen() failed: " << strerror(err);
throw std::runtime_error("posix_spawn_file_actions_addopen() failed");
}
}
PosixSpawnFileActions::operator posix_spawn_file_actions_t*()
{
return mInitialized ? &mFileActions : nullptr;
}
}
#endif
| [
"40593460+jiaoxie83847573p@users.noreply.github.com"
] | 40593460+jiaoxie83847573p@users.noreply.github.com |
a5260691777c1ddacaf6544601cdaf0659545036 | b7b4989dd1a86084f9dc71b0371e19861f71b092 | /solve_line_eq_funct_nocin.cpp | 0fadab1174c037c0e90b1c7d2e5a9ad4c6d179f9 | [] | no_license | jeaimehp/ISP-src | aa4c8d10b6bc23d6d2fbbc59def0936b94c02e46 | b29e9651b0ffe6cacdbbf6cfed487d251e4f7d08 | refs/heads/master | 2021-05-03T12:42:01.390088 | 2018-09-19T13:52:28 | 2018-09-19T13:52:28 | 120,500,117 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 638 | cpp | /*
* Program Author: Jeaime Powell
* Program Name: Solve for Y
* Program Function: Solves for Y in y = mx+b
* Created: 2018-01-31
*/
#include <iostream>
using std::cin;
using std::cout;
using std::endl;
float eq_line (int x, float m, int b);
int main ()
{
int point_x = 2, yintercept_b = 1;
float slope_m = .3, point_y;
point_y = eq_line(point_x, slope_m, yintercept_b);
cout << point_y << " = (" << slope_m << "*" << point_x << ") + " << yintercept_b << endl;
}
float eq_line (int x, float m, int b)
{
float y;
y = m * x + b;
return y;
}
| [
"jeaimehp@gmail.com"
] | jeaimehp@gmail.com |
4bb30feec936152b74ca5f226937d1b31af8932f | 337e351f12c583c6c86e6a8e7d6edeb0e0a43107 | /C++/RecordingAudioSolution/winrt/impl/Windows.Globalization.Fonts.0.h | 2a97fb8358f4e5f9770234c99df2dbb7980b319f | [] | no_license | dngoins/HololensDXTutorials | de7d3ba8f25f633557b98f51828ac73d671266a4 | 532907a7be6005e9f3483e26727324b3392c02f3 | refs/heads/master | 2020-04-02T06:11:29.362302 | 2018-10-27T21:16:03 | 2018-10-27T21:16:03 | 64,985,100 | 30 | 5 | null | 2016-10-01T00:17:51 | 2016-08-05T03:16:10 | C++ | UTF-8 | C++ | false | false | 6,483 | h | // C++/WinRT v1.0.171013.2
// Copyright (c) 2017 Microsoft Corporation. All rights reserved.
#pragma once
WINRT_EXPORT namespace winrt::Windows::UI::Text {
enum class FontStretch;
enum class FontStyle;
struct FontWeight;
}
WINRT_EXPORT namespace winrt::Windows::Globalization::Fonts {
struct ILanguageFont;
struct ILanguageFontGroup;
struct ILanguageFontGroupFactory;
struct LanguageFont;
struct LanguageFontGroup;
}
namespace winrt::impl {
template <> struct category<Windows::Globalization::Fonts::ILanguageFont>{ using type = interface_category; };
template <> struct category<Windows::Globalization::Fonts::ILanguageFontGroup>{ using type = interface_category; };
template <> struct category<Windows::Globalization::Fonts::ILanguageFontGroupFactory>{ using type = interface_category; };
template <> struct category<Windows::Globalization::Fonts::LanguageFont>{ using type = class_category; };
template <> struct category<Windows::Globalization::Fonts::LanguageFontGroup>{ using type = class_category; };
template <> struct name<Windows::Globalization::Fonts::ILanguageFont>{ static constexpr auto & value{ L"Windows.Globalization.Fonts.ILanguageFont" }; };
template <> struct name<Windows::Globalization::Fonts::ILanguageFontGroup>{ static constexpr auto & value{ L"Windows.Globalization.Fonts.ILanguageFontGroup" }; };
template <> struct name<Windows::Globalization::Fonts::ILanguageFontGroupFactory>{ static constexpr auto & value{ L"Windows.Globalization.Fonts.ILanguageFontGroupFactory" }; };
template <> struct name<Windows::Globalization::Fonts::LanguageFont>{ static constexpr auto & value{ L"Windows.Globalization.Fonts.LanguageFont" }; };
template <> struct name<Windows::Globalization::Fonts::LanguageFontGroup>{ static constexpr auto & value{ L"Windows.Globalization.Fonts.LanguageFontGroup" }; };
template <> struct guid<Windows::Globalization::Fonts::ILanguageFont>{ static constexpr GUID value{ 0xB12E5C3A,0xB76D,0x459B,{ 0xBE,0xEB,0x90,0x11,0x51,0xCD,0x77,0xD1 } }; };
template <> struct guid<Windows::Globalization::Fonts::ILanguageFontGroup>{ static constexpr GUID value{ 0xF33A7FC3,0x3A5C,0x4AEA,{ 0xB9,0xFF,0xB3,0x9F,0xB2,0x42,0xF7,0xF6 } }; };
template <> struct guid<Windows::Globalization::Fonts::ILanguageFontGroupFactory>{ static constexpr GUID value{ 0xFCAEAC67,0x4E77,0x49C7,{ 0xB8,0x56,0xDD,0xE9,0x34,0xFC,0x73,0x5B } }; };
template <> struct default_interface<Windows::Globalization::Fonts::LanguageFont>{ using type = Windows::Globalization::Fonts::ILanguageFont; };
template <> struct default_interface<Windows::Globalization::Fonts::LanguageFontGroup>{ using type = Windows::Globalization::Fonts::ILanguageFontGroup; };
template <typename D>
struct consume_Windows_Globalization_Fonts_ILanguageFont
{
hstring FontFamily() const noexcept;
Windows::UI::Text::FontWeight FontWeight() const noexcept;
Windows::UI::Text::FontStretch FontStretch() const noexcept;
Windows::UI::Text::FontStyle FontStyle() const noexcept;
double ScaleFactor() const noexcept;
};
template <> struct consume<Windows::Globalization::Fonts::ILanguageFont> { template <typename D> using type = consume_Windows_Globalization_Fonts_ILanguageFont<D>; };
template <typename D>
struct consume_Windows_Globalization_Fonts_ILanguageFontGroup
{
Windows::Globalization::Fonts::LanguageFont UITextFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont UIHeadingFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont UITitleFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont UICaptionFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont UINotificationHeadingFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont TraditionalDocumentFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont ModernDocumentFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont DocumentHeadingFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont FixedWidthTextFont() const noexcept;
Windows::Globalization::Fonts::LanguageFont DocumentAlternate1Font() const noexcept;
Windows::Globalization::Fonts::LanguageFont DocumentAlternate2Font() const noexcept;
};
template <> struct consume<Windows::Globalization::Fonts::ILanguageFontGroup> { template <typename D> using type = consume_Windows_Globalization_Fonts_ILanguageFontGroup<D>; };
template <typename D>
struct consume_Windows_Globalization_Fonts_ILanguageFontGroupFactory
{
Windows::Globalization::Fonts::LanguageFontGroup CreateLanguageFontGroup(param::hstring const& languageTag) const;
};
template <> struct consume<Windows::Globalization::Fonts::ILanguageFontGroupFactory> { template <typename D> using type = consume_Windows_Globalization_Fonts_ILanguageFontGroupFactory<D>; };
template <> struct abi<Windows::Globalization::Fonts::ILanguageFont>{ struct type : ::IInspectable
{
virtual HRESULT __stdcall get_FontFamily(HSTRING* value) = 0;
virtual HRESULT __stdcall get_FontWeight(struct_of<2>* weight) = 0;
virtual HRESULT __stdcall get_FontStretch(Windows::UI::Text::FontStretch* stretch) = 0;
virtual HRESULT __stdcall get_FontStyle(Windows::UI::Text::FontStyle* style) = 0;
virtual HRESULT __stdcall get_ScaleFactor(double* scale) = 0;
};};
template <> struct abi<Windows::Globalization::Fonts::ILanguageFontGroup>{ struct type : ::IInspectable
{
virtual HRESULT __stdcall get_UITextFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_UIHeadingFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_UITitleFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_UICaptionFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_UINotificationHeadingFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_TraditionalDocumentFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_ModernDocumentFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_DocumentHeadingFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_FixedWidthTextFont(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_DocumentAlternate1Font(::IUnknown** value) = 0;
virtual HRESULT __stdcall get_DocumentAlternate2Font(::IUnknown** value) = 0;
};};
template <> struct abi<Windows::Globalization::Fonts::ILanguageFontGroupFactory>{ struct type : ::IInspectable
{
virtual HRESULT __stdcall CreateLanguageFontGroup(HSTRING languageTag, ::IUnknown** recommendedFonts) = 0;
};};
}
| [
"dngoins@hotmail.com"
] | dngoins@hotmail.com |
203da56f4fe2dabe0f8309b8345717b4cb4e087a | 96e934a15f8ccb08ed05b8f28e85018d091aa3ed | /Win32/PETool/StdAfx.cpp | 48fa1baa5076b132f30063407fafd9750a3d9b30 | [] | no_license | EricDoReMi/NoteBook | a0794ab4461f4fc1f702c2dbd930b9ba74927790 | faa8b21f2af54bc123334eb7ffcad048750534ba | refs/heads/master | 2021-05-08T04:38:50.435463 | 2019-05-21T05:50:54 | 2019-05-21T05:50:54 | 108,415,852 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 285 | cpp | // stdafx.cpp : source file that includes just the standard includes
// PETool.pch will be the pre-compiled header
// stdafx.obj will contain the pre-compiled type information
#include "StdAfx.h"
// TODO: reference any additional headers you need in STDAFX.H
// and not in this file
| [
"shimaorun@163.com"
] | shimaorun@163.com |
809bf12e0bfabe618a807bf4110ec1709672a664 | 50d462c448b6e4e7f4ec6243d7d039c8d860216e | /ncurses/window.cpp | 7bb44b993fdefbb67b289d9900bf3587caf82d21 | [] | no_license | lflxp/leetcode | 54abe6991482c7edb7acc1e103b07415dbbdc5f1 | 550d0d09f767141258bcdef13430048e2d45da06 | refs/heads/master | 2020-05-02T22:59:57.253697 | 2019-11-26T16:21:02 | 2019-11-26T16:21:02 | 178,269,572 | 3 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,393 | cpp | #include <ncurses.h>
WINDOW *create_newwin(int height, int width, int starty, int startx);
void destroy_win(WINDOW *local_win);
int main(int argc, char *argv[])
{
WINDOW *my_win;
int startx, starty, width, height;
int ch;
initscr();
cbreak();
keypad(stdscr, TRUE); /* 程序需要使用F1 功能键*/
height = 3;
width = 10;
starty =0
/ 2; /*计算窗口中心位置的行数*/
startx = 0
/ 2; /*计算窗口中心位置的列数*/
printw("Press F1 to exit");
refresh();
my_win = create_newwin(height, width, starty, startx);
while((ch = getch()) != KEY_F(1))
{ switch(ch)
{ case KEY_LEFT:
destroy_win(my_win);
my_win = create_newwin(height, width, starty,startx);
break;
case KEY_RIGHT:
destroy_win(my_win);
my_win = create_newwin(height, width, starty,++startx);
break;
case KEY_UP:
destroy_win(my_win);
my_win = create_newwin(height, width, starty,startx);
break;
case KEY_DOWN:
destroy_win(my_win);
my_win = create_newwin(height, width, ++starty,startx);
break;
}
}
endwin(); /*结束curses 模式*/
return 0;
}
WINDOW *create_newwin(int height, int width, int starty, int startx)
{
WINDOW *local_win;
local_win = newwin(height, width, starty, startx);
box(local_win, 0 , 0); /* 0, 0 是字符默认的行列起始位置*/
wrefresh(local_win); /*刷新窗口缓冲,显示box */
return local_win;
}
void destroy_win(WINDOW *local_win)
{/* box(local_win, ' ', ' ');不会按照预期的那样清除窗口边框。而是在窗口的四个角落留下残
余字符*/
wborder(local_win, '|', '|', ' ', ' ', '+', '+', '+', '+');
/*参数注解9.3:
* 1. win:当前操作的窗口
* 2. ls:用于显示窗口左边界的字符
* 3. rs:用于显示窗口右边界的字符
* 4. ts:用于显示窗口上边界的字符
* 5. bs:用于显示窗口下边界的字符
NCURSES Programming HOWTO 中文版(第二版)
29
* 6. tl:用于显示窗口左上角的字符
* 7. tr:用于显示窗口右上角的字符
* 8. bl:用于显示窗口左下角的字符
* 9. br:用于显示窗口右下角的字符
*/
wrefresh(local_win);
delwin(local_win);
}
| [
"lxp@lflxp.cn"
] | lxp@lflxp.cn |
ccb01dcdc0e8cd4e544155185828d86e4376518d | 938495d61712257f36cfeaa36f4380a760930047 | /sukmig1.cpp | ee1167dd046b56e8be295da5f898c9af0c74618e | [] | no_license | chaoshunh/seismic_unix | cec401f04e77c8dd6caf93e8cbac000a7ea15794 | c975332d5fab748d5f42ed8225e9f878def7d76a | refs/heads/master | 2022-11-06T18:22:16.105316 | 2020-06-26T16:52:43 | 2020-06-26T16:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,750 | cpp | /* Copyright (c) University of British Columbia, 1999.*/
/* All rights reserved. */
/* SUKMIG: $Date: March 1999 */
#include "su.h"
#include "segy.h"
#include "clibrarytd.h"
/*********************** self documentation **********************/
char *sdoc[] = {
" ",
" SUKMIG0 - First attempt for Kirchhoff migration ",
" ",
" ",
" sukmig0 < stdin > stdout [optional parameters] ",
" ",
" cdpmin=0 Fisrt CDP in meters ",
" cdpmax=100 Last CDP ",
" vel=2000 Velocity of migration (in meters) ",
" ",
NULL};
/* Credits:
* Daniel Trad.
* Trace header fields accessed: ns, cdp, dt, offset
/**************** end self doc ***********************************/
segy tr,trf; // for malloc use *trr
void kmig1(float *d, float cdp, float h, float **m, float *t, float *x, float vel) ;
void rjwfilter(float **d,int nt,int nh, float dt);
void filt(float *trace,int nt,float dt,float fmax,int ls,int m,float *trf);
int nt,nh,nx; // Size of volume x,h,t
float dt,dh,dx; // Sampling
int main(int argc, char **argv)
{
int j,i, k, ix;
register int it;
float *d, **m;
float *x, *t, h, cdp, vel, cdpmin, cdpmax;
extern int nt, nh, nx;
extern float dt,dh,dx;
const double pi=acos(-1.);
float fmax;
// Initialize
initargs(argc, argv);
requestdoc(1);
// Get parameters
if (!getparfloat("vel", &vel)) vel = 2000;
if (!getparfloat("cdpmin", &cdpmin)) cdpmin = 0;
if (!getparfloat("cdpmax", &cdpmax)) cdpmax = 1000;
if (!getparint("nx", &nx)) nx = 100;
// Get info from first trace
if (!gettr(&tr)) err("can't read first trace");
if (!tr.dt) err("dt header field must be set");
if (!tr.ns) err("ns header field must be set");
dt = ((float) tr.dt)/1000000.0;
nt = (int) tr.ns;
fmax=0.8/(2*dt);
fprintf(stderr,"nt=%d,dt=%f,nx=%d,vel=%f,fmax=%f\n",nt,dt,nx,vel,fmax);
// Allocate memory for data and model
if ((d=ealloc1float(nt))==NULL)
fprintf(stderr,"***Sorry, space for d could not be allocated\n");
if ((m=ealloc2float(nx,nt))==NULL)
fprintf(stderr,"***Sorry, space for m could not be allocated\n");
if ((x=ealloc1float(nx))==NULL)
fprintf(stderr,"***Sorry, space for x could not be allocated\n");
if ((t=ealloc1float(nt))==NULL)
fprintf(stderr,"***Sorry, space for t could not be allocated\n");
dx=(cdpmax-cdpmin)/(nx-1);
for(ix=0;ix<nx;ix++) x[ix]=cdpmin+dx*ix;
for(it=0;it<nt;it++) t[it]=it*dt;
fprintf(stderr,"**************************\n");
for (ix=0;ix<nx;ix++) for (it=0;it<nt;it++) m[it][ix]=0; // Output trace
j=0;
do { // Loop over traces
j++;
//fprintf(stderr,"j=%d,tr.cdp=%d\n",j,tr.cdp);
h=(float) tr.offset;
h/=2; // halfoffset
cdp=(float) tr.cdp;
// SU phase shift filter and lowpass filter
filt(tr.data,nt,dt,fmax,0,50,trf.data);
for (it=0;it<nt;it++)
d[it]=(float) tr.data[it];
kmig1(d,cdp,h,m,t,x,vel);
}while (gettr(&tr));
//for (ix=0;ix<nx;ix++)
// for (it=0;it<nt;it++)
// m[it][ix]/=(vel*sqrt(pi*MAX(t[it],1e-3)));
//rjwfilter(m,nt,nx,dt); // My phase shift filter
for (ix=0;ix<nx;ix++){
for (it=0;it<nt;it++)
tr.data[it]=m[it][ix];
tr.cdp=(int) x[ix];
tr.dt=(int) (dt*1e6);
tr.ntr=nx;
tr.ns=nt;
tr.tracl=ix;
tr.tracr=ix;
tr.offset=0;
tr.sx=(int) x[ix];
tr.gx=(int) x[ix];
puttr(&tr);
}
free1float(t);
free1float(x);
free2float(m);
free1float(d);
return EXIT_SUCCESS;
}
| [
"danielotrad@gmail.com"
] | danielotrad@gmail.com |
a56262eaa7a12102a09965af3a28e8ee9dc13762 | 0ad2c3c5df37f3432156168b520abad9fc19dc26 | /Jogos/jogoDaVelha/jogo_da_velha_2.cpp | 42c08baca86d16bc8aba99a7b951f1507016bb78 | [
"MIT"
] | permissive | Renanvt/Curso_de_C_e_CPlusPlus | 33a87be387fd08f00b75cfd71d1fe6f90a93d32b | d6b5e3341b5f65961f9b0e19291dd6ed307c6f21 | refs/heads/master | 2023-02-17T06:16:21.654338 | 2021-01-13T16:30:09 | 2021-01-13T16:30:09 | 263,964,040 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 7,462 | cpp | #include <stdio.h>
#include <stdlib.h>
#include <string>
#include <iostream>
using namespace std;
//Área de definição de cabeçalhos de função
void menuInicial();
void limpaTela(){
system("CLS");
}
void iniciaTabuleiro(char tabuleiro[3][3]){
//Navega por cada posição do tabuleiro e coloca o símbolo de '-'
int linha,coluna;
for(linha = 0; linha < 3; linha++){
for(coluna = 0; coluna < 3; coluna++){
tabuleiro[linha][coluna] = '-';
}
}
}
void exibeTabuleiro (char tabuleiro[3][3]){
//Exibe o tabuleiro com suas linhas e colunas quebrando a linha ao sair de um for
int linha,coluna;
cout << "\n";
for(linha = 0; linha < 3; linha++){
for(coluna = 0; coluna < 3; coluna++){
cout << tabuleiro[linha][coluna];
}
cout << "\n";
}
}
//1 = X venceu, 2 = O venceu, 0 = Nada Aconteceu
int confereTabuleiro(char tabuleiro[3][3]){
int linha, coluna;
//Confere linhas
for(linha = 0; linha < 3; linha++){
if(tabuleiro[linha][0] == 'X' && tabuleiro[linha][0] == tabuleiro[linha][1] && tabuleiro[linha][1] == tabuleiro[linha][2]){
return 1;
}else if(tabuleiro[linha][0] == 'O' && tabuleiro[linha][0] == tabuleiro[linha][1] && tabuleiro[linha][1] == tabuleiro[linha][2]){
return 2;
}
}
//Confere Colunas
for(coluna = 0; coluna < 3; coluna++){
if(tabuleiro[0][coluna] == 'X' && tabuleiro[0][coluna] == tabuleiro[1][coluna] && tabuleiro[1][coluna] == tabuleiro[2][coluna]){
return 1;
}else if(tabuleiro[0][coluna] == 'O' && tabuleiro[0][coluna] == tabuleiro[1][coluna] && tabuleiro[1][coluna] == tabuleiro[2][coluna]){
return 2;
}
}
//Diagonal Principal
if(tabuleiro[0][0] != '-' && tabuleiro[0][0] == tabuleiro[1][1] && tabuleiro[1][1] == tabuleiro[2][2]){
if(tabuleiro[0][0] == 'X'){
return 1;
}else{
return 2;
}
}
//Diagonal Secundária
if(tabuleiro[0][2] != '-' && tabuleiro[0][2] == tabuleiro[1][1] && tabuleiro[1][1] == tabuleiro[2][0]){
if(tabuleiro[0][2] == 'X'){
return 1;
}else{
return 2;
}
}
return 0;
}
void exibeInstrucoes(){
cout << "\nMapa de Posicoes:";
cout << "\n 7 | 8 | 9";
cout << "\n 4 | 5 | 6";
cout << "\n 1 | 2 | 3";
}
void jogo(string nomeDoJogadorUm, string nomeDoJogadorDois, int pontuacaoJogadorUm, int pontuacaoJogadorDois){
///Variáveis Gerais
string nomeDoJogadorAtual;//Nomes dos jogadores
char tabuleiro[3][3]; //Tabuleiro do Jogo
int linha,coluna; //Auxiliares para tabuleiro
int linhaJogada,colunaJogada,posicaoJogada; //Posição em que o jogador posiciona sua marca
int estadoDeJogo = 1; //0 = Sem jogo,1 = Em Jogo
int turnoDoJogador = 1; //1 = X, 2 = O
int rodada = 0; //Quantas vezes os jogadores jogaram no total
int opcao; //Opção de reinício
bool posicionouJogada; //Verifica se o jogador colocou um marcador no tabuleiro
//Coloca os '-' no tabuleiro para indicar o vazio
iniciaTabuleiro(tabuleiro);
while(rodada < 9 && estadoDeJogo == 1){
limpaTela();
cout << "\nRodada:" << rodada << "\n";
cout << "Pontuacao:" << nomeDoJogadorUm << " " << pontuacaoJogadorUm << " x " << pontuacaoJogadorDois << " " << nomeDoJogadorDois;
//Exibe o tabuleiro na tela
exibeTabuleiro(tabuleiro);
//Exibe qual numero corresponde a qual posicao
exibeInstrucoes();
//Atualiza o nome do jogador atual
if(turnoDoJogador == 1){
nomeDoJogadorAtual = nomeDoJogadorUm;
}else{
nomeDoJogadorAtual = nomeDoJogadorDois;
}
posicionouJogada = false;
//Matriz de posicoes possíveis
int posicoes[9][2] = {{2,0},{2,1},{2,2},{1,0},{1,1},{1,2},{0,0},{0,1},{0,2}};
while(posicionouJogada == false){
//Lê a jogada
cout << "\n" << nomeDoJogadorAtual << "Digite uma posicao conforme o mapa acima:";
cin >> posicaoJogada;
//Passa a linha e coluna de acordo com a matriz de posições exibida no mapa
linhaJogada = posicoes[posicaoJogada-1][0];
colunaJogada = posicoes[posicaoJogada-1][1];
//Verifica se a posição é vazia
if(tabuleiro[linhaJogada][colunaJogada] == '-'){
//Conseguiu posicionar um marcador
posicionouJogada = true;
//Verifica de quem é a vez para posicionar o marcador
if(turnoDoJogador == 1){
tabuleiro[linhaJogada][colunaJogada] = 'X';
turnoDoJogador = 2;
}else{
tabuleiro[linhaJogada][colunaJogada] = 'O';
turnoDoJogador = 1;
}
}
}
//Confere se o jogo acabou
if(confereTabuleiro(tabuleiro) == 1){
cout << "\nO jogador X venceu";
pontuacaoJogadorUm++;
estadoDeJogo = 0;
}else if(confereTabuleiro(tabuleiro) == 2){
cout << "O jogador O venceu";
pontuacaoJogadorDois++;
estadoDeJogo = 0;
}
//Aumenta uma rodada
rodada++;
}
exibeTabuleiro(tabuleiro);
cout << "Fim de jogo";
cout << "\nO que deseja fazer?";
cout << "\n1-Continuar Jogando";
cout << "\n2-Menu Inicial";
cout << "\n3-Sair";
cin >> opcao;
if(opcao == 1){
jogo(nomeDoJogadorUm, nomeDoJogadorDois,pontuacaoJogadorUm,pontuacaoJogadorDois);
}else if(opcao == 2){
menuInicial();
}
}
void menuInicial(){
//Nome dos jogadores
string nomeDoJogadorUm, nomeDoJogadorDois;
//Opção escolhida pelo usuário
int opcao = 0;
//Enquanto o jogador não digita uma opcao válida, mostra o menu novamente
while(opcao < 1 || opcao > 3){
cout << "Bem vindo ao Jogo da Velha";
cout << "\n1 - Jogar";
cout << "\n2 - Sobre";
cout << "\n3 - Sair";
cout << "\nEscolha uma opcao e tecle ENTER:";
//Faz a leitura da opcao
cin >> opcao;
limpaTela();
//Faz algo de acordo com a opcao escolhida
switch(opcao){
case 1:
//Inicia o jogo
//cout << "Jogo iniciado";
cout << "Digite o nome do jogador 1:\n";
cin >> nomeDoJogadorUm;
cout << "Digite o nome do jogador 2:\n";
cin >> nomeDoJogadorDois;
jogo(nomeDoJogadorUm, nomeDoJogadorDois,0,0);
break;
case 2:
//Mostra informacoes do Jogo
cout << "Informacoes do jogo";
break;
case 3:
cout << "Ate mais!";
break;
}
}
}
int main(){
menuInicial();
return 0;
}
| [
"jonatan_rvs@hotmail.com"
] | jonatan_rvs@hotmail.com |
42e6a7f529562f291983c5fa85542fcbbb99f944 | 8f50c262f89d3dc4f15f2f67eb76e686b8f808f5 | /Control/PerformanceMonitoring/PerfMonTests/src/PerfMonTestLeakyAlg.h | 6e16112d8890b8005911f79186a039be4d24c47c | [
"Apache-2.0"
] | permissive | strigazi/athena | 2d099e6aab4a94ab8b636ae681736da4e13ac5c9 | 354f92551294f7be678aebcd7b9d67d2c4448176 | refs/heads/master | 2022-12-09T02:05:30.632208 | 2020-09-03T14:03:18 | 2020-09-03T14:03:18 | 292,587,480 | 0 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,273 | h | ///////////////////////// -*- C++ -*- /////////////////////////////
/*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// PerfMonTestLeakyAlg.h
// Header file for class PerfMonTest::LeakyAlg
// Author: S.Binet<binet@cern.ch>
///////////////////////////////////////////////////////////////////
#ifndef PERFMONTESTS_PERFMONTESTLEAKYALG_H
#define PERFMONTESTS_PERFMONTESTLEAKYALG_H
// STL includes
#include <string>
#include <list>
#include <vector>
// FrameWork includes
#include "AthenaBaseComps/AthAlgorithm.h"
#include "GaudiKernel/ServiceHandle.h"
namespace PerfMonTest {
class LeakyAlg : public AthAlgorithm
{
///////////////////////////////////////////////////////////////////
// Public methods:
///////////////////////////////////////////////////////////////////
public:
// Copy constructor:
/// Constructor with parameters:
LeakyAlg( const std::string& name, ISvcLocator* pSvcLocator );
/// Destructor:
virtual ~LeakyAlg();
// Assignment operator:
//LeakyAlg &operator=(const LeakyAlg &alg);
// Athena algorithm's Hooks
virtual StatusCode initialize();
virtual StatusCode execute();
virtual StatusCode finalize();
///////////////////////////////////////////////////////////////////
// Const methods:
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// Non-const methods:
///////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////
// Private data:
///////////////////////////////////////////////////////////////////
private:
/// Default constructor:
LeakyAlg();
/// Property to setup the size of the leak
int m_leakSize;
struct Leak {
std::vector<int> m_data;
};
/// nbr of Leak objects
int m_nbrLeaks;
/// container to hold the leaked objects
std::list<Leak*> m_leaks;
};
// I/O operators
//////////////////////
///////////////////////////////////////////////////////////////////
// Inline methods:
///////////////////////////////////////////////////////////////////
} //> end namespace PerfMonTest
#endif //> PERFMONTESTS_PERFMONTESTLEAKYALG_H
| [
"graemes.cern@gmail.com"
] | graemes.cern@gmail.com |
0d2d840f8ba0049c93645f82f08b23f6af3ff33b | 83cac28fdb540e9cd23770136e898d848699466e | /lib/c++/src/mmglm_spd_multithread_fast.cpp | d147a18bf7cf0b4754549dd641b1a558d3cf5a57 | [
"MIT"
] | permissive | MLman/MMGLM_HTCONDOR | 79c191767c978a76ce84e6cf657da79124d5c467 | 8a9b5fcbda4bccd9167eb03dd6977b515cda91cf | refs/heads/master | 2020-06-14T04:45:55.487250 | 2017-05-23T20:59:11 | 2017-05-23T20:59:11 | 75,233,692 | 0 | 1 | null | 2017-05-23T20:59:12 | 2016-11-30T22:43:06 | Matlab | UTF-8 | C++ | false | false | 5,517 | cpp | //============================================================================
// Name : legr_core.cpp
// Author : Hyunwoo J. Kim
// : Anmol Mohanty
// Version : 0.5
// Date : 2016/07/06 13:05:35 (CDT)
// Copyright :
// Description :
//============================================================================
#include <armadillo>
#include <iostream>
#include <boost/filesystem.hpp>
#include <boost/filesystem/operations.hpp>
#include <boost/filesystem/path.hpp>
#include <fstream>
#include <omp.h>
#include <unistd.h>
#include "spd_funcs.h"
#include "mmglm_spd.h"
#define DIM_DTI 6
// Index of elements in save files
#define iDxx 0
#define iDxy 1
#define iDxz 2
#define iDyy 3
#define iDyz 4
#define iDzz 5
using namespace std;
//using namespace arma; //for the armadillo library, this is separate from boost
namespace fs=boost::filesystem; //namespace is being declared
int main(int argc, char** argv)
{
//creating 3 paths named below
fs::path input_dir;
fs::path shared_dir;
fs::path result_fname;
unsigned logicalcpucount ;
logicalcpucount = sysconf( _SC_NPROCESSORS_ONLN);
int nthreads;
printf("################################################\n");
printf("### MMGLM_SPD_PAR ###\n");
printf("################################################\n");
printf("\n The number of cups is %d. \n",logicalcpucount);
if(argc == 1 || argc >=6){
cout<<"\n MMGLM_SPD_PAR performs MMGLMs on SPDs. " <<endl;
cout<<" P_values are the significance for the last covariate controlling\n";
cout<<" for all covariates except the _last_ one in \"Xs_arma.mat\"." <<endl<<endl;
cout<<" Usage: " <<endl;
cout<<" >>> mmglm_spd_par $input_dir $shared_dir"
" ($result_fname==p_value.txt)" << endl;
cout<<" >>> mmglm_spd_par $input_dir $shared_dir $result_fname " << endl;
cout<<" >>> mmglm_spd_par $input_dir $shared_dir $result_fname $num_threads" << endl;
cout<<"\n ### Requirements ### "<<endl;
cout<<"\n $input_dir/Ys_arma.mat\n $input_dir/mask_job_arma.mat\n"
" $shared_dir/Xs_arma.mat \n $shared_dir/idx_perm_arma.mat" << endl<<endl;
return 1;
}
if(argc >= 2){
input_dir = argv[1]; // Results will be written in input_dir, too.
shared_dir = "./";
}
if(argc >= 3){
shared_dir = argv[2];
}
if(argc >= 4){
result_fname = argv[3];
}else{
result_fname="p_value.txt";
}
if(argc >=5){
nthreads = atoi(argv[4]);
}else{
nthreads = logicalcpucount;
}
printf("\n The number of threads for OMP is set to %d. \n",nthreads);
omp_set_num_threads(nthreads);
arma::mat X; //declaring a matrix armadillo code || Armadillo API
arma::mat Yv;
fs::path Xname = "Xs_arma.mat";
X.load((shared_dir/Xname).string(), raw_ascii); //load into the variable X
fs::path cur_dir(fs::current_path());
fs::path Yname = "Ys_arma.mat";
Yv.load((input_dir/Yname).string(),raw_ascii); // load into vY
// Convert into cube
unsigned int nsubjects = Yv.n_cols;
cube Y(3,3,nsubjects);
arma::imat idx_dti;
fs::path idx_name = "idx_perm_arma.mat";
idx_dti.load((shared_dir/idx_name).string(), raw_ascii);
float nperms = idx_dti.n_rows;
arma::imat mask_job;
fs::path maskname = "mask_job_arma.mat";
mask_job.load((input_dir/maskname).string(),raw_ascii);
unsigned int nvoxels = mask_job.n_rows;
unsigned int dimX = X.n_rows;
arma::mat ErrMx1(nvoxels, nperms);
arma::mat ErrMx2(nvoxels, nperms);
ErrMx1 = ErrMx1.zeros(); //initialize
ErrMx2 = ErrMx2.zeros();
// #pragma omp parallel for shared(ErrMx1, ErrMx2)
// #pragma omp parallel
// {
// #pragma omp for nowait
// #pragma omp for
#pragma omp parallel for
for(unsigned int ivoxel = 0; ivoxel < nvoxels; ivoxel++){
getY(Y,Yv,ivoxel);
//generalize this one
mmglm_spd_perm(ErrMx1, X.rows(0,dimX-2), Y, idx_dti,ivoxel);
mmglm_spd_perm(ErrMx2, X, Y, idx_dti,ivoxel);
}
// }
//difference/improvement in the errors
arma::mat ErrMxfinal = ErrMx1-ErrMx2;
//creates a p_value vector of type float for all voxels
float *p_value=(float*)malloc(nvoxels*sizeof(float));
unsigned int ivoxel;
#pragma omp parallel for
for(ivoxel = 0; ivoxel < nvoxels; ivoxel++){
unsigned int count=0;
size_t length=nperms;
// What's the last element?
while(--length){
if(ErrMxfinal(ivoxel,length)>ErrMxfinal(ivoxel,0))
count++; //find out values greater than ref value
}
p_value[ivoxel]= count/nperms; //typecasting
}
//Writing the p_value vector to a .txt file.
//Alternately armabinascii maybe used
//Checking if file exists and deletes it
if( remove( result_fname ) == 0 ) //file exists
perror( "File existed and has been cleaned up" );
//handle to the file
ofstream fout;
//opening an output stream for file p_value.txt
fout.open(result_fname.string().c_str());
//checking whether file could be opened or not.
//If file does not exist or don't have write permissions, file
//stream could not be opened.
if(fout.is_open()){
for(unsigned int i=0;i<nvoxels-1;i++){
fout << p_value[i]; //writing ith character of p_value in the file
fout <<"\n";
}
fout << p_value[nvoxels-1]; //To write no unnecessary newline char.
fout.close();
}else{
cout << "File could not be opened. Please try again" << endl;
return 1;
}
cout << "Finished" << endl;
return 0;
}
| [
"kimbellw@gmail.com"
] | kimbellw@gmail.com |
2b8ae6d86d3bcd7ae4c408e1fe9bf381c14cebd6 | 741dafeb834dbca0e58ca1b393cc5bf12ba0da13 | /cses/Edit Distance/main.cpp | facc08debf897d950f208240e61f97a6beaec2f1 | [] | no_license | HoangViet144/Competitive-Programming | 8c3a28f97b0de8ad9f501cbae9c0767d6a4b956f | 19e9472545a10379511af3cf64ad0d4c1305dd8c | refs/heads/master | 2021-07-15T14:11:45.515412 | 2020-11-09T01:45:54 | 2020-11-09T01:45:54 | 221,480,049 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,092 | cpp | #include <bits/stdc++.h>
#define FOR(i,a,b) for(long long i = (a); i < (b); i++)
#define FORD(i,a,b) for(int i = (a); i >= (b); i--)
#define REP(i,a) for(int i = 0; i < (a); i++)
#define REPD(i,a) for(int i = (a)-1; i >= 0; i--)
#define sz(a) (int)a.size()
#define ALL(a) a.begin(),a.end()
#define ii pair<int,int>
#define fi first
#define se second
#define ll long long
#define N 1e5
using namespace std;
int main()
{
string a,b;
cin>>a>>b;
int n= a.length(), m=b.length();
a=" "+a;
b=" "+b;
vector<vector<ll>> dp(2, vector<ll>(m+1,1e9));
for(int i=0;i<=n;i++) dp[i%2][0]=i;
for(int i=0;i<=m;i++) dp[0][i]=i;
for(int i=1;i<=n;i++)
{
for(int j=1;j<=m;j++)
dp[i%2][j]=1e9;
dp[i%2][0]=i;
for(int j=1;j<=m;j++)
{
//dp[i%2][j]=j;
if(a[i]==b[j])
dp[i%2][j] = min(dp[i%2][j],dp[(i-1)%2][j-1]);
else
dp[i%2][j] = min(dp[i%2][j], min(min(dp[i%2][j-1], dp[(i-1)%2][j-1]),dp[(i-1)%2][j])+1);
}
}
cout<<dp[n%2][m];
return 0;
}
| [
"viet14042000@gmail.com"
] | viet14042000@gmail.com |
edf57aab38b6dea5356b18adff11b28ae485fc33 | cb0fd7bd24243b0582f3d4ffb1826f839dd9f174 | /509.斐波那契数.cpp | 37ce9bcbfa5b807cf3672d1fef0772acf72c689d | [] | no_license | Maserhe/LeetCode | efde6e9e9e0eadc251c9e87d620986658acf4665 | 8bd29088d386df75ce4e3e0bad0a94d48799f435 | refs/heads/master | 2023-07-08T11:09:40.346412 | 2021-08-15T15:59:34 | 2021-08-15T15:59:34 | 279,108,901 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 265 | cpp | /*
* @lc app=leetcode.cn id=509 lang=cpp
*
* [509] 斐波那契数
*/
// @lc code=start
class Solution {
public:
int fib(int N) {
if (N == 0) return 0;
if (N == 1) return 1;
return fib(N - 1) + fib(N - 2);
}
};
// @lc code=end
| [
"982289931@qq.com"
] | 982289931@qq.com |
68c6f65593b42b142649a8ed4bf10572eacfc275 | 745c9c1dd7045b1d9025210b41353f5d7292d89d | /contour/NormalGrid.h | 0cb6fed57b1f081e280b94fcbce8efe81143a4da | [
"MIT"
] | permissive | fmidev/smartmet-engine-contour | 4a7c237cefbe9f02989f0b596900da1db23fafc3 | 3b06c801ec0efea35a2c8f57ec0a2546743de080 | refs/heads/master | 2023-09-01T19:38:07.733406 | 2023-08-28T05:30:15 | 2023-08-28T05:30:15 | 75,187,384 | 0 | 1 | MIT | 2021-08-31T05:03:34 | 2016-11-30T13:02:23 | C++ | UTF-8 | C++ | false | false | 1,929 | h | #pragma once
#include "BaseGrid.h"
#include <fmt/format.h>
#include <gis/BoolMatrix.h>
#include <gis/CoordinateMatrix.h>
#include <macgyver/Exception.h>
#include <newbase/NFmiDataMatrix.h>
#include <newbase/NFmiPoint.h>
#include <limits>
namespace SmartMet
{
namespace Engine
{
namespace Contour
{
// A Grid containing a regular matrix with only wraparound possibility
class NormalGrid : public BaseGrid
{
public:
NormalGrid() = delete;
NormalGrid(NFmiDataMatrix<float>& theMatrix,
const Fmi::CoordinateMatrix& theCoords,
const Fmi::BoolMatrix& theValidCells);
// Provide wrap-around capability for world data
double x(long i, long j) const override;
double y(long i, long j) const override;
float operator()(long i, long j) const override;
void set(long i, long j, float z) override { itsMatrix[i][j] = z; }
bool valid(long i, long j) const override { return itsValidCells(i, j); }
std::size_t width() const override { return itsWidth; }
std::size_t height() const override { return itsHeight; }
// We expand the grid by one cell in all directions to surround the data with missing values
std::array<long, 4> bbox() const override { return itsBBox; }
void smooth(std::size_t size, std::size_t degree) override;
private:
long mini() const { return itsBBox[0]; }
long minj() const { return itsBBox[1]; }
long maxi() const { return itsBBox[2]; }
long maxj() const { return itsBBox[3]; }
const Fmi::CoordinateMatrix& itsCoords;
const Fmi::BoolMatrix& itsValidCells;
NFmiDataMatrix<float>& itsMatrix;
const std::size_t itsNX; // data width
const std::size_t itsWidth; // cordinates width
const std::size_t itsHeight;
std::array<long, 4> itsBBox; // limits for cell iteration
}; // class NormalGrid
} // namespace Contour
} // namespace Engine
} // namespace SmartMet
| [
"mika.heiskanen@fmi.fi"
] | mika.heiskanen@fmi.fi |
60914ceb78d22c7936f5c8edb35b5c1d1fe03a11 | 6ee6cc888f0a82e36fd1687fed4a109f0cb800a7 | /leetcode/349.cpp | 1dca24c478f924855e8c48b9315efe8f9458c5bd | [] | no_license | Rayleigh0328/OJ | 1977e3dfc05f96437749b6259eda4d13133d2c87 | 3d7caaf356c69868a2f4359377ec75e15dafb4c3 | refs/heads/master | 2021-01-21T04:32:03.645841 | 2019-12-01T06:33:44 | 2019-12-01T06:33:44 | 49,385,474 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 574 | cpp | class Solution {
public:
vector<int> intersection(vector<int>& nums1, vector<int>& nums2)
{
set<int> s1;
s1.clear();
set<int> s2;
s2.clear();
for (int i=0;i<nums1.size();s1.insert(nums1[i++]));
for (int i=0;i<nums2.size();s2.insert(nums2[i++]));
vector<int> ans;
ans.clear();
set<int>::iterator it;
for (it = s1.begin(); it != s1.end(); ++it)
if (s2.find(*it) != s2.end())
ans.push_back(*it);
return ans;
}
}; | [
"j4bian@uwaterloo.ca"
] | j4bian@uwaterloo.ca |
7186a465d95ef574dc14274cab2b4d8c44a1304b | e8edb50d91e78e66d3aed3355bc6238cc20db1e6 | /HtmlEditor/inserthiddenfielddialog.h | ccda325de196af7c9282713a86dbb692b9553010 | [] | no_license | twosilly/HtmeEditor | bf064a6caab7d108f36eca9facda9d67c090850d | 89f6c8001d9861209846fe2990330e314bfd130b | refs/heads/master | 2020-04-23T01:43:33.578443 | 2019-02-15T07:44:46 | 2019-02-15T07:44:46 | 170,822,360 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 567 | h | #ifndef INSERTHIDDENFIELDDIALOG_H
#define INSERTHIDDENFIELDDIALOG_H
#include <QDialog>
#include "editor.h"
namespace Ui {
class InsertHiddenFieldDialog;
}
class InsertHiddenFieldDialog : public QDialog
{
Q_OBJECT
public:
explicit InsertHiddenFieldDialog(QWidget *parent = 0, Editor *e = 0);
~InsertHiddenFieldDialog();
private slots:
void on_closeButton_clicked();
void on_insertButton_clicked();
private:
Ui::InsertHiddenFieldDialog *ui;
Editor *editor;
};
#endif // INSERTHIDDENFIELDDIALOG_H
| [
"ryan@Ryans-MacBook-Pro-2.local"
] | ryan@Ryans-MacBook-Pro-2.local |
52870f7d239e84dbbaac56961242352458f4ed80 | ede3acf4970626666e627f816ecad0b1b9cd1052 | /test_file/test_file.cpp | 108d2fef1f124754deb51759c2460491e478daee | [] | no_license | Rock9man/cpp | 55c9e3cc04c338ed648ce4283de88e38f7ada978 | cdd485537b8393995042775f42a022b75567f326 | refs/heads/master | 2022-12-19T02:54:03.453942 | 2020-09-03T07:36:14 | 2020-09-03T07:36:14 | 292,439,782 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 820 | cpp | #include <iostream>
#include <fstream>
using namespace std;
int main(){
char data[100];
ofstream outfile;
outfile.open("after.dat");
cout << "Waiting to the file" << endl;
cout << "Enter your name:";
cin.getline(data,100);
outfile << data << endl;
cout << "Enter your age:";
cin.getline(data,100);
outfile << data << endl;
cout << "Enter your sex:";
cin.getline(data,100);
outfile << data << endl;
outfile.close();
ifstream infile;
infile.open("after.dat");
infile >> data;
cout <<"your info: " << endl;
cout <<"your name is "<< data << endl;
infile >> data;
cout <<"your age is "<< data << endl;
infile >> data;
cout <<"your sex is "<< data << endl;
infile.close();
cout << "Hello word" << endl;
return 0;
}
| [
"wangjun4@iauto.com"
] | wangjun4@iauto.com |
814490ccb7e7d13f107af0ddb4118991b03c88d9 | e6e6c81568e0f41831a85490895a7cf5c929d50e | /atcoder/Other/pakencamp_2019_4/pakencamp_2019_4_c.cpp | 07d5fd69a2851678416ee90976faba89fd0f02d3 | [] | no_license | mint6421/kyopro | 69295cd06ff907cd6cc43887ce964809aa2534d9 | f4ef43669352d84bd32e605a40f75faee5358f96 | refs/heads/master | 2021-07-02T04:57:13.566704 | 2020-10-23T06:51:20 | 2020-10-23T06:51:20 | 182,088,856 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,091 | cpp |
#include<bits/stdc++.h>
using namespace std;
#define inf INT_MAX
#define INF LLONG_MAX
#define ll long long
#define ull unsigned long long
#define M (int)(1e9+7)
#define P pair<int,int>
#define FOR(i,m,n) for(int i=(int)m;i<(int)n;i++)
#define RFOR(i,m,n) for(int i=(int)m;i>=(int)n;i--)
#define rep(i,n) FOR(i,0,n)
#define rrep(i,n) RFOR(i,n,0)
#define all(a) a.begin(),a.end()
const int vx[4] = {0,1,0,-1};
const int vy[4] = {1,0,-1,0};
#define F first
#define S second
#define PB push_back
#define EB emplace_back
#define int ll
#define vi vector<int>
#define IP pair<int,P>
#define PI pair<P,int>
#define PP pair<P,P>
#define Yes(f){cout<<(f?"Yes":"No")<<endl;}
#define YES(f){cout<<(f?"YES":"NO")<<endl;}
signed main(){
cin.tie(0);
ios::sync_with_stdio(false);
cout<<fixed<<setprecision(20);
double ans=0;
double l1,r1,l2,r2,l3,r3;
cin>>l1>>r1>>l2>>r2>>l3>>r3;
for(double i=l1;i<=r1;i++){
double s=1/(r1-l1+1);
if(i>=r2||i>=r3) break;
//cout<<s<<endl;
ans+=s*((r2-max(l2,i+1)+1)/(r2-l2+1))*((r3-max(l3,i+1)+1)/(r3-l3+1));
}
cout<<ans<<endl;
}
| [
"ee177100@meiji.ac.jp"
] | ee177100@meiji.ac.jp |
433143a7c52fb141e39d954379a5713341676737 | 5db7f2ba278be1847e9621010ebc3032aae8d603 | /include/tao/json/external/pegtl/internal/lf_eol.hpp | 0c761035ecd26bd830939c498d99fe480cb69c9e | [
"MIT",
"BSD-3-Clause"
] | permissive | octwanna/json | 946b08a9d490e455d265fe40d4900cada8d00425 | e19760fe5814bf5c62c29c391cbf5b808661a3c2 | refs/heads/master | 2021-09-02T09:41:24.554013 | 2018-01-01T15:05:05 | 2018-01-01T15:05:05 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,023 | hpp | // Copyright (c) 2016-2018 Dr. Colin Hirsch and Daniel Frey
// Please see LICENSE for license or visit https://github.com/taocpp/PEGTL/
#ifndef TAOCPP_JSON_PEGTL_INCLUDE_INTERNAL_LF_EOL_HPP
#define TAOCPP_JSON_PEGTL_INCLUDE_INTERNAL_LF_EOL_HPP
#include "../config.hpp"
#include "../eol_pair.hpp"
namespace tao
{
namespace TAOCPP_JSON_PEGTL_NAMESPACE
{
namespace internal
{
struct lf_eol
{
static constexpr int ch = '\n';
template< typename Input >
static eol_pair match( Input& in ) noexcept( noexcept( in.size( 1 ) ) )
{
eol_pair p = { false, in.size( 1 ) };
if( p.second ) {
if( in.peek_char() == '\n' ) {
in.bump_to_next_line();
p.first = true;
}
}
return p;
}
};
} // namespace internal
} // namespace TAOCPP_JSON_PEGTL_NAMESPACE
} // namespace tao
#endif
| [
"d.frey@gmx.de"
] | d.frey@gmx.de |
768e305cf32bc14e399c5db6e1c62994c220b355 | 04b1803adb6653ecb7cb827c4f4aa616afacf629 | /third_party/blink/renderer/core/feature_policy/feature_policy_parser.h | 5739397fc6ae16735a29bc12a3726b0f199b7f1a | [
"LGPL-2.0-or-later",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.1-only",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft",
"MIT",
"Apache-2.0",
"BSD-3-Clause"
] | permissive | Samsung/Castanets | 240d9338e097b75b3f669604315b06f7cf129d64 | 4896f732fc747dfdcfcbac3d442f2d2d42df264a | refs/heads/castanets_76_dev | 2023-08-31T09:01:04.744346 | 2021-07-30T04:56:25 | 2021-08-11T05:45:21 | 125,484,161 | 58 | 49 | BSD-3-Clause | 2022-10-16T19:31:26 | 2018-03-16T08:07:37 | null | UTF-8 | C++ | false | false | 6,433 | h | // Copyright 2016 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_FEATURE_POLICY_PARSER_H_
#define THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_FEATURE_POLICY_PARSER_H_
#include <memory>
#include "base/memory/scoped_refptr.h"
#include "third_party/blink/public/common/feature_policy/feature_policy.h"
#include "third_party/blink/renderer/core/core_export.h"
#include "third_party/blink/renderer/core/feature_policy/feature_policy_helper.h"
#include "third_party/blink/renderer/platform/weborigin/security_origin.h"
#include "third_party/blink/renderer/platform/wtf/text/string_hash.h"
#include "third_party/blink/renderer/platform/wtf/text/wtf_string.h"
#include "third_party/blink/renderer/platform/wtf/vector.h"
// Forward declare for friendship.
void ParseValueForFuzzer(blink::mojom::PolicyValueType, const WTF::String&);
namespace blink {
class Document;
class ExecutionContext;
// These values match the "FeaturePolicyAllowlistType" enum in
// tools/metrics/histograms/enums.xml. Entries should not be renumbered and
// numeric values should never be reused.
enum class FeaturePolicyAllowlistType {
kEmpty = 0,
kNone = 1,
kSelf = 2,
kSrc = 3,
kStar = 4,
kOrigins = 5,
kKeywordsOnly = 6,
kMixed = 7,
kMinValue = 0,
kMaxValue = kMixed
};
// Returns the list of features which are currently available in this context,
// including any features which have been made available by an origin trial.
CORE_EXPORT const Vector<String> GetAvailableFeatures(ExecutionContext*);
// FeaturePolicyParser is a collection of methods which are used to convert
// Feature Policy declarations, in headers and iframe attributes, into
// ParsedFeaturePolicy structs. This class encapsulates all of the logic for
// parsing feature names, origin lists, and threshold values.
// Note that code outside of /renderer/ should not be parsing policy directives
// from strings, but if necessary, should be constructing ParsedFeaturePolicy
// structs directly.
class CORE_EXPORT FeaturePolicyParser {
STATIC_ONLY(FeaturePolicyParser);
public:
// Converts a header policy string into a vector of allowlists, one for each
// feature specified. Unrecognized features are filtered out. If |messages| is
// not null, then any message in the input will cause a warning message to be
// appended to it. The optional ExecutionContext is used to determine if any
// origin trials affect the parsing.
// Example of a feature policy string:
// "vibrate a.com b.com; fullscreen 'none'; payment 'self', payment *".
static ParsedFeaturePolicy ParseHeader(
const String& policy,
scoped_refptr<const SecurityOrigin>,
Vector<String>* messages,
ExecutionContext* execution_context = nullptr);
// Converts a container policy string into a vector of allowlists, given self
// and src origins provided, one for each feature specified. Unrecognized
// features are filtered out. If |messages| is not null, then any message in
// the input will cause as warning message to be appended to it. Example of a
// feature policy string:
// "vibrate a.com 'src'; fullscreen 'none'; payment 'self', payment *".
static ParsedFeaturePolicy ParseAttribute(
const String& policy,
scoped_refptr<const SecurityOrigin> self_origin,
scoped_refptr<const SecurityOrigin> src_origin,
Vector<String>* messages,
Document* document = nullptr);
// Converts a feature policy string into a vector of allowlists (see comments
// above), with an explicit FeatureNameMap. This algorithm is called by both
// header policy parsing and container policy parsing. |self_origin|,
// |src_origin|, and |execution_context| are nullable. The optional
// ExecutionContext is used to determine if any origin trials affect the
// parsing.
static ParsedFeaturePolicy Parse(
const String& policy,
scoped_refptr<const SecurityOrigin> self_origin,
scoped_refptr<const SecurityOrigin> src_origin,
Vector<String>* messages,
const FeatureNameMap& feature_names,
ExecutionContext* execution_context = nullptr);
private:
friend void ::ParseValueForFuzzer(mojom::PolicyValueType, const String&);
static PolicyValue GetFallbackValueForFeature(
mojom::FeaturePolicyFeature feature);
static PolicyValue ParseValueForType(mojom::PolicyValueType feature_type,
const String& value_string,
bool* ok);
};
// Returns true iff any declaration in the policy is for the given feature.
CORE_EXPORT bool IsFeatureDeclared(mojom::FeaturePolicyFeature,
const ParsedFeaturePolicy&);
// Removes any declaration in the policy for the given feature. Returns true if
// the policy was modified.
CORE_EXPORT bool RemoveFeatureIfPresent(mojom::FeaturePolicyFeature,
ParsedFeaturePolicy&);
// If no declaration in the policy exists already for the feature, adds a
// declaration which disallows the feature in all origins. Returns true if the
// policy was modified.
CORE_EXPORT bool DisallowFeatureIfNotPresent(mojom::FeaturePolicyFeature,
ParsedFeaturePolicy&);
// If no declaration in the policy exists already for the feature, adds a
// declaration which allows the feature in all origins. Returns true if the
// policy was modified.
CORE_EXPORT bool AllowFeatureEverywhereIfNotPresent(mojom::FeaturePolicyFeature,
ParsedFeaturePolicy&);
// Replaces any existing declarations in the policy for the given feature with
// a declaration which disallows the feature in all origins.
CORE_EXPORT void DisallowFeature(mojom::FeaturePolicyFeature,
ParsedFeaturePolicy&);
// Replaces any existing declarations in the policy for the given feature with
// a declaration which allows the feature in all origins.
CORE_EXPORT void AllowFeatureEverywhere(mojom::FeaturePolicyFeature,
ParsedFeaturePolicy&);
CORE_EXPORT const String& GetNameForFeature(mojom::FeaturePolicyFeature);
} // namespace blink
#endif // THIRD_PARTY_BLINK_RENDERER_CORE_FEATURE_POLICY_FEATURE_POLICY_PARSER_H_
| [
"sunny.nam@samsung.com"
] | sunny.nam@samsung.com |
ab3096e8f1126d07ab75b0f5176615d4b465a2ac | 0d99bcb8b8717008c1ec9b080c6c86c2b1710eee | /날씨/build/Android/Preview1/app/src/main/include/Fuse.Layouts.StackLayout.h | 435dca302f06320dea2d79c855e2a88bc10ec722 | [] | no_license | shj4849/Fuse | 526d92bc49a0a2d8087beece987b1701dc35cccc | 447f49f96f9dadf203f5f91e8a1d67f19d8ecc04 | refs/heads/master | 2021-05-15T23:08:09.523726 | 2017-12-21T05:28:53 | 2017-12-21T05:28:53 | 106,758,124 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,641 | h | // This file was generated based on C:/Users/t2/AppData/Local/Fusetools/Packages/Fuse.Controls.Panels/1.4.0/Layouts/StackLayout.uno.
// WARNING: Changes might be lost if you edit this file directly.
#pragma once
#include <Fuse.Layouts.Layout.h>
namespace g{namespace Fuse{namespace Layouts{struct StackLayout;}}}
namespace g{namespace Fuse{struct LayoutParams;}}
namespace g{namespace Fuse{struct Visual;}}
namespace g{namespace Uno{struct Float2;}}
namespace g{namespace Uno{struct Float4;}}
namespace g{
namespace Fuse{
namespace Layouts{
// public sealed class StackLayout :24
// {
::g::Fuse::Layouts::Layout_type* StackLayout_typeof();
void StackLayout__ctor_2_fn(StackLayout* __this);
void StackLayout__ArrangePaddingBox_fn(StackLayout* __this, ::g::Fuse::Visual* container, ::g::Uno::Float4* padding, ::g::Fuse::LayoutParams* lp);
void StackLayout__get_ContentAlignment_fn(StackLayout* __this, int* __retval);
void StackLayout__set_ContentAlignment_fn(StackLayout* __this, int* value);
void StackLayout__get_EffectiveContentAlignment_fn(StackLayout* __this, int* __retval);
void StackLayout__get_EffectiveItemSpacing_fn(StackLayout* __this, float* __retval);
void StackLayout__GetContentSize_fn(StackLayout* __this, ::g::Fuse::Visual* container, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void StackLayout__GetElementsSize_fn(StackLayout* __this, ::g::Fuse::Visual* container, ::g::Fuse::LayoutParams* lp, ::g::Uno::Float2* __retval);
void StackLayout__get_ItemSpacing_fn(StackLayout* __this, float* __retval);
void StackLayout__set_ItemSpacing_fn(StackLayout* __this, float* value);
void StackLayout__get_Mode_fn(StackLayout* __this, int* __retval);
void StackLayout__set_Mode_fn(StackLayout* __this, int* value);
void StackLayout__New2_fn(StackLayout** __retval);
void StackLayout__get_Orientation_fn(StackLayout* __this, int* __retval);
void StackLayout__set_Orientation_fn(StackLayout* __this, int* value);
void StackLayout__ResetOrientation_fn(StackLayout* __this);
struct StackLayout : ::g::Fuse::Layouts::Layout
{
int _orientation;
float _itemSpacing;
int _contentAlignment;
int _mode;
void ctor_2();
int ContentAlignment();
void ContentAlignment(int value);
int EffectiveContentAlignment();
float EffectiveItemSpacing();
::g::Uno::Float2 GetElementsSize(::g::Fuse::Visual* container, ::g::Fuse::LayoutParams lp);
float ItemSpacing();
void ItemSpacing(float value);
int Mode();
void Mode(int value);
int Orientation();
void Orientation(int value);
void ResetOrientation();
static StackLayout* New2();
};
// }
}}} // ::g::Fuse::Layouts
| [
"shj4849@naver.com"
] | shj4849@naver.com |
ffdd9f0787cffaafa58fc10882f866c3917b45af | 77170cbcd2c87952763f770d50abd2d8b671f9d2 | /aws-cpp-sdk-route53/include/aws/route53/model/GetHealthCheckStatusRequest.h | 606a20340fbe458d96d3a52adbd75af76ad521c5 | [
"JSON",
"MIT",
"Apache-2.0"
] | permissive | bittorrent/aws-sdk-cpp | 795f1cdffb92f6fccb4396d8f885f7bf99829ce7 | 3f84fee22a0f4d5926aadf8d3303ea15a76421fd | refs/heads/master | 2020-12-03T00:41:12.194688 | 2016-03-04T01:41:51 | 2016-03-04T01:41:51 | 53,150,048 | 1 | 1 | null | 2016-03-04T16:43:12 | 2016-03-04T16:43:12 | null | UTF-8 | C++ | false | false | 29,690 | h | /*
* 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.
*/
#pragma once
#include <aws/route53/Route53_EXPORTS.h>
#include <aws/route53/Route53Request.h>
#include <aws/core/utils/memory/stl/AWSString.h>
namespace Aws
{
namespace Route53
{
namespace Model
{
/**
* <p>A complex type that contains information about the request to get health
* check status for a health check.</p>
*/
class AWS_ROUTE53_API GetHealthCheckStatusRequest : public Route53Request
{
public:
GetHealthCheckStatusRequest();
Aws::String SerializePayload() const override;
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline const Aws::String& GetHealthCheckId() const{ return m_healthCheckId; }
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline void SetHealthCheckId(const Aws::String& value) { m_healthCheckIdHasBeenSet = true; m_healthCheckId = value; }
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline void SetHealthCheckId(Aws::String&& value) { m_healthCheckIdHasBeenSet = true; m_healthCheckId = value; }
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline void SetHealthCheckId(const char* value) { m_healthCheckIdHasBeenSet = true; m_healthCheckId.assign(value); }
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline GetHealthCheckStatusRequest& WithHealthCheckId(const Aws::String& value) { SetHealthCheckId(value); return *this;}
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline GetHealthCheckStatusRequest& WithHealthCheckId(Aws::String&& value) { SetHealthCheckId(value); return *this;}
/**
* <p>If you want Amazon Route 53 to return this resource record set in response to
* a DNS query only when a health check is passing, include the
* <code>HealthCheckId</code> element and specify the ID of the applicable health
* check.</p> <p>Amazon Route 53 determines whether a resource record set is
* healthy by periodically sending a request to the endpoint that is specified in
* the health check. If that endpoint returns an HTTP status code of 2xx or 3xx,
* the endpoint is healthy. If the endpoint returns an HTTP status code of 400 or
* greater, or if the endpoint doesn't respond for a certain amount of time, Amazon
* Route 53 considers the endpoint unhealthy and also considers the resource record
* set unhealthy.</p> <p>The <code>HealthCheckId</code> element is only useful when
* Amazon Route 53 is choosing between two or more resource record sets to respond
* to a DNS query, and you want Amazon Route 53 to base the choice in part on the
* status of a health check. Configuring health checks only makes sense in the
* following configurations:</p> <ul> <li>You're checking the health of the
* resource record sets in a weighted, latency, geolocation, or failover resource
* record set, and you specify health check IDs for all of the resource record
* sets. If the health check for one resource record set specifies an endpoint that
* is not healthy, Amazon Route 53 stops responding to queries using the value for
* that resource record set.</li> <li><p>You set <code>EvaluateTargetHealth</code>
* to <code>true</code> for the resource record sets in an alias, weighted alias,
* latency alias, geolocation alias, or failover alias resource record set, and you
* specify health check IDs for all of the resource record sets that are referenced
* by the alias resource record sets. For more information about this
* configuration, see <a>EvaluateTargetHealth</a>.</p> <p>Amazon Route 53 doesn't
* check the health of the endpoint specified in the resource record set, for
* example, the endpoint specified by the IP address in the <code>Value</code>
* element. When you add a <code>HealthCheckId</code> element to a resource record
* set, Amazon Route 53 checks the health of the endpoint that you specified in the
* health check.</p> </li> </ul> <p>For geolocation resource record sets, if an
* endpoint is unhealthy, Amazon Route 53 looks for a resource record set for the
* larger, associated geographic region. For example, suppose you have resource
* record sets for a state in the United States, for the United States, for North
* America, and for all locations. If the endpoint for the state resource record
* set is unhealthy, Amazon Route 53 checks the resource record sets for the United
* States, for North America, and for all locations (a resource record set for
* which the value of CountryCode is <code>*</code>), in that order, until it finds
* a resource record set for which the endpoint is healthy.</p> <p>If your health
* checks specify the endpoint only by domain name, we recommend that you create a
* separate health check for each endpoint. For example, create a health check for
* each HTTP server that is serving content for www.example.com. For the value of
* <code>FullyQualifiedDomainName</code>, specify the domain name of the server
* (such as <code>us-east-1-www.example.com</code>), not the name of the resource
* record sets (example.com).</p> <important>In this configuration, if you create a
* health check for which the value of <code>FullyQualifiedDomainName</code>
* matches the name of the resource record sets and then associate the health check
* with those resource record sets, health check results will be
* unpredictable.</important>
*/
inline GetHealthCheckStatusRequest& WithHealthCheckId(const char* value) { SetHealthCheckId(value); return *this;}
private:
Aws::String m_healthCheckId;
bool m_healthCheckIdHasBeenSet;
};
} // namespace Model
} // namespace Route53
} // namespace Aws
| [
"henso@amazon.com"
] | henso@amazon.com |
28a5bb14b0ddfb354f69ea99e472104d648aec59 | a349dbf18493cd9bbb2bc9288671f2c981aa8233 | /All Other Topics/Three way partitioning.cpp | 0fbb322fde9564705ff79e2da0352f9fa0d1ef71 | [] | no_license | Ashish-kumar7/geeks-for-geeks-solutions | dd67fb596162d866a8043460f07e2052dc38446d | 045dc4041323b4f912fcb50ae087eb5865fbacb3 | refs/heads/master | 2022-10-27T14:43:09.588551 | 2022-10-02T10:41:56 | 2022-10-02T10:41:56 | 228,147,267 | 38 | 50 | null | 2022-10-19T05:32:24 | 2019-12-15T07:40:36 | C++ | UTF-8 | C++ | false | false | 104 | cpp | vector<int> threeWayPartition(vector<int> A, int a, int b){
sort(A.begin(),A.end());
return A;
} | [
"ashishkumar357ak@gmail.com"
] | ashishkumar357ak@gmail.com |
4e18eb18068a9ec6305e23d6be0e8966c63e1b70 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/d9/1db961dfdae8fd/main.cpp | 6a1951619d18268a24a4700c509a3b70aeced9e3 | [] | no_license | WhiZTiM/coliru | 3a6c4c0bdac566d1aa1c21818118ba70479b0f40 | 2c72c048846c082f943e6c7f9fa8d94aee76979f | refs/heads/master | 2021-01-01T05:10:33.812560 | 2015-08-24T19:09:22 | 2015-08-24T19:09:22 | 56,789,706 | 3 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 348 | cpp | #include <type_traits>
#include <utility>
template<typename T>
constexpr T add(T&& t) {
return std::forward<T>(t);
}
template<typename T, typename... Args>
constexpr typename std::common_type<T, Args...>::type add(T&& t, Args... args) {
return std::forward<T>(t) + add(args...);
}
int main() {
static_assert(add(1,2,3) == 6, "..");
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
e89619b184c74b3f03b6855abbbfa9816c0ba0b2 | 63e15f017004e4c77b36c3858f6eac8cd5d0a872 | /swg_generated/cpp/model/MemberLevel.cpp | 0bfaaf2146523f1125d44b9fe3cd7ff66cb38f3c | [
"MIT"
] | permissive | 7leekee7/upbit-client | 9eac3cfe6d90d34cda624f9f3125573a89e168ff | 43201797a605d1e1b3e0db1183ced8ec9997699f | refs/heads/main | 2023-02-16T13:46:49.681895 | 2021-01-15T04:52:22 | 2021-01-15T04:52:22 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 12,005 | cpp | /**
* Upbit Open API
* ## REST API for Upbit Exchange - Base URL: [https://api.upbit.com] - Official Upbit API Documents: [https://docs.upbit.com] - Official Support email: [open-api@upbit.com]
*
* OpenAPI spec version: 1.1.6
* Contact: ujhin942@gmail.com
*
* NOTE: This class is auto generated by the swagger code generator 2.4.17.
* https://github.com/swagger-api/swagger-codegen.git
* Do not edit the class manually.
*/
#include "MemberLevel.h"
namespace io {
namespace swagger {
namespace client {
namespace model {
MemberLevel::MemberLevel()
{
m_Security_level = 0.0;
m_Security_levelIsSet = false;
m_Fee_level = 0.0;
m_Fee_levelIsSet = false;
m_Email_verified = false;
m_Email_verifiedIsSet = false;
m_Identity_auth_verified = false;
m_Identity_auth_verifiedIsSet = false;
m_Bank_account_verified = false;
m_Bank_account_verifiedIsSet = false;
m_Kakao_pay_auth_verified = false;
m_Kakao_pay_auth_verifiedIsSet = false;
m_Locked = false;
m_LockedIsSet = false;
m_Wallet_locked = false;
m_Wallet_lockedIsSet = false;
}
MemberLevel::~MemberLevel()
{
}
void MemberLevel::validate()
{
// TODO: implement validation
}
web::json::value MemberLevel::toJson() const
{
web::json::value val = web::json::value::object();
if(m_Security_levelIsSet)
{
val[utility::conversions::to_string_t("security_level")] = ModelBase::toJson(m_Security_level);
}
if(m_Fee_levelIsSet)
{
val[utility::conversions::to_string_t("fee_level")] = ModelBase::toJson(m_Fee_level);
}
if(m_Email_verifiedIsSet)
{
val[utility::conversions::to_string_t("email_verified")] = ModelBase::toJson(m_Email_verified);
}
if(m_Identity_auth_verifiedIsSet)
{
val[utility::conversions::to_string_t("identity_auth_verified")] = ModelBase::toJson(m_Identity_auth_verified);
}
if(m_Bank_account_verifiedIsSet)
{
val[utility::conversions::to_string_t("bank_account_verified")] = ModelBase::toJson(m_Bank_account_verified);
}
if(m_Kakao_pay_auth_verifiedIsSet)
{
val[utility::conversions::to_string_t("kakao_pay_auth_verified")] = ModelBase::toJson(m_Kakao_pay_auth_verified);
}
if(m_LockedIsSet)
{
val[utility::conversions::to_string_t("locked")] = ModelBase::toJson(m_Locked);
}
if(m_Wallet_lockedIsSet)
{
val[utility::conversions::to_string_t("wallet_locked")] = ModelBase::toJson(m_Wallet_locked);
}
return val;
}
void MemberLevel::fromJson(web::json::value& val)
{
if(val.has_field(utility::conversions::to_string_t("security_level")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("security_level")];
if(!fieldValue.is_null())
{
setSecurityLevel(ModelBase::doubleFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("fee_level")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("fee_level")];
if(!fieldValue.is_null())
{
setFeeLevel(ModelBase::doubleFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("email_verified")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("email_verified")];
if(!fieldValue.is_null())
{
setEmailVerified(ModelBase::boolFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("identity_auth_verified")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("identity_auth_verified")];
if(!fieldValue.is_null())
{
setIdentityAuthVerified(ModelBase::boolFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("bank_account_verified")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("bank_account_verified")];
if(!fieldValue.is_null())
{
setBankAccountVerified(ModelBase::boolFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("kakao_pay_auth_verified")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("kakao_pay_auth_verified")];
if(!fieldValue.is_null())
{
setKakaoPayAuthVerified(ModelBase::boolFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("locked")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("locked")];
if(!fieldValue.is_null())
{
setLocked(ModelBase::boolFromJson(fieldValue));
}
}
if(val.has_field(utility::conversions::to_string_t("wallet_locked")))
{
web::json::value& fieldValue = val[utility::conversions::to_string_t("wallet_locked")];
if(!fieldValue.is_null())
{
setWalletLocked(ModelBase::boolFromJson(fieldValue));
}
}
}
void MemberLevel::toMultipart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix) const
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(m_Security_levelIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("security_level"), m_Security_level));
}
if(m_Fee_levelIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("fee_level"), m_Fee_level));
}
if(m_Email_verifiedIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("email_verified"), m_Email_verified));
}
if(m_Identity_auth_verifiedIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("identity_auth_verified"), m_Identity_auth_verified));
}
if(m_Bank_account_verifiedIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("bank_account_verified"), m_Bank_account_verified));
}
if(m_Kakao_pay_auth_verifiedIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("kakao_pay_auth_verified"), m_Kakao_pay_auth_verified));
}
if(m_LockedIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("locked"), m_Locked));
}
if(m_Wallet_lockedIsSet)
{
multipart->add(ModelBase::toHttpContent(namePrefix + utility::conversions::to_string_t("wallet_locked"), m_Wallet_locked));
}
}
void MemberLevel::fromMultiPart(std::shared_ptr<MultipartFormData> multipart, const utility::string_t& prefix)
{
utility::string_t namePrefix = prefix;
if(namePrefix.size() > 0 && namePrefix.substr(namePrefix.size() - 1) != utility::conversions::to_string_t("."))
{
namePrefix += utility::conversions::to_string_t(".");
}
if(multipart->hasContent(utility::conversions::to_string_t("security_level")))
{
setSecurityLevel(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("security_level"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("fee_level")))
{
setFeeLevel(ModelBase::doubleFromHttpContent(multipart->getContent(utility::conversions::to_string_t("fee_level"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("email_verified")))
{
setEmailVerified(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("email_verified"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("identity_auth_verified")))
{
setIdentityAuthVerified(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("identity_auth_verified"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("bank_account_verified")))
{
setBankAccountVerified(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("bank_account_verified"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("kakao_pay_auth_verified")))
{
setKakaoPayAuthVerified(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("kakao_pay_auth_verified"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("locked")))
{
setLocked(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("locked"))));
}
if(multipart->hasContent(utility::conversions::to_string_t("wallet_locked")))
{
setWalletLocked(ModelBase::boolFromHttpContent(multipart->getContent(utility::conversions::to_string_t("wallet_locked"))));
}
}
double MemberLevel::getSecurityLevel() const
{
return m_Security_level;
}
void MemberLevel::setSecurityLevel(double value)
{
m_Security_level = value;
m_Security_levelIsSet = true;
}
bool MemberLevel::securityLevelIsSet() const
{
return m_Security_levelIsSet;
}
void MemberLevel::unsetSecurity_level()
{
m_Security_levelIsSet = false;
}
double MemberLevel::getFeeLevel() const
{
return m_Fee_level;
}
void MemberLevel::setFeeLevel(double value)
{
m_Fee_level = value;
m_Fee_levelIsSet = true;
}
bool MemberLevel::feeLevelIsSet() const
{
return m_Fee_levelIsSet;
}
void MemberLevel::unsetFee_level()
{
m_Fee_levelIsSet = false;
}
bool MemberLevel::isEmailVerified() const
{
return m_Email_verified;
}
void MemberLevel::setEmailVerified(bool value)
{
m_Email_verified = value;
m_Email_verifiedIsSet = true;
}
bool MemberLevel::emailVerifiedIsSet() const
{
return m_Email_verifiedIsSet;
}
void MemberLevel::unsetEmail_verified()
{
m_Email_verifiedIsSet = false;
}
bool MemberLevel::isIdentityAuthVerified() const
{
return m_Identity_auth_verified;
}
void MemberLevel::setIdentityAuthVerified(bool value)
{
m_Identity_auth_verified = value;
m_Identity_auth_verifiedIsSet = true;
}
bool MemberLevel::identityAuthVerifiedIsSet() const
{
return m_Identity_auth_verifiedIsSet;
}
void MemberLevel::unsetIdentity_auth_verified()
{
m_Identity_auth_verifiedIsSet = false;
}
bool MemberLevel::isBankAccountVerified() const
{
return m_Bank_account_verified;
}
void MemberLevel::setBankAccountVerified(bool value)
{
m_Bank_account_verified = value;
m_Bank_account_verifiedIsSet = true;
}
bool MemberLevel::bankAccountVerifiedIsSet() const
{
return m_Bank_account_verifiedIsSet;
}
void MemberLevel::unsetBank_account_verified()
{
m_Bank_account_verifiedIsSet = false;
}
bool MemberLevel::isKakaoPayAuthVerified() const
{
return m_Kakao_pay_auth_verified;
}
void MemberLevel::setKakaoPayAuthVerified(bool value)
{
m_Kakao_pay_auth_verified = value;
m_Kakao_pay_auth_verifiedIsSet = true;
}
bool MemberLevel::kakaoPayAuthVerifiedIsSet() const
{
return m_Kakao_pay_auth_verifiedIsSet;
}
void MemberLevel::unsetKakao_pay_auth_verified()
{
m_Kakao_pay_auth_verifiedIsSet = false;
}
bool MemberLevel::isLocked() const
{
return m_Locked;
}
void MemberLevel::setLocked(bool value)
{
m_Locked = value;
m_LockedIsSet = true;
}
bool MemberLevel::lockedIsSet() const
{
return m_LockedIsSet;
}
void MemberLevel::unsetLocked()
{
m_LockedIsSet = false;
}
bool MemberLevel::isWalletLocked() const
{
return m_Wallet_locked;
}
void MemberLevel::setWalletLocked(bool value)
{
m_Wallet_locked = value;
m_Wallet_lockedIsSet = true;
}
bool MemberLevel::walletLockedIsSet() const
{
return m_Wallet_lockedIsSet;
}
void MemberLevel::unsetWallet_locked()
{
m_Wallet_lockedIsSet = false;
}
}
}
}
}
| [
"ujhin942@gmail.com"
] | ujhin942@gmail.com |
006db99b3fea58a53ede3d294fb44d62898909c0 | bd729ef9fcd96ea62e82bb684c831d9917017d0e | /keche/trunk/comm_app/projects/share/queue/queuemgr.cpp | c8c9287460b1054b0b12502dac35237a0d0b042a | [] | no_license | shanghaif/workspace-kepler | 849c7de67b1f3ee5e7da55199c05c737f036780c | ac1644be26a21f11a3a4a00319c450eb590c1176 | refs/heads/master | 2023-03-22T03:38:55.103692 | 2018-03-24T02:39:41 | 2018-03-24T02:39:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,829 | cpp | /*
* queuemgr.cpp
*
* Created on: 2012-10-22
* Author: humingqing
*
* memo: 主要实现的功能
* 1. 异步发送的数据等待队列,当接收到响应后清空对象,当等待响应超时时,需要重新发送
* 2. 重新发送每一次等待超时时间,与次的时间为乘2的等待关系,也就是重发次数越多等待时间越长
* 3. 如果终端处理能力有限,保证当需要发送数据直接入队列等待发送会顺序发送
* 4. 当顺序发送时,平台收到终端上一个下发的响应后,自动触发下一个等待需要发送的消息
* 5. 如果等待发送数据超时,平台会自动下发消息,如果有多个超时下发数据,则只发送单个数据,直到收到上一个应答或者再次超时再下发
*/
#include "queuemgr.h"
#include <assert.h>
CQueueMgr::CQueue::CQueue( IQCaller *pCaller , int ent )
{
_pCaller = pCaller ;
_send = 0 ;
_next = _pre = NULL ;
_maxent = ent ;
}
CQueueMgr::CQueue::~CQueue()
{
int size = 0 ;
_QData *p = _queue.move(size) ;
if ( size == 0 )
return ;
while( p->_next != NULL ) {
p = p->_next ;
_pCaller->Destroy( p->_pre->_ptr ) ;
delete p->_pre ;
}
if ( p != NULL ) {
_pCaller->Destroy( p->_ptr ) ;
delete p ;
}
_index.clear() ;
_send = 0 ;
}
// 添加数据
bool CQueueMgr::CQueue::Add( unsigned int seq, void *data, int timeout, bool send )
{
// 先移除原有的数据
Remove( seq ) ;
_QData *p = new _QData ;
assert( p != NULL ) ;
p->_seq = seq ;
p->_ntime = timeout ;
p->_time = time(NULL) + timeout ;
p->_ptr = data ;
if ( send ) {
p->_ent = -1 ;
} else {
p->_ent = _maxent ;
}
Add( p ) ;
_index.insert( std::make_pair(seq, p ) ) ;
return true ;
}
// 添加到节点中
void CQueueMgr::CQueue::Add( _QData *p )
{
_queue.insert( p ) ;
if ( p->_ent < 0 )
_send = _send + 1 ;
// printf( "add seq id %d, size %d, send %d \n", p->_seq , _size, _send ) ;
}
// 删除数据
void CQueueMgr::CQueue::Remove( unsigned int seq )
{
_QIndex::iterator it = _index.find( seq ) ;
if ( it == _index.end() )
return ;
_QData *p = it->second ;
_index.erase( it ) ;
Remove( p ) ;
_pCaller->Destroy( p->_ptr ) ;
delete p ;
}
// 移除所有的数据节点
void CQueueMgr::CQueue::Remove( _QData *p )
{
// printf( "remove seq id %d\n", p->_seq ) ;
if ( p->_ent < 0 )
_send = _send - 1 ;
_queue.erase( p ) ;
}
// 触发入队列的数据发送一次
void CQueueMgr::CQueue::Send( void )
{
if ( _send == 0 )
return ;
_QData *p = _queue.begin() ;
while( p != NULL ) {
if ( p->_ent < 0 )
break ;
p = _queue.next(p) ;
}
if ( p != NULL ) {
Remove( p ) ;
p->_ent = _maxent ;
p->_time = time(NULL) + p->_ntime ;
Add( p ) ;
_pCaller->OnReSend( p->_ptr ) ;
// printf( "send seq %d\n", p->_seq ) ;
}
}
// 检测超时的数据
bool CQueueMgr::CQueue::Check( int &nexttime )
{
if ( _queue.size() == 0 )
return false;
time_t now = time(NULL) ;
_QData *t,*p = _queue.begin() ;
int nsend = 0 ;
while ( p != NULL ) {
if ( p->_time > now )
break ;
t = p ;
p = _queue.next(p) ;
// 先从前面移走的数据
Remove( t ) ;
// 如果为等待发送的数据,超时发送按顺序单个发送
if ( t->_ent < 0 ) {
if ( nsend == 0 ) {// 调用发送接口发送数据
_pCaller->OnReSend( t->_ptr ) ;
t->_ent = _maxent ;
nsend = nsend + 1 ;
}
} else { // 否则为等待响应发送的数据
// 调用发送接口发送数据
_pCaller->OnReSend( t->_ptr ) ;
t->_ntime = t->_ntime * 2 ; // 每一次等待时间随次数减少而增加的
t->_ent = t->_ent - 1 ;
}
t->_time = now + t->_ntime ;
// 如果发送次为零就不再处理
if ( t->_ent == 0 ) { // 移除超时的元素,不重发也不再等待
_index.erase( t->_seq ) ;
_pCaller->Destroy( t->_ptr ) ;
delete t ;
} else {
Add( t ) ; // 按时间序列添加队列中
}
}
if ( _queue.size() == 0 )
return false ;
// 取得最近发送需要等待的时间
nexttime = _queue.begin()->_time - now ;
return true ;
}
CQueueMgr::CQueueMgr( IQCaller *pCaller , int time, int ent )
{
_maxspan = time ;
_maxent = ent ;
_pCaller = pCaller ;
if ( ! _thread.init( 1, NULL, this ) ) {
printf( "init queue thread failed\n" ) ;
return ;
}
_inited = true ;
_thread.start() ;
}
CQueueMgr::~CQueueMgr()
{
Clear() ;
if ( ! _inited )
return ;
_inited = false ;
_monitor.notifyEnd() ;
_thread.stop() ;
}
// 添加到等待发送队列中,是否为延后由线程对象来发送,主要触
bool CQueueMgr::Add( const char *id, unsigned int seq, void *data , bool send )
{
_mutex.lock() ;
CQueue *p = NULL ;
CMapQueue::iterator it = _index.find( id ) ;
if ( it == _index.end() ) {
p = new CQueue(_pCaller, _maxent ) ;
p->_id = id ;
_queue.push( p ) ;
_index.insert( std::make_pair(id, p ) ) ;
} else {
p = it->second ;
}
bool success = p->Add( seq, data, _maxspan , send ) ;
_mutex.unlock() ;
_monitor.notify() ;
return success ;
}
// 删除ID号对象
void CQueueMgr::Del( const char *id )
{
_mutex.lock() ;
CMapQueue::iterator it = _index.find( id ) ;
if ( it == _index.end() ) {
_mutex.unlock() ;
return ;
}
CQueue *p = it->second ;
_index.erase( it ) ;
delete _queue.erase( p ) ;
_mutex.unlock() ;
}
// 移除对象
void CQueueMgr::Remove( const char *id, unsigned int seq , bool check )
{
_mutex.lock() ;
CMapQueue::iterator it = _index.find( id ) ;
if ( it == _index.end() ) {
_mutex.unlock() ;
return ;
}
// 收到响应应答后清空等待数据
it->second->Remove( seq ) ;
if ( check ) { // 发送等待需要发送的数据
it->second->Send() ;
}
_mutex.unlock() ;
_monitor.notify() ;
}
// 实现线程对象运行检测接口
void CQueueMgr::run( void *param )
{
while( _inited ) {
int ntime = 30 ;
_mutex.lock() ;
if( _queue.size() > 0 ) {
int nval = 0 ;
CQueue *t, *p = _queue.begin() ;
while( p != NULL ){
t = p ;
p = _queue.next( p ) ;
// 检测数据是否需要发送
if ( ! t->Check( nval ) ) {
// 移除数据
_queue.erase( t ) ;
// 删队索引元素
_index.erase( t->_id ) ;
delete t ;
continue ;
}
// 计算出队列元素最近需要处理消息时间
if ( nval < ntime ) {
ntime = nval ;
}
}
}
_mutex.unlock() ;
// printf( "run time over %d, size %d\n", ntime , _size ) ;
ntime = ( ntime <= 0 ) ? 1 : ntime ;
_monitor.lock() ;
_monitor.wait(ntime) ;
_monitor.unlock() ;
}
}
// 清空所有数据
void CQueueMgr::Clear( void )
{
_mutex.lock() ;
int size = 0 ;
CQueue *p = _queue.move( size ) ;
if ( size == 0 ) {
_mutex.unlock() ;
return ;
}
while( p != NULL ) {
p = p->_next ;
delete p->_pre ;
}
_index.clear() ;
_mutex.unlock() ;
}
| [
"zhangjunfang0505@163.com"
] | zhangjunfang0505@163.com |
9ded3bdf6a6197276ca566634469212f913dd724 | 6587876b70f16f6cd389b34ca60358f96a0ecc61 | /BrakeController/lib/ParticleBrake/ParticleBrake.h | af914adedaf03cb371ea2aa83cd237b841365990 | [] | no_license | Woz4tetra/SEA-Prototype-3-Code | 8aa1ba87ef895647c4d093062404984228fb7199 | b68f73c6cdd902e45d2c748fd79814134bad2fdd | refs/heads/master | 2020-04-03T14:03:24.897147 | 2019-03-02T05:24:23 | 2019-03-02T05:24:23 | 155,310,034 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,047 | h | #include <Arduino.h>
#include <Wire.h>
#include <Adafruit_INA219.h>
class ParticleBrake
{
public:
ParticleBrake(Adafruit_INA219 *ina219, int current_control_pin);
void reset();
void set(double current_mA);
double getShuntVoltage();
double getBusVoltage();
double getCurrent_mA();
double getPower_mW();
double getLoadVoltage();
int getCurrentPinValue();
double getSetPoint();
void update();
double Kp, Ki, Kd;
bool pidEnabled;
double response_unforced_msec, response_forced_msec;
private:
void setCurrentPin(int pwm_value);
void clearVariables();
int PARTICLE_BRAKE_CURRENT_CONTROL_PIN;
int current_pin_value;
double shuntvoltage, busvoltage, current_mA, power_mW, loadvoltage;
Adafruit_INA219 *ina219;
double pidSetPoint;
double pidPrevError;
double pidSumError;
uint32_t prevPidTimer = 0;
uint32_t pidDelay; // microseconds
};
| [
"woz4tetra@gmail.com"
] | woz4tetra@gmail.com |
425a04751de4cd4fffeede1a50a951d686a682c9 | 4f6a3200f2133c4afe6e1b9535efce0d6d04f038 | /src/net/WrapTCPService.h | 9a8a557da1f01c62d129dcf596830b1fae4170a0 | [] | no_license | hpplinux/accumulation-dev | 5342e8077753279bbb382bf5f164957b673b6bb1 | e99613f34be75e220ef01280ae0f56b6fe3e4a8a | refs/heads/master | 2020-12-24T10:32:12.347133 | 2017-01-22T06:23:03 | 2017-01-22T06:23:03 | 73,155,660 | 0 | 0 | null | 2016-11-08T06:20:39 | 2016-11-08T06:20:39 | null | GB18030 | C++ | false | false | 2,843 | h | #ifndef _WRAP_TCP_SERVICE_H
#define _WRAP_TCP_SERVICE_H
#include <string>
#include <stdint.h>
#include "TCPService.h"
#include "NonCopyable.h"
class WrapServer;
/* 以智能指针对象为网络会话标识的网络服务 */
class TCPSession : public NonCopyable
{
public:
typedef std::shared_ptr<TCPSession> PTR;
typedef std::weak_ptr<TCPSession> WEAK_PTR;
typedef std::function<void(TCPSession::PTR&)> CLOSE_CALLBACK;
typedef std::function<size_t(TCPSession::PTR&, const char*, size_t)> DATA_CALLBACK;
int64_t getUD() const;
void setUD(int64_t ud);
const std::string& getIP() const;
int64_t getSocketID() const;
void send(const char* buffer, size_t len, const DataSocket::PACKED_SENDED_CALLBACK& callback = nullptr) const;
void send(const DataSocket::PACKET_PTR& packet, const DataSocket::PACKED_SENDED_CALLBACK& callback = nullptr) const;
void postShutdown() const;
void postClose() const;
void setCloseCallback(CLOSE_CALLBACK&& callback);
void setCloseCallback(const CLOSE_CALLBACK& callback);
void setDataCallback(DATA_CALLBACK&& callback);
void setDataCallback(const DATA_CALLBACK& callback);
protected:
virtual ~TCPSession();
private:
TCPSession();
void setSocketID(int64_t id);
void setIP(const std::string& ip);
void setService(TcpService::PTR& service);
CLOSE_CALLBACK& getCloseCallback();
DATA_CALLBACK& getDataCallback();
static PTR Create()
{
struct make_shared_enabler : public TCPSession {};
return std::make_shared<make_shared_enabler>();
}
private:
TcpService::PTR mService;
int64_t mSocketID;
std::string mIP;
int64_t mUserData;
CLOSE_CALLBACK mCloseCallback;
DATA_CALLBACK mDataCallback;
friend class WrapServer;
};
class WrapServer : public NonCopyable
{
public:
typedef std::shared_ptr<WrapServer> PTR;
typedef std::weak_ptr<WrapServer> WEAK_PTR;
typedef std::function<void(TCPSession::PTR&)> SESSION_ENTER_CALLBACK;
WrapServer();
virtual ~WrapServer();
TcpService::PTR& getService();
void startWorkThread(size_t threadNum, TcpService::FRAME_CALLBACK callback = nullptr);
void addSession(sock fd, const SESSION_ENTER_CALLBACK& userEnterCallback, bool isUseSSL, size_t maxRecvBufferSize, bool forceSameThreadLoop = false);
private:
TcpService::PTR mTCPService;
};
#endif | [
"irons.du@gmail.com"
] | irons.du@gmail.com |
07bdcd574a6d2692d2138094efd5159333e151a6 | efd6e6a6ba308bd10a552cf2b5a1ecd1c3a1ad89 | /Week5/Cigar.h | 4441a1613744c1f22591d08339057ccf745e4ff3 | [] | no_license | Appsalar/OOP | d522c2184730a621c95922e3e617e8b7770bdc53 | 559eb254f3c5a5b47aaf4827bfc4c50651e1628e | refs/heads/master | 2021-01-17T07:09:00.240935 | 2017-03-29T09:19:48 | 2017-03-29T09:19:48 | 52,432,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 360 | h | #ifndef CIGAR_H
#define CIGAR_H
#include <fstream>
#include <iostream>
const int MAX_NAME_SIZE = 73;
struct Cigar
{
char name[MAX_NAME_SIZE];
double price;
};
void checkFileExist(const char* fileName);
bool readFromFile(std::ifstream& input, Cigar*& pArr, int& Count);
bool writeToFile(std::ofstream& output, Cigar* pArr, int Count);
#endif // CIGAR_H
| [
"sasmose@yahoo.com"
] | sasmose@yahoo.com |
7f18972299cc4917d9edbb4925673f25dd59337a | 1af49694004c6fbc31deada5618dae37255ce978 | /media/capture/video/chromeos/request_manager.cc | 7dedadf09b3e29ca054f5fa9997ad8ef9aeed361 | [
"BSD-3-Clause"
] | permissive | sadrulhc/chromium | 59682b173a00269ed036eee5ebfa317ba3a770cc | a4b950c23db47a0fdd63549cccf9ac8acd8e2c41 | refs/heads/master | 2023-02-02T07:59:20.295144 | 2020-12-01T21:32:32 | 2020-12-01T21:32:32 | 317,678,056 | 3 | 0 | BSD-3-Clause | 2020-12-01T21:56:26 | 2020-12-01T21:56:25 | null | UTF-8 | C++ | false | false | 38,573 | cc | // 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.
#include "media/capture/video/chromeos/request_manager.h"
#include <sync/sync.h>
#include <initializer_list>
#include <map>
#include <set>
#include <string>
#include <utility>
#include "base/bind.h"
#include "base/callback_helpers.h"
#include "base/posix/safe_strerror.h"
#include "base/strings/string_number_conversions.h"
#include "base/trace_event/trace_event.h"
#include "media/capture/video/chromeos/camera_buffer_factory.h"
#include "media/capture/video/chromeos/camera_metadata_utils.h"
#include "media/capture/video/chromeos/video_capture_features_chromeos.h"
#include "mojo/public/cpp/platform/platform_handle.h"
#include "mojo/public/cpp/system/platform_handle.h"
namespace media {
namespace {
constexpr uint32_t kUndefinedFrameNumber = 0xFFFFFFFF;
constexpr std::initializer_list<StreamType> kYUVReprocessStreams = {
StreamType::kYUVInput, StreamType::kJpegOutput};
} // namespace
RequestManager::RequestManager(
mojo::PendingReceiver<cros::mojom::Camera3CallbackOps>
callback_ops_receiver,
std::unique_ptr<StreamCaptureInterface> capture_interface,
CameraDeviceContext* device_context,
VideoCaptureBufferType buffer_type,
std::unique_ptr<CameraBufferFactory> camera_buffer_factory,
BlobifyCallback blobify_callback,
scoped_refptr<base::SingleThreadTaskRunner> ipc_task_runner,
CameraAppDeviceImpl* camera_app_device,
ClientType client_type)
: callback_ops_(this, std::move(callback_ops_receiver)),
capture_interface_(std::move(capture_interface)),
device_context_(device_context),
video_capture_use_gmb_(buffer_type ==
VideoCaptureBufferType::kGpuMemoryBuffer),
stream_buffer_manager_(
new StreamBufferManager(device_context_,
video_capture_use_gmb_,
std::move(camera_buffer_factory),
client_type)),
blobify_callback_(std::move(blobify_callback)),
ipc_task_runner_(std::move(ipc_task_runner)),
capturing_(false),
partial_result_count_(1),
first_frame_shutter_time_(base::TimeTicks()),
camera_app_device_(std::move(camera_app_device)),
client_type_(client_type) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
DCHECK(callback_ops_.is_bound());
DCHECK(device_context_);
// We use base::Unretained() for the StreamBufferManager here since we
// guarantee |request_buffer_callback| is only used by RequestBuilder. In
// addition, since C++ destroys member variables in reverse order of
// construction, we can ensure that RequestBuilder will be destroyed prior
// to StreamBufferManager since RequestBuilder constructs after
// StreamBufferManager.
auto request_buffer_callback =
base::BindRepeating(&StreamBufferManager::RequestBufferForCaptureRequest,
base::Unretained(stream_buffer_manager_.get()));
request_builder_ = std::make_unique<RequestBuilder>(
device_context_, std::move(request_buffer_callback));
}
RequestManager::~RequestManager() = default;
void RequestManager::SetUpStreamsAndBuffers(
VideoCaptureFormat capture_format,
const cros::mojom::CameraMetadataPtr& static_metadata,
std::vector<cros::mojom::Camera3StreamPtr> streams) {
// The partial result count metadata is optional; defaults to 1 in case it
// is not set in the static metadata.
const cros::mojom::CameraMetadataEntryPtr* partial_count = GetMetadataEntry(
static_metadata,
cros::mojom::CameraMetadataTag::ANDROID_REQUEST_PARTIAL_RESULT_COUNT);
if (partial_count) {
partial_result_count_ =
*reinterpret_cast<int32_t*>((*partial_count)->data.data());
}
auto pipeline_depth = GetMetadataEntryAsSpan<uint8_t>(
static_metadata,
cros::mojom::CameraMetadataTag::ANDROID_REQUEST_PIPELINE_MAX_DEPTH);
CHECK_EQ(pipeline_depth.size(), 1u);
pipeline_depth_ = pipeline_depth[0];
preview_buffers_queued_ = 0;
// Set the last received frame number for each stream types to be undefined.
for (const auto& stream : streams) {
StreamType stream_type = StreamIdToStreamType(stream->id);
last_received_frame_number_map_[stream_type] = kUndefinedFrameNumber;
}
stream_buffer_manager_->SetUpStreamsAndBuffers(
capture_format, static_metadata, std::move(streams));
}
cros::mojom::Camera3StreamPtr RequestManager::GetStreamConfiguration(
StreamType stream_type) {
return stream_buffer_manager_->GetStreamConfiguration(stream_type);
}
bool RequestManager::HasStreamsConfiguredForTakePhoto() {
if (stream_buffer_manager_->IsReprocessSupported()) {
return stream_buffer_manager_->HasStreamsConfigured(
{StreamType::kPreviewOutput, StreamType::kJpegOutput,
StreamType::kYUVInput, StreamType::kYUVOutput});
} else {
return stream_buffer_manager_->HasStreamsConfigured(
{StreamType::kPreviewOutput, StreamType::kJpegOutput});
}
}
void RequestManager::StartPreview(
cros::mojom::CameraMetadataPtr preview_settings) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
DCHECK(repeating_request_settings_.is_null());
capturing_ = true;
repeating_request_settings_ = std::move(preview_settings);
PrepareCaptureRequest();
}
void RequestManager::StopPreview(base::OnceCallback<void(int32_t)> callback) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
capturing_ = false;
repeating_request_settings_ = nullptr;
if (callback) {
capture_interface_->Flush(std::move(callback));
}
}
void RequestManager::TakePhoto(cros::mojom::CameraMetadataPtr settings,
ReprocessTaskQueue reprocess_tasks) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
if (stream_buffer_manager_->IsReprocessSupported()) {
pending_reprocess_tasks_queue_.push(std::move(reprocess_tasks));
} else {
// There should be only one reprocess task in the queue which is format
// conversion task.
DCHECK_EQ(reprocess_tasks.size(), 1lu);
take_photo_callback_queue_.push(
std::move(reprocess_tasks.front().callback));
}
take_photo_settings_queue_.push(std::move(settings));
}
base::WeakPtr<RequestManager> RequestManager::GetWeakPtr() {
return weak_ptr_factory_.GetWeakPtr();
}
void RequestManager::AddResultMetadataObserver(
ResultMetadataObserver* observer) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
DCHECK(!result_metadata_observers_.count(observer));
result_metadata_observers_.insert(observer);
}
void RequestManager::RemoveResultMetadataObserver(
ResultMetadataObserver* observer) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
DCHECK(result_metadata_observers_.count(observer));
result_metadata_observers_.erase(observer);
}
void RequestManager::SetCaptureMetadata(cros::mojom::CameraMetadataTag tag,
cros::mojom::EntryType type,
size_t count,
std::vector<uint8_t> value) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
cros::mojom::CameraMetadataEntryPtr setting =
cros::mojom::CameraMetadataEntry::New();
setting->tag = tag;
setting->type = type;
setting->count = count;
setting->data = std::move(value);
capture_settings_override_.push_back(std::move(setting));
}
void RequestManager::SetRepeatingCaptureMetadata(
cros::mojom::CameraMetadataTag tag,
cros::mojom::EntryType type,
size_t count,
std::vector<uint8_t> value) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
cros::mojom::CameraMetadataEntryPtr setting =
cros::mojom::CameraMetadataEntry::New();
setting->tag = tag;
setting->type = type;
setting->count = count;
setting->data = std::move(value);
capture_settings_repeating_override_[tag] = std::move(setting);
}
void RequestManager::UnsetRepeatingCaptureMetadata(
cros::mojom::CameraMetadataTag tag) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
auto it = capture_settings_repeating_override_.find(tag);
if (it == capture_settings_repeating_override_.end()) {
LOG(ERROR) << "Unset a non-existent metadata: " << tag;
return;
}
capture_settings_repeating_override_.erase(it);
}
void RequestManager::SetJpegOrientation(
cros::mojom::CameraMetadataPtr* settings,
int32_t orientation) {
auto e = BuildMetadataEntry(
cros::mojom::CameraMetadataTag::ANDROID_JPEG_ORIENTATION, orientation);
AddOrUpdateMetadataEntry(settings, std::move(e));
}
void RequestManager::SetSensorTimestamp(
cros::mojom::CameraMetadataPtr* settings,
uint64_t shutter_timestamp) {
auto e = BuildMetadataEntry(
cros::mojom::CameraMetadataTag::ANDROID_SENSOR_TIMESTAMP,
base::checked_cast<int64_t>(shutter_timestamp));
AddOrUpdateMetadataEntry(settings, std::move(e));
}
void RequestManager::SetZeroShutterLag(cros::mojom::CameraMetadataPtr* settings,
bool enabled) {
auto e = BuildMetadataEntry(
cros::mojom::CameraMetadataTag::ANDROID_CONTROL_ENABLE_ZSL,
static_cast<uint8_t>(enabled));
AddOrUpdateMetadataEntry(settings, std::move(e));
}
void RequestManager::PrepareCaptureRequest() {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
if (!capturing_) {
return;
}
// There are two types of devices, each has several possible combinations of
// streams.
//
// For device with reprocess capability:
// 1. Preview
// 2. Capture (YuvOutput)
// 3. Preview + Capture (YuvOutput)
// 4. Reprocess (YuvInput + BlobOutput)
//
// For device without reprocess capability:
// 1. Preview
// 2. Capture (BlobOutput)
// 3. Preview + Capture (BlobOutput)
std::set<StreamType> stream_types;
cros::mojom::CameraMetadataPtr settings;
TakePhotoCallback callback = base::NullCallback();
base::Optional<uint64_t> input_buffer_id;
cros::mojom::Effect reprocess_effect = cros::mojom::Effect::NO_EFFECT;
bool is_reprocess_request = false;
bool is_preview_request = false;
bool is_oneshot_request = false;
// First, check if there are pending reprocess tasks.
is_reprocess_request = TryPrepareReprocessRequest(
&stream_types, &settings, &callback, &input_buffer_id, &reprocess_effect);
// If there is no pending reprocess task, then check if there are pending
// one-shot requests. And also try to put preview in the request.
if (!is_reprocess_request) {
is_preview_request = TryPreparePreviewRequest(&stream_types, &settings);
// Order matters here. If the preview request and oneshot request are both
// added in single capture request, the settings will be overridden by the
// later.
is_oneshot_request =
TryPrepareOneShotRequest(&stream_types, &settings, &callback);
}
if (!is_reprocess_request && !is_oneshot_request && !is_preview_request) {
// We have to keep the pipeline full.
if (preview_buffers_queued_ < pipeline_depth_) {
ipc_task_runner_->PostTask(
FROM_HERE,
base::BindOnce(&RequestManager::PrepareCaptureRequest, GetWeakPtr()));
}
return;
}
auto capture_request = request_builder_->BuildRequest(
std::move(stream_types), std::move(settings), input_buffer_id);
CHECK_GT(capture_request->output_buffers.size(), 0u);
CaptureResult& pending_result =
pending_results_[capture_request->frame_number];
pending_result.unsubmitted_buffer_count =
capture_request->output_buffers.size();
pending_result.input_buffer_id = input_buffer_id;
pending_result.reprocess_effect = reprocess_effect;
pending_result.still_capture_callback = std::move(callback);
pending_result.orientation = device_context_->GetCameraFrameRotation();
// For reprocess supported devices, bind the ReprocessTaskQueue with this
// frame number. Once the shot result is returned, we will rebind the
// ReprocessTaskQueue with the id of YUV buffer which contains the result.
if (is_oneshot_request && stream_buffer_manager_->IsReprocessSupported() &&
!pending_reprocess_tasks_queue_.empty()) {
frame_number_reprocess_tasks_map_[capture_request->frame_number] =
std::move(pending_reprocess_tasks_queue_.front());
pending_reprocess_tasks_queue_.pop();
}
if (is_preview_request) {
++preview_buffers_queued_;
}
// Currently only 3A related settings will be applied, which means we don't
// need to apply for reprocess request.
if (!is_reprocess_request) {
UpdateCaptureSettings(&capture_request->settings);
}
capture_interface_->ProcessCaptureRequest(
std::move(capture_request),
base::BindOnce(&RequestManager::OnProcessedCaptureRequest, GetWeakPtr()));
}
bool RequestManager::TryPrepareReprocessRequest(
std::set<StreamType>* stream_types,
cros::mojom::CameraMetadataPtr* settings,
TakePhotoCallback* callback,
base::Optional<uint64_t>* input_buffer_id,
cros::mojom::Effect* reprocess_effect) {
if (buffer_id_reprocess_job_info_map_.empty() ||
!stream_buffer_manager_->HasFreeBuffers(kYUVReprocessStreams)) {
return false;
}
// Consume reprocess task.
ReprocessJobInfo* reprocess_job_info;
for (auto& it : buffer_id_reprocess_job_info_map_) {
if (processing_buffer_ids_.count(it.first) == 0) {
*input_buffer_id = it.first;
reprocess_job_info = &it.second;
break;
}
}
if (!*input_buffer_id) {
return false;
}
ReprocessTaskQueue* reprocess_task_queue = &reprocess_job_info->task_queue;
ReprocessTask task = std::move(reprocess_task_queue->front());
reprocess_task_queue->pop();
stream_types->insert(kYUVReprocessStreams);
// Prepare metadata by adding extra metadata.
*settings = reprocess_job_info->metadata.Clone();
SetSensorTimestamp(settings, reprocess_job_info->shutter_timestamp);
SetJpegOrientation(settings, reprocess_job_info->orientation);
for (auto& metadata : task.extra_metadata) {
AddOrUpdateMetadataEntry(settings, std::move(metadata));
}
*callback = std::move(task.callback);
*reprocess_effect = task.effect;
processing_buffer_ids_.insert(**input_buffer_id);
// Remove the mapping from map if all tasks consumed.
if (reprocess_task_queue->empty()) {
buffer_id_reprocess_job_info_map_.erase(**input_buffer_id);
}
return true;
}
bool RequestManager::TryPreparePreviewRequest(
std::set<StreamType>* stream_types,
cros::mojom::CameraMetadataPtr* settings) {
if (preview_buffers_queued_ == pipeline_depth_) {
return false;
}
if (!stream_buffer_manager_->HasFreeBuffers({StreamType::kPreviewOutput})) {
// Try our best to reserve an usable buffer. If the reservation still
// fails, then we'd have to drop the camera frame.
DLOG(WARNING) << "Late request for reserving preview buffer";
stream_buffer_manager_->ReserveBuffer(StreamType::kPreviewOutput);
if (!stream_buffer_manager_->HasFreeBuffers({StreamType::kPreviewOutput})) {
DLOG(WARNING) << "No free buffer for preview stream";
return false;
}
}
stream_types->insert({StreamType::kPreviewOutput});
*settings = repeating_request_settings_.Clone();
return true;
}
bool RequestManager::TryPrepareOneShotRequest(
std::set<StreamType>* stream_types,
cros::mojom::CameraMetadataPtr* settings,
TakePhotoCallback* callback) {
if (stream_buffer_manager_->IsReprocessSupported()) {
// For devices that support reprocess, fill the frame data in YUV buffer and
// reprocess on that YUV buffer.
if (take_photo_settings_queue_.empty() ||
!stream_buffer_manager_->HasFreeBuffers({StreamType::kYUVOutput})) {
return false;
}
stream_types->insert({StreamType::kYUVOutput});
*settings = std::move(take_photo_settings_queue_.front());
} else {
// For devices that do not support reprocess, fill the frame data in BLOB
// buffer and fill the callback.
if (take_photo_settings_queue_.empty() ||
take_photo_callback_queue_.empty() ||
!stream_buffer_manager_->HasFreeBuffers({StreamType::kJpegOutput})) {
return false;
}
stream_types->insert({StreamType::kJpegOutput});
*callback = std::move(take_photo_callback_queue_.front());
take_photo_callback_queue_.pop();
*settings = std::move(take_photo_settings_queue_.front());
SetJpegOrientation(settings, device_context_->GetCameraFrameRotation());
}
SetZeroShutterLag(settings, true);
take_photo_settings_queue_.pop();
return true;
}
void RequestManager::OnProcessedCaptureRequest(int32_t result) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
if (!capturing_) {
return;
}
if (result != 0) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerProcessCaptureRequestFailed,
FROM_HERE,
std::string("Process capture request failed: ") +
base::safe_strerror(-result));
return;
}
PrepareCaptureRequest();
}
void RequestManager::ProcessCaptureResult(
cros::mojom::Camera3CaptureResultPtr result) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
if (!capturing_) {
return;
}
uint32_t frame_number = result->frame_number;
// A new partial result may be created in either ProcessCaptureResult or
// Notify.
CaptureResult& pending_result = pending_results_[frame_number];
// |result->partial_result| is set to 0 if the capture result contains only
// the result buffer handles and no result metadata.
if (result->partial_result != 0) {
uint32_t result_id = result->partial_result;
if (result_id > partial_result_count_) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerInvalidPendingResultId,
FROM_HERE,
std::string("Invalid pending_result id: ") +
base::NumberToString(result_id));
return;
}
if (pending_result.partial_metadata_received.count(result_id)) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedDuplicatedPartialMetadata,
FROM_HERE,
std::string("Received duplicated partial metadata: ") +
base::NumberToString(result_id));
return;
}
DVLOG(2) << "Received partial result " << result_id << " for frame "
<< frame_number;
pending_result.partial_metadata_received.insert(result_id);
MergeMetadata(&pending_result.metadata, result->result);
}
if (result->output_buffers) {
if (result->output_buffers->size() > kMaxConfiguredStreams) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerIncorrectNumberOfOutputBuffersReceived,
FROM_HERE,
std::string("Incorrect number of output buffers received: ") +
base::NumberToString(result->output_buffers->size()));
return;
}
for (auto& stream_buffer : result->output_buffers.value()) {
DVLOG(2) << "Received capture result for frame " << frame_number
<< " stream_id: " << stream_buffer->stream_id;
StreamType stream_type = StreamIdToStreamType(stream_buffer->stream_id);
if (stream_type == StreamType::kUnknown) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerInvalidTypeOfOutputBuffersReceived,
FROM_HERE,
std::string("Invalid type of output buffers received: ") +
base::NumberToString(stream_buffer->stream_id));
return;
}
// The camera HAL v3 API specifies that only one capture result can carry
// the result buffer for any given frame number.
if (last_received_frame_number_map_[stream_type] ==
kUndefinedFrameNumber) {
last_received_frame_number_map_[stream_type] = frame_number;
} else {
if (last_received_frame_number_map_[stream_type] == frame_number) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedMultipleResultBuffersForFrame,
FROM_HERE,
std::string("Received multiple result buffers for frame ") +
base::NumberToString(frame_number) +
std::string(" for stream ") +
base::NumberToString(stream_buffer->stream_id));
return;
} else if (last_received_frame_number_map_[stream_type] >
frame_number) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedFrameIsOutOfOrder,
FROM_HERE,
std::string("Received frame is out-of-order; expect frame number "
"greater than ") +
base::NumberToString(
last_received_frame_number_map_[stream_type]) +
std::string(" but got ") +
base::NumberToString(frame_number));
} else {
last_received_frame_number_map_[stream_type] = frame_number;
}
}
if (stream_buffer->status ==
cros::mojom::Camera3BufferStatus::CAMERA3_BUFFER_STATUS_ERROR) {
// If the buffer is marked as error, its content is discarded for this
// frame. Send the buffer to the free list directly through
// SubmitCaptureResult.
SubmitCaptureResult(frame_number, stream_type,
std::move(stream_buffer));
} else {
pending_result.buffers[stream_type] = std::move(stream_buffer);
}
}
}
TRACE_EVENT1("camera", "Capture Result", "frame_number", frame_number);
TrySubmitPendingBuffers(frame_number);
}
void RequestManager::TrySubmitPendingBuffers(uint32_t frame_number) {
if (!pending_results_.count(frame_number)) {
return;
}
CaptureResult& pending_result = pending_results_[frame_number];
// If the metadata is not ready, or the shutter time is not set, just
// returned.
bool is_ready_to_submit =
pending_result.partial_metadata_received.size() > 0 &&
*pending_result.partial_metadata_received.rbegin() ==
partial_result_count_ &&
!pending_result.reference_time.is_null();
if (!is_ready_to_submit) {
return;
}
if (!pending_result.buffers.empty()) {
// Put pending buffers into local map since |pending_result| might be
// deleted in SubmitCaptureResult(). We should not reference pending_result
// after SubmitCaptureResult() is triggered.
std::map<StreamType, cros::mojom::Camera3StreamBufferPtr> buffers =
std::move(pending_result.buffers);
for (auto& it : buffers) {
SubmitCaptureResult(frame_number, it.first, std::move(it.second));
}
}
}
void RequestManager::Notify(cros::mojom::Camera3NotifyMsgPtr message) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
if (!capturing_) {
return;
}
if (message->type == cros::mojom::Camera3MsgType::CAMERA3_MSG_ERROR) {
auto error = std::move(message->message->get_error());
uint32_t frame_number = error->frame_number;
uint64_t error_stream_id = error->error_stream_id;
StreamType stream_type = StreamIdToStreamType(error_stream_id);
if (stream_type == StreamType::kUnknown) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerUnknownStreamInCamera3NotifyMsg,
FROM_HERE,
std::string("Unknown stream in Camera3NotifyMsg: ") +
base::NumberToString(error_stream_id));
return;
}
cros::mojom::Camera3ErrorMsgCode error_code = error->error_code;
HandleNotifyError(frame_number, stream_type, error_code);
} else if (message->type ==
cros::mojom::Camera3MsgType::CAMERA3_MSG_SHUTTER) {
auto shutter = std::move(message->message->get_shutter());
uint32_t frame_number = shutter->frame_number;
uint64_t shutter_time = shutter->timestamp;
DVLOG(2) << "Received shutter time for frame " << frame_number;
if (!shutter_time) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerReceivedInvalidShutterTime,
FROM_HERE,
std::string("Received invalid shutter time: ") +
base::NumberToString(shutter_time));
return;
}
CaptureResult& pending_result = pending_results_[frame_number];
pending_result.shutter_timestamp = shutter_time;
// Shutter timestamp is in ns.
base::TimeTicks reference_time =
base::TimeTicks() +
base::TimeDelta::FromMicroseconds(shutter_time / 1000);
pending_result.reference_time = reference_time;
if (first_frame_shutter_time_.is_null()) {
// Record the shutter time of the first frame for calculating the
// timestamp.
first_frame_shutter_time_ = reference_time;
}
pending_result.timestamp = reference_time - first_frame_shutter_time_;
if (camera_app_device_ && pending_result.still_capture_callback) {
camera_app_device_->OnShutterDone();
}
TrySubmitPendingBuffers(frame_number);
}
}
void RequestManager::HandleNotifyError(
uint32_t frame_number,
StreamType stream_type,
cros::mojom::Camera3ErrorMsgCode error_code) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
std::string warning_msg;
switch (error_code) {
case cros::mojom::Camera3ErrorMsgCode::CAMERA3_MSG_ERROR_DEVICE:
// Fatal error and no more frames will be produced by the device.
device_context_->SetErrorState(
media::VideoCaptureError::kCrosHalV3BufferManagerFatalDeviceError,
FROM_HERE, "Fatal device error");
return;
case cros::mojom::Camera3ErrorMsgCode::CAMERA3_MSG_ERROR_REQUEST:
// An error has occurred in processing the request; the request
// specified by |frame_number| has been dropped by the camera device.
// Subsequent requests are unaffected.
//
// The HAL will call ProcessCaptureResult with the buffers' state set to
// STATUS_ERROR. The content of the buffers will be dropped and the
// buffers will be reused in SubmitCaptureResult.
warning_msg =
std::string("An error occurred while processing request for frame ") +
base::NumberToString(frame_number);
break;
case cros::mojom::Camera3ErrorMsgCode::CAMERA3_MSG_ERROR_RESULT:
// An error has occurred in producing the output metadata buffer for a
// result; the output metadata will not be available for the frame
// specified by |frame_number|. Subsequent requests are unaffected.
warning_msg = std::string(
"An error occurred while producing result "
"metadata for frame ") +
base::NumberToString(frame_number);
break;
case cros::mojom::Camera3ErrorMsgCode::CAMERA3_MSG_ERROR_BUFFER:
// An error has occurred in placing the output buffer into a stream for
// a request. |frame_number| specifies the request for which the buffer
// was dropped, and |stream_type| specifies the stream that dropped
// the buffer.
//
// The HAL will call ProcessCaptureResult with the buffer's state set to
// STATUS_ERROR. The content of the buffer will be dropped and the
// buffer will be reused in SubmitCaptureResult.
warning_msg =
std::string(
"An error occurred while filling output buffer for frame ") +
base::NumberToString(frame_number);
break;
default:
// To eliminate the warning for not handling CAMERA3_MSG_NUM_ERRORS
break;
}
LOG(WARNING) << warning_msg << " with type = " << stream_type;
device_context_->LogToClient(warning_msg);
// If the buffer is already returned by the HAL, submit it and we're done.
if (pending_results_.count(frame_number)) {
auto it = pending_results_[frame_number].buffers.find(stream_type);
if (it != pending_results_[frame_number].buffers.end()) {
auto stream_buffer = std::move(it->second);
pending_results_[frame_number].buffers.erase(stream_type);
SubmitCaptureResult(frame_number, stream_type, std::move(stream_buffer));
}
}
}
void RequestManager::SubmitCaptureResult(
uint32_t frame_number,
StreamType stream_type,
cros::mojom::Camera3StreamBufferPtr stream_buffer) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
DCHECK(pending_results_.count(frame_number));
CaptureResult& pending_result = pending_results_[frame_number];
DVLOG(2) << "Submit capture result of frame " << frame_number
<< " for stream " << static_cast<int>(stream_type);
for (auto* observer : result_metadata_observers_) {
observer->OnResultMetadataAvailable(frame_number, pending_result.metadata);
}
if (camera_app_device_) {
camera_app_device_->OnResultMetadataAvailable(
pending_result.metadata,
static_cast<cros::mojom::StreamType>(stream_type));
}
// Wait on release fence before delivering the result buffer to client.
if (stream_buffer->release_fence.is_valid()) {
const int kSyncWaitTimeoutMs = 1000;
mojo::PlatformHandle fence =
mojo::UnwrapPlatformHandle(std::move(stream_buffer->release_fence));
if (!fence.is_valid()) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToUnwrapReleaseFenceFd,
FROM_HERE, "Failed to unwrap release fence fd");
return;
}
if (sync_wait(fence.GetFD().get(), kSyncWaitTimeoutMs)) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerSyncWaitOnReleaseFenceTimedOut,
FROM_HERE, "Sync wait on release fence timed out");
return;
}
}
uint64_t buffer_ipc_id = stream_buffer->buffer_id;
// Deliver the captured data to client.
if (stream_buffer->status ==
cros::mojom::Camera3BufferStatus::CAMERA3_BUFFER_STATUS_OK) {
if (stream_type == StreamType::kPreviewOutput) {
SubmitCapturedPreviewBuffer(frame_number, buffer_ipc_id);
} else if (stream_type == StreamType::kJpegOutput) {
SubmitCapturedJpegBuffer(frame_number, buffer_ipc_id);
} else if (stream_type == StreamType::kYUVOutput) {
DCHECK_GT(pending_result.shutter_timestamp, 0UL);
ReprocessJobInfo reprocess_job_info(
std::move(frame_number_reprocess_tasks_map_[frame_number]),
std::move(pending_result.metadata), pending_result.shutter_timestamp,
pending_result.orientation);
buffer_id_reprocess_job_info_map_.emplace(buffer_ipc_id,
std::move(reprocess_job_info));
frame_number_reprocess_tasks_map_.erase(frame_number);
// Don't release the buffer since we will need it as input buffer for
// reprocessing. We will release it until all reprocess tasks for this
// buffer are done.
}
} else {
stream_buffer_manager_->ReleaseBufferFromCaptureResult(stream_type,
buffer_ipc_id);
}
if (stream_type == StreamType::kPreviewOutput) {
--preview_buffers_queued_;
}
pending_result.unsubmitted_buffer_count--;
if (pending_result.unsubmitted_buffer_count == 0) {
pending_results_.erase(frame_number);
}
// Every time a buffer is released, try to prepare another capture request
// again.
PrepareCaptureRequest();
}
void RequestManager::SubmitCapturedPreviewBuffer(uint32_t frame_number,
uint64_t buffer_ipc_id) {
const CaptureResult& pending_result = pending_results_[frame_number];
if (video_capture_use_gmb_) {
VideoCaptureFormat format;
base::Optional<VideoCaptureDevice::Client::Buffer> buffer =
stream_buffer_manager_->AcquireBufferForClientById(
StreamType::kPreviewOutput, buffer_ipc_id, &format);
CHECK(buffer);
// TODO: Figure out the right color space for the camera frame. We may need
// to populate the camera metadata with the color space reported by the V4L2
// device.
VideoFrameMetadata metadata;
if (base::FeatureList::IsEnabled(
features::kDisableCameraFrameRotationAtSource)) {
// Camera frame rotation at source is disabled, so we record the intended
// video frame rotation in the metadata. The consumer of the video frame
// is responsible for taking care of the frame rotation.
auto translate_rotation = [](const int rotation) -> VideoRotation {
switch (rotation) {
case 0:
return VideoRotation::VIDEO_ROTATION_0;
case 90:
return VideoRotation::VIDEO_ROTATION_90;
case 180:
return VideoRotation::VIDEO_ROTATION_180;
case 270:
return VideoRotation::VIDEO_ROTATION_270;
}
return VideoRotation::VIDEO_ROTATION_0;
};
metadata.rotation =
translate_rotation(device_context_->GetRotationForDisplay());
} else {
// All frames are pre-rotated to the display orientation.
metadata.rotation = VideoRotation::VIDEO_ROTATION_0;
}
device_context_->SubmitCapturedVideoCaptureBuffer(
client_type_, std::move(*buffer), format, pending_result.reference_time,
pending_result.timestamp, metadata);
// |buffer| ownership is transferred to client, so we need to reserve a
// new video buffer.
stream_buffer_manager_->ReserveBuffer(StreamType::kPreviewOutput);
} else {
gfx::GpuMemoryBuffer* gmb = stream_buffer_manager_->GetGpuMemoryBufferById(
StreamType::kPreviewOutput, buffer_ipc_id);
CHECK(gmb);
device_context_->SubmitCapturedGpuMemoryBuffer(
client_type_, gmb,
stream_buffer_manager_->GetStreamCaptureFormat(
StreamType::kPreviewOutput),
pending_result.reference_time, pending_result.timestamp);
stream_buffer_manager_->ReleaseBufferFromCaptureResult(
StreamType::kPreviewOutput, buffer_ipc_id);
}
}
void RequestManager::SubmitCapturedJpegBuffer(uint32_t frame_number,
uint64_t buffer_ipc_id) {
CaptureResult& pending_result = pending_results_[frame_number];
DCHECK(pending_result.still_capture_callback);
gfx::Size buffer_dimension =
stream_buffer_manager_->GetBufferDimension(StreamType::kJpegOutput);
gfx::GpuMemoryBuffer* gmb = stream_buffer_manager_->GetGpuMemoryBufferById(
StreamType::kJpegOutput, buffer_ipc_id);
CHECK(gmb);
if (video_capture_use_gmb_ && !gmb->Map()) {
device_context_->SetErrorState(
media::VideoCaptureError::
kCrosHalV3BufferManagerFailedToCreateGpuMemoryBuffer,
FROM_HERE, "Failed to map GPU memory buffer");
return;
}
const Camera3JpegBlob* header = reinterpret_cast<Camera3JpegBlob*>(
reinterpret_cast<const uintptr_t>(gmb->memory(0)) +
buffer_dimension.width() - sizeof(Camera3JpegBlob));
if (header->jpeg_blob_id != kCamera3JpegBlobId) {
device_context_->SetErrorState(
media::VideoCaptureError::kCrosHalV3BufferManagerInvalidJpegBlob,
FROM_HERE, "Invalid JPEG blob");
if (video_capture_use_gmb_) {
gmb->Unmap();
}
return;
}
// Still capture result from HALv3 already has orientation info in EXIF,
// so just provide 0 as screen rotation in |blobify_callback_| parameters.
mojom::BlobPtr blob = blobify_callback_.Run(
reinterpret_cast<const uint8_t*>(gmb->memory(0)), header->jpeg_size,
stream_buffer_manager_->GetStreamCaptureFormat(StreamType::kJpegOutput),
0);
if (blob) {
int task_status = kReprocessSuccess;
if (stream_buffer_manager_->IsReprocessSupported()) {
task_status = CameraAppDeviceImpl::GetReprocessReturnCode(
pending_result.reprocess_effect, &pending_result.metadata);
}
std::move(pending_result.still_capture_callback)
.Run(task_status, std::move(blob));
} else {
// TODO(wtlee): If it is fatal, we should set error state here.
LOG(ERROR) << "Failed to blobify the captured JPEG image";
}
if (pending_result.input_buffer_id) {
// Remove the id from processing list to run next reprocess task.
processing_buffer_ids_.erase(*pending_result.input_buffer_id);
// If all reprocess tasks are done for this buffer, release the buffer.
if (!base::Contains(buffer_id_reprocess_job_info_map_,
*pending_result.input_buffer_id)) {
stream_buffer_manager_->ReleaseBufferFromCaptureResult(
StreamType::kYUVOutput, *pending_result.input_buffer_id);
}
}
stream_buffer_manager_->ReleaseBufferFromCaptureResult(
StreamType::kJpegOutput, buffer_ipc_id);
if (video_capture_use_gmb_) {
gmb->Unmap();
}
}
void RequestManager::UpdateCaptureSettings(
cros::mojom::CameraMetadataPtr* capture_settings) {
DCHECK(ipc_task_runner_->BelongsToCurrentThread());
if (capture_settings_override_.empty() &&
capture_settings_repeating_override_.empty()) {
return;
}
for (const auto& setting : capture_settings_repeating_override_) {
AddOrUpdateMetadataEntry(capture_settings, setting.second.Clone());
}
for (auto& s : capture_settings_override_) {
AddOrUpdateMetadataEntry(capture_settings, std::move(s));
}
capture_settings_override_.clear();
SortCameraMetadata(capture_settings);
}
RequestManager::CaptureResult::CaptureResult()
: metadata(cros::mojom::CameraMetadata::New()),
unsubmitted_buffer_count(0) {}
RequestManager::CaptureResult::~CaptureResult() = default;
RequestManager::ReprocessJobInfo::ReprocessJobInfo(
ReprocessTaskQueue queue,
cros::mojom::CameraMetadataPtr metadata,
uint64_t timestamp,
int32_t orientation)
: task_queue(std::move(queue)),
metadata(std::move(metadata)),
shutter_timestamp(timestamp),
orientation(orientation) {}
RequestManager::ReprocessJobInfo::ReprocessJobInfo(ReprocessJobInfo&& info)
: task_queue(std::move(info.task_queue)),
metadata(std::move(info.metadata)),
shutter_timestamp(info.shutter_timestamp),
orientation(info.orientation) {}
RequestManager::ReprocessJobInfo::~ReprocessJobInfo() = default;
} // namespace media
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
70d127a2ed3a13a45d8671f6af67e3814491e6b8 | c6a7372402d35daf8ce41f3fb1f2fef9ad163a91 | /lab/Assignment 1/heapSort_tv.cpp | e685246c27de72607e5d609ce4ba5999b2243a3b | [] | no_license | mayank1101/Advance-Data-Structures-and-Algorithms-CSL-006P1M- | cec49de64e6e280186116c0ae54b57c2750dfff9 | 5650c8367d5ce4351e6419be9179e453c7522e74 | refs/heads/master | 2022-11-19T01:02:05.212658 | 2020-07-21T16:00:44 | 2020-07-21T16:00:44 | 266,050,540 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,993 | cpp | #include<iostream>
#include<fstream>
#include<sys/time.h>
#include<iomanip>
#include<cstring>
using namespace std;
int *arr = new int[10000];
static int count;
void readFileBest(){
ifstream File("bestcase.txt",ios::in); //create file object and open file to read
if(File.is_open()){ // if file is open
int x=0,i=0;
while(File >> x){ // read integer from file one by one
arr[i++] = x; //store read integer into array
}
}
else{
cout << "Unable to read from file\n";
}
}
void readFileWorst(){
ifstream File("worstcase.txt",ios::in); //create file object and open file to read
if(File.is_open()){ // if file is open
int x=0,i=0;
while(File >> x){ // read integer from file one by one
arr[i++] = x; //store read integer into array
}
}
else{
cout << "Unable to read from file\n";
}
}
void readFileAverage(){
ifstream File("averagecase.txt",ios::in); //create file object and open file to read
if(File.is_open()){ // if file is open
int x=0,i=0;
while(File >> x){ // read integer from file one by one
arr[i++] = x; //store read integer into array
}
}
else{
cout << "Unable to read from file\n";
}
}
void swap(int *a, int *b)
{
count++;
int temp = *a;
*a = *b;
*b = temp;
}
void max_heapify(int arr[], int n, int parent_index)
{
int largest = parent_index;
int left_child_index = 2*parent_index+1;
int right_child_index = 2*parent_index+2;
if(left_child_index < n && arr[left_child_index] > arr[largest]){
largest = left_child_index;
}
else if(right_child_index < n && arr[right_child_index] > arr[largest]){
largest = right_child_index;
}
if(largest != parent_index){
swap(&arr[largest], &arr[parent_index]);
max_heapify(arr,n,largest);
}
}
void heapSort(int arr[], int n)
{
for(int i=n/2-1;i>=0;i--)
{
max_heapify(arr,n,i);
}
for(int i=n-1;i>=0;i--)
{
swap(&arr[i],&arr[0]);
max_heapify(arr,i,0);
}
}
void printArr(int arr[], int n){
for(int i=0;i<n;i++){
cout << arr[i] << " ";
}
cout << "\n";
}
int main(void)
{
cout << "<--------------------------------------------------------------->\n";
cout << "Average Case : \n";
readFileAverage(); //read data form file
struct timeval tvalStart, tvalEnd; //create struct timeval type variables
gettimeofday(&tvalStart,NULL);
count=0;
heapSort(arr,10000); //invock heapSort
gettimeofday(&tvalEnd,NULL);
double time_taken = (tvalEnd.tv_usec - tvalStart.tv_usec);
cout << "Number of swaps/exchanges : " << count << "\n";
cout << "Using timeval, Elapsed Time: " << time_taken << " micro seconds\n" << setprecision(9);
cout << "<--------------------------------------------------------------->\n";
cout << "Worst Case : \n";
readFileWorst(); //read data form file
struct timeval tvalStart1, tvalEnd1;
gettimeofday(&tvalStart1,NULL);
count=0;
heapSort(arr,10000); //invock heapSort
gettimeofday(&tvalEnd1,NULL);
double time_taken1 = (tvalEnd1.tv_usec - tvalStart1.tv_usec);
cout << "Number of swaps/exchanges : " << count << "\n";
cout << "Using timeval, Elapsed Time: " << time_taken1 << " micro seconds\n" << setprecision(9);
cout << "<--------------------------------------------------------------->\n";
cout << "Best Case : \n";
readFileBest(); //read data form file
struct timeval tvalStart2, tvalEnd2;
gettimeofday(&tvalStart2,NULL);
count=0;
heapSort(arr,10000); //invock heapSort
gettimeofday(&tvalEnd2,NULL);
double time_taken2 = (tvalEnd2.tv_usec - tvalStart2.tv_usec);
cout << "Number of swaps/exchanges : " << count << "\n";
cout << "Using timeval, Elapsed Time: " << time_taken2 << " micro seconds\n" << setprecision(9);
cout << "<--------------------------------------------------------------->\n";
//get current system time
time_t mytime = time(NULL);
char * time_str = ctime(&mytime);
time_str[strlen(time_str)-1] = '\0';
cout << "Finished computation on : " << time_str;
return 0;
}
| [
"mayank1101ganesh@gmail.com"
] | mayank1101ganesh@gmail.com |
112fe03db98b9164a550fb268b7ca812fdfd7d18 | 686eaf8071fad1b26e9b5ce6b66b94e88b6bb002 | /HW2/Code/Neuron_arg.cpp | 0cd75e2e39dd123d03c4a8ead2401a07452272ee | [] | no_license | ascv0228/SystemC | c8f846d9f1b5ecc6a96613ebeded8e2eb209fbf7 | 9fa29631355f297775b439f6bad7de29238d0b01 | refs/heads/main | 2023-04-03T18:21:33.341369 | 2021-04-14T03:43:37 | 2021-04-14T03:43:37 | 357,764,051 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 381 | cpp | #include "Neuron_arg.h"
void Neuron::neuron() {
// vvvvv put your code here vvvvv
float x, temp1, temp2;
x = input1 * w1 + input2 * w2 + b;
temp1 = 0.5 + 0.25*x - 1./48.*x*x*x + 1./480.*x*x*x*x*x;
if (temp1<=0){
temp2 = 0;
}
else if (temp1>=1){
temp2 = 1;
}
else {
temp2 = temp1;
}
output.write(temp2);
// ^^^^^ put your code here ^^^^^
} | [
"77038091+ascv0228@users.noreply.github.com"
] | 77038091+ascv0228@users.noreply.github.com |
57d3bd84a42b28a8d15a00d4747eeb550797f5ae | 7960814b707c4915ac18a3e2d0b7b228b0f8c40e | /Classes/breakout/BreakoutGameOver.cpp | a4c574e755ac4891c72f45b05f2ac24438e3d1a4 | [] | no_license | vienbk91/parkour | bc77b79d4238f641ba0acc12860b00cd009bd408 | 1a4d4544d426c3633b27a3c8ff54fc1c667cd80c | refs/heads/master | 2021-01-10T21:57:17.927090 | 2015-06-25T02:40:08 | 2015-06-25T02:40:08 | 38,023,437 | 1 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 1,090 | cpp | #include "breakout\BreakoutGameOver.h"
USING_NS_CC;
BreakoutGameOver::BreakoutGameOver()
{
}
BreakoutGameOver::~BreakoutGameOver()
{
}
BreakoutGameOver* BreakoutGameOver::create(const Color4B& color , int offset)
{
BreakoutGameOver* scene = new BreakoutGameOver();
if(scene && scene->initWithColor(color,offset))
{
scene->autorelease();
return scene;
}
CC_SAFE_DELETE(scene);
return NULL;
}
bool BreakoutGameOver::initWithColor(const Color4B& color , int offset)
{
if(!LayerColor::initWithColor(color))
{
return false;
}
Size visibleSize = Director::getInstance()->getVisibleSize();
_offset = offset;
cocos2d::log("Diem: %d" , offset);
auto labelScore = LabelTTF::create("Score : " , "Arial" , 50);
labelScore->setFontSize(50);
labelScore->setAnchorPoint(Vec2::ANCHOR_MIDDLE);
labelScore->setPosition(Vec2(visibleSize.width/2 , visibleSize.height /2));
std::stringstream text;
text << "Score : " << _offset << std::endl;
cocos2d::log("%s", text.str().c_str());
labelScore->setString(text.str().c_str());
this->addChild(labelScore);
return true;
} | [
"vienbk91@gmail.com"
] | vienbk91@gmail.com |
8525ea26b94c1ba95b0803f43bac5b1f84b5d86f | 27fbce7c075cd9f4cee7e1250e82cd56a7699c02 | /tests/ami_test/ami_collocation/collocation_tester.h | 0703fdc6867f48c9edca78438620c472d39aaa43 | [
"MIT"
] | permissive | jwillemsen/taox11 | fe11af6a7185c25d0f236b80c608becbdbf3c8c3 | f16805cfdd5124d93d2426094191f15e10f53123 | refs/heads/master | 2023-09-04T18:23:46.570811 | 2023-08-14T19:50:01 | 2023-08-14T19:50:01 | 221,247,177 | 0 | 0 | MIT | 2023-09-04T14:53:28 | 2019-11-12T15:14:26 | C++ | UTF-8 | C++ | false | false | 1,146 | h | /**
* @file collocation_tester.h
* @author Marijke Hengstmengel
*
* @brief CORBA C++11 AMI Collocation Test
*
* @copyright Copyright (c) Remedy IT Expertise BV
*/
#ifndef TAOX11_AMI_COLLOCATION_TEST_H
#define TAOX11_AMI_COLLOCATION_TEST_H
#pragma once
#include "ami_testAmiC.h"
class Handler
: public virtual CORBA::amic_traits<A::AMI_Test>::replyhandler_base_type
{
public:
/// Constructor.
Handler () = default;
/// Destructor.
~Handler () = default;
void foo (int32_t ami_return_val,
int32_t out_l) override;
void foo_excep (
IDL::traits<::Messaging::ExceptionHolder>::ref_type excep_holder) override;
};
class Collocation_Test
{
public:
Collocation_Test ();
int shutdown ();
int init (int argc, ACE_TCHAR *argv[]);
int run ();
private:
IDL::traits<CORBA::ORB>::ref_type orb_;
IDL::traits<PortableServer::POA>::ref_type root_poa_;
IDL::traits<PortableServer::POAManager>::ref_type poa_manager_;
CORBA::amic_traits<A::AMI_Test>::replyhandler_ref_type test_handler_;
CORBA::amic_traits<A::AMI_Test>::ref_type ami_test_var_;
};
#endif /* TAOX11_AMI_COLLOCATION_TEST_H */
| [
"jwillemsen@remedy.nl"
] | jwillemsen@remedy.nl |
33cce36e67b09f0a61c15561cf70c05748baf72e | 974486287250f52425496ed5d04de0b9028168b6 | /src/ITokenizer.cc | 2d0a853e6a260763730a1510873be7a80c19b504 | [
"MIT"
] | permissive | koenvw/Tokenizer | 57c3fc078497b962e2f62209707c16606bbfcfd9 | 780cd628815812f4b786ea23b0b1ff66ebe26acf | refs/heads/master | 2020-03-28T04:02:30.468993 | 2018-09-13T13:24:29 | 2018-09-13T13:24:29 | 147,690,753 | 0 | 0 | MIT | 2018-09-06T14:59:21 | 2018-09-06T14:59:21 | null | UTF-8 | C++ | false | false | 1,579 | cc | #include "onmt/ITokenizer.h"
#include "onmt/SpaceTokenizer.h"
namespace onmt
{
const std::string ITokenizer::feature_marker("│");
void ITokenizer::tokenize(const std::string& text,
std::vector<std::string>& words,
std::vector<std::vector<std::string> >& features,
std::unordered_map<std::string, size_t>&) const
{
tokenize(text, words, features);
}
void ITokenizer::tokenize(const std::string& text, std::vector<std::string>& words) const
{
std::vector<std::vector<std::string> > features;
tokenize(text, words, features);
}
std::string ITokenizer::detokenize(const std::vector<std::string>& words) const
{
std::vector<std::vector<std::string> > features;
return detokenize(words, features);
}
std::string ITokenizer::tokenize(const std::string& text) const
{
std::vector<std::string> words;
std::vector<std::vector<std::string> > features;
tokenize(text, words, features);
std::string output;
for (size_t i = 0; i < words.size(); ++i)
{
if (i > 0)
output += " ";
output += words[i];
for (size_t j = 0; j < features.size(); ++j)
output += feature_marker + features[j][i];
}
return output;
}
std::string ITokenizer::detokenize(const std::string& text) const
{
std::vector<std::string> words;
std::vector<std::vector<std::string> > features;
SpaceTokenizer::get_instance().tokenize(text, words, features);
return detokenize(words, features);
}
}
| [
"guillaume.klein@systrangroup.com"
] | guillaume.klein@systrangroup.com |
54af99c47f6b46654da3e0c37c76aba18cb91155 | 8dceac1e58973cd7d99210907bdbdb910e799d36 | /ABC/163/A.cpp | c680e5853fc41bf21146ff17b08c2223e4052883 | [] | no_license | shna47/AtCoder | 0ff461aa3152b3e93bf3067309a5f598ba300944 | 69d42770b67d5fd46b7af3932fa576a63e545442 | refs/heads/master | 2022-10-31T14:07:04.022858 | 2020-06-11T06:21:21 | 2020-06-11T06:21:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 179 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i=0;i<n;++i)
typedef long long int ll;
int main(){
double R;
cin >> R;
cout << (R+R)*3.14 << endl;
}
| [
"hareruya_niconico@yahoo.co.jp"
] | hareruya_niconico@yahoo.co.jp |
56a046998f5f0b45eb2e474a684a89372f2e799a | 53c7da14be78c94f7571701f8afa23ccebfb106f | /Labs/Synthetic Lighting/My Solution/L0_21100157/morphing.cpp | 11bdd084793a1e9388fb7585c21e9766586d6179 | [] | no_license | raahimkhan/Computer-Graphics | 1fae9d8023087bb5d7dcece1b622bdcbbf92ad76 | ddd42abc51c25ea87117c953637ae934d81a38cb | refs/heads/main | 2023-02-05T22:18:29.987154 | 2020-12-26T10:57:44 | 2020-12-26T10:57:44 | 324,517,590 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 353 | cpp | #include <opencv2/highgui.hpp>
#include "filters.cpp"
using namespace cv;
//Part 1:
Mat morphing(Mat inp1, Mat inp2, float w){
Mat morph = (w*inp1) + ((1-w)*inp2) ;
return morph;
}
//Part 4:
Mat filtered_morphing(Mat inp1, Mat inp2, float w){
Mat morph = (w*colored_light(inp1, 2)) + ((1-w)*colored_light(inp2, 0)) ;
return morph;
}
| [
"21100157@lums.edu.pk"
] | 21100157@lums.edu.pk |
989955e66f96f98ee90d865ab201a2ed643c5ef7 | 72d9009d19e92b721d5cc0e8f8045e1145921130 | /BayesSUR/inst/testfiles/randIntUniform/libFuzzer_randIntUniform/randIntUniform_DeepState_TestHarness.cpp | 8633a24800461718d236f233553242a122422833 | [] | no_license | akhikolla/TestedPackages-NoIssues | be46c49c0836b3f0cf60e247087089868adf7a62 | eb8d498cc132def615c090941bc172e17fdce267 | refs/heads/master | 2023-03-01T09:10:17.227119 | 2021-01-25T19:44:44 | 2021-01-25T19:44:44 | 332,027,727 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,496 | cpp | // AUTOMATICALLY GENERATED BY RCPPDEEPSTATE PLEASE DO NOT EDIT BY HAND, INSTEAD EDIT
// randIntUniform_DeepState_TestHarness_generation.cpp and randIntUniform_DeepState_TestHarness_checks.cpp
#include <fstream>
#include <RInside.h>
#include <iostream>
#include <RcppDeepState.h>
#include <qs.h>
#include <DeepState.hpp>
int randIntUniform(const int a, const int b);
TEST(BayesSUR_deepstate_test,randIntUniform_test){
static int rinside_flag = 0;
if(rinside_flag == 0)
{
rinside_flag = 1;
RInside R;
} std::time_t current_timestamp = std::time(0);
std::cout << "input starts" << std::endl;
IntegerVector a(1);
a[0] = RcppDeepState_int();
std::string a_t = "/home/akhila/fuzzer_packages/fuzzedpackages/BayesSUR/inst/testfiles/randIntUniform/libFuzzer_randIntUniform/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_a.qs";
qs::c_qsave(a,a_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "a values: "<< a << std::endl;
IntegerVector b(1);
b[0] = RcppDeepState_int();
std::string b_t = "/home/akhila/fuzzer_packages/fuzzedpackages/BayesSUR/inst/testfiles/randIntUniform/libFuzzer_randIntUniform/libfuzzer_inputs/" + std::to_string(current_timestamp) +
"_b.qs";
qs::c_qsave(b,b_t,
"high", "zstd", 1, 15, true, 1);
std::cout << "b values: "<< b << std::endl;
std::cout << "input ends" << std::endl;
try{
randIntUniform(a[0],b[0]);
}
catch(Rcpp::exception& e){
std::cout<<"Exception Handled"<<std::endl;
}
}
| [
"akhilakollasrinu424jf@gmail.com"
] | akhilakollasrinu424jf@gmail.com |
63e7c4b90d3156f084eef7c7f2b3775dc1bc5f45 | dfd312b460385d72721389ee337ef4ca63af9106 | /Craftgame/PlayerCommandSender.h | 4966ef25a4e69965c4bda060d3a11609627b0eed | [] | no_license | Alex2772/Craftgame | 1e7b04242f274099668fb5aa99976d67c0c415d2 | 7c13a585da4ee00242113f851ad3d38a9e26c3b5 | refs/heads/unstable | 2021-10-24T17:36:36.163729 | 2021-09-26T14:05:01 | 2021-09-26T14:05:01 | 138,429,074 | 13 | 6 | null | 2019-11-26T21:24:19 | 2018-06-23T19:46:45 | C++ | UTF-8 | C++ | false | false | 300 | h | #pragma once
#include "CommandSender.h"
class EntityPlayerMP;
class PlayerCommandSender : public CommandSender {
private:
EntityPlayerMP* player;
public:
PlayerCommandSender(EntityPlayerMP* p);
virtual void sendMessage(std::string message);
EntityPlayerMP* getPlayer()
{
return player;
}
}; | [
"alex2772sc@gmail.com"
] | alex2772sc@gmail.com |
79b692236f02691a1ff7658b4fe7d4519c569262 | 6dcb5aca877030e9d3367ab45abb9611192ca13e | /src/libs/insteon/SwitchDevice.cpp | 9e069bea6aefdb85f3af83471a1de709bdc6860a | [
"MIT"
] | permissive | moneytech/dhas | d510dedfd26499093f8a26bf43f260c5c95f2e87 | 424212d4766c02f5df9e363ddb8ad2c295ed49d8 | refs/heads/master | 2021-09-03T18:24:07.451825 | 2018-01-10T23:23:59 | 2018-01-10T23:23:59 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,210 | cpp | #include "utils/Logging.h"
#include "SwitchDevice.h"
#include <iomanip>
SwitchDevice::SwitchDevice(std::string name, InsteonID id, InsteonModem *p): InsteonDevice(name,id,p)
{
mDeviceParameter = 0;
// Query that device's initial status
this->writeCommand(id,0x19,0);
}
SwitchDevice::~SwitchDevice(){
}
unsigned char SwitchDevice::getLevel()
{
return mDeviceParameter;
}
/*void SwitchDevice::setLevel(unsigned char v)
{
mDeviceParameter = v;
}*/
void SwitchDevice::toggle(unsigned char subdev)
{
if (mDeviceParameter == 0)
{
this->writeCommand(mID,0x11,255);
}
else
{
this->writeCommand(mID,0x14,0);
}
}
void SwitchDevice::turnOnOrOff(bool on, unsigned char level, unsigned char subdev)
{
if (on)
{
unsigned char cmd = 0x11;
if (level ==255)
{
cmd = 0x12;
} else {
cmd = 0x11;
}
this->writeCommand(mID,cmd,level);
}
else
{
this->writeCommand(mID,0x14,0);
}
}
InsteonDeviceType SwitchDevice::getDeviceType()
{
return OnOff;
}
void SwitchDevice::processEvent(Dumais::JSON::JSON& json, unsigned char* buf)
{
// Get the status
unsigned char flags = buf[8];
unsigned char status = (flags & 0b11100000)>>5;
unsigned char cmd1 = buf[9];
unsigned char cmd2 = buf[10];
bool ackOfDirectMessage = (status==0b001);
if (ackOfDirectMessage)
{
unsigned char command = cmd1;
if (getLastDirectMessageSent().cmd1==0x19) command = 0x19;
// The "status request" command does not echo the command in the message. We must deduce it.
// So we check what was the last message sent to associate this ACK to it.
if (command==0x19)
{
// Note: It is possible that we get level=0. In this case, the light is off.
this->setDeviceParameter(cmd2);
if (this->isInitialized())
{
json.addValue("insteon","event");
json.addValue(mID,"id");
json.addValue(this->getName(),"name");
json.addValue("unsolicited","trigger");
json.addValue(this->getDeviceType(),"type");
json.addValue((unsigned int)cmd2,"value");
}
else
{
this->setInitialized();
// The first time we get this, we don't wanna notify anyone.
LOG("Initial level for device "<<std::hex<<mID<<" is " << (int)cmd2);
}
}
else if (command==0x11 || command==0x12)
{
unsigned char level = 255;
json.addValue("insteon","event");
json.addValue(mID,"id");
json.addValue(this->getName(),"name");
json.addValue("ack","trigger");
json.addValue("switch","type");
json.addValue(level,"value");
this->setDeviceParameter(level);
}
else if (command==0x13 || command==0x14)
{
unsigned char level = 0;
json.addValue("insteon","event");
json.addValue(mID,"id");
json.addValue(this->getName(),"name");
json.addValue("ack","trigger");
json.addValue("switch","type");
json.addValue(level,"value");
this->setDeviceParameter(level);
}
}
else if (status==0b010) // Group cleanup direct message
{
json.addValue("insteon","event");
json.addValue(mID,"id");
json.addValue(this->getName(),"name");
json.addValue("unsolicited","trigger");
unsigned char level = 0;
if (cmd1==0x11 || cmd1==0x12){
level = 255;
json.addValue("switch","type");
json.addValue(level,"value");
this->setDeviceParameter(level);
} else if (cmd1==0x13 || cmd1==0x14) {
level = 0;
json.addValue("switch","type");
json.addValue(level,"value");
this->setDeviceParameter(level);
} else {
}
} else if (status ==0b110){
if (cmd1==0x18)
{
/**
* When someone dims a light manually, we get a frist event (cmd1=0x17) saying that a manual change
* has started. cmd2 will be 1 if the user is brightening the light or 0 if dimming down.
* When the desired brightness has been hit, we get a "manual change stopped" (cmd1=0x18).
* We won't get any data informing us of the brightness selected. So we need to do a status query.
*/
LOG("Manual change stopped for device "<<std::hex<<mID);
// This is a "stop manual change" command. A dimmer has changed so we must query its new state
this->writeCommand(mID,0x19,0);
}
}
}
void SwitchDevice::toJSON(Dumais::JSON::JSON& obj)
{
std::stringstream ss;
ss << "0x" << std::hex << std::setfill('0') << std::setw(6) << mID;
obj.addValue(ss.str(),"id");
obj.addValue(this->getName(),"name");
obj.addValue(this->getDeviceType(),"type");
obj.addValue((unsigned int)this->getLevel(),"level");
}
| [
"git@dumaisnet.ca"
] | git@dumaisnet.ca |
d3a928d1f8be14a1061456fc31070e4df272f384 | 8071b5498e98919bd68236fb23a75ee2afcc67f9 | /monthly_cases/monthly_cases.cpp | 330deb183d376b205b691bba93427142f244e704 | [] | no_license | biotyree/white_belt_cpp | 500cae77444fc3b1947488545a4ba5c7e1254f2a | fe0507c4a60b44a23643c0bc330e011ab1d616b3 | refs/heads/master | 2023-07-12T23:04:58.444616 | 2021-08-22T15:17:44 | 2021-08-22T15:17:44 | 388,800,271 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,242 | cpp |
#include <iostream>
#include <vector>
#include <string>
using namespace std;
void ADD(vector<vector<string>>& months, int currMonth)
{
int date;
string actEvent;
cin >> date >> actEvent;
if (months[currMonth][date - 1] != "")
months[currMonth][date - 1] += " ";
months[currMonth][date - 1] += actEvent;
}
void NEXT(vector<vector<string>>& months, int& currMonth, const vector<int> days_count)
{
int prevMonth = currMonth++;
if (currMonth == 13)
currMonth = 0;
months[currMonth].assign(days_count[currMonth], "");
if (days_count[currMonth] >= days_count[prevMonth])
for (int i = 0; i < days_count[prevMonth]; i++)
months[currMonth][i] = months[prevMonth][i];
else
{
for (int i = 0; i < days_count[currMonth]; i++)
months[currMonth][i] = months[prevMonth][i];
for (int i = days_count[currMonth]; i < days_count[prevMonth]; i++)
{
if (months[currMonth][days_count[currMonth] - 1] != "")
months[currMonth][days_count[currMonth] - 1] += " ";
months[currMonth][days_count[currMonth] - 1] += months[prevMonth][i];
}
}
}
void DUMP(const vector<vector<string>>& months, int currMonth)
{
int date;
int number = 0;
cin >> date;
date--;
if (months[currMonth][date] != "")
{
for (int i = 0; i < months[currMonth][date].length(); i++)
if (months[currMonth][date][i] == ' ')
number++;
cout << number + 1 << months[currMonth][date] << endl;
}
else
cout << "0" << endl;
}
int main()
{
int Q;
cin >> Q;
int currMonth = 0;
vector<vector<string>> months(12);
const vector<int> days_count = { 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31 };
months[currMonth].assign(days_count[currMonth], "");
string comm;
for (int j = 0; j < Q; j++)
{
comm = "";
cin >> comm;
if (comm == "ADD")
ADD(months, currMonth);
else if (comm == "NEXT")
{
NEXT(months, currMonth, days_count);
}
else if (comm == "DUMP")
{
DUMP(months, currMonth);
}
}
return 0;
}
| [
"afanasyev00@yandex.ru"
] | afanasyev00@yandex.ru |
27b5f145cee3dd70d24a6aed9ec1403024051f38 | 1fb15d09d1bde31521a18de500c2707d209ad197 | /src/emitters/tests/szlquantile_regtest.cc | d8f0c676aad7109b68590d1593b8b3862890e853 | [
"BSD-3-Clause"
] | permissive | chen3feng/szl | 5482cb996d8595ac1731c9a16c0c1c921a1cf9e1 | 9081619365f7fdc72bf28ddc063426bdc37f35ef | refs/heads/master | 2023-05-01T15:29:34.052198 | 2020-06-08T17:56:51 | 2020-06-08T17:56:51 | 270,629,939 | 0 | 0 | NOASSERTION | 2020-06-08T10:44:05 | 2020-06-08T10:44:04 | null | UTF-8 | C++ | false | false | 4,743 | cc | // Copyright 2010 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
// ------------------------------------------------------------------------
// Unittest for quantile table implementation (sawquantile.cc) in szl.
#include <stdio.h>
#include <math.h>
#include <set>
#include <vector>
#include "public/porting.h"
#include "public/logging.h"
#include "utilities/strutils.h"
#include "utilities/random_base.h"
#include "utilities/acmrandom.h"
#include "public/szlencoder.h"
#include "public/szldecoder.h"
#include "public/szlvalue.h"
#include "public/szlresults.h"
#include "public/szltabentry.h"
static void TestQuantiles(const int N, const int num_quantiles) {
CHECK_GE(N, 1);
CHECK_GE(num_quantiles, 2);
//VLOG(1) << StringPrintf("TestQuantiles(%d, %d) in progress ...",
// N, num_quantiles);
VLOG(1) << "TestQuantiles(" << N << ", " << num_quantiles << ") in progress.";
SzlType t(SzlType::TABLE);
t.set_table("quantile");
SzlField tfld("", SzlType::kString);
t.set_element(&tfld);
t.set_param(num_quantiles);
string error;
CHECK(t.Valid(&error)) << ": " << error;
SzlTabWriter* swr = SzlTabWriter::CreateSzlTabWriter(t, &error);
CHECK(swr != NULL) << ": " << error;
// Create szl tab entries by the table swr.
SzlTabEntry* quant = swr->CreateEntry("");
CHECK(quant != NULL);
// Insert N elements into the table.
for (int64 i = N; i >= 1; i -= 2) {
SzlEncoder enc;
enc.PutString(StringPrintf("xx-%09lld", i).c_str());
quant->AddElem(enc.data());
}
for (int64 i = N-1; i >= 1; i -= 2) {
SzlEncoder enc;
enc.PutString(StringPrintf("xx-%09lld", i).c_str());
quant->AddElem(enc.data());
}
string result;
quant->Flush(&result);
CHECK_EQ(quant->TotElems(), 0);
SzlResults* sres = SzlResults::CreateSzlResults(t, &error);
CHECK(sres != NULL) << ": " << error;
CHECK(sres->ParseFromString(result));
CHECK_EQ(sres->Results()->size(), num_quantiles);
vector<string> const *rvec = sres->Results();
SzlDecoder dec(rvec->front().data(), rvec->front().size());
{ // Check the max and min elements.
int index;
string vstr;
dec.GetString(&vstr);
CHECK_EQ(sscanf(vstr.c_str(), "xx-%d", &index), 1);
CHECK(index == 1) << " : lowest value not equal to min inserted";
dec.Init(rvec->back().data(), rvec->back().size());
dec.GetString(&vstr);
CHECK_EQ(sscanf(vstr.c_str(), "xx-%d", &index), 1);
CHECK(index == N) << " : highest value not equal to max inserted";
}
const double epsilon = 1.0 / (num_quantiles - 1.0);
for (int i = 1; i < sres->Results()->size() - 1; ++i) {
dec.Init(rvec->at(i).data(), rvec->at(i).size());
string vstr;
dec.GetString(&vstr);
int index;
CHECK_EQ(sscanf(vstr.c_str(), "xx-%d", &index), 1);
CHECK_LE(index, static_cast<int>(
ceil(i*N/(num_quantiles - 1.0)) + epsilon*N));
CHECK_GE(index, static_cast<int>(
ceil(i*N/(num_quantiles - 1.0)) - epsilon*N));
}
delete quant;
delete swr;
delete sres;
}
static void TestForNValues(const int N, const int num_quantiles) {
// This regtest takes over 30 minutes as of 2006/03. With SzlACMRandom::OneIn(5),
// the #test cases will reduce to one-fifth. SzlACMRandom::GoodSeed() ensures
// that we choose a different seed everytime the regtest runs.
SzlACMRandom rnd;
rnd.Reset(SzlACMRandom::GoodSeed());
if (rnd.OneIn(5)) {
TestQuantiles(N, num_quantiles);
}
if (rnd.OneIn(5)) {
TestQuantiles(N, num_quantiles);
}
}
static void Test(const int num_quantiles) {
TestForNValues(1, num_quantiles);
TestForNValues(2, num_quantiles);
TestForNValues(5, num_quantiles);
TestForNValues(10, num_quantiles);
TestForNValues(15, num_quantiles);
TestForNValues(19, num_quantiles);
TestForNValues(269, num_quantiles);
TestForNValues(4423, num_quantiles);
TestForNValues(80897, num_quantiles);
TestForNValues(120897, num_quantiles);
TestForNValues(1000000, num_quantiles);
}
int main(int argc, char** argv) {
ProcessCommandLineArguments(argc, argv);
InitializeAllModules();
Test(2);
Test(3);
Test(9);
Test(65);
Test(100);
Test(233);
Test(1345);
puts("PASS");
return 0;
}
| [
"bgibbons@google.com@413cfee2-6280-6547-3bd8-6f5aabe6079b"
] | bgibbons@google.com@413cfee2-6280-6547-3bd8-6f5aabe6079b |
1c30d206c0ac4b33cca8d5e985fc5d36af6cffda | b3a158034526daacee4427fa2eae0b797f904924 | /MainApp/TaskMar/MainFrm.h | ffba1246cc148d36dd19da518ecfcf1c0a326beb | [] | no_license | 15831944/Corpse | e1785c12d620f7defd16ab0b0abb0705907815c9 | 51ca96ada1db58272fff3bdbdff165200be96191 | refs/heads/master | 2023-06-29T08:36:07.487065 | 2021-05-22T01:31:41 | 2021-05-22T01:31:41 | null | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 913 | h |
// MainFrm.h : CMainFrame 类的接口
//
#pragma once
typedef CList<CBitmap*,CBitmap*> CBitmapList;
class CMainFrame : public CFrameWnd
{
protected: // 仅从序列化创建
CMainFrame();
DECLARE_DYNCREATE(CMainFrame)
// 属性
public:
// 操作
public:
// 重写
public:
virtual BOOL PreCreateWindow(CREATESTRUCT& cs);
virtual BOOL OnCreateClient(LPCREATESTRUCT lpcs, CCreateContext* pContext);
// 实现
public:
virtual ~CMainFrame();
#ifdef _DEBUG
virtual void AssertValid() const;
virtual void Dump(CDumpContext& dc) const;
#endif
protected: // 控件条嵌入成员
CStatusBar m_wndStatusBar;
CSplitterWnd m_wndSplitter;
// 生成的消息映射函数
protected:
afx_msg int OnCreate(LPCREATESTRUCT lpCreateStruct);
DECLARE_MESSAGE_MAP()
public:
afx_msg void OnRunSystemDlg();
afx_msg void OnSize(UINT nType, int cx, int cy);
};
| [
"Uniquers@853a975a-7e59-4707-9df1-4264b926ceb7"
] | Uniquers@853a975a-7e59-4707-9df1-4264b926ceb7 |
834fafc6eeb284ac0984c3bb650cad030d63d059 | 54a28d4ccfed643b6aef2474dd4cf108219cc15a | /node_modules/pg/src/binding.cc | 7a2364beb8f370e23bb8e69ce152fa302c3fcc86 | [
"MIT"
] | permissive | emsal0/prose | c8a659b4f0837c767d93f60a1b67b493f8464c23 | 665e6c51fd06f0e2e99ac5cdf28a3b5e7fcfd9c0 | refs/heads/master | 2021-06-04T12:13:57.748689 | 2015-03-09T04:06:09 | 2015-03-09T04:06:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 25,808 | cc | #include <libpq-fe.h>
#include <node.h>
#include <node_buffer.h>
#include <string.h>
#include <assert.h>
#include <stdlib.h>
#define LOG(msg) printf("%s\n",msg);
#define TRACE(msg) //printf("%s\n", msg);
#define THROW(msg) return ThrowException(Exception::Error(String::New(msg)));
using namespace v8;
using namespace node;
static Persistent<String> severity_symbol;
static Persistent<String> code_symbol;
static Persistent<String> detail_symbol;
static Persistent<String> hint_symbol;
static Persistent<String> position_symbol;
static Persistent<String> internalPosition_symbol;
static Persistent<String> internalQuery_symbol;
static Persistent<String> where_symbol;
static Persistent<String> file_symbol;
static Persistent<String> line_symbol;
static Persistent<String> routine_symbol;
static Persistent<String> name_symbol;
static Persistent<String> value_symbol;
static Persistent<String> type_symbol;
static Persistent<String> channel_symbol;
static Persistent<String> payload_symbol;
static Persistent<String> emit_symbol;
static Persistent<String> command_symbol;
class Connection : public ObjectWrap {
public:
//creates the V8 objects & attaches them to the module (target)
static void
Init (Handle<Object> target)
{
HandleScope scope;
Local<FunctionTemplate> t = FunctionTemplate::New(New);
t->InstanceTemplate()->SetInternalFieldCount(1);
t->SetClassName(String::NewSymbol("Connection"));
emit_symbol = NODE_PSYMBOL("emit");
severity_symbol = NODE_PSYMBOL("severity");
code_symbol = NODE_PSYMBOL("code");
detail_symbol = NODE_PSYMBOL("detail");
hint_symbol = NODE_PSYMBOL("hint");
position_symbol = NODE_PSYMBOL("position");
internalPosition_symbol = NODE_PSYMBOL("internalPosition");
internalQuery_symbol = NODE_PSYMBOL("internalQuery");
where_symbol = NODE_PSYMBOL("where");
file_symbol = NODE_PSYMBOL("file");
line_symbol = NODE_PSYMBOL("line");
routine_symbol = NODE_PSYMBOL("routine");
name_symbol = NODE_PSYMBOL("name");
value_symbol = NODE_PSYMBOL("value");
type_symbol = NODE_PSYMBOL("dataTypeID");
channel_symbol = NODE_PSYMBOL("channel");
payload_symbol = NODE_PSYMBOL("payload");
command_symbol = NODE_PSYMBOL("command");
NODE_SET_PROTOTYPE_METHOD(t, "connect", Connect);
NODE_SET_PROTOTYPE_METHOD(t, "escapeIdentifier", EscapeIdentifier);
NODE_SET_PROTOTYPE_METHOD(t, "escapeLiteral", EscapeLiteral);
NODE_SET_PROTOTYPE_METHOD(t, "_sendQuery", SendQuery);
NODE_SET_PROTOTYPE_METHOD(t, "_sendQueryWithParams", SendQueryWithParams);
NODE_SET_PROTOTYPE_METHOD(t, "_sendPrepare", SendPrepare);
NODE_SET_PROTOTYPE_METHOD(t, "_sendQueryPrepared", SendQueryPrepared);
NODE_SET_PROTOTYPE_METHOD(t, "cancel", Cancel);
NODE_SET_PROTOTYPE_METHOD(t, "end", End);
NODE_SET_PROTOTYPE_METHOD(t, "_sendCopyFromChunk", SendCopyFromChunk);
NODE_SET_PROTOTYPE_METHOD(t, "_endCopyFrom", EndCopyFrom);
target->Set(String::NewSymbol("Connection"), t->GetFunction());
TRACE("created class");
}
//static function called by libuv as callback entrypoint
static void
io_event(uv_poll_t* w, int status, int revents)
{
TRACE("Received IO event");
if(status == -1) {
TRACE("Connection error. -1 status from lib_uv_poll");
}
Connection *connection = static_cast<Connection*>(w->data);
connection->HandleIOEvent(revents);
}
//v8 entry point into Connection#connect
static Handle<Value>
Connect(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
if(args.Length() == 0 || !args[0]->IsString()) {
THROW("Must include connection string as only argument to connect");
}
String::Utf8Value conninfo(args[0]->ToString());
bool success = self->Connect(*conninfo);
if(!success) {
self -> EmitLastError();
self -> DestroyConnection();
}
return Undefined();
}
//v8 entry point into Connection#cancel
static Handle<Value>
Cancel(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
bool success = self->Cancel();
if(!success) {
self -> EmitLastError();
self -> DestroyConnection();
}
return Undefined();
}
//v8 entry point into Connection#escapeIdentifier
static Handle<Value>
EscapeIdentifier(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
char* inputStr = MallocCString(args[0]);
if(!inputStr) {
THROW("Unable to allocate memory for a string in EscapeIdentifier.")
}
char* escapedStr = self->EscapeIdentifier(inputStr);
free(inputStr);
if(escapedStr == NULL) {
THROW(self->GetLastError());
}
Local<Value> jsStr = String::New(escapedStr, strlen(escapedStr));
PQfreemem(escapedStr);
return scope.Close(jsStr);
}
//v8 entry point into Connection#escapeLiteral
static Handle<Value>
EscapeLiteral(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
char* inputStr = MallocCString(args[0]);
if(!inputStr) {
THROW("Unable to allocate memory for a string in EscapeIdentifier.")
}
char* escapedStr = self->EscapeLiteral(inputStr);
free(inputStr);
if(escapedStr == NULL) {
THROW(self->GetLastError());
}
Local<Value> jsStr = String::New(escapedStr, strlen(escapedStr));
PQfreemem(escapedStr);
return scope.Close(jsStr);
}
//v8 entry point into Connection#_sendQuery
static Handle<Value>
SendQuery(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
const char *lastErrorMessage;
if(!args[0]->IsString()) {
THROW("First parameter must be a string query");
}
char* queryText = MallocCString(args[0]);
int result = self->Send(queryText);
free(queryText);
if(result == 0) {
lastErrorMessage = self->GetLastError();
THROW(lastErrorMessage);
}
//TODO should we flush before throw?
self->Flush();
return Undefined();
}
//v8 entry point into Connection#_sendQueryWithParams
static Handle<Value>
SendQueryWithParams(const Arguments& args)
{
HandleScope scope;
//dispatch non-prepared parameterized query
return DispatchParameterizedQuery(args, false);
}
//v8 entry point into Connection#_sendPrepare(string queryName, string queryText, int nParams)
static Handle<Value>
SendPrepare(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
String::Utf8Value queryName(args[0]);
String::Utf8Value queryText(args[1]);
int length = args[2]->Int32Value();
self->SendPrepare(*queryName, *queryText, length);
return Undefined();
}
//v8 entry point into Connection#_sendQueryPrepared(string queryName, string[] paramValues)
static Handle<Value>
SendQueryPrepared(const Arguments& args)
{
HandleScope scope;
//dispatch prepared parameterized query
return DispatchParameterizedQuery(args, true);
}
static Handle<Value>
DispatchParameterizedQuery(const Arguments& args, bool isPrepared)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
String::Utf8Value queryName(args[0]);
//TODO this is much copy/pasta code
if(!args[0]->IsString()) {
THROW("First parameter must be a string");
}
if(!args[1]->IsArray()) {
THROW("Values must be an array");
}
Local<Array> jsParams = Local<Array>::Cast(args[1]);
int len = jsParams->Length();
char** paramValues = ArgToCStringArray(jsParams);
if(!paramValues) {
THROW("Unable to allocate char **paramValues from Local<Array> of v8 params");
}
char* queryText = MallocCString(args[0]);
int result = 0;
if(isPrepared) {
result = self->SendPreparedQuery(queryText, len, paramValues);
} else {
result = self->SendQueryParams(queryText, len, paramValues);
}
free(queryText);
ReleaseCStringArray(paramValues, len);
if(result == 1) {
return Undefined();
}
self->EmitLastError();
THROW("Postgres returned non-1 result from query dispatch.");
}
//v8 entry point into Connection#end
static Handle<Value>
End(const Arguments& args)
{
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
self->End();
return Undefined();
}
uv_poll_t read_watcher_;
uv_poll_t write_watcher_;
PGconn *connection_;
bool connecting_;
bool ioInitialized_;
bool copyOutMode_;
bool copyInMode_;
bool reading_;
bool writing_;
bool ended_;
Connection () : ObjectWrap ()
{
connection_ = NULL;
connecting_ = false;
ioInitialized_ = false;
copyOutMode_ = false;
copyInMode_ = false;
reading_ = false;
writing_ = false;
ended_ = false;
TRACE("Initializing ev watchers");
read_watcher_.data = this;
write_watcher_.data = this;
}
~Connection ()
{
}
static Handle<Value>
SendCopyFromChunk(const Arguments& args) {
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
//TODO handle errors in some way
if (args.Length() < 1 && !Buffer::HasInstance(args[0])) {
THROW("SendCopyFromChunk requires 1 Buffer argument");
}
self->SendCopyFromChunk(args[0]->ToObject());
return Undefined();
}
static Handle<Value>
EndCopyFrom(const Arguments& args) {
HandleScope scope;
Connection *self = ObjectWrap::Unwrap<Connection>(args.This());
char * error_msg = NULL;
if (args[0]->IsString()) {
error_msg = MallocCString(args[0]);
}
//TODO handle errors in some way
self->EndCopyFrom(error_msg);
free(error_msg);
return Undefined();
}
protected:
//v8 entry point to constructor
static Handle<Value>
New (const Arguments& args)
{
HandleScope scope;
Connection *connection = new Connection();
connection->Wrap(args.This());
return args.This();
}
char * EscapeIdentifier(const char *str)
{
TRACE("js::EscapeIdentifier")
return PQescapeIdentifier(connection_, str, strlen(str));
}
char * EscapeLiteral(const char *str)
{
TRACE("js::EscapeLiteral")
return PQescapeLiteral(connection_, str, strlen(str));
}
int Send(const char *queryText)
{
TRACE("js::Send")
int rv = PQsendQuery(connection_, queryText);
StartWrite();
return rv;
}
int SendQueryParams(const char *command, const int nParams, const char * const *paramValues)
{
TRACE("js::SendQueryParams")
int rv = PQsendQueryParams(connection_, command, nParams, NULL, paramValues, NULL, NULL, 0);
StartWrite();
return rv;
}
int SendPrepare(const char *name, const char *command, const int nParams)
{
TRACE("js::SendPrepare")
int rv = PQsendPrepare(connection_, name, command, nParams, NULL);
StartWrite();
return rv;
}
int SendPreparedQuery(const char *name, int nParams, const char * const *paramValues)
{
int rv = PQsendQueryPrepared(connection_, name, nParams, paramValues, NULL, NULL, 0);
StartWrite();
return rv;
}
bool Cancel()
{
PGcancel* pgCancel = PQgetCancel(connection_);
char errbuf[256];
int result = PQcancel(pgCancel, errbuf, 256);
StartWrite();
PQfreeCancel(pgCancel);
return result;
}
//flushes socket
void Flush()
{
if(PQflush(connection_) == 1) {
TRACE("Flushing");
uv_poll_start(&write_watcher_, UV_WRITABLE, io_event);
}
}
//safely destroys the connection at most 1 time
void DestroyConnection()
{
if(connection_ != NULL) {
PQfinish(connection_);
connection_ = NULL;
}
}
//initializes initial async connection to postgres via libpq
//and hands off control to libev
bool Connect(const char* conninfo)
{
if(ended_) return true;
connection_ = PQconnectStart(conninfo);
if (!connection_) {
LOG("Connection couldn't be created");
}
ConnStatusType status = PQstatus(connection_);
if(CONNECTION_BAD == status) {
return false;
}
if (PQsetnonblocking(connection_, 1) == -1) {
LOG("Unable to set connection to non-blocking");
return false;
}
int fd = PQsocket(connection_);
if(fd < 0) {
LOG("socket fd was negative. error");
return false;
}
assert(PQisnonblocking(connection_));
PQsetNoticeProcessor(connection_, NoticeReceiver, this);
TRACE("Setting watchers to socket");
uv_poll_init(uv_default_loop(), &read_watcher_, fd);
uv_poll_init(uv_default_loop(), &write_watcher_, fd);
ioInitialized_ = true;
connecting_ = true;
StartWrite();
Ref();
return true;
}
static void NoticeReceiver(void *arg, const char *message)
{
Connection *self = (Connection*)arg;
self->HandleNotice(message);
}
void HandleNotice(const char *message)
{
HandleScope scope;
Handle<Value> notice = String::New(message);
Emit("notice", ¬ice);
}
//called to process io_events from libuv
void HandleIOEvent(int revents)
{
if(connecting_) {
TRACE("Processing connecting_ io");
HandleConnectionIO();
return;
}
if(revents & UV_READABLE) {
TRACE("revents & UV_READABLE");
TRACE("about to consume input");
if(PQconsumeInput(connection_) == 0) {
TRACE("could not read, terminating");
End();
EmitLastError();
//LOG("Something happened, consume input is 0");
return;
}
TRACE("Consumed");
//declare handlescope as this method is entered via a libuv callback
//and not part of the public v8 interface
HandleScope scope;
if (this->copyOutMode_) {
this->HandleCopyOut();
}
if (!this->copyInMode_ && !this->copyOutMode_ && PQisBusy(connection_) == 0) {
PGresult *result;
bool didHandleResult = false;
TRACE("PQgetResult");
while ((result = PQgetResult(connection_))) {
TRACE("HandleResult");
didHandleResult = HandleResult(result);
TRACE("PQClear");
PQclear(result);
if(!didHandleResult) {
//this means that we are in copy in or copy out mode
//in this situation PQgetResult will return same
//result untill all data will be read (copy out) or
//until data end notification (copy in)
//and because of this, we need to break cycle
break;
}
}
//might have fired from notification
if(didHandleResult) {
Emit("_readyForQuery");
}
}
PGnotify *notify;
TRACE("PQnotifies");
while ((notify = PQnotifies(connection_))) {
Local<Object> result = Object::New();
result->Set(channel_symbol, String::New(notify->relname));
result->Set(payload_symbol, String::New(notify->extra));
Handle<Value> res = (Handle<Value>)result;
Emit("notification", &res);
PQfreemem(notify);
}
}
if(revents & UV_WRITABLE) {
TRACE("revents & UV_WRITABLE");
if (PQflush(connection_) == 0) {
//nothing left to write, poll the socket for more to read
StartRead();
}
}
}
bool HandleCopyOut () {
char * buffer = NULL;
int copied;
Buffer * chunk;
copied = PQgetCopyData(connection_, &buffer, 1);
while (copied > 0) {
chunk = Buffer::New(buffer, copied);
Local<Value> node_chunk = Local<Value>::New(chunk->handle_);
Emit("copyData", &node_chunk);
PQfreemem(buffer);
copied = PQgetCopyData(connection_, &buffer, 1);
}
if (copied == 0) {
//wait for next read ready
//result was not handled completely
return false;
} else if (copied == -1) {
this->copyOutMode_ = false;
return true;
} else if (copied == -2) {
this->copyOutMode_ = false;
return true;
}
return false;
}
//maps the postgres tuple results to v8 objects
//and emits row events
//TODO look at emitting fewer events because the back & forth between
//javascript & c++ might introduce overhead (requires benchmarking)
void EmitRowDescription(const PGresult* result)
{
HandleScope scope;
Local<Array> row = Array::New();
int fieldCount = PQnfields(result);
for(int fieldNumber = 0; fieldNumber < fieldCount; fieldNumber++) {
Local<Object> field = Object::New();
//name of field
char* fieldName = PQfname(result, fieldNumber);
field->Set(name_symbol, String::New(fieldName));
//oid of type of field
int fieldType = PQftype(result, fieldNumber);
field->Set(type_symbol, Integer::New(fieldType));
row->Set(Integer::New(fieldNumber), field);
}
Handle<Value> e = (Handle<Value>)row;
Emit("_rowDescription", &e);
}
bool HandleResult(PGresult* result)
{
TRACE("PQresultStatus");
ExecStatusType status = PQresultStatus(result);
switch(status) {
case PGRES_TUPLES_OK:
{
EmitRowDescription(result);
HandleTuplesResult(result);
EmitCommandMetaData(result);
return true;
}
break;
case PGRES_FATAL_ERROR:
{
TRACE("HandleErrorResult");
HandleErrorResult(result);
return true;
}
break;
case PGRES_COMMAND_OK:
case PGRES_EMPTY_QUERY:
{
EmitCommandMetaData(result);
return true;
}
break;
case PGRES_COPY_IN:
{
this->copyInMode_ = true;
Emit("copyInResponse");
return false;
}
break;
case PGRES_COPY_OUT:
{
this->copyOutMode_ = true;
Emit("copyOutResponse");
return this->HandleCopyOut();
}
break;
default:
printf("YOU SHOULD NEVER SEE THIS! PLEASE OPEN AN ISSUE ON GITHUB! Unrecogized query status: %s\n", PQresStatus(status));
break;
}
return true;
}
void EmitCommandMetaData(PGresult* result)
{
HandleScope scope;
Local<Object> info = Object::New();
info->Set(command_symbol, String::New(PQcmdStatus(result)));
info->Set(value_symbol, String::New(PQcmdTuples(result)));
Handle<Value> e = (Handle<Value>)info;
Emit("_cmdStatus", &e);
}
//maps the postgres tuple results to v8 objects
//and emits row events
//TODO look at emitting fewer events because the back & forth between
//javascript & c++ might introduce overhead (requires benchmarking)
void HandleTuplesResult(const PGresult* result)
{
HandleScope scope;
int rowCount = PQntuples(result);
for(int rowNumber = 0; rowNumber < rowCount; rowNumber++) {
//create result object for this row
Local<Array> row = Array::New();
int fieldCount = PQnfields(result);
for(int fieldNumber = 0; fieldNumber < fieldCount; fieldNumber++) {
//value of field
if(PQgetisnull(result, rowNumber, fieldNumber)) {
row->Set(Integer::New(fieldNumber), Null());
} else {
char* fieldValue = PQgetvalue(result, rowNumber, fieldNumber);
row->Set(Integer::New(fieldNumber), String::New(fieldValue));
}
}
Handle<Value> e = (Handle<Value>)row;
Emit("_row", &e);
}
}
void HandleErrorResult(const PGresult* result)
{
HandleScope scope;
//instantiate the return object as an Error with the summary Postgres message
TRACE("ReadResultField");
const char* errorMessage = PQresultErrorField(result, PG_DIAG_MESSAGE_PRIMARY);
if(!errorMessage) {
//there is no error, it has already been consumed in the last
//read-loop callback
return;
}
Local<Object> msg = Local<Object>::Cast(Exception::Error(String::New(errorMessage)));
TRACE("AttachErrorFields");
//add the other information returned by Postgres to the error object
AttachErrorField(result, msg, severity_symbol, PG_DIAG_SEVERITY);
AttachErrorField(result, msg, code_symbol, PG_DIAG_SQLSTATE);
AttachErrorField(result, msg, detail_symbol, PG_DIAG_MESSAGE_DETAIL);
AttachErrorField(result, msg, hint_symbol, PG_DIAG_MESSAGE_HINT);
AttachErrorField(result, msg, position_symbol, PG_DIAG_STATEMENT_POSITION);
AttachErrorField(result, msg, internalPosition_symbol, PG_DIAG_INTERNAL_POSITION);
AttachErrorField(result, msg, internalQuery_symbol, PG_DIAG_INTERNAL_QUERY);
AttachErrorField(result, msg, where_symbol, PG_DIAG_CONTEXT);
AttachErrorField(result, msg, file_symbol, PG_DIAG_SOURCE_FILE);
AttachErrorField(result, msg, line_symbol, PG_DIAG_SOURCE_LINE);
AttachErrorField(result, msg, routine_symbol, PG_DIAG_SOURCE_FUNCTION);
Handle<Value> m = msg;
TRACE("EmitError");
Emit("_error", &m);
}
void AttachErrorField(const PGresult *result, const Local<Object> msg, const Persistent<String> symbol, int fieldcode)
{
char *val = PQresultErrorField(result, fieldcode);
if(val) {
msg->Set(symbol, String::New(val));
}
}
void End()
{
TRACE("stopping read & write");
StopRead();
StopWrite();
DestroyConnection();
Emit("_end");
ended_ = true;
}
private:
//EventEmitter was removed from c++ in node v0.5.x
void Emit(const char* message) {
HandleScope scope;
Handle<Value> args[1] = { String::New(message) };
Emit(1, args);
}
void Emit(const char* message, Handle<Value>* arg) {
HandleScope scope;
Handle<Value> args[2] = { String::New(message), *arg };
Emit(2, args);
}
void Emit(int length, Handle<Value> *args) {
HandleScope scope;
Local<Value> emit_v = this->handle_->Get(emit_symbol);
assert(emit_v->IsFunction());
Local<Function> emit_f = emit_v.As<Function>();
TryCatch tc;
emit_f->Call(this->handle_, length, args);
if(tc.HasCaught()) {
FatalException(tc);
}
}
void HandleConnectionIO()
{
PostgresPollingStatusType status = PQconnectPoll(connection_);
switch(status) {
case PGRES_POLLING_READING:
TRACE("Polled: PGRES_POLLING_READING");
StartRead();
break;
case PGRES_POLLING_WRITING:
TRACE("Polled: PGRES_POLLING_WRITING");
StartWrite();
break;
case PGRES_POLLING_FAILED:
StopRead();
StopWrite();
TRACE("Polled: PGRES_POLLING_FAILED");
EmitLastError();
break;
case PGRES_POLLING_OK:
TRACE("Polled: PGRES_POLLING_OK");
connecting_ = false;
StartRead();
Emit("connect");
default:
//printf("Unknown polling status: %d\n", status);
break;
}
}
void EmitError(const char *message)
{
Local<Value> exception = Exception::Error(String::New(message));
Emit("_error", &exception);
}
void EmitLastError()
{
EmitError(PQerrorMessage(connection_));
}
const char *GetLastError()
{
return PQerrorMessage(connection_);
}
void StopWrite()
{
TRACE("write STOP");
if(ioInitialized_ && writing_) {
uv_poll_stop(&write_watcher_);
writing_ = false;
}
}
void StartWrite()
{
TRACE("write START");
if(reading_) {
TRACE("stop READ to start WRITE");
StopRead();
}
uv_poll_start(&write_watcher_, UV_WRITABLE, io_event);
writing_ = true;
}
void StopRead()
{
TRACE("read STOP");
if(ioInitialized_ && reading_) {
uv_poll_stop(&read_watcher_);
reading_ = false;
}
}
void StartRead()
{
TRACE("read START");
if(writing_) {
TRACE("stop WRITE to start READ");
StopWrite();
}
uv_poll_start(&read_watcher_, UV_READABLE, io_event);
reading_ = true;
}
//Converts a v8 array to an array of cstrings
//the result char** array must be free() when it is no longer needed
//if for any reason the array cannot be created, returns 0
static char** ArgToCStringArray(Local<Array> params)
{
int len = params->Length();
char** paramValues = new char*[len];
for(int i = 0; i < len; i++) {
Handle<Value> val = params->Get(i);
if(val->IsString()) {
char* cString = MallocCString(val);
//will be 0 if could not malloc
if(!cString) {
LOG("ArgToCStringArray: OUT OF MEMORY OR SOMETHING BAD!");
ReleaseCStringArray(paramValues, i-1);
return 0;
}
paramValues[i] = cString;
} else if(val->IsNull()) {
paramValues[i] = NULL;
} else {
//a paramter was not a string
LOG("Parameter not a string");
ReleaseCStringArray(paramValues, i-1);
return 0;
}
}
return paramValues;
}
//helper function to release cString arrays
static void ReleaseCStringArray(char **strArray, int len)
{
for(int i = 0; i < len; i++) {
free(strArray[i]);
}
delete [] strArray;
}
//helper function to malloc new string from v8string
static char* MallocCString(v8::Handle<Value> v8String)
{
String::Utf8Value utf8String(v8String->ToString());
char *cString = (char *) malloc(strlen(*utf8String) + 1);
if(!cString) {
return cString;
}
strcpy(cString, *utf8String);
return cString;
}
void SendCopyFromChunk(Handle<Object> chunk) {
PQputCopyData(connection_, Buffer::Data(chunk), Buffer::Length(chunk));
}
void EndCopyFrom(char * error_msg) {
PQputCopyEnd(connection_, error_msg);
this->copyInMode_ = false;
}
};
extern "C" void init (Handle<Object> target)
{
HandleScope scope;
Connection::Init(target);
}
NODE_MODULE(binding, init)
| [
"ff@aight"
] | ff@aight |
8d5ee18af20413c0a35aa14f385c4501dea2afe2 | 8d123cef6c1efbd7c2151cbe696750015a4e2852 | /xD3dEngine/Math/AryI2.h | 611ad988e3967a1305ff3fb711cc94be9502cebc | [] | no_license | MSsaber/xD3dEngine | 990bbdaf6a293a3673b043d2acfaefc90b797523 | 36fc0157204f0a3d73ad1a9d8fe84fc7d61e6f16 | refs/heads/master | 2020-04-07T03:06:25.129510 | 2018-12-08T20:08:49 | 2018-12-08T20:08:49 | 158,002,690 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,935 | h | #ifndef VecNumECI2_H_
#define VecNumECI2_H_
#include "Array.h"
namespace XD3D
{
class AryI2 : public Array<int, 2>
{
public:
AryI2() { VecNum[0] = 0, VecNum[1] = 0; }
AryI2(int x, int y) { VecNum[0] = x, VecNum[1] = y; }
inline AryI2(const AryI2& other) {
VecNum[0] = other.VecNum[0], VecNum[1] = other.VecNum[1];
}
AryI2(AryI2&& other) {
VecNum[0] = other.VecNum[0], VecNum[1] = other.VecNum[1];
}
virtual ~AryI2() {}
public:
inline void Set(int x, int y) { VecNum[0] = x, VecNum[1] = y; }
inline void Set(const AryI2& v) {
VecNum[0] = v.VecNum[0], VecNum[1] = v.VecNum[1];
}
inline bool operator ==(const AryI2& other) const {
return VecNum[0] == other.VecNum[0] && VecNum[1] == other.VecNum[1];
}
inline bool operator !=(const AryI2& other) const {
return VecNum[0] != other.VecNum[0] || VecNum[1] != other.VecNum[1];
}
inline int operator [](int index) const { return VecNum[index]; }
inline int& operator [](int index) { return VecNum[index]; }
inline int& x() { return VecNum[0]; }
inline int& y() { return VecNum[1]; }
inline int x() const { return VecNum[0]; }
inline int y() const { return VecNum[1]; }
inline AryI2 operator * (int n) const { return AryI2(VecNum[0] * n, VecNum[1] * n); }
inline AryI2 operator / (int n) const { return AryI2(VecNum[0] / n, VecNum[1] / n); }
inline AryI2 operator + (int n) const { return AryI2(VecNum[0] + n, VecNum[1] + n); }
inline AryI2 operator - (int n) const { return AryI2(VecNum[0] - n, VecNum[1] - n); }
inline AryI2 operator + (const AryI2& v) const {
return AryI2(VecNum[0] + v.VecNum[0], VecNum[1] + v.VecNum[1]);
}
inline AryI2 operator - (const AryI2& v) const {
return AryI2(VecNum[0] - v.VecNum[0], VecNum[1] - v.VecNum[1]);
}
inline AryI2 operator * (const AryI2& v) const {
return AryI2(VecNum[0] * v.VecNum[0], VecNum[1] * v.VecNum[1]);
}
};
}
#endif //!VecNumECI2_H_
| [
"1752615737@qq.com"
] | 1752615737@qq.com |
a38d5a852b3df612031b6c1d07dc923dbf158282 | c8b39acfd4a857dc15ed3375e0d93e75fa3f1f64 | /Engine/Source/Editor/ClothingSystemEditor/Public/ClothingAssetFactory.h | 39d2df15e24ade06db53a0e93b7e01ec09a3ff64 | [
"MIT",
"LicenseRef-scancode-proprietary-license"
] | permissive | windystrife/UnrealEngine_NVIDIAGameWorks | c3c7863083653caf1bc67d3ef104fb4b9f302e2a | b50e6338a7c5b26374d66306ebc7807541ff815e | refs/heads/4.18-GameWorks | 2023-03-11T02:50:08.471040 | 2022-01-13T20:50:29 | 2022-01-13T20:50:29 | 124,100,479 | 262 | 179 | MIT | 2022-12-16T05:36:38 | 2018-03-06T15:44:09 | C++ | UTF-8 | C++ | false | false | 3,557 | h | // Copyright 1998-2016 Epic Games, Inc. All Rights Reserved.
#pragma once
#include "ClothingAsset.h"
#include "ClothingAssetFactoryInterface.h"
#include "GPUSkinPublicDefs.h"
#include "ClothingAssetFactory.generated.h"
DECLARE_LOG_CATEGORY_EXTERN(LogClothingAssetFactory, Log, All);
namespace nvidia
{
namespace apex
{
class ClothingAsset;
}
}
namespace NvParameterized
{
class Interface;
}
UCLASS(hidecategories=Object)
class CLOTHINGSYSTEMEDITOR_API UClothingAssetFactory : public UClothingAssetFactoryBase
{
GENERATED_BODY()
public:
UClothingAssetFactory(const FObjectInitializer& ObjectInitializer);
// Import the given file, treating it as an APEX asset file and return the resulting asset
virtual UClothingAssetBase* Import(const FString& Filename, USkeletalMesh* TargetMesh, FName InName = NAME_None) override;
virtual UClothingAssetBase* Reimport(const FString& Filename, USkeletalMesh* TargetMesh, UClothingAssetBase* OriginalAsset) override;
virtual UClothingAssetBase* CreateFromSkeletalMesh(USkeletalMesh* TargetMesh, FSkeletalMeshClothBuildParams& Params) override;
virtual UClothingAssetBase* ImportLodToClothing(USkeletalMesh* TargetMesh, FSkeletalMeshClothBuildParams& Params) override;
// Tests whether the given filename should be able to be imported
virtual bool CanImport(const FString& Filename) override;
// Given an APEX asset, build a UClothingAsset containing the required data
virtual UClothingAssetBase* CreateFromApexAsset(nvidia::apex::ClothingAsset* InApexAsset, USkeletalMesh* TargetMesh, FName InName = NAME_None) override;
private:
#if WITH_APEX_CLOTHING
struct FApexVertData
{
uint16 BoneIndices[MAX_TOTAL_INFLUENCES];
};
// Convert from APEX to UE coodinate system
nvidia::apex::ClothingAsset* ConvertApexAssetCoordSystem(nvidia::apex::ClothingAsset* InAsset);
// Convert APEX UV direction to UE UV direction
void FlipAuthoringUvs(NvParameterized::Interface* InRenderMeshAuthoringInterface, bool bFlipU, bool bFlipV);
// Extraction methods for pulling the required data from an APEX asset and
// pushing it to a UClothingAsset
void ExtractLodPhysicalData(UClothingAsset* NewAsset, nvidia::apex::ClothingAsset &InApexAsset, int32 InLodIdx, FClothLODData &InLodData, TArray<FApexVertData>& OutApexVertData);
void ExtractBoneData(UClothingAsset* NewAsset, nvidia::apex::ClothingAsset &InApexAsset);
void ExtractSphereCollisions(UClothingAsset* NewAsset, nvidia::apex::ClothingAsset &InApexAsset, int32 InLodIdx, FClothLODData &InLodData);
void ExtractMaterialParameters(UClothingAsset* NewAsset, nvidia::apex::ClothingAsset &InApexAsset);
#endif
// Utility methods for skeletal mesh extraction //////////////////////////
/**
* Using a physics asset, extract spheres and capsules and apply them to the provided collision container
* @param InPhysicsAsset The asset to pull body information from
* @param TargetMesh The mesh we are targetting
* @param TargetClothingAsset The clothing asset we are targetting
* @param OutCollisionData The collision container to fill
*/
void ExtractPhysicsAssetBodies(UPhysicsAsset* InPhysicsAsset, USkeletalMesh* TargetMesh, UClothingAsset* TargetClothingAsset, FClothCollisionData& OutCollisionData);
/** Handles internal import of LODs */
bool ImportToLodInternal(USkeletalMesh* SourceMesh, int32 SourceLodIndex, int32 SourceSectionIndex, UClothingAsset* DestAsset, FClothLODData& DestLod, FClothLODData* InParameterRemapSource = nullptr);
//////////////////////////////////////////////////////////////////////////
}; | [
"tungnt.rec@gmail.com"
] | tungnt.rec@gmail.com |
de63c1ea1de94b336556d6d5377147188f3a846d | 548bbbdf60919fc0cd77c3eec73470f572bc0c01 | /console_source/consoleoutput.h | ec28909ab3d51517526b33dcd695e3c52107eb81 | [
"MIT"
] | permissive | horsicq/PDBRipper | 54dab11749516c3c17adb4bfd5878d8ca24311a3 | 25d04da0f285dc31fae274323834735fd6d876a0 | refs/heads/master | 2023-08-22T22:36:03.104640 | 2023-08-21T17:14:43 | 2023-08-21T17:14:43 | 237,050,734 | 712 | 86 | MIT | 2022-10-18T12:14:08 | 2020-01-29T18:13:05 | C | UTF-8 | C++ | false | false | 1,469 | h | /* Copyright (c) 2020-2023 hors<horsicq@gmail.com>
*
* 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 CONSOLEOUTPUT_H
#define CONSOLEOUTPUT_H
#include <QObject>
class ConsoleOutput : public QObject
{
Q_OBJECT
public:
explicit ConsoleOutput(QObject *parent=nullptr);
public slots:
void infoMessage(QString sText);
void errorMessage(QString sText);
};
#endif // CONSOLEOUTPUT_H
| [
"horsicq@gmail.com"
] | horsicq@gmail.com |
7c3169d8992ea46fb581ea5b1eb596e41ff7ab20 | df295d7ec2064c527d7c47f7dfd3a6364c7a9cbf | /codeforces/practice/DIV1_202A.cpp | 169e38f45a587e00f863ea954ad6201707b7427f | [] | no_license | Shahraaz/CP_S4 | 7df25e4b764f0067ce51600e76923a7ed1b6fb82 | b1ae31fa40028ab878f27b4435bfe0d356b70df0 | refs/heads/master | 2020-05-24T22:08:55.990592 | 2019-07-15T23:42:49 | 2019-07-15T23:42:49 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,089 | cpp | //Optimise
#include <bits/stdc++.h>
using namespace std;
// #define multitest 1
#define Debug 1
#ifdef Debug
#define db(...) ZZ(#__VA_ARGS__, __VA_ARGS__);
template <typename Arg1>
void ZZ(const char *name, Arg1 &&arg1)
{
std::cerr << name << " = " << arg1 << endl;
}
template <typename Arg1, typename... Args>
void ZZ(const char *names, Arg1 &&arg1, Args &&... args)
{
const char *comma = strchr(names + 1, ',');
std::cerr.write(names, comma - names) << " = " << arg1;
ZZ(comma, args...);
}
#else
#define db(...)
#endif
typedef long long ll;
typedef long double ld;
#define f first
#define s second
#define pb push_back
const long long mod = 1000000007;
void solve()
{
int n;
cin >> n;
vector<int> a(n);
ll sum = 0;
for (auto &x : a)
{
cin >> x;
sum += x;
} // sort(a.begin(),a.end());
ll answer = *max_element(a.begin(), a.end());
answer = max(answer, (sum + n - 2) / (n - 1));
cout << answer << '\n';
}
int main()
{
#ifndef Debug
ios_base::sync_with_stdio(0);
cin.tie(0);
#endif
int t = 1;
#ifdef multitest
cin >> t;
#endif
while (t--)
solve();
return 0;
} | [
"shahraazhussain@gmail.com"
] | shahraazhussain@gmail.com |
4b26822a3e37379643afe71047b85b368f6d448c | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir7942/dir8062/dir8063/dir8254/dir8444/dir8720/dir10555/file10994.cpp | ed440ae0f609fcc9ed8fe3c7319565582c1355ef | [] | no_license | tgeng/HugeProject | 829c3bdfb7cbaf57727c41263212d4a67e3eb93d | 4488d3b765e8827636ce5e878baacdf388710ef2 | refs/heads/master | 2022-08-21T16:58:54.161627 | 2020-05-28T01:54:03 | 2020-05-28T01:54:03 | 267,468,475 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 115 | cpp | #ifndef file10994
#error "macro file10994 must be defined"
#endif
static const char* file10994String = "file10994"; | [
"tgeng@google.com"
] | tgeng@google.com |
e9fe8143e31061335f2db2cf84fbb0f49a251f66 | e758d58e8956f8ed3b1231e8f80039a2d81ebf22 | /rovioStreaming.h | 79f373c749b4d1ca4697647ee7e95faf505dff2f | [] | no_license | aurea-dt/rovioAPI | ed6462d001c134b4c8e2f9ec62650557786e3adf | 5c52cba9e74d177887dab67818f674e8e5109afc | refs/heads/master | 2016-09-05T16:55:49.826261 | 2015-06-09T01:10:08 | 2015-06-09T01:10:08 | 37,098,835 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,159 | h | ////////////////////////////////////////////////////////////////////////////////
// rovioStreaming.h
// Mario Chirinos Colunga
// Oscar Sanchez Sioridia
// Áurea - Desarrollo Tecnológico
// http://www.aurea-dt.com
// 17 Dic 2010 - 22 Jun 2013
//------------------------------------------------------------------------------
// Notes:
// Media streaming using gstreamer
//
////////////////////////////////////////////////////////////////////////////////
#ifndef IPCAM_H
#define IPCAM_H
// your public header include
#include <iostream>
#include <gst/gst.h>
#include <gtk/gtk.h>
#ifdef GDK_WINDOWING_X11
#include <gdk/gdkx.h> // for GDK_WINDOW_XID
#endif
#include <gst/interfaces/xoverlay.h>
//------------------------------------------------------------------------------
using namespace std;
typedef void (*videoCallback)(unsigned char*, unsigned int, unsigned int, unsigned int, void *);
typedef void (*rovioAudioCallback)(unsigned char*, unsigned int, unsigned int, unsigned int, void *);
//------------------------------------------------------------------------------
class rovioStreaming
{
private:
string videouri;
//video window
unsigned long int video_window_xid;
GtkWidget *videoWindow;
GtkWidget *drawArea;
// common elements
GstElement *rtspSrc;
GstElement *pipeline;
//video elements
int width;
int height;
GstElement *videoDecoder;
GstElement *videoFilter;
GstElement *videoFilterCaps;
GstElement *videoQueue;
GstElement *colorSpaceConverter1;
GstElement *colorSpaceConverter2;
GstElement *videoSink;
// audio elements
GstElement *audioDecoder;
GstElement *audioFilter;
GstElement *audioQueue;
GstElement *audioSink;
void static srcNewPad_callback(GstElement *element, GstPad *pad, void *data);
void static videoDecoderNewPad_callback(GstElement *element, GstPad *pad, void *data);
void static audioDecoderNewPad_callback(GstElement *element, GstPad *pad, void *data);
static int pipeline_bus_callback(GstBus *bus, GstMessage *message, void *data);
static int videoFilter_handoff_callback(GstElement *filter, GstBuffer *buffer, void *user_data);
static int audioFilter_handoff_callback(GstElement *filter, GstBuffer *buffer, void *user_data);
static void video_widget_realize_cb(GtkWidget* widget, void* user_data);
static GstBusSyncReply bus_sync_handler_cb(GstBus * bus, GstMessage * message, void* user_data);
static void hideanddisconnect_cb(GtkObject *object, void* user_data);
static void hide_cb(GtkObject *object, void* user_data);
videoCallback videoFpt;
rovioAudioCallback audioFpt;
public:
string name;
void* userdata;
int connect();
int disconnect();
unsigned int getWidth() const;
unsigned int getHeight() const;
const char* getDev() const;
void setVideoFilter(videoCallback ftp);
void unsetVideoFilter();
void setAudioFilter(rovioAudioCallback ftp);
void unsetAudioFilter();
int startAudioFilter();
int stopAudioFilter();
int startVideoFilter();
int stopVideoFilter();
void printCaps(GstPad *pad);
rovioStreaming(const char* _uri);
~rovioStreaming();
};
//------------------------------------------------------------------------------
#endif
| [
"mchc@aurea.dtdns.net"
] | mchc@aurea.dtdns.net |
9bd9978ed3913a4fd5a4a8f7f926193e14b6e929 | c776476e9d06b3779d744641e758ac3a2c15cddc | /examples/litmus/c/run-scripts/tmp_5/WRW+WR+fencembonceonce+poonceacquire+Once.c.cbmc_out.cpp | 20339b3066f2c024d33f57f159392138e7280ef6 | [] | no_license | ashutosh0gupta/llvm_bmc | aaac7961c723ba6f7ffd77a39559e0e52432eade | 0287c4fb180244e6b3c599a9902507f05c8a7234 | refs/heads/master | 2023-08-02T17:14:06.178723 | 2023-07-31T10:46:53 | 2023-07-31T10:46:53 | 143,100,825 | 3 | 4 | null | 2023-05-25T05:50:55 | 2018-08-01T03:47:00 | C++ | UTF-8 | C++ | false | false | 35,499 | cpp | // Global variabls:
// 0:vars:2
// 2:atom_1_X0_1:1
// 3:atom_2_X1_0:1
// Local global variabls:
// 0:thr0:1
// 1:thr1:1
// 2:thr2:1
#define ADDRSIZE 4
#define LOCALADDRSIZE 3
#define NTHREAD 4
#define NCONTEXT 5
#define ASSUME(stmt) __CPROVER_assume(stmt)
#define ASSERT(stmt) __CPROVER_assert(stmt, "error")
#define max(a,b) (a>b?a:b)
char __get_rng();
char get_rng( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
char get_rng_th( char from, char to ) {
char ret = __get_rng();
ASSUME(ret >= from && ret <= to);
return ret;
}
int main(int argc, char **argv) {
// Declare arrays for intial value version in contexts
int local_mem[LOCALADDRSIZE];
// Dumping initializations
local_mem[0+0] = 0;
local_mem[1+0] = 0;
local_mem[2+0] = 0;
int cstart[NTHREAD];
int creturn[NTHREAD];
// declare arrays for contexts activity
int active[NCONTEXT];
int ctx_used[NCONTEXT];
// declare arrays for intial value version in contexts
int meminit_[ADDRSIZE*NCONTEXT];
#define meminit(x,k) meminit_[(x)*NCONTEXT+k]
int coinit_[ADDRSIZE*NCONTEXT];
#define coinit(x,k) coinit_[(x)*NCONTEXT+k]
int deltainit_[ADDRSIZE*NCONTEXT];
#define deltainit(x,k) deltainit_[(x)*NCONTEXT+k]
// declare arrays for running value version in contexts
int mem_[ADDRSIZE*NCONTEXT];
#define mem(x,k) mem_[(x)*NCONTEXT+k]
int co_[ADDRSIZE*NCONTEXT];
#define co(x,k) co_[(x)*NCONTEXT+k]
int delta_[ADDRSIZE*NCONTEXT];
#define delta(x,k) delta_[(x)*NCONTEXT+k]
// declare arrays for local buffer and observed writes
int buff_[NTHREAD*ADDRSIZE];
#define buff(x,k) buff_[(x)*ADDRSIZE+k]
int pw_[NTHREAD*ADDRSIZE];
#define pw(x,k) pw_[(x)*ADDRSIZE+k]
// declare arrays for context stamps
char cr_[NTHREAD*ADDRSIZE];
#define cr(x,k) cr_[(x)*ADDRSIZE+k]
char iw_[NTHREAD*ADDRSIZE];
#define iw(x,k) iw_[(x)*ADDRSIZE+k]
char cw_[NTHREAD*ADDRSIZE];
#define cw(x,k) cw_[(x)*ADDRSIZE+k]
char cx_[NTHREAD*ADDRSIZE];
#define cx(x,k) cx_[(x)*ADDRSIZE+k]
char is_[NTHREAD*ADDRSIZE];
#define is(x,k) is_[(x)*ADDRSIZE+k]
char cs_[NTHREAD*ADDRSIZE];
#define cs(x,k) cs_[(x)*ADDRSIZE+k]
char crmax_[NTHREAD*ADDRSIZE];
#define crmax(x,k) crmax_[(x)*ADDRSIZE+k]
char sforbid_[ADDRSIZE*NCONTEXT];
#define sforbid(x,k) sforbid_[(x)*NCONTEXT+k]
// declare arrays for synchronizations
int cl[NTHREAD];
int cdy[NTHREAD];
int cds[NTHREAD];
int cdl[NTHREAD];
int cisb[NTHREAD];
int caddr[NTHREAD];
int cctrl[NTHREAD];
int r0= 0;
char creg_r0;
char creg__r0__1_;
int r1= 0;
char creg_r1;
char creg__r1__0_;
int r2= 0;
char creg_r2;
int r3= 0;
char creg_r3;
int r4= 0;
char creg_r4;
int r5= 0;
char creg_r5;
int r6= 0;
char creg_r6;
char creg__r6__2_;
int r7= 0;
char creg_r7;
int r8= 0;
char creg_r8;
int r9= 0;
char creg_r9;
int r10= 0;
char creg_r10;
char creg__r10__1_;
int r11= 0;
char creg_r11;
char old_cctrl= 0;
char old_cr= 0;
char old_cdy= 0;
char old_cw= 0;
char new_creg= 0;
buff(0,0) = 0;
pw(0,0) = 0;
cr(0,0) = 0;
iw(0,0) = 0;
cw(0,0) = 0;
cx(0,0) = 0;
is(0,0) = 0;
cs(0,0) = 0;
crmax(0,0) = 0;
buff(0,1) = 0;
pw(0,1) = 0;
cr(0,1) = 0;
iw(0,1) = 0;
cw(0,1) = 0;
cx(0,1) = 0;
is(0,1) = 0;
cs(0,1) = 0;
crmax(0,1) = 0;
buff(0,2) = 0;
pw(0,2) = 0;
cr(0,2) = 0;
iw(0,2) = 0;
cw(0,2) = 0;
cx(0,2) = 0;
is(0,2) = 0;
cs(0,2) = 0;
crmax(0,2) = 0;
buff(0,3) = 0;
pw(0,3) = 0;
cr(0,3) = 0;
iw(0,3) = 0;
cw(0,3) = 0;
cx(0,3) = 0;
is(0,3) = 0;
cs(0,3) = 0;
crmax(0,3) = 0;
cl[0] = 0;
cdy[0] = 0;
cds[0] = 0;
cdl[0] = 0;
cisb[0] = 0;
caddr[0] = 0;
cctrl[0] = 0;
cstart[0] = get_rng(0,NCONTEXT-1);
creturn[0] = get_rng(0,NCONTEXT-1);
buff(1,0) = 0;
pw(1,0) = 0;
cr(1,0) = 0;
iw(1,0) = 0;
cw(1,0) = 0;
cx(1,0) = 0;
is(1,0) = 0;
cs(1,0) = 0;
crmax(1,0) = 0;
buff(1,1) = 0;
pw(1,1) = 0;
cr(1,1) = 0;
iw(1,1) = 0;
cw(1,1) = 0;
cx(1,1) = 0;
is(1,1) = 0;
cs(1,1) = 0;
crmax(1,1) = 0;
buff(1,2) = 0;
pw(1,2) = 0;
cr(1,2) = 0;
iw(1,2) = 0;
cw(1,2) = 0;
cx(1,2) = 0;
is(1,2) = 0;
cs(1,2) = 0;
crmax(1,2) = 0;
buff(1,3) = 0;
pw(1,3) = 0;
cr(1,3) = 0;
iw(1,3) = 0;
cw(1,3) = 0;
cx(1,3) = 0;
is(1,3) = 0;
cs(1,3) = 0;
crmax(1,3) = 0;
cl[1] = 0;
cdy[1] = 0;
cds[1] = 0;
cdl[1] = 0;
cisb[1] = 0;
caddr[1] = 0;
cctrl[1] = 0;
cstart[1] = get_rng(0,NCONTEXT-1);
creturn[1] = get_rng(0,NCONTEXT-1);
buff(2,0) = 0;
pw(2,0) = 0;
cr(2,0) = 0;
iw(2,0) = 0;
cw(2,0) = 0;
cx(2,0) = 0;
is(2,0) = 0;
cs(2,0) = 0;
crmax(2,0) = 0;
buff(2,1) = 0;
pw(2,1) = 0;
cr(2,1) = 0;
iw(2,1) = 0;
cw(2,1) = 0;
cx(2,1) = 0;
is(2,1) = 0;
cs(2,1) = 0;
crmax(2,1) = 0;
buff(2,2) = 0;
pw(2,2) = 0;
cr(2,2) = 0;
iw(2,2) = 0;
cw(2,2) = 0;
cx(2,2) = 0;
is(2,2) = 0;
cs(2,2) = 0;
crmax(2,2) = 0;
buff(2,3) = 0;
pw(2,3) = 0;
cr(2,3) = 0;
iw(2,3) = 0;
cw(2,3) = 0;
cx(2,3) = 0;
is(2,3) = 0;
cs(2,3) = 0;
crmax(2,3) = 0;
cl[2] = 0;
cdy[2] = 0;
cds[2] = 0;
cdl[2] = 0;
cisb[2] = 0;
caddr[2] = 0;
cctrl[2] = 0;
cstart[2] = get_rng(0,NCONTEXT-1);
creturn[2] = get_rng(0,NCONTEXT-1);
buff(3,0) = 0;
pw(3,0) = 0;
cr(3,0) = 0;
iw(3,0) = 0;
cw(3,0) = 0;
cx(3,0) = 0;
is(3,0) = 0;
cs(3,0) = 0;
crmax(3,0) = 0;
buff(3,1) = 0;
pw(3,1) = 0;
cr(3,1) = 0;
iw(3,1) = 0;
cw(3,1) = 0;
cx(3,1) = 0;
is(3,1) = 0;
cs(3,1) = 0;
crmax(3,1) = 0;
buff(3,2) = 0;
pw(3,2) = 0;
cr(3,2) = 0;
iw(3,2) = 0;
cw(3,2) = 0;
cx(3,2) = 0;
is(3,2) = 0;
cs(3,2) = 0;
crmax(3,2) = 0;
buff(3,3) = 0;
pw(3,3) = 0;
cr(3,3) = 0;
iw(3,3) = 0;
cw(3,3) = 0;
cx(3,3) = 0;
is(3,3) = 0;
cs(3,3) = 0;
crmax(3,3) = 0;
cl[3] = 0;
cdy[3] = 0;
cds[3] = 0;
cdl[3] = 0;
cisb[3] = 0;
caddr[3] = 0;
cctrl[3] = 0;
cstart[3] = get_rng(0,NCONTEXT-1);
creturn[3] = get_rng(0,NCONTEXT-1);
// Dumping initializations
mem(0+0,0) = 0;
mem(0+1,0) = 0;
mem(2+0,0) = 0;
mem(3+0,0) = 0;
// Dumping context matching equalities
co(0,0) = 0;
delta(0,0) = -1;
mem(0,1) = meminit(0,1);
co(0,1) = coinit(0,1);
delta(0,1) = deltainit(0,1);
mem(0,2) = meminit(0,2);
co(0,2) = coinit(0,2);
delta(0,2) = deltainit(0,2);
mem(0,3) = meminit(0,3);
co(0,3) = coinit(0,3);
delta(0,3) = deltainit(0,3);
mem(0,4) = meminit(0,4);
co(0,4) = coinit(0,4);
delta(0,4) = deltainit(0,4);
co(1,0) = 0;
delta(1,0) = -1;
mem(1,1) = meminit(1,1);
co(1,1) = coinit(1,1);
delta(1,1) = deltainit(1,1);
mem(1,2) = meminit(1,2);
co(1,2) = coinit(1,2);
delta(1,2) = deltainit(1,2);
mem(1,3) = meminit(1,3);
co(1,3) = coinit(1,3);
delta(1,3) = deltainit(1,3);
mem(1,4) = meminit(1,4);
co(1,4) = coinit(1,4);
delta(1,4) = deltainit(1,4);
co(2,0) = 0;
delta(2,0) = -1;
mem(2,1) = meminit(2,1);
co(2,1) = coinit(2,1);
delta(2,1) = deltainit(2,1);
mem(2,2) = meminit(2,2);
co(2,2) = coinit(2,2);
delta(2,2) = deltainit(2,2);
mem(2,3) = meminit(2,3);
co(2,3) = coinit(2,3);
delta(2,3) = deltainit(2,3);
mem(2,4) = meminit(2,4);
co(2,4) = coinit(2,4);
delta(2,4) = deltainit(2,4);
co(3,0) = 0;
delta(3,0) = -1;
mem(3,1) = meminit(3,1);
co(3,1) = coinit(3,1);
delta(3,1) = deltainit(3,1);
mem(3,2) = meminit(3,2);
co(3,2) = coinit(3,2);
delta(3,2) = deltainit(3,2);
mem(3,3) = meminit(3,3);
co(3,3) = coinit(3,3);
delta(3,3) = deltainit(3,3);
mem(3,4) = meminit(3,4);
co(3,4) = coinit(3,4);
delta(3,4) = deltainit(3,4);
// Dumping thread 1
int ret_thread_1 = 0;
cdy[1] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[1] >= cstart[1]);
T1BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !36, metadata !DIExpression()), !dbg !42
// br label %label_1, !dbg !43
goto T1BLOCK1;
T1BLOCK1:
// call void @llvm.dbg.label(metadata !41), !dbg !44
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !37, metadata !DIExpression()), !dbg !45
// call void @llvm.dbg.value(metadata i64 1, metadata !40, metadata !DIExpression()), !dbg !45
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !46
// ST: Guess
iw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STIW _l20_c3
old_cw = cw(1,0);
cw(1,0) = get_rng(0,NCONTEXT-1);// 1 ASSIGN STCOM _l20_c3
// Check
ASSUME(active[iw(1,0)] == 1);
ASSUME(active[cw(1,0)] == 1);
ASSUME(sforbid(0,cw(1,0))== 0);
ASSUME(iw(1,0) >= 0);
ASSUME(iw(1,0) >= 0);
ASSUME(cw(1,0) >= iw(1,0));
ASSUME(cw(1,0) >= old_cw);
ASSUME(cw(1,0) >= cr(1,0));
ASSUME(cw(1,0) >= cl[1]);
ASSUME(cw(1,0) >= cisb[1]);
ASSUME(cw(1,0) >= cdy[1]);
ASSUME(cw(1,0) >= cdl[1]);
ASSUME(cw(1,0) >= cds[1]);
ASSUME(cw(1,0) >= cctrl[1]);
ASSUME(cw(1,0) >= caddr[1]);
// Update
caddr[1] = max(caddr[1],0);
buff(1,0) = 1;
mem(0,cw(1,0)) = 1;
co(0,cw(1,0))+=1;
delta(0,cw(1,0)) = -1;
ASSUME(creturn[1] >= cw(1,0));
// ret i8* null, !dbg !47
ret_thread_1 = (- 1);
goto T1BLOCK_END;
T1BLOCK_END:
// Dumping thread 2
int ret_thread_2 = 0;
cdy[2] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[2] >= cstart[2]);
T2BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !50, metadata !DIExpression()), !dbg !60
// br label %label_2, !dbg !48
goto T2BLOCK1;
T2BLOCK1:
// call void @llvm.dbg.label(metadata !59), !dbg !62
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !52, metadata !DIExpression()), !dbg !63
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !51
// LD: Guess
old_cr = cr(2,0);
cr(2,0) = get_rng(0,NCONTEXT-1);// 2 ASSIGN LDCOM _l26_c15
// Check
ASSUME(active[cr(2,0)] == 2);
ASSUME(cr(2,0) >= iw(2,0));
ASSUME(cr(2,0) >= 0);
ASSUME(cr(2,0) >= cdy[2]);
ASSUME(cr(2,0) >= cisb[2]);
ASSUME(cr(2,0) >= cdl[2]);
ASSUME(cr(2,0) >= cl[2]);
// Update
creg_r0 = cr(2,0);
crmax(2,0) = max(crmax(2,0),cr(2,0));
caddr[2] = max(caddr[2],0);
if(cr(2,0) < cw(2,0)) {
r0 = buff(2,0);
ASSUME((!(( (cw(2,0) < 1) && (1 < crmax(2,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(2,0) < 2) && (2 < crmax(2,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(2,0) < 3) && (3 < crmax(2,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(2,0) < 4) && (4 < crmax(2,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(2,0) != co(0,cr(2,0))) {
ASSUME(cr(2,0) >= old_cr);
}
pw(2,0) = co(0,cr(2,0));
r0 = mem(0,cr(2,0));
}
ASSUME(creturn[2] >= cr(2,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !54, metadata !DIExpression()), !dbg !63
// %conv = trunc i64 %0 to i32, !dbg !52
// call void @llvm.dbg.value(metadata i32 %conv, metadata !51, metadata !DIExpression()), !dbg !60
// call void (...) @dmbsy(), !dbg !53
// dumbsy: Guess
old_cdy = cdy[2];
cdy[2] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[2] >= old_cdy);
ASSUME(cdy[2] >= cisb[2]);
ASSUME(cdy[2] >= cdl[2]);
ASSUME(cdy[2] >= cds[2]);
ASSUME(cdy[2] >= cctrl[2]);
ASSUME(cdy[2] >= cw(2,0+0));
ASSUME(cdy[2] >= cw(2,0+1));
ASSUME(cdy[2] >= cw(2,2+0));
ASSUME(cdy[2] >= cw(2,3+0));
ASSUME(cdy[2] >= cr(2,0+0));
ASSUME(cdy[2] >= cr(2,0+1));
ASSUME(cdy[2] >= cr(2,2+0));
ASSUME(cdy[2] >= cr(2,3+0));
ASSUME(creturn[2] >= cdy[2]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !55, metadata !DIExpression()), !dbg !67
// call void @llvm.dbg.value(metadata i64 1, metadata !57, metadata !DIExpression()), !dbg !67
// store atomic i64 1, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !55
// ST: Guess
iw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l28_c3
old_cw = cw(2,0+1*1);
cw(2,0+1*1) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l28_c3
// Check
ASSUME(active[iw(2,0+1*1)] == 2);
ASSUME(active[cw(2,0+1*1)] == 2);
ASSUME(sforbid(0+1*1,cw(2,0+1*1))== 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(iw(2,0+1*1) >= 0);
ASSUME(cw(2,0+1*1) >= iw(2,0+1*1));
ASSUME(cw(2,0+1*1) >= old_cw);
ASSUME(cw(2,0+1*1) >= cr(2,0+1*1));
ASSUME(cw(2,0+1*1) >= cl[2]);
ASSUME(cw(2,0+1*1) >= cisb[2]);
ASSUME(cw(2,0+1*1) >= cdy[2]);
ASSUME(cw(2,0+1*1) >= cdl[2]);
ASSUME(cw(2,0+1*1) >= cds[2]);
ASSUME(cw(2,0+1*1) >= cctrl[2]);
ASSUME(cw(2,0+1*1) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,0+1*1) = 1;
mem(0+1*1,cw(2,0+1*1)) = 1;
co(0+1*1,cw(2,0+1*1))+=1;
delta(0+1*1,cw(2,0+1*1)) = -1;
ASSUME(creturn[2] >= cw(2,0+1*1));
// %cmp = icmp eq i32 %conv, 1, !dbg !56
creg__r0__1_ = max(0,creg_r0);
// %conv1 = zext i1 %cmp to i32, !dbg !56
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !58, metadata !DIExpression()), !dbg !60
// store i32 %conv1, i32* @atom_1_X0_1, align 4, !dbg !57, !tbaa !58
// ST: Guess
iw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STIW _l30_c15
old_cw = cw(2,2);
cw(2,2) = get_rng(0,NCONTEXT-1);// 2 ASSIGN STCOM _l30_c15
// Check
ASSUME(active[iw(2,2)] == 2);
ASSUME(active[cw(2,2)] == 2);
ASSUME(sforbid(2,cw(2,2))== 0);
ASSUME(iw(2,2) >= creg__r0__1_);
ASSUME(iw(2,2) >= 0);
ASSUME(cw(2,2) >= iw(2,2));
ASSUME(cw(2,2) >= old_cw);
ASSUME(cw(2,2) >= cr(2,2));
ASSUME(cw(2,2) >= cl[2]);
ASSUME(cw(2,2) >= cisb[2]);
ASSUME(cw(2,2) >= cdy[2]);
ASSUME(cw(2,2) >= cdl[2]);
ASSUME(cw(2,2) >= cds[2]);
ASSUME(cw(2,2) >= cctrl[2]);
ASSUME(cw(2,2) >= caddr[2]);
// Update
caddr[2] = max(caddr[2],0);
buff(2,2) = (r0==1);
mem(2,cw(2,2)) = (r0==1);
co(2,cw(2,2))+=1;
delta(2,cw(2,2)) = -1;
ASSUME(creturn[2] >= cw(2,2));
// ret i8* null, !dbg !62
ret_thread_2 = (- 1);
goto T2BLOCK_END;
T2BLOCK_END:
// Dumping thread 3
int ret_thread_3 = 0;
cdy[3] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[3] >= cstart[3]);
T3BLOCK0:
// call void @llvm.dbg.value(metadata i8* %arg, metadata !78, metadata !DIExpression()), !dbg !88
// br label %label_3, !dbg !48
goto T3BLOCK1;
T3BLOCK1:
// call void @llvm.dbg.label(metadata !87), !dbg !90
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !79, metadata !DIExpression()), !dbg !91
// call void @llvm.dbg.value(metadata i64 2, metadata !81, metadata !DIExpression()), !dbg !91
// store atomic i64 2, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !51
// ST: Guess
iw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l36_c3
old_cw = cw(3,0+1*1);
cw(3,0+1*1) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l36_c3
// Check
ASSUME(active[iw(3,0+1*1)] == 3);
ASSUME(active[cw(3,0+1*1)] == 3);
ASSUME(sforbid(0+1*1,cw(3,0+1*1))== 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(iw(3,0+1*1) >= 0);
ASSUME(cw(3,0+1*1) >= iw(3,0+1*1));
ASSUME(cw(3,0+1*1) >= old_cw);
ASSUME(cw(3,0+1*1) >= cr(3,0+1*1));
ASSUME(cw(3,0+1*1) >= cl[3]);
ASSUME(cw(3,0+1*1) >= cisb[3]);
ASSUME(cw(3,0+1*1) >= cdy[3]);
ASSUME(cw(3,0+1*1) >= cdl[3]);
ASSUME(cw(3,0+1*1) >= cds[3]);
ASSUME(cw(3,0+1*1) >= cctrl[3]);
ASSUME(cw(3,0+1*1) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,0+1*1) = 2;
mem(0+1*1,cw(3,0+1*1)) = 2;
co(0+1*1,cw(3,0+1*1))+=1;
delta(0+1*1,cw(3,0+1*1)) = -1;
ASSUME(creturn[3] >= cw(3,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !83, metadata !DIExpression()), !dbg !93
// %0 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) acquire, align 8, !dbg !53
// LD: Guess
// : Acquire
old_cr = cr(3,0);
cr(3,0) = get_rng(0,NCONTEXT-1);// 3 ASSIGN LDCOM _l37_c15
// Check
ASSUME(active[cr(3,0)] == 3);
ASSUME(cr(3,0) >= iw(3,0));
ASSUME(cr(3,0) >= 0);
ASSUME(cr(3,0) >= cdy[3]);
ASSUME(cr(3,0) >= cisb[3]);
ASSUME(cr(3,0) >= cdl[3]);
ASSUME(cr(3,0) >= cl[3]);
ASSUME(cr(3,0) >= cx(3,0));
ASSUME(cr(3,0) >= cs(3,0+0));
ASSUME(cr(3,0) >= cs(3,0+1));
ASSUME(cr(3,0) >= cs(3,2+0));
ASSUME(cr(3,0) >= cs(3,3+0));
// Update
creg_r1 = cr(3,0);
crmax(3,0) = max(crmax(3,0),cr(3,0));
caddr[3] = max(caddr[3],0);
if(cr(3,0) < cw(3,0)) {
r1 = buff(3,0);
ASSUME((!(( (cw(3,0) < 1) && (1 < crmax(3,0)) )))||(sforbid(0,1)> 0));
ASSUME((!(( (cw(3,0) < 2) && (2 < crmax(3,0)) )))||(sforbid(0,2)> 0));
ASSUME((!(( (cw(3,0) < 3) && (3 < crmax(3,0)) )))||(sforbid(0,3)> 0));
ASSUME((!(( (cw(3,0) < 4) && (4 < crmax(3,0)) )))||(sforbid(0,4)> 0));
} else {
if(pw(3,0) != co(0,cr(3,0))) {
ASSUME(cr(3,0) >= old_cr);
}
pw(3,0) = co(0,cr(3,0));
r1 = mem(0,cr(3,0));
}
cl[3] = max(cl[3],cr(3,0));
ASSUME(creturn[3] >= cr(3,0));
// call void @llvm.dbg.value(metadata i64 %0, metadata !85, metadata !DIExpression()), !dbg !93
// %conv = trunc i64 %0 to i32, !dbg !54
// call void @llvm.dbg.value(metadata i32 %conv, metadata !82, metadata !DIExpression()), !dbg !88
// %cmp = icmp eq i32 %conv, 0, !dbg !55
creg__r1__0_ = max(0,creg_r1);
// %conv1 = zext i1 %cmp to i32, !dbg !55
// call void @llvm.dbg.value(metadata i32 %conv1, metadata !86, metadata !DIExpression()), !dbg !88
// store i32 %conv1, i32* @atom_2_X1_0, align 4, !dbg !56, !tbaa !57
// ST: Guess
iw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STIW _l39_c15
old_cw = cw(3,3);
cw(3,3) = get_rng(0,NCONTEXT-1);// 3 ASSIGN STCOM _l39_c15
// Check
ASSUME(active[iw(3,3)] == 3);
ASSUME(active[cw(3,3)] == 3);
ASSUME(sforbid(3,cw(3,3))== 0);
ASSUME(iw(3,3) >= creg__r1__0_);
ASSUME(iw(3,3) >= 0);
ASSUME(cw(3,3) >= iw(3,3));
ASSUME(cw(3,3) >= old_cw);
ASSUME(cw(3,3) >= cr(3,3));
ASSUME(cw(3,3) >= cl[3]);
ASSUME(cw(3,3) >= cisb[3]);
ASSUME(cw(3,3) >= cdy[3]);
ASSUME(cw(3,3) >= cdl[3]);
ASSUME(cw(3,3) >= cds[3]);
ASSUME(cw(3,3) >= cctrl[3]);
ASSUME(cw(3,3) >= caddr[3]);
// Update
caddr[3] = max(caddr[3],0);
buff(3,3) = (r1==0);
mem(3,cw(3,3)) = (r1==0);
co(3,cw(3,3))+=1;
delta(3,cw(3,3)) = -1;
ASSUME(creturn[3] >= cw(3,3));
// ret i8* null, !dbg !61
ret_thread_3 = (- 1);
goto T3BLOCK_END;
T3BLOCK_END:
// Dumping thread 0
int ret_thread_0 = 0;
cdy[0] = get_rng(0,NCONTEXT-1);
ASSUME(cdy[0] >= cstart[0]);
T0BLOCK0:
// %thr0 = alloca i64, align 8
// %thr1 = alloca i64, align 8
// %thr2 = alloca i64, align 8
// call void @llvm.dbg.value(metadata i32 %argc, metadata !106, metadata !DIExpression()), !dbg !129
// call void @llvm.dbg.value(metadata i8** %argv, metadata !107, metadata !DIExpression()), !dbg !129
// %0 = bitcast i64* %thr0 to i8*, !dbg !64
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %0) #7, !dbg !64
// call void @llvm.dbg.declare(metadata i64* %thr0, metadata !108, metadata !DIExpression()), !dbg !131
// %1 = bitcast i64* %thr1 to i8*, !dbg !66
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %1) #7, !dbg !66
// call void @llvm.dbg.declare(metadata i64* %thr1, metadata !112, metadata !DIExpression()), !dbg !133
// %2 = bitcast i64* %thr2 to i8*, !dbg !68
// call void @llvm.lifetime.start.p0i8(i64 8, i8* %2) #7, !dbg !68
// call void @llvm.dbg.declare(metadata i64* %thr2, metadata !113, metadata !DIExpression()), !dbg !135
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !114, metadata !DIExpression()), !dbg !136
// call void @llvm.dbg.value(metadata i64 0, metadata !116, metadata !DIExpression()), !dbg !136
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !71
// ST: Guess
iw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l48_c3
old_cw = cw(0,0+1*1);
cw(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l48_c3
// Check
ASSUME(active[iw(0,0+1*1)] == 0);
ASSUME(active[cw(0,0+1*1)] == 0);
ASSUME(sforbid(0+1*1,cw(0,0+1*1))== 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(iw(0,0+1*1) >= 0);
ASSUME(cw(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cw(0,0+1*1) >= old_cw);
ASSUME(cw(0,0+1*1) >= cr(0,0+1*1));
ASSUME(cw(0,0+1*1) >= cl[0]);
ASSUME(cw(0,0+1*1) >= cisb[0]);
ASSUME(cw(0,0+1*1) >= cdy[0]);
ASSUME(cw(0,0+1*1) >= cdl[0]);
ASSUME(cw(0,0+1*1) >= cds[0]);
ASSUME(cw(0,0+1*1) >= cctrl[0]);
ASSUME(cw(0,0+1*1) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0+1*1) = 0;
mem(0+1*1,cw(0,0+1*1)) = 0;
co(0+1*1,cw(0,0+1*1))+=1;
delta(0+1*1,cw(0,0+1*1)) = -1;
ASSUME(creturn[0] >= cw(0,0+1*1));
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0), metadata !117, metadata !DIExpression()), !dbg !138
// call void @llvm.dbg.value(metadata i64 0, metadata !119, metadata !DIExpression()), !dbg !138
// store atomic i64 0, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 0) monotonic, align 8, !dbg !73
// ST: Guess
iw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l49_c3
old_cw = cw(0,0);
cw(0,0) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l49_c3
// Check
ASSUME(active[iw(0,0)] == 0);
ASSUME(active[cw(0,0)] == 0);
ASSUME(sforbid(0,cw(0,0))== 0);
ASSUME(iw(0,0) >= 0);
ASSUME(iw(0,0) >= 0);
ASSUME(cw(0,0) >= iw(0,0));
ASSUME(cw(0,0) >= old_cw);
ASSUME(cw(0,0) >= cr(0,0));
ASSUME(cw(0,0) >= cl[0]);
ASSUME(cw(0,0) >= cisb[0]);
ASSUME(cw(0,0) >= cdy[0]);
ASSUME(cw(0,0) >= cdl[0]);
ASSUME(cw(0,0) >= cds[0]);
ASSUME(cw(0,0) >= cctrl[0]);
ASSUME(cw(0,0) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,0) = 0;
mem(0,cw(0,0)) = 0;
co(0,cw(0,0))+=1;
delta(0,cw(0,0)) = -1;
ASSUME(creturn[0] >= cw(0,0));
// store i32 0, i32* @atom_1_X0_1, align 4, !dbg !74, !tbaa !75
// ST: Guess
iw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l50_c15
old_cw = cw(0,2);
cw(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l50_c15
// Check
ASSUME(active[iw(0,2)] == 0);
ASSUME(active[cw(0,2)] == 0);
ASSUME(sforbid(2,cw(0,2))== 0);
ASSUME(iw(0,2) >= 0);
ASSUME(iw(0,2) >= 0);
ASSUME(cw(0,2) >= iw(0,2));
ASSUME(cw(0,2) >= old_cw);
ASSUME(cw(0,2) >= cr(0,2));
ASSUME(cw(0,2) >= cl[0]);
ASSUME(cw(0,2) >= cisb[0]);
ASSUME(cw(0,2) >= cdy[0]);
ASSUME(cw(0,2) >= cdl[0]);
ASSUME(cw(0,2) >= cds[0]);
ASSUME(cw(0,2) >= cctrl[0]);
ASSUME(cw(0,2) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,2) = 0;
mem(2,cw(0,2)) = 0;
co(2,cw(0,2))+=1;
delta(2,cw(0,2)) = -1;
ASSUME(creturn[0] >= cw(0,2));
// store i32 0, i32* @atom_2_X1_0, align 4, !dbg !79, !tbaa !75
// ST: Guess
iw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STIW _l51_c15
old_cw = cw(0,3);
cw(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN STCOM _l51_c15
// Check
ASSUME(active[iw(0,3)] == 0);
ASSUME(active[cw(0,3)] == 0);
ASSUME(sforbid(3,cw(0,3))== 0);
ASSUME(iw(0,3) >= 0);
ASSUME(iw(0,3) >= 0);
ASSUME(cw(0,3) >= iw(0,3));
ASSUME(cw(0,3) >= old_cw);
ASSUME(cw(0,3) >= cr(0,3));
ASSUME(cw(0,3) >= cl[0]);
ASSUME(cw(0,3) >= cisb[0]);
ASSUME(cw(0,3) >= cdy[0]);
ASSUME(cw(0,3) >= cdl[0]);
ASSUME(cw(0,3) >= cds[0]);
ASSUME(cw(0,3) >= cctrl[0]);
ASSUME(cw(0,3) >= caddr[0]);
// Update
caddr[0] = max(caddr[0],0);
buff(0,3) = 0;
mem(3,cw(0,3)) = 0;
co(3,cw(0,3))+=1;
delta(3,cw(0,3)) = -1;
ASSUME(creturn[0] >= cw(0,3));
// %call = call i32 @pthread_create(i64* noundef %thr0, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t0, i8* noundef null) #7, !dbg !80
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[1] >= cdy[0]);
// %call3 = call i32 @pthread_create(i64* noundef %thr1, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t1, i8* noundef null) #7, !dbg !81
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[2] >= cdy[0]);
// %call4 = call i32 @pthread_create(i64* noundef %thr2, %union.pthread_attr_t* noundef null, i8* (i8*)* noundef @t2, i8* noundef null) #7, !dbg !82
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cstart[3] >= cdy[0]);
// %3 = load i64, i64* %thr0, align 8, !dbg !83, !tbaa !84
r3 = local_mem[0];
// %call5 = call i32 @pthread_join(i64 noundef %3, i8** noundef null), !dbg !86
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[1]);
// %4 = load i64, i64* %thr1, align 8, !dbg !87, !tbaa !84
r4 = local_mem[1];
// %call6 = call i32 @pthread_join(i64 noundef %4, i8** noundef null), !dbg !88
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[2]);
// %5 = load i64, i64* %thr2, align 8, !dbg !89, !tbaa !84
r5 = local_mem[2];
// %call7 = call i32 @pthread_join(i64 noundef %5, i8** noundef null), !dbg !90
// dumbsy: Guess
old_cdy = cdy[0];
cdy[0] = get_rng(0,NCONTEXT-1);
// Check
ASSUME(cdy[0] >= old_cdy);
ASSUME(cdy[0] >= cisb[0]);
ASSUME(cdy[0] >= cdl[0]);
ASSUME(cdy[0] >= cds[0]);
ASSUME(cdy[0] >= cctrl[0]);
ASSUME(cdy[0] >= cw(0,0+0));
ASSUME(cdy[0] >= cw(0,0+1));
ASSUME(cdy[0] >= cw(0,2+0));
ASSUME(cdy[0] >= cw(0,3+0));
ASSUME(cdy[0] >= cr(0,0+0));
ASSUME(cdy[0] >= cr(0,0+1));
ASSUME(cdy[0] >= cr(0,2+0));
ASSUME(cdy[0] >= cr(0,3+0));
ASSUME(creturn[0] >= cdy[0]);
ASSUME(cdy[0] >= creturn[3]);
// call void @llvm.dbg.value(metadata i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1), metadata !121, metadata !DIExpression()), !dbg !153
// %6 = load atomic i64, i64* getelementptr inbounds ([2 x i64], [2 x i64]* @vars, i64 0, i64 1) monotonic, align 8, !dbg !92
// LD: Guess
old_cr = cr(0,0+1*1);
cr(0,0+1*1) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l61_c12
// Check
ASSUME(active[cr(0,0+1*1)] == 0);
ASSUME(cr(0,0+1*1) >= iw(0,0+1*1));
ASSUME(cr(0,0+1*1) >= 0);
ASSUME(cr(0,0+1*1) >= cdy[0]);
ASSUME(cr(0,0+1*1) >= cisb[0]);
ASSUME(cr(0,0+1*1) >= cdl[0]);
ASSUME(cr(0,0+1*1) >= cl[0]);
// Update
creg_r6 = cr(0,0+1*1);
crmax(0,0+1*1) = max(crmax(0,0+1*1),cr(0,0+1*1));
caddr[0] = max(caddr[0],0);
if(cr(0,0+1*1) < cw(0,0+1*1)) {
r6 = buff(0,0+1*1);
ASSUME((!(( (cw(0,0+1*1) < 1) && (1 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,1)> 0));
ASSUME((!(( (cw(0,0+1*1) < 2) && (2 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,2)> 0));
ASSUME((!(( (cw(0,0+1*1) < 3) && (3 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,3)> 0));
ASSUME((!(( (cw(0,0+1*1) < 4) && (4 < crmax(0,0+1*1)) )))||(sforbid(0+1*1,4)> 0));
} else {
if(pw(0,0+1*1) != co(0+1*1,cr(0,0+1*1))) {
ASSUME(cr(0,0+1*1) >= old_cr);
}
pw(0,0+1*1) = co(0+1*1,cr(0,0+1*1));
r6 = mem(0+1*1,cr(0,0+1*1));
}
ASSUME(creturn[0] >= cr(0,0+1*1));
// call void @llvm.dbg.value(metadata i64 %6, metadata !123, metadata !DIExpression()), !dbg !153
// %conv = trunc i64 %6 to i32, !dbg !93
// call void @llvm.dbg.value(metadata i32 %conv, metadata !120, metadata !DIExpression()), !dbg !129
// %cmp = icmp eq i32 %conv, 2, !dbg !94
creg__r6__2_ = max(0,creg_r6);
// %conv8 = zext i1 %cmp to i32, !dbg !94
// call void @llvm.dbg.value(metadata i32 %conv8, metadata !124, metadata !DIExpression()), !dbg !129
// %7 = load i32, i32* @atom_1_X0_1, align 4, !dbg !95, !tbaa !75
// LD: Guess
old_cr = cr(0,2);
cr(0,2) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l63_c12
// Check
ASSUME(active[cr(0,2)] == 0);
ASSUME(cr(0,2) >= iw(0,2));
ASSUME(cr(0,2) >= 0);
ASSUME(cr(0,2) >= cdy[0]);
ASSUME(cr(0,2) >= cisb[0]);
ASSUME(cr(0,2) >= cdl[0]);
ASSUME(cr(0,2) >= cl[0]);
// Update
creg_r7 = cr(0,2);
crmax(0,2) = max(crmax(0,2),cr(0,2));
caddr[0] = max(caddr[0],0);
if(cr(0,2) < cw(0,2)) {
r7 = buff(0,2);
ASSUME((!(( (cw(0,2) < 1) && (1 < crmax(0,2)) )))||(sforbid(2,1)> 0));
ASSUME((!(( (cw(0,2) < 2) && (2 < crmax(0,2)) )))||(sforbid(2,2)> 0));
ASSUME((!(( (cw(0,2) < 3) && (3 < crmax(0,2)) )))||(sforbid(2,3)> 0));
ASSUME((!(( (cw(0,2) < 4) && (4 < crmax(0,2)) )))||(sforbid(2,4)> 0));
} else {
if(pw(0,2) != co(2,cr(0,2))) {
ASSUME(cr(0,2) >= old_cr);
}
pw(0,2) = co(2,cr(0,2));
r7 = mem(2,cr(0,2));
}
ASSUME(creturn[0] >= cr(0,2));
// call void @llvm.dbg.value(metadata i32 %7, metadata !125, metadata !DIExpression()), !dbg !129
// %8 = load i32, i32* @atom_2_X1_0, align 4, !dbg !96, !tbaa !75
// LD: Guess
old_cr = cr(0,3);
cr(0,3) = get_rng(0,NCONTEXT-1);// 0 ASSIGN LDCOM _l64_c13
// Check
ASSUME(active[cr(0,3)] == 0);
ASSUME(cr(0,3) >= iw(0,3));
ASSUME(cr(0,3) >= 0);
ASSUME(cr(0,3) >= cdy[0]);
ASSUME(cr(0,3) >= cisb[0]);
ASSUME(cr(0,3) >= cdl[0]);
ASSUME(cr(0,3) >= cl[0]);
// Update
creg_r8 = cr(0,3);
crmax(0,3) = max(crmax(0,3),cr(0,3));
caddr[0] = max(caddr[0],0);
if(cr(0,3) < cw(0,3)) {
r8 = buff(0,3);
ASSUME((!(( (cw(0,3) < 1) && (1 < crmax(0,3)) )))||(sforbid(3,1)> 0));
ASSUME((!(( (cw(0,3) < 2) && (2 < crmax(0,3)) )))||(sforbid(3,2)> 0));
ASSUME((!(( (cw(0,3) < 3) && (3 < crmax(0,3)) )))||(sforbid(3,3)> 0));
ASSUME((!(( (cw(0,3) < 4) && (4 < crmax(0,3)) )))||(sforbid(3,4)> 0));
} else {
if(pw(0,3) != co(3,cr(0,3))) {
ASSUME(cr(0,3) >= old_cr);
}
pw(0,3) = co(3,cr(0,3));
r8 = mem(3,cr(0,3));
}
ASSUME(creturn[0] >= cr(0,3));
// call void @llvm.dbg.value(metadata i32 %8, metadata !126, metadata !DIExpression()), !dbg !129
// %and = and i32 %7, %8, !dbg !97
creg_r9 = max(creg_r7,creg_r8);
r9 = r7 & r8;
// call void @llvm.dbg.value(metadata i32 %and, metadata !127, metadata !DIExpression()), !dbg !129
// %and9 = and i32 %conv8, %and, !dbg !98
creg_r10 = max(creg__r6__2_,creg_r9);
r10 = (r6==2) & r9;
// call void @llvm.dbg.value(metadata i32 %and9, metadata !128, metadata !DIExpression()), !dbg !129
// %cmp10 = icmp eq i32 %and9, 1, !dbg !99
creg__r10__1_ = max(0,creg_r10);
// br i1 %cmp10, label %if.then, label %if.end, !dbg !101
old_cctrl = cctrl[0];
cctrl[0] = get_rng(0,NCONTEXT-1);
ASSUME(cctrl[0] >= old_cctrl);
ASSUME(cctrl[0] >= creg__r10__1_);
if((r10==1)) {
goto T0BLOCK1;
} else {
goto T0BLOCK2;
}
T0BLOCK1:
// call void @__assert_fail(i8* noundef getelementptr inbounds ([2 x i8], [2 x i8]* @.str, i64 0, i64 0), i8* noundef getelementptr inbounds ([126 x i8], [126 x i8]* @.str.1, i64 0, i64 0), i32 noundef 67, i8* noundef getelementptr inbounds ([23 x i8], [23 x i8]* @__PRETTY_FUNCTION__.main, i64 0, i64 0)) #8, !dbg !102
// unreachable, !dbg !102
r11 = 1;
goto T0BLOCK_END;
T0BLOCK2:
// %9 = bitcast i64* %thr2 to i8*, !dbg !105
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %9) #7, !dbg !105
// %10 = bitcast i64* %thr1 to i8*, !dbg !105
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %10) #7, !dbg !105
// %11 = bitcast i64* %thr0 to i8*, !dbg !105
// call void @llvm.lifetime.end.p0i8(i64 8, i8* %11) #7, !dbg !105
// ret i32 0, !dbg !106
ret_thread_0 = 0;
goto T0BLOCK_END;
T0BLOCK_END:
ASSUME(meminit(0,1) == mem(0,0));
ASSUME(coinit(0,1) == co(0,0));
ASSUME(deltainit(0,1) == delta(0,0));
ASSUME(meminit(0,2) == mem(0,1));
ASSUME(coinit(0,2) == co(0,1));
ASSUME(deltainit(0,2) == delta(0,1));
ASSUME(meminit(0,3) == mem(0,2));
ASSUME(coinit(0,3) == co(0,2));
ASSUME(deltainit(0,3) == delta(0,2));
ASSUME(meminit(0,4) == mem(0,3));
ASSUME(coinit(0,4) == co(0,3));
ASSUME(deltainit(0,4) == delta(0,3));
ASSUME(meminit(1,1) == mem(1,0));
ASSUME(coinit(1,1) == co(1,0));
ASSUME(deltainit(1,1) == delta(1,0));
ASSUME(meminit(1,2) == mem(1,1));
ASSUME(coinit(1,2) == co(1,1));
ASSUME(deltainit(1,2) == delta(1,1));
ASSUME(meminit(1,3) == mem(1,2));
ASSUME(coinit(1,3) == co(1,2));
ASSUME(deltainit(1,3) == delta(1,2));
ASSUME(meminit(1,4) == mem(1,3));
ASSUME(coinit(1,4) == co(1,3));
ASSUME(deltainit(1,4) == delta(1,3));
ASSUME(meminit(2,1) == mem(2,0));
ASSUME(coinit(2,1) == co(2,0));
ASSUME(deltainit(2,1) == delta(2,0));
ASSUME(meminit(2,2) == mem(2,1));
ASSUME(coinit(2,2) == co(2,1));
ASSUME(deltainit(2,2) == delta(2,1));
ASSUME(meminit(2,3) == mem(2,2));
ASSUME(coinit(2,3) == co(2,2));
ASSUME(deltainit(2,3) == delta(2,2));
ASSUME(meminit(2,4) == mem(2,3));
ASSUME(coinit(2,4) == co(2,3));
ASSUME(deltainit(2,4) == delta(2,3));
ASSUME(meminit(3,1) == mem(3,0));
ASSUME(coinit(3,1) == co(3,0));
ASSUME(deltainit(3,1) == delta(3,0));
ASSUME(meminit(3,2) == mem(3,1));
ASSUME(coinit(3,2) == co(3,1));
ASSUME(deltainit(3,2) == delta(3,1));
ASSUME(meminit(3,3) == mem(3,2));
ASSUME(coinit(3,3) == co(3,2));
ASSUME(deltainit(3,3) == delta(3,2));
ASSUME(meminit(3,4) == mem(3,3));
ASSUME(coinit(3,4) == co(3,3));
ASSUME(deltainit(3,4) == delta(3,3));
ASSERT(r11== 0);
}
| [
"tuan-phong.ngo@it.uu.se"
] | tuan-phong.ngo@it.uu.se |
b3250ed2bb6e21419077124b127eaaf52ac7415c | 40b46d370ec4c4763627566df36f6d723b7a33be | /Arduino/delay_phase_setter/delay_phase_setter.ino | 45c7ed49116fba6e53ce12399a7fba4b48d5c889 | [] | no_license | dsr373/phase-locked-loops | fdb6e14e9f5711e8e33c3a510f07073dff69f581 | 3e89b8c84de6f9af1f3b6b3d7fac8d5e950342c2 | refs/heads/master | 2021-02-07T11:46:07.742683 | 2018-10-22T20:26:13 | 2018-10-22T20:26:13 | 244,021,483 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,846 | ino | // program that generates two square waves based on the half-period received as a serial port input
// input is in microseconds
// the waves are out of phase by a factor also received as serial input
// this is given in degrees (0 to 360)
// variables
unsigned long t = 125; // wait time
unsigned long phase_diff = 0; // the phase difference in 10^-4 of 180 degrees (i.e. 1e4 -> 180 deg)
String string_read; // value read from serial
unsigned long t_ahead, t_behind; // the time that only
// global constants
const int pin = 13; // the pin to generate the signal on
const int pin2 = 10; // the second pin, which is out of phase
const int pinmask = (1 << (pin-8)); // pin 1 bitmaks
const int pinmask2 = (1 << (pin2-8)); // pin 2 bitmask
const int bitmask = pinmask | pinmask2 ; // the port covers bits from 8 to 13, so that's why minus 8
// the function pointer to use to wait
void (*waitfunc)(unsigned long) = &delay;
void (*cycle_func)() = &pin1_first;
void setup() {
DDRB = bitmask;
Serial.begin(9600);
// noInterrupts(); // for some reason this messes up EVERYTHING
// cli();
}
void loop() {
if(Serial.available()) {
string_read = Serial.readString();
string_read.trim();
Serial.println(String("read: ") + string_read);
parseInput(string_read);
}
// on and off
cycle_func();
}
void parseInput(String received) {
unsigned long value_read = 0;
if(received.startsWith("f")) {
// here setting frequency
value_read = received.substring(1).toInt();
// here set in microseconds and use the us function
if(value_read >= 1 && value_read < 16000) {
t = value_read;
setTimes();
waitfunc = &myDelayMicroseconds;
Serial.println(String("updated period: ") + String(t) + String("us"));
}
// here set in milliseconds and use the ms function
else if(value_read >= 16000 && value_read < 1000000) {
t = value_read / 1000;
setTimes();
waitfunc = &delay;
Serial.println(String("updated period: ") + String(t) + String("ms"));
}
}
else if(received.startsWith("p")) {
// here setting phase
value_read = received.substring(1).toInt();
value_read = value_read % 360;
if(value_read >= 0) {
if(value_read >= 0 && value_read <=180) {
phase_diff = value_read * 10000 / 180;
cycle_func = &pin1_first;
setTimes();
}
else if(value_read > 180 && value_read < 360) {
phase_diff = (360 - value_read) * 10000 / 180;
cycle_func = &pin2_first;
setTimes();
}
Serial.println(String("updated phase diff: ") + String(value_read) + String(" deg"));
}
}
}
inline void setTimes() {
t_ahead = t * phase_diff / 10000;
t_behind = t - t_ahead;
}
inline void pin1_first() {
// this is called if phase_diff is in [0, 180] degrees
PORTB = pinmask; // set pin 1
waitfunc(t_ahead); // wait a fraction of t
PORTB = bitmask; // set both
waitfunc(t_behind); // wait the rest of t
PORTB = pinmask2; // set just the second pin
waitfunc(t_ahead); // wait a fraction of t
PORTB = 0; // reset both
waitfunc(t_behind);
}
inline void pin2_first() {
// this is called if phase_diff is in (180, 360) degrees
PORTB = pinmask2; // set pin 2
waitfunc(t_ahead); // wait a fraction of t
PORTB = bitmask; // set both
waitfunc(t_behind); // wait the rest of t
PORTB = pinmask; // set just pin 1
waitfunc(t_ahead); // wait a fraction of t
PORTB = 0; // reset both
waitfunc(t_behind);
}
inline void myDelayMicroseconds(unsigned long us) {
// this is a terrible hack
// basically the types of delay and delayMicroseconds don't match
// so therefore I need to define this to be able to assign them to the function pointer
delayMicroseconds((unsigned int)us);
}
| [
"seremet.dan@gmail.com"
] | seremet.dan@gmail.com |
0b5fcd14bd885aa815dc516c237ddc73c89c4039 | 1012e393862a4fc9b41dd4236f3924e389e16039 | /src/treelearner/split_info.hpp | 0444dd089d3c7d3551fe17a5b96800053f9512d6 | [
"MIT",
"LicenseRef-scancode-unknown-license-reference",
"Python-2.0"
] | permissive | atksh/mimalloc-lgb | 71ff2e34691d4285f8f295d788a34178885e8b7f | add692a5ef9a91cad0bc78fa18a051d43a8c930e | refs/heads/master | 2022-12-04T10:44:05.855977 | 2020-08-13T19:08:21 | 2020-08-13T19:08:21 | 286,140,190 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 9,777 | hpp | /*!
* Copyright (c) 2016 Microsoft Corporation. All rights reserved.
* Licensed under the MIT License. See LICENSE file in the project root for license information.
*/
#ifndef LIGHTGBM_TREELEARNER_SPLIT_INFO_HPP_
#define LIGHTGBM_TREELEARNER_SPLIT_INFO_HPP_
#include <LightGBM/meta.h>
#include <limits>
#include <cmath>
#include <cstdint>
#include <cstring>
#include <functional>
#include <vector>
#include <mimalloc.h>
namespace LightGBM
{
/*!
* \brief Used to store some information for gain split point
*/
struct SplitInfo
{
public:
/*! \brief Feature index */
int feature = -1;
/*! \brief Split threshold */
uint32_t threshold = 0;
/*! \brief Left number of data after split */
data_size_t left_count = 0;
/*! \brief Right number of data after split */
data_size_t right_count = 0;
int num_cat_threshold = 0;
/*! \brief Left output after split */
double left_output = 0.0;
/*! \brief Right output after split */
double right_output = 0.0;
/*! \brief Split gain */
double gain = kMinScore;
/*! \brief Left sum gradient after split */
double left_sum_gradient = 0;
/*! \brief Left sum hessian after split */
double left_sum_hessian = 0;
/*! \brief Right sum gradient after split */
double right_sum_gradient = 0;
/*! \brief Right sum hessian after split */
double right_sum_hessian = 0;
std::vector<uint32_t, mi_stl_allocator<uint32_t>> cat_threshold;
/*! \brief True if default split is left */
bool default_left = true;
int8_t monotone_type = 0;
inline static int Size(int max_cat_threshold)
{
return 2 * sizeof(int) + sizeof(uint32_t) + sizeof(bool) + sizeof(double) * 7 + sizeof(data_size_t) * 2 + max_cat_threshold * sizeof(uint32_t) + sizeof(int8_t);
}
inline void CopyTo(char *buffer) const
{
std::memcpy(buffer, &feature, sizeof(feature));
buffer += sizeof(feature);
std::memcpy(buffer, &left_count, sizeof(left_count));
buffer += sizeof(left_count);
std::memcpy(buffer, &right_count, sizeof(right_count));
buffer += sizeof(right_count);
std::memcpy(buffer, &gain, sizeof(gain));
buffer += sizeof(gain);
std::memcpy(buffer, &threshold, sizeof(threshold));
buffer += sizeof(threshold);
std::memcpy(buffer, &left_output, sizeof(left_output));
buffer += sizeof(left_output);
std::memcpy(buffer, &right_output, sizeof(right_output));
buffer += sizeof(right_output);
std::memcpy(buffer, &left_sum_gradient, sizeof(left_sum_gradient));
buffer += sizeof(left_sum_gradient);
std::memcpy(buffer, &left_sum_hessian, sizeof(left_sum_hessian));
buffer += sizeof(left_sum_hessian);
std::memcpy(buffer, &right_sum_gradient, sizeof(right_sum_gradient));
buffer += sizeof(right_sum_gradient);
std::memcpy(buffer, &right_sum_hessian, sizeof(right_sum_hessian));
buffer += sizeof(right_sum_hessian);
std::memcpy(buffer, &default_left, sizeof(default_left));
buffer += sizeof(default_left);
std::memcpy(buffer, &monotone_type, sizeof(monotone_type));
buffer += sizeof(monotone_type);
std::memcpy(buffer, &num_cat_threshold, sizeof(num_cat_threshold));
buffer += sizeof(num_cat_threshold);
std::memcpy(buffer, cat_threshold.data(), sizeof(uint32_t) * num_cat_threshold);
}
void CopyFrom(const char *buffer)
{
std::memcpy(&feature, buffer, sizeof(feature));
buffer += sizeof(feature);
std::memcpy(&left_count, buffer, sizeof(left_count));
buffer += sizeof(left_count);
std::memcpy(&right_count, buffer, sizeof(right_count));
buffer += sizeof(right_count);
std::memcpy(&gain, buffer, sizeof(gain));
buffer += sizeof(gain);
std::memcpy(&threshold, buffer, sizeof(threshold));
buffer += sizeof(threshold);
std::memcpy(&left_output, buffer, sizeof(left_output));
buffer += sizeof(left_output);
std::memcpy(&right_output, buffer, sizeof(right_output));
buffer += sizeof(right_output);
std::memcpy(&left_sum_gradient, buffer, sizeof(left_sum_gradient));
buffer += sizeof(left_sum_gradient);
std::memcpy(&left_sum_hessian, buffer, sizeof(left_sum_hessian));
buffer += sizeof(left_sum_hessian);
std::memcpy(&right_sum_gradient, buffer, sizeof(right_sum_gradient));
buffer += sizeof(right_sum_gradient);
std::memcpy(&right_sum_hessian, buffer, sizeof(right_sum_hessian));
buffer += sizeof(right_sum_hessian);
std::memcpy(&default_left, buffer, sizeof(default_left));
buffer += sizeof(default_left);
std::memcpy(&monotone_type, buffer, sizeof(monotone_type));
buffer += sizeof(monotone_type);
std::memcpy(&num_cat_threshold, buffer, sizeof(num_cat_threshold));
buffer += sizeof(num_cat_threshold);
cat_threshold.resize(num_cat_threshold);
std::memcpy(cat_threshold.data(), buffer, sizeof(uint32_t) * num_cat_threshold);
}
inline void Reset()
{
// initialize with -1 and -inf gain
feature = -1;
gain = kMinScore;
}
inline bool operator>(const SplitInfo &si) const
{
double local_gain = this->gain;
double other_gain = si.gain;
// replace nan with -inf
if (local_gain == NAN)
{
local_gain = kMinScore;
}
// replace nan with -inf
if (other_gain == NAN)
{
other_gain = kMinScore;
}
int local_feature = this->feature;
int other_feature = si.feature;
// replace -1 with max int
if (local_feature == -1)
{
local_feature = INT32_MAX;
}
// replace -1 with max int
if (other_feature == -1)
{
other_feature = INT32_MAX;
}
if (local_gain != other_gain)
{
return local_gain > other_gain;
}
else
{
// if same gain, use smaller feature
return local_feature < other_feature;
}
}
inline bool operator==(const SplitInfo &si) const
{
double local_gain = this->gain;
double other_gain = si.gain;
// replace nan with -inf
if (local_gain == NAN)
{
local_gain = kMinScore;
}
// replace nan with -inf
if (other_gain == NAN)
{
other_gain = kMinScore;
}
int local_feature = this->feature;
int other_feature = si.feature;
// replace -1 with max int
if (local_feature == -1)
{
local_feature = INT32_MAX;
}
// replace -1 with max int
if (other_feature == -1)
{
other_feature = INT32_MAX;
}
if (local_gain != other_gain)
{
return local_gain == other_gain;
}
else
{
// if same gain, use smaller feature
return local_feature == other_feature;
}
}
};
struct LightSplitInfo
{
public:
/*! \brief Feature index */
int feature = -1;
/*! \brief Split gain */
double gain = kMinScore;
/*! \brief Left number of data after split */
data_size_t left_count = 0;
/*! \brief Right number of data after split */
data_size_t right_count = 0;
inline void Reset()
{
// initialize with -1 and -inf gain
feature = -1;
gain = kMinScore;
}
void CopyFrom(const SplitInfo &other)
{
feature = other.feature;
gain = other.gain;
left_count = other.left_count;
right_count = other.right_count;
}
void CopyFrom(const char *buffer)
{
std::memcpy(&feature, buffer, sizeof(feature));
buffer += sizeof(feature);
std::memcpy(&left_count, buffer, sizeof(left_count));
buffer += sizeof(left_count);
std::memcpy(&right_count, buffer, sizeof(right_count));
buffer += sizeof(right_count);
std::memcpy(&gain, buffer, sizeof(gain));
buffer += sizeof(gain);
}
inline bool operator>(const LightSplitInfo &si) const
{
double local_gain = this->gain;
double other_gain = si.gain;
// replace nan with -inf
if (local_gain == NAN)
{
local_gain = kMinScore;
}
// replace nan with -inf
if (other_gain == NAN)
{
other_gain = kMinScore;
}
int local_feature = this->feature;
int other_feature = si.feature;
// replace -1 with max int
if (local_feature == -1)
{
local_feature = INT32_MAX;
}
// replace -1 with max int
if (other_feature == -1)
{
other_feature = INT32_MAX;
}
if (local_gain != other_gain)
{
return local_gain > other_gain;
}
else
{
// if same gain, use smaller feature
return local_feature < other_feature;
}
}
inline bool operator==(const LightSplitInfo &si) const
{
double local_gain = this->gain;
double other_gain = si.gain;
// replace nan with -inf
if (local_gain == NAN)
{
local_gain = kMinScore;
}
// replace nan with -inf
if (other_gain == NAN)
{
other_gain = kMinScore;
}
int local_feature = this->feature;
int other_feature = si.feature;
// replace -1 with max int
if (local_feature == -1)
{
local_feature = INT32_MAX;
}
// replace -1 with max int
if (other_feature == -1)
{
other_feature = INT32_MAX;
}
if (local_gain != other_gain)
{
return local_gain == other_gain;
}
else
{
// if same gain, use smaller feature
return local_feature == other_feature;
}
}
};
} // namespace LightGBM
#endif // LightGBM_TREELEARNER_SPLIT_INFO_HPP_
| [
"atksh@example.com"
] | atksh@example.com |
5eeb3b50798620e065e1324393141ed1d77cb556 | cab42dcd40aa393a1571377264a6c95e96230893 | /src/nav/detail/aptdatcache.h | 77c37485e9ffcb6e1349a1b12035fa7eec26e418 | [
"BSD-3-Clause"
] | permissive | samcrow/PPL | a81a1bc36dead2929ec36a3d239aba5cfa141a1f | 4d91c92f80bf988b9772c9c516085aaa6a6535c0 | refs/heads/master | 2020-12-24T10:11:26.579416 | 2015-01-29T04:42:56 | 2015-01-29T04:42:56 | 23,296,961 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,494 | h | // Copyright (c) 2014, Sam Crow samcrow@uw.edu
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted provided that the following conditions are met:
//
// 1. Redistributions of source code must retain the above copyright notice, this
// list of conditions and the following disclaimer.
// 2. Redistributions in binary form must reproduce the above copyright notice,
// this list of conditions and the following disclaimer in the documentation
// and/or other materials provided with the distribution.
//
// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
// ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
// WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
// DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
// ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
// (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
// LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
// ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
// (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
// SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
//
// The views and conclusions contained in the software and documentation are those
// of the authors and should not be interpreted as representing official policies,
// either expressed or implied, of the FreeBSD Project.
#ifndef AIRPORTCACHE_H
#define AIRPORTCACHE_H
#include "../../namespaces.h"
#include "../../util/concurrentmap.h"
#include "../exceptions.h"
#include <fstream>
#include <unordered_map>
#include "aptdatreader.h"
namespace PPLNAMESPACE {
namespace detail {
/**
* @brief The AptDatCache class provides access to
* cached information on airports from an apt.dat file.
*
* Instead of actually caching airport information in memory,
* this class stores the position in the apt.dat file where each
* airport's record begins.
*/
class AptDatCache
{
public:
/**
* @brief Constructor
* @param path The path to the apt.dat file
*/
AptDatCache(const std::string& path);
/**
* @brief Returns the position of the entry in the apt.dat file
* for the airport with the requested code.
*
* Timing information: Before airports are cached, this method
* searches linearly throught the apt.dat file for the requested
* airport. This can take seconds or tens of seconds.
*
* To find every airport in advance, call startFindingAllAirports().
*
* @param code
* @return The position in the file before the beginning of the airport's record
* @throws NoSuchAirportException if no airport with the requested ID exists
* @throws ReadInProgressException if no airport with the required ID is known
* and it could not be searched for because a search is already in progress
*/
std::streamsize findAirport(const std::string& code);
/**
* @brief Returns true if the airport with the provided code
* is cached and easily accessible. Otherwise returns false.
* @param code
* @return
*/
bool hasAirportCached(const std::string& code);
/**
* @brief Starts a procedure to asynchronously search through
* the file and find the airport with the requested code.
*
* If the requested airport is already cached, this method
* does nothing.
*
* @param code The airport code to search for
* @throws ReadInProgressException if an airport data search is
* already taking place
*/
void startFindingAirport(const std::string& code);
/**
* @brief Starts a procedure to asynchronously search through
* the file and cache the locations of all airports.
* @throws ReadInProgressException if an airport data search
* is already taking place
*/
void startFindingAllAirports();
/**
* @brief Returns the path to the apt.dat file that is being used
* @return
*/
std::string path() const;
private:
AptDatReader reader;
/// Maps airport IDs to file positions
ConcurrentMap<std::string, std::streamsize> airportCache;
void findAllAirports();
void findAirport_private(std::string code);
};
}
}
#endif // AIRPORTCACHE_H
| [
"samcrow@uw.edu"
] | samcrow@uw.edu |
c9fcd05aedeae3a3a7858649a599b30307b7c2b3 | 226a1ddbd3342970a7181c1a07b69ba073132204 | /baekjoon/Practice/q_10039.cpp | be6f28de1b7b88fc94f2fffd2e6dad9d8f490331 | [] | no_license | jig6795/Algorithm | ccef8932dfb9b1d9835bb067b5ff702a7791a05f | 8d9d5fadffb7325c3cd9a2b822384d1595ef3c4c | refs/heads/master | 2020-07-22T13:59:29.055552 | 2020-05-12T06:43:14 | 2020-05-12T06:43:14 | 207,226,362 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 384 | cpp | // Q10039
// 평균 점수
// 시간복잡도 - O(n)
#include <iostream>
using namespace std;
int main(void)
{
ios_base::sync_with_stdio(false);
cin.tie(nullptr);
int n;
int sum = 0;
for(int i=0;i<5;i++)
{
cin >> n;
if(n < 40)
{
n = 40;
}
sum += n;
}
cout << sum / 5 << '\n';
return 0;
} | [
"wjd1rb@gmail.com"
] | wjd1rb@gmail.com |
77579790a6a1edb8edf197333590c4916f236717 | eae0f480188b52eb01993dee5eff8cb00d93005d | /agg-2.5/include/agg_rasterizer_outline.h | 91bf119e5ddd420022db50f302bf4c5f13507c08 | [
"MIT",
"GPL-2.0-only",
"GPL-2.0-or-later"
] | permissive | jangko/nimAGG | 49a0675b01ab885497ca7e1fa99cc4fa9f9c9e5d | 0566604c1576517ae25b1d5bc430f896d15bd16f | refs/heads/devel | 2021-01-11T09:26:22.349647 | 2019-05-30T10:08:31 | 2019-05-30T10:08:31 | 76,875,061 | 18 | 0 | MIT | 2019-05-30T09:57:22 | 2016-12-19T15:48:12 | Nim | UTF-8 | C++ | false | false | 4,621 | h | //----------------------------------------------------------------------------
// Anti-Grain Geometry (AGG) - Version 2.5
// A high quality rendering engine for C++
// Copyright (C) 2002-2006 Maxim Shemanarev
// Contact: mcseem@antigrain.com
// mcseemagg@yahoo.com
// http://antigrain.com
//
// AGG is free software; you can redistribute it and/or
// modify it under the terms of the GNU General Public License
// as published by the Free Software Foundation; either version 2
// of the License, or (at your option) any later version.
//
// AGG 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 AGG; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
// MA 02110-1301, USA.
//----------------------------------------------------------------------------
#ifndef AGG_RASTERIZER_OUTLINE_INCLUDED
#define AGG_RASTERIZER_OUTLINE_INCLUDED
#include "agg_basics.h"
namespace agg
{
//======================================================rasterizer_outline
template<class Renderer> class rasterizer_outline
{
public:
explicit rasterizer_outline(Renderer& ren) :
m_ren(&ren),
m_start_x(0),
m_start_y(0),
m_vertices(0)
{}
void attach(Renderer& ren) { m_ren = &ren; }
//--------------------------------------------------------------------
void move_to(int x, int y)
{
m_vertices = 1;
m_ren->move_to(m_start_x = x, m_start_y = y);
}
//--------------------------------------------------------------------
void line_to(int x, int y)
{
++m_vertices;
m_ren->line_to(x, y);
}
//--------------------------------------------------------------------
void move_to_d(double x, double y)
{
move_to(m_ren->coord(x), m_ren->coord(y));
}
//--------------------------------------------------------------------
void line_to_d(double x, double y)
{
line_to(m_ren->coord(x), m_ren->coord(y));
}
//--------------------------------------------------------------------
void close()
{
if(m_vertices > 2)
{
line_to(m_start_x, m_start_y);
}
m_vertices = 0;
}
//--------------------------------------------------------------------
void add_vertex(double x, double y, unsigned cmd)
{
if(is_move_to(cmd))
{
move_to_d(x, y);
}
else
{
if(is_end_poly(cmd))
{
if(is_closed(cmd)) close();
}
else
{
line_to_d(x, y);
}
}
}
//--------------------------------------------------------------------
template<class VertexSource>
void add_path(VertexSource& vs, unsigned path_id=0)
{
double x;
double y;
unsigned cmd;
vs.rewind(path_id);
while(!is_stop(cmd = vs.vertex(&x, &y)))
{
add_vertex(x, y, cmd);
}
}
//--------------------------------------------------------------------
template<class VertexSource, class ColorStorage, class PathId>
void render_all_paths(VertexSource& vs,
const ColorStorage& colors,
const PathId& path_id,
unsigned num_paths)
{
for(unsigned i = 0; i < num_paths; i++)
{
m_ren->line_color(colors[i]);
add_path(vs, path_id[i]);
}
}
//--------------------------------------------------------------------
template<class Ctrl> void render_ctrl(Ctrl& c)
{
unsigned i;
for(i = 0; i < c.num_paths(); i++)
{
m_ren->line_color(c.color(i));
add_path(c, i);
}
}
private:
Renderer* m_ren;
int m_start_x;
int m_start_y;
unsigned m_vertices;
};
}
#endif
| [
"jangko128@gmail.com"
] | jangko128@gmail.com |
6402a29aac376517d7d099b363935c872e17cd64 | 85ba56df8b459a2e3c4c7e3d66bf4d96c7f8c9b1 | /LinkedLIsts/Interviewbit/removeDuplicatesII.cpp | 8382b68b42e8384871705f69450c2f9e7baa250d | [] | no_license | raghavaggarwal99/Competitive | 80c29213a4f81b39a01d5b2b5e70ab22ceb9738c | fa8a472eddf612f969ec67104110bcdfe03332c9 | refs/heads/master | 2021-07-10T09:31:01.666951 | 2020-09-26T17:03:40 | 2020-09-26T17:03:40 | 203,055,409 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 779 | cpp | /**
* Definition for singly-linked list.
* struct ListNode {
* int val;
* ListNode *next;
* ListNode(int x) : val(x), next(NULL) {}
* };
*/
ListNode* Solution::deleteDuplicates(ListNode* A) {
// DO NOT write int main() function
if ((A==NULL) || (A->next == NULL) ){return A;}
ListNode* pre = new ListNode(0);
pre->next = A;
A =pre;
ListNode* p = A;
while(p->next!=NULL){
ListNode *p2 = p->next;
while ((p2->next!=NULL)&&(p2->val==p2->next->val)){
p2=p2->next;
}
if (p2!=p->next){
p->next=p2->next;
}else{
p=p->next;
}
}
return A->next;
}
| [
"ragha170103048@iitg.ac.in"
] | ragha170103048@iitg.ac.in |
99f1e93321c3f247532d3c5d0b7481a91e119952 | d1ad68da0d7d3a71c2d43d297d6fd3cffbbf75c2 | /atcoder/arc05/b.cpp | a5caba980681d3a7169691e4e28af6a2a3beb335 | [] | no_license | hamko/procon | 2a0a685b88a69951be7a9217dd32955f9500df57 | a822f8089a3063a158d47ea48c54aca89934f855 | refs/heads/master | 2021-01-17T00:00:10.915298 | 2020-02-24T06:24:33 | 2020-02-24T06:24:33 | 55,990,248 | 7 | 1 | null | 2020-02-24T06:24:34 | 2016-04-11T16:49:50 | C++ | UTF-8 | C++ | false | false | 1,490 | cpp | #include <bits/stdc++.h>
using namespace std;
#define rep(i,n) for(int i = 0; i < n; i++)
#define pb push_back
#define all(x) x.begin(), x.end()
template<class T1, class T2> bool chmin(T1 &a, T2 b) { return b < a && (a = b, true); }
template<class T1, class T2> bool chmax(T1 &a, T2 b) { return a < b && (a = b, true); }
template <typename T, typename U> ostream &operator<<(ostream &o, const pair<T, U> &v) { o << "(" << v.first << ", " << v.second << ")"; return o; }
template <typename T> ostream &operator<<(ostream &o, const vector<T> &v) { if (!v.empty()) { o << '['; copy(v.begin(), v.end(), ostream_iterator<T>(o, ", ")); o << "\b\b]"; } return o; }
using ll = long long; using ld = long double; using vll = vector<ll>; using vi = vector<int>;
typedef pair<ll, ll> P;
static const double EPS = 1e-14;
static const long long INF = 1e18;
#define MAX_N 100005
ll si, sj;
string d;
ll di, dj;
vector<string> m;
map<P, ll> memo;
int main(void) {
cin.tie(0); ios::sync_with_stdio(false);
cin >> sj >> si; sj--; si--;
cin >> d;
rep(i, d.length()) {
if (d[i] == 'L') dj = -1;
if (d[i] == 'R') dj = 1;
if (d[i] == 'U') di = -1;
if (d[i] == 'D') di = 1;
}
m.resize(9); rep(i, 9) cin >> m[i];
rep(i, 4) {
if (si+di>=9) di*=-1;
if (si+di<0) di*=-1;
if (sj+dj>=9) dj*=-1;
if (sj+dj<0) dj*=-1;
cout << m[si][sj];
si+=di;
sj+=dj;
}
cout << endl;
return 0;
}
| [
"wakataberyo@gmail.com"
] | wakataberyo@gmail.com |
69a4392a723233158027d14067d46d13440e853e | 4bc0a1cfce366ee3412a2b80eab5a2e73688666a | /OOPLHW2/MoneySimulator/Money.cpp | 10cd44424f350067a6fcfa2890cfafa131631929 | [] | no_license | aquther/OOP-Assignments | 8152accbd7ffb10534453f0d5af1b80b24e39d7d | 960d51a6b3888f6704635345c28a8c3d4029098e | refs/heads/master | 2021-01-10T13:53:06.859485 | 2016-04-17T12:03:23 | 2016-04-17T12:03:23 | 52,276,254 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,900 | cpp | #include "Money.h"
#include <iostream>
Money::Money(int a, int b):levove(a),stotinki(b) {}
Money::~Money(){}
int Money::SetLev(int a)
{
levove = a;
return 0;
}
int Money::SetStotinki(int a)
{
stotinki = a;
return 0;
}
int Money::GetLev()const
{
return levove;
}
int Money::GetStotinki()const
{
return stotinki;
}
int Money::Read()
{
std::cout << "Enter amount of leva : ";
std::cin >> levove;
std::cout << "Enter amout of stotinki : ";
std::cin >> stotinki;
if (stotinki >= 100)
{
levove += stotinki / 100;
stotinki = stotinki - (stotinki / 100) * 100;
}
return 0;
}
int Money::Print()
{
std::cout << levove << " leva and " << stotinki << " stotinki.\n";
return 0;
}
Money Money::operator+(const Money&a)const
{
return Money(this->GetLev() + a.GetLev(),this->GetStotinki()+a.GetStotinki());
}
Money Money::operator-(const Money&a)const
{
int newlev;
int newstot;
if ((levove<a.levove)||((levove == a.levove) && (stotinki < a.stotinki)))
{
std::cout << "First amount is less than the second one!\n";
}
else if ((levove == a.levove) && (stotinki >= a.stotinki))
{
return Money(0, stotinki - a.stotinki);
}
else {
if (stotinki<a.stotinki)
{
return Money(levove-a.levove-1, 100 + stotinki-a.stotinki);
}
else return Money(levove - a.levove, stotinki - a.stotinki);
}
}
bool Money::operator>(const Money&a)const
{
if(levove!=a.GetLev())
return levove>a.levove;
else return stotinki > a.stotinki;
}
bool Money::operator<(const Money&a)const {
if (levove != a.GetLev())
return levove<a.levove;
else return stotinki < a.stotinki;
}
std::ostream& operator<<(std::ostream&out, const Money&a)
{
out << a.GetLev() << " leva and " << a.GetStotinki() << " stotinki. \n";
return out;
}
Money operator%(double n, Money& a)
{
double pari = (a.levove + a.stotinki / 100.0)*(n/100);
return Money((int)pari, (pari - (int)pari)*100);
} | [
"aquther@abv.bg"
] | aquther@abv.bg |
5e82d432c27b96c390e104e8aedd8962f2a8fb22 | 1ec55de30cbb2abdbaed005bc756b37eafcbd467 | /Nacro/SDK/FN_ToiletFactory_Frame_01_classes.hpp | 12c23edfd9bb9d5ff871e55c17593cb6abb78157 | [
"BSD-2-Clause"
] | permissive | GDBOI101/Nacro | 6e91dc63af27eaddd299b25351c82e4729013b0b | eebabf662bbce6d5af41820ea0342d3567a0aecc | refs/heads/master | 2023-07-01T04:55:08.740931 | 2021-08-09T13:52:43 | 2021-08-09T13:52:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 976 | hpp | #pragma once
// Fortnite (1.8) SDK
#ifdef _MSC_VER
#pragma pack(push, 0x8)
#endif
namespace SDK
{
//---------------------------------------------------------------------------
//Classes
//---------------------------------------------------------------------------
// BlueprintGeneratedClass ToiletFactory_Frame_01.ToiletFactory_Frame_01_C
// 0x0008 (0x10D8 - 0x10D0)
class AToiletFactory_Frame_01_C : public ABuildingContainer
{
public:
struct FPointerToUberGraphFrame UberGraphFrame; // 0x10D0(0x0008) (Transient, DuplicateTransient)
static UClass* StaticClass()
{
static auto ptr = UObject::FindClass("BlueprintGeneratedClass ToiletFactory_Frame_01.ToiletFactory_Frame_01_C");
return ptr;
}
void UserConstructionScript();
void OnLoot();
void OnLootRepeat();
void OnBeginSearch();
void ExecuteUbergraph_ToiletFactory_Frame_01(int EntryPoint);
};
}
#ifdef _MSC_VER
#pragma pack(pop)
#endif
| [
"68667854+Pakchunk@users.noreply.github.com"
] | 68667854+Pakchunk@users.noreply.github.com |
087c850e6ca40c55c48c9d3bcba2a05312529bf8 | 3448a43cf0635866b25e5d513dd60fb003f47e29 | /src/xrGame/Script_Binder_Camp.h | 1a2094cbc1ae3cea3b121f75650bb46fb29c929b | [
"LicenseRef-scancode-warranty-disclaimer",
"BSD-2-Clause"
] | permissive | xrLil-Batya/cordisproject | 49632acc5e68bea9847d001d82fb049703d223c2 | 24275a382fec62a4e58d11579bf497b894f220ba | refs/heads/master | 2023-03-19T01:17:25.170059 | 2020-11-17T14:22:06 | 2020-11-17T14:22:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 557 | h | #pragma once
namespace Cordis
{
namespace Scripts
{
class Script_Binder_Camp : public CScriptBinderObject
{
using inherited = CScriptBinderObject;
public:
Script_Binder_Camp(void) = delete;
Script_Binder_Camp(CScriptGameObject* const p_client_object);
~Script_Binder_Camp(void);
virtual void reinit();
virtual bool net_Spawn(SpawnType DC);
virtual void net_Destroy();
virtual void shedule_Update(u32 time_delta);
virtual bool net_SaveRelevant();
};
}
}
| [
"phantom1020@yandex.ru"
] | phantom1020@yandex.ru |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.