blob_id stringlengths 40 40 | directory_id stringlengths 40 40 | path stringlengths 4 201 | content_id stringlengths 40 40 | detected_licenses listlengths 0 85 | license_type stringclasses 2
values | repo_name stringlengths 7 100 | snapshot_id stringlengths 40 40 | revision_id stringlengths 40 40 | branch_name stringclasses 260
values | visit_date timestamp[us] | revision_date timestamp[us] | committer_date timestamp[us] | github_id int64 11.4k 681M ⌀ | star_events_count int64 0 209k | fork_events_count int64 0 110k | gha_license_id stringclasses 17
values | gha_event_created_at timestamp[us] | gha_created_at timestamp[us] | gha_language stringclasses 80
values | src_encoding stringclasses 28
values | language stringclasses 1
value | is_vendor bool 1
class | is_generated bool 2
classes | length_bytes int64 8 9.86M | extension stringclasses 52
values | content stringlengths 8 9.86M | authors listlengths 1 1 | author stringlengths 0 119 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
16015f8e755e9348dbd89265f84a84632a2406ea | 9c80234bc06f81f2f1b3d603a25c4ce74d22d5aa | /many_particle/openmp/energies.cpp | 98e52692f0d2f8674dd0814c4633e08b0fdab7d9 | [] | no_license | aFuerst/tensorflow-simulations | cff88e445691da6d86bde99954a75357a5c18a61 | 178ff14f0906373c9663f07d63cf14127b4361d0 | refs/heads/master | 2022-08-24T11:12:07.564034 | 2022-08-23T14:50:45 | 2022-08-23T14:50:45 | 218,312,500 | 0 | 1 | null | 2022-08-23T14:50:52 | 2019-10-29T14:54:10 | Python | UTF-8 | C++ | false | false | 2,205 | cpp | // This function has the potential energy evaluations
// For now, we have LJ interaction potential between particles
using namespace std;
#include <vector>
#include "particle.h"
#include "simulationbox.h"
double update_energies(vector<PARTICLE>& ljatom, SIMULATIONBOX& box, double dcut)
{
// potential energy
// this is our workload
vector<double> lj_atom_atom (ljatom.size(),0.0);
unsigned int i;
// what you need to compute energy
// recall that we are working with a truncated-shifted LJ potential
// while the shift does not matter in the force calculation (why?), it matters here, hence the energy_shift calculation below
// compute the energy shift term
// energy is computed as pair-wise sums
#pragma omp parallel for schedule(dynamic) private(i)
for (i = 0; i < ljatom.size(); i++)
{
double uljpair = 0.0;
for (unsigned int j = 0; j < ljatom.size(); j++)
{
if (j == i) continue;
VECTOR3D r_vec = ljatom[i].posvec - ljatom[j].posvec;
double r, r2, r6, d, d2, d6;
if (r_vec.x > box.lx/2) r_vec.x -= box.lx;
if (r_vec.x < -box.lx/2) r_vec.x += box.lx;
if (r_vec.y > box.ly/2) r_vec.y -= box.ly;
if (r_vec.y < -box.ly/2) r_vec.y += box.ly;
if (r_vec.z > box.lz/2) r_vec.z -= box.lz;
if (r_vec.z < -box.lz/2) r_vec.z += box.lz;
double elj = 1.0;
double dcut2 = dcut * dcut;
double dcut6 = dcut2 * dcut2 * dcut2;
double dcut12 = dcut6 * dcut6;
double energy_shift = 4*elj*(1/dcut12 - 1/dcut6);
r = r_vec.Magnitude();
d = 1; // note: reduced units, all particles have the same diameter
if (r < dcut * d)
{
r2 = r * r;
r6 = r2 * r2 * r2;
d2 = d * d;
d6 = d2 * d2 * d2;
uljpair = uljpair + 4 * elj * (d6 / r6) * ( ( d6 / r6 ) - 1 ) - energy_shift;
}
else
uljpair = uljpair + 0.0;
}
lj_atom_atom[i] = uljpair;
}
double total_lj_atom_atom = 0;
for (unsigned int i = 0; i < ljatom.size(); i++)
total_lj_atom_atom += lj_atom_atom[i];
total_lj_atom_atom = 0.5 * total_lj_atom_atom;
// factor of half for double counting -- does that make sense?
return total_lj_atom_atom;
}
| [
"fuersta.2013@gmail.com"
] | fuersta.2013@gmail.com |
8f30b33c2f117184b74d35d845244ebe8c7fa2d8 | 61d720c020b08faa58a1e6c82aef3e75dc58dc10 | /Pointers/src/Pointers_7.cpp | c4a6da78af3cbbc7f25a4cf788fae02d1769c54b | [] | no_license | VinothVB/CPP | e2186b8b9d643607dd7b8de261ff54f6759e7b3c | e8a2f33a8ef9e35abb3060c6da9a73d7301789e9 | refs/heads/master | 2022-12-30T22:49:54.866457 | 2020-10-24T06:25:53 | 2020-10-24T06:25:53 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,060 | cpp |
/*
Understanding the pointers concept
*/
#include <iostream>
void func(int** c)
{
std::cout << "Address of c :: " << &c << std::endl;
std::cout << "Value of c is the address of b :: " << c << std::endl << std::endl;
std::cout << "value at address of b :: " << *c << std::endl;
/*
so if you see here *c gives me the value at the address (the variable c was holding)
which is nothing but the address of another variable(this is still a value for a paritcular
address that is stored on the memory to acces)
now if you want to find the address of this value on the memory block you need to reference it
and for referencing it we user & operator.
*/
std::cout << "&(*c) :: " << &(*c) << std::endl;
std::cout << "value at the address of a:: " << **c << std::endl;
}
int main()
{
int a = 10;
int* b = &a;
std::cout << "Address of a :: " << &a << std::endl << std::endl;
std::cout << "Address of b :: 1 :: " << &b << std::endl;
std::cout << "Value of b is the address of a:: 2 :: " << b << std::endl;
func(&b);
return 0;
} | [
"49783910+shreyjp5788@users.noreply.github.com"
] | 49783910+shreyjp5788@users.noreply.github.com |
2563a4d60a03729369d3a0ecf22ff4294a995a4c | 2640ba3385677fe7de5508029cc507174ab69549 | /inc/gr.hpp | dd0936641c762b87253bc3b9fe91c9dae38e4527 | [] | no_license | zoghbi-a/gr | abce39ab563bef7be0df17921e9ba3ad7e279dc8 | de0c3463dfc9abedbd2754953ecc97dfc734fce6 | refs/heads/master | 2023-06-20T15:12:50.614989 | 2023-05-30T19:00:40 | 2023-05-30T19:00:40 | 188,257,836 | 0 | 0 | null | 2023-05-30T19:00:41 | 2019-05-23T15:10:54 | C++ | UTF-8 | C++ | false | false | 225 | hpp | /*
* gr.hpp
*
* Created on: Nov 18, 2014
* Author: abzoghbi
*/
#ifndef INC_GR_HPP_
#define INC_GR_HPP_
#include "flash.hpp"
#include "disk.hpp"
#include "input.hpp"
void print_usage();
#endif /* INC_GR_HPP_ */
| [
"abzoghbi@umich.edu"
] | abzoghbi@umich.edu |
8657487e1463d1ba5ae4bac9d42500414ef449dc | 856d2aced5e15909fe7d68a83d5977beee385527 | /07-recursive-circus/main.cpp | 29b010db475e9285368cd7268a22e97f7f076c69 | [] | no_license | djrollins/AdventOfCode2017 | c13b51a3c1f9cffc456b5e9297983250c0b8c610 | 54c403d51d1716f38327fe9c4c02c8460cb775cf | refs/heads/master | 2021-08-31T19:32:54.933158 | 2017-12-22T15:10:55 | 2017-12-22T15:10:55 | 113,070,996 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,473 | cpp | #include <algorithm>
#include <iostream>
#include <iterator>
#include <numeric>
#include <regex>
#include <set>
#include <string>
#include <unordered_map>
struct program
{
std::string name;
int weight;
std::vector<std::string> children;
};
using program_cache = std::map<std::string, program>;
using weight_cache = std::map<std::string, int>;
static int total_weight(
program const &program,
program_cache const &programs,
weight_cache &weights)
{
if (auto found = weights.find(program.name); found != std::end(weights))
return found->second;
auto &weight = weights[program.name];
weight = std::accumulate(
std::begin(program.children), std::end(program.children), program.weight,
[&ps=programs, &ws=weights](auto w, auto const &n) {
return w + total_weight(ps.at(n), ps, ws);
});
return weight;
}
int main()
{
std::regex regex{R"(\w+)"};
std::string buffer;
std::vector<std::string> vec;
program_cache programs;
std::set<std::string> left;
std::set<std::string> right;
while (std::getline(std::cin, buffer)) {
if (!buffer.size()) continue;
std::copy(
std::sregex_token_iterator(buffer.begin(), buffer.end(), regex, 0),
std::sregex_token_iterator(),
std::back_inserter(vec));
program prog{vec[0], std::atoi(vec[1].c_str()), {vec.begin() + 2, vec.end()}};
auto [iter, _] = programs.emplace(vec[0], std::move(prog));
left.insert(iter->first);
right.insert(std::begin(iter->second.children), std::end(iter->second.children));
vec.clear();
}
std::string root;
// ptr to root as I know ther is only one.
std::set_difference(left.begin(), left.end(), right.begin(), right.end(), &root);
std::cout << "root: " << root << '\n';
weight_cache weights;
auto unbalanced = std::find_if(std::begin(programs), std::end(programs),
[&programs, &weights](auto const &entry) {
auto const &kids = entry.second.children;
return !std::equal(std::begin(kids), std::end(kids), std::rbegin(kids),
[&ps=programs, &ws=weights](auto const &lhs, auto const &rhs) {
return total_weight(ps.at(lhs), ps, ws)
== total_weight(ps.at(rhs), ps, ws);
});
});
std::cout << "unbalanced: " << unbalanced->first << '\n';
std::cout << "children: " << '\n';
for (auto const &child_name : unbalanced->second.children) {
auto const &child = programs.at(child_name);
std::cout << '\t' << child.name << ": (" << child.weight << ") "
<< total_weight(child, programs, weights) << '\n';
}
}
| [
"daniel@djrollins.com"
] | daniel@djrollins.com |
e6a0e59ad216994cc22192ad87da700e699f65cd | 7b88ae96aeb758858cd0df1c1c50b6f0212f2ac9 | /include/Desktop.h | 194c1af1eb577f3fcb9aec454f0ff55b1fee3619 | [] | no_license | MartinUbl/SpringMeadow | 23056b9ae1e3c1f7dce17f222e06b76cca393efe | 172bd9056dd7d2a834f62c0c867f59d9150f548f | refs/heads/master | 2020-05-17T03:15:40.849666 | 2013-11-10T01:56:29 | 2013-11-10T01:56:29 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,057 | h | #ifndef SM_DESKTOP_H
#define SM_DESKTOP_H
#include <Singleton.h>
#include <Window.h>
#define MAX_WINDOW_HANDLES 50000
#define FOREGROUND_DRAW_POSITION 1
#define ALWAYS_ON_TOP_DRAW_POSITION 0
enum SystemFonts
{
SYSFONT_WINDOW_TITLE = 0,
SYSFONT_WINDOW_TEXT = 1,
MAX_SYSFONT
};
class Desktop
{
public:
Desktop();
~Desktop();
void Init();
void MouseEvent(bool left, bool press);
void MouseMove();
int32 RegisterWindow(SMWindow* target);
void UnregisterWindow(int32 handle, SMWindow* target);
void SetForegroundWindow(int32 handle);
SMWindow* GetWindow(int32 handle);
int32 GetFontID(SystemFonts fontpos) { return m_systemFonts[fontpos]; };
void Draw();
private:
std::vector<SMWindow*> m_windowHandles;
int32 m_foregroundWindow;
int32 m_systemFonts[MAX_SYSFONT];
};
#define sDesktop Singleton<Desktop>::getInstance()
#define FONT(a) sDesktop->GetFontID(a)
#endif
| [
"cmaranec@seznam.cz"
] | cmaranec@seznam.cz |
fd3a5d733d42994062a75a680211f100b461f797 | 71845d6caf989453e3f5453739ea5538de163de3 | /google-perftools-1.10/src/windows/port.h | d724c0689384b942dd2c02b111c394b77665acd2 | [
"BSD-3-Clause"
] | permissive | bcui6611/google-perftools-1.10 | 623e65ebab508beb8b5097d23a43696406d82867 | a782312a602bb0e8dd418b13f7cad8849736d8dd | refs/heads/master | 2016-08-04T21:51:16.901725 | 2012-02-10T18:26:25 | 2012-02-10T18:26:25 | 3,337,562 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 15,614 | h | /* Copyright (c) 2007, Google Inc.
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are
* met:
*
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above
* copyright notice, this list of conditions and the following disclaimer
* in the documentation and/or other materials provided with the
* distribution.
* * Neither the name of Google Inc. nor the names of its
* contributors may be used to endorse or promote products derived from
* this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
* OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
* SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
* LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
* DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
* THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
* (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* ---
* Author: Craig Silverstein
*
* These are some portability typedefs and defines to make it a bit
* easier to compile this code under VC++.
*
* Several of these are taken from glib:
* http://developer.gnome.org/doc/API/glib/glib-windows-compatability-functions.html
*/
#ifndef GOOGLE_BASE_WINDOWS_H_
#define GOOGLE_BASE_WINDOWS_H_
/* You should never include this file directly, but always include it
from either config.h (MSVC) or mingw.h (MinGW/msys). */
#if !defined(GOOGLE_PERFTOOLS_WINDOWS_CONFIG_H_) && \
!defined(GOOGLE_PERFTOOLS_WINDOWS_MINGW_H_)
# error "port.h should only be included from config.h or mingw.h"
#endif
#ifdef _WIN32
#ifndef WIN32_LEAN_AND_MEAN
#define WIN32_LEAN_AND_MEAN /* We always want minimal includes */
#endif
#include <windows.h>
#include <io.h> /* because we so often use open/close/etc */
#include <direct.h> /* for _getcwd */
#include <process.h> /* for _getpid */
#include <limits.h> /* for PATH_MAX */
#include <stdarg.h> /* for va_list */
#include <stdio.h> /* need this to override stdio's (v)snprintf */
#include <sys/types.h> /* for _off_t */
#include <assert.h>
#include <stdlib.h> /* for rand, srand, _strtoxxx */
#include <time.h> /* for time */
/*
* 4018: signed/unsigned mismatch is common (and ok for signed_i < unsigned_i)
* 4244: otherwise we get problems when subtracting two size_t's to an int
* 4288: VC++7 gets confused when a var is defined in a loop and then after it
* 4267: too many false positives for "conversion gives possible data loss"
* 4290: it's ok windows ignores the "throw" directive
* 4996: Yes, we're ok using "unsafe" functions like vsnprintf and getenv()
* 4146: internal_logging.cc intentionally negates an unsigned value
*/
#ifdef _MSC_VER
#pragma warning(disable:4018 4244 4288 4267 4290 4996 4146)
#endif
#ifndef __cplusplus
/* MSVC does not support C99 */
# if !defined(__STDC_VERSION__) || __STDC_VERSION__ < 199901L
# ifdef _MSC_VER
# define inline __inline
# else
# define inline static
# endif
# endif
#endif
#ifdef __cplusplus
# define EXTERN_C extern "C"
#else
# define EXTERN_C extern
#endif
/* ----------------------------------- BASIC TYPES */
#ifndef HAVE_STDINT_H
#ifndef HAVE___INT64 /* we need to have all the __intX names */
# error Do not know how to set up type aliases. Edit port.h for your system.
#endif
typedef __int8 int8_t;
typedef __int16 int16_t;
typedef __int32 int32_t;
typedef __int64 int64_t;
typedef unsigned __int8 uint8_t;
typedef unsigned __int16 uint16_t;
typedef unsigned __int32 uint32_t;
typedef unsigned __int64 uint64_t;
#endif /* #ifndef HAVE_STDINT_H */
/* I guess MSVC's <types.h> doesn't include ssize_t by default? */
#ifdef _MSC_VER
typedef intptr_t ssize_t;
#endif
/* ----------------------------------- THREADS */
#ifndef HAVE_PTHREAD /* not true for MSVC, but may be true for MSYS */
typedef DWORD pthread_t;
typedef DWORD pthread_key_t;
typedef LONG pthread_once_t;
enum { PTHREAD_ONCE_INIT = 0 }; /* important that this be 0! for SpinLock */
inline pthread_t pthread_self(void) {
return GetCurrentThreadId();
}
#ifdef __cplusplus
inline bool pthread_equal(pthread_t left, pthread_t right) {
return left == right;
}
/* This replaces maybe_threads.{h,cc} */
EXTERN_C pthread_key_t PthreadKeyCreate(void (*destr_fn)(void*)); /* port.cc */
inline int perftools_pthread_key_create(pthread_key_t *pkey,
void (*destructor)(void*)) {
pthread_key_t key = PthreadKeyCreate(destructor);
if (key != TLS_OUT_OF_INDEXES) {
*(pkey) = key;
return 0;
} else {
return GetLastError();
}
}
inline void* perftools_pthread_getspecific(DWORD key) {
DWORD err = GetLastError();
void* rv = TlsGetValue(key);
if (err) SetLastError(err);
return rv;
}
inline int perftools_pthread_setspecific(pthread_key_t key, const void *value) {
if (TlsSetValue(key, (LPVOID)value))
return 0;
else
return GetLastError();
}
EXTERN_C int perftools_pthread_once(pthread_once_t *once_control,
void (*init_routine)(void));
#endif /* __cplusplus */
#endif /* HAVE_PTHREAD */
inline void sched_yield(void) {
Sleep(0);
}
/*
* __declspec(thread) isn't usable in a dll opened via LoadLibrary().
* But it doesn't work to LoadLibrary() us anyway, because of all the
* things we need to do before main()! So this kind of TLS is safe for us.
*/
#define __thread __declspec(thread)
/*
* This code is obsolete, but I keep it around in case we are ever in
* an environment where we can't or don't want to use google spinlocks
* (from base/spinlock.{h,cc}). In that case, uncommenting this out,
* and removing spinlock.cc from the build, should be enough to revert
* back to using native spinlocks.
*/
#if 0
// Windows uses a spinlock internally for its mutexes, making our life easy!
// However, the Windows spinlock must always be initialized, making life hard,
// since we want LINKER_INITIALIZED. We work around this by having the
// linker initialize a bool to 0, and check that before accessing the mutex.
// This replaces spinlock.{h,cc}, and all the stuff it depends on (atomicops)
#ifdef __cplusplus
class SpinLock {
public:
SpinLock() : initialize_token_(PTHREAD_ONCE_INIT) {}
// Used for global SpinLock vars (see base/spinlock.h for more details).
enum StaticInitializer { LINKER_INITIALIZED };
explicit SpinLock(StaticInitializer) : initialize_token_(PTHREAD_ONCE_INIT) {
perftools_pthread_once(&initialize_token_, InitializeMutex);
}
// It's important SpinLock not have a destructor: otherwise we run
// into problems when the main thread has exited, but other threads
// are still running and try to access a main-thread spinlock. This
// means we leak mutex_ (we should call DeleteCriticalSection()
// here). However, I've verified that all SpinLocks used in
// perftools have program-long scope anyway, so the leak is
// perfectly fine. But be aware of this for the future!
void Lock() {
// You'd thionk this would be unnecessary, since we call
// InitializeMutex() in our constructor. But sometimes Lock() can
// be called before our constructor is! This can only happen in
// global constructors, when this is a global. If we live in
// bar.cc, and some global constructor in foo.cc calls a routine
// in bar.cc that calls this->Lock(), then Lock() may well run
// before our global constructor does. To protect against that,
// we do this check. For SpinLock objects created after main()
// has started, this pthread_once call will always be a noop.
perftools_pthread_once(&initialize_token_, InitializeMutex);
EnterCriticalSection(&mutex_);
}
void Unlock() {
LeaveCriticalSection(&mutex_);
}
// Used in assertion checks: assert(lock.IsHeld()) (see base/spinlock.h).
inline bool IsHeld() const {
// This works, but probes undocumented internals, so I've commented it out.
// c.f. http://msdn.microsoft.com/msdnmag/issues/03/12/CriticalSections/
//return mutex_.LockCount>=0 && mutex_.OwningThread==GetCurrentThreadId();
return true;
}
private:
void InitializeMutex() { InitializeCriticalSection(&mutex_); }
pthread_once_t initialize_token_;
CRITICAL_SECTION mutex_;
};
class SpinLockHolder { // Acquires a spinlock for as long as the scope lasts
private:
SpinLock* lock_;
public:
inline explicit SpinLockHolder(SpinLock* l) : lock_(l) { l->Lock(); }
inline ~SpinLockHolder() { lock_->Unlock(); }
};
#endif // #ifdef __cplusplus
// This keeps us from using base/spinlock.h's implementation of SpinLock.
#define BASE_SPINLOCK_H_ 1
#endif /* #if 0 */
/* ----------------------------------- MMAP and other memory allocation */
#ifndef HAVE_MMAP /* not true for MSVC, but may be true for msys */
#define MAP_FAILED 0
#define MREMAP_FIXED 2 /* the value in linux, though it doesn't really matter */
/* These, when combined with the mmap invariants below, yield the proper action */
#define PROT_READ PAGE_READWRITE
#define PROT_WRITE PAGE_READWRITE
#define MAP_ANONYMOUS MEM_RESERVE
#define MAP_PRIVATE MEM_COMMIT
#define MAP_SHARED MEM_RESERVE /* value of this #define is 100% arbitrary */
#if __STDC__ && !defined(__MINGW32__)
typedef _off_t off_t;
#endif
/* VirtualAlloc only replaces for mmap when certain invariants are kept. */
inline void *mmap(void *addr, size_t length, int prot, int flags,
int fd, off_t offset) {
if (addr == NULL && fd == -1 && offset == 0 &&
prot == (PROT_READ|PROT_WRITE) && flags == (MAP_PRIVATE|MAP_ANONYMOUS)) {
return VirtualAlloc(0, length, MEM_RESERVE | MEM_COMMIT, PAGE_READWRITE);
} else {
return NULL;
}
}
inline int munmap(void *addr, size_t length) {
return VirtualFree(addr, 0, MEM_RELEASE) ? 0 : -1;
}
#endif /* HAVE_MMAP */
/* We could maybe use VirtualAlloc for sbrk as well, but no need */
inline void *sbrk(intptr_t increment) {
// sbrk returns -1 on failure
return (void*)-1;
}
/* ----------------------------------- STRING ROUTINES */
/*
* We can't just use _vsnprintf and _snprintf as drop-in-replacements,
* because they don't always NUL-terminate. :-( We also can't use the
* name vsnprintf, since windows defines that (but not snprintf (!)).
*/
#if defined(_MSC_VER) && _MSC_VER >= 1400
/* We can use safe CRT functions, which the required functionality */
inline int perftools_vsnprintf(char *str, size_t size, const char *format,
va_list ap) {
return vsnprintf_s(str, size, _TRUNCATE, format, ap);
}
#else
inline int perftools_vsnprintf(char *str, size_t size, const char *format,
va_list ap) {
if (size == 0) /* not even room for a \0? */
return -1; /* not what C99 says to do, but what windows does */
str[size-1] = '\0';
return _vsnprintf(str, size-1, format, ap);
}
#endif
#ifndef HAVE_SNPRINTF
inline int snprintf(char *str, size_t size, const char *format, ...) {
va_list ap;
int r;
va_start(ap, format);
r = perftools_vsnprintf(str, size, format, ap);
va_end(ap);
return r;
}
#endif
#define PRIx64 "I64x"
#define SCNx64 "I64x"
#define PRId64 "I64d"
#define SCNd64 "I64d"
#define PRIu64 "I64u"
#ifdef _WIN64
# define PRIuPTR "llu"
# define PRIxPTR "llx"
#else
# define PRIuPTR "lu"
# define PRIxPTR "lx"
#endif
/* ----------------------------------- FILE IO */
#ifndef PATH_MAX
#define PATH_MAX 1024
#endif
#ifndef __MINGW32__
enum { STDIN_FILENO = 0, STDOUT_FILENO = 1, STDERR_FILENO = 2 };
#endif
#ifndef O_RDONLY
#define O_RDONLY _O_RDONLY
#endif
#if __STDC__ && !defined(__MINGW32__)
/* These functions are considered non-standard */
inline int access(const char *pathname, int mode) {
return _access(pathname, mode);
}
inline int open(const char *pathname, int flags, int mode = 0) {
return _open(pathname, flags, mode);
}
inline int close(int fd) {
return _close(fd);
}
inline ssize_t read(int fd, void *buf, size_t count) {
return _read(fd, buf, count);
}
inline ssize_t write(int fd, const void *buf, size_t count) {
return _write(fd, buf, count);
}
inline off_t lseek(int fd, off_t offset, int whence) {
return _lseek(fd, offset, whence);
}
inline char *getcwd(char *buf, size_t size) {
return _getcwd(buf, size);
}
inline int mkdir(const char *pathname, int) {
return _mkdir(pathname);
}
inline FILE *popen(const char *command, const char *type) {
return _popen(command, type);
}
inline int pclose(FILE *stream) {
return _pclose(stream);
}
#endif
EXTERN_C PERFTOOLS_DLL_DECL void WriteToStderr(const char* buf, int len);
/* ----------------------------------- SYSTEM/PROCESS */
#ifdef pid_t
#undef pid_t
typedef int pid_t;
#endif
#if __STDC__ && !defined(__MINGW32__)
inline pid_t getpid(void) { return _getpid(); }
#endif
inline pid_t getppid(void) { return 0; }
/* Handle case when poll is used to simulate sleep. */
inline int poll(struct pollfd* fds, int nfds, int timeout) {
assert(fds == NULL);
assert(nfds == 0);
Sleep(timeout);
return 0;
}
EXTERN_C int getpagesize(); /* in port.cc */
/* ----------------------------------- OTHER */
inline void srandom(unsigned int seed) { srand(seed); }
inline long random(void) { return rand(); }
inline unsigned int sleep(unsigned int seconds) {
Sleep(seconds * 1000);
return 0;
}
// mingw64 seems to define timespec (though mingw.org mingw doesn't),
// protected by the _TIMESPEC_DEFINED macro.
#ifndef _TIMESPEC_DEFINED
struct timespec {
int tv_sec;
int tv_nsec;
};
#endif
inline int nanosleep(const struct timespec *req, struct timespec *rem) {
Sleep(req->tv_sec * 1000 + req->tv_nsec / 1000000);
return 0;
}
#ifndef __MINGW32__
inline long long int strtoll(const char *nptr, char **endptr, int base) {
return _strtoi64(nptr, endptr, base);
}
inline unsigned long long int strtoull(const char *nptr, char **endptr,
int base) {
return _strtoui64(nptr, endptr, base);
}
inline long long int strtoq(const char *nptr, char **endptr, int base) {
return _strtoi64(nptr, endptr, base);
}
inline unsigned long long int strtouq(const char *nptr, char **endptr,
int base) {
return _strtoui64(nptr, endptr, base);
}
inline long long atoll(const char *nptr) {
return _atoi64(nptr);
}
#endif
#define __THROW throw()
/* ----------------------------------- TCMALLOC-SPECIFIC */
/* tcmalloc.cc calls this so we can patch VirtualAlloc() et al. */
extern void PatchWindowsFunctions();
// ----------------------------------- BUILD-SPECIFIC
/*
* windows/port.h defines compatibility APIs for several .h files, which
* we therefore shouldn't be #including directly. This hack keeps us from
* doing so. TODO(csilvers): do something more principled.
*/
#define GOOGLE_MAYBE_THREADS_H_ 1
#endif /* _WIN32 */
#undef inline
#undef EXTERN_C
#endif /* GOOGLE_BASE_WINDOWS_H_ */
| [
"bin.cui@gmail.com"
] | bin.cui@gmail.com |
94e12a67cb45cdab461f9e9bed5e4554cec51e55 | b22588340d7925b614a735bbbde1b351ad657ffc | /athena/Control/CxxUtils/CxxUtils/ones.h | 57a23f878c606e42c25067273ef678573a2af433 | [] | no_license | rushioda/PIXELVALID_athena | 90befe12042c1249cbb3655dde1428bb9b9a42ce | 22df23187ef85e9c3120122c8375ea0e7d8ea440 | refs/heads/master | 2020-12-14T22:01:15.365949 | 2020-01-19T03:59:35 | 2020-01-19T03:59:35 | 234,836,993 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 639 | h | // This file's extension implies that it's C, but it's really -*- C++ -*-.
/*
Copyright (C) 2002-2017 CERN for the benefit of the ATLAS collaboration
*/
// $Id$
/**
* @file CxxUtils/ones.h
* @author scott snyder <snyder@bnl.gov>
* @date Oct, 2014
* @brief Construct a bit mask.
*/
#ifndef CXXUTILS_ONES_H
#define CXXUTILS_ONES_H
namespace CxxUtils {
/**
* @brief Return a bit mask with the lower @a n bits set.
*/
template <class T>
inline
T ones (unsigned int n)
{
if (n >= sizeof(T) * 8)
return ~static_cast<T>(0);
return (static_cast<T>(1) << n) - 1;
}
} // namespace CxxUtils
#endif // not CXXUTILS_ONES_H
| [
"rushioda@lxplus754.cern.ch"
] | rushioda@lxplus754.cern.ch |
3d329942ce6df5256d4ed4c0682eb2270478cb70 | abbec1cd1a4fa296ba4904b3519037e7fe15340b | /percent.cpp | 6da7f82a0d88f640f3b099596f24bf27fd1647f7 | [] | no_license | ferdyanggara/cpp | 82e70268d2a292b57eba8401fe0156e786beb633 | ddf8bac186cf477013e54f15ee168474d6adbf08 | refs/heads/master | 2023-01-13T05:37:58.753604 | 2020-11-14T07:19:35 | 2020-11-14T07:19:35 | 296,805,114 | 0 | 0 | null | 2020-11-14T07:19:36 | 2020-09-19T06:54:05 | C++ | UTF-8 | C++ | false | false | 5,584 | cpp | #include <iostream>
#include <limits>
#include <assert.h>
using namespace std;
// C string termination character
const char NULL_CHAR = '\0';
// The "not found" flag
const int NOT_FOUND = -1;
// Single character wildcard
const char DOT = '.';
// Zero or single character wildcard
const char QMARK = '?';
// Zero or more character wildcard
const char PERCENT = '%';
// Matches the beginning of a string
const char CARET = '^';
int findSubLenAtStrPosWithPercent(const char str[], const char pattern[], int strPos, int patPos);
bool checkQuestionMark(const char pattern[], int patPos = 0){
if(pattern[patPos] == NULL_CHAR)
return true;
if(pattern[patPos] != QMARK)
return false;
return checkQuestionMark(pattern, patPos + 1);
}
bool checkPercentMark(const char pattern[], int patPos = 0){
if(pattern[patPos] == NULL_CHAR)
return true;
if(pattern[patPos] != PERCENT)
return false;
return checkQuestionMark(pattern, patPos + 1);
}
int minString(const char str[], const char pattern[], int strPos, int patPos){
if(pattern[patPos] == NULL_CHAR || str[strPos] == NULL_CHAR)
return 0;
return minString(str, pattern, strPos + 1, patPos + 1) + 1;
}
int minStringPercent(const char str[], int strPos){
if(str[strPos] == NULL_CHAR)
return 0;
return minStringPercent(str, strPos + 1) + 1;
}
bool checkOneCharWildcard(const char str[], const char pattern[], int strPos, int patPos){
if(str[strPos] == NULL_CHAR)
return false;
if(pattern[patPos] == QMARK)
return checkOneCharWildcard(str, pattern, strPos + 1, patPos + 1);
if(pattern[patPos] == str[strPos])
return true;
return false;
}
int getOffsetWildCard(const char str[], const char pattern[], int strPos, int patPos){
// cout << "Nstr: " << str[strPos] << endl;
if(str[strPos] == NULL_CHAR)
return NOT_FOUND;
if(str[strPos] == pattern[patPos + 1]){
// cout << "strPos: " << strPos << endl;
int testOffset = getOffsetWildCard(str, pattern, strPos + 1, patPos);
if(testOffset != NOT_FOUND){
return testOffset + 1;
}
return 0;
}
int result = getOffsetWildCard(str, pattern, strPos + 1, patPos);
if(result != NOT_FOUND)
return result + 1;
return result;
}
int findSubLenAtStrPosWithPercent(const char str[], const char pattern[], int strPos = 0, int patPos = 0)
{
cout << "str: " << str[strPos] << ", pat: " << pattern[patPos] << endl;
if(pattern[patPos] == NULL_CHAR)
return NOT_FOUND;
if(str[strPos] == NULL_CHAR){
if(pattern[patPos] != NULL_CHAR && !checkPercentMark(pattern, patPos))
return NOT_FOUND;
return 0;
}
if (pattern[patPos] == str[strPos])
{
if (pattern[patPos + 1] == NULL_CHAR) // the entire pattern is matched
return 1;
// otherwise, the match is only part way through
int result = findSubLenAtStrPosWithPercent(str, pattern, strPos + 1, patPos + 1); // check if the remaining part of the pattern
// matches with that of the substring
if (result != NOT_FOUND) // only return a match when the entire pattern is matched
return 1 + result;
}
else if(pattern[patPos] == PERCENT){
// case where end of pattern consists of percents
if(checkPercentMark(pattern, patPos)){
return minStringPercent(str, strPos);
}
if(pattern[patPos + 1] == PERCENT)
return findSubLenAtStrPosWithPercent(str, pattern, strPos, patPos + 1);
// determine whether percent is zero or more character wildcard
int offset = getOffsetWildCard(str, pattern, strPos, patPos);
if(offset == NOT_FOUND)
return NOT_FOUND;
if(!offset){
cout << "zero char" << endl;
return findSubLenAtStrPosWithPercent(str, pattern, strPos, patPos + 1);
}
// cout << "offset: " << offset << endl;
int result = findSubLenAtStrPosWithPercent(str, pattern, strPos + offset, patPos + 1);
if(result != NOT_FOUND)
return result + offset;
}
// cout << "NOt Found !" << endl;
return NOT_FOUND;
}
int matchSubWithPercent(const char str[], const char pattern[], int& length, int start = 0){
length = 0;
if (str[start] == NULL_CHAR)
return NOT_FOUND;
int testLength = findSubLenAtStrPosWithPercent(str, pattern, start);
if (testLength != NOT_FOUND) {
cout << "Found!" << endl;
length = testLength;
return start;
}
return matchSubWithPercent(str, pattern, length, start + 1);
}
int main(){
int index;
int length;
// length = findSubLenAtStrPosWithPercent("cpoerjj", "c%%%r%%");
// length = findSubLenAtStrPosWithPercent("beyond", "%rbe%z");
// index = matchSubWithPercent("idk", "%", length); // 0 and 3
// index = matchSubWithPercent("ikidk", "i%k", length); // 0 and 5
// index = matchSubWithPercent("lolidk", "dk%", length); // 4 and 2
// index = matchSubWithPercent("ilolol", "%ol", length); // 0 and 6
// index = matchSubWithPercent("ilolol", "lo%", length); // 1 and 5
// index = matchSubWithPercent("lol", "w%w", length); // NOT_FOUND and 0
index = matchSubWithPercent("something", "%%%s%%t%h", length); // 0 and 6
cout << "Index: " << index << endl;
cout << "Length: " << length << endl;
return 0;
} | [
"jovanedric01@gmail.com"
] | jovanedric01@gmail.com |
fc2cde9af33d534c1bc55dc93776285bae97596e | 54b37241d83de4de308f335d412e0ce9df392a78 | /src-rmcrt/CCA/Components/Arches/PropertyModelsV2/sumRadiation.h | 8c5997f9110129f68a26bfe65f339cbd4707b86e | [
"MIT"
] | permissive | jholmen/Uintah-sc19 | dac772fbbc7ab9b8b2bf1be02a08c9e2d8166d24 | fae5ebe7821ec23709e97736f1378aa4aa01e645 | refs/heads/master | 2023-04-15T21:18:28.362715 | 2021-04-20T13:54:30 | 2021-04-20T13:54:30 | 359,625,839 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,119 | h | #ifndef Uintah_Component_Arches_PropertyModelV2_sumRadiation_h
#define Uintah_Component_Arches_PropertyModelV2_sumRadiation_h
#include <CCA/Components/Arches/Task/TaskInterface.h>
#include <Core/Exceptions/ProblemSetupException.h>
namespace Uintah{
class BoundaryCondition_new;
class sumRadiation : public TaskInterface {
public:
typedef std::vector<ArchesFieldContainer::VariableInformation> VIVec;
sumRadiation( std::string task_name, int matl_index ) :
TaskInterface( task_name, matl_index ){
}
~sumRadiation(){}
TaskAssignedExecutionSpace loadTaskEvalFunctionPointers();
void problemSetup( ProblemSpecP& db );
void register_initialize( VIVec& variable_registry , const bool pack_tasks);
void register_timestep_init( VIVec& variable_registry , const bool packed_tasks);
void register_restart_initialize( VIVec& variable_registry , const bool packed_tasks);
void register_timestep_eval( VIVec& variable_registry, const int time_substep , const bool packed_tasks);
void register_compute_bcs( VIVec& variable_registry, const int time_substep , const bool packed_tasks){}
void compute_bcs( const Patch* patch, ArchesTaskInfoManager* tsk_info ){}
void initialize( const Patch* patch, ArchesTaskInfoManager* tsk_info );
void restart_initialize( const Patch* patch, ArchesTaskInfoManager* tsk_info );
void timestep_init( const Patch* patch, ArchesTaskInfoManager* tsk_info );
template <typename EXECUTION_SPACE, typename MEMORY_SPACE>
void eval( const Patch* patch, ArchesTaskInfoManager* tsk_info, void* stream );
void create_local_labels();
class Builder : public TaskInterface::TaskBuilder {
public:
Builder( std::string task_name, int matl_index )
: _task_name(task_name), _matl_index(matl_index){}
~Builder(){ }
sumRadiation* build()
{ return scinew sumRadiation( _task_name, _matl_index ); }
private:
std::string _task_name;
int _matl_index;
};
private:
std::vector<std::string> _gas_part_name;
std::string m_abskt_name;
};
}
#endif
| [
"jholmen@sci.utah.edu"
] | jholmen@sci.utah.edu |
89bfe9b5b97c7e82dc192b3248f7c5b291328811 | c31e46a9a3199aa2eea81d61fb0de27317354e88 | /P2evenFibonacciSum.cpp | 4e930f12c18782df17fc1927311fb5fd03c92fc3 | [] | no_license | SeanSiders/projectEulerSolutions | 268fcb617c92f6c34fd8744f567171eca1370304 | 0aa69178f7e3065de94b354b4b8c631873199d65 | refs/heads/master | 2020-12-03T20:03:47.780622 | 2020-01-02T22:11:39 | 2020-01-02T22:11:39 | 231,467,949 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 468 | cpp | #include <iostream>
uint64_t evenFibonacciSum(uint64_t n)
{ /*return the sum of all even numbers in the fibonacci sequence <= n*/
uint64_t a = 0;
uint64_t b = 1;
uint64_t fNum = 0;
uint64_t fibonacciSum = 0;
while (fNum <= n)
{
fNum = a + b;
a = b;
b = fNum;
if (fNum % 2 == 0)
fibonacciSum += fNum;
}
return fibonacciSum;
}
int main()
{
uint64_t maxNum;
std::cin >> maxNum;
std::cout << evenFibonacciSum(maxNum) << std::endl;
return 0;
} | [
"sean.siders@icloud.com"
] | sean.siders@icloud.com |
aab99ea0a23704298119aaf19e98b7e6d2822144 | 6874f9f3d48a43091b02923a26135fb32df10a97 | /C_scripts/SIFT/sift.h | 177dbfa0106cfea01586d61c5845acd08617afc6 | [] | no_license | hellmonky/project | e7fc834e101d697e7bcf7d905274107b1306f71e | 483c8c4b82d17c001fdaf3d80058bf3e53d71390 | refs/heads/master | 2021-01-10T10:43:51.388845 | 2017-02-23T08:13:30 | 2017-02-23T08:13:30 | 36,220,081 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 6,325 | h | #ifndef SIFT_H
#define SIFT_H
#include <vector>
using namespace std;
#include <opencv.hpp>//只需要包含一个就可以了
using namespace cv;
/************************************************************************/
/* 0 宏定义 */
/************************************************************************/
#define INIT_SIGMA 0.5
#define SIGMA 1.6
#define INTERVALS 3
#define RATIO 10
#define MAX_INTERPOLATION_STEPS 5
#define DXTHRESHOLD 0.03
#define ORI_HIST_BINS 36
#define ORI_SIGMA_TIMES 1.5
#define ORI_WINDOW_RADIUS 3.0 * ORI_SIGMA_TIMES
#define ORI_SMOOTH_TIMES 2
#define ORI_PEAK_RATIO 0.8
#define FEATURE_ELEMENT_LENGTH 128
#define DESCR_HIST_BINS 8
#define IMG_BORDER 5
#define DESCR_WINDOW_WIDTH 4
#define DESCR_SCALE_ADJUST 3
#define DESCR_MAG_THR 0.2
#define INT_DESCR_FCTR 512.0
/************************************************************************/
/* 1 设计的数据结构 */
/************************************************************************/
struct Keypoint
{
int octave; //关键点所在组
int interval;// 关键点所在层
double offset_interval;//插值调整后的层的增量
int x; //x,y坐标,根据octave和interval可取的层内图像
int y;
//scale = sigma0*pow(2.0, o+s/S)
double scale; //空间尺度坐标
double dx; //特征点坐标,该坐标被缩放成原图像大小
double dy;
double offset_x;
double offset_y;
//高斯金字塔组内各层尺度坐标,不同组的相同层的sigma值相同
//关键点所在组的组内尺度
double octave_scale; //offset_i;
double ori;//方向
int descr_length;
double descriptor[FEATURE_ELEMENT_LENGTH]; //FEATURE_ELEMENT_LENGTH默认为128维向量
double val;//极值
};
/************************************************************************/
/* 2.1 函数声明——内部接口 */
/************************************************************************/
bool GaussKernel1D(vector<double>& gausskernel, double sigma);//一维gauss模板
bool GaussKernel2D(vector<double>& gausskernel, double sigma);//二维gauss模板
void GaussianTemplateSmooth(const Mat &src, Mat &dst, double sigma);//使用自建模板平滑,未使用sigma,边缘无处理
bool GaussianSmoothSingle(const Mat &src, Mat &dst, double sigma, bool isOpenCV);//只能处理单通道的图像
bool GaussianSmoothMult(const Mat &src, Mat &dst, double sigma, bool isOpenCV);//处理多通道的图像
void ConvertToGray(const Mat& src, Mat& dst);
void UpSample(const Mat &src, Mat &dst);//升采样
void CreateInitSmoothGray(const Mat &src, Mat &dst, double sigma = SIGMA);//构建-1层初始图像,SIGMA=1.6
double PyrAt(const vector<vector<Mat>>& pyr, int octaves, int intervals, int x, int y);
void DownSample(const Mat& src, Mat& dst);//降采样
void GaussPyramid(const Mat& src, vector<vector<Mat>>& gausspyriads, int octaves , int intervals, double sigma);
void Sub(const Mat& a, const Mat& b, Mat & c);//图像相减
void DogPyramid(const vector<vector<Mat>>& gauss_pyr, vector<vector<Mat>>& dog_pyr, int octaves, int intervals);
bool isExtremum(const vector<vector<Mat>>& dog_pyr, int octaves, int intervals, int x, int y);
void DerivativeOf3D(const vector<vector<Mat>>& dog_pyr, int octaves, int intervals, int x, int y, double *dx);//一阶导数矩阵
void Hessian3D(const vector<vector<Mat>>& dog_pyr, int octaves, int intervals, int x, int y, double *H);//3*3阶Hessian矩阵
bool Inverse3D(const double *H, double *H_inve);//3*3阶Hessian矩阵求逆
void GetOffsetX(const vector<vector<Mat>>& dog_pyr, int octaves, int intervals, int x, int y, double *offset_x);
double GetFabsDx(const vector<vector<Mat>>& dog_pyr, int octaves, int intervals, int x, int y, const double* offset_x);
Keypoint* InterploationExtremum(const vector<vector<Mat>>& dog_pyr, int octave, int interval, int x, int y, double dxthreshold = DXTHRESHOLD);
bool passEdgeResponse(const vector<vector<Mat>>& pyr, int octaves, int intervals, int x, int y, double r = RATIO);//默认RATIO = 10
void DetectionLocalExtrema(const vector<vector<Mat>>& dog_pyr, vector<Keypoint>& extrema, int octaves, int intervals=INTERVALS);
void CalculateScale(vector<Keypoint>& features, double sigma = SIGMA, int intervals = INTERVALS);
void HalfFeatures(vector<Keypoint>& features);//由于计算Hessian矩阵导数的时候用了Taylor级数,有2倍关系
bool CalcGradMagOri(const Mat& gauss, int x, int y, double& mag, double& ori);
void CalculateOrientationHistogram(const Mat& gauss, int x, int y, int bins, int radius, double sigma, vector<double>& hist);
double DominantDirection(vector<double>& hist, int n);
void GaussSmoothOriHist(vector<double>& hist, int n);
void CalcOriFeatures(const Keypoint& keypoint, vector<Keypoint>& features, const vector<double>&hist, int n, double mag_thr);
void OrientationAssignment(vector<Keypoint>& extrema, vector<Keypoint>& features, const vector<vector<Mat>>& gauss_pyr);
void InterpHistEntry(double ***hist, double xbin, double ybin, double obin, double mag, int bins, int d);
void NormalizeDescr(Keypoint& feat);//归一化处理
void HistToDescriptor(double ***hist, int width, int bins, Keypoint& feature);
double*** CalculateDescrHist(const Mat& gauss, int x, int y, double octave_scale, double ori, int bins, int width);
void DescriptorRepresentation(vector<Keypoint>& features, const vector<vector<Mat>>& gauss_pyr, int bins, int width);
/************************************************************************/
/* 2.1 函数声明——外部接口 */
/************************************************************************/
void Sift(const Mat &src, vector<Keypoint>& features, double sigma, int intervals=INTERVALS);
void write_features(const vector<Keypoint>&features, const char*file);
bool FeatureCmp(Keypoint& f1, Keypoint& f2);
void DrawKeyPoints(Mat &src, vector<Keypoint>& keypoints);
void DrawSiftFeature(Mat& src, Keypoint& feat, CvScalar color);
void DrawSiftFeatures(Mat& src, vector<Keypoint>& features);
const char* GetFileName(const char* dir, int i);//很实用的函数
void write_pyr(const vector<vector<Mat>>& pyr, const char* dir);
#endif SIFT_H | [
"hellmonky@qq.com"
] | hellmonky@qq.com |
f302bb3c4e33b80e5f1c275713928002b4e9151a | d30594a1e2d6621a1e629409c3f2b047e9e22c85 | /src/solver/ThreadPool.cpp | 8db88af32cb62d112a4a7a614d69b2d3efce953e | [] | no_license | hankiou/Tetravex-resolve | a966c596917143ab7cd7d6e670fe5ef24eea39a9 | ccc21581f0844e10a9b8a79299c2378010c96676 | refs/heads/master | 2020-08-12T20:00:32.745180 | 2019-11-16T12:09:39 | 2019-11-16T12:09:39 | 214,834,376 | 0 | 3 | null | 2019-11-16T12:09:40 | 2019-10-13T14:26:03 | null | UTF-8 | C++ | false | false | 311 | cpp | #include "../../include/solver/ThreadPool.h"
using namespace std;
ThreadPool::ThreadPool(){}
void ThreadPool::addThread(thread* t){threads.push_back(t);}
void ThreadPool::joinThreads(){for(thread* t : threads){t->join();}}
void ThreadPool::killThreads(){
for(thread* t : threads){
t->~thread();}
} | [
"thehankiou@gmail.com"
] | thehankiou@gmail.com |
e6cbebbab36a138821988997b8b13046a37e533a | 63c71060f36866bca4ac27304cef6d5755fdc35c | /src/DataCacher/CacherVirtualFile.h | 17270693eb3a1a7e13eaa5f6bc6ad8abb4eb0f79 | [] | no_license | 15831944/barry_dev | bc8441cbfbd4b62fbb42bee3dcb79ff7f5fcaf8a | d4a83421458aa28ca293caa7a5567433e9358596 | refs/heads/master | 2022-03-24T07:00:26.810732 | 2015-12-22T07:19:58 | 2015-12-22T07:19:58 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,627 | h | ////////////////////////////////////////////////////////////////////////////
//
// Copyright (C) 2005
// Packet Engineering, Inc. All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification is not permitted unless authorized in writing by a duly
// appointed officer of Packet Engineering, Inc. or its derivatives
//
//
// Modification History:
// 08/23/2012 Created by Chen Ding
////////////////////////////////////////////////////////////////////////////
#ifndef Aos_DataxCacher_CacherVirtualFile_h
#define Aos_DataxCacher_CacherVirtualFile_h
#include "DataCacher/Ptrs.h"
#include "DataSort/Ptrs.h"
#include "DataSort/DataSort.h"
#include "Rundata/Ptrs.h"
#include "SEInterfaces/Ptrs.h"
#include "SEInterfaces/ActionObj.h"
#include "SEInterfaces/TaskObj.h"
#include "SEInterfaces/WriteCacherObj.h"
#include "Util/RCObject.h"
#include "Util/RCObjImp.h"
#include "Util/Ptrs.h"
#include "XmlUtil/Ptrs.h"
#include <vector>
using namespace std;
class AosCacherVirtualFile : public AosWriteCacherObj
{
private:
OmnMutexPtr mLock;
AosXmlTagPtr mActions;
AosDataCacherObjPtr mFilteredTrashCan;
AosDataCacherObjPtr mUnrecogCacher;
AosDataCacherObjPtr mUnrecogTrashCan;
AosValueSelObjPtr mCacherPicker;
u64 mNumErrors;
AosNetFileObjPtr mNetFile;
public:
AosCacherVirtualFile(const bool flag);
AosCacherVirtualFile(const AosXmlTagPtr &def, const AosRundataPtr &rdata);
~AosCacherVirtualFile();
virtual bool appendData(const AosBuffPtr &buff, const AosRundataPtr &rdata);
virtual bool appendRecord( const AosDataRecordObjPtr &record, const AosRundataPtr &rdata);
virtual bool appendEntry( const AosValueRslt &value, const AosRundataPtr &rdata);
virtual bool finish(
const u64 &totalentries,
const AosXmlTagPtr &xml,
const AosRundataPtr &rdata);
virtual bool finish(const AosRundataPtr &rdata);
virtual bool clear();
virtual int64_t size();
virtual char* getData(int64_t&) const;
virtual AosDataBlobObjPtr toDataBlob() const;
virtual AosDataCacherObjPtr clone();
virtual AosDataCacherObjPtr clone(const AosXmlTagPtr&, const AosRundataPtr&);
virtual bool serializeTo(const AosBuffPtr&, const AosRundataPtr&);
virtual bool serializeFrom(const AosBuffPtr&, const AosRundataPtr&);
virtual bool split(vector<AosDataCacherObjPtr>&, const AosRundataPtr&);
virtual AosReadCacherObjPtr convertToReadCacher();
virtual char* nextValue(int&, const AosRundataPtr&);
virtual bool getNextBlock(AosBuffPtr &buff, const AosRundataPtr &rdata);
private:
bool config(const AosXmlTagPtr &conf, const AosRundataPtr &rdata);
};
#endif
| [
"barryniu@jimodb.com"
] | barryniu@jimodb.com |
a7dd4efee8f67f41a3edbe785d9d57c2e002b06e | d4d571a94409b31179c4afe1bdeeef2b8a3ca733 | /src/Components/CvMatGenerator/CvMatGenerator.cpp | 7233978bc8f56d150734bd85855f8530117909c1 | [] | no_license | qiubix/SampleGenerators | c56e119e63ebb30e9914aad0848a575a4978e05a | b0a0ff44e86dd56934e793953732f803291961c2 | refs/heads/master | 2021-01-21T04:50:48.586578 | 2016-06-13T10:04:30 | 2016-06-13T10:04:30 | 49,492,881 | 0 | 0 | null | 2016-01-19T13:41:50 | 2016-01-12T10:32:58 | C++ | UTF-8 | C++ | false | false | 1,670 | cpp | /*!
* \file CvMatGenerator.cpp
* \brief
*/
#include <memory>
#include <string>
#include <iostream>
#include <opencv2/highgui/highgui.hpp>
#include "CvMatGenerator.hpp"
#include "Logger.hpp"
namespace Generators {
namespace Sample {
CvMatGenerator::CvMatGenerator(const std::string & name) :
Base::Component(name),
property_width("matrix.width", 4),
property_height("matrix.height", 3),
property_value("matrix.value", 1)
{
LOG(LTRACE)<<"Hello CvMatGenerator\n";
registerProperty(property_width);
registerProperty(property_height);
registerProperty(property_value);
}
CvMatGenerator::~CvMatGenerator() {
LOG(LTRACE)<<"Good bye CvMatGenerator\n";
}
void CvMatGenerator::prepareInterface() {
LOG(LTRACE) << "CvMatGenerator::prepareInterface\n";
registerStream("out_img", &out_img);
}
void CvMatGenerator::setPropertyValue(const string &propertyName, const int newValue) {
if (property_width.name() == propertyName) {
property_width(newValue);
} else if (property_height.name() == propertyName){
property_height(newValue);
} else {
property_value(newValue);
}
}
bool CvMatGenerator::onInit() {
LOG(LTRACE) << "CvMatGenerator::initialize\n";
return true;
}
bool CvMatGenerator::onFinish() {
LOG(LTRACE) << "CvMatGenerator::finish\n";
return true;
}
bool CvMatGenerator::onStop() {
LOG(LTRACE) << "CvMatGenerator::onStop\n";
return true;
}
bool CvMatGenerator::onStart() {
LOG(LTRACE) << "CvMatGenerator::onStart\n";
img = cv::Mat::ones(property_height,property_width, CV_32S);
img = img * property_value;
out_img.write(img);
return true;
}
}//: namespace Sample
}//: namespace Generators
| [
"qiubix@gmail.com"
] | qiubix@gmail.com |
0aa559447ff3c2323745120a8b0f064198247c23 | 765a726a60389159396d349160944d5eeccc14c3 | /cpp/U109103.cpp | 30a476a837df7bdc8c0113aff2fe37290a2b7e11 | [] | no_license | shiyihang2007/Codes | fb2ab64ddfe33d6ab2fbe9cda46c04db140f396d | 9123306461422174a99020aa12f3e9b3b33d49a8 | refs/heads/master | 2022-11-16T11:46:37.988072 | 2020-04-07T04:19:48 | 2020-04-07T04:19:48 | 253,684,189 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 625 | cpp | #include <bits/stdc++.h>
using namespace std;
int n,m;
int d[105][105],t[105][105];
int a,b,c;
int main(){
cin>>n>>m;
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
cin>>d[i][j];
}
}
cin>>a>>b>>c;
for(int i=0;i<c;++i){
for(int j=0;j<c;++j){
t[a+j][b+c-i]=d[a+i][b+j];
}
}
for(int i=0;i<c;++i){
for(int j=0;j<c;++j){
d[a+i][b+j]=t[a+i][b+c-j];
}
}
for(int i=1;i<=n;++i){
for(int j=1;j<=m;++j){
printf("%d ",d[i][j]);
}
puts("");
}
} | [
"noreply@github.com"
] | noreply@github.com |
9a6ed9743cbd46712e4efc9eaf5adfe528af1b86 | a8fde6cc44096c470b3ffca6b84d07d58627e6a5 | /AFC.ino | 73765829d8187346fd9137718b11ec4eabc63a3a | [] | no_license | aacgriet/AUTOMATED-FAN-CLEANER | ece8bcbf5510b48aad614159ee86465b37b66998 | af1c5bf34afffefc786e267c658ceb95b4ce6028 | refs/heads/master | 2020-07-02T19:12:11.346489 | 2019-08-10T13:37:22 | 2019-08-10T13:37:22 | 201,634,798 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,667 | ino | #include<Servo.h>
Servo myServo1;
const int trigPin = 5;
const int echoPin = 6;
long duration;
int distance;
const int stepPin = 3;
const int dirPin = 4;
void setup()
{
pinMode(stepPin,OUTPUT);
pinMode(dirPin,OUTPUT);
Serial.begin(9600);
pinMode(trigPin,OUTPUT);
pinMode(echoPin,INPUT);
myServo1.attach(12);
}
void loop() {
if (Serial.available()>0)
switch(Serial.read())
{
case 'a':
SetTheBlade();
break;
case 'b':
CleanTheBlade();
break;
case 'c':
Retract();
break;
}
}
void SetTheBlade()
{
int i=0;
while(i==0){
digitalWrite(dirPin,HIGH);
for(int x = 0; x < 10000 ;x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(500);
digitalWrite(stepPin,LOW);
delayMicroseconds(500);
digitalWrite(trigPin, LOW);
delayMicroseconds(2);
digitalWrite(trigPin, HIGH);
delayMicroseconds(10);
digitalWrite(trigPin, LOW);
duration = pulseIn(echoPin, HIGH);
distance= duration*0.034/2;
Serial.print("Distance: ");
Serial.println(distance);
if(distance<=10)
{
x=20000;
i++;
}}
}}
void CleanTheBlade()
{
myservo1.write(0);
delay(1000);
digitalWrite(dirPin,HIGH);
for(int x = 0; x < 10000 ;x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(500);
digitalWrite(stepPin,LOW);
delayMicroseconds(500);
}
digitalWrite(dirPin,LOW);
for(int x = 0; x < 10000 ;x++) {
digitalWrite(stepPin,HIGH);
delayMicroseconds(500);
digitalWrite(stepPin,LOW);
delayMicroseconds(500);
}
}
void Retract()
{
myServo1.write(180);
delay(1000);
}
| [
"noreply@github.com"
] | noreply@github.com |
c33e0c1c97bfb8827f0d3e83eae2de4d417d0201 | 4b38230b0bc1e08db32758ef9a45fbf907e7a776 | /include/svgpp/factory/color.hpp | e0f8956d08d7bae245b3e14537924ed90fad6f0a | [
"BSL-1.0"
] | permissive | svgpp/svgpp | 65ad70a6373a5b5d5100fe70bd68ab1d548ab232 | 1583a7b209038bfd0d98c6ce7d4c93986f7b235e | refs/heads/master | 2022-10-14T14:37:32.175114 | 2022-09-30T16:05:00 | 2022-09-30T16:05:00 | 16,960,683 | 525 | 107 | BSL-1.0 | 2023-08-31T10:10:22 | 2014-02-18T19:23:21 | C++ | UTF-8 | C++ | false | false | 728 | hpp | // Copyright Oleg Maximenko 2014.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//
// See http://github.com/svgpp/svgpp for library home page.
#pragma once
#include <svgpp/factory/icc_color_stub.hpp>
#include <svgpp/factory/integer_color.hpp>
namespace svgpp { namespace factory
{
namespace color
{
typedef integer<> default_factory;
template<class Context>
struct by_context
{
typedef default_factory type;
};
}
namespace icc_color
{
typedef stub default_factory;
template<class Context>
struct by_context
{
typedef default_factory type;
};
}
}} | [
"olegmax@gmail.com"
] | olegmax@gmail.com |
04f2ed183d54d9241525db21559eb8dac82cdbbe | 36aab89d53d4e373b9b7e6e9bc61d7622afb4902 | /codechef/MAR17/SUMDIS/testcases.cpp | 54efee6edf61374829851149c3c916dda445edda | [] | no_license | vikram-rathore1/competitive_programming | 052518f36053eab24a2b0343cd6965549a919b42 | 598cbcb3dfde75751ee9a820fb52ebe3b4d64d44 | refs/heads/master | 2022-04-12T11:14:44.968592 | 2020-04-03T21:10:12 | 2020-04-03T21:10:12 | 65,635,969 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 358 | cpp | #include<bits/stdc++.h>
using namespace std;
int main() {
srand(time(0));
int t, n;
t = 2;
n = 5;
cout << t << "\n";
while(t--) {
cout << n << "\n";
for (int i = 1; i < 4; i++) {
for (int j = 0; j < n - i; j++) cout << (rand() % 20) + 1 << " ";
cout << "\n";
}
}
return 0;
}
| [
"rathore.vikram624@gmail.com"
] | rathore.vikram624@gmail.com |
590a823619984af792823096dbc7b364354a2c7f | 5026d5e0cfc910ff2c2985c087fac65cbecf9a3c | /test/vs/AsyncMssql/AsyncMssql.cpp | 4c5979bd612dea377b2564926154ec0602d379eb | [
"LicenseRef-scancode-unknown-license-reference",
"Apache-2.0"
] | permissive | DatabasesWorks/qtl-database-library-for-MySQL-SQLite-and-ODBC | 4d187567f8025ff8c4cd1e8df163b82ff84338d3 | cb88ba251b4e7e4e28ba0f82dfb1963b585a2702 | refs/heads/master | 2022-05-13T00:42:33.516564 | 2022-03-22T16:50:24 | 2022-03-22T16:50:24 | 179,248,750 | 0 | 0 | Apache-2.0 | 2022-03-22T16:50:25 | 2019-04-03T08:47:19 | C++ | UTF-8 | C++ | false | false | 3,146 | cpp | #include "pch.h"
#include <iostream>
#include <array>
#include "../../../include/qtl_odbc.hpp"
class SimpleEventLoop
{
public:
SimpleEventLoop()
{
m_objs.reserve(MAXIMUM_WAIT_OBJECTS);
m_nExpired = INFINITE;
m_hStopEvent = CreateEvent(NULL, TRUE, FALSE, NULL);
m_objs.push_back(m_hStopEvent);
}
qtl::event* add(HANDLE hEvent)
{
if (m_objs.size() < m_objs.capacity())
{
m_objs.push_back(hEvent);
std::unique_ptr<event_item> item(new event_item(*this, hEvent));
event_item* result = item.get();
m_items.push_back(std::move(item));
return result;
}
return nullptr;
}
void run()
{
while (m_objs.size()>1)
{
DWORD dwSize = m_objs.size();
DWORD dwTimeout = m_nExpired - GetTickCount();
DWORD dwObject = WaitForMultipleObjects(dwSize, m_objs.data(), FALSE, dwTimeout);
if (dwObject >= WAIT_OBJECT_0 && WAIT_OBJECT_0 + dwSize)
{
DWORD index = dwObject - WAIT_OBJECT_0;
HANDLE hEvent = m_objs[index];
if (hEvent == m_hStopEvent)
break;
m_objs.erase(m_objs.begin() + index);
fire(hEvent, qtl::event::ef_read | qtl::event::ef_write);
}
else if (dwObject == WAIT_TIMEOUT)
{
fire_timeout();
}
}
}
void stop()
{
SetEvent(m_hStopEvent);
}
private:
class event_item : public qtl::event
{
public:
event_item(SimpleEventLoop& ev, HANDLE hEvent) : m_ev(&ev), m_hEvent(hEvent), m_busying(false)
{
}
virtual void set_io_handler(int flags, long timeout, std::function<void(int)>&& handler) override
{
m_handler = handler;
m_busying = true;
m_nExpired = GetTickCount() + timeout*1000;
m_ev->m_nExpired = std::min<DWORD>(m_ev->m_nExpired, m_nExpired);
}
virtual void remove() override
{
if(!m_busying)
m_ev->remove(this);
}
virtual bool is_busying() override
{
return m_busying;
}
HANDLE m_hEvent;
std::function<void(int)> m_handler;
SimpleEventLoop* m_ev;
DWORD m_nExpired;
bool m_busying;
};
HANDLE m_hStopEvent;
std::vector<HANDLE> m_objs;
std::vector<std::unique_ptr<event_item>> m_items;
DWORD m_nExpired;
void remove_object(event_item* item)
{
auto it = std::find_if(m_objs.begin(), m_objs.end(), [item](HANDLE hEvent) {
return item->m_hEvent == hEvent;
});
if (it != m_objs.end())
{
m_objs.erase(it);
}
}
void remove(event_item* item)
{
remove_object(item);
{
auto it = std::find_if(m_items.begin(), m_items.end(), [item](const std::unique_ptr<event_item>& v) {
return item == v.get();
});
if (it != m_items.end())
{
m_items.erase(it);
}
}
}
void fire(HANDLE hEvent, int flags)
{
auto it = std::find_if(m_items.begin(), m_items.end(), [hEvent](const std::unique_ptr<event_item>& v) {
return hEvent == v->m_hEvent;
});
if (it != m_items.end())
{
(*it)->m_handler(flags);
}
}
void fire_timeout()
{
for (auto& item : m_items)
{
if (item->m_nExpired < m_nExpired)
{
item->m_handler(qtl::event::ef_timeout);
remove_object(item.get());
}
else
{
m_nExpired = std::min<DWORD>(item->m_nExpired, m_nExpired);
}
}
}
};
int main()
{
SimpleEventLoop ev;
ev.run();
return 0;
}
| [
"glyc@sina.com.cn"
] | glyc@sina.com.cn |
3dbab537935585aa9f0c1342762a728de58182c3 | 7bb34b9837b6304ceac6ab45ce482b570526ed3c | /external/webkit/Source/WebKit2/WebProcess/Plugins/Netscape/JSNPMethod.h | 0fd01eae2c353f4ba2ddf57847f35ba52a02be67 | [
"Apache-2.0",
"LicenseRef-scancode-warranty-disclaimer",
"LGPL-2.0-or-later",
"GPL-1.0-or-later",
"GPL-2.0-only",
"LGPL-2.1-only",
"LGPL-2.0-only",
"BSD-2-Clause",
"LicenseRef-scancode-other-copyleft"
] | permissive | ghsecuritylab/android_platform_sony_nicki | 7533bca5c13d32a8d2a42696344cc10249bd2fd8 | 526381be7808e5202d7865aa10303cb5d249388a | refs/heads/master | 2021-02-28T20:27:31.390188 | 2013-10-15T07:57:51 | 2013-10-15T07:57:51 | 245,730,217 | 0 | 0 | Apache-2.0 | 2020-03-08T00:59:27 | 2020-03-08T00:59:26 | null | UTF-8 | C++ | false | false | 2,198 | h | /*
* Copyright (C) 2010 Apple Inc. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY APPLE INC. AND ITS CONTRIBUTORS ``AS IS''
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO,
* THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR
* PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL APPLE INC. OR ITS CONTRIBUTORS
* BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
* SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
* INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
* CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
* ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF
* THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef JSNPMethod_h
#define JSNPMethod_h
#include <JavaScriptCore/InternalFunction.h>
typedef void* NPIdentifier;
namespace WebKit {
// A JSObject that wraps an NPMethod.
class JSNPMethod : public JSC::InternalFunction {
public:
JSNPMethod(JSC::ExecState*, JSC::JSGlobalObject*, const JSC::Identifier&, NPIdentifier);
static const JSC::ClassInfo s_info;
NPIdentifier npIdentifier() const { return m_npIdentifier; }
private:
static JSC::Structure* createStructure(JSC::JSGlobalData& globalData, JSC::JSValue prototype)
{
return JSC::Structure::create(globalData, prototype, JSC::TypeInfo(JSC::ObjectType, StructureFlags), AnonymousSlotCount, &s_info);
}
virtual JSC::CallType getCallData(JSC::CallData&);
NPIdentifier m_npIdentifier;
};
} // namespace WebKit
#endif // JSNPMethod_h
| [
"gahlotpercy@gmail.com"
] | gahlotpercy@gmail.com |
151cd7a1b1d4c73d40267763aa5087b36561ac40 | 30bdd8ab897e056f0fb2f9937dcf2f608c1fd06a | /contest/1542503741.cpp | abda327e6180277cfab4756ac43a8783f79b8a75 | [] | no_license | thegamer1907/Code_Analysis | 0a2bb97a9fb5faf01d983c223d9715eb419b7519 | 48079e399321b585efc8a2c6a84c25e2e7a22a61 | refs/heads/master | 2020-05-27T01:20:55.921937 | 2019-11-20T11:15:11 | 2019-11-20T11:15:11 | 188,403,594 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 730 | cpp | #include <iostream>
#include <cstdio>
#include <cstdlib>
#include <cmath>
#include <algorithm>
#include <vector>
#include <map>
#include <set>
#include <bitset>
#include <string>
#include <queue>
#include <stack>
#include <sstream>
#include <cstring>
#include <numeric>
#include <ctime>
#include <cassert>
using namespace std;
string cmptemp;
string pass;
string bark[105];
int n;
bool res;
bool solve() {
for(int i = 0; i < n; i++) {
for(int j = 0; j < n; j++) {
cmptemp = bark[i] + bark[j];
if(cmptemp.find(pass) != cmptemp.npos) {
return true;
}
}
}
return false;
}
int main() {
cin >> pass >> n;
for(int i = 0; i < n; i++) {
cin >> bark[i];
}
cout << (solve()?"YES":"NO") << endl;
return 0;
} | [
"harshitagar1907@gmail.com"
] | harshitagar1907@gmail.com |
189caafff6de425da129790161d17a041193a009 | 8b63cfd684ac88c56636546852308ab12f383d53 | /7.17 인쇄용_노트/segmentTree.cpp | 6dde4c9fdaa08d25d85c64d852bed642eefa31b3 | [] | no_license | shinbian11/1_day_1_commit | 3b2716d910ef18ca78b663085cc86d8ff7d585cb | 6096609ff6529e37bb8adfcf373bc75bf4691422 | refs/heads/master | 2021-04-10T05:49:56.178476 | 2021-03-30T15:19:17 | 2021-03-30T15:19:17 | 248,914,980 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,592 | cpp | //세그먼트 트리 이용 (2042번 - 구간 합 구하기)
#include <bits/stdc++.h>
using namespace std;
typedef long long ll;
ll init(vector <ll>& v, vector<ll>& tree, int node, int start, int end)
{
if (start == end)
{
return tree[node] = v[start];
}
ll mid = (start + end) / 2;
return tree[node] = init(v, tree, node * 2, start, mid) + init(v, tree, node * 2 + 1, mid + 1, end);
}
void update(vector<ll>& tree, int node, int start, int end, ll index, ll diff)
{
if ((start > index) || (end < index))
return;
tree[node] += diff;
if (start != end)
{
int mid = (start + end) / 2;
update(tree, node * 2, start, mid, index, diff);
update(tree, node * 2+1, mid+1, end, index, diff);
}
}
ll sum(vector<ll>& tree, int node, int start, int end, ll left, ll right)
{
if ((right < start) || (end < left))
return 0;
if ((left <= start) && (end <= right))
return tree[node];
int mid = (start + end) / 2;
return sum(tree, node * 2, start, mid, left, right) + sum(tree, node * 2 + 1, mid + 1, end, left, right);
}
int main()
{
-ios::sync_with_stdio(false);
cin.tie(NULL);
int n, m, k;
cin >> n >> m >> k;
int h = (int)ceil(log2(n));
int tree_size = (1 << (h + 1));
vector<ll> v(n);
vector<ll> tree(tree_size);
for (int i = 0; i < n; i++)
cin >> v[i];
init(v, tree, 1, 0, n - 1);
for (int i = 0; i <= m + k - 1; i++)
{
ll a, b, c;
cin >> a >> b >> c;
if (a == 1)
{
ll diff = c - v[b - 1];
v[b - 1] = c;
update(tree, 1, 0, n - 1, b - 1, diff);
}
else if (a == 2)
{
cout << sum(tree, 1, 0, n - 1, b - 1, c - 1) << '\n';
}
}
} | [
"shinbian11@naver.com"
] | shinbian11@naver.com |
a230b9487cbcd2a65c714e27c04114ad0d968b5b | 8ee0be0b14ec99858712a5c37df4116a52cb9801 | /Client/Sound/MusicMgr.cpp | 1243d0827508eb0699f8f06fe2bc16d573a1088b | [] | no_license | eRose-DatabaseCleaning/Sources-non-evo | 47968c0a4fd773d6ff8c9eb509ad19caf3f48d59 | 2b152f5dba3bce3c135d98504ebb7be5a6c0660e | refs/heads/master | 2021-01-13T14:31:36.871082 | 2019-05-24T14:46:41 | 2019-05-24T14:46:41 | 72,851,710 | 6 | 3 | null | 2016-11-14T23:30:24 | 2016-11-04T13:47:51 | C++ | UTF-8 | C++ | false | false | 1,704 | cpp | #include "stdafx.h"
#include ".\musicmgr.h"
#include "MusicPlayer.h"
#include "DirectMusicPlayer.h"
#include "OggMusicPlayer.h"
#include "MSSMusicPlayer.h"
/// for singleton
CMusicMgr _MusicMgr;
CMusicMgr::CMusicMgr(void)
{
m_pPlayer = NULL;
m_bReadyDevice = false;
}
CMusicMgr::~CMusicMgr(void)
{
}
bool CMusicMgr::Init( PLAYER_TYPE playerType )
{
Clear();
switch( playerType )
{
case DIRECT_MUSIC_TYPE:
m_pPlayer = new CDirectMusicPlayer();
break;
case OGG_MUSIC_TYPE:
m_pPlayer = new COggMusicPlayer();
break;
case MSS_MUSIC_TYPE:
m_pPlayer = new CMSSMusicPlayer();
break;
}
if( m_pPlayer->Init() == false )
{
m_bReadyDevice = false;
return false;
}
m_bReadyDevice = true;
return true;
}
void CMusicMgr::Clear()
{
if( m_pPlayer )
{
delete m_pPlayer;
m_pPlayer = NULL;
}
m_bReadyDevice = false;
}
bool CMusicMgr::Play( const char* fName )
{
if( m_bReadyDevice )
{
if( m_pPlayer )
{
return m_pPlayer->Play( fName );
}
}
return false;
}
void CMusicMgr::Stop()
{
if( m_bReadyDevice )
{
if( m_pPlayer )
{
m_pPlayer->Stop();
}
}
}
void CMusicMgr::Run()
{
if( m_bReadyDevice )
{
if( m_pPlayer )
{
m_pPlayer->Run();
}
}
}
void CMusicMgr::Pause()
{
if( m_bReadyDevice )
{
if( m_pPlayer )
{
m_pPlayer->Pause( );
}
}
}
void CMusicMgr::SetVolume( long lVolume )
{
if( m_bReadyDevice )
{
if( m_pPlayer )
{
m_pPlayer->SetVolume( lVolume );
}
}
}
void CMusicMgr::HandleEvent()
{
if( m_bReadyDevice )
{
if( m_pPlayer )
{
m_pPlayer->HandleEvent();
}
}
} | [
"hugo.delannoy@hotmail.com"
] | hugo.delannoy@hotmail.com |
741b7aa20feedd1995b2de431dcd3caddeb0d55a | adb0c7140f0a53f81aae6cd948975f48e91baaaa | /APG4b/4-5/0-memory.cpp | 797246c027e1914354118425454d58abe0646443 | [] | no_license | ncyamane/atcoder | f6a7d5c8d6cee5d7f923fb41fc2b4a734230079f | 5441ac19d8a99fc17271c9889d9d813102623cbf | refs/heads/master | 2022-11-24T18:38:19.549233 | 2020-08-02T15:13:12 | 2020-08-02T15:13:12 | 259,620,549 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 94 | cpp | #include <bits/stdc++.h>
using namespace std;
int main() { cout << sizeof(int32_t) << endl; } | [
"chabajunsei@gmail.com"
] | chabajunsei@gmail.com |
8bdf47ea5db2224b2543ece0835c371d3a52d8fe | 89d4bbfe996fc2eb01c905006477e550ab503ba8 | /src/util/network.cpp | 37fa82fddd096bf65d99b174c42b9f82c9e7e8ec | [
"LicenseRef-scancode-unknown-license-reference",
"PHP-3.01",
"Zend-2.0"
] | permissive | huzhiguang/hiphop-php_20121224_stable | 77baf7b391c8a0a5840109016a0a7b1669d82aa3 | ce84927f05ec524ded40fc9918fdc22dbb8aeb91 | refs/heads/master | 2020-06-04T08:05:59.831789 | 2013-08-07T07:58:57 | 2013-08-07T07:58:57 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,773 | cpp | /*
+----------------------------------------------------------------------+
| HipHop for PHP |
+----------------------------------------------------------------------+
| Copyright (c) 2010- Facebook, Inc. (http://www.facebook.com) |
+----------------------------------------------------------------------+
| This source file is subject to version 3.01 of the PHP license, |
| that is bundled with this package in the file LICENSE, and is |
| available through the world-wide-web at the following url: |
| http://www.php.net/license/3_01.txt |
| If you did not receive a copy of the PHP license and are unable to |
| obtain it through the world-wide-web, please send a note to |
| license@php.net so we can mail you a copy immediately. |
+----------------------------------------------------------------------+
*/
#include "network.h"
#include "lock.h"
#include "process.h"
#include "util.h"
#include <netinet/in.h>
#include <arpa/nameser.h>
#include <resolv.h>
#include <net/if.h>
#include <sys/ioctl.h>
namespace HPHP {
///////////////////////////////////////////////////////////////////////////////
// without calling res_init(), any call to getaddrinfo() may leak memory:
// http://sources.redhat.com/ml/libc-hacker/2004-02/msg00049.html
class ResolverLibInitializer {
public:
ResolverLibInitializer() {
res_init();
// We call sethostent with stayopen = 1 to keep /etc/hosts open across calls
// to prevent mmap contention inside the kernel. Two calls are necessary to
// properly initialize the stayopen flag in glibc.
sethostent(1);
sethostent(1);
}
};
static ResolverLibInitializer _resolver_lib_initializer;
///////////////////////////////////////////////////////////////////////////////
// thread-safe network functions
std::string Util::safe_inet_ntoa(struct in_addr &in) {
char buf[256];
memset(buf, 0, sizeof(buf));
inet_ntop(AF_INET, &in, buf, sizeof(buf)-1);
return buf;
}
bool Util::safe_gethostbyname(const char *address, HostEnt &result) {
#if defined(__APPLE__)
struct hostent *hp = gethostbyname(address);
if (!hp) {
return false;
}
result.hostbuf = *hp;
freehostent(hp);
return true;
#else
struct hostent *hp;
int res;
size_t hstbuflen = 1024;
result.tmphstbuf = (char*)malloc(hstbuflen);
while ((res = gethostbyname_r(address, &result.hostbuf, result.tmphstbuf,
hstbuflen, &hp, &result.herr)) == ERANGE) {
hstbuflen *= 2;
result.tmphstbuf = (char*)realloc(result.tmphstbuf, hstbuflen);
}
return !res && hp;
#endif
}
///////////////////////////////////////////////////////////////////////////////
std::string Util::GetPrimaryIP() {
struct utsname buf;
uname((struct utsname *)&buf);
HostEnt result;
if (!safe_gethostbyname(buf.nodename, result)) {
return buf.nodename;
}
struct in_addr in;
memcpy(&in.s_addr, *(result.hostbuf.h_addr_list), sizeof(in.s_addr));
return safe_inet_ntoa(in);
}
/** yfliulei@360buy.com on 2012-11-2
original method(GetPrimaryIP) has a problem:
on machine: 192.168.12.34 (hostname: BP-YZH-1-xxxx.360buy.com)
output:
IP Address : 202.106.199.39
so it is need to write a new emthod
*/
std::string Util::GetPrimaryIP_ioctl() {
int s ;
struct ifconf conf;
struct ifreq *ifr;
char buff[BUFSIZ];
int num ;
int i ;
std::string sPrimaryIP ;
s = socket(PF_INET, SOCK_DGRAM, 0);
conf.ifc_len = BUFSIZ;
conf.ifc_buf = buff;
ioctl(s, SIOCGIFCONF, &conf);
num = conf.ifc_len / sizeof(struct ifreq);
ifr = conf.ifc_req;
for (i = 0; i < num; i++) {
struct sockaddr_in *sin = (struct sockaddr_in *) (&ifr->ifr_addr);
ioctl(s, SIOCGIFFLAGS, ifr);
if (((ifr->ifr_flags & IFF_LOOPBACK) == 0) && (ifr->ifr_flags & IFF_UP) && ifr->ifr_name) {
sPrimaryIP.append(inet_ntoa(sin->sin_addr)) ;
break ;
}
ifr++;
}
return sPrimaryIP ;
}
bool Util::GetNetworkStats(const char *iface, int &in_bps, int &out_bps) {
ASSERT(iface && *iface);
const char *argv[] = {"", "1", "1", "-n", "DEV", NULL};
string out;
Process::Exec("sar", argv, NULL, out);
vector<string> lines;
Util::split('\n', out.c_str(), lines, true);
for (unsigned int i = 0; i < lines.size(); i++) {
string &line = lines[i];
if (line.find(iface) != string::npos) {
vector<string> fields;
Util::split(' ', line.c_str(), fields, true);
if (fields[1] == iface) {
in_bps = atoll(fields[4].c_str());
out_bps = atoll(fields[5].c_str());
return true;
}
}
}
return false;
}
///////////////////////////////////////////////////////////////////////////////
}
| [
"huzhiguang@jd.com"
] | huzhiguang@jd.com |
1695984adfe30c2729acd1aee35fab3d5aaf55ec | d352af82d968c645f5566ba31d809b811a229e1c | /src/geometry/Mesh.cc | 0af9b54d2b54748afa4e277f9f52d6b8718d2f3d | [
"MIT"
] | permissive | robertsj/libdetran | 9b20ce691cc8eaa84e3845483ac6ae9f80da40ce | be5e1cd00fecf3a16669d8e81f29557939088628 | refs/heads/dev | 2023-01-21T16:53:09.485828 | 2023-01-16T16:38:38 | 2023-01-16T16:38:38 | 3,748,964 | 8 | 10 | MIT | 2023-01-26T14:22:09 | 2012-03-17T16:28:54 | C++ | UTF-8 | C++ | false | false | 8,230 | cc | //----------------------------------*-C++-*-----------------------------------//
/**
* @file Mesh.cc
* @author Jeremy Roberts
* @brief Mesh class member definitions.
*/
//----------------------------------------------------------------------------//
#include "Mesh.hh"
#include <numeric>
#include <iostream>
namespace detran_geometry
{
//----------------------------------------------------------------------------//
Mesh::Mesh(size_t dim,
vec_int xfm,
vec_int yfm,
vec_int zfm,
vec_dbl xcme,
vec_dbl ycme,
vec_dbl zcme,
vec_int mat_map)
: d_dimension(dim)
, d_xfm(xfm)
, d_yfm(yfm)
, d_zfm(zfm)
, d_xcme(xcme)
, d_ycme(ycme)
, d_zcme(zcme)
{
Require(mat_map.size() == d_xfm.size()*d_yfm.size()*d_zfm.size());
// Setup discretizations, etc.
setup();
// Set the coarse mesh material map.
std::string s = "MATERIAL";
add_coarse_mesh_map(s, mat_map);
}
//----------------------------------------------------------------------------//
Mesh::Mesh(size_t dim,
vec_dbl xfme,
vec_dbl yfme,
vec_dbl zfme,
vec_int mat_map)
: d_dimension(dim)
, d_xfm(vec_int(xfme.size()-1, 1))
, d_yfm(vec_int(yfme.size()-1, 1))
, d_zfm(vec_int(zfme.size()-1, 1))
, d_xcme(xfme)
, d_ycme(yfme)
, d_zcme(zfme)
{
// Setup discretizations, etc.
setup();
// Add the fine mesh material map.
Assert(mat_map.size() == d_number_cells);
std::string s = "MATERIAL";
add_mesh_map(s, mat_map);
}
//----------------------------------------------------------------------------//
void Mesh::add_coarse_mesh_map(std::string map_key, vec_int m_map)
{
// Temporary map.
vec_int tmp_m_map(d_number_cells, 0);
int i_save = 0; // place holders
int j_save = 0;
int k_save = 0;
for (size_t k = 0; k < d_zfm.size(); ++k)
{
// Fine mesh z range for this kth coarse mesh.
size_t k1 = k_save;
size_t k2 = k_save + d_zfm[k];
for (size_t j = 0; j < d_yfm.size(); ++j)
{
// Fine mesh x range for this jth coarse mesh.
size_t j1 = j_save;
size_t j2 = j_save + d_yfm[j];
for (size_t i = 0; i < d_xfm.size(); ++i)
{
// Fine mesh y range for this ith coarse mesh.
size_t i1 = i_save;
size_t i2 = i_save + d_xfm[i];
for (size_t kk = k1; kk < k2; ++kk)
{
for (size_t jj = j1; jj < j2; ++jj)
{
for (size_t ii = i1; ii < i2; ++ii)
{
tmp_m_map[ii + jj * d_number_cells_x +
kk * d_number_cells_x * d_number_cells_y] =
m_map[i + j * d_xfm.size() + k * d_xfm.size()*d_yfm.size()];
}
}
}
i_save = std::accumulate(d_xfm.begin(), d_xfm.begin() + i + 1, 0);
}
i_save = 0;
j_save = std::accumulate(d_yfm.begin(), d_yfm.begin() + j + 1, 0);
}
j_save = 0;
k_save = std::accumulate(d_zfm.begin(), d_zfm.begin() + k + 1, 0);
}
add_mesh_map(map_key, tmp_m_map);
return;
}
//----------------------------------------------------------------------------//
void Mesh::add_mesh_map(std::string map_key, vec_int mesh_map)
{
Require(!map_key.empty());
Require(mesh_map.size() == d_number_cells);
// Erase the value associated with the key if it exists.
mesh_map_type::iterator it;
it = d_mesh_map.find(map_key);
if (it != d_mesh_map.end())
d_mesh_map.erase(it);
// Add the new value.
d_mesh_map[map_key] = mesh_map;
}
//----------------------------------------------------------------------------//
bool Mesh::mesh_map_exists(std::string map_key)
{
mesh_map_type::iterator iter;
iter = d_mesh_map.find(map_key);
if (iter != d_mesh_map.end())
return true;
else
return false;
}
//----------------------------------------------------------------------------//
const Mesh::vec_int& Mesh::mesh_map(std::string map_key)
{
Insist(mesh_map_exists(map_key), "Mesh map key not found:" + map_key);
return d_mesh_map[map_key];
}
//----------------------------------------------------------------------------//
void Mesh::setup()
{
// Preconditions
Require(d_xfm.size() > 0);
Require(d_yfm.size() > 0);
Require(d_zfm.size() > 0);
Require(d_xcme.size() == d_xfm.size()+1);
Require(d_ycme.size() == d_yfm.size()+1);
Require(d_zcme.size() == d_zfm.size()+1);
for (size_t i = 0; i < d_xfm.size(); ++i)
{
Require(d_xfm[i] > 0);
}
for (size_t i = 0; i < d_yfm.size(); ++i)
{
Require(d_yfm[i] > 0);
}
for (size_t i = 0; i < d_zfm.size(); ++i)
{
Require(d_zfm[i] > 0);
}
// Compute numbers of cells.
d_number_cells_x = std::accumulate(d_xfm.begin(), d_xfm.end(), 0);
d_number_cells_y = std::accumulate(d_yfm.begin(), d_yfm.end(), 0);
d_number_cells_z = std::accumulate(d_zfm.begin(), d_zfm.end(), 0);
d_number_cells = d_number_cells_x * d_number_cells_y * d_number_cells_z;
// Cell widths.
d_dx.resize(d_number_cells_x, 0.0);
d_dy.resize(d_number_cells_y, 0.0);
d_dz.resize(d_number_cells_z, 0.0);
// Total domain widths
d_total_width_x = d_xcme[d_xcme.size()-1] - d_xcme[0];
d_total_width_y = d_ycme[d_ycme.size()-1] - d_ycme[0];
d_total_width_z = d_zcme[d_zcme.size()-1] - d_zcme[0];
if (dimension() < 3)
d_total_width_z = 1.0;
if (dimension() < 2)
d_total_width_y = 1.0;
// Discretize.
int ph = 0; // place holder
for (size_t i = 0; i < d_xfm.size(); ++i)
{
// Fine mesh x range for this Ith coarse mesh.
size_t i1 = ph;
size_t i2 = ph + d_xfm[i];
for (size_t ii = i1; ii < i2; ++ii)
d_dx[ii] = (d_xcme[i + 1] - d_xcme[i]) / d_xfm[i];
ph = std::accumulate(d_xfm.begin(), d_xfm.begin() + i + 1, 0);
}
ph = 0;
for (size_t j = 0; j < d_yfm.size(); j++)
{
// Fine mesh y range for this Jth coarse mesh.
size_t j1 = ph;
size_t j2 = ph + d_yfm[j];
for (size_t jj = j1; jj < j2; jj++)
{
Assert(jj < d_number_cells_y);
d_dy[jj] = (d_ycme[j + 1] - d_ycme[j]) / d_yfm[j];
}
ph = std::accumulate(d_yfm.begin(), d_yfm.begin() + j + 1, 0);
}
ph = 0;
for (size_t k = 0; k < d_zfm.size(); k++)
{
// Fine mesh z range for this Kth coarse mesh.
int k1 = ph;
int k2 = ph + d_zfm[k];
for (int kk = k1; kk < k2; kk++)
d_dz[kk] = (d_zcme[k + 1] - d_zcme[k]) / d_zfm[k];
ph = std::accumulate(d_zfm.begin(), d_zfm.begin() + k + 1, 0);
}
}
//----------------------------------------------------------------------------//
void Mesh::display() const
{
using std::cout;
using std::endl;
cout << endl << "Detran Mesh" << endl;
cout << " dimension: " << d_dimension << endl;
cout << " number cells: " << d_number_cells << endl;
cout << " number x cells: " << d_number_cells_x << endl;
cout << " number y cells: " << d_number_cells_y << endl;
cout << " number z cells: " << d_number_cells_z << endl;
cout << " x width: " << d_total_width_x << endl;
cout << " y width: " << d_total_width_y << endl;
cout << " z width: " << d_total_width_z << endl;
cout << " x coarse mesh edges: " << endl << " ";
for (size_t i = 0; i < d_xcme.size(); i++)
{
cout << d_xcme[i] << " ";
}
cout << endl << " y coarse mesh edges: " << endl << " ";
for (size_t i = 0; i < d_ycme.size(); i++)
{
cout << d_ycme[i] << " ";
}
cout << endl << " z coarse mesh edges: " << endl << " ";
for (size_t i = 0; i < d_zcme.size(); i++)
{
cout << d_zcme[i] << " ";
}
cout << endl << " x fine mesh count: " << endl << " ";
for (size_t i = 0; i < d_xfm.size(); i++)
{
cout << d_xfm[i] << " ";
}
cout << endl << " y fine mesh count: " << endl << " ";
for (size_t i = 0; i < d_yfm.size(); i++)
{
cout << d_yfm[i] << " ";
}
cout << endl << " z fine mesh count: " << endl << " ";
for (size_t i = 0; i < d_zfm.size(); i++)
{
cout << d_zfm[i] << " ";
}
cout << endl << endl;
}
} // end namespace detran
//----------------------------------------------------------------------------//
// end of Mesh.cc
//----------------------------------------------------------------------------//
| [
"robertsj@mit.edu"
] | robertsj@mit.edu |
63a9043f005b273c83066ec924287f66fe387286 | 198fd283722a7b694f4adf88099f4838552423d4 | /ex-proposto-25.cpp | 1598d1f65ba591c5c83950ab6b0c3fbeceb766e2 | [] | no_license | ramonchiara/exercicios_c_cpp_ed_quarentena | 30c099dceca3a838650847bf19ab26c45d2683e2 | c26dcef2b02aec839fbe16a8283c2cb03045fcd8 | refs/heads/master | 2022-04-23T06:08:53.035531 | 2020-04-25T03:50:17 | 2020-04-25T03:50:17 | 257,489,826 | 1 | 0 | null | null | null | null | ISO-8859-1 | C++ | false | false | 5,388 | cpp | #include <iomanip>
#include <iostream>
#include <stdlib.h>
#include "ListaLinearVetor.h"
using namespace std;
#define MEDIA_MINIMA 6
struct Aluno {
string matricula;
string nome;
double p1, p2;
double media()
{
return (p1 + p2) / 2;
}
bool aprovado()
{
return media() >= MEDIA_MINIMA;
}
void leDados()
{
string p1s, p2s;
cout << "Matrícula: ";
getline(cin, matricula);
cout << "Nome: ";
getline(cin, nome);
cout << "P1: ";
getline(cin, p1s);
cout << "P2: ";
getline(cin, p2s);
p1 = atoi(p1s.c_str());
p2 = atoi(p2s.c_str());
}
void imprime()
{
cout << matricula << " - " << nome;
}
};
int procura(Lista<Aluno> &sala, string matricula)
{
int indice = -1;
for(int i = 0; i < sala.quantidade(); i++) {
Aluno aluno = sala.acesso(i);
if(aluno.matricula == matricula) {
indice = i;
break;
}
}
return indice;
}
int procuraPosicao(Lista<Aluno> &sala, string nome)
{
int indice = 0;
for(int i = 0; i < sala.quantidade(); i++) {
Aluno aluno = sala.acesso(i);
if(aluno.nome > nome) {
indice = i;
break;
}
}
return indice;
}
int listaAlunos(Lista<Aluno> &sala, bool aprovados)
{
int quantidade = 0;
for(int i = 0; i < sala.quantidade(); i++) {
Aluno aluno = sala.acesso(i);
if(aluno.aprovado() == aprovados) {
aluno.imprime();
cout << " - ";
cout << aluno.media();
cout << endl;
quantidade++;
}
}
return quantidade;
}
int main()
{
Lista<Aluno> sala(1000); // a sala pode ter, no máximo, 1000 alunos
bool sair = false;
do {
cout << "1 - Inserir aluno" << endl;
cout << "2 - Listar alunos" << endl;
cout << "3 - Consultar aluno" << endl;
cout << "4 - Atualizar aluno" << endl;
cout << "5 - Remover aluno" << endl;
cout << "6 - Listar alunos aprovados" << endl;
cout << "7 - Listar alunos reprovados" << endl;
cout << "8 - Sair" << endl;
cout << "Sua opção: ";
string opcao;
getline(cin, opcao);
cout << endl;
if(opcao == "1") {
if(sala.cheia()) {
cout << "Capacidade máxima atingida." << endl;
} else {
Aluno novo;
novo.leDados();
int indice = procura(sala, novo.matricula);
if(indice >= 0) {
cout << "Já existe aluno com essa matrícula." << endl;
} else {
int posicao = procuraPosicao(sala, novo.nome);
bool sucesso = sala.insere(novo, posicao);
if(sucesso) {
cout << "Aluno cadastrado." << endl;
} else {
cout << "Erro o cadastrar o aluno." << endl;
}
}
}
} else if(opcao == "2") {
if(sala.vazia()) {
cout << "Nenhum aluno cadastrado. Capacidade: " << sala.capacidade() << endl;
} else {
for(int i = 0; i < sala.quantidade(); i++) {
Aluno aluno = sala.acesso(i);
aluno.imprime();
cout << endl;
}
cout << "Quantidade de alunos: " << sala.quantidade() << endl;
}
} else if(opcao == "3") {
string matricula;
cout << "Matrícula: ";
getline(cin, matricula);
int indice = procura(sala, matricula);
if(indice < 0) {
cout << "Não foi encontrado um aluno com essa matrícula." << endl;
} else {
Aluno aluno = sala.acesso(indice);
aluno.imprime();
cout << " - P1: " << aluno.p1 << " - P2: " << aluno.p2 << endl;
}
} else if(opcao == "4") {
string matricula;
cout << "Matrícula: ";
getline(cin, matricula);
int indice = procura(sala, matricula);
if(indice < 0) {
cout << "Não foi encontrado um aluno com essa matrícula." << endl;
} else {
cout << "Entre com os novos dados: " << endl;
Aluno aluno;
aluno.leDados();
sala.atualiza(indice, aluno);
}
} else if(opcao == "5") {
string matricula;
cout << "Matrícula: ";
getline(cin, matricula);
int indice = procura(sala, matricula);
if(indice < 0) {
cout << "Não foi encontrado um aluno com essa matrícula." << endl;
} else {
sala.remover(indice);
}
} else if(opcao == "6") {
int quantidade = listaAlunos(sala, true);
cout << "Aluno aprovados: " << quantidade << endl;
} else if(opcao == "7") {
int quantidade = listaAlunos(sala, false);
cout << "Aluno reprovados: " << quantidade << endl;
} else if(opcao == "8") {
sair = true;
}
cout << endl;
} while(!sair);
}
| [
"ramonchiara@gmail.com"
] | ramonchiara@gmail.com |
24b84a9f9e492bbd9362254d899f6e1b0f7f66b3 | 8e03a46915ea742ef645bf67eca150495921879d | /modules/core/include/nt2/dsl/functions/reshaping/run.hpp | 49e64e10ebe6d00ca5c46535b892732c8e10dbee | [
"BSL-1.0"
] | permissive | Quanteek/nt2 | 03fb4da84c0e499b6426078fc58566df44cc7eee | 47009031c60cecc9c509f6b7595d6421acdfe811 | refs/heads/master | 2021-01-18T10:48:44.921773 | 2012-05-01T20:00:26 | 2012-05-01T20:00:26 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,882 | hpp | //==============================================================================
// Copyright 2003 - 2011 LASMEA UMR 6602 CNRS/Univ. Clermont II
// Copyright 2009 - 2011 LRI UMR 8623 CNRS/Univ Paris Sud XI
//
// Distributed under the Boost Software License, Version 1.0.
// See accompanying file LICENSE.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt
//==============================================================================
#ifndef NT2_DSL_FUNCTIONS_RESHAPING_RUN_HPP_INCLUDED
#define NT2_DSL_FUNCTIONS_RESHAPING_RUN_HPP_INCLUDED
#include <nt2/sdk/simd/category.hpp>
#include <nt2/dsl/functions/run.hpp>
#include <nt2/sdk/meta/reshaping_hierarchy.hpp>
namespace nt2 { namespace ext
{
//============================================================================
// reshaping expression forward to its inner member
//============================================================================
NT2_FUNCTOR_IMPLEMENTATION( nt2::tag::run_, tag::cpu_
, (A0)(Tag)(State)(Data)(N)
, ((node_<A0, reshaping_<Tag>, N>))
(generic_< integer_<State> >)
((unspecified_<Data>))
)
{
typedef typename boost::proto::result_of::child_c<A0&,0>::type base;
typedef typename meta::
call<nt2::tag::run_ ( base
, State const&
, Data const&
)
>::type result_type;
BOOST_FORCEINLINE result_type
operator()(A0& a0, State const& p, Data const& t) const
{
return nt2::run(boost::proto::child_c<0>(a0), p ,t);
}
};
} }
#endif
| [
"joel.falcou@lri.fr"
] | joel.falcou@lri.fr |
4055107bd89130a1fed405d988d4c73238bfb473 | 62c45c77da533177b2cf234733cf34f18dfaf94a | /elang/lir/transforms/stack_allocator.h | 99d07a88749476191820564541cf816c1a560a57 | [
"Apache-2.0"
] | permissive | eval1749/elang | ff76d95c0000ed1d61434b387d319f950f68509a | 5208b386ba3a3e866a5c0f0271280f79f9aac8c4 | refs/heads/master | 2020-04-29T17:44:53.579355 | 2015-12-11T18:51:34 | 2015-12-11T18:51:34 | 28,262,329 | 2 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,233 | h | // Copyright 2015 Project Vogue. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#ifndef ELANG_LIR_TRANSFORMS_STACK_ALLOCATOR_H_
#define ELANG_LIR_TRANSFORMS_STACK_ALLOCATOR_H_
#include <algorithm>
#include <set>
#include <unordered_map>
#include "base/macros.h"
#include "elang/base/zone_allocated.h"
#include "elang/base/zone_owner.h"
#include "elang/base/zone_vector.h"
#include "elang/lir/lir_export.h"
#include "elang/lir/value.h"
namespace elang {
namespace lir {
class Editor;
class ConflictMap;
class Instruction;
class StackAssignments;
//////////////////////////////////////////////////////////////////////
//
// StackAllocator
//
class ELANG_LIR_EXPORT StackAllocator final : public ZoneOwner {
public:
StackAllocator(const Editor* editor, StackAssignments* assignments);
~StackAllocator();
Value AllocationFor(Value vreg) const;
Value Allocate(Value vreg);
void AllocateForPreserving(Value physical);
void Assign(Value vreg, Value proxy);
void Free(Value vreg);
void Reallocate(Value vreg, Value proxy);
void Reset();
void TrackCall(Instruction* instruction);
private:
struct Slot : ZoneAllocated {
Value proxy;
ZoneVector<Value> users;
explicit Slot(Zone* zone) : users(zone) {}
};
struct SlotLess {
bool operator()(const Slot* a, const Slot* b) const {
return a->proxy.data < b->proxy.data;
}
};
// Returns |Slot| for |vreg| or null if unavailable.
Slot* FreeSlotFor(Value vreg) const;
// Returns true if users of |slot| are conflicted to |vreg|.
bool IsConflict(const Slot* slot, Value vreg) const;
// Returns newly allocated spill slot which can hold value of |type|.
Slot* NewSlot(Value type);
void TrackArgument(Value proxy);
int const alignment_;
StackAssignments* const assignments_;
const ConflictMap& conflict_map_;
std::set<Slot*, SlotLess> free_slots_;
std::set<Slot*, SlotLess> live_slots_;
int size_;
// Map virtual register to memory proxy.
std::unordered_map<Value, Slot*> slot_map_;
DISALLOW_COPY_AND_ASSIGN(StackAllocator);
};
} // namespace lir
} // namespace elang
#endif // ELANG_LIR_TRANSFORMS_STACK_ALLOCATOR_H_
| [
"eval1749@gmail.com"
] | eval1749@gmail.com |
21a22df6e8145d7384660a96f9005607addfd523 | dd80a584130ef1a0333429ba76c1cee0eb40df73 | /external/chromium_org/media/audio/audio_low_latency_input_output_unittest.cc | c0cfa6937cfc2e47a0473903d368abbcd2678454 | [
"MIT",
"BSD-3-Clause"
] | permissive | karunmatharu/Android-4.4-Pay-by-Data | 466f4e169ede13c5835424c78e8c30ce58f885c1 | fcb778e92d4aad525ef7a995660580f948d40bc9 | refs/heads/master | 2021-03-24T13:33:01.721868 | 2017-02-18T17:48:49 | 2017-02-18T17:48:49 | 81,847,777 | 0 | 2 | MIT | 2020-03-09T00:02:12 | 2017-02-13T16:47:00 | null | UTF-8 | C++ | false | false | 16,396 | cc | // Copyright (c) 2012 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "base/basictypes.h"
#include "base/environment.h"
#include "base/file_util.h"
#include "base/memory/scoped_ptr.h"
#include "base/message_loop/message_loop.h"
#include "base/path_service.h"
#include "base/synchronization/lock.h"
#include "base/test/test_timeouts.h"
#include "base/time/time.h"
#include "build/build_config.h"
#include "media/audio/audio_io.h"
#include "media/audio/audio_manager_base.h"
#include "media/audio/fake_audio_log_factory.h"
#include "media/base/seekable_buffer.h"
#include "testing/gmock/include/gmock/gmock.h"
#include "testing/gtest/include/gtest/gtest.h"
#if defined(USE_ALSA)
#include "media/audio/alsa/audio_manager_alsa.h"
#elif defined(OS_MACOSX)
#include "media/audio/mac/audio_manager_mac.h"
#elif defined(OS_WIN)
#include "media/audio/win/audio_manager_win.h"
#include "media/audio/win/core_audio_util_win.h"
#elif defined(OS_ANDROID)
#include "media/audio/android/audio_manager_android.h"
#else
#include "media/audio/fake_audio_manager.h"
#endif
namespace media {
#if defined(USE_ALSA)
typedef AudioManagerAlsa AudioManagerAnyPlatform;
#elif defined(OS_MACOSX)
typedef AudioManagerMac AudioManagerAnyPlatform;
#elif defined(OS_WIN)
typedef AudioManagerWin AudioManagerAnyPlatform;
#elif defined(OS_ANDROID)
typedef AudioManagerAndroid AudioManagerAnyPlatform;
#else
typedef FakeAudioManager AudioManagerAnyPlatform;
#endif
// Limits the number of delay measurements we can store in an array and
// then write to file at end of the WASAPIAudioInputOutputFullDuplex test.
static const size_t kMaxDelayMeasurements = 1000;
// Name of the output text file. The output file will be stored in the
// directory containing media_unittests.exe.
// Example: \src\build\Debug\audio_delay_values_ms.txt.
// See comments for the WASAPIAudioInputOutputFullDuplex test for more details
// about the file format.
static const char kDelayValuesFileName[] = "audio_delay_values_ms.txt";
// Contains delay values which are reported during the full-duplex test.
// Total delay = |buffer_delay_ms| + |input_delay_ms| + |output_delay_ms|.
struct AudioDelayState {
AudioDelayState()
: delta_time_ms(0),
buffer_delay_ms(0),
input_delay_ms(0),
output_delay_ms(0) {
}
// Time in milliseconds since last delay report. Typical value is ~10 [ms].
int delta_time_ms;
// Size of internal sync buffer. Typical value is ~0 [ms].
int buffer_delay_ms;
// Reported capture/input delay. Typical value is ~10 [ms].
int input_delay_ms;
// Reported render/output delay. Typical value is ~40 [ms].
int output_delay_ms;
};
// This class mocks the platform specific audio manager and overrides
// the GetMessageLoop() method to ensure that we can run our tests on
// the main thread instead of the audio thread.
class MockAudioManager : public AudioManagerAnyPlatform {
public:
MockAudioManager() : AudioManagerAnyPlatform(&fake_audio_log_factory_) {}
virtual ~MockAudioManager() {}
virtual scoped_refptr<base::MessageLoopProxy> GetMessageLoop() OVERRIDE {
return base::MessageLoop::current()->message_loop_proxy();
}
private:
FakeAudioLogFactory fake_audio_log_factory_;
DISALLOW_COPY_AND_ASSIGN(MockAudioManager);
};
// Test fixture class.
class AudioLowLatencyInputOutputTest : public testing::Test {
protected:
AudioLowLatencyInputOutputTest() {}
virtual ~AudioLowLatencyInputOutputTest() {}
AudioManager* audio_manager() { return &mock_audio_manager_; }
base::MessageLoopForUI* message_loop() { return &message_loop_; }
// Convenience method which ensures that we are not running on the build
// bots and that at least one valid input and output device can be found.
bool CanRunAudioTests() {
bool input = audio_manager()->HasAudioInputDevices();
bool output = audio_manager()->HasAudioOutputDevices();
LOG_IF(WARNING, !input) << "No input device detected.";
LOG_IF(WARNING, !output) << "No output device detected.";
return input && output;
}
private:
base::MessageLoopForUI message_loop_;
MockAudioManager mock_audio_manager_;
DISALLOW_COPY_AND_ASSIGN(AudioLowLatencyInputOutputTest);
};
// This audio source/sink implementation should be used for manual tests
// only since delay measurements are stored on an output text file.
// All incoming/recorded audio packets are stored in an intermediate media
// buffer which the renderer reads from when it needs audio for playout.
// The total effect is that recorded audio is played out in loop back using
// a sync buffer as temporary storage.
class FullDuplexAudioSinkSource
: public AudioInputStream::AudioInputCallback,
public AudioOutputStream::AudioSourceCallback {
public:
FullDuplexAudioSinkSource(int sample_rate,
int samples_per_packet,
int channels)
: sample_rate_(sample_rate),
samples_per_packet_(samples_per_packet),
channels_(channels),
input_elements_to_write_(0),
output_elements_to_write_(0),
previous_write_time_(base::TimeTicks::Now()) {
// Size in bytes of each audio frame (4 bytes for 16-bit stereo PCM).
frame_size_ = (16 / 8) * channels_;
// Start with the smallest possible buffer size. It will be increased
// dynamically during the test if required.
buffer_.reset(
new media::SeekableBuffer(0, samples_per_packet_ * frame_size_));
frames_to_ms_ = static_cast<double>(1000.0 / sample_rate_);
delay_states_.reset(new AudioDelayState[kMaxDelayMeasurements]);
}
virtual ~FullDuplexAudioSinkSource() {
// Get complete file path to output file in the directory containing
// media_unittests.exe. Example: src/build/Debug/audio_delay_values_ms.txt.
base::FilePath file_name;
EXPECT_TRUE(PathService::Get(base::DIR_EXE, &file_name));
file_name = file_name.AppendASCII(kDelayValuesFileName);
FILE* text_file = base::OpenFile(file_name, "wt");
DLOG_IF(ERROR, !text_file) << "Failed to open log file.";
VLOG(0) << ">> Output file " << file_name.value() << " has been created.";
// Write the array which contains time-stamps, buffer size and
// audio delays values to a text file.
size_t elements_written = 0;
while (elements_written <
std::min(input_elements_to_write_, output_elements_to_write_)) {
const AudioDelayState state = delay_states_[elements_written];
fprintf(text_file, "%d %d %d %d\n",
state.delta_time_ms,
state.buffer_delay_ms,
state.input_delay_ms,
state.output_delay_ms);
++elements_written;
}
base::CloseFile(text_file);
}
// AudioInputStream::AudioInputCallback.
virtual void OnData(AudioInputStream* stream,
const uint8* src, uint32 size,
uint32 hardware_delay_bytes,
double volume) OVERRIDE {
base::AutoLock lock(lock_);
// Update three components in the AudioDelayState for this recorded
// audio packet.
const base::TimeTicks now_time = base::TimeTicks::Now();
const int diff = (now_time - previous_write_time_).InMilliseconds();
previous_write_time_ = now_time;
if (input_elements_to_write_ < kMaxDelayMeasurements) {
delay_states_[input_elements_to_write_].delta_time_ms = diff;
delay_states_[input_elements_to_write_].buffer_delay_ms =
BytesToMilliseconds(buffer_->forward_bytes());
delay_states_[input_elements_to_write_].input_delay_ms =
BytesToMilliseconds(hardware_delay_bytes);
++input_elements_to_write_;
}
// Store the captured audio packet in a seekable media buffer.
if (!buffer_->Append(src, size)) {
// An attempt to write outside the buffer limits has been made.
// Double the buffer capacity to ensure that we have a buffer large
// enough to handle the current sample test scenario.
buffer_->set_forward_capacity(2 * buffer_->forward_capacity());
buffer_->Clear();
}
}
virtual void OnClose(AudioInputStream* stream) OVERRIDE {}
virtual void OnError(AudioInputStream* stream) OVERRIDE {}
// AudioOutputStream::AudioSourceCallback.
virtual int OnMoreData(AudioBus* audio_bus,
AudioBuffersState buffers_state) OVERRIDE {
base::AutoLock lock(lock_);
// Update one component in the AudioDelayState for the packet
// which is about to be played out.
if (output_elements_to_write_ < kMaxDelayMeasurements) {
int output_delay_bytes = buffers_state.hardware_delay_bytes;
#if defined(OS_WIN)
// Special fix for Windows in combination with Wave where the
// pending bytes field of the audio buffer state is used to
// report the delay.
if (!CoreAudioUtil::IsSupported()) {
output_delay_bytes = buffers_state.pending_bytes;
}
#endif
delay_states_[output_elements_to_write_].output_delay_ms =
BytesToMilliseconds(output_delay_bytes);
++output_elements_to_write_;
}
int size;
const uint8* source;
// Read the data from the seekable media buffer which contains
// captured data at the same size and sample rate as the output side.
if (buffer_->GetCurrentChunk(&source, &size) && size > 0) {
EXPECT_EQ(channels_, audio_bus->channels());
size = std::min(audio_bus->frames() * frame_size_, size);
EXPECT_EQ(static_cast<size_t>(size) % sizeof(*audio_bus->channel(0)), 0U);
audio_bus->FromInterleaved(
source, size / frame_size_, frame_size_ / channels_);
buffer_->Seek(size);
return size / frame_size_;
}
return 0;
}
virtual int OnMoreIOData(AudioBus* source,
AudioBus* dest,
AudioBuffersState buffers_state) OVERRIDE {
NOTREACHED();
return 0;
}
virtual void OnError(AudioOutputStream* stream) OVERRIDE {}
protected:
// Converts from bytes to milliseconds taking the sample rate and size
// of an audio frame into account.
int BytesToMilliseconds(uint32 delay_bytes) const {
return static_cast<int>((delay_bytes / frame_size_) * frames_to_ms_ + 0.5);
}
private:
base::Lock lock_;
scoped_ptr<media::SeekableBuffer> buffer_;
int sample_rate_;
int samples_per_packet_;
int channels_;
int frame_size_;
double frames_to_ms_;
scoped_ptr<AudioDelayState[]> delay_states_;
size_t input_elements_to_write_;
size_t output_elements_to_write_;
base::TimeTicks previous_write_time_;
};
class AudioInputStreamTraits {
public:
typedef AudioInputStream StreamType;
static AudioParameters GetDefaultAudioStreamParameters(
AudioManager* audio_manager) {
return audio_manager->GetInputStreamParameters(
AudioManagerBase::kDefaultDeviceId);
}
static StreamType* CreateStream(AudioManager* audio_manager,
const AudioParameters& params) {
return audio_manager->MakeAudioInputStream(params,
AudioManagerBase::kDefaultDeviceId);
}
};
class AudioOutputStreamTraits {
public:
typedef AudioOutputStream StreamType;
static AudioParameters GetDefaultAudioStreamParameters(
AudioManager* audio_manager) {
return audio_manager->GetDefaultOutputStreamParameters();
}
static StreamType* CreateStream(AudioManager* audio_manager,
const AudioParameters& params) {
return audio_manager->MakeAudioOutputStream(params, std::string(),
std::string());
}
};
// Traits template holding a trait of StreamType. It encapsulates
// AudioInputStream and AudioOutputStream stream types.
template <typename StreamTraits>
class StreamWrapper {
public:
typedef typename StreamTraits::StreamType StreamType;
explicit StreamWrapper(AudioManager* audio_manager)
:
audio_manager_(audio_manager),
format_(AudioParameters::AUDIO_PCM_LOW_LATENCY),
#if defined(OS_ANDROID)
channel_layout_(CHANNEL_LAYOUT_MONO),
#else
channel_layout_(CHANNEL_LAYOUT_STEREO),
#endif
bits_per_sample_(16) {
// Use the preferred sample rate.
const AudioParameters& params =
StreamTraits::GetDefaultAudioStreamParameters(audio_manager_);
sample_rate_ = params.sample_rate();
// Use the preferred buffer size. Note that the input side uses the same
// size as the output side in this implementation.
samples_per_packet_ = params.frames_per_buffer();
}
virtual ~StreamWrapper() {}
// Creates an Audio[Input|Output]Stream stream object using default
// parameters.
StreamType* Create() {
return CreateStream();
}
int channels() const {
return ChannelLayoutToChannelCount(channel_layout_);
}
int bits_per_sample() const { return bits_per_sample_; }
int sample_rate() const { return sample_rate_; }
int samples_per_packet() const { return samples_per_packet_; }
private:
StreamType* CreateStream() {
StreamType* stream = StreamTraits::CreateStream(audio_manager_,
AudioParameters(format_, channel_layout_, sample_rate_,
bits_per_sample_, samples_per_packet_));
EXPECT_TRUE(stream);
return stream;
}
AudioManager* audio_manager_;
AudioParameters::Format format_;
ChannelLayout channel_layout_;
int bits_per_sample_;
int sample_rate_;
int samples_per_packet_;
};
typedef StreamWrapper<AudioInputStreamTraits> AudioInputStreamWrapper;
typedef StreamWrapper<AudioOutputStreamTraits> AudioOutputStreamWrapper;
// This test is intended for manual tests and should only be enabled
// when it is required to make a real-time test of audio in full duplex and
// at the same time create a text file which contains measured delay values.
// The file can later be analyzed off line using e.g. MATLAB.
// MATLAB example:
// D=load('audio_delay_values_ms.txt');
// x=cumsum(D(:,1));
// plot(x, D(:,2), x, D(:,3), x, D(:,4), x, D(:,2)+D(:,3)+D(:,4));
// axis([0, max(x), 0, max(D(:,2)+D(:,3)+D(:,4))+10]);
// legend('buffer delay','input delay','output delay','total delay');
// xlabel('time [msec]')
// ylabel('delay [msec]')
// title('Full-duplex audio delay measurement');
TEST_F(AudioLowLatencyInputOutputTest, DISABLED_FullDuplexDelayMeasurement) {
if (!CanRunAudioTests())
return;
AudioInputStreamWrapper aisw(audio_manager());
AudioInputStream* ais = aisw.Create();
EXPECT_TRUE(ais);
AudioOutputStreamWrapper aosw(audio_manager());
AudioOutputStream* aos = aosw.Create();
EXPECT_TRUE(aos);
// This test only supports identical parameters in both directions.
// TODO(henrika): it is possible to cut delay here by using different
// buffer sizes for input and output.
if (aisw.sample_rate() != aosw.sample_rate() ||
aisw.samples_per_packet() != aosw.samples_per_packet() ||
aisw.channels()!= aosw.channels() ||
aisw.bits_per_sample() != aosw.bits_per_sample()) {
LOG(ERROR) << "This test requires symmetric input and output parameters. "
"Ensure that sample rate and number of channels are identical in "
"both directions";
aos->Close();
ais->Close();
return;
}
EXPECT_TRUE(ais->Open());
EXPECT_TRUE(aos->Open());
FullDuplexAudioSinkSource full_duplex(
aisw.sample_rate(), aisw.samples_per_packet(), aisw.channels());
VLOG(0) << ">> You should now be able to hear yourself in loopback...";
DVLOG(0) << " sample_rate : " << aisw.sample_rate();
DVLOG(0) << " samples_per_packet: " << aisw.samples_per_packet();
DVLOG(0) << " channels : " << aisw.channels();
ais->Start(&full_duplex);
aos->Start(&full_duplex);
// Wait for approximately 10 seconds. The user shall hear his own voice
// in loop back during this time. At the same time, delay recordings are
// performed and stored in the output text file.
message_loop()->PostDelayedTask(FROM_HERE,
base::MessageLoop::QuitClosure(), TestTimeouts::action_timeout());
message_loop()->Run();
aos->Stop();
ais->Stop();
// All Close() operations that run on the mocked audio thread,
// should be synchronous and not post additional close tasks to
// mocked the audio thread. Hence, there is no need to call
// message_loop()->RunUntilIdle() after the Close() methods.
aos->Close();
ais->Close();
}
} // namespace media
| [
"karun.matharu@gmail.com"
] | karun.matharu@gmail.com |
ebb97650f0a406c0d63bb85a1c09feb0dd67a1e0 | aa820beea2a4a7b863c6659bc997b1e30eb67211 | /common/drm/drmueventthread.h | fdf2b1ad3eeeae9b85a0633a212d4fb3861d8596 | [] | no_license | pyn1/temp | 10590ccc8bc9282ca2503a6b5621e5a42da904e7 | 7771f2c6770aa3115d12414dbdc1945e7f1403a8 | refs/heads/master | 2021-01-21T18:10:18.623958 | 2017-05-22T06:04:18 | 2017-05-22T06:04:18 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,055 | h | /*
// Copyright (c) 2017 Intel Corporation
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
*/
#ifndef COMMON_DRM_DRMUEVENTTHREAD_H
#define COMMON_DRM_DRMUEVENTTHREAD_H
#include "drm.h"
#include "hwcthread.h"
namespace hwcomposer {
class Drm;
class GpuDevice;
//*****************************************************************************
//
// DrmUEventThread class - responsible for handling HDMI uevents
//
//*****************************************************************************
class DrmUEventThread : public HWCThread
{
public:
DrmUEventThread(GpuDevice& device, Drm& drm);
virtual ~DrmUEventThread();
bool Initialize();
private:
//Thread functions
void HandleRoutine() override;
// Decode the most recent message and forward it to DRM for the appropriate displays.
// Returns -1 if not decoded.
int onUEvent( void );
// Decodes the most recent message into an event.
Drm::UEvent decodeUEvent( void );
private:
GpuDevice& mDevice;
// TODO: change to HotPlugListener
//Drm pointer
Drm& mDrm;
uint32_t mESDConnectorType;
uint32_t mESDConnectorID;
// Maximum supported message size.
static const int MSG_LEN = 256;
// UEvent file handle (opened in readyToRun).
int mUeventFd;
// Most recent read message.
char mUeventMsg[MSG_LEN];
// Most recent read message size.
size_t mUeventMsgSize;
};
}; // namespace hwcomposer
#endif // COMMON_DRM_DRMUEVENTTHREAD_H
| [
"kalyan.kondapally@intel.com"
] | kalyan.kondapally@intel.com |
a10b3085ce9f32460f1b0120fce32e4668b9d82a | a9636f0d96503b890f0f80d52de6fa7beb3ffe29 | /signal_analysis/visualdescriptor.h | 167c22037d729890a80ed5afab9db4a65c747f17 | [] | no_license | grigp/a-analyser | 5d14e8f91e2104fbc8ffbf47a28d20fd95eb667e | 026badde88531b13a788140f8a3e13f08d4a5371 | refs/heads/master | 2023-09-01T08:09:35.475413 | 2023-06-14T11:37:22 | 2023-06-14T11:37:22 | 244,710,881 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 896 | h | #ifndef VISUALDESCRIPTOR_H
#define VISUALDESCRIPTOR_H
#include <QObject>
#include "basedefines.h"
class Visual;
/*!
* \brief Класс описателя визуализаторов The VisualDescriptor class
*/
class VisualDescriptor
{
public:
VisualDescriptor(BaseDefines::TestLevel level);
virtual ~VisualDescriptor();
virtual QString uid() = 0;
virtual QString name() = 0;
virtual Visual* getVisualWidget(QWidget *parent = nullptr,
const QString& testUid = "",
const QString& probeUid = "",
const QString& channelId = "",
const QString& sectionNumber = "") = 0;
BaseDefines::TestLevel level() {return m_level;}
private:
BaseDefines::TestLevel m_level {BaseDefines::tlNone};
};
#endif // VISUALDESCRIPTOR_H
| [
"grig_p@mail.ru"
] | grig_p@mail.ru |
1747386c1f11fe062b29c4d056c54937f37d6b33 | 5552798e3562cad0b615b6141f8ea33214bba861 | /C++/Algorithm/toposort.cpp | 9043c1630255503442e10d3f0ff4cd6071bd745c | [] | no_license | YashSharma/C-files | 3922994cf7f0f5947173aa2b26a7dc399919267b | 3d7107e16c428ee056814b33ca9b89ab113b0753 | refs/heads/master | 2016-08-12T09:16:25.499792 | 2015-12-20T08:24:47 | 2015-12-20T08:24:47 | 48,312,664 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,292 | cpp | #include<iostream>
#include<list>
#include<stack>
using namespace std;
class Graph
{ int V;
list<int> *adj;
void topologicalSortUtil(int v,bool visited[],stack<int> &stack);
public:
Graph(int V);
void addEdge(int v,int w);
void topologicalSort();
};
Graph::Graph(int V)
{ this->V=V;
adj=new list<int>[V];
}
void Graph::addEdge(int v,int w)
{ adj[v].push_back(w);
}
void Graph::topologicalSortUtil(int v,bool visited[],stack<int> &Stack)
{ visited[v]=true;
list<int>::iterator i;
for(i=adj[v].begin();i!=adj[v].end();i++)
{ if(!visited[*i])
topologicalSortUtil(*i,visited,Stack);
}
Stack.push(v);
}
void Graph::topologicalSort()
{ stack<int> Stack;
bool* visited=new bool[V];
for(int i=0;i<V;i++)
visited[i]=false;
for(int i=0;i<V;i++)
{ if(!visited[i])
topologicalSortUtil(i,visited,Stack);
}
while(Stack.empty()==false)
{ cout<<Stack.top()<<" ";
Stack.pop();
}
printf("\n");
}
int main()
{ Graph g(6);
g.addEdge(5, 2);
g.addEdge(5, 0);
g.addEdge(4, 0);
g.addEdge(4, 1);
g.addEdge(2, 3);
g.addEdge(3, 1);
cout << "Following is a Topological Sort of the given graph \n";
g.topologicalSort();
return 0;
} | [
"Apple@Yash-MacBook-Air.local"
] | Apple@Yash-MacBook-Air.local |
a09c79307e48b0d6b1bfeb22ccc950ecc74e76ea | 76c907dc1e769e0da1a357f49af1a676bc1c01a2 | /codechef/LONG JUNE16/FRJUMPEditorialCode.cpp | 0a6827167e491347499f072366557f06c72827ef | [] | no_license | sandeepnmenon/Competitive-Coding | 771a6e9a3a81768db030096a72ab220311328ebf | 5f6adaaf6059d56dbd9f3dfb667648db6724bd31 | refs/heads/master | 2022-12-15T20:33:20.347480 | 2022-12-06T02:25:59 | 2022-12-06T02:25:59 | 33,935,722 | 0 | 0 | null | 2022-07-09T05:27:29 | 2015-04-14T14:11:31 | C++ | UTF-8 | C++ | false | false | 3,032 | cpp | #include<bits/stdc++.h>
#define Nmax 100
#define ll long long
using namespace std;
const int nmax = 100010;
const int inf = 1000000007;
int n, a[nmax], q, type, pos, val, step;
ll remain[nmax], rem;
long double dig[nmax];
int sq;
ll binpow(ll a, ll b, ll c){
ll r =1 ;
while (b){
if (b&1) r*=a;
a*=a;
r%=c;
a%=c;
b>>=1;
}
return r;
}
ll inverse(ll a){
return binpow(a, inf-2, inf);
}
int main()
{
srand(time(0));
scanf("%d\n", &n);
sq = sqrt(n+0.0)+1;
for (int i=1; i<=n; i++) {
scanf("%d", a+i);
}
for (int j=1; j<=sq; j++){
pos = 1;
rem = 1;
long double sum=0;
//sum=log10(a[1]*a[1+j]*a[1+j+j]*a[1+j+j+j]...)=log10(a[1])+log10(a[1+j])+log10(a[1+j+j])....
while (pos<=n){
sum+=log10(a[pos]);
rem = (rem*a[pos])%inf;
pos+=j;
}
remain[j] = rem;
dig[j] = sum;
}
scanf("%d", &q);
//We have 2 parts
//if step is more that sqrt(n) - brute force
//else will just output the answer precalculated earlier
//also during all updates we should maintain our "precalculation" structure
while (q--){
scanf("%d", &type);
if (type==1){
scanf("%d %d", &pos, &val);
ll inv = inverse(a[pos]); //Inverse element for a[pos]
if (pos==1) {
for (int i=1; i<=sq; i++){
remain[i]*=inv;
remain[i]%=inf;
remain[i]*=val;
remain[i]%=inf;
dig[i]-=log10(a[1]+0.0);
dig[i]+=log10(val+0.0);
}
} else {
for (int i=1; i<=min(pos-1, sq); i++){
if ((pos-1)%i==0){
dig[i]-=log10(a[pos]+0.0);
dig[i]+=log10(val+0.0);
remain[i]*=inv;
remain[i]%=inf;
remain[i]*=val;
remain[i]%=inf;
}
}
}
a[pos]=val;
} else
{
scanf("%d", &step);
if (step>sq){
rem = 1;
pos = 1;
long double sum=0;
while (pos<=n){
sum+=log10(a[pos]+0.0);
rem = (rem*a[pos])%inf;
pos+=step;
}
rem = (rem+inf)%inf;
int first = (int)(pow(10.0, sum-floor(sum))+0.000000001);
if (first==10) first=1;
printf("%d %d\n", first, rem);
//cout << first << " " << rem << endl;
}
else {
int first = (int)(pow(10.0, dig[step]-floor(dig[step]))+0.000000001);
if (first==10) first=1;
printf("%d %d\n", first, remain[step]);
//cout << first << " " << remain[step] << endl;
}
}
}
}
| [
"sandeep.n.menon@ieee.org"
] | sandeep.n.menon@ieee.org |
d864d887a12e2a23774e9fd67548587183fcebfb | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/wget/hunk_3453.cpp | bccc48c270b6ba66a19aa62554a3355ed10a1c51 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,300 | cpp | xfree (mynewloc);
mynewloc = xstrdup (newloc_parsed->url);
- if (!redirections)
- {
- redirections = make_string_hash_table (0);
- /* Add current URL immediately so we can detect it as soon
- as possible in case of a cycle. */
- string_set_add (redirections, u->url);
- }
-
- /* The new location is OK. Check for max. number of
- redirections. */
+ /* Check for max. number of redirections. */
if (++redirection_count > MAX_REDIRECTIONS)
{
logprintf (LOG_NOTQUIET, _("%d redirections exceeded.\n"),
MAX_REDIRECTIONS);
url_free (newloc_parsed);
url_free (u);
- if (redirections)
- string_set_free (redirections);
- xfree (url);
- xfree (mynewloc);
- return WRONGCODE;
- }
-
- /*Check for redirection cycle by
- peeking through the history of redirections. */
- if (string_set_contains (redirections, newloc_parsed->url))
- {
- logprintf (LOG_NOTQUIET, _("%s: Redirection cycle detected.\n"),
- mynewloc);
- url_free (newloc_parsed);
- url_free (u);
- if (redirections)
- string_set_free (redirections);
xfree (url);
xfree (mynewloc);
return WRONGCODE;
}
- string_set_add (redirections, newloc_parsed->url);
xfree (url);
url = mynewloc;
| [
"993273596@qq.com"
] | 993273596@qq.com |
7bad8c0ca35b2082420499836f26c91287cb2b73 | 5d83739af703fb400857cecc69aadaf02e07f8d1 | /Archive2/f8/10978159d62730/main.cpp | ed98475e8cbeaff89e18340f39e2854f0ebc9158 | [] | 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 | 196 | cpp | #include <iostream>
int called_once()
{
std::cout << "1";
return 0;
}
void call()
{
static int x = called_once();
(void)x;
}
int main()
{
call();
call();
call();
} | [
"francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df"
] | francis.rammeloo@36614edc-3e3a-acb8-9062-c8ae0e4185df |
a24faf1fad75794f81e1c906ad9533cf8d1ce146 | 04230fbf25fdea36a2d473233e45df21b6ff6fff | /1462-D.cpp | 13617488996ab363e3698c5da8e9496b2a206f55 | [
"MIT"
] | permissive | ankiiitraj/questionsSolved | 48074d674bd39fe67da1f1dc7c944b95a3ceac34 | 8452b120935a9c3d808b45f27dcdc05700d902fc | refs/heads/master | 2021-07-22T10:16:13.538256 | 2021-02-12T11:51:47 | 2021-02-12T11:51:47 | 241,689,398 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,683 | cpp | #include <bits/stdc++.h>
#include <time.h>
#define int long long int
#define pb push_back
#define mem(a, x) memset(a, x, sizeof a)
#define all(a) a.begin(), a.end()
#define scnarr(a, n) for (int i = 0; i < n; ++i) cin >> a[i]
#define vi vector<int>
#define si set<int>
#define pii pair <int, int>
#define sii set<pii>
#define vii vector<pii>
#define mii map <int, int>
#define faster ios_base::sync_with_stdio(false); cin.tie(NULL); cout.tie(NULL)
using namespace std;
using namespace chrono;
/*
----------------------------------------------------------------------
Things to remember : check for coners n = 1, pass references instead
*/
/* -------------------------------Solution Sarted--------------------------------------*/
//Constants
const int MOD = 1000000007; // 1e9 + 7
const int MAXN = 1000005; // 1e6 +5
const int INF = 100000000000005; // 1e15 +5
void solve(){
int n, res = INF;
cin >> n;
vi a(n +1), pref(n +1, 0);
for(int i = 1; i <= n; ++i){
cin >> a[i];
pref[i] = pref[i -1] + a[i];
}
for(int i = 1; i <= n; ++i){
int sum = pref[i], prev = i;
int cur = i -1;
for(int j = prev +1; j <= n; ++j){
if(pref[j] - pref[prev] == sum){
cur += j - prev -1;
prev = j;
}
}
if(prev == n)
res = min(res, cur);
}
cout << res << endl;
return;
}
signed main()
{
faster;
#ifndef ONLINE_JUDGE
freopen("ip.txt", "r", stdin);
freopen("op.txt", "w", stdout);
#endif
int t; cin >> t; while(t--)
solve();
return 0;
}
//Author : Ankit Raj
//Problem Link :
/*Snippets*/
/*
sieve - prime factorization using sieve and primes in range
zpower - pow with mod
plate - Initial template
bfs
dfs
fenwik - BIT
binary_search
segment_tree
*/
| [
"ankitatiiitr@gmail.com"
] | ankitatiiitr@gmail.com |
1abe92a3107cee8dc43756f332bfbc4ea6d27ffb | 480bcc3f1f7aa1a1aefc31adf11cd1a669a07403 | /Lw5/rational/rational/CRational.cpp | ed8a071dd93961dade893cc444f6edd086fb0260 | [] | no_license | KrovYR/oop | 5e4993065c6c3c3e61c23f854f2eb8e47279a0bd | 1719f1622a401e3fbb40ef7c2795897e55383053 | refs/heads/master | 2022-11-14T09:51:30.224242 | 2020-07-13T13:57:16 | 2020-07-13T13:57:16 | 279,065,868 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 6,267 | cpp | #include "CRational.h"
CRational::CRational(int value)
{
m_numerator = value;
}
CRational::CRational(int numerator, int denominator)
{
m_numerator = numerator;
m_denominator = denominator;
Assign(numerator, denominator);
}
int CRational::GetNumerator() const
{
return m_numerator;
}
int CRational::GetDenominator() const
{
return m_denominator;
}
double CRational::ToDouble() const
{
const auto doublePrecisionNumerator = static_cast<double>(m_numerator);
return doublePrecisionNumerator / m_denominator;
}
std::pair<int, CRational> CRational::ToMixedFraction() const
{
const int integerPart = m_numerator / m_denominator;
const int fractionalPartNumerator = m_numerator - integerPart * m_denominator;
CRational fractionalPart = CRational(fractionalPartNumerator, m_denominator);
return { integerPart, fractionalPart };
}
const CRational CRational::operator+() const
{
return *this;
}
const CRational CRational::operator-() const
{
return CRational(-m_numerator, m_denominator);
}
const CRational CRational::operator+=(const CRational& addend)
{
const int addendNumerator = addend.GetNumerator();
const int addendDenominator = addend.GetDenominator();
if (!addendNumerator)
{
return *this;
}
const int numerator = m_numerator * addendDenominator + addendNumerator * m_denominator;
const int denominator = m_denominator * addendDenominator;
Assign(numerator, denominator);
return *this;
}
const CRational CRational::operator-=(const CRational& subtrahend)
{
const int subtrahendNumerator = subtrahend.GetNumerator();
const int subtrahendDenominator = subtrahend.GetDenominator();
if (!subtrahendNumerator)
{
return *this;
}
const int numerator = m_numerator * subtrahendDenominator - subtrahendNumerator * m_denominator;
const int denominator = m_denominator * subtrahendDenominator;
Assign(numerator, denominator);
return *this;
}
const CRational CRational::operator*=(const CRational& multiplier)
{
const int numerator = m_numerator * multiplier.GetNumerator();
const int denominator = m_denominator * multiplier.GetDenominator();
Assign(numerator, denominator);
return *this;
}
const CRational CRational::operator/=(const CRational& divider)
{
const int numerator = m_numerator * divider.GetDenominator();
const int denominator = m_denominator * divider.GetNumerator();
Assign(numerator, denominator);
return *this;
}
void CRational::Assign(int numerator, int denominator)
{
if (denominator == 0)
{
throw std::logic_error("Denominator must not be equal to zero");
}
if (denominator < 0)
{
numerator = -numerator;
denominator = -denominator;
}
m_numerator = numerator;
m_denominator = denominator;
Normalize();
}
void CRational::Normalize()
{
const auto getGreatestCommonDivisor = [](unsigned int a, unsigned int b) -> unsigned int {
while (b != 0)
{
std::swap(a, b);
b = b % a;
}
return (a != 0) ? a : 1;
};
const int greatestCommonDivisor = getGreatestCommonDivisor(abs(m_numerator), m_denominator);
m_numerator /= greatestCommonDivisor;
m_denominator /= greatestCommonDivisor;
}
const CRational operator+(const CRational& lhs, const CRational& rhs)
{
const int numerator = lhs.GetNumerator() * rhs.GetDenominator() + rhs.GetNumerator() * lhs.GetDenominator();
const int denominator = lhs.GetDenominator() * rhs.GetDenominator();
return CRational(numerator, denominator);
}
const CRational operator-(const CRational& lhs, const CRational& rhs)
{
const int numerator = lhs.GetNumerator() * rhs.GetDenominator() - rhs.GetNumerator() * lhs.GetDenominator();
const int denominator = lhs.GetDenominator() * rhs.GetDenominator();
return CRational(numerator, denominator);
}
const CRational operator*(const CRational& lhs, const CRational& rhs)
{
const int numerator = lhs.GetNumerator() * rhs.GetNumerator();
const int denominator = lhs.GetDenominator() * rhs.GetDenominator();
return CRational(numerator, denominator);
}
const CRational operator/(const CRational& lhs, const CRational& rhs)
{
const int numerator = lhs.GetNumerator() * rhs.GetDenominator();
const int denominator = lhs.GetDenominator() * rhs.GetNumerator();
return CRational(numerator, denominator);
}
const bool operator==(const CRational& lhs, const CRational& rhs)
{
const bool isNumeratorsEqual = lhs.GetNumerator() == rhs.GetNumerator();
const bool isDenominatorsEqual = lhs.GetDenominator() == rhs.GetDenominator();
return isNumeratorsEqual && isDenominatorsEqual;
}
const bool operator!=(const CRational& lhs, const CRational& rhs)
{
const bool isNumeratorsUnequal = lhs.GetNumerator() != rhs.GetNumerator();
const bool isDenominatorsUneEqual = lhs.GetDenominator() != rhs.GetDenominator();
return isNumeratorsUnequal || isDenominatorsUneEqual;
}
const bool operator<(const CRational& lhs, const CRational& rhs)
{
return (lhs.GetNumerator() * rhs.GetDenominator()) < (rhs.GetNumerator() * lhs.GetDenominator());
}
const bool operator>(const CRational& lhs, const CRational& rhs)
{
return (lhs.GetNumerator() * rhs.GetDenominator()) > (rhs.GetNumerator() * lhs.GetDenominator());
}
const bool operator<=(const CRational& lhs, const CRational& rhs)
{
return (lhs.GetNumerator() * rhs.GetDenominator()) <= (rhs.GetNumerator() * lhs.GetDenominator());
}
const bool operator>=(const CRational& lhs, const CRational& rhs)
{
return (lhs.GetNumerator() * rhs.GetDenominator()) >= (rhs.GetNumerator() * lhs.GetDenominator());
}
std::ostream& operator<<(std::ostream& output, const CRational& number)
{
output << number.GetNumerator() << "/" << number.GetDenominator();
return output;
}
std::istream& operator>>(std::istream& stream, CRational& number)
{
int numerator = 0;
int denominator = 1;
if ((stream >> numerator) && (stream.get() == '/') && (stream >> denominator))
{
number = CRational(numerator, denominator);
return stream;
}
stream.setstate(std::ios_base::failbit);
return stream;
} | [
"52441522+KrovYR@users.noreply.github.com"
] | 52441522+KrovYR@users.noreply.github.com |
0acef2dfea99ec6bc89428de6a9ef038acec4418 | 3c88e65e76d8a41fca5bc469eb99117b996711f2 | /pgadmin_old/pgadmin4-1.2/runtime/pgAdmin4.cpp | b1f470d811a7cfb1104e7ab91ea9eddf9810ee28 | [
"PostgreSQL"
] | permissive | luvres/alpine | 85591b77f0dbc328d89e028c22ef1479be33ffbe | 05dc3e77cc8c454143525fed79e38bc38fc390f7 | refs/heads/master | 2021-01-11T15:48:48.478244 | 2017-10-31T15:30:32 | 2017-10-31T15:30:32 | 79,933,463 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,971 | cpp | //////////////////////////////////////////////////////////////////////////
//
// pgAdmin 4 - PostgreSQL Tools
//
// Copyright (C) 2013 - 2017, The pgAdmin Development Team
// This software is released under the PostgreSQL Licence
//
// pgAdmin4.cpp - Main application entry point
//
//////////////////////////////////////////////////////////////////////////
#include "pgAdmin4.h"
// Must be before QT
#include <Python.h>
#if QT_VERSION >= 0x050000
#include <QtWidgets>
#else
#include <QApplication>
#include <QDebug>
#include <QtNetwork>
#include <QLineEdit>
#include <QInputDialog>
#include <QSplashScreen>
#endif
// App headers
#include "BrowserWindow.h"
#include "ConfigWindow.h"
#include "Server.h"
#include <QTime>
void delay( int milliseconds )
{
QTime endTime = QTime::currentTime().addMSecs( milliseconds );
while( QTime::currentTime() < endTime )
{
QCoreApplication::processEvents( QEventLoop::AllEvents, 100 );
}
}
int main(int argc, char * argv[])
{
// Create the QT application
QApplication app(argc, argv);
// Setup the settings management
QCoreApplication::setOrganizationName("pgadmin");
QCoreApplication::setOrganizationDomain("pgadmin.org");
QCoreApplication::setApplicationName(PGA_APP_NAME.toLower().replace(" ", ""));
// Display the spash screen
QSplashScreen *splash = new QSplashScreen();
splash->setPixmap(QPixmap(":/splash.png"));
splash->show();
app.processEvents(QEventLoop::AllEvents);
quint16 port = 0L;
// Find an unused port number. Essentially, we're just reserving one
// here that Flask will use when we start up the server.
// In order to use the socket, we need to free this socket ASAP.
// Hence - putting this code in a code block so the scope of the socket
// variable vanishes to make that socket available.
{
QUdpSocket socket;
socket.bind(0, QUdpSocket::ShareAddress);
port = socket.localPort();
}
// Fire up the webserver
Server *server;
bool done = false;
while (done != true)
{
server = new Server(port);
if (!server->Init())
{
qDebug() << server->getError();
QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError());
QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);
exit(1);
}
server->start();
// This is a hack. Wait a second and then check to see if the server thread
// is still running. If it's not, we probably had a startup error
delay(1000);
// Any errors?
if (server->isFinished() || server->getError().length() > 0)
{
splash->finish(NULL);
qDebug() << server->getError();
QString error = QString(QWidget::tr("An error occurred initialising the application server:\n\n%1")).arg(server->getError());
QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);
// Allow the user to tweak the Python Path if needed
QSettings settings;
bool ok;
ConfigWindow *dlg = new ConfigWindow();
dlg->setWindowTitle(QWidget::tr("Configuration"));
dlg->setPythonPath(settings.value("PythonPath").toString());
dlg->setApplicationPath(settings.value("ApplicationPath").toString());
dlg->setModal(true);
ok = dlg->exec();
QString pythonpath = dlg->getPythonPath();
QString applicationpath = dlg->getApplicationPath();
if (ok)
{
settings.setValue("PythonPath", pythonpath);
settings.setValue("ApplicationPath", applicationpath);
settings.sync();
}
else
{
exit(1);
}
delete server;
}
else
done = true;
}
// Generate the app server URL
QString appServerUrl = QString("http://localhost:%1/").arg(port);
// Now the server should be up, we'll attempt to connect and get a response.
// We'll retry in a loop a few time before aborting if necessary. The browser
// will also retry - that shouldn't (in theory) be necessary, but it won't
// hurt.
int attempt = 0;
while (attempt++ < 3)
{
bool alive = PingServer(QUrl(appServerUrl));
if (alive)
{
break;
}
if (attempt == 10)
{
QString error(QWidget::tr("The application server could not be contacted."));
QMessageBox::critical(NULL, QString(QWidget::tr("Fatal Error")), error);
exit(1);
}
delay(1000);
}
// Create & show the main window
BrowserWindow browserWindow(appServerUrl);
browserWindow.setWindowTitle(PGA_APP_NAME);
browserWindow.setWindowIcon(QIcon(":/pgAdmin4.ico"));
browserWindow.show();
// Go!
splash->finish(NULL);
return app.exec();
}
// Ping the application server to see if it's alive
bool PingServer(QUrl url)
{
QNetworkAccessManager manager;
QEventLoop loop;
QNetworkReply *reply;
QVariant redirectUrl;
url.setPath("/ping");
do
{
reply = manager.get(QNetworkRequest(url));
QObject::connect(reply, SIGNAL(finished()), &loop, SLOT(quit()));
loop.exec();
redirectUrl = reply->attribute(QNetworkRequest::RedirectionTargetAttribute);
url = redirectUrl.toUrl();
if (!redirectUrl.isNull())
delete reply;
} while (!redirectUrl.isNull());
if (reply->error() != QNetworkReply::NoError)
{
return false;
}
QString response = reply->readAll();
if (response != "PING")
{
qDebug() << "Failed to connect, server response: " << response;
return false;
}
return true;
}
| [
"luvres@hotmail.com"
] | luvres@hotmail.com |
b443e1ae2dc569172dfe5d042dd3c56c6a478499 | 1c4440e4d4809363199a4f14450d037f34e0f898 | /Funcao01.cpp | eb8f1a26cb779a18c3801367fae016c4a3b7eb7b | [] | no_license | bruno101/Tarefa-7---MN-II | 686fdfea3b586a7b9ad56577f415a4b3a6fe13b4 | df0c385b7a27003821bea2790c782762ad83b451 | refs/heads/master | 2023-07-28T05:45:38.326805 | 2021-09-05T22:10:34 | 2021-09-05T22:10:34 | 385,709,152 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 71 | cpp | #include "Funcao01.h"
double Funcao01::f(double x) {
return x*x*x;
} | [
"bbarros.sousa@hotmail.com"
] | bbarros.sousa@hotmail.com |
1bac4beacf4c921c93ff993943c1d2545868ebd6 | e6cbd9fe34605f4f36fee21ab67cf29a97e9965c | /ConsoleApplication1/PhoneBuilder.h | c7960152fd5612affba4d8a2842a37f11bd92e85 | [] | no_license | Rogerlin2013/DesignPatterns | 0667f63e39e5c886cd4b385821a860a763557fa9 | 82d733f14be8f76dd6544713dc522e1967580dde | refs/heads/master | 2020-05-20T04:24:18.523251 | 2019-05-11T10:41:58 | 2019-05-11T10:41:58 | 185,383,242 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 327 | h | #pragma once
class PhoneProduct;
class PhoneBuilder
{
public:
PhoneBuilder();
virtual ~PhoneBuilder();
virtual void createPhone() = 0;
virtual void buildCPU() = 0;
virtual void buildCapacity() = 0;
virtual void buildDisplay() = 0;
virtual PhoneProduct* obtainPhone() = 0;
protected:
PhoneProduct* phoneProduct;
};
| [
"rogerlin2010@gmail.com"
] | rogerlin2010@gmail.com |
7ae223f8d7e08825df376d3916bf20835a20a4d5 | 13f67a8813233b162c687207649c0252e95d0455 | /tonic-suite/asr/src/nnet2/nnet-compute.cc | ba0c00db16d8e031b9099995abf4379591ac2f73 | [
"BSD-3-Clause"
] | permissive | jhauswald/djinn | 19010e7ee604f756a82bde4c99a2418e463633a1 | f5e4d4a22c9c3c1561846c87a9cb25f77e470dcb | refs/heads/master | 2021-01-12T21:38:03.599604 | 2015-08-19T15:59:37 | 2015-08-19T15:59:37 | 37,376,692 | 1 | 1 | null | 2015-06-13T15:31:20 | 2015-06-13T15:31:19 | null | UTF-8 | C++ | false | false | 7,097 | cc | // nnet2/nnet-compute.cc
// Copyright 2012 Johns Hopkins University (author: Daniel Povey)
// See ../../COPYING for clarification regarding multiple 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
//
// THIS CODE IS PROVIDED *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED
// WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE,
// MERCHANTABLITY OR NON-INFRINGEMENT.
// See the Apache 2 License for the specific language governing permissions and
// limitations under the License.
#include "nnet2/nnet-compute.h"
#include "hmm/posterior.h"
namespace kaldi {
namespace nnet2 {
/*
This class does the forward and possibly backward computation for (typically)
a whole utterance of contiguous features. You'll instantiate one of
these classes each time you want to do this computation.
*/
class NnetComputer {
public:
/* Initializer. If pad == true, pad input with nnet.LeftContext() frames on
the left and nnet.RightContext() frames on the right (duplicate the first
and last frames.) */
NnetComputer(const Nnet &nnet, const CuMatrixBase<BaseFloat> &input_feats,
bool pad, Nnet *nnet_to_update = NULL);
/// The forward-through-the-layers part of the computation.
void Propagate();
void Backprop(CuMatrix<BaseFloat> *tmp_deriv);
/// Computes objf derivative at last layer, and returns objective
/// function summed over labels and multiplied by utterance_weight.
/// [Note: utterance_weight will normally be 1.0].
BaseFloat ComputeLastLayerDeriv(const Posterior &pdf_post,
CuMatrix<BaseFloat> *deriv) const;
CuMatrixBase<BaseFloat> &GetOutput() { return forward_data_.back(); }
private:
const Nnet &nnet_;
std::vector<CuMatrix<BaseFloat> > forward_data_;
Nnet *nnet_to_update_; // May be NULL, if just want objective function
// but no gradient info or SGD.
};
NnetComputer::NnetComputer(const Nnet &nnet,
const CuMatrixBase<BaseFloat> &input_feats, bool pad,
Nnet *nnet_to_update)
: nnet_(nnet), nnet_to_update_(nnet_to_update) {
int32 dim = input_feats.NumCols();
KALDI_ASSERT(dim == nnet.InputDim());
forward_data_.resize(nnet.NumComponents() + 1);
int32 left_context = (pad ? nnet_.LeftContext() : 0),
right_context = (pad ? nnet_.RightContext() : 0);
int32 num_rows = left_context + input_feats.NumRows() + right_context;
CuMatrix<BaseFloat> &input(forward_data_[0]);
input.Resize(num_rows, dim);
input.Range(left_context, input_feats.NumRows(), 0, dim)
.CopyFromMat(input_feats);
for (int32 i = 0; i < left_context; i++)
input.Row(i).CopyFromVec(input_feats.Row(0));
int32 last_row = input_feats.NumRows() - 1;
for (int32 i = 0; i < right_context; i++)
input.Row(num_rows - i - 1).CopyFromVec(input_feats.Row(last_row));
}
/// This is the forward part of the computation.
void NnetComputer::Propagate() {
for (int32 c = 0; c < nnet_.NumComponents(); c++) {
const Component &component = nnet_.GetComponent(c);
CuMatrix<BaseFloat> &input = forward_data_[c],
&output = forward_data_[c + 1];
component.Propagate(input, 1, &output);
const Component *prev_component =
(c == 0 ? NULL : &(nnet_.GetComponent(c - 1)));
bool will_do_backprop = (nnet_to_update_ != NULL),
keep_last_output = will_do_backprop &&
((c > 0 && prev_component->BackpropNeedsOutput()) ||
component.BackpropNeedsInput());
if (!keep_last_output)
forward_data_[c].Resize(0, 0); // We won't need this data; save memory.
}
}
BaseFloat NnetComputer::ComputeLastLayerDeriv(
const Posterior &pdf_post, CuMatrix<BaseFloat> *deriv) const {
// TODO: convert this to proper CUDA code, c.f. ComputeObjfAndDeriv
// in nnet-update.cc (I'm not sure, though, that this code is ever reached.)
int32 num_components = nnet_.NumComponents();
double tot_objf = 0.0, tot_weight = 0.0;
const CuMatrix<BaseFloat> &last_layer_output = forward_data_[num_components];
int32 num_frames = last_layer_output.NumRows(),
num_pdfs = last_layer_output.NumCols();
KALDI_ASSERT(pdf_post.size() == static_cast<size_t>(num_frames));
deriv->Resize(num_frames, num_pdfs); // will zero it.
for (int32 i = 0; i < deriv->NumRows(); i++) {
for (size_t j = 0; j < pdf_post[i].size(); j++) {
int32 label = pdf_post[i][j].first;
BaseFloat weight = pdf_post[i][j].second;
KALDI_ASSERT(label >= 0 && label < num_pdfs);
BaseFloat this_prob = last_layer_output(i, label);
KALDI_ASSERT(this_prob >
0.99e-20); // We floored to 1.0e-20 in SoftmaxLayer.
tot_objf += weight * log(this_prob);
tot_weight += weight;
(*deriv)(i, label) += weight / this_prob; // could be "=", assuming the
// labels are all distinct.
}
}
KALDI_VLOG(4) << "Objective function is " << (tot_objf / tot_weight)
<< " per frame over " << tot_weight << " samples.";
return tot_objf;
}
void NnetComputer::Backprop(CuMatrix<BaseFloat> *tmp_deriv) {
KALDI_ASSERT(nnet_to_update_ != NULL); // Or why do backprop?
// If later this reasoning changes, we can change this
// statement and add logic to make component_to_update, below,
// NULL if necessary.
int32 num_chunks = 1;
for (int32 c = nnet_.NumComponents() - 1; c >= 0; c--) {
const Component &component = nnet_.GetComponent(c);
Component *component_to_update = &(nnet_to_update_->GetComponent(c));
const CuMatrix<BaseFloat> &input = forward_data_[c],
&output = forward_data_[c + 1],
&output_deriv = *tmp_deriv;
CuMatrix<BaseFloat> input_deriv;
component.Backprop(input, output, output_deriv, num_chunks,
component_to_update, &input_deriv);
*tmp_deriv = input_deriv;
}
}
void NnetComputation(const Nnet &nnet,
const CuMatrixBase<BaseFloat> &input, // features
bool pad_input, CuMatrixBase<BaseFloat> *output) {
NnetComputer nnet_computer(nnet, input, pad_input, NULL);
nnet_computer.Propagate();
output->CopyFromMat(nnet_computer.GetOutput());
}
BaseFloat NnetGradientComputation(const Nnet &nnet,
const CuMatrixBase<BaseFloat> &input,
bool pad_input, const Posterior &pdf_post,
Nnet *nnet_to_update) {
NnetComputer nnet_computer(nnet, input, pad_input, nnet_to_update);
nnet_computer.Propagate();
CuMatrix<BaseFloat> deriv;
BaseFloat ans;
ans = nnet_computer.ComputeLastLayerDeriv(pdf_post, &deriv);
nnet_computer.Backprop(&deriv);
return ans;
}
} // namespace nnet2
} // namespace kaldi
| [
"ypkang@umich.edu"
] | ypkang@umich.edu |
7a3c10101111b63aaf4f578a195ecb17eeed01ff | 6357b957b3ce084fe43b14d07bf2e1d352d9aaa6 | /mouseEncoder/mouse_encoder.ino | 63d18c36e4edb477646abb6697f850aff5a7cac0 | [] | no_license | asiodd1/swagelok_lockingSystem | 59af298efc02a8a21b564c371e27c0bae938dee5 | 7652c47c7266cd7e9af22e6ce462bfc267124db5 | refs/heads/main | 2023-08-20T17:58:42.778854 | 2021-10-27T05:59:49 | 2021-10-27T05:59:49 | 413,294,843 | 0 | 0 | null | 2021-10-04T09:23:49 | 2021-10-04T06:09:05 | C++ | UTF-8 | C++ | false | false | 2,156 | ino |
#define DEBOUNCE_TIME 8 //延时用来过滤不正常的信号,此数字太大的话会对快速的旋转不起反应
// 定义引脚2.3
int APhase = 3;
int BPhase = 2;
long count = 0;//计数
long preverCount = 0;//上一次的计数
long currentCount = 0;//当前计数
void getSpeed()
{
preverCount = currentCount;
currentCount = count;
Serial.println( "speed is " + String (currentCount - preverCount) ) ;
}
void setup()
{
Serial.begin(9600);
pinMode(APhase, INPUT);//上拉电阻
pinMode(BPhase, INPUT);
Serial.println("set up");
delay(1000);
//pinMode(LED_BUILTIN,OUTPUT);
}
void loop()
{
int firstAPhaseState= digitalRead(APhase);
//digitalWrite(LED_BUILTIN,firstAPhaseState);//用板上自带的灯显示A相的状态
if (firstAPhaseState == 1 )
{
//Serial.println(firstAPhaseState);
delay(DEBOUNCE_TIME);
int secendAPhaseState = digitalRead(APhase);
if (secendAPhaseState == 0) //从1变成0 开始判断是正转还是反转
{
Serial.println("1變成0");
int BPhaseState = digitalRead(BPhase);
//用B相信号判断正反转
if (BPhaseState == 0)
{
count++;
Serial.println(count);
}
if (BPhaseState == 1)
{
count--;
Serial.println(count);
}
Serial.println("APhase"+String(secendAPhaseState));
Serial.println("BPhase"+String(BPhaseState));
}
}
if (firstAPhaseState == 0) //初始状态是0的判断,想改进的话可以用外部中断的上升沿事件
{
//delay(DEBOUNCE_TIME);
int secendAPhaseState = digitalRead(APhase);
if (secendAPhaseState == 1)
{
Serial.println("0變成1");
if (digitalRead(BPhase) == 1)
{
count++;
Serial.println(count);
}
if (digitalRead(BPhase) == 0)
{
count--;
Serial.println(count);
}
Serial.println("APhase: "+String(secendAPhaseState));
//Serial.println("BPhase: "+String(BPhaseState));
}
}
delay(1);//延时增加程序稳定性
}
| [
"noreply@github.com"
] | noreply@github.com |
a045d7f3597105b31082ca802d9066097df1bef5 | 48dc4953e424f2e422b36965bf80b8c0b6bf74f2 | /mcpp/mcpp3/ex03/ClapTrap.hpp | 86dc90793d60b3b488ccff222170da79363b8b06 | [] | no_license | Krcdb/42 | 21b47feee856aa1ffbebef2e6330146624db6532 | 896d5681bfd2f636f84cc3ba9e9d9a89e169d2d4 | refs/heads/master | 2023-05-01T18:50:38.411080 | 2023-03-03T11:35:51 | 2023-03-03T11:35:51 | 125,866,691 | 1 | 0 | null | 2023-04-23T20:01:03 | 2018-03-19T14:02:15 | C | UTF-8 | C++ | false | false | 1,802 | hpp | /* ************************************************************************** */
/* */
/* ::: :::::::: */
/* ClapTrap.hpp :+: :+: :+: */
/* +:+ +:+ +:+ */
/* By: user42 <user42@student.42.fr> +#+ +:+ +#+ */
/* +#+#+#+#+#+ +#+ */
/* Created: 2020/09/29 17:38:00 by memartin #+# #+# */
/* Updated: 2020/11/24 15:40:46 by user42 ### ########.fr */
/* */
/* ************************************************************************** */
#ifndef CLAPTRAP_HPP
# define CLAPTRAP_HPP
# include <string>
# include <iostream>
# include <cstdlib>
class ClapTrap
{
private:
std::string _name;
int _hp;
int _hpMax;
int _ep;
int _epMax;
int _level;
int _armorDamageReduction;
protected:
std::ostream& say(void);
std::ostream& say(std::string output);
int _meleeAttackDamage;
int _rangedAttackDamage;
public:
ClapTrap(void);
ClapTrap(std::string name, int hp, int hpMax, int ep, int epMax, int level, int meleeAttackDamage, int rangedAttackDamage, int armorDamageReduction);
ClapTrap(const ClapTrap &other);
virtual ~ClapTrap(void);
ClapTrap &operator =(const ClapTrap &other);
void takeDamage(unsigned int amount);
void beRepaired(unsigned int amount);
void displayStatus(void);
int &getHp(void);
int &getEp(void);
const std::string &getName(void);
};
#endif
| [
"medo.mrt@gmail.com"
] | medo.mrt@gmail.com |
7faa5210ca6568e080aa2ccbbe53f0475bddefb6 | 64ea142b58e912d7608b4fb99c00c0be8b48093f | /Source/Project/UI/CombatUI.h | 4fd5ec262104150b634e857bfe09f6e7db53d67b | [] | no_license | Joaquin808/SeniorProject | ad2b2d2fb10e3b2bf2ef9560bd60529acadaf933 | e63cfec56deca902e06e42bba0640772968a4b90 | refs/heads/master | 2022-12-02T17:38:59.340912 | 2020-08-16T22:08:10 | 2020-08-16T22:08:10 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 507 | h | // Fill out your copyright notice in the Description page of Project Settings.
#pragma once
#include "CoreMinimal.h"
#include "Blueprint/UserWidget.h"
#include "CombatUI.generated.h"
UCLASS()
class PROJECT_API UCombatUI : public UUserWidget
{
GENERATED_BODY()
public:
UPROPERTY(meta = (BindWidgetOptional))
class UProgressBar* HealthBar;
UPROPERTY(BlueprintReadOnly)
float MaxHealth;
UPROPERTY(BlueprintReadOnly)
float Health;
public:
void SetHealthBar(float Health, float MaxHealth);
};
| [
"42978361+Joaquin808@users.noreply.github.com"
] | 42978361+Joaquin808@users.noreply.github.com |
9ef8e0cb38ae31a9b5251747000d8b96975ac3eb | 84518f8ff431dcd50886c1dc8ee030f5e0c49f87 | /tp6/Principale.cpp | b31c82027fd5c58ded0bf614725ffe1f28d39b65 | [] | no_license | ArchSirius/inf1010 | feda36581c29e8f4fc68892bbb1ef7d74402f17f | 6caeae451afe748a4ad1525472f23882bae4e52a | refs/heads/master | 2021-03-27T12:33:20.118934 | 2015-11-05T23:13:57 | 2015-11-05T23:13:57 | 49,438,317 | 0 | 0 | null | null | null | null | WINDOWS-1252 | C++ | false | false | 1,352 | cpp | #include"Principale.h"
Principale::Principale()
{
setFixedSize(250, 150);
boutonInscription = new QPushButton("Ouvrir un nouveau compte bancaire", this);
boutonConnexion = new QPushButton("Connexion à votre compte", this);
sortir = new QPushButton("Sortir", this);
vboxPrincipale = new QVBoxLayout(this);
vboxPrincipale->addWidget(boutonInscription);
vboxPrincipale->addWidget(boutonConnexion);
vboxPrincipale->addWidget(sortir);
general = new QGroupBox("Clicquez sur un bouton", this);
general->setLayout(vboxPrincipale);
layoutPrincipal = new QVBoxLayout(this);
layoutPrincipal->addWidget(general);
setLayout(layoutPrincipal);
setWindowTitle("Bienvenu chez votre banque");
connect(boutonInscription, SIGNAL(clicked()), this, SLOT(inscription()));
connect(boutonConnexion, SIGNAL(clicked()), this, SLOT(connexion()));
connect(sortir, SIGNAL(clicked()), qApp, SLOT(quit()));
}
void Principale::inscription()
{
Inscription *uneInscription = new Inscription();
uneInscription->show();
}
void Principale::connexion()
{
Connexion *uneConnexion = new Connexion();
uneConnexion->show();
}
| [
"samuel.rondeau@polymtl.ca"
] | samuel.rondeau@polymtl.ca |
17813c77bea84b042a3decf44cb8ecbaa50ca1df | 1aa3b6c1fb9ef1201ca588a7fea64b65799f4d7a | /test2/test2/stop.cpp | ce8d38f5d3f80da4366c1534e59c6996e70b37ab | [] | no_license | ybkimdb/cplus | 1f63d5ef105ebadf3063b66e06e06f7ec6a9a0a5 | 5aa96f25088b0239d8a7e88a89b3f7605a1c53b2 | refs/heads/master | 2021-01-10T01:06:30.816698 | 2016-03-01T08:05:38 | 2016-03-01T08:05:38 | 47,963,569 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 788 | cpp |
#include <iostream>
#include <chrono>
int main()
{
using shakes = std::chrono::duration<int, std::ratio<1, 100000000>>;
using jiffies = std::chrono::duration<int, std::centi>;
using microfortnights = std::chrono::duration<float, std::ratio<12096, 10000>>;
using nanocenturies = std::chrono::duration<float, std::ratio<3155, 1000>>;
std::chrono::seconds sec(1);
std::cout << "1 second is:\n";
std::cout << std::chrono::duration_cast<shakes>(sec).count()
<< " shakes\n";
std::cout << std::chrono::duration_cast<jiffies>(sec).count()
<< " jiffies\n";
std::cout << microfortnights(sec).count() << " microfortnights\n";
std::cout << nanocenturies(sec).count() << " nanocenturies\n";
std::cout << nanocenturies(sec).count() << " nanocenturies\n";
char ch;
std::cin >> ch;
} | [
"ybkimdb@gmail.com"
] | ybkimdb@gmail.com |
3a770c8e9edb88d13b5b3dfdb607644ca26ff802 | 4b758ca583d2a58d4d711381405e024109a0f08f | /dali/operators/image/convolution/gaussian_blur_params.h | effbbf04b1c455d51e7a94ab5385d68bd02a3fc4 | [
"Apache-2.0",
"LicenseRef-scancode-free-unknown"
] | permissive | ConnectionMaster/DALI | 76ff07b2fa3f62490b059088c88ade7570130ff4 | 6b90519d2c209d705e8912a5f00b71a018aeaa52 | refs/heads/master | 2023-04-14T13:04:57.520421 | 2021-01-22T16:34:31 | 2021-01-22T16:34:31 | 187,683,855 | 1 | 1 | Apache-2.0 | 2023-04-03T23:45:28 | 2019-05-20T17:18:56 | C++ | UTF-8 | C++ | false | false | 5,546 | h | // Copyright (c) 2020, NVIDIA CORPORATION. All rights reserved.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#ifndef DALI_OPERATORS_IMAGE_CONVOLUTION_GAUSSIAN_BLUR_PARAMS_H_
#define DALI_OPERATORS_IMAGE_CONVOLUTION_GAUSSIAN_BLUR_PARAMS_H_
#include <vector>
#include "dali/core/dev_array.h"
#include "dali/pipeline/data/views.h"
#include "dali/pipeline/operator/common.h"
namespace dali {
namespace gaussian_blur {
inline int SigmaToDiameter(float sigma) {
return 2 * ceilf(sigma * 3) + 1;
}
inline float DiameterToSigma(int diameter) {
// Based on OpenCV
int radius = (diameter - 1) / 2;
return (radius - 1) * 0.3 + 0.8;
}
struct DimDesc {
int usable_axes_start;
int usable_axes_count;
int total_axes_count;
bool has_channels;
bool is_sequence;
};
template <int axes>
struct GaussianBlurParams {
DeviceArray<int, axes> window_sizes;
DeviceArray<float, axes> sigmas;
bool IsUniform() const {
for (int i = 1; i < axes; i++) {
if (sigmas[0] != sigmas[i] || window_sizes[0] != window_sizes[i]) {
return false;
}
}
return true;
}
bool operator==(const GaussianBlurParams<axes> &other) const {
return window_sizes == other.window_sizes && sigmas == other.sigmas;
}
bool operator!=(const GaussianBlurParams<axes> &other) const {
return !(*this == other);
}
};
inline void FillGaussian(const TensorView<StorageCPU, float, 1> &window, float sigma) {
int r = (window.num_elements() - 1) / 2;
// 1 / sqrt(2 * pi * sigma^2) * exp(-(x^2) / (2 * sigma^2))
// the 1 / sqrt(2 * pi * sigma^2) coefficient disappears as we normalize the sum to 1.
float exp_scale = 0.5f / (sigma * sigma);
float sum = 0.f;
// Calculate first half
for (int x = -r; x < 0; x++) {
*window(x + r) = exp(-(x * x * exp_scale));
sum += *window(x + r);
}
// Total sum, it's symmetric with `1` in the center.
sum *= 2.;
sum += 1.0;
float scale = 1.f / sum;
// place center, scaled element
*window(r) = scale;
// scale all elements so they sum up to 1, duplicate the second half
for (int x = 0; x < r; x++) {
*window(x) *= scale;
*window(2 * r - x) = *window(x);
}
}
template <int axes>
class GaussianWindows {
public:
GaussianWindows() {
previous.sigmas = uniform_array<axes>(-1.f);
previous.window_sizes = uniform_array<axes>(0);
}
void PrepareWindows(const GaussianBlurParams<axes> ¶ms) {
bool changed = previous != params;
if (!changed)
return;
// Reallocate if necessary and fill the windows
bool is_uniform = params.IsUniform();
if (is_uniform) {
int required_elements = params.window_sizes[0];
memory.resize(required_elements);
TensorView<StorageCPU, float, 1> tmp_view = {memory.data(), {required_elements}};
FillGaussian(tmp_view, params.sigmas[0]);
precomputed_window = uniform_array<axes>(
TensorView<StorageCPU, const float, 1>{memory.data(), {params.window_sizes[0]}});
} else {
int required_elements = 0;
for (int i = 0; i < axes; i++) {
required_elements += params.window_sizes[i];
}
memory.resize(required_elements);
int offset = 0;
for (int i = 0; i < axes; i++) {
TensorView<StorageCPU, float, 1> tmp_view = {&memory[offset], {params.window_sizes[i]}};
offset += params.window_sizes[i];
FillGaussian(tmp_view, params.sigmas[i]);
precomputed_window[i] = tmp_view;
}
}
}
// Return the already filled windows
std::array<TensorView<StorageCPU, const float, 1>, axes> GetWindows() const {
return precomputed_window;
}
private:
std::array<TensorView<StorageCPU, const float, 1>, axes> precomputed_window;
GaussianBlurParams<axes> previous;
std::vector<float> memory;
};
// This can be fused and we can handle batch of params at a time
// instead of vector of sample params but depending on the parameter changes
// it will probably impact allocation patterns in different ways and need
// to be evaluated if it is fine or not
template <int axes>
void RepackAsTL(std::array<TensorListShape<1>, axes> &out,
const std::vector<GaussianBlurParams<axes>> ¶ms) {
for (int axis = 0; axis < axes; axis++) {
out[axis].resize(params.size());
for (size_t i = 0; i < params.size(); i++) {
out[axis].set_tensor_shape(i, {params[i].window_sizes[axis]});
}
}
}
template <int axes>
void RepackAsTL(std::array<TensorListView<StorageCPU, const float, 1>, axes> &out,
const std::vector<GaussianWindows<axes>> &windows) {
for (int axis = 0; axis < axes; axis++) {
int nsamples = windows.size();
out[axis].data.resize(nsamples);
out[axis].shape.resize(nsamples);
for (int i = 0; i < nsamples; i++) {
out[axis].data[i] = windows[i].GetWindows()[axis].data;
out[axis].shape.set_tensor_shape(i, windows[i].GetWindows()[axis].shape);
}
}
}
} // namespace gaussian_blur
} // namespace dali
#endif // DALI_OPERATORS_IMAGE_CONVOLUTION_GAUSSIAN_BLUR_PARAMS_H_
| [
"noreply@github.com"
] | noreply@github.com |
94328270fbf9b84b547f965c245a725871ed7c82 | 53e3e676b66e4ed6bbf7941c7e78c2820fcbed59 | /devel/include/std_msgs/MultiArrayDimension.h | 2835f77d82d9c08fb85858a10d8fa855582d6c4a | [] | no_license | daichi08/catkin_ws_atPi | 0bdc3e5f2c7073d888a2f6109c0842521c99104e | 9690697e1d432f06c5ee4570a0e7d1a2cc7c44ed | refs/heads/master | 2020-03-22T21:09:04.291933 | 2018-08-02T06:10:41 | 2018-08-02T06:10:41 | 140,661,209 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,713 | h | // Generated by gencpp from file std_msgs/MultiArrayDimension.msg
// DO NOT EDIT!
#ifndef STD_MSGS_MESSAGE_MULTIARRAYDIMENSION_H
#define STD_MSGS_MESSAGE_MULTIARRAYDIMENSION_H
#include <string>
#include <vector>
#include <map>
#include <ros/types.h>
#include <ros/serialization.h>
#include <ros/builtin_message_traits.h>
#include <ros/message_operations.h>
namespace std_msgs
{
template <class ContainerAllocator>
struct MultiArrayDimension_
{
typedef MultiArrayDimension_<ContainerAllocator> Type;
MultiArrayDimension_()
: label()
, size(0)
, stride(0) {
}
MultiArrayDimension_(const ContainerAllocator& _alloc)
: label(_alloc)
, size(0)
, stride(0) {
(void)_alloc;
}
typedef std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > _label_type;
_label_type label;
typedef uint32_t _size_type;
_size_type size;
typedef uint32_t _stride_type;
_stride_type stride;
typedef boost::shared_ptr< ::std_msgs::MultiArrayDimension_<ContainerAllocator> > Ptr;
typedef boost::shared_ptr< ::std_msgs::MultiArrayDimension_<ContainerAllocator> const> ConstPtr;
}; // struct MultiArrayDimension_
typedef ::std_msgs::MultiArrayDimension_<std::allocator<void> > MultiArrayDimension;
typedef boost::shared_ptr< ::std_msgs::MultiArrayDimension > MultiArrayDimensionPtr;
typedef boost::shared_ptr< ::std_msgs::MultiArrayDimension const> MultiArrayDimensionConstPtr;
// constants requiring out of line definition
template<typename ContainerAllocator>
std::ostream& operator<<(std::ostream& s, const ::std_msgs::MultiArrayDimension_<ContainerAllocator> & v)
{
ros::message_operations::Printer< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >::stream(s, "", v);
return s;
}
} // namespace std_msgs
namespace ros
{
namespace message_traits
{
// BOOLTRAITS {'IsFixedSize': False, 'IsMessage': True, 'HasHeader': False}
// {'std_msgs': ['/home/pi/catkin_ws/src/std_msgs/msg']}
// !!!!!!!!!!! ['__class__', '__delattr__', '__dict__', '__doc__', '__eq__', '__format__', '__getattribute__', '__hash__', '__init__', '__module__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', '__weakref__', '_parsed_fields', 'constants', 'fields', 'full_name', 'has_header', 'header_present', 'names', 'package', 'parsed_fields', 'short_name', 'text', 'types']
template <class ContainerAllocator>
struct IsFixedSize< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct IsFixedSize< ::std_msgs::MultiArrayDimension_<ContainerAllocator> const>
: FalseType
{ };
template <class ContainerAllocator>
struct IsMessage< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
: TrueType
{ };
template <class ContainerAllocator>
struct IsMessage< ::std_msgs::MultiArrayDimension_<ContainerAllocator> const>
: TrueType
{ };
template <class ContainerAllocator>
struct HasHeader< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
: FalseType
{ };
template <class ContainerAllocator>
struct HasHeader< ::std_msgs::MultiArrayDimension_<ContainerAllocator> const>
: FalseType
{ };
template<class ContainerAllocator>
struct MD5Sum< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
{
static const char* value()
{
return "4cd0c83a8683deae40ecdac60e53bfa8";
}
static const char* value(const ::std_msgs::MultiArrayDimension_<ContainerAllocator>&) { return value(); }
static const uint64_t static_value1 = 0x4cd0c83a8683deaeULL;
static const uint64_t static_value2 = 0x40ecdac60e53bfa8ULL;
};
template<class ContainerAllocator>
struct DataType< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
{
static const char* value()
{
return "std_msgs/MultiArrayDimension";
}
static const char* value(const ::std_msgs::MultiArrayDimension_<ContainerAllocator>&) { return value(); }
};
template<class ContainerAllocator>
struct Definition< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
{
static const char* value()
{
return "string label # label of given dimension\n\
uint32 size # size of given dimension (in type units)\n\
uint32 stride # stride of given dimension\n\
";
}
static const char* value(const ::std_msgs::MultiArrayDimension_<ContainerAllocator>&) { return value(); }
};
} // namespace message_traits
} // namespace ros
namespace ros
{
namespace serialization
{
template<class ContainerAllocator> struct Serializer< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
{
template<typename Stream, typename T> inline static void allInOne(Stream& stream, T m)
{
stream.next(m.label);
stream.next(m.size);
stream.next(m.stride);
}
ROS_DECLARE_ALLINONE_SERIALIZER
}; // struct MultiArrayDimension_
} // namespace serialization
} // namespace ros
namespace ros
{
namespace message_operations
{
template<class ContainerAllocator>
struct Printer< ::std_msgs::MultiArrayDimension_<ContainerAllocator> >
{
template<typename Stream> static void stream(Stream& s, const std::string& indent, const ::std_msgs::MultiArrayDimension_<ContainerAllocator>& v)
{
s << indent << "label: ";
Printer<std::basic_string<char, std::char_traits<char>, typename ContainerAllocator::template rebind<char>::other > >::stream(s, indent + " ", v.label);
s << indent << "size: ";
Printer<uint32_t>::stream(s, indent + " ", v.size);
s << indent << "stride: ";
Printer<uint32_t>::stream(s, indent + " ", v.stride);
}
};
} // namespace message_operations
} // namespace ros
#endif // STD_MSGS_MESSAGE_MULTIARRAYDIMENSION_H
| [
"b1504000@planet.kanazawa-it.ac.jp"
] | b1504000@planet.kanazawa-it.ac.jp |
4ff3fb169ea6a6ec75572ec9de552d49e468356b | 19c8c65b59bb23ca56a504f0e4f9505536278b14 | /binding/libavutil_base64.inc | efabebbe3e5f29c00c3cf97e4d09e605b8111e7c | [] | no_license | DJMaster/ffmpeg-fpc | f2d8de9b75bdf0cbee0d47f467909250a5592f68 | c307e6ebfef9c82294a788a2527d1e3e548f62ef | refs/heads/master | 2021-01-18T12:56:43.468095 | 2017-12-14T19:52:00 | 2017-12-14T19:52:00 | 100,367,837 | 18 | 6 | null | null | null | null | UTF-8 | C++ | false | false | 2,534 | inc | //
// avutil.h header binding for the Free Pascal Compiler aka FPC
//
// Binaries and demos available at http://www.djmaster.com/
//
(*
* Copyright (c) 2006 Ryan Martell. (rdm4@martellventures.com)
*
* This file is part of FFmpeg.
*
* FFmpeg is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* FFmpeg is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with FFmpeg; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*)
// #ifndef AVUTIL_BASE64_H
// #define AVUTIL_BASE64_H
// #include <stdint.h>
(**
* @defgroup lavu_base64 Base64
* @ingroup lavu_crypto
* @{
*)
(**
* Decode a base64-encoded string.
*
* @param out buffer for decoded data
* @param in null-terminated input string
* @param out_size size in bytes of the out buffer, must be at
* least 3/4 of the length of in, that is AV_BASE64_DECODE_SIZE(strlen(in))
* @return number of bytes written, or a negative value in case of
* invalid input
*)
function av_base64_decode(out_: pcuint8; const in_: pchar; out_size: cint): cint; cdecl; external LIB_AVUTIL;
(**
* Calculate the output size in bytes needed to decode a base64 string
* with length x to a data buffer.
*)
//TODO #define AV_BASE64_DECODE_SIZE(x) ((x) * 3LL / 4)
(**
* Encode data to base64 and null-terminate.
*
* @param out buffer for encoded data
* @param out_size size in bytes of the out buffer (including the
* null terminator), must be at least AV_BASE64_SIZE(in_size)
* @param in input buffer containing the data to encode
* @param in_size size in bytes of the in buffer
* @return out or NULL in case of error
*)
function av_base64_encode(out_: pchar; out_size: cint; const in_: pcuint8; in_size: cint): pchar; cdecl; external LIB_AVUTIL;
(**
* Calculate the output size needed to base64-encode x bytes to a
* null-terminated string.
*)
//TODO #define AV_BASE64_SIZE(x) (((x)+2) / 3 * 4 + 1)
(**
* @}
*)
// #endif (* AVUTIL_BASE64_H *)
| [
"developers@djmaster.com"
] | developers@djmaster.com |
4aaae3a33fdc17bcad0151a99aeff4abea7099a4 | 3136459fd674e1027f480895ba6685312ac6959b | /source/owlcore/bardescr.cpp | c1f434841ea7a5d84c238b1ea4672acee59e80b4 | [
"Zlib"
] | permissive | pierrebestwork/owl-next | 701d1a6cbabd4566a0628aa8a64343b498d1e977 | 94ba85e8b4dcb978f095b479f85fe4ba3af2fe4e | refs/heads/master | 2023-02-14T02:03:33.656218 | 2020-03-16T16:41:49 | 2020-03-16T16:41:49 | 326,663,717 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 18,967 | cpp | //----------------------------------------------------------------------------
// ObjectWindows
// Copyright (c) 1998 by Yura Bidus, All Rights Reserved
//
/// \file
/// Implementation of class TBarDescr
//----------------------------------------------------------------------------
#include <owl/pch.h>
#include <owl/resource.h>
#include <owl/celarray.h>
#include <owl/gadget.h>
#include <owl/buttonga.h>
#include <owl/gadgetwi.h>
#include <owl/functor.h>
#include <owl/bardescr.h>
#include <owl/template.h>
#include <owl/functor.h>
#include <owl/glyphbtn.h>
namespace owl {
OWL_DIAGINFO;
/// \cond
struct __TBarDescrGdNode {
__TBarDescrGdNode(TGadget* gd, bool ug): Gadget(gd),UseGlyph(ug){}
~__TBarDescrGdNode();
TGadget* Gadget;
bool UseGlyph;
};
//
__TBarDescrGdNode::~__TBarDescrGdNode()
{
delete Gadget;
}
//
class TBarDescrGdArray: public TIPtrArray<__TBarDescrGdNode*>{ // internal usage
public:
TBarDescrGdArray(int count):TIPtrArray<__TBarDescrGdNode*>(count){}
};
/// \endcond
//
//
//
static TGadget* CreateGadget(int index, int id, bool& usecell)
{
usecell = false;
if(id == 0)
return new TSeparatorGadget;
usecell = true;
return new TButtonGadget(index,
id,
TButtonGadget::Command,
false,
TButtonGadget::Up,true);
}
// -----------------------------------------------------------------------------
////////////////////////////////////////////////////////////////////////////////
// class TBarDescr
// ~~~~~ ~~~~~~~~~
/// \class TBarDescr
/// TBarDescr describes your control bar and its functional groups. TBarDescr
/// provides an easy way for you to group gadgets on your control bar and to add new
/// groups to an existing control bar. It uses a resource ID to identify the bar
/// resource and an array of count values to indicate the number of gadgets in each
/// group on the control bar.
///
/// The TGroup enum enumerates the six basic functional groups on a control bar:
/// File, Edit, Container, Object, Window, and Help. TBarDescr's constructors simply
/// initialize the members based on the arguments passed.
///
/// TFrameWindow::MergeBar actually performs the real work of merging the gadgets
/// groups.
///
/// For a single document application (SDI), the gadgets are merged as soon as you
/// load the application. See the sample program, bardescm, for an example of MDI
/// control bar merging, and bardescr, for an example of SDI control bar merging.
///
/// One technique you can use to create a control bar involves invoking the
/// TBarDescr constructor and passing the number of group counts for each gadgets
/// selection.
///
/// For example, if your original gadgets groups included these items:
/// \image html bm78.BMP
/// you might use the following group counts:
/// <TABLE>
/// <TR><TD>Group</TD> <TD>Count</TD> <TD>Menu</TD></TR>
/// <TR><TD>FileGroup</TD> <TD>1</TD> <TD>File</TD></TR>
/// <TR><TD>EditGroup</TD> <TD>2</TD> <TD>Edit Search</TD></TR>
/// <TR><TD>ContainerGroup</TD> <TD>1</TD> <TD>View</TD></TR>
/// <TR><TD>ObjectGroup</TD> <TD>3</TD> <TD>Page Paragraph Word</TD></TR>
/// <TR><TD>WindowGroup</TD> <TD>1</TD> <TD>Window</TD></TR>
/// <TR><TD>HelpGroup</TD> <TD>1</TD> <TD>Help</TD></TR>
/// </TABLE>
/// You would then invoke the constructor this way:
/// \code
/// TBarDescr(IDM_MYMENU, 1, 2, 1, 3, 1, 1)
/// \endcode
/// You can build the previous control bar by merging two control bars. When a zero
/// is passed in the TBarDescr's constructor, the group indicated by the zero is
/// filled in by the child control bar's group, if an item is specified, when the
/// bar merging occurs. Set your application's parent frame control bar by
/// specifying these gadget groups:
/// \image html bm79.BMP
/// and passing these group counts in the constructor:
/// \code
/// TBarDescr(IDM_FRAME, 1, 0, 1, 0, 1, 1)
/// \endcode
/// Set the word-processor child control bar this way:
/// \image html bm80.BMP
/// and pass these values in the constructor:
/// \code
/// TBarDescr(IDM_WPROC, 0, 2, 0, 3, 0, 1)
/// \endcode
/// If no child is active, only the frame menu will be active. When the word
/// processor's child window becomes active, the child control bar is merged with
/// the frame bar. Every group that is 0 in the child control bar leaves the
/// parent's group intact. The previous example interleaves every group except for
/// the last group, the Help group, in which the child replaces the frame bar.
///
/// By convention, the even groups (File, Container, Window) usually belong to the
/// outside frame or container, and the odd groups (Edit, Object, Help) belong to
/// the child or contained group.
///
/// If a -1 is used in a group count, the merger eliminates the parent's group
/// without replacing it. For example, another child control bar, such as a
/// calculator, could be added to your application in this way:
/// \image html bm81.BMP
/// \code
/// TBarDescr(IDM_WCALC, 0, 1, -1, 1, 0, 1)
/// \endcode
/// In this example, the child's control group contributes nothing from the
/// container group, and the parent's container group is removed. This produces a
/// merged bar (with the View control bar selection eliminated as a result of the
/// -1) that looks like this:
/// \image html bm82.BMP
///
/// If you want to merge the following parent gadget groups
/// \image html bm79.BMP
/// with these paint window gadget groups,
/// \image html bm83.BMP
/// pass the following group counts in the constructor:
/// \code
/// TBarDescr(IDM_WPAINT, 0, 1, 0, 2, 0, 1)
/// \endcode
/// This produces the following merged control bar:
/// \image html bm84.BMP
///
/// The simplest way to add groups to a control bar involves defining the control
/// groups and adding separators in a resource file. Insert the term BUTTON -1
/// between each gadgets group and an additional separator if one of the gadgets
/// groups is not present. For example, the resource file for Step 13 of the
/// ObjectWindows tutorial defines the following gadgets groups and separators:
/// \code
/// IDB_DVMDI TOOLBAR 20, 20
/// {
/// BUTTON CM_FILENEW
/// BUTTON CM_FILEOPEN
/// BUTTON CM_FILESAVE
/// BUTTON CM_FILESAVEAS
/// SEPARATOR
/// BUTTON -1
/// BUTTON -1
/// BUTTON CM_ABOUT
/// BUTTON -1
/// }
/// IDB_DVMDI BITMAP "dvmain.bmp"
/// \endcode
/// You can see the separators by loading Step13.rc into Resource Workshop.
///
/// Step13.cpp uses these commands from the resource file to set the main window and
/// its menu, passing IDM_MDICMNDS as the parameter to SetMenuDescr function, as
/// follows:
/// \code
/// frame->SetBarDescr(new TBarDescr(IDB_DVMDI));
/// \endcode
/// It produces the following menu groups:
/// \image html bm85.BMP
///
/// TBarDescr's functions let you perform control bar merging similar to menu
/// merging. That is, you can merge control bars from a MDI frame window, with
/// those of an the MDI child window. When child is selected, the control bars of
/// the child window merges with that of the frame window.
/// Default constructor for a TBarDescr object. No menu resources or groups are
/// specified. Constructs an empty control bar. For internal use only.
TBarDescr::TBarDescr()
:
BarRes(0),
CelArray(0),
Id(0),
Module(0)
{
GadgetFunctor = new TGadgetFunctor;
SetBuilder(TGadget_FUNCTOR(CreateGadget));
Gadgets = new TBarDescrGdArray(5);
for (int i = 0; i < NumGroups; i++)
GroupCount[i] = 0;
}
// -----------------------------------------------------------------------------
/// Not implemented. Forbidden and protected contructor.
TBarDescr::TBarDescr(const TBarDescr& bar)
:
Id(bar.Id),
Module(bar.Module)
{
GadgetFunctor = new TGadgetFunctor;
SetBuilder(TGadget_FUNCTOR(CreateGadget));
Gadgets = new TBarDescrGdArray(5);
BarRes = new TToolbarRes(*bar.BarRes);
CHECK(BarRes->IsOK());
{ // map colors
TBtnBitmap bitmap(BarRes->GetBitmap(),
TColor::LtGray,
NoAutoDelete);
}
CelArray = new TCelArray(&BarRes->GetBitmap(),
BarRes->GetCount(),
TSize(BarRes->GetWidth(), BarRes->GetHeight()),
TPoint(0, 0), // offset
BarRes->GetBitmap().Height()/BarRes->GetHeight());
ExtractGroups();
}
// -----------------------------------------------------------------------------
/// Creates a control bar descriptor from the controlbar resource specified in the
/// id parameter. Calls the function ExtractGroups to extract the group counts based
/// on the separator items in the control bar.
TBarDescr::TBarDescr(TResId barResId, TModule* module)
:
Id(barResId),
Module(module),
BarRes(0),
CelArray(0)
{
GadgetFunctor = new TGadgetFunctor;
SetBuilder(TGadget_FUNCTOR(CreateGadget));
Gadgets = new TBarDescrGdArray(5);
SetBitmap(barResId, module);
ExtractGroups();
}
// -----------------------------------------------------------------------------
/// Constructs a control bar descriptor from the resource indicated by id. Places
/// the gadgets in groups according the values of the fg, eg, cg, of, wg, and hg
/// parameters. The fg, eg, cg, of, wg, and hg parameters represent the functional
/// groups identified by the TGroup enum. Calls the function ExtractGroups to
/// extract the group counts based on the separator items in the menu bar.
TBarDescr::TBarDescr(TResId id, int fg, int eg, int cg, int og, int wg,
int hg, TModule* module)
:
Id(id),
Module(module),
BarRes(0),
CelArray(0)
{
GadgetFunctor = new TGadgetFunctor;
SetBuilder(TGadget_FUNCTOR(CreateGadget));
Gadgets = new TBarDescrGdArray(5);
SetBitmap(id, module);
if (!ExtractGroups()) {
GroupCount[FileGroup] = fg;
GroupCount[EditGroup] = eg;
GroupCount[ContainerGroup] = cg;
GroupCount[ObjectGroup] = og;
GroupCount[WindowGroup] = wg;
GroupCount[HelpGroup] = hg;
}
}
// -----------------------------------------------------------------------------
/// Destroys the TBarDescr object.
TBarDescr::~TBarDescr()
{
delete Gadgets;
delete BarRes;
delete CelArray;
delete GadgetFunctor;
}
//
void TBarDescr::SetBuilder(const TGadgetFunctor& functor)
{
*GadgetFunctor = functor;
}
// -----------------------------------------------------------------------------
/// Set new bitmap for use in gadgets.
bool
TBarDescr::SetBitmap(TResId newResId, TModule* module)
{
delete BarRes;
BarRes = 0;
Module = module;
// Load toolbar resource
// NOTE: Don't let TToolbarRes own bitmap, we'll give it to TCelArray
// instead.
BarRes = new TToolbarRes(module ? module->GetHandle() : 0,
newResId,
NoAutoDelete);
if (BarRes->IsOK()){
delete CelArray;
CelArray = 0;
{ // map colors
TBtnBitmap bitmap(BarRes->GetBitmap(),
TColor::LtGray,
NoAutoDelete);
}
CelArray = new TCelArray(&BarRes->GetBitmap(), BarRes->GetCount(),
TSize(BarRes->GetWidth(), BarRes->GetHeight()),
TPoint(0, 0), // offset
BarRes->GetBitmap().Height()/BarRes->GetHeight());
return true;
}
return false;
}
//
static void CreateGadgets(TBarDescrGdArray* array, const TGadgetFunctor& builder,
TToolbarRes* barRes)
{
for (int i=0,j=0; i < barRes->GetCount(); i++) {
if(barRes->GetIds()[i] == uint16(-1))
continue;
bool usecell;
TGadget* gd = (builder)(j, barRes->GetIds()[i], usecell);
array->Add(new __TBarDescrGdNode(gd,usecell));
if(usecell)
j++;
}
}
// -----------------------------------------------------------------------------
/// Inserts into destWindow's gadgets.
bool
TBarDescr::Create(TGadgetWindow& destWindow)
{
// Build toolbar from resource and from descriptor string
if (BarRes && BarRes->IsOK()) {
if(!Gadgets->Size())
CreateGadgets(Gadgets, *GetBuilder(), BarRes);
int numRows = BarRes->GetBitmap().Height()/BarRes->GetHeight();
TCelArray* cellArray = new TCelArray(TSize(BarRes->GetWidth(), BarRes->GetHeight()),
0, BarRes->GetCount(), 5, numRows);
cellArray->RemoveAll();
destWindow.SetCelArray(cellArray);
for (int i=0,j=0; i < (int)Gadgets->Size(); i++){
destWindow.Insert(*(*Gadgets)[i]->Gadget);
if((*Gadgets)[i]->UseGlyph)
cellArray->Add(*CelArray, j++);
}
return true;
}
return false;
}
// -----------------------------------------------------------------------------
/// Merges this gadgets and sourceBarDescr gadgets and inserts them into
/// destWindow's gadgets.
bool
TBarDescr::Merge(const TBarDescr& srcBarDescr, TGadgetWindow& destWindow)
{
if (BarRes && BarRes->IsOK()){
RemoveGadgets(destWindow);
if(!srcBarDescr.Gadgets->Size())
CreateGadgets(srcBarDescr.Gadgets, *((TBarDescr&)srcBarDescr).GetBuilder(),
srcBarDescr.BarRes);
TCelArray& cellArray = destWindow.GetCelArray();
cellArray.RemoveAll();
int gdIndex1 = 0;
int gdIndex2 = 0;
int cellIndex = 0;
int cellIndex1 = 0;
int cellIndex2 = 0;
for (int g = 0; g < NumGroups; g++){
if (srcBarDescr.GroupCount[g] > 0){
for (int i=0; i < srcBarDescr.GroupCount[g]; i++){
__TBarDescrGdNode* node = (*srcBarDescr.Gadgets)[gdIndex1];
destWindow.Insert(*node->Gadget);
if(node->UseGlyph){
cellArray.Add(*srcBarDescr.CelArray, cellIndex1);
TButtonGadget* bg = TYPESAFE_DOWNCAST(node->Gadget, TButtonGadget);
if(bg)
bg->SetGlyphIndex(cellIndex);
cellIndex++;
cellIndex1++;
}
gdIndex1++;
}
}
else if (srcBarDescr.GroupCount[g] == 0 && GroupCount[g] > 0) {
for (int i=0; i < GroupCount[g]; i++){
__TBarDescrGdNode* node = (*Gadgets)[gdIndex2];
destWindow.Insert(*node->Gadget);
if(node->UseGlyph){
cellArray.Add(*CelArray, cellIndex2);
TButtonGadget* bg = TYPESAFE_DOWNCAST(node->Gadget, TButtonGadget);
if(bg)
bg->SetGlyphIndex(cellIndex);
cellIndex++;
cellIndex2++;
}
gdIndex2++;
}
}
}
destWindow.Invalidate();
destWindow.LayoutSession();
destWindow.UpdateWindow();
return true;
}
return false;
}
// -----------------------------------------------------------------------------
/// Removes the gadgets in destWindow and then inserts these gadgets.
bool
TBarDescr::Restore(TGadgetWindow& destWindow)
{
if (BarRes && BarRes->IsOK()){
RemoveGadgets(destWindow);
TCelArray& cellArray = destWindow.GetCelArray();
cellArray.RemoveAll();
int gdIndex = 0;
int cellIndex = 0;
for (int g=0; g < NumGroups; g++){
if(GroupCount[g]!= 0){
for (int i=0; i < GroupCount[g]; i++){
__TBarDescrGdNode* node = (*Gadgets)[gdIndex];
destWindow.Insert(*node->Gadget);
if(node->UseGlyph){
cellArray.Add(*CelArray, cellIndex);
TButtonGadget* bg = TYPESAFE_DOWNCAST(node->Gadget, TButtonGadget);
if(bg)
bg->SetGlyphIndex(cellIndex);
cellIndex++;
}
gdIndex++;
}
}
}
destWindow.Invalidate();
destWindow.LayoutSession();
destWindow.UpdateWindow();
return true;
}
return false;
}
// -----------------------------------------------------------------------------
/// Removes all gadgets from destWindow.
bool
TBarDescr::RemoveGadgets(TGadgetWindow& destWindow)
{
TGadget* gadget = destWindow.FirstGadget();
if(gadget && gadget->GetId() == IDG_FLATHANDLE)
gadget = gadget->NextGadget();
while (gadget) {
TGadget* tmp = gadget;
gadget = gadget->NextGadget();
destWindow.Remove(*tmp);
}
return true;
}
//
/// Scan bar looking for separators that signify group divisions
/// return whether we found any at all
//
/// Extracts the group counts from the loaded menu bar by counting the number of
/// menus between separator items. After the group counts are extracted, the
/// separators are removed. Returns true if separators (groups) were found; false
/// otherwise.
bool
TBarDescr::ExtractGroups()
{
if (!BarRes)
return false; // no bar to extract from...
// walk BarRes & remove separators, setting up count as we go.
//
int itemCount = BarRes->GetCount();
int g = 0;
int count = 0;
for (int i = 0; i < itemCount;i++) {
if (BarRes->GetIds()[i] == uint16(-1)){
if (g < NumGroups)
GroupCount[g++] = count;
count = 0;
}
else
count++;
}
// Leave if no separators were found
//
bool retval = true;
if (!g)
retval = false;
// Get trailing group
//
if (g < NumGroups)
GroupCount[g++] = count;
// Finish zeroing groups
//
for (; g < NumGroups; g++)
GroupCount[g] = 0;
return retval;
}
//
//
//
#if !defined(BI_NO_OBJ_STREAMING)
//
/// Extract the menu descriptor from the persistent stream.
//
_OWLCFUNC(ipstream&)
operator >>(ipstream& is, TBarDescr& b)
{
is >> b.Id;
is >> b.Module;
b.BarRes = new TToolbarRes((b.Module ? b.Module->GetHandle() : 0), b.Id, NoAutoDelete);
{ // map colors
TBtnBitmap bitmap(b.BarRes->GetBitmap(), TColor::LtGray, NoAutoDelete);
}
int numRows = b.BarRes->GetBitmap().Height()/b.BarRes->GetHeight();
b.CelArray = new TCelArray(&b.BarRes->GetBitmap(),b.BarRes->GetCount(),
TSize(b.BarRes->GetWidth(), b.BarRes->GetHeight()),
TPoint(0, 0), // offset
numRows);
for (int i = 0; i < TBarDescr::NumGroups; i++)
is >> b.GroupCount[i];
return is;
}
//
/// Insert the menu descriptor into the persistent stream.
//
_OWLCFUNC(opstream&)
operator <<(opstream& os, const TBarDescr& b)
{
os << b.Id;
os << b.Module;
for (int i = 0; i < TBarDescr::NumGroups; i++)
os << b.GroupCount[i];
return os;
}
#endif // #if !defined(BI_NO_OBJ_STREAMING)
} // OWL namespace
/* ========================================================================== */
| [
"Pierre.Best@taxsystems.com"
] | Pierre.Best@taxsystems.com |
1b223ad0cab3a25173b1c4f0332ea7962e371ac1 | 84e0b9b87646a4563a31c2408397d829b20fed5e | /src/txmempool.cpp | 3600cc29fc7bdf23b6edd7525d3a0b1813265655 | [
"MIT"
] | permissive | Frenchh/Code-source | a47f1bf8b0b656fd3e7e0b683962df8fb84db984 | fb684160eb23a6f4019d8f3cbee4405348ba5215 | refs/heads/master | 2020-04-07T21:53:30.443384 | 2018-11-24T22:46:10 | 2018-11-24T22:46:10 | 158,733,776 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 26,617 | cpp | // Copyright (c) 2009-2010 Satoshi Nakamoto
// Copyright (c) 2009-2014 The Bitcoin developers
// Copyright (c) 2016-2017 The PIVX developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
#include "txmempool.h"
#include "clientversion.h"
#include "main.h"
#include "streams.h"
#include "util.h"
#include "utilmoneystr.h"
#include "version.h"
#include <boost/circular_buffer.hpp>
using namespace std;
CTxMemPoolEntry::CTxMemPoolEntry() : nFee(0), nTxSize(0), nModSize(0), nTime(0), dPriority(0.0)
{
nHeight = MEMPOOL_HEIGHT;
}
CTxMemPoolEntry::CTxMemPoolEntry(const CTransaction& _tx, const CAmount& _nFee, int64_t _nTime, double _dPriority, unsigned int _nHeight) : tx(_tx), nFee(_nFee), nTime(_nTime), dPriority(_dPriority), nHeight(_nHeight)
{
nTxSize = ::GetSerializeSize(tx, SER_NETWORK, PROTOCOL_VERSION);
nModSize = tx.CalculateModifiedSize(nTxSize);
}
CTxMemPoolEntry::CTxMemPoolEntry(const CTxMemPoolEntry& other)
{
*this = other;
}
double
CTxMemPoolEntry::GetPriority(unsigned int currentHeight) const
{
CAmount nValueIn = tx.GetValueOut() + nFee;
double deltaPriority = ((double)(currentHeight - nHeight) * nValueIn) / nModSize;
double dResult = dPriority + deltaPriority;
return dResult;
}
/**
* Keep track of fee/priority for transactions confirmed within N blocks
*/
class CBlockAverage
{
private:
boost::circular_buffer<CFeeRate> feeSamples;
boost::circular_buffer<double> prioritySamples;
template <typename T>
std::vector<T> buf2vec(boost::circular_buffer<T> buf) const
{
std::vector<T> vec(buf.begin(), buf.end());
return vec;
}
public:
CBlockAverage() : feeSamples(100), prioritySamples(100) {}
void RecordFee(const CFeeRate& feeRate)
{
feeSamples.push_back(feeRate);
}
void RecordPriority(double priority)
{
prioritySamples.push_back(priority);
}
size_t FeeSamples() const { return feeSamples.size(); }
size_t GetFeeSamples(std::vector<CFeeRate>& insertInto) const
{
BOOST_FOREACH (const CFeeRate& f, feeSamples)
insertInto.push_back(f);
return feeSamples.size();
}
size_t PrioritySamples() const { return prioritySamples.size(); }
size_t GetPrioritySamples(std::vector<double>& insertInto) const
{
BOOST_FOREACH (double d, prioritySamples)
insertInto.push_back(d);
return prioritySamples.size();
}
/**
* Used as belt-and-suspenders check when reading to detect
* file corruption
*/
static bool AreSane(const CFeeRate fee, const CFeeRate& minRelayFee)
{
if (fee < CFeeRate(0))
return false;
if (fee.GetFeePerK() > minRelayFee.GetFeePerK() * 10000)
return false;
return true;
}
static bool AreSane(const std::vector<CFeeRate>& vecFee, const CFeeRate& minRelayFee)
{
BOOST_FOREACH (CFeeRate fee, vecFee) {
if (!AreSane(fee, minRelayFee))
return false;
}
return true;
}
static bool AreSane(const double priority)
{
return priority >= 0;
}
static bool AreSane(const std::vector<double> vecPriority)
{
BOOST_FOREACH (double priority, vecPriority) {
if (!AreSane(priority))
return false;
}
return true;
}
void Write(CAutoFile& fileout) const
{
std::vector<CFeeRate> vecFee = buf2vec(feeSamples);
fileout << vecFee;
std::vector<double> vecPriority = buf2vec(prioritySamples);
fileout << vecPriority;
}
void Read(CAutoFile& filein, const CFeeRate& minRelayFee)
{
std::vector<CFeeRate> vecFee;
filein >> vecFee;
if (AreSane(vecFee, minRelayFee))
feeSamples.insert(feeSamples.end(), vecFee.begin(), vecFee.end());
else
throw runtime_error("Corrupt fee value in estimates file.");
std::vector<double> vecPriority;
filein >> vecPriority;
if (AreSane(vecPriority))
prioritySamples.insert(prioritySamples.end(), vecPriority.begin(), vecPriority.end());
else
throw runtime_error("Corrupt priority value in estimates file.");
if (feeSamples.size() + prioritySamples.size() > 0)
LogPrint("estimatefee", "Read %d fee samples and %d priority samples\n",
feeSamples.size(), prioritySamples.size());
}
};
class CMinerPolicyEstimator
{
private:
/**
* Records observed averages transactions that confirmed within one block, two blocks,
* three blocks etc.
*/
std::vector<CBlockAverage> history;
std::vector<CFeeRate> sortedFeeSamples;
std::vector<double> sortedPrioritySamples;
int nBestSeenHeight;
/**
* nBlocksAgo is 0 based, i.e. transactions that confirmed in the highest seen block are
* nBlocksAgo == 0, transactions in the block before that are nBlocksAgo == 1 etc.
*/
void seenTxConfirm(const CFeeRate& feeRate, const CFeeRate& minRelayFee, double dPriority, int nBlocksAgo)
{
// Last entry records "everything else".
int nBlocksTruncated = min(nBlocksAgo, (int)history.size() - 1);
assert(nBlocksTruncated >= 0);
// We need to guess why the transaction was included in a block-- either
// because it is high-priority or because it has sufficient fees.
bool sufficientFee = (feeRate > minRelayFee);
bool sufficientPriority = AllowFree(dPriority);
const char* assignedTo = "unassigned";
if (sufficientFee && !sufficientPriority && CBlockAverage::AreSane(feeRate, minRelayFee)) {
history[nBlocksTruncated].RecordFee(feeRate);
assignedTo = "fee";
} else if (sufficientPriority && !sufficientFee && CBlockAverage::AreSane(dPriority)) {
history[nBlocksTruncated].RecordPriority(dPriority);
assignedTo = "priority";
} else {
// Neither or both fee and priority sufficient to get confirmed:
// don't know why they got confirmed.
}
LogPrint("estimatefee", "Seen TX confirm: %s : %s fee/%g priority, took %d blocks\n",
assignedTo, feeRate.ToString(), dPriority, nBlocksAgo);
}
public:
CMinerPolicyEstimator(int nEntries) : nBestSeenHeight(0)
{
history.resize(nEntries);
}
void seenBlock(const std::vector<CTxMemPoolEntry>& entries, int nBlockHeight, const CFeeRate minRelayFee)
{
if (nBlockHeight <= nBestSeenHeight) {
// Ignore side chains and re-orgs; assuming they are random
// they don't affect the estimate.
// And if an attacker can re-org the chain at will, then
// you've got much bigger problems than "attacker can influence
// transaction fees."
return;
}
nBestSeenHeight = nBlockHeight;
// Fill up the history buckets based on how long transactions took
// to confirm.
std::vector<std::vector<const CTxMemPoolEntry*> > entriesByConfirmations;
entriesByConfirmations.resize(history.size());
BOOST_FOREACH (const CTxMemPoolEntry& entry, entries) {
// How many blocks did it take for miners to include this transaction?
int delta = nBlockHeight - entry.GetHeight();
if (delta <= 0) {
// Re-org made us lose height, this should only happen if we happen
// to re-org on a difficulty transition point: very rare!
continue;
}
if ((delta - 1) >= (int)history.size())
delta = history.size(); // Last bucket is catch-all
entriesByConfirmations.at(delta - 1).push_back(&entry);
}
for (size_t i = 0; i < entriesByConfirmations.size(); i++) {
std::vector<const CTxMemPoolEntry*>& e = entriesByConfirmations.at(i);
// Insert at most 10 random entries per bucket, otherwise a single block
// can dominate an estimate:
if (e.size() > 10) {
std::random_shuffle(e.begin(), e.end());
e.resize(10);
}
BOOST_FOREACH (const CTxMemPoolEntry* entry, e) {
// Fees are stored and reported as FRENCH-per-kb:
CFeeRate feeRate(entry->GetFee(), entry->GetTxSize());
double dPriority = entry->GetPriority(entry->GetHeight()); // Want priority when it went IN
seenTxConfirm(feeRate, minRelayFee, dPriority, i);
}
}
//After new samples are added, we have to clear the sorted lists,
//so they'll be resorted the next time someone asks for an estimate
sortedFeeSamples.clear();
sortedPrioritySamples.clear();
for (size_t i = 0; i < history.size(); i++) {
if (history[i].FeeSamples() + history[i].PrioritySamples() > 0)
LogPrint("estimatefee", "estimates: for confirming within %d blocks based on %d/%d samples, fee=%s, prio=%g\n",
i,
history[i].FeeSamples(), history[i].PrioritySamples(),
estimateFee(i + 1).ToString(), estimatePriority(i + 1));
}
}
/**
* Can return CFeeRate(0) if we don't have any data for that many blocks back. nBlocksToConfirm is 1 based.
*/
CFeeRate estimateFee(int nBlocksToConfirm)
{
nBlocksToConfirm--;
if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
return CFeeRate(0);
if (sortedFeeSamples.size() == 0) {
for (size_t i = 0; i < history.size(); i++)
history.at(i).GetFeeSamples(sortedFeeSamples);
std::sort(sortedFeeSamples.begin(), sortedFeeSamples.end(),
std::greater<CFeeRate>());
}
if (sortedFeeSamples.size() < 11) {
// Eleven is Gavin's Favorite Number
// ... but we also take a maximum of 10 samples per block so eleven means
// we're getting samples from at least two different blocks
return CFeeRate(0);
}
int nBucketSize = history.at(nBlocksToConfirm).FeeSamples();
// Estimates should not increase as number of confirmations goes up,
// but the estimates are noisy because confirmations happen discretely
// in blocks. To smooth out the estimates, use all samples in the history
// and use the nth highest where n is (number of samples in previous bucket +
// half the samples in nBlocksToConfirm bucket):
size_t nPrevSize = 0;
for (int i = 0; i < nBlocksToConfirm; i++)
nPrevSize += history.at(i).FeeSamples();
size_t index = min(nPrevSize + nBucketSize / 2, sortedFeeSamples.size() - 1);
return sortedFeeSamples[index];
}
double estimatePriority(int nBlocksToConfirm)
{
nBlocksToConfirm--;
if (nBlocksToConfirm < 0 || nBlocksToConfirm >= (int)history.size())
return -1;
if (sortedPrioritySamples.size() == 0) {
for (size_t i = 0; i < history.size(); i++)
history.at(i).GetPrioritySamples(sortedPrioritySamples);
std::sort(sortedPrioritySamples.begin(), sortedPrioritySamples.end(),
std::greater<double>());
}
if (sortedPrioritySamples.size() < 11)
return -1.0;
int nBucketSize = history.at(nBlocksToConfirm).PrioritySamples();
// Estimates should not increase as number of confirmations needed goes up,
// but the estimates are noisy because confirmations happen discretely
// in blocks. To smooth out the estimates, use all samples in the history
// and use the nth highest where n is (number of samples in previous buckets +
// half the samples in nBlocksToConfirm bucket).
size_t nPrevSize = 0;
for (int i = 0; i < nBlocksToConfirm; i++)
nPrevSize += history.at(i).PrioritySamples();
size_t index = min(nPrevSize + nBucketSize / 2, sortedPrioritySamples.size() - 1);
return sortedPrioritySamples[index];
}
void Write(CAutoFile& fileout) const
{
fileout << nBestSeenHeight;
fileout << history.size();
BOOST_FOREACH (const CBlockAverage& entry, history) {
entry.Write(fileout);
}
}
void Read(CAutoFile& filein, const CFeeRate& minRelayFee)
{
int nFileBestSeenHeight;
filein >> nFileBestSeenHeight;
size_t numEntries;
filein >> numEntries;
if (numEntries <= 0 || numEntries > 10000)
throw runtime_error("Corrupt estimates file. Must have between 1 and 10k entries.");
std::vector<CBlockAverage> fileHistory;
for (size_t i = 0; i < numEntries; i++) {
CBlockAverage entry;
entry.Read(filein, minRelayFee);
fileHistory.push_back(entry);
}
// Now that we've processed the entire fee estimate data file and not
// thrown any errors, we can copy it to our history
nBestSeenHeight = nFileBestSeenHeight;
history = fileHistory;
assert(history.size() > 0);
}
};
CTxMemPool::CTxMemPool(const CFeeRate& _minRelayFee) : nTransactionsUpdated(0),
minRelayFee(_minRelayFee)
{
// Sanity checks off by default for performance, because otherwise
// accepting transactions becomes O(N^2) where N is the number
// of transactions in the pool
fSanityCheck = false;
// 25 blocks is a compromise between using a lot of disk/memory and
// trying to give accurate estimates to people who might be willing
// to wait a day or two to save a fraction of a penny in fees.
// Confirmation times for very-low-fee transactions that take more
// than an hour or three to confirm are highly variable.
minerPolicyEstimator = new CMinerPolicyEstimator(25);
}
CTxMemPool::~CTxMemPool()
{
delete minerPolicyEstimator;
}
void CTxMemPool::pruneSpent(const uint256& hashTx, CCoins& coins)
{
LOCK(cs);
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.lower_bound(COutPoint(hashTx, 0));
// iterate over all COutPoints in mapNextTx whose hash equals the provided hashTx
while (it != mapNextTx.end() && it->first.hash == hashTx) {
coins.Spend(it->first.n); // and remove those outputs from coins
it++;
}
}
unsigned int CTxMemPool::GetTransactionsUpdated() const
{
LOCK(cs);
return nTransactionsUpdated;
}
void CTxMemPool::AddTransactionsUpdated(unsigned int n)
{
LOCK(cs);
nTransactionsUpdated += n;
}
bool CTxMemPool::addUnchecked(const uint256& hash, const CTxMemPoolEntry& entry)
{
// Add to memory pool without checking anything.
// Used by main.cpp AcceptToMemoryPool(), which DOES do
// all the appropriate checks.
LOCK(cs);
{
mapTx[hash] = entry;
const CTransaction& tx = mapTx[hash].GetTx();
for (unsigned int i = 0; i < tx.vin.size(); i++)
mapNextTx[tx.vin[i].prevout] = CInPoint(&tx, i);
nTransactionsUpdated++;
totalTxSize += entry.GetTxSize();
}
return true;
}
void CTxMemPool::remove(const CTransaction& origTx, std::list<CTransaction>& removed, bool fRecursive)
{
// Remove transaction from memory pool
{
LOCK(cs);
std::deque<uint256> txToRemove;
txToRemove.push_back(origTx.GetHash());
if (fRecursive && !mapTx.count(origTx.GetHash())) {
// If recursively removing but origTx isn't in the mempool
// be sure to remove any children that are in the pool. This can
// happen during chain re-orgs if origTx isn't re-accepted into
// the mempool for any reason.
for (unsigned int i = 0; i < origTx.vout.size(); i++) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(origTx.GetHash(), i));
if (it == mapNextTx.end())
continue;
txToRemove.push_back(it->second.ptx->GetHash());
}
}
while (!txToRemove.empty()) {
uint256 hash = txToRemove.front();
txToRemove.pop_front();
if (!mapTx.count(hash))
continue;
const CTransaction& tx = mapTx[hash].GetTx();
if (fRecursive) {
for (unsigned int i = 0; i < tx.vout.size(); i++) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(COutPoint(hash, i));
if (it == mapNextTx.end())
continue;
txToRemove.push_back(it->second.ptx->GetHash());
}
}
BOOST_FOREACH (const CTxIn& txin, tx.vin)
mapNextTx.erase(txin.prevout);
removed.push_back(tx);
totalTxSize -= mapTx[hash].GetTxSize();
mapTx.erase(hash);
nTransactionsUpdated++;
}
}
}
void CTxMemPool::removeCoinbaseSpends(const CCoinsViewCache* pcoins, unsigned int nMemPoolHeight)
{
// Remove transactions spending a coinbase which are now immature
LOCK(cs);
list<CTransaction> transactionsToRemove;
for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
const CTransaction& tx = it->second.GetTx();
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end())
continue;
const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
if (fSanityCheck) assert(coins);
if (!coins || ((coins->IsCoinBase() || coins->IsCoinStake()) && nMemPoolHeight - coins->nHeight < (unsigned)Params().COINBASE_MATURITY())) {
transactionsToRemove.push_back(tx);
break;
}
}
}
BOOST_FOREACH (const CTransaction& tx, transactionsToRemove) {
list<CTransaction> removed;
remove(tx, removed, true);
}
}
void CTxMemPool::removeConflicts(const CTransaction& tx, std::list<CTransaction>& removed)
{
// Remove transactions which depend on inputs of tx, recursively
list<CTransaction> result;
LOCK(cs);
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
std::map<COutPoint, CInPoint>::iterator it = mapNextTx.find(txin.prevout);
if (it != mapNextTx.end()) {
const CTransaction& txConflict = *it->second.ptx;
if (txConflict != tx) {
remove(txConflict, removed, true);
}
}
}
}
/**
* Called when a block is connected. Removes from mempool and updates the miner fee estimator.
*/
void CTxMemPool::removeForBlock(const std::vector<CTransaction>& vtx, unsigned int nBlockHeight, std::list<CTransaction>& conflicts)
{
LOCK(cs);
std::vector<CTxMemPoolEntry> entries;
BOOST_FOREACH (const CTransaction& tx, vtx) {
uint256 hash = tx.GetHash();
if (mapTx.count(hash))
entries.push_back(mapTx[hash]);
}
minerPolicyEstimator->seenBlock(entries, nBlockHeight, minRelayFee);
BOOST_FOREACH (const CTransaction& tx, vtx) {
std::list<CTransaction> dummy;
remove(tx, dummy, false);
removeConflicts(tx, conflicts);
ClearPrioritisation(tx.GetHash());
}
}
void CTxMemPool::clear()
{
LOCK(cs);
mapTx.clear();
mapNextTx.clear();
totalTxSize = 0;
++nTransactionsUpdated;
}
void CTxMemPool::check(const CCoinsViewCache* pcoins) const
{
if (!fSanityCheck)
return;
LogPrint("mempool", "Checking mempool with %u transactions and %u inputs\n", (unsigned int)mapTx.size(), (unsigned int)mapNextTx.size());
uint64_t checkTotal = 0;
CCoinsViewCache mempoolDuplicate(const_cast<CCoinsViewCache*>(pcoins));
LOCK(cs);
list<const CTxMemPoolEntry*> waitingOnDependants;
for (std::map<uint256, CTxMemPoolEntry>::const_iterator it = mapTx.begin(); it != mapTx.end(); it++) {
unsigned int i = 0;
checkTotal += it->second.GetTxSize();
const CTransaction& tx = it->second.GetTx();
bool fDependsWait = false;
BOOST_FOREACH (const CTxIn& txin, tx.vin) {
// Check that every mempool transaction's inputs refer to available coins, or other mempool tx's.
std::map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(txin.prevout.hash);
if (it2 != mapTx.end()) {
const CTransaction& tx2 = it2->second.GetTx();
assert(tx2.vout.size() > txin.prevout.n && !tx2.vout[txin.prevout.n].IsNull());
fDependsWait = true;
} else {
const CCoins* coins = pcoins->AccessCoins(txin.prevout.hash);
assert(coins && coins->IsAvailable(txin.prevout.n));
}
// Check whether its inputs are marked in mapNextTx.
std::map<COutPoint, CInPoint>::const_iterator it3 = mapNextTx.find(txin.prevout);
assert(it3 != mapNextTx.end());
assert(it3->second.ptx == &tx);
assert(it3->second.n == i);
i++;
}
if (fDependsWait)
waitingOnDependants.push_back(&it->second);
else {
CValidationState state;
CTxUndo undo;
assert(CheckInputs(tx, state, mempoolDuplicate, false, 0, false, NULL));
UpdateCoins(tx, state, mempoolDuplicate, undo, 1000000);
}
}
unsigned int stepsSinceLastRemove = 0;
while (!waitingOnDependants.empty()) {
const CTxMemPoolEntry* entry = waitingOnDependants.front();
waitingOnDependants.pop_front();
CValidationState state;
if (!mempoolDuplicate.HaveInputs(entry->GetTx())) {
waitingOnDependants.push_back(entry);
stepsSinceLastRemove++;
assert(stepsSinceLastRemove < waitingOnDependants.size());
} else {
assert(CheckInputs(entry->GetTx(), state, mempoolDuplicate, false, 0, false, NULL));
CTxUndo undo;
UpdateCoins(entry->GetTx(), state, mempoolDuplicate, undo, 1000000);
stepsSinceLastRemove = 0;
}
}
for (std::map<COutPoint, CInPoint>::const_iterator it = mapNextTx.begin(); it != mapNextTx.end(); it++) {
uint256 hash = it->second.ptx->GetHash();
map<uint256, CTxMemPoolEntry>::const_iterator it2 = mapTx.find(hash);
const CTransaction& tx = it2->second.GetTx();
assert(it2 != mapTx.end());
assert(&tx == it->second.ptx);
assert(tx.vin.size() > it->second.n);
assert(it->first == it->second.ptx->vin[it->second.n].prevout);
}
assert(totalTxSize == checkTotal);
}
void CTxMemPool::queryHashes(vector<uint256>& vtxid)
{
vtxid.clear();
LOCK(cs);
vtxid.reserve(mapTx.size());
for (map<uint256, CTxMemPoolEntry>::iterator mi = mapTx.begin(); mi != mapTx.end(); ++mi)
vtxid.push_back((*mi).first);
}
bool CTxMemPool::lookup(uint256 hash, CTransaction& result) const
{
LOCK(cs);
map<uint256, CTxMemPoolEntry>::const_iterator i = mapTx.find(hash);
if (i == mapTx.end()) return false;
result = i->second.GetTx();
return true;
}
CFeeRate CTxMemPool::estimateFee(int nBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimateFee(nBlocks);
}
double CTxMemPool::estimatePriority(int nBlocks) const
{
LOCK(cs);
return minerPolicyEstimator->estimatePriority(nBlocks);
}
bool CTxMemPool::WriteFeeEstimates(CAutoFile& fileout) const
{
try {
LOCK(cs);
fileout << 120000; // version required to read: 0.12.00 or later
fileout << CLIENT_VERSION; // version that wrote the file
minerPolicyEstimator->Write(fileout);
} catch (const std::exception&) {
LogPrintf("CTxMemPool::WriteFeeEstimates() : unable to write policy estimator data (non-fatal)");
return false;
}
return true;
}
bool CTxMemPool::ReadFeeEstimates(CAutoFile& filein)
{
try {
int nVersionRequired, nVersionThatWrote;
filein >> nVersionRequired >> nVersionThatWrote;
if (nVersionRequired > CLIENT_VERSION)
return error("CTxMemPool::ReadFeeEstimates() : up-version (%d) fee estimate file", nVersionRequired);
LOCK(cs);
minerPolicyEstimator->Read(filein, minRelayFee);
} catch (const std::exception&) {
LogPrintf("CTxMemPool::ReadFeeEstimates() : unable to read policy estimator data (non-fatal)");
return false;
}
return true;
}
void CTxMemPool::PrioritiseTransaction(const uint256 hash, const string strHash, double dPriorityDelta, const CAmount& nFeeDelta)
{
{
LOCK(cs);
std::pair<double, CAmount>& deltas = mapDeltas[hash];
deltas.first += dPriorityDelta;
deltas.second += nFeeDelta;
}
LogPrintf("PrioritiseTransaction: %s priority += %f, fee += %d\n", strHash, dPriorityDelta, FormatMoney(nFeeDelta));
}
void CTxMemPool::ApplyDeltas(const uint256 hash, double& dPriorityDelta, CAmount& nFeeDelta)
{
LOCK(cs);
std::map<uint256, std::pair<double, CAmount> >::iterator pos = mapDeltas.find(hash);
if (pos == mapDeltas.end())
return;
const std::pair<double, CAmount>& deltas = pos->second;
dPriorityDelta += deltas.first;
nFeeDelta += deltas.second;
}
void CTxMemPool::ClearPrioritisation(const uint256 hash)
{
LOCK(cs);
mapDeltas.erase(hash);
}
CCoinsViewMemPool::CCoinsViewMemPool(CCoinsView* baseIn, CTxMemPool& mempoolIn) : CCoinsViewBacked(baseIn), mempool(mempoolIn) {}
bool CCoinsViewMemPool::GetCoins(const uint256& txid, CCoins& coins) const
{
// If an entry in the mempool exists, always return that one, as it's guaranteed to never
// conflict with the underlying cache, and it cannot have pruned entries (as it contains full)
// transactions. First checking the underlying cache risks returning a pruned entry instead.
CTransaction tx;
if (mempool.lookup(txid, tx)) {
coins = CCoins(tx, MEMPOOL_HEIGHT);
return true;
}
return (base->GetCoins(txid, coins) && !coins.IsPruned());
}
bool CCoinsViewMemPool::HaveCoins(const uint256& txid) const
{
return mempool.exists(txid) || base->HaveCoins(txid);
}
| [
"florent.accault@gmail.com"
] | florent.accault@gmail.com |
e5eadf7ddd6821ae7de3efa6aa2d42bc07564637 | c436fc304da315ed7cfa4129faaba14d165a246e | /foundation/include/json/rapidjson/internal/strfunc.h | c68608bece690645b1206e591be8c0614fa77644 | [] | no_license | wjbwstone/wstone | dae656ffff30616d85293bcc356ab7ab7cebd5ba | 25da4de6900e6cc34a96a3882f1307b7a9bbf8b0 | refs/heads/main | 2023-02-17T16:44:50.679974 | 2021-01-20T05:53:24 | 2021-01-20T05:53:24 | 330,961,566 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,378 | h | // Tencent is pleased to support the open source community by making RapidJSON available.
//
// Copyright (C) 2015 THL A29 Limited, a Tencent company, and Milo Yip. All rights reserved.
//
// Licensed under the MIT License (the "License"); you may not use this file except
// in compliance with the License. You may obtain a copy of the License at
//
// http://opensource.org/licenses/MIT
//
// Unless required by applicable law or agreed to in writing, software distributed
// under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR
// CONDITIONS OF ANY KIND, either express or implied. See the License for the
// specific language governing permissions and limitations under the License.
#ifndef RAPIDJSON_INTERNAL_STRFUNC_H_
#define RAPIDJSON_INTERNAL_STRFUNC_H_
#include "../stream.h"
#include <cwchar>
RAPIDJSON_NAMESPACE_BEGIN
namespace internal {
//! Custom strlen() which works on different character types.
/*! \tparam Ch Character type (e.g. char, wchar_t, short)
\param s Null-terminated input string.
\return Number of characters in the string.
\note This has the same semantics as strlen(), the return value is not number of Unicode codepoints.
*/
template <typename Ch>
inline SizeType StrLen(const Ch* s) {
if(nullptr != s) {
const Ch* p = s;
while(*p) ++p;
return SizeType(p - s);
}
return 0;
}
template <>
inline SizeType StrLen(const char* s) {
if(nullptr != s) {
return SizeType(std::strlen(s));
}
return 0;
}
template <>
inline SizeType StrLen(const wchar_t* s) {
if(nullptr != s) {
return SizeType(std::wcslen(s));
}
return 0;
}
//! Returns number of code points in a encoded string.
template<typename Encoding>
bool CountStringCodePoint(const typename Encoding::Ch* s, SizeType length, SizeType* outCount) {
RAPIDJSON_ASSERT(s != 0);
RAPIDJSON_ASSERT(outCount != 0);
if(nullptr == s || 0 == outCount) {
return false;
}
GenericStringStream<Encoding> is(s);
const typename Encoding::Ch* end = s + length;
SizeType count = 0;
while (is.src_ < end) {
unsigned codepoint;
if (!Encoding::Decode(is, &codepoint))
return false;
count++;
}
*outCount = count;
return true;
}
} // namespace internal
RAPIDJSON_NAMESPACE_END
#endif // RAPIDJSON_INTERNAL_STRFUNC_H_
| [
"junbo.wen@enmotech.com"
] | junbo.wen@enmotech.com |
cf279c3418b6982564e7d5b7990c43ff8ac3bf21 | 72117e99852982d1974b87c154334722487b23cd | /d3d11example/ImportModel.h | 10113974625b5b802c6c721683d2d60d639d40a7 | [] | no_license | monk973/d3d11example | d27a1f38889b2e5f2ec56678b835bfc3800ca5d7 | c9be730263335d19eab5dfb902c4225530e9a4c9 | refs/heads/master | 2021-01-10T06:10:00.985188 | 2016-04-11T08:20:45 | 2016-04-11T08:20:45 | 50,535,238 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 448 | h | #pragma once
#include "GameStatic.h"
class ImportModel
{
public:
ImportModel();
virtual ~ImportModel();
public:
void Init(char* dirWithFileName);
char* LoadStringFromFile(char* dirWithFileName);
void LoadAtOnce();
void LoadVertex();
void LoadUV();
void LoadNormal();
void LoadMaterial();
vertex_ptn* GetVerticesInfo();
int GetVertexCount();
private:
string m_string;
vertex_ptn* m_vertices=nullptr;
int m_vertexCount = 0;
};
| [
"monk973@naver.com"
] | monk973@naver.com |
f3f66b562502757f6949f6a263f445b27a9d4f27 | 1674b5520a838ef78c227226339e5ff580cdf6e1 | /TextureMapping/Vertex.cpp | 5aa7672418d03b62978d320d8e9530884e191d8f | [] | no_license | jorgeag-google/VulkanTutorial | 8482eb912f4b7931ff34700bb2822cc7315af51b | 36cc1b2c047a7ea4d557a69bcc2f380131bfc9a4 | refs/heads/main | 2023-06-10T06:32:21.321815 | 2021-07-02T20:43:15 | 2021-07-02T20:43:15 | 376,126,123 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,114 | cpp | #include "Vertex.h"
VkVertexInputBindingDescription Vertex::getBindingDescription() {
VkVertexInputBindingDescription bindingDescription{};
bindingDescription.binding = 0;
bindingDescription.stride = sizeof(Vertex);
bindingDescription.inputRate = VK_VERTEX_INPUT_RATE_VERTEX;
return bindingDescription;
}
std::array<VkVertexInputAttributeDescription, 3> Vertex::getAttributeDescriptions() {
std::array<VkVertexInputAttributeDescription, 3> attributeDescriptions{};
attributeDescriptions[0].binding = 0;
attributeDescriptions[0].location = 0;
attributeDescriptions[0].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[0].offset = offsetof(Vertex, pos);
attributeDescriptions[1].binding = 0;
attributeDescriptions[1].location = 1;
attributeDescriptions[1].format = VK_FORMAT_R32G32B32_SFLOAT;
attributeDescriptions[1].offset = offsetof(Vertex, color);
attributeDescriptions[2].binding = 0;
attributeDescriptions[2].location = 2;
attributeDescriptions[2].format = VK_FORMAT_R32G32_SFLOAT;
attributeDescriptions[2].offset = offsetof(Vertex, texCoord);
return attributeDescriptions;
} | [
"jorgeag@google.com"
] | jorgeag@google.com |
ebe869f645434fa331a6d8021f9b18eb1a668423 | 715cf2089f8882c3a5f9ab0cb64bbdbc1466ce02 | /sem5/rsa.cpp | cbac1eb452bd1f284a5ede94d582a562fafd46c3 | [] | no_license | ShriBatman/myCodes | def9de8b72b5d406d2fb2a0c07cd8e7294679019 | 72798e04f8b504ddc7ae2ae2295dea13a94156ff | refs/heads/master | 2021-01-17T19:23:15.520349 | 2019-04-20T12:25:43 | 2019-04-20T12:25:43 | 95,568,212 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 587 | cpp | //i am vengence i am the night i am Batman
//ios_base::sync_with_stdio(false);cin.tie(NULL);
#include<bits/stdc++.h>
using namespace std;
long long int gcd(long long int a,long long int b){
if(a<b){
long long int p = a;
a=b;
b=p;
}
return a%b==0?b:gcd(b,a%b);
}
int main()
{
long long int i,j,k,l,m,n,r,t,p,q,phi,e,d;
cin>>m;
p=3;
q=7;
n=p*q;
phi = (p-1)*(q-1);
e=2;
while(1){
if(gcd(e,phi)==1) break;
else e++;
}
d=(1+(2*phi))/e;
k = pow(m,e);
k = fmod(k,n);
cout<<k<<"\n";
t = pow(k,d);
t = fmod(t,n);
cout<<t<<"\n";
return 0;
}
| [
"aksh.scg@gmail.com"
] | aksh.scg@gmail.com |
dd0a8ed6f8f006eee5152c685537f5d04c3ae840 | 6a6984544a4782e131510a81ed32cc0c545ab89c | /src/filter-tools/public/filter-tools/FilterCheckModule.h | 81a44f957440ee9f2ff01f4c805677873db612a6 | [] | no_license | wardVD/IceSimV05 | f342c035c900c0555fb301a501059c37057b5269 | 6ade23a2fd990694df4e81bed91f8d1fa1287d1f | refs/heads/master | 2020-11-27T21:41:05.707538 | 2016-09-02T09:45:50 | 2016-09-02T09:45:50 | 67,210,139 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 975 | h | #ifndef FILTERCHECKMODULE_H_INCLUDED
#define FILTERCHECKMODULE_H_INCLUDED
/**
* @author Kevin Meagher
*
* @brief This module verifies the result of the pole filter
*
* If you re-run the reconstructions and filters in the north,
* this module will check the results of the filters still in I3Bools
* against the I3FilterResultMap that the pole filter generated.
* It prints the result to standard out.
*/
#include <icetray/I3Module.h>
class FilterCheckModule : public I3Module
{
public:
FilterCheckModule(const I3Context& context);
void Configure();
void Physics(I3FramePtr frame);
void Finish();
private:
typedef std::map <std::string, std::pair <int, int> > FilterStatisticsMap;
///map of filter names to number of times the filter matches and the number of comparisons made
FilterStatisticsMap filter_matches_;
///Name of I3FilterResultMap object in frame
std::string filter_result_name_;
};
#endif // FILTERCHECKMODULE_H_INCLUDED
| [
"wardvandriessche@gmail.com"
] | wardvandriessche@gmail.com |
befc1701dc0acf19dba82752547f9983c0f975e4 | 9c214878c7f55f31463e91bd5f9d4f434b86b8c8 | /phSolver/common/phio_posix.cc | 905d83289a0b6beb9c14878fd93ff79608ddb156 | [
"BSD-3-Clause"
] | permissive | SCOREC/phasta | 7b779159ac268f4faee69f1d06c08b0f3db16729 | ae2199b83ce11f226f596152da66a81b5e42dd7b | refs/heads/master | 2023-06-24T15:35:07.005666 | 2020-03-24T22:22:51 | 2020-03-24T22:22:51 | 43,773,717 | 0 | 5 | BSD-3-Clause | 2019-04-02T21:28:30 | 2015-10-06T19:33:37 | Fortran | UTF-8 | C++ | false | false | 2,514 | cc | #include "phIO.h"
#include "phio_base.h"
#include "phio_posix.h"
#include "phComm.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <assert.h>
#include <phastaIO.h>
#include <sstream>
#include <string>
namespace {
std::string appendRank(const char* phrase) {
std::stringstream ss;
ss << phrase << phcomm_rank()+1;
return ss.str();
}
void close(phio_fp f, const char* mode) {
closefile(f->file, mode);
free(f->file);
free(f);
}
}
void posix_openfile(const char filename[], phio_fp f) {
std::string posixName = appendRank(filename);
posix_openfile_single(posixName.c_str(),f);
}
void posix_openfile_single(const char filename[], phio_fp f) {
assert(f->mode == 'r' || f->mode == 'w');
std::string posixName(filename);
if(f->mode == 'r')
openfile(posixName.c_str(), "read", f->file);
else if(f->mode == 'w')
openfile(posixName.c_str(), "write", f->file);
}
void posix_closefile(phio_fp f) {
assert(f->mode == 'r' || f->mode == 'w');
if(f->mode == 'r')
close(f, "read");
else if(f->mode == 'w')
close(f, "write");
}
void posix_readheader(
int* fileDescriptor,
const char keyphrase[],
void* valueArray,
int* nItems,
const char datatype[],
const char iotype[] ) {
readheader(fileDescriptor, keyphrase,
valueArray, nItems, datatype, iotype);
}
void posix_writeheader(
const int* fileDescriptor,
const char keyphrase[],
const void* valueArray,
const int* nItems,
const int* ndataItems,
const char datatype[],
const char iotype[] ) {
writeheader(fileDescriptor, keyphrase, valueArray,
nItems, ndataItems, datatype, iotype);
}
void posix_readdatablock(
int* fileDescriptor,
const char keyphrase[],
void* valueArray,
int* nItems,
const char datatype[],
const char iotype[] ) {
readdatablock(fileDescriptor, keyphrase,
valueArray, nItems, datatype, iotype);
}
void posix_writedatablock(
const int* fileDescriptor,
const char keyphrase[],
const void* valueArray,
const int* nItems,
const char datatype[],
const char iotype[]) {
writedatablock(fileDescriptor, keyphrase, valueArray,
nItems, datatype, iotype);
}
void posix_constructname(
const char* in,
char* out) {
std::string fullname(in);
std::string gname("geombc");
if( fullname.find(gname) != std::string::npos )
fullname.append(".dat");
fullname.append(".");
sprintf(out, "%s", fullname.c_str());
}
| [
"smithc11@rpi.edu"
] | smithc11@rpi.edu |
6bbcced2f1104a8d62725f26a7ca2f2cc9e7cba9 | fcab6942912e1e75628238599411f46126654a80 | /project/CommPrototype/Utilities/Utilities.h | 49166ebebb588a9bcd07af84a7df542b7f4949bb | [] | no_license | Mpandura/Dependency-Based-Code-Publisher | 5f4af2ba79c16402e198cb3619bc4ef08c2b85d1 | 5a04b704893ef15514bf4fe930e62847b00cfb4a | refs/heads/master | 2021-09-03T06:17:14.971792 | 2018-01-06T08:57:06 | 2018-01-06T08:57:06 | 116,468,579 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,586 | h | #ifndef UTILITIES_H
#define UTILITIES_H
///////////////////////////////////////////////////////////////////////
// Utilities.h - small, generally usefule, helper classes //
// ver 1.1 //
// Language: C++, Visual Studio 2015 //
// Application: Most Projects, CSE687 - Object Oriented Design //
// Author: Jim Fawcett, Syracuse University, CST 4-187 //
// jfawcett@twcny.rr.com //
///////////////////////////////////////////////////////////////////////
/*
* Package Operations:
* -------------------
* This package provides classes StringHelper and Converter and a global
* function putline(). This class will be extended continuously for
* awhile to provide convenience functions for general C++ applications.
*
* Build Process:
* --------------
* Required Files: Utilities.h, Utilities.cpp
*
* Build Command: devenv Utilities.sln /rebuild debug
*
* Maintenance History:
* --------------------
* ver 1.1 : 06 Feb 2015
* - fixed bug in split which turns a comma separated string into
* a vector of tokens.
* - added comments
* ver 1.0 : 05 Feb 2016
* - first release
*
* Planned Additions and Changes:
* ------------------------------
* - none yet
*/
#include <string>
#include <vector>
#include <iostream>
#include <sstream>
#include <functional>
namespace Utilities
{
///////////////////////////////////////////////////////////////////
// Utilities for std::string
// - split accepts comma separated list of items and returns
// std::vector containing each item
// - Title writes src string to console with underline of '=' chars
// - title writes src string to console with underline of '-' chars
class StringHelper
{
public:
static std::vector<std::string> split(const std::string& src);
static void Title(const std::string& src, char underline = '-');
static void title(const std::string& src);
static std::string trim(const std::string& src);
std::string Utilities::StringHelper::getFileName(std::string input) {
size_t s = input.size();
size_t index = input.find_last_of('.');
return input.replace(index, s - index, "");
}
static std::string addHeaderAndFooterLines(const std::string& src);
};
///////////////////////////////////////////////////////////////////
// function writes return to console
void putline();
///////////////////////////////////////////////////////////////////
// DisplayLocation writes start address, ending address and size
// to console
std::string ToDecAddressString(size_t address);
std::string ToHexAddressString(size_t address);
template<typename T>
void DisplayLocation(T& t)
{
size_t address = reinterpret_cast<size_t>(&t);
size_t size = sizeof(t);
std::cout << ToDecAddressString(address)
<< " : "
<< ToDecAddressString(address + size)
<< ", " << size;
}
///////////////////////////////////////////////////////////////////
// Converter converts template type T to and from string
template <typename T>
class Converter
{
public:
static std::string toString(const T& t);
static T toValue(const std::string& src);
};
template <typename T>
std::string Converter<T>::toString(const T& t)
{
std::ostringstream out;
out << t;
return out.str();
}
template<typename T>
T Converter<T>::toValue(const std::string& src)
{
std::istringstream in(src);
T t;
in >> t;
return t;
}
}
#endif
| [
"manju.manu94@gmail.com"
] | manju.manu94@gmail.com |
51dae7ea45481b225b9988aa9249ff90b0684369 | b38f2454a645986f71c2228ef6a8a9db2278863f | /src/elle/reactor/http/StatusCode.hh | 4c5cdf69acf67653bc7a6bf6df87700d5539d844 | [
"Apache-2.0"
] | permissive | jerry-zww/elle | 45360045c662c406775fa3c4ed459cbfbaa5f58a | c53b76e3d632fb1ba62090859032354dee35cf79 | refs/heads/master | 2020-03-20T19:09:45.871593 | 2017-09-08T12:45:39 | 2017-09-08T12:45:39 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,745 | hh | #pragma once
#include <iosfwd>
namespace elle
{
namespace reactor
{
namespace http
{
/// HTTP status code
enum class StatusCode
{
Continue = 100,
Switching_Protocols = 101,
OK = 200,
Created = 201,
Accepted = 202,
Non_Authoritative_Information = 203,
No_Content = 204,
Reset_Content = 205,
Partial_Content = 206,
Multiple_Choices = 300,
Moved_Permanently = 301,
Found = 302,
See_Other = 303,
Not_Modified = 304,
Use_Proxy = 305,
Unused = 306,
Temporary_Redirect = 307,
Bad_Request = 400,
Unauthorized = 401,
Payment_Required = 402,
Forbidden = 403,
Not_Found = 404,
Method_Not_Allowed = 405,
Not_Acceptable = 406,
Proxy_Authentication_Required = 407,
Request_Timeout = 408,
Conflict = 409,
Gone = 410,
Length_Required = 411,
Precondition_Failed = 412,
Request_Entity_Too_Large = 413,
Request_URI_Too_Long = 414,
Unsupported_Media_Type = 415,
Requested_Range_Not_Satisfiable = 416,
Expectation_Failed = 417,
Unprocessable_Entity = 422,
Internal_Server_Error = 500,
Not_Implemented = 501,
Bad_Gateway = 502,
Service_Unavailable = 503,
Gateway_Timeout = 504,
HTTP_Version_Not_Supported = 505,
};
std::ostream&
operator <<(std::ostream& output,
StatusCode method);
}
}
}
namespace std
{
template<>
struct hash<elle::reactor::http::StatusCode>
{
size_t
operator ()(elle::reactor::http::StatusCode const& code) const;
};
}
| [
"antony.mechin@docker.com"
] | antony.mechin@docker.com |
25fedd4a3789eb4dc0ef0d90d6c51bf19010e834 | dbc5fd6f0b741d07aca08cff31fe88d2f62e8483 | /lib/Transforms/Scalar/LoopPredication.cpp | 4d056d0db9598deb9311639803cd888899dd927f | [
"LicenseRef-scancode-unknown-license-reference",
"NCSA"
] | permissive | yrnkrn/zapcc | 647246a2ed860f73adb49fa1bd21333d972ff76b | c6a8aa30006d997eff0d60fd37b0e62b8aa0ea50 | refs/heads/master | 2023-03-08T22:55:12.842122 | 2020-07-21T10:21:59 | 2020-07-21T10:21:59 | 137,340,494 | 1,255 | 88 | NOASSERTION | 2020-07-21T10:22:01 | 2018-06-14T10:00:31 | C++ | UTF-8 | C++ | false | false | 27,822 | cpp | //===-- LoopPredication.cpp - Guard based loop predication pass -----------===//
//
// The LLVM Compiler Infrastructure
//
// This file is distributed under the University of Illinois Open Source
// License. See LICENSE.TXT for details.
//
//===----------------------------------------------------------------------===//
//
// The LoopPredication pass tries to convert loop variant range checks to loop
// invariant by widening checks across loop iterations. For example, it will
// convert
//
// for (i = 0; i < n; i++) {
// guard(i < len);
// ...
// }
//
// to
//
// for (i = 0; i < n; i++) {
// guard(n - 1 < len);
// ...
// }
//
// After this transformation the condition of the guard is loop invariant, so
// loop-unswitch can later unswitch the loop by this condition which basically
// predicates the loop by the widened condition:
//
// if (n - 1 < len)
// for (i = 0; i < n; i++) {
// ...
// }
// else
// deoptimize
//
// It's tempting to rely on SCEV here, but it has proven to be problematic.
// Generally the facts SCEV provides about the increment step of add
// recurrences are true if the backedge of the loop is taken, which implicitly
// assumes that the guard doesn't fail. Using these facts to optimize the
// guard results in a circular logic where the guard is optimized under the
// assumption that it never fails.
//
// For example, in the loop below the induction variable will be marked as nuw
// basing on the guard. Basing on nuw the guard predicate will be considered
// monotonic. Given a monotonic condition it's tempting to replace the induction
// variable in the condition with its value on the last iteration. But this
// transformation is not correct, e.g. e = 4, b = 5 breaks the loop.
//
// for (int i = b; i != e; i++)
// guard(i u< len)
//
// One of the ways to reason about this problem is to use an inductive proof
// approach. Given the loop:
//
// if (B(0)) {
// do {
// I = PHI(0, I.INC)
// I.INC = I + Step
// guard(G(I));
// } while (B(I));
// }
//
// where B(x) and G(x) are predicates that map integers to booleans, we want a
// loop invariant expression M such the following program has the same semantics
// as the above:
//
// if (B(0)) {
// do {
// I = PHI(0, I.INC)
// I.INC = I + Step
// guard(G(0) && M);
// } while (B(I));
// }
//
// One solution for M is M = forall X . (G(X) && B(X)) => G(X + Step)
//
// Informal proof that the transformation above is correct:
//
// By the definition of guards we can rewrite the guard condition to:
// G(I) && G(0) && M
//
// Let's prove that for each iteration of the loop:
// G(0) && M => G(I)
// And the condition above can be simplified to G(Start) && M.
//
// Induction base.
// G(0) && M => G(0)
//
// Induction step. Assuming G(0) && M => G(I) on the subsequent
// iteration:
//
// B(I) is true because it's the backedge condition.
// G(I) is true because the backedge is guarded by this condition.
//
// So M = forall X . (G(X) && B(X)) => G(X + Step) implies G(I + Step).
//
// Note that we can use anything stronger than M, i.e. any condition which
// implies M.
//
// When S = 1 (i.e. forward iterating loop), the transformation is supported
// when:
// * The loop has a single latch with the condition of the form:
// B(X) = latchStart + X <pred> latchLimit,
// where <pred> is u<, u<=, s<, or s<=.
// * The guard condition is of the form
// G(X) = guardStart + X u< guardLimit
//
// For the ult latch comparison case M is:
// forall X . guardStart + X u< guardLimit && latchStart + X <u latchLimit =>
// guardStart + X + 1 u< guardLimit
//
// The only way the antecedent can be true and the consequent can be false is
// if
// X == guardLimit - 1 - guardStart
// (and guardLimit is non-zero, but we won't use this latter fact).
// If X == guardLimit - 1 - guardStart then the second half of the antecedent is
// latchStart + guardLimit - 1 - guardStart u< latchLimit
// and its negation is
// latchStart + guardLimit - 1 - guardStart u>= latchLimit
//
// In other words, if
// latchLimit u<= latchStart + guardLimit - 1 - guardStart
// then:
// (the ranges below are written in ConstantRange notation, where [A, B) is the
// set for (I = A; I != B; I++ /*maywrap*/) yield(I);)
//
// forall X . guardStart + X u< guardLimit &&
// latchStart + X u< latchLimit =>
// guardStart + X + 1 u< guardLimit
// == forall X . guardStart + X u< guardLimit &&
// latchStart + X u< latchStart + guardLimit - 1 - guardStart =>
// guardStart + X + 1 u< guardLimit
// == forall X . (guardStart + X) in [0, guardLimit) &&
// (latchStart + X) in [0, latchStart + guardLimit - 1 - guardStart) =>
// (guardStart + X + 1) in [0, guardLimit)
// == forall X . X in [-guardStart, guardLimit - guardStart) &&
// X in [-latchStart, guardLimit - 1 - guardStart) =>
// X in [-guardStart - 1, guardLimit - guardStart - 1)
// == true
//
// So the widened condition is:
// guardStart u< guardLimit &&
// latchStart + guardLimit - 1 - guardStart u>= latchLimit
// Similarly for ule condition the widened condition is:
// guardStart u< guardLimit &&
// latchStart + guardLimit - 1 - guardStart u> latchLimit
// For slt condition the widened condition is:
// guardStart u< guardLimit &&
// latchStart + guardLimit - 1 - guardStart s>= latchLimit
// For sle condition the widened condition is:
// guardStart u< guardLimit &&
// latchStart + guardLimit - 1 - guardStart s> latchLimit
//
// When S = -1 (i.e. reverse iterating loop), the transformation is supported
// when:
// * The loop has a single latch with the condition of the form:
// B(X) = X <pred> latchLimit, where <pred> is u>, u>=, s>, or s>=.
// * The guard condition is of the form
// G(X) = X - 1 u< guardLimit
//
// For the ugt latch comparison case M is:
// forall X. X-1 u< guardLimit and X u> latchLimit => X-2 u< guardLimit
//
// The only way the antecedent can be true and the consequent can be false is if
// X == 1.
// If X == 1 then the second half of the antecedent is
// 1 u> latchLimit, and its negation is latchLimit u>= 1.
//
// So the widened condition is:
// guardStart u< guardLimit && latchLimit u>= 1.
// Similarly for sgt condition the widened condition is:
// guardStart u< guardLimit && latchLimit s>= 1.
// For uge condition the widened condition is:
// guardStart u< guardLimit && latchLimit u> 1.
// For sge condition the widened condition is:
// guardStart u< guardLimit && latchLimit s> 1.
//===----------------------------------------------------------------------===//
#include "llvm/Transforms/Scalar/LoopPredication.h"
#include "llvm/Analysis/LoopInfo.h"
#include "llvm/Analysis/LoopPass.h"
#include "llvm/Analysis/ScalarEvolution.h"
#include "llvm/Analysis/ScalarEvolutionExpander.h"
#include "llvm/Analysis/ScalarEvolutionExpressions.h"
#include "llvm/IR/Function.h"
#include "llvm/IR/GlobalValue.h"
#include "llvm/IR/IntrinsicInst.h"
#include "llvm/IR/Module.h"
#include "llvm/IR/PatternMatch.h"
#include "llvm/Pass.h"
#include "llvm/Support/Debug.h"
#include "llvm/Transforms/Scalar.h"
#include "llvm/Transforms/Utils/LoopUtils.h"
#define DEBUG_TYPE "loop-predication"
using namespace llvm;
static cl::opt<bool> EnableIVTruncation("loop-predication-enable-iv-truncation",
cl::Hidden, cl::init(true));
static cl::opt<bool> EnableCountDownLoop("loop-predication-enable-count-down-loop",
cl::Hidden, cl::init(true));
namespace {
class LoopPredication {
/// Represents an induction variable check:
/// icmp Pred, <induction variable>, <loop invariant limit>
struct LoopICmp {
ICmpInst::Predicate Pred;
const SCEVAddRecExpr *IV;
const SCEV *Limit;
LoopICmp(ICmpInst::Predicate Pred, const SCEVAddRecExpr *IV,
const SCEV *Limit)
: Pred(Pred), IV(IV), Limit(Limit) {}
LoopICmp() {}
void dump() {
dbgs() << "LoopICmp Pred = " << Pred << ", IV = " << *IV
<< ", Limit = " << *Limit << "\n";
}
};
ScalarEvolution *SE;
Loop *L;
const DataLayout *DL;
BasicBlock *Preheader;
LoopICmp LatchCheck;
bool isSupportedStep(const SCEV* Step);
Optional<LoopICmp> parseLoopICmp(ICmpInst *ICI) {
return parseLoopICmp(ICI->getPredicate(), ICI->getOperand(0),
ICI->getOperand(1));
}
Optional<LoopICmp> parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
Value *RHS);
Optional<LoopICmp> parseLoopLatchICmp();
bool CanExpand(const SCEV* S);
Value *expandCheck(SCEVExpander &Expander, IRBuilder<> &Builder,
ICmpInst::Predicate Pred, const SCEV *LHS, const SCEV *RHS,
Instruction *InsertAt);
Optional<Value *> widenICmpRangeCheck(ICmpInst *ICI, SCEVExpander &Expander,
IRBuilder<> &Builder);
Optional<Value *> widenICmpRangeCheckIncrementingLoop(LoopICmp LatchCheck,
LoopICmp RangeCheck,
SCEVExpander &Expander,
IRBuilder<> &Builder);
Optional<Value *> widenICmpRangeCheckDecrementingLoop(LoopICmp LatchCheck,
LoopICmp RangeCheck,
SCEVExpander &Expander,
IRBuilder<> &Builder);
bool widenGuardConditions(IntrinsicInst *II, SCEVExpander &Expander);
// When the IV type is wider than the range operand type, we can still do loop
// predication, by generating SCEVs for the range and latch that are of the
// same type. We achieve this by generating a SCEV truncate expression for the
// latch IV. This is done iff truncation of the IV is a safe operation,
// without loss of information.
// Another way to achieve this is by generating a wider type SCEV for the
// range check operand, however, this needs a more involved check that
// operands do not overflow. This can lead to loss of information when the
// range operand is of the form: add i32 %offset, %iv. We need to prove that
// sext(x + y) is same as sext(x) + sext(y).
// This function returns true if we can safely represent the IV type in
// the RangeCheckType without loss of information.
bool isSafeToTruncateWideIVType(Type *RangeCheckType);
// Return the loopLatchCheck corresponding to the RangeCheckType if safe to do
// so.
Optional<LoopICmp> generateLoopLatchCheck(Type *RangeCheckType);
public:
LoopPredication(ScalarEvolution *SE) : SE(SE){};
bool runOnLoop(Loop *L);
};
class LoopPredicationLegacyPass : public LoopPass {
public:
static char ID;
LoopPredicationLegacyPass() : LoopPass(ID) {
initializeLoopPredicationLegacyPassPass(*PassRegistry::getPassRegistry());
}
void getAnalysisUsage(AnalysisUsage &AU) const override {
getLoopAnalysisUsage(AU);
}
bool runOnLoop(Loop *L, LPPassManager &LPM) override {
if (skipLoop(L))
return false;
auto *SE = &getAnalysis<ScalarEvolutionWrapperPass>().getSE();
LoopPredication LP(SE);
return LP.runOnLoop(L);
}
};
char LoopPredicationLegacyPass::ID = 0;
} // end namespace llvm
INITIALIZE_PASS_BEGIN(LoopPredicationLegacyPass, "loop-predication",
"Loop predication", false, false)
INITIALIZE_PASS_DEPENDENCY(LoopPass)
INITIALIZE_PASS_END(LoopPredicationLegacyPass, "loop-predication",
"Loop predication", false, false)
Pass *llvm::createLoopPredicationPass() {
return new LoopPredicationLegacyPass();
}
PreservedAnalyses LoopPredicationPass::run(Loop &L, LoopAnalysisManager &AM,
LoopStandardAnalysisResults &AR,
LPMUpdater &U) {
LoopPredication LP(&AR.SE);
if (!LP.runOnLoop(&L))
return PreservedAnalyses::all();
return getLoopPassPreservedAnalyses();
}
Optional<LoopPredication::LoopICmp>
LoopPredication::parseLoopICmp(ICmpInst::Predicate Pred, Value *LHS,
Value *RHS) {
const SCEV *LHSS = SE->getSCEV(LHS);
if (isa<SCEVCouldNotCompute>(LHSS))
return None;
const SCEV *RHSS = SE->getSCEV(RHS);
if (isa<SCEVCouldNotCompute>(RHSS))
return None;
// Canonicalize RHS to be loop invariant bound, LHS - a loop computable IV
if (SE->isLoopInvariant(LHSS, L)) {
std::swap(LHS, RHS);
std::swap(LHSS, RHSS);
Pred = ICmpInst::getSwappedPredicate(Pred);
}
const SCEVAddRecExpr *AR = dyn_cast<SCEVAddRecExpr>(LHSS);
if (!AR || AR->getLoop() != L)
return None;
return LoopICmp(Pred, AR, RHSS);
}
Value *LoopPredication::expandCheck(SCEVExpander &Expander,
IRBuilder<> &Builder,
ICmpInst::Predicate Pred, const SCEV *LHS,
const SCEV *RHS, Instruction *InsertAt) {
// TODO: we can check isLoopEntryGuardedByCond before emitting the check
Type *Ty = LHS->getType();
assert(Ty == RHS->getType() && "expandCheck operands have different types?");
if (SE->isLoopEntryGuardedByCond(L, Pred, LHS, RHS))
return Builder.getTrue();
Value *LHSV = Expander.expandCodeFor(LHS, Ty, InsertAt);
Value *RHSV = Expander.expandCodeFor(RHS, Ty, InsertAt);
return Builder.CreateICmp(Pred, LHSV, RHSV);
}
Optional<LoopPredication::LoopICmp>
LoopPredication::generateLoopLatchCheck(Type *RangeCheckType) {
auto *LatchType = LatchCheck.IV->getType();
if (RangeCheckType == LatchType)
return LatchCheck;
// For now, bail out if latch type is narrower than range type.
if (DL->getTypeSizeInBits(LatchType) < DL->getTypeSizeInBits(RangeCheckType))
return None;
if (!isSafeToTruncateWideIVType(RangeCheckType))
return None;
// We can now safely identify the truncated version of the IV and limit for
// RangeCheckType.
LoopICmp NewLatchCheck;
NewLatchCheck.Pred = LatchCheck.Pred;
NewLatchCheck.IV = dyn_cast<SCEVAddRecExpr>(
SE->getTruncateExpr(LatchCheck.IV, RangeCheckType));
if (!NewLatchCheck.IV)
return None;
NewLatchCheck.Limit = SE->getTruncateExpr(LatchCheck.Limit, RangeCheckType);
DEBUG(dbgs() << "IV of type: " << *LatchType
<< "can be represented as range check type:" << *RangeCheckType
<< "\n");
DEBUG(dbgs() << "LatchCheck.IV: " << *NewLatchCheck.IV << "\n");
DEBUG(dbgs() << "LatchCheck.Limit: " << *NewLatchCheck.Limit << "\n");
return NewLatchCheck;
}
bool LoopPredication::isSupportedStep(const SCEV* Step) {
return Step->isOne() || (Step->isAllOnesValue() && EnableCountDownLoop);
}
bool LoopPredication::CanExpand(const SCEV* S) {
return SE->isLoopInvariant(S, L) && isSafeToExpand(S, *SE);
}
Optional<Value *> LoopPredication::widenICmpRangeCheckIncrementingLoop(
LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
SCEVExpander &Expander, IRBuilder<> &Builder) {
auto *Ty = RangeCheck.IV->getType();
// Generate the widened condition for the forward loop:
// guardStart u< guardLimit &&
// latchLimit <pred> guardLimit - 1 - guardStart + latchStart
// where <pred> depends on the latch condition predicate. See the file
// header comment for the reasoning.
// guardLimit - guardStart + latchStart - 1
const SCEV *GuardStart = RangeCheck.IV->getStart();
const SCEV *GuardLimit = RangeCheck.Limit;
const SCEV *LatchStart = LatchCheck.IV->getStart();
const SCEV *LatchLimit = LatchCheck.Limit;
// guardLimit - guardStart + latchStart - 1
const SCEV *RHS =
SE->getAddExpr(SE->getMinusSCEV(GuardLimit, GuardStart),
SE->getMinusSCEV(LatchStart, SE->getOne(Ty)));
if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
!CanExpand(LatchLimit) || !CanExpand(RHS)) {
DEBUG(dbgs() << "Can't expand limit check!\n");
return None;
}
auto LimitCheckPred =
ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
DEBUG(dbgs() << "LHS: " << *LatchLimit << "\n");
DEBUG(dbgs() << "RHS: " << *RHS << "\n");
DEBUG(dbgs() << "Pred: " << LimitCheckPred << "\n");
Instruction *InsertAt = Preheader->getTerminator();
auto *LimitCheck =
expandCheck(Expander, Builder, LimitCheckPred, LatchLimit, RHS, InsertAt);
auto *FirstIterationCheck = expandCheck(Expander, Builder, RangeCheck.Pred,
GuardStart, GuardLimit, InsertAt);
return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
}
Optional<Value *> LoopPredication::widenICmpRangeCheckDecrementingLoop(
LoopPredication::LoopICmp LatchCheck, LoopPredication::LoopICmp RangeCheck,
SCEVExpander &Expander, IRBuilder<> &Builder) {
auto *Ty = RangeCheck.IV->getType();
const SCEV *GuardStart = RangeCheck.IV->getStart();
const SCEV *GuardLimit = RangeCheck.Limit;
const SCEV *LatchLimit = LatchCheck.Limit;
if (!CanExpand(GuardStart) || !CanExpand(GuardLimit) ||
!CanExpand(LatchLimit)) {
DEBUG(dbgs() << "Can't expand limit check!\n");
return None;
}
// The decrement of the latch check IV should be the same as the
// rangeCheckIV.
auto *PostDecLatchCheckIV = LatchCheck.IV->getPostIncExpr(*SE);
if (RangeCheck.IV != PostDecLatchCheckIV) {
DEBUG(dbgs() << "Not the same. PostDecLatchCheckIV: "
<< *PostDecLatchCheckIV
<< " and RangeCheckIV: " << *RangeCheck.IV << "\n");
return None;
}
// Generate the widened condition for CountDownLoop:
// guardStart u< guardLimit &&
// latchLimit <pred> 1.
// See the header comment for reasoning of the checks.
Instruction *InsertAt = Preheader->getTerminator();
auto LimitCheckPred =
ICmpInst::getFlippedStrictnessPredicate(LatchCheck.Pred);
auto *FirstIterationCheck = expandCheck(Expander, Builder, ICmpInst::ICMP_ULT,
GuardStart, GuardLimit, InsertAt);
auto *LimitCheck = expandCheck(Expander, Builder, LimitCheckPred, LatchLimit,
SE->getOne(Ty), InsertAt);
return Builder.CreateAnd(FirstIterationCheck, LimitCheck);
}
/// If ICI can be widened to a loop invariant condition emits the loop
/// invariant condition in the loop preheader and return it, otherwise
/// returns None.
Optional<Value *> LoopPredication::widenICmpRangeCheck(ICmpInst *ICI,
SCEVExpander &Expander,
IRBuilder<> &Builder) {
DEBUG(dbgs() << "Analyzing ICmpInst condition:\n");
DEBUG(ICI->dump());
// parseLoopStructure guarantees that the latch condition is:
// ++i <pred> latchLimit, where <pred> is u<, u<=, s<, or s<=.
// We are looking for the range checks of the form:
// i u< guardLimit
auto RangeCheck = parseLoopICmp(ICI);
if (!RangeCheck) {
DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
return None;
}
DEBUG(dbgs() << "Guard check:\n");
DEBUG(RangeCheck->dump());
if (RangeCheck->Pred != ICmpInst::ICMP_ULT) {
DEBUG(dbgs() << "Unsupported range check predicate(" << RangeCheck->Pred
<< ")!\n");
return None;
}
auto *RangeCheckIV = RangeCheck->IV;
if (!RangeCheckIV->isAffine()) {
DEBUG(dbgs() << "Range check IV is not affine!\n");
return None;
}
auto *Step = RangeCheckIV->getStepRecurrence(*SE);
// We cannot just compare with latch IV step because the latch and range IVs
// may have different types.
if (!isSupportedStep(Step)) {
DEBUG(dbgs() << "Range check and latch have IVs different steps!\n");
return None;
}
auto *Ty = RangeCheckIV->getType();
auto CurrLatchCheckOpt = generateLoopLatchCheck(Ty);
if (!CurrLatchCheckOpt) {
DEBUG(dbgs() << "Failed to generate a loop latch check "
"corresponding to range type: "
<< *Ty << "\n");
return None;
}
LoopICmp CurrLatchCheck = *CurrLatchCheckOpt;
// At this point, the range and latch step should have the same type, but need
// not have the same value (we support both 1 and -1 steps).
assert(Step->getType() ==
CurrLatchCheck.IV->getStepRecurrence(*SE)->getType() &&
"Range and latch steps should be of same type!");
if (Step != CurrLatchCheck.IV->getStepRecurrence(*SE)) {
DEBUG(dbgs() << "Range and latch have different step values!\n");
return None;
}
if (Step->isOne())
return widenICmpRangeCheckIncrementingLoop(CurrLatchCheck, *RangeCheck,
Expander, Builder);
else {
assert(Step->isAllOnesValue() && "Step should be -1!");
return widenICmpRangeCheckDecrementingLoop(CurrLatchCheck, *RangeCheck,
Expander, Builder);
}
}
bool LoopPredication::widenGuardConditions(IntrinsicInst *Guard,
SCEVExpander &Expander) {
DEBUG(dbgs() << "Processing guard:\n");
DEBUG(Guard->dump());
IRBuilder<> Builder(cast<Instruction>(Preheader->getTerminator()));
// The guard condition is expected to be in form of:
// cond1 && cond2 && cond3 ...
// Iterate over subconditions looking for icmp conditions which can be
// widened across loop iterations. Widening these conditions remember the
// resulting list of subconditions in Checks vector.
SmallVector<Value *, 4> Worklist(1, Guard->getOperand(0));
SmallPtrSet<Value *, 4> Visited;
SmallVector<Value *, 4> Checks;
unsigned NumWidened = 0;
do {
Value *Condition = Worklist.pop_back_val();
if (!Visited.insert(Condition).second)
continue;
Value *LHS, *RHS;
using namespace llvm::PatternMatch;
if (match(Condition, m_And(m_Value(LHS), m_Value(RHS)))) {
Worklist.push_back(LHS);
Worklist.push_back(RHS);
continue;
}
if (ICmpInst *ICI = dyn_cast<ICmpInst>(Condition)) {
if (auto NewRangeCheck = widenICmpRangeCheck(ICI, Expander, Builder)) {
Checks.push_back(NewRangeCheck.getValue());
NumWidened++;
continue;
}
}
// Save the condition as is if we can't widen it
Checks.push_back(Condition);
} while (Worklist.size() != 0);
if (NumWidened == 0)
return false;
// Emit the new guard condition
Builder.SetInsertPoint(Guard);
Value *LastCheck = nullptr;
for (auto *Check : Checks)
if (!LastCheck)
LastCheck = Check;
else
LastCheck = Builder.CreateAnd(LastCheck, Check);
Guard->setOperand(0, LastCheck);
DEBUG(dbgs() << "Widened checks = " << NumWidened << "\n");
return true;
}
Optional<LoopPredication::LoopICmp> LoopPredication::parseLoopLatchICmp() {
using namespace PatternMatch;
BasicBlock *LoopLatch = L->getLoopLatch();
if (!LoopLatch) {
DEBUG(dbgs() << "The loop doesn't have a single latch!\n");
return None;
}
ICmpInst::Predicate Pred;
Value *LHS, *RHS;
BasicBlock *TrueDest, *FalseDest;
if (!match(LoopLatch->getTerminator(),
m_Br(m_ICmp(Pred, m_Value(LHS), m_Value(RHS)), TrueDest,
FalseDest))) {
DEBUG(dbgs() << "Failed to match the latch terminator!\n");
return None;
}
assert((TrueDest == L->getHeader() || FalseDest == L->getHeader()) &&
"One of the latch's destinations must be the header");
if (TrueDest != L->getHeader())
Pred = ICmpInst::getInversePredicate(Pred);
auto Result = parseLoopICmp(Pred, LHS, RHS);
if (!Result) {
DEBUG(dbgs() << "Failed to parse the loop latch condition!\n");
return None;
}
// Check affine first, so if it's not we don't try to compute the step
// recurrence.
if (!Result->IV->isAffine()) {
DEBUG(dbgs() << "The induction variable is not affine!\n");
return None;
}
auto *Step = Result->IV->getStepRecurrence(*SE);
if (!isSupportedStep(Step)) {
DEBUG(dbgs() << "Unsupported loop stride(" << *Step << ")!\n");
return None;
}
auto IsUnsupportedPredicate = [](const SCEV *Step, ICmpInst::Predicate Pred) {
if (Step->isOne()) {
return Pred != ICmpInst::ICMP_ULT && Pred != ICmpInst::ICMP_SLT &&
Pred != ICmpInst::ICMP_ULE && Pred != ICmpInst::ICMP_SLE;
} else {
assert(Step->isAllOnesValue() && "Step should be -1!");
return Pred != ICmpInst::ICMP_UGT && Pred != ICmpInst::ICMP_SGT &&
Pred != ICmpInst::ICMP_UGE && Pred != ICmpInst::ICMP_SGE;
}
};
if (IsUnsupportedPredicate(Step, Result->Pred)) {
DEBUG(dbgs() << "Unsupported loop latch predicate(" << Result->Pred
<< ")!\n");
return None;
}
return Result;
}
// Returns true if its safe to truncate the IV to RangeCheckType.
bool LoopPredication::isSafeToTruncateWideIVType(Type *RangeCheckType) {
if (!EnableIVTruncation)
return false;
assert(DL->getTypeSizeInBits(LatchCheck.IV->getType()) >
DL->getTypeSizeInBits(RangeCheckType) &&
"Expected latch check IV type to be larger than range check operand "
"type!");
// The start and end values of the IV should be known. This is to guarantee
// that truncating the wide type will not lose information.
auto *Limit = dyn_cast<SCEVConstant>(LatchCheck.Limit);
auto *Start = dyn_cast<SCEVConstant>(LatchCheck.IV->getStart());
if (!Limit || !Start)
return false;
// This check makes sure that the IV does not change sign during loop
// iterations. Consider latchType = i64, LatchStart = 5, Pred = ICMP_SGE,
// LatchEnd = 2, rangeCheckType = i32. If it's not a monotonic predicate, the
// IV wraps around, and the truncation of the IV would lose the range of
// iterations between 2^32 and 2^64.
bool Increasing;
if (!SE->isMonotonicPredicate(LatchCheck.IV, LatchCheck.Pred, Increasing))
return false;
// The active bits should be less than the bits in the RangeCheckType. This
// guarantees that truncating the latch check to RangeCheckType is a safe
// operation.
auto RangeCheckTypeBitSize = DL->getTypeSizeInBits(RangeCheckType);
return Start->getAPInt().getActiveBits() < RangeCheckTypeBitSize &&
Limit->getAPInt().getActiveBits() < RangeCheckTypeBitSize;
}
bool LoopPredication::runOnLoop(Loop *Loop) {
L = Loop;
DEBUG(dbgs() << "Analyzing ");
DEBUG(L->dump());
Module *M = L->getHeader()->getModule();
// There is nothing to do if the module doesn't use guards
auto *GuardDecl =
M->getFunction(Intrinsic::getName(Intrinsic::experimental_guard));
if (!GuardDecl || GuardDecl->use_empty())
return false;
DL = &M->getDataLayout();
Preheader = L->getLoopPreheader();
if (!Preheader)
return false;
auto LatchCheckOpt = parseLoopLatchICmp();
if (!LatchCheckOpt)
return false;
LatchCheck = *LatchCheckOpt;
DEBUG(dbgs() << "Latch check:\n");
DEBUG(LatchCheck.dump());
// Collect all the guards into a vector and process later, so as not
// to invalidate the instruction iterator.
SmallVector<IntrinsicInst *, 4> Guards;
for (const auto BB : L->blocks())
for (auto &I : *BB)
if (auto *II = dyn_cast<IntrinsicInst>(&I))
if (II->getIntrinsicID() == Intrinsic::experimental_guard)
Guards.push_back(II);
if (Guards.empty())
return false;
SCEVExpander Expander(*SE, *DL, "loop-predication");
bool Changed = false;
for (auto *Guard : Guards)
Changed |= widenGuardConditions(Guard, Expander);
return Changed;
}
| [
"yaron.keren@gmail.com"
] | yaron.keren@gmail.com |
c2e8352c4931968ffe30da7f12fc55505d9187e9 | a79107565e7fc19e64243867d0136eca56cbdd37 | /JobSearchLog/src/UserInfo.cpp | a60f9d85878dc0457f13d7c581ae49f448cd8a77 | [] | no_license | masmowa/samples | fb7d7fb7f46e9222267093d4f5f637dfd72eb3a8 | 177add6589b7ffd5457b92a0388461cdd439cc3b | refs/heads/master | 2021-01-10T07:23:20.605946 | 2020-03-15T13:18:47 | 2020-03-15T13:18:47 | 52,021,876 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,388 | cpp | #include "UserInfo.h"
#include "dbg_Utility.h"
const char* UserInfo::xml_section_name = "User-Data";
UserInfo::UserInfo()
: basic_STORAGE(xml_section_name)
{
//ctor
this->Init();
this->TestDataInit();
}
UserInfo::~UserInfo()
{
//dtor
}
//
/** \brief load data into a "named" xml block and attached to xml-document-object, to allow it to be serialized
*
* \param pdoc tinyxml2::XMLDocument*
* \param proot tinyxml2::XMLElement*
* \return bool
*
*/
bool UserInfo::ToXML(tinyxml2::XMLDocument* pdoc, tinyxml2::XMLElement * proot)
{
std::cout << "++" << __PRETTY_FUNCTION__ << std::endl;
bool result = true;
tinyxml2::XMLElement* pElem = pdoc->NewElement(this->m_name.c_str());
// add comment about contents
std::string s = " Elements of " + m_keys[0] + " ";
tinyxml2::XMLComment * comment = pdoc->NewComment(s.c_str());
pElem->LinkEndChild(comment);
// add items from dictionary
for (auto & iter : this->m_data) {
tinyxml2::XMLElement* pData = pdoc->NewElement(iter.first.c_str());
pData->LinkEndChild(pdoc->NewText(iter.second.c_str()));
pElem->LinkEndChild(pData);
}
comment = pdoc->NewComment(" End of Element ");
pElem->LinkEndChild(comment);
dbg_Utility::print_xml_element(pElem);
(proot)->LinkEndChild(pElem);
dbg_Utility::print_xml_element(pElem);
return result;
}
| [
"masmowa@gmail.com"
] | masmowa@gmail.com |
24d27773b889220dd86d008d7da41ce915e83a48 | a3cd6195d5becb43fb21099af5b2079983592fe7 | /solutions/black/week1/transport_catalog_svg_integration/src/transport_drawer.h | 1a6f1169dd7f2e0b217f2071948cfa170ce7a01e | [] | no_license | korotindev/c-plus-plus-belts | f51e17df1941b991f280d86a79d11a752da06415 | 719329cf4291f29752527d07800a9c042d9e7c73 | refs/heads/master | 2023-02-23T15:09:02.495396 | 2021-02-02T11:50:22 | 2021-02-02T11:50:22 | 253,024,569 | 1 | 0 | null | 2020-12-10T16:00:03 | 2020-04-04T14:55:31 | C++ | UTF-8 | C++ | false | false | 1,818 | h | #pragma once
#include <algorithm>
#include <memory>
#include <optional>
#include <set>
#include <string>
#include <unordered_map>
#include <variant>
#include <vector>
#include "descriptions.h"
#include "json.h"
#include "svg.h"
class TransportDrawer {
public:
TransportDrawer(const Descriptions::StopsDict &stops_dict, const Descriptions::BusesDict &buses_dict,
const Json::Dict &render_settings_json);
struct RenderSettings {
double width;
double height;
double padding;
double stop_radius;
double line_width;
uint32_t stop_label_font_size;
Svg::Point stop_label_offset;
Svg::Color underlayer_color;
double underlayer_width;
std::vector<Svg::Color> color_palette;
uint32_t bus_label_font_size;
Svg::Point bus_label_offset;
std::vector<std::string> layers;
};
std::shared_ptr<const std::string> Draw() const;
private:
void DrawBusRoute(size_t id, const Descriptions::Bus *bus, const Descriptions::StopsDict &stops_dict) const;
void DrawBusName(size_t id, const Descriptions::Bus *bus, const Descriptions::StopsDict &stops_dict) const;
void DrawStop(const Descriptions::Stop *stop) const;
void DrawStopName(const Descriptions::Stop *stop) const;
RenderSettings MakeRenderSettings(const Json::Dict &render_settings_json);
struct Projection {
Projection(const RenderSettings &render_settings);
const RenderSettings &render_settings_;
double max_lat = 0.0;
double min_lon = 0.0;
double zoom_coef = 0.0;
Svg::Point ConvertSpherePoint(const Sphere::Point &sphere_point) const;
void CaculateZoom(double min_lat, double max_lon);
};
RenderSettings render_settings_;
Projection projection_;
std::shared_ptr<Svg::Document> renderer_;
mutable std::shared_ptr<const std::string> svg_map_;
};
| [
"dev.korotin@gmail.com"
] | dev.korotin@gmail.com |
6fd3329bef28bfb4d56644af090888247f00b8ba | e322533baa2e72feabff1d1d423f1af956bee5b4 | /2nd lab/funarea.cpp | e9cebbb9dfe4b61449cae4a963d60ff5874d2431 | [] | no_license | Abhinav1281/2nd-Year | 110bd05ae6e7b636530e5008a53d7ea3ee123fb6 | d74f5423605a4c389ae48c44d2cea2f68d97ad6b | refs/heads/master | 2023-07-07T07:42:10.130294 | 2021-08-15T13:32:19 | 2021-08-15T13:32:19 | 302,523,449 | 0 | 0 | null | 2021-08-15T13:32:20 | 2020-10-09T03:31:55 | C++ | UTF-8 | C++ | false | false | 399 | cpp | #include <iostream>
using namespace std;
void Fun_Area(int r)
{
cout<<(3.14*r*r)<<"\n";
}
void Fun_Area(int r,int t)
{
cout<<(2*(r+t))<<"\n";
}
void Fun_Area(int r,int t,int q)
{
cout<<(r*t*q)<<"\n";
}
void Fun_Area()
{
cout<<"NO VALUE PROVIDED";
}
int main()
{
int r=10;
int a=5,b=10,c=20;
Fun_Area(r);
Fun_Area(a,b);
Fun_Area(a,b,c);
Fun_Area();
} | [
"abhisione2@gmail.com"
] | abhisione2@gmail.com |
ade97160c57367f425c5083d34fa86d2026ac923 | 413d8f76ad942ab485d054957f55a4fcf3ebc6b0 | /168.excel-sheet-column-title.cpp | 79a9f9fbfab498fc885c6bd5c0014a617d31d2d8 | [] | no_license | pradeep3008k/LeetCode-Sheet | c95645190ef0037cb355e0af17cc4deb3fb8092f | 4218b88c0a4bf4ab921e634d33b87d393d9517ae | refs/heads/master | 2023-07-10T00:11:45.372541 | 2021-08-15T13:36:56 | 2021-08-15T13:36:56 | 389,982,877 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 538 | cpp | /*
* @lc app=leetcode id=168 lang=cpp
*
* [168] Excel Sheet Column Title
*/
#include<bits/stdc++.h>
using namespace std;
// @lc code=start
class Solution {
public:
string convertToTitle(int n) {
string ans;
while(n){
int curr=n%26;
n=n/26;
if(curr==0){
ans.insert(ans.begin(),'Z');
n--;
}
else{
ans.insert(ans.begin(),(char)(curr+64));
}
}
return ans;
}
};
// @lc code=end
| [
"pradeep3008k@gmail.com"
] | pradeep3008k@gmail.com |
d48b75d64d9b25b2961e7bc19f9882edec2d35f3 | 1291bef3196b93b5622f2bf7d22643b70708ee19 | /jni/Renderable/Shaders/GeometryShaderProgram.h | dba37ea249ee23bbbf622a6bd0859a9090aa03ea | [] | no_license | datalinkE/imperfectvoid | caa63cafac5afc4b942d62014ad4fe6969b181a0 | 7899660e6c23a3261e8fe4f66cc895e3ba61b6fc | refs/heads/master | 2016-08-06T08:58:28.062270 | 2014-05-13T15:17:21 | 2014-05-13T15:17:21 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 359 | h | #ifndef BASICSHADER_H_
#define BASICSHADER_H_
#include "ShaderProgram.h"
class GeometryShaderProgram
: public ShaderProgram
{
private:
GLint m_positionAttributeHandle;
public:
GeometryShaderProgram();
virtual ~GeometryShaderProgram();
virtual void Link();
virtual void Setup(Renderable& renderable);
};
#endif // BASICSHADER_H_
| [
"01.datalink@gmail.com"
] | 01.datalink@gmail.com |
591b82dcec2cf26257b40cb45af1c12ce84d88f0 | 94dbfcf94dd0a61d7cd197cf996602d5a2acdda7 | /weekly_contest/74/6023_minimum-white-tiles-after-covering-with-carpets.cpp | e0a7831217de7cdf48e4fd79943e8baab2558676 | [] | no_license | PengJi/Algorithms | 46ac90691cc20b0f769374ac3d848a26766965b1 | 6aa26240679bc209a6fd69580b9c7994cef51b54 | refs/heads/master | 2023-07-21T05:57:50.637703 | 2023-07-07T10:16:48 | 2023-07-09T10:17:10 | 243,935,787 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,014 | cpp | class Solution {
public:
/* dp[i][j] 表示使用了i条地毯覆盖[0,j]的地板, 最小的白色砖块数 */
/* dp[0][j], [0,j]一共的白色砖块数 */
/* dp[i][j], dp[i][j] = min(dp[i][j-1] + floor[j], dp[i-1][j-carpetLen]) */
int minimumWhiteTiles(string floor, int numCarpets, int carpetLen) {
int n = floor.size();
vector<vector<int>> dp(numCarpets + 1, vector<int>(n));
int cnt = 0;
/* dp初始化 */
for (int j = 0; j < n; j++) {
cnt += (floor[j] - '0');
dp[0][j] = cnt;
}
/* dp动态方程转移 */
for (int i = 1; i <= numCarpets; i++) {
for (int j = 0; j < n; j++) {
if (j < carpetLen) {
dp[i][j] = 0;
} else {
dp[i][j] = min(dp[i][j - 1] + (floor[j] - '0'),
dp[i - 1][j - carpetLen]);
}
}
}
return dp[numCarpets][n - 1];
}
};
| [
"jipengpro@gmail.com"
] | jipengpro@gmail.com |
c0b12a20ca0c476cc2e08afa04084fc1eb1afd53 | 8776551db844fcbd2bc8e6d1967a3c526e9bf229 | /chapter03/findfile/singleinherit/src/qrc_findfile.cpp | aefa902248362c16a869032d77fc87ed7c19d2d4 | [] | no_license | Simon-GitHub/MasterQt4Programming | fbf3e1c5539232497841f31d4a31bd7463e77d4f | ce1bb661cedccc43b7f2a083c832badc2c4eef9f | refs/heads/master | 2021-01-23T12:57:48.419045 | 2017-06-03T01:24:28 | 2017-06-03T01:24:28 | 93,213,840 | 0 | 2 | null | null | null | null | UTF-8 | C++ | false | false | 13,203 | cpp | /****************************************************************************
** Resource object code
**
** Created: Mon Aug 6 16:42:44 2007
** by: The Resource Compiler for Qt version 4.3.0
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/
#include <QtCore/qglobal.h>
static const unsigned char qt_resource_data[] = {
// /home/lcf/book/widget/findfile/findfile.png
0x0,0x0,0x8,0xad,
0x89,
0x50,0x4e,0x47,0xd,0xa,0x1a,0xa,0x0,0x0,0x0,0xd,0x49,0x48,0x44,0x52,0x0,
0x0,0x0,0x20,0x0,0x0,0x0,0x20,0x8,0x6,0x0,0x0,0x0,0x73,0x7a,0x7a,0xf4,
0x0,0x0,0x0,0x20,0x74,0x45,0x58,0x74,0x53,0x6f,0x66,0x74,0x77,0x61,0x72,0x65,
0x0,0x4b,0x44,0x45,0x20,0x54,0x68,0x75,0x6d,0x62,0x6e,0x61,0x69,0x6c,0x20,0x47,
0x65,0x6e,0x65,0x72,0x61,0x74,0x6f,0x72,0xbe,0xa0,0x62,0x8b,0x0,0x0,0x0,0x17,
0x74,0x45,0x58,0x74,0x54,0x68,0x75,0x6d,0x62,0x3a,0x3a,0x4d,0x54,0x69,0x6d,0x65,
0x0,0x31,0x31,0x34,0x37,0x36,0x30,0x33,0x35,0x36,0x33,0x2a,0xf7,0x5a,0xfa,0x0,
0x0,0x0,0x19,0x74,0x45,0x58,0x74,0x54,0x68,0x75,0x6d,0x62,0x3a,0x3a,0x4d,0x69,
0x6d,0x65,0x74,0x79,0x70,0x65,0x0,0x69,0x6d,0x61,0x67,0x65,0x2f,0x70,0x6e,0x67,
0x3f,0xb2,0x56,0x4e,0x0,0x0,0x0,0x10,0x74,0x45,0x58,0x74,0x54,0x68,0x75,0x6d,
0x62,0x3a,0x3a,0x53,0x69,0x7a,0x65,0x0,0x32,0x30,0x31,0x31,0xd3,0x9a,0xbd,0x5a,
0x0,0x0,0x0,0x60,0x7a,0x54,0x58,0x74,0x54,0x68,0x75,0x6d,0x62,0x3a,0x3a,0x55,
0x52,0x49,0x0,0x0,0x78,0x9c,0x5,0xc1,0xd1,0xd,0x80,0x20,0xc,0x5,0xc0,0x89,
0xca,0xb,0xd1,0x2f,0xb7,0x21,0x50,0xb0,0x9,0x50,0xa5,0x35,0x3a,0xbe,0x77,0x55,
0x3a,0x1f,0x0,0x4e,0x1d,0x8c,0x9e,0x2b,0x4c,0xab,0xbf,0x69,0x31,0x6e,0xa7,0x2f,
0x46,0xd2,0x8b,0xa7,0xe9,0xb3,0x32,0x93,0xad,0x4c,0x7b,0x88,0x61,0x43,0xd1,0x8c,
0xd3,0x47,0x87,0x8c,0xd4,0xd8,0xd0,0x65,0xb6,0x47,0xcc,0x89,0x8b,0x78,0x95,0x59,
0xc2,0x35,0xdb,0xf,0xc0,0x27,0x20,0xa3,0xea,0xa7,0xf3,0x32,0x0,0x0,0x7,0x78,
0x49,0x44,0x41,0x54,0x58,0x85,0xb5,0x97,0x5d,0x6c,0x93,0xd7,0x19,0xc7,0x7f,0xcf,
0x79,0x5f,0xdb,0x71,0x3e,0x1c,0x27,0x71,0xbe,0x80,0xa4,0x69,0x43,0xc2,0xa0,0x4,
0x58,0xc2,0xc7,0xa0,0xea,0x60,0x1b,0x74,0x53,0x35,0xb5,0x2a,0x12,0x55,0xab,0xc1,
0xda,0xd1,0xa,0x69,0x57,0xbb,0xd9,0xb4,0x4d,0xbb,0xdd,0xc5,0x34,0x55,0xe5,0x66,
0x9b,0xb4,0x8b,0x6d,0x94,0xc1,0x3a,0xa9,0xa8,0xed,0x46,0x29,0x22,0x14,0x9,0xfa,
0x1,0x2b,0x81,0x95,0x42,0x8,0x34,0x34,0x84,0x90,0x2f,0x27,0x21,0x8e,0x9d,0xc4,
0x8e,0xed,0xf7,0x7d,0xcf,0xd9,0x85,0xd,0x85,0x90,0x50,0x4,0xda,0x23,0xfd,0xf5,
0x5e,0x58,0xf6,0xf3,0x7b,0xff,0xff,0x73,0x9e,0x73,0x2c,0xc6,0x18,0xfe,0xf8,0x8a,
0xac,0x49,0x65,0xb0,0x3d,0x83,0x4,0xfd,0xb4,0xb9,0x1e,0x96,0x31,0x8,0x80,0xad,
0xa8,0xb1,0x14,0xb5,0xda,0xa0,0x3c,0x4d,0x72,0x24,0xc1,0xbb,0xbf,0xff,0x37,0x1f,
0x2,0x33,0xc6,0x18,0xcd,0x43,0x96,0xfc,0xe9,0x55,0x7e,0x53,0xbf,0xfc,0xe9,0x9d,
0x5a,0x1b,0xcb,0x18,0xa3,0x16,0x2d,0xfb,0x5e,0xa1,0xd6,0x46,0x30,0x46,0x0,0x42,
0x91,0x47,0xec,0xc2,0xb2,0x85,0x3e,0x65,0x5,0xc5,0xcd,0x24,0xcd,0x7b,0x7f,0xd8,
0x3a,0xd2,0x71,0x69,0x7c,0xf7,0x9e,0xe3,0xfc,0x3,0x88,0x19,0x63,0xbc,0x87,0x22,
0x38,0xd7,0xfe,0x5a,0xd4,0x18,0xcf,0x18,0xed,0xce,0xab,0xf4,0x4c,0xd2,0x8c,0x44,
0x87,0x8c,0xeb,0xba,0xe6,0xca,0xf9,0xe3,0xce,0xcf,0x7f,0xc8,0xe9,0x2d,0x2b,0x78,
0x9,0x28,0x3,0xc4,0x18,0xc3,0x83,0x4a,0x19,0xad,0x15,0xc6,0x5,0xe3,0xcc,0xa3,
0x2c,0xae,0x93,0x62,0x6c,0x34,0x8a,0x65,0x59,0x34,0x2c,0xdd,0x60,0x6f,0xfb,0xd9,
0x5f,0x56,0x36,0xd5,0xf0,0xe2,0x33,0xab,0xd9,0xc,0x14,0x8b,0x88,0x3c,0xa8,0x1,
0xa,0x34,0xe0,0xe4,0x95,0x9d,0x43,0xe,0xc6,0x38,0xcc,0xa4,0x93,0x0,0xd8,0xb6,
0x8f,0xc7,0xd7,0x6f,0xf3,0xbf,0xfa,0xab,0xbf,0x6e,0x7a,0x24,0xc2,0xe,0xa0,0x1,
0x8,0x3e,0x4,0x80,0x1,0xe3,0xdd,0xc3,0x81,0x9c,0x8c,0x76,0x6f,0x7d,0xa9,0xa8,
0xa8,0x84,0x25,0xeb,0xb6,0x5,0xda,0xd6,0x6d,0xfc,0xf6,0xc6,0x65,0x3c,0xb,0x94,
0x8b,0x88,0x7a,0x10,0x0,0x3b,0x7,0x90,0x8f,0x0,0x33,0x37,0xa5,0x78,0xb8,0x4e,
0x8a,0x63,0x1f,0x1c,0x26,0x31,0x39,0x85,0x52,0x42,0x38,0x5c,0x82,0x63,0x2,0xbe,
0xe9,0x34,0x75,0x40,0x35,0x30,0x6,0x64,0x1e,0xc0,0x1,0xd,0xa4,0xc1,0xcc,0x80,
0x49,0xcd,0x29,0xbf,0xcf,0xa5,0xb6,0xa6,0x98,0x99,0xe9,0x41,0xa6,0x13,0xfd,0xb8,
0x99,0x1b,0x4,0x3,0x1a,0xcf,0x99,0xc6,0xd3,0x14,0x2,0x85,0xb9,0xdf,0x7a,0x10,
0x7,0xcc,0xcd,0x8,0x5c,0x72,0x30,0x77,0x97,0xa5,0xc,0xb5,0xd5,0xe5,0xb8,0x4e,
0x3,0xbd,0xd7,0xfa,0x19,0x19,0x99,0xe0,0x4c,0xc7,0x39,0x3e,0x3e,0x1b,0xb5,0xa3,
0x71,0x96,0x0,0x9b,0x81,0x2,0x11,0xb9,0x8,0x8c,0x2,0x9e,0x31,0x66,0x6e,0x3b,
0xef,0x2,0x40,0xe7,0x0,0x70,0xf3,0xcf,0xbb,0x4b,0x80,0xcb,0x97,0xbb,0xe9,0xba,
0x74,0x15,0xcb,0x57,0x42,0x7d,0xc3,0x32,0x22,0x55,0xb,0x79,0xe6,0xb9,0xed,0xfe,
0xbe,0x6b,0xbd,0x2d,0x9f,0x9f,0xef,0xc,0x9f,0x3a,0x75,0xaa,0xf5,0xd8,0xb1,0x63,
0x9f,0x45,0xa3,0xd1,0xf,0x81,0x93,0x22,0x32,0x73,0x3f,0x10,0xf6,0x57,0x11,0xa4,
0xe6,0x5,0x38,0x79,0xea,0x3c,0x97,0xbf,0x8c,0xf2,0xe8,0x63,0x2b,0x58,0x54,0xff,
0xd,0x12,0x89,0x4,0x87,0xf,0xb7,0x33,0x3a,0x3a,0x4a,0x55,0x55,0x55,0xc1,0xc6,
0x8d,0x1b,0x9b,0x9e,0x7a,0xea,0xa9,0xa6,0x27,0x9f,0x7c,0x72,0xf9,0xde,0xbd,0x7b,
0x1f,0x3f,0x79,0xf2,0x64,0x35,0x70,0x48,0x44,0x26,0xbf,0x6e,0x5a,0xde,0xb6,0x8,
0xf3,0x9a,0x55,0xe7,0x3e,0xbf,0xc2,0xc5,0xcb,0xfd,0x34,0x2f,0xdb,0x40,0x49,0x49,
0x84,0x37,0xf6,0xed,0xe3,0xec,0xa5,0x4b,0x24,0xd,0xdc,0x88,0x45,0xf5,0xf4,0x94,
0x93,0xfd,0xe7,0xfb,0xed,0x6a,0xf3,0xfa,0xb5,0xf6,0xb6,0xad,0xcf,0x35,0x84,0x4a,
0xc3,0x61,0xc7,0x71,0x8a,0x3a,0x3a,0x3a,0x34,0x70,0xf8,0xeb,0x20,0x6c,0xd0,0x18,
0xe3,0x80,0xce,0xdc,0x5,0x30,0x1e,0x9b,0xe4,0xb3,0xf3,0x5f,0x50,0xbb,0xa0,0x85,
0x50,0xa8,0x92,0x7d,0x7,0xe,0x70,0x79,0x6c,0x84,0x82,0xe5,0x4b,0xa9,0x5e,0x50,
0x8f,0x75,0xe5,0x33,0xdd,0xdf,0x35,0x3a,0xd9,0x1f,0x9b,0x72,0xc7,0x3f,0x3a,0x5d,
0x3c,0x3e,0x95,0xc,0xfe,0xf4,0xe5,0x1d,0xe1,0xe7,0x9f,0x7f,0xfe,0x9b,0x3d,0x3d,
0x3d,0xe3,0xb1,0x58,0x6c,0x0,0xf8,0xaf,0x88,0xa4,0xe6,0x8b,0x23,0xef,0x80,0x41,
0x6b,0xd,0xb3,0x40,0xbb,0xaf,0xf4,0x93,0xcd,0x6,0xa8,0x6b,0x58,0xc6,0xe9,0xb3,
0x67,0x19,0x76,0xb3,0x54,0x7f,0x6b,0xd,0x55,0x8b,0x9b,0x28,0xae,0x5c,0x48,0x8a,
0x84,0xf1,0x67,0xca,0xa6,0xa8,0x32,0xf1,0xde,0xb1,0xc1,0xc0,0x7f,0xae,0xd,0xd5,
0xb6,0x9e,0x39,0x53,0xb6,0x65,0xcb,0x96,0xaa,0xa3,0x47,0x8f,0xae,0x6a,0x6f,0x6f,
0x7f,0x2,0xe8,0x25,0xb7,0x3d,0xef,0xb6,0x17,0x50,0x18,0xd0,0xf3,0xcc,0xe9,0x2f,
0xaf,0xe,0x52,0x54,0x5a,0x4d,0x3a,0x9d,0xa6,0x27,0x3a,0x4c,0x41,0x73,0x23,0x75,
0x2b,0x5b,0x28,0xaf,0xaf,0x23,0x18,0x2a,0xc1,0xa,0x16,0x18,0x55,0x58,0xe4,0xb0,
0xa0,0x21,0xc6,0x92,0x55,0x3,0x17,0xa4,0xb8,0xef,0xcc,0x17,0x3d,0xe9,0x74,0x3a,
0x4d,0x5b,0x5b,0x5b,0xd,0xd0,0x2,0x54,0x1,0xfe,0xf9,0x22,0x50,0x6,0x30,0x5a,
0xa3,0xe7,0xd0,0xe0,0xe0,0x18,0xe5,0xe5,0xb5,0x64,0xb3,0x59,0x66,0x82,0x1,0x2a,
0x1b,0x1f,0xa3,0x30,0x1c,0x46,0x44,0x71,0xcb,0x51,0x11,0x83,0x3f,0x90,0xa5,0x72,
0x61,0x82,0xfa,0xe6,0x91,0xde,0x64,0x36,0x9e,0xcd,0x66,0x69,0x69,0x69,0x29,0x6,
0x16,0x1,0x91,0x7b,0x2,0x80,0xc1,0xe4,0x63,0x98,0xed,0x40,0x2c,0x3e,0x85,0x3f,
0x50,0x88,0x6d,0xdb,0xb8,0xa1,0x10,0x85,0xe5,0x65,0x88,0x65,0x31,0xc7,0xc4,0x34,
0xf8,0xfc,0x2e,0x15,0xd5,0xd3,0x57,0x33,0x8c,0xd9,0xb6,0x4d,0x24,0x12,0xf1,0x1,
0xa5,0x40,0x18,0xf0,0xcd,0xf,0x60,0xc0,0x68,0x83,0x36,0x77,0x3b,0x10,0xc,0xf8,
0xb9,0xde,0xd7,0x8b,0xdf,0xef,0xa7,0x2e,0x12,0x41,0x59,0x76,0x1e,0x8e,0xbc,0x3,
0xb3,0x40,0x7c,0x7e,0xaf,0xad,0xb9,0x31,0xe0,0xf7,0xfb,0xe9,0xea,0xea,0xba,0x99,
0x79,0x1,0x60,0xdd,0xc3,0x1,0x30,0x46,0x63,0xc,0x68,0xad,0x31,0xf9,0x5,0xa9,
0xb5,0xa6,0xac,0xac,0x84,0xc1,0xc1,0x5e,0x44,0x84,0xba,0xc2,0x22,0x3c,0xc7,0xb9,
0xe5,0xce,0x9c,0xe5,0xb9,0xb2,0xbe,0xa1,0xb6,0x5c,0x44,0xe8,0xec,0xec,0xcc,0x0,
0x69,0xc0,0x63,0xbe,0x11,0x7b,0x2b,0x82,0x59,0xcd,0x6f,0x36,0xa9,0xab,0xab,0x64,
0x78,0xa8,0x8f,0xa1,0xa1,0x21,0x16,0x97,0x47,0xa8,0x48,0xce,0xe0,0xb9,0x6e,0x2e,
0xb4,0xd9,0x10,0x9e,0xab,0xb6,0x55,0x17,0x34,0xac,0x6f,0xac,0x2f,0x1f,0x1a,0x1a,
0xa2,0xa3,0xa3,0x23,0x4d,0xee,0x80,0x9a,0xce,0x43,0xcc,0xd,0x90,0x33,0xd2,0xdc,
0xd1,0xfc,0xa6,0x3,0x4d,0x8d,0xb,0xf1,0x5b,0x59,0x3e,0x38,0x7a,0x8,0x37,0x9d,
0x66,0x89,0x1d,0xa0,0x32,0x99,0x46,0xbb,0xee,0x9d,0xee,0x6b,0x4f,0x5e,0xac,0x9,
0x3c,0xba,0xad,0xb1,0x6a,0x89,0xc9,0x66,0xec,0xfd,0xfb,0xf7,0xcf,0x74,0x77,0x77,
0xa7,0x81,0x21,0x20,0x41,0xee,0x62,0x71,0x8f,0x8,0xf2,0xd,0x67,0x3b,0xb0,0xa0,
0xb6,0x82,0xd5,0xad,0x4d,0x8c,0x46,0x7b,0x79,0xfb,0xed,0xb7,0x28,0x45,0x58,0x1f,
0x2c,0xa6,0xcd,0xd1,0x2c,0xc8,0x66,0x29,0xb7,0x7c,0xf2,0xec,0xe2,0xfa,0xf0,0x9f,
0x9f,0x68,0x6a,0xfb,0xc5,0xaa,0x86,0xd5,0xf5,0xc5,0x5,0xe1,0xbf,0xed,0xd9,0x93,
0x39,0x71,0xe2,0x44,0xa6,0xb9,0xb9,0xb9,0xa0,0xa2,0xa2,0xa2,0x19,0x68,0x2,0x6a,
0x44,0xc4,0x9e,0xeb,0xe6,0x24,0x67,0xdf,0xfb,0xf5,0xe8,0x92,0xd,0x4f,0x57,0xba,
0x99,0x4,0x46,0x3b,0x77,0x7c,0x68,0xc,0x4c,0x4d,0xa7,0x39,0xf0,0xce,0x47,0x7c,
0xf2,0xe9,0x17,0xd8,0xfe,0x10,0x6b,0xd7,0x3e,0xc1,0xa6,0x4d,0x9b,0x8,0x85,0x42,
0xb9,0xdd,0xe1,0xba,0x4c,0x4e,0x4e,0x72,0xfc,0xf8,0x71,0xe,0x1e,0x3c,0x98,0xea,
0xea,0xea,0xca,0x46,0x22,0x11,0x76,0xed,0xda,0x15,0x4e,0x24,0x12,0x33,0xaf,0xbf,
0xfe,0xfa,0xb9,0xfa,0xe0,0x74,0xbc,0x73,0x44,0xef,0x3,0xe,0x1,0xd3,0xb7,0x5f,
0x64,0x6f,0x4d,0xc2,0xaf,0x16,0x97,0x20,0xa2,0x10,0x65,0xa1,0xc4,0x26,0x14,0x2e,
0x66,0xeb,0xd6,0x1f,0x50,0x58,0x52,0xce,0x7,0x47,0x3f,0x36,0xef,0x1e,0xd8,0xcb,
0x5b,0x6f,0xee,0x21,0x50,0x58,0x4c,0x20,0x50,0x2c,0xc9,0x54,0xca,0x8d,0xc5,0x62,
0x4e,0x22,0x91,0xc8,0xc6,0x62,0xb1,0xe9,0x4c,0x26,0x33,0xe0,0x38,0x8e,0x2f,0x1e,
0x8f,0x2f,0x4b,0x24,0x12,0xc1,0x9f,0x6c,0xa8,0x5d,0xb7,0x21,0x74,0x4d,0xf6,0x5d,
0x70,0x17,0x1e,0xbc,0xe4,0x55,0x0,0x6f,0x8a,0xc8,0xc4,0x4d,0x8,0x3b,0x3f,0x5,
0x40,0x14,0xa2,0x7c,0x88,0xb2,0x11,0xe5,0x43,0x59,0x7e,0x2c,0xab,0x80,0xf1,0xe8,
0x75,0xef,0xd2,0x27,0xef,0x3b,0x89,0x73,0x47,0x3c,0x89,0xe,0xce,0x8c,0xf,0xe2,
0xf6,0x8d,0xe1,0xa5,0x32,0x58,0xe4,0xb6,0x97,0x7,0xa4,0x80,0x18,0xd0,0x3,0x74,
0xc6,0xe3,0x71,0x6b,0xf7,0xee,0xdd,0xde,0x33,0xcb,0x6b,0xda,0x96,0xaa,0x5e,0x35,
0xa9,0x84,0x1f,0xaf,0xb4,0x5b,0x94,0xc8,0xce,0x7f,0x75,0xb9,0xa,0xd8,0x27,0x22,
0x71,0x63,0x8c,0x67,0x3,0x28,0x2b,0x88,0x65,0x6b,0x44,0x14,0xca,0xe,0x10,0x8b,
0xf6,0x7b,0x17,0x4f,0x1d,0x76,0xba,0xcf,0x1c,0x71,0xaf,0xf6,0xe,0x4c,0x5e,0x1c,
0xe0,0x7a,0x67,0x3f,0xdd,0xc3,0x13,0xc,0xe7,0x17,0x94,0x2,0x2,0x7c,0x35,0x60,
0x52,0xc0,0xd,0x60,0x0,0xb8,0xe,0x68,0x7b,0x66,0x6a,0x83,0x15,0x4d,0xca,0x44,
0x89,0x60,0x29,0x50,0xa,0x79,0x79,0x85,0xbd,0x52,0x9,0x3b,0xde,0xb9,0xe8,0x1a,
0x60,0xbf,0x88,0xc4,0x6d,0x0,0x5f,0xa0,0x94,0x89,0x91,0x41,0xaf,0xf3,0xe4,0xc1,
0x3b,0x9b,0x5e,0xa7,0x7b,0x38,0x4e,0x1f,0x10,0x5,0xfa,0xf3,0xcf,0xa9,0x7c,0x53,
0x2b,0x17,0x21,0x2a,0xef,0x42,0x86,0xdc,0x96,0x9b,0x2,0x9c,0x98,0x63,0xf6,0x9e,
0x18,0xd6,0x35,0xdf,0x51,0x6a,0x85,0xa5,0x20,0x27,0x2d,0xaf,0xb4,0xda,0xad,0x22,
0xf0,0x76,0xa7,0xb,0xb0,0x5f,0x7e,0xfb,0x2,0xaf,0xf9,0x2d,0x5e,0x18,0x8e,0xa3,
0x3b,0xfb,0x19,0x9c,0xa3,0xe9,0x50,0xfe,0xed,0x26,0xf3,0x6f,0xea,0x90,0xbb,0x24,
0x29,0xee,0xbc,0x7,0xea,0xdb,0x4,0x10,0x2,0x5e,0x7a,0xac,0x50,0x76,0x7e,0x77,
0x91,0x5a,0x59,0x59,0x22,0x54,0x96,0x2a,0xaa,0x42,0x42,0x79,0xa9,0x98,0x5f,0x1e,
0xc9,0x9e,0xb8,0x10,0xd5,0xbf,0x13,0x72,0xa7,0xd5,0x1a,0x60,0x31,0xb9,0xc9,0x35,
0x34,0xab,0x69,0x12,0x70,0xee,0xf7,0x8e,0x77,0xb3,0x44,0xc4,0x22,0xf7,0xcf,0x69,
0x7b,0x63,0x91,0x6c,0xdf,0x52,0xa7,0x5a,0x23,0x25,0x22,0x55,0xa5,0x8a,0x4f,0x47,
0xf4,0xf8,0xfe,0xb,0xee,0x87,0xc0,0x1b,0x36,0x30,0x1,0x7c,0xa,0x5c,0xcc,0x5b,
0x39,0xfd,0xa0,0x4d,0x6f,0x2f,0x63,0x8c,0x27,0x22,0x13,0xc0,0xdf,0x7b,0x92,0xc6,
0xc8,0x80,0xe6,0xfb,0xf5,0xaa,0xf5,0xf4,0xa8,0x1b,0x6b,0xef,0xd3,0x9d,0xc0,0x79,
0xe0,0x86,0x3c,0x44,0x8f,0xfb,0xaa,0xbc,0x13,0x61,0xe0,0x47,0x11,0xbf,0x3c,0x77,
0x23,0x6b,0x26,0xf2,0xcd,0x3f,0x2,0x3a,0xff,0xef,0x0,0xb3,0x20,0x56,0x93,0x3b,
0x1d,0x6f,0x0,0x5f,0x2,0xb1,0xff,0x1,0x2c,0x4a,0x8b,0xc,0x2d,0x65,0x69,0x34,
0x0,0x0,0x0,0x0,0x49,0x45,0x4e,0x44,0xae,0x42,0x60,0x82,
};
static const unsigned char qt_resource_name[] = {
// new
0x0,0x3,
0x0,0x0,0x74,0xc7,
0x0,0x6e,
0x0,0x65,0x0,0x77,
// prefix1
0x0,0x7,
0x7,0x8b,0xd0,0x51,
0x0,0x70,
0x0,0x72,0x0,0x65,0x0,0x66,0x0,0x69,0x0,0x78,0x0,0x31,
// findfile.png
0x0,0xc,
0x5,0x88,0xc2,0xc7,
0x0,0x66,
0x0,0x69,0x0,0x6e,0x0,0x64,0x0,0x66,0x0,0x69,0x0,0x6c,0x0,0x65,0x0,0x2e,0x0,0x70,0x0,0x6e,0x0,0x67,
};
static const unsigned char qt_resource_struct[] = {
// :
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x1,
// :/new
0x0,0x0,0x0,0x0,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x2,
// :/new/prefix1
0x0,0x0,0x0,0xc,0x0,0x2,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x3,
// :/new/prefix1/findfile.png
0x0,0x0,0x0,0x20,0x0,0x0,0x0,0x0,0x0,0x1,0x0,0x0,0x0,0x0,
};
int qInitResources_findfile()
{
extern bool qRegisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
qRegisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_CONSTRUCTOR_FUNCTION(qInitResources_findfile)
int qCleanupResources_findfile()
{
extern bool qUnregisterResourceData(int, const unsigned char *, const unsigned char *, const unsigned char *);
qUnregisterResourceData(0x01, qt_resource_struct, qt_resource_name, qt_resource_data);
return 1;
}
Q_DESTRUCTOR_FUNCTION(qCleanupResources_findfile)
| [
"mengxs1008@163.com"
] | mengxs1008@163.com |
d0b640d8bfbc1ea851305926f2c5ce5e0281fe1b | e33b71c78961467a05dd44da1e6e281cdfc5cd03 | /11050_이항 계수 1/main_RuntimeError.cpp | 617346c32822e704501f76edb13a92ddf945b348 | [] | no_license | syjang37/BAEKJOON | cfeaf808c0b4908e5f7edf8d938576912c9fface | eddf875b757ee0b8579fc50b116d95a375da9209 | refs/heads/master | 2022-12-07T06:30:10.811595 | 2020-08-26T18:11:46 | 2020-08-26T18:11:46 | 289,044,687 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 516 | cpp | #include <iostream>
#include <string.h>
using namespace std;
int ** arr;
int binomial(int n, int k);
int main()
{
int n = 0;
int k = 0;
scanf("%d %d", &n, &k);
fflush(stdin);
arr = new int*[n + 1];
for (int i = 0; i < n + 1; i++) {
arr[i] = new int[k];
memset(arr[i], -1, sizeof(int)*k);
}
printf("%d\n", binomial(n, k));
return 0;
}
int binomial(int n, int k)
{
if (n == k || k == 0) {
arr[n][k] = 1;
}
else
{
arr[n][k] = binomial(n - 1, k) + binomial(n - 1, k - 1);
}
return arr[n][k];
} | [
"slong94@naver.com"
] | slong94@naver.com |
df2187f9b72d0bbf04fd099c88380208039fed45 | ff383401324de6a733c57014925e1db9e153b822 | /Difficulty/Hard/[126] Word Ladder II/solution.cpp | fa2555915723e3e2aae0d051fd65fc170c9529b3 | [] | no_license | ForSign/Leetcode-1 | 7af7a74c9a5c01c7e67faa5f6e5874f4d3902565 | 9a2d41fb15304cc7aaff5a36aced5dc0ab6d3745 | refs/heads/master | 2023-03-15T20:21:07.254494 | 2020-10-14T08:04:24 | 2020-10-14T08:04:24 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,260 | cpp | /*
* @lc app=leetcode id=126 lang=cpp
*
* [126] Word Ladder II
*/
// @lc code=start
class Solution {
private:
unordered_set<string> wordList;
vector<vector<string>> ans;
unordered_set<string> visited;
int level = 1;
int minLevel = INT_MAX;
public:
vector<vector<string>> findLadders(string beginWord, string endWord,vector<string> &words ) {
//Putting all words in a set
for(auto word: words)
wordList.insert(word);
//wordList.insert(endWord); Cant insert endWord now
//Queue of Paths
queue<vector<string>> q;
q.push({beginWord});
while (!q.empty())
{
vector<string> path = q.front(); q.pop();
if (path.size() > level)
{
for (string w : visited)
wordList.erase(w);
if (path.size() > minLevel)
break;
else
level = path.size();
}
string lastWord = path.back();
addNeighboursToQ(lastWord,path,q,endWord);
}
return ans;
}
void addNeighboursToQ(string curr,vector<string> path,queue<vector<string>> &q,const string &endWord)
{
for(int i=0;i<curr.size();i++)
{
char originalChar = curr[i];
for(int j=0;j<26;j++)
{
curr[i] = j + 'a';
if(wordList.find(curr)!=wordList.end())
{
vector<string> newpath = path;
newpath.push_back(curr);
visited.insert(curr);
if (curr == endWord) {
minLevel = level;
ans.push_back(newpath);
}
else
q.push(newpath);
}
}
curr[i] = originalChar;
}
}
};
class Solution {
public:
vector<vector<string>> findLadders(string beginWord, string endWord, vector<string>& wordList) {
if (find(wordList.begin(), wordList.end(), endWord) == wordList.end()) return vector<vector<string>>();
vector<string> newWordList;
for(auto& s : wordList){
if (stringDiff(s, beginWord) != beginWord.size() ||
stringDiff(s, endWord) != endWord.size())
newWordList.push_back(s);
}
vector<vector<string>> res;
unordered_map<string, int> dict;
for (auto& s : newWordList){
if (s == endWord) dict[s] = 1;
else dict[s] = 0;
}
vector<string> ladder(1, beginWord);
int min_height = INT_MAX;
findLadder(res, beginWord, endWord, newWordList, ladder, 0, min_height, dict);
return res;
}
void findLadder(vector<vector<string>>& res, string beginWord, string endWord, vector<string>& wordList, vector<string>& ladder, int height, int& min_height, unordered_map<string, int>& dict) {
if (height > min_height) return;
if (stringDiff(beginWord, endWord) == 1)
{
ladder.push_back(endWord);
if (height < min_height){
res.clear();
min_height = height;
}
res.push_back(ladder);
ladder.pop_back();
return;
}
for (auto & s : wordList) {
if (stringDiff(beginWord, s) == 1 && dict[s] == 0) {
ladder.push_back(s);
dict[s] = 1;
findLadder(res, s, endWord, wordList, ladder, height + 1, min_height, dict);
dict[s] = 0;
ladder.pop_back();
}
}
}
int stringDiff(string word1, string word2) {
int count = 0;
for (int i = 0; i < word1.size(); ++i) {
if (word1[i] != word2[i]) count++;
}
return count;
}
};
// @lc code=end
| [
"15270989505@163.com"
] | 15270989505@163.com |
a18480de820ab9a5f39cf2b209ebc18415fe5124 | 557ac069bf9505b3dfeadfb2570911dba4bf4067 | /hw_set_2/hw7/patient.cc | 870537edf6d86afd255e97d3a5e24aedb99efe24 | [] | no_license | dacarlin/boot_camp_homework | 8f9cca26ab12a8af3fa35343a1496bdec7bbb14a | 78b6b4a622ae6c61a37ba985bc20f5ab8bef5372 | refs/heads/master | 2020-06-11T05:44:10.369334 | 2017-01-14T22:41:40 | 2017-01-14T22:41:40 | 75,993,999 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,304 | cc | #include <iostream>
#include <string>
// Assignment:
//
// Write a "Patient" class here that represents patient data for a medical clinic.
//
// Patient data to store:
// * Name (a single C++ std::string)
// * Current height (in m)
// * Current weight (in kg)
//
// The data should be encapsulated (private).
// No direct access to the data should be allowed,
// only access data through class member functions (see below).
//
// You should provide a way to construct a patient class with a name,
// as well as one where no name is availible yet.
// (Use a value of "0" to represent an unknown height or weight,
// and an empty string to represent an unknown name.)
//
// Three methods ("set_name", "set_height", "set_weight") should be provided
// which allow you to individually change the name, the height, or the weight.
// - You should check that the provided height and weight are positive,
// and set them to the unknown values (see above) if they are invalid (negative).
//
// Three additional methods ("get_name", "get_height", "get_weight")
// should allow you to obtain the name, height and weight of a patient.
//
// You should also provide a method ("bmi") which calculates
// the patient's BMI (body mass index) and returns it.
// (The BMI is the weight in kg divided by the square of the height in meters:
// http://en.wikipedia.org/wiki/Body_mass_index).
// If either the height or weight is unknown, return "0" for the BMI.
//
// For the moment ignore any complications regarding the validity
// of BMI for assessing health, or complications regarding applying
// it to any particular group of people (like infants).
class Patient {
private:
// data here
std::string name;
double height, weight; // meters, kilograms
public:
//Patient( std::string n ) :name{n}, height{0}, weight{0} {}
//Patient() :name{""}, height{0}, weight{0} {}
// why don't these work? See p. 35 of Stroustrup, "A Tour of C++"
Patient( std::string n ) { name = n; height = 0; weight = 0; }
Patient() { name = ""; height = 0; weight = 0; }
// methods to set private data
void set_name( std::string n ) {
name = n;
}
void set_height( double h ) {
height = h;
}
void set_weight( double w ) {
weight = w;
}
// methods to get data
std::string get_name() {
return name;
}
double get_height() {
return height;
}
double get_weight() {
return weight;
}
// method to calculate BMI
double bmi() {
if ( height > 0 and weight > 0 ) {
return weight / ( height * height ); // unit: kg/m^2
} else {
return 0;
}
}
};
int main() {
Patient father("Andrew Nonymous");
Patient mother("Ursula N. Known");
Patient baby;
//Father's height and weight are unknown.
mother.set_name("Ursula N. Nonymous");
mother.set_height(1.65);
mother.set_weight(58);
baby.set_height(0.495);
baby.set_weight(3.4);
std::cout << "Baby: " << baby.get_name() << " BMI: " << baby.bmi() << std::endl;
std::cout << "Mother: " << mother.get_name() << " BMI: " << mother.bmi() << std::endl;
std::cout << "Father: " << father.get_name() << " BMI: " << father.bmi() << std::endl;
return 0;
}
| [
"carlin@ucdavis.edu"
] | carlin@ucdavis.edu |
682d2e08495a4f4ce890fa4a1f21d74475831618 | 9da899bf6541c6a0514219377fea97df9907f0ae | /Runtime/Core/Public/Modules/Boilerplate/ModuleBoilerplate.h | 58febc4231070532707263827becb080bb35faaa | [] | no_license | peichangliang123/UE4 | 1aa4df3418c077dd8f82439ecc808cd2e6de4551 | 20e38f42edc251ee96905ed8e96e1be667bc14a5 | refs/heads/master | 2023-08-17T11:31:53.304431 | 2021-09-15T00:31:03 | 2021-09-15T00:31:03 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 3,722 | h | // Copyright Epic Games, Inc. All Rights Reserved.
#pragma once
#include "CoreTypes.h"
#include "HAL/UnrealMemory.h"
#include "UObject/NameTypes.h"
class FChunkedFixedUObjectArray;
// Boilerplate that is included once for each module, even in monolithic builds
#if !defined(PER_MODULE_BOILERPLATE_ANYLINK)
#define PER_MODULE_BOILERPLATE_ANYLINK(ModuleImplClass, ModuleName)
#endif
/**
* Override new + delete operators (and array versions) in every module.
* This prevents the possibility of mismatched new/delete calls such as a new[] that
* uses Unreal's allocator and a delete[] that uses the system allocator.
*/
#if USING_CODE_ANALYSIS
#define OPERATOR_NEW_MSVC_PRAGMA MSVC_PRAGMA( warning( suppress : 28251 ) ) // warning C28251: Inconsistent annotation for 'new': this instance has no annotations
#else
#define OPERATOR_NEW_MSVC_PRAGMA
#endif
#if !FORCE_ANSI_ALLOCATOR
#define REPLACEMENT_OPERATOR_NEW_AND_DELETE \
OPERATOR_NEW_MSVC_PRAGMA void* operator new ( size_t Size ) OPERATOR_NEW_THROW_SPEC { return FMemory::Malloc( Size ); } \
OPERATOR_NEW_MSVC_PRAGMA void* operator new[]( size_t Size ) OPERATOR_NEW_THROW_SPEC { return FMemory::Malloc( Size ); } \
OPERATOR_NEW_MSVC_PRAGMA void* operator new ( size_t Size, const std::nothrow_t& ) OPERATOR_NEW_NOTHROW_SPEC { return FMemory::Malloc( Size ); } \
OPERATOR_NEW_MSVC_PRAGMA void* operator new[]( size_t Size, const std::nothrow_t& ) OPERATOR_NEW_NOTHROW_SPEC { return FMemory::Malloc( Size ); } \
void operator delete ( void* Ptr ) OPERATOR_DELETE_THROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete[]( void* Ptr ) OPERATOR_DELETE_THROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete ( void* Ptr, const std::nothrow_t& ) OPERATOR_DELETE_NOTHROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete[]( void* Ptr, const std::nothrow_t& ) OPERATOR_DELETE_NOTHROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete ( void* Ptr, size_t Size ) OPERATOR_DELETE_THROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete[]( void* Ptr, size_t Size ) OPERATOR_DELETE_THROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete ( void* Ptr, size_t Size, const std::nothrow_t& ) OPERATOR_DELETE_NOTHROW_SPEC { FMemory::Free( Ptr ); } \
void operator delete[]( void* Ptr, size_t Size, const std::nothrow_t& ) OPERATOR_DELETE_NOTHROW_SPEC { FMemory::Free( Ptr ); }
#else
#define REPLACEMENT_OPERATOR_NEW_AND_DELETE
#endif
class FChunkedFixedUObjectArray;
#ifdef DISABLE_UE4_VISUALIZER_HELPERS
#define UE4_VISUALIZERS_HELPERS
#elif PLATFORM_UNIX
// GDB/LLDB pretty printers don't use these - no need to export additional symbols. This also solves ODR violation reported by ASan on Linux
#define UE4_VISUALIZERS_HELPERS
#else
#define UE4_VISUALIZERS_HELPERS \
uint8** GNameBlocksDebug = FNameDebugVisualizer::GetBlocks(); \
FChunkedFixedUObjectArray*& GObjectArrayForDebugVisualizers = GCoreObjectArrayForDebugVisualizers; \
TArray<FMinimalName, TInlineAllocator<3>>*& GComplexObjectPathDebug = GCoreComplexObjectPathDebug; \
FObjectHandlePackageDebugData*& GObjectHandlePackageDebug = GCoreObjectHandlePackageDebug;
#endif
// in DLL builds, these are done per-module, otherwise we just need one in the application
// visual studio cannot find cross dll data for visualizers, so these provide access
#define PER_MODULE_BOILERPLATE \
UE4_VISUALIZERS_HELPERS \
REPLACEMENT_OPERATOR_NEW_AND_DELETE
| [
"ouczbs@qq.com"
] | ouczbs@qq.com |
4f8f9db9acbdf75f051703ee134f698ff06e00e7 | 08b8cf38e1936e8cec27f84af0d3727321cec9c4 | /data/crawl/make/hunk_673.cpp | d3481c0a15ccfedb5dfb76bf89d68d3976345021 | [] | no_license | ccdxc/logSurvey | eaf28e9c2d6307140b17986d5c05106d1fd8e943 | 6b80226e1667c1e0760ab39160893ee19b0e9fb1 | refs/heads/master | 2022-01-07T21:31:55.446839 | 2018-04-21T14:12:43 | 2018-04-21T14:12:43 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 405 | cpp | fatal (NILF,
_("internal error: invalid --jobserver-fds string `%s'"), cp);
+ DB (DB_JOBS,
+ (_("Jobserver client (fds %d,%d)\n"), job_fds[0], job_fds[1]));
+
/* The combination of a pipe + !job_slots means we're using the
jobserver. If !job_slots and we don't have a pipe, we can start
infinite jobs. If we see both a pipe and job_slots >0 that means the
| [
"993273596@qq.com"
] | 993273596@qq.com |
ab7f8f0f931603c6b66934604eacaaa6978b679d | b7f3edb5b7c62174bed808079c3b21fb9ea51d52 | /chromecast/common/activity_filtering_url_loader_throttle.cc | 0aad4cb81c28e5f864c9f474bfacf605d4b273fd | [
"BSD-3-Clause"
] | permissive | otcshare/chromium-src | 26a7372773b53b236784c51677c566dc0ad839e4 | 64bee65c921db7e78e25d08f1e98da2668b57be5 | refs/heads/webml | 2023-03-21T03:20:15.377034 | 2020-11-16T01:40:14 | 2020-11-16T01:40:14 | 209,262,645 | 18 | 21 | BSD-3-Clause | 2023-03-23T06:20:07 | 2019-09-18T08:52:07 | null | UTF-8 | C++ | false | false | 1,503 | cc | // Copyright 2020 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 "chromecast/common/activity_filtering_url_loader_throttle.h"
namespace chromecast {
namespace {
const char kCancelReason[] = "ActivityFilteringURLLoaderThrottle";
} // namespace
ActivityFilteringURLLoaderThrottle::ActivityFilteringURLLoaderThrottle(
ActivityUrlFilter* filter)
: url_filter_(filter) {}
ActivityFilteringURLLoaderThrottle::~ActivityFilteringURLLoaderThrottle() =
default;
void ActivityFilteringURLLoaderThrottle::WillStartRequest(
network::ResourceRequest* request,
bool* /* defer */) {
FilterURL(request->url);
}
void ActivityFilteringURLLoaderThrottle::WillRedirectRequest(
net::RedirectInfo* redirect_info,
const network::mojom::URLResponseHead& /* response_head */,
bool* /* defer */,
std::vector<std::string>* /* to_be_removed_request_headers */,
net::HttpRequestHeaders* /* modified_request_headers */,
net::HttpRequestHeaders* /* modified_cors_exempt_request_headers */) {
FilterURL(redirect_info->new_url);
}
void ActivityFilteringURLLoaderThrottle::DetachFromCurrentSequence() {}
void ActivityFilteringURLLoaderThrottle::FilterURL(const GURL& url) {
// Pass through allowed URLs, block otherwise.
if (!url_filter_->UrlMatchesWhitelist(url))
delegate_->CancelWithError(net::ERR_ACCESS_DENIED, kCancelReason);
}
} // namespace chromecast
| [
"commit-bot@chromium.org"
] | commit-bot@chromium.org |
cc7c155c622442346039491bfb55d6d692605970 | bdc8de490835cc0082454f9d9a37018c18fe8b5b | /690.cpp | f7984a5cf8fcf159dfdfb3ad413e83a267634f83 | [] | no_license | bytefly/leetcode | b3385bea2d0c1aefd9be2964d8e8ea23d89b2f3d | 4940a78c77ccbcd9dbd421dd8a090ee28f81ad0f | refs/heads/master | 2022-01-26T00:03:35.436151 | 2020-04-02T10:30:42 | 2020-04-02T10:30:42 | 230,178,910 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,698 | cpp | #include <iostream>
#include <vector>
#include <map>
#include <queue>
using namespace std;
// Employee info
class Employee {
public:
// It's the unique ID of each node.
// unique id of this employee
int id;
// the importance value of this employee
int importance;
// the id of direct subordinates
vector<int> subordinates;
public:
Employee(int _id, int _importance, vector<int> _sub) {
id = _id;
importance = _importance;
subordinates = _sub;
}
};
class Solution {
public:
int getImportance(vector<Employee*> employees, int id) {
map<int, int> m;
queue<int> q;
Employee *leader;
int ans = 0;
for (int i = 0; i < employees.size(); i++) {
m[employees[i]->id] = i;
if (employees[i]->id == id) {
q.push(employees[i]->id);
}
}
while (!q.empty()) {
leader = employees[m[q.front()]];
ans += leader->importance;
for (int i = 0; i < leader->subordinates.size(); i++) {
q.push(leader->subordinates[i]);
}
q.pop();
}
return ans;
}
};
int main(int argc, char **argv) {
vector<Employee*> v;
vector<int> sub1;
sub1.push_back(2);
sub1.push_back(3);
v.push_back(new Employee(1, 5, sub1));
vector<int> sub2;
v.push_back(new Employee(2, 3, sub2));
vector<int> sub3;
v.push_back(new Employee(3, 3, sub3));
Solution s;
cout<<s.getImportance(v, 1)<<endl;
}
| [
"zhengrui.l@gmail.com"
] | zhengrui.l@gmail.com |
9dc201ff7ae74c06c4ce07ecf09a9230865f7497 | 07a7198d296041275750af246d6c05f710b42907 | /src/libs/gui/ConfigurePanelInterface.hpp | 211c6315da8fa85647b0a338a2e5f63a21713f07 | [] | no_license | chenlijun99/DeviceInterface | 1da03f4e5a084673228c3afd476beb40709cbde4 | 00c5fe37e6afbf08af7de356e759e1fd68bb32fc | refs/heads/master | 2021-06-22T20:10:20.932318 | 2017-08-29T07:38:46 | 2017-08-29T07:38:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 778 | hpp | #ifndef CONFIGUREPANELINTERFACE_HPP
#define CONFIGUREPANELINTERFACE_HPP
#include <ConfigurableUiInterface.hpp>
#include <ToggleButton.hpp>
#include <IntLineEdit.hpp>
#include <QMap>
class UiPanelConfiguration;
class DeviceConfiguration;
class QDockWidget;
namespace interface
{
class ConfigurePanel : public ConfigurableUiInterface
{
public:
QMap<QString, ToggleButton*> flagToggleButtons;
QMap<QString, IntLineEdit*> parameterLineEdits;
QPushButton *configureButton;
QMap<QString, ToggleButton*> previousFlagToggleButtons;
QMap<QString, IntLineEdit*> previousParameterLineEdits;
virtual void clearInterface(QWidget *widget) override;
void setupInterface(QDockWidget *widget,
const UiPanelConfiguration &uiConfig);
};
}
#endif // CONFIGUREPANELINTERFACE_H
| [
"chenlijun1999@gmail.com"
] | chenlijun1999@gmail.com |
a559027e2819394232f6b6251d114ec89714e5c3 | 877fff5bb313ccd23d1d01bf23b1e1f2b13bb85a | /app/src/main/cpp/dir7941/dir22441/dir28114/dir28115/file28151.cpp | 0260823d5a08d7a710a6cafded5ea171312f102a | [] | 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 file28151
#error "macro file28151 must be defined"
#endif
static const char* file28151String = "file28151"; | [
"tgeng@google.com"
] | tgeng@google.com |
44b7486b0a41b68043af9771ed89a4614f912d33 | 6c8c72fa2b053cc43cc84999ffcb73d4adb5c2eb | /src/invariant/InvariantDoesNotHold.h | 906e660ccb1832161153614c7648f7dfb0c45422 | [
"BSL-1.0",
"BSD-3-Clause",
"Apache-2.0",
"LicenseRef-scancode-public-domain",
"MIT",
"BSD-2-Clause",
"FSFAP"
] | permissive | parki02/starall | 730b9e89cd54b2c87db7171b5aaddcc5fa521732 | f6c0878560a6220c44db21e2ea0cbaf1c0dd9a2f | refs/heads/master | 2020-03-24T22:42:13.747356 | 2018-08-01T03:20:02 | 2018-08-01T03:20:02 | 142,956,536 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 459 | h | #pragma once
// Copyright 2017 Starall 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
#include <stdexcept>
namespace starall
{
class InvariantDoesNotHold : public std::runtime_error
{
public:
explicit InvariantDoesNotHold(std::string const& msg);
virtual ~InvariantDoesNotHold() override;
};
}
| [
"parki02@hanmail.net"
] | parki02@hanmail.net |
eeccdf19362940aa6de48b4ecaa5bad405fff102 | 2e70851249c4ea5560d435eb3157d58286ccad6a | /libs/core/include/fcppt/type_traits/is_brigand_sequence.hpp | 6a89902565720e8fac0837f7acecd6cf2818eaf1 | [
"BSL-1.0"
] | permissive | Aurora-Community/fcppt | cd19d9c773b61425d8f07fcc396c88ea244e6d59 | da7ebc30f2bd078dbcef73b0c94001c190b87165 | refs/heads/master | 2020-08-06T22:50:27.241996 | 2019-10-05T09:45:45 | 2019-10-05T09:45:56 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 892 | hpp | // Copyright Carl Philipp Reh 2009 - 2018.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
#ifndef FCPPT_TYPE_TRAITS_IS_BRIGAND_SEQUENCE_HPP_INCLUDED
#define FCPPT_TYPE_TRAITS_IS_BRIGAND_SEQUENCE_HPP_INCLUDED
#include <fcppt/config/external_begin.hpp>
#include <brigand/sequences/list.hpp>
#include <type_traits>
#include <fcppt/config/external_end.hpp>
namespace fcppt
{
namespace type_traits
{
/**
\brief Checks if an type is an brigand sequence.
\ingroup fcppttypetraits
Checks if \a Type is an brigand sequence.
\tparam Type Can be any type
*/
template<
typename Type
>
struct is_brigand_sequence
:
std::false_type
{
};
template<
typename... Types
>
struct is_brigand_sequence<
::brigand::list<
Types...
>
>
:
std::true_type
{
};
}
}
#endif
| [
"carlphilippreh@gmail.com"
] | carlphilippreh@gmail.com |
a89a800ec1ebe7904d1c9cc12f3ed95bd324622c | 2a96f694672417702c63b29dd659ce262273aa6a | /be/src/olap/comparison_predicate.h | 3590b9ef7aa3b0ca01c01b4bdfa15d4f2059815e | [
"Apache-2.0",
"BSD-3-Clause",
"PSF-2.0",
"bzip2-1.0.6",
"LicenseRef-scancode-public-domain",
"dtoa"
] | permissive | Arleff/incubator-doris | 36c7de6d955cdf60a11a32ad3b032c0db4ca37b1 | 2a290048c777c45fe4e0783d4e87982bd3a08a71 | refs/heads/master | 2020-04-04T02:47:07.443083 | 2018-11-01T08:33:09 | 2018-11-01T08:33:09 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,736 | h | // Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements. See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership. The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License. You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied. See the License for the
// specific language governing permissions and limitations
// under the License.
#ifndef BDG_PALO_BE_SRC_OLAP_COMPARISON_PREDICATE_H
#define BDG_PALO_BE_SRC_OLAP_COMPARISON_PREDICATE_H
#include <stdint.h>
#include "olap/column_predicate.h"
namespace palo {
class VectorizedRowBatch;
#define COMPARISON_PRED_CLASS_DEFINE(CLASS) \
template <class type> \
class CLASS : public ColumnPredicate { \
public: \
CLASS(int column_id, const type& value); \
virtual ~CLASS() { } \
virtual void evaluate(VectorizedRowBatch* batch) const override; \
private: \
int32_t _column_id; \
type _value; \
}; \
COMPARISON_PRED_CLASS_DEFINE(EqualPredicate)
COMPARISON_PRED_CLASS_DEFINE(NotEqualPredicate)
COMPARISON_PRED_CLASS_DEFINE(LessPredicate)
COMPARISON_PRED_CLASS_DEFINE(LessEqualPredicate)
COMPARISON_PRED_CLASS_DEFINE(GreaterPredicate)
COMPARISON_PRED_CLASS_DEFINE(GreaterEqualPredicate)
} //namespace palo
#endif //BDG_PALO_BE_SRC_OLAP_COMPARISON_PREDICATE_H
| [
"buaa.zhaoc@gmail.com"
] | buaa.zhaoc@gmail.com |
489c44839ad1629dc4cdd449a7ad3a81ee5c8a42 | e8be0ea47b64f636d3645e015f7a58fd1e7df0a8 | /src/algo/move1.cc | 7a68ff15b747d690641f378bdb2479fad4babc83 | [] | no_license | reach2arunprakash/CppSTLStudy | 2653b0bd6fe0acffacedeee8b4ec9df966d43462 | 8f24badd286ba76037f423996321058d11a65455 | refs/heads/master | 2021-01-14T14:27:50.199647 | 2014-12-21T08:20:15 | 2014-12-21T08:20:15 | 63,300,953 | 0 | 1 | null | 2016-07-14T04:01:35 | 2016-07-14T04:01:35 | null | UTF-8 | C++ | false | false | 1,661 | cc | /* The following code example is taken from the book
* "The C++ Standard Library - A Tutorial and Reference, 2nd Edition"
* by Nicolai M. Josuttis, Addison-Wesley, 2012
*
* (C) Copyright Nicolai M. Josuttis 2012.
* Permission to copy, use, modify, sell and distribute this software
* is granted provided this copyright notice appears in all copies.
* This software is provided "as is" without express or implied
* warranty, and with no claim as to its suitability for any purpose.
*/
#include "algostuff.h"
int main() {
std::vector<std::string> coll1 = {"Hello", "this", "is", "an", "exmaple"};
std::list<std::string> coll2;
// copy elements of coll1 into coll2
// - use back inserter to insert instead of overwrite
// - use copy() because the elements in coll1 are used again
std::copy(coll1.cbegin(), coll1.cend(), std::back_inserter(coll2));
// print elements of coll2
// - copy elements to cout using an ostream iterator
// - use move() because these elements in coll2 are not used again
std::move(coll2.cbegin(), coll2.cend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << '\n';
// copy elements of coll1 into coll2 in reverse order
// - now overwrites (coll2.size() still fits)
// - use move() because these elements in coll1 are not used again
std::move(coll1.crbegin(), coll1.crend(), coll2.begin());
// print elements of coll2 again
// - use move() because these elements in coll2 are not used again
std::move(coll2.cbegin(), coll2.cend(),
std::ostream_iterator<std::string>(std::cout, " "));
std::cout << '\n';
}
| [
"cbpark@gmail.com"
] | cbpark@gmail.com |
8133ae1c9431b66b77a06549389dd24d6fc796b4 | fd16da2b2d81255933bb544b4b6b7940bd57c45b | /src/mineserver/network/message/encryptionrequest.h | 99a4eb40d89f9aa8fb93daef0c57427c55fd781e | [] | no_license | leroybird/mineserver2 | 4ced674986c684d9a8fac2c7e7312b2270b3eef4 | 0f0dc20d891d606ccab10cbf3beae53fef3c7f53 | refs/heads/master | 2022-05-13T12:52:38.301920 | 2013-01-29T00:11:35 | 2013-01-29T00:11:35 | 7,418,279 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,001 | h | /*
Copyright (c) 2013, The Mineserver Project
All rights reserved.
Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:
* Redistributions of source code must retain the above copyright
notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
notice, this list of conditions and the following disclaimer in the
documentation and/or other materials provided with the distribution.
* Neither the name of the The Mineserver Project nor the
names of its contributors may be used to endorse or promote products
derived from this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY
DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#ifndef MINESERVER_NETWORK_PACKET_ENCRYPTIONREQUEST_H
#define MINESERVER_NETWORK_PACKET_ENCRYPTIONREQUEST_H
#include <string>
#include <mineserver/byteorder.h>
#include <mineserver/network/message.h>
namespace Mineserver
{
struct Network_Message_EncryptionRequest : public Mineserver::Network_Message
{
std::string serverId;
uint16_t publicKeyLength;
uint8_t* publicKey;
uint16_t verifyTokenLength;
uint8_t* verifyToken;
};
}
#endif
| [
"timaaarrreee@gmail.com"
] | timaaarrreee@gmail.com |
b6c97b109b66f8b665fa875add7327b33ed52fbc | 2048ea675884671407770d6aef449a05f8d34b74 | /cocosim/PlayField.h | f914f782403211e132d0e64434ea5a5915fbbd69 | [
"Apache-2.0"
] | permissive | YichaoLin/YichaoThesisSim | 3d79216bc719115b5ae323623092f2c27fe29295 | cebd16b925fce6bc8e690bbd6d1f0166f42b8b26 | refs/heads/master | 2020-03-29T13:10:25.310330 | 2018-09-23T03:17:48 | 2018-09-23T03:17:48 | 149,944,018 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 72 | h | #pragma once
class PlayField
{
public:
PlayField();
~PlayField();
};
| [
"ylin108@uottawa.ca"
] | ylin108@uottawa.ca |
c5199da33b403908101060837e289f98a454769f | e0c53aaf160928a4b53bee6b136c4cc36b8d57a4 | /WarheadFileReadWrite/warheadfilereadwriteengine.h | 588888496352d365920cdcacbe97c4a522c70091 | [] | no_license | MisYue/DeseaVrsoft | f7b0999f687a2f7299077bcfdfef13b4be0acf94 | 95843597b74f926fa793963e255c6ff6855e4831 | refs/heads/master | 2021-01-19T05:03:32.165534 | 2017-04-06T09:28:26 | 2017-04-06T09:28:26 | 87,411,092 | 0 | 0 | null | null | null | null | GB18030 | C++ | false | false | 1,580 | h | //***************************************
// 创建时间: 2017:3:15 9:20
// 文件名称: warheadfilereadwriteengine.h
// 文件作者: 岳群磊
//
// 功能说明: 战斗部文件读写类定义,写入格式:(whd,pwr,svg,stl),读取格式(whd),参见文件格式说明文档
//***************************************
#ifndef WARHEADFILEREADWRITEENGINE_H
#define WARHEADFILEREADWRITEENGINE_H
#include "warheadfilereadwrite_global.h"
#include <QtCore>
class ReadWriteBase;
class WarheadDataEntity;
class WarheadDrawBase;
struct WARHEADFILEREADWRITE_EXPORT WarheadDataEntityWrap
{
const WarheadDataEntity* warhead; //战斗部
const WarheadDrawBase* painter_2d; //二维绘制对象
const WarheadDrawBase* painter_3d; //三维绘制对象
QStringList pwr_to_out; //需要输出的威力(任务GUID)列表
WarheadDataEntityWrap();
};
typedef WarheadDataEntityWrap WarheadReadWriteWrap;
class WARHEADFILEREADWRITE_EXPORT WarheadFileReadWriteEngine
{
public:
enum Format
{
kWhd, //结构格式
kPwr, //威力格式
kSvg, //Svg结构
kStl, //Stl结构
};
WarheadFileReadWriteEngine();
~WarheadFileReadWriteEngine();
// 写入战斗部
bool Write(const WarheadDataEntityWrap* warhead_wrap, const QString& file_name);
// 读取战斗部
WarheadDataEntity* Read(const QString& file_name);
// 将战斗部写入QString
QString WriteString(const WarheadDataEntityWrap* warhead_wrap, Format format);
// 从QString中读取战斗部
WarheadDataEntity* ReadString(const QString& text, Format format);
};
#endif // WARHEADFILEREADWRITEENGINE_H
| [
"1405590994@qq.com"
] | 1405590994@qq.com |
62fbc02b7f0c96e401302db4ed1ebb82f725ad6c | 0f1e7229b9465f0774c7510aad2910cb9fd609d9 | /src/reir/exec/llvm_environment.hpp | bf309c9880d4938d5a50f812b54db4618b8d153e | [
"Apache-2.0"
] | permissive | large-scale-oltp-team/reir | e5430bebe68dadc925549cd016a6fe1b16c18d72 | 427db5f24e15f22cd2a4f4a716caf9392dae1d9b | refs/heads/master | 2020-04-04T09:26:05.174899 | 2018-11-06T09:16:32 | 2018-11-06T09:16:32 | 155,817,817 | 1 | 0 | Apache-2.0 | 2018-11-06T09:16:33 | 2018-11-02T05:24:07 | C++ | UTF-8 | C++ | false | false | 412 | hpp | #ifndef REIR_LLVM_ENVIRONMENT_HPP_
#define REIR_LLVM_ENVIRONMENT_HPP_
#include <llvm/Support/TargetSelect.h>
namespace reir {
class llvm_environment {
public:
llvm_environment() {
llvm::InitializeNativeTarget();
llvm::InitializeNativeTargetAsmPrinter();
llvm::InitializeNativeTargetAsmParser();
}
};
static llvm_environment env_;
} // namespace reir
#endif // REIR_LLVM_ENVIRONMENT_HPP_
| [
"hiroki.kumazaki@gmail.com"
] | hiroki.kumazaki@gmail.com |
c248f935be63712f1e4ceba6a99ce4824f614d33 | a5dbe4f1ced6b379675a2d7aac622db7644c04c6 | /src/unit_test/switching/internal/sai_fdb_unit_test_internal.cpp | 5b2c8e862f6ee879c8dfece867a2809f12d0bfa4 | [] | no_license | gsherwin3/opx-sai-common | 292f222d9e144e642b9b5674e7151986b29c9fde | 3f6c9818b39f50f2acf187e90bf3a82183e595cd | refs/heads/master | 2021-01-13T12:57:07.523380 | 2017-02-13T14:57:47 | 2017-02-13T14:57:47 | 78,762,289 | 0 | 0 | null | 2017-01-12T16:04:25 | 2017-01-12T16:04:25 | null | UTF-8 | C++ | false | false | 8,806 | cpp | /*
* Copyright (c) 2016 Dell 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
*
* THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR
* CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT
* LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS
* FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT.
*
* See the Apache Version 2.0 License for specific language governing
* permissions and limitations under the License.
*/
/**
* @file sai_fdb_unit_test.cpp
*/
#include <unistd.h>
#include <stdlib.h>
#include <string.h>
#include <stdio.h>
#include "gtest/gtest.h"
#include "inttypes.h"
extern "C" {
#include "sai.h"
#include "saifdb.h"
#include "saitypes.h"
#include "saiswitch.h"
#include "sailag.h"
#include "sai_l2_unit_test_defs.h"
#include "sai_fdb_main.h"
#include "sai_fdb_unit_test.h"
}
#define MAX_FDB_NOTIFICATIONS 50
sai_fdb_notification_data_t notification_data[MAX_FDB_NOTIFICATIONS];
uint_t fdb_num_notifications;
bool notification_wait = true;
static inline void sai_set_test_registered_entry(uint8_t last_octet,sai_fdb_entry_t* fdb_entry)
{
memset(fdb_entry,0, sizeof(sai_fdb_entry_t));
fdb_entry->mac_address[5] = last_octet;
fdb_entry->vlan_id = SAI_GTEST_VLAN;
}
sai_status_t sai_fdb_test_internal_callback(uint_t num_notifications,
sai_fdb_notification_data_t *data)
{
fdb_num_notifications = num_notifications;
printf("Received :%d notifications\r\n",num_notifications);
memcpy(notification_data, data, sizeof(sai_fdb_notification_data_t)*num_notifications);
notification_wait = false;
return SAI_STATUS_SUCCESS;
}
void fdbInit ::sai_fdb_create_registered_entry (sai_fdb_entry_t fdb_entry,
sai_fdb_entry_type_t type,
sai_object_id_t port_id,
sai_packet_action_t action)
{
sai_attribute_t attr_list[SAI_MAX_FDB_ATTRIBUTES];
memset(attr_list,0, sizeof(attr_list));
attr_list[0].id = SAI_FDB_ENTRY_ATTR_TYPE;
attr_list[0].value.s32 = type;
attr_list[1].id = SAI_FDB_ENTRY_ATTR_PORT_ID;
attr_list[1].value.oid = port_id;
attr_list[2].id = SAI_FDB_ENTRY_ATTR_PACKET_ACTION;
attr_list[2].value.s32 = action;
ASSERT_EQ(SAI_STATUS_SUCCESS,
sai_fdb_api_table->create_fdb_entry(
(const sai_fdb_entry_t*)&fdb_entry,
SAI_MAX_FDB_ATTRIBUTES,
(const sai_attribute_t*)attr_list));
}
TEST_F(fdbInit, sai_fdb_single_notification_callback)
{
sai_fdb_entry_t fdb_entry;
sai_set_test_registered_entry(0xa,&fdb_entry);
sai_l2_fdb_register_internal_callback(sai_fdb_test_internal_callback);
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_register_fdb_entry(&fdb_entry));
sai_fdb_create_registered_entry(fdb_entry,SAI_FDB_ENTRY_TYPE_DYNAMIC, port_id_1, SAI_PACKET_ACTION_FORWARD);
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( notification_data[0].port_id, port_id_1);
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_LEARNED);
ASSERT_EQ( 0, memcmp(&fdb_entry,¬ification_data[0].fdb_entry, sizeof(sai_fdb_entry_t)));
ASSERT_EQ( 1, fdb_num_notifications);
fdb_num_notifications = 0;
memset(notification_data, 0, sizeof(notification_data));
ASSERT_EQ(SAI_STATUS_SUCCESS,
sai_fdb_api_table->remove_fdb_entry(
(const sai_fdb_entry_t*)&fdb_entry));
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_FLUSHED);
ASSERT_EQ( 0, memcmp(&fdb_entry,¬ification_data[0].fdb_entry, sizeof(sai_fdb_entry_t)));
ASSERT_EQ( 1, fdb_num_notifications);
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_deregister_fdb_entry(&fdb_entry));
}
TEST_F(fdbInit, sai_fdb_multi_notification_callback)
{
sai_fdb_entry_t fdb_entry1;
sai_fdb_entry_t fdb_entry2;
sai_attribute_t flush_attr[1];
sai_set_test_registered_entry(0xa,&fdb_entry1);
sai_set_test_registered_entry(0xb,&fdb_entry2);
sai_l2_fdb_register_internal_callback(sai_fdb_test_internal_callback);
sai_fdb_create_registered_entry(fdb_entry1, SAI_FDB_ENTRY_TYPE_DYNAMIC, port_id_1, SAI_PACKET_ACTION_FORWARD);
sai_fdb_create_registered_entry(fdb_entry2, SAI_FDB_ENTRY_TYPE_DYNAMIC, port_id_2, SAI_PACKET_ACTION_FORWARD);
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_register_fdb_entry(&fdb_entry1));
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_register_fdb_entry(&fdb_entry2));
flush_attr[0].id = SAI_FDB_FLUSH_ATTR_VLAN_ID;
flush_attr[0].value.u16 = SAI_GTEST_VLAN;
ASSERT_EQ(SAI_STATUS_SUCCESS,
sai_fdb_api_table->flush_fdb_entries(1,
(const sai_attribute_t*)flush_attr));
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( 2, fdb_num_notifications);
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_FLUSHED);
ASSERT_EQ( notification_data[1].fdb_event, SAI_FDB_EVENT_FLUSHED);
fdb_num_notifications = 0;
memset(notification_data, 0, sizeof(notification_data));
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_deregister_fdb_entry(&fdb_entry1));
sai_fdb_create_registered_entry(fdb_entry1, SAI_FDB_ENTRY_TYPE_DYNAMIC, port_id_1, SAI_PACKET_ACTION_FORWARD);
sai_fdb_create_registered_entry(fdb_entry2, SAI_FDB_ENTRY_TYPE_DYNAMIC, port_id_2, SAI_PACKET_ACTION_FORWARD);
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( notification_data[0].port_id, port_id_2);
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_LEARNED);
ASSERT_EQ( 0, memcmp(&fdb_entry2,¬ification_data[0].fdb_entry, sizeof(sai_fdb_entry_t)));
ASSERT_EQ( 1, fdb_num_notifications);
fdb_num_notifications = 0;
memset(notification_data, 0, sizeof(notification_data));
flush_attr[0].id = SAI_FDB_FLUSH_ATTR_VLAN_ID;
flush_attr[0].value.u16 = SAI_GTEST_VLAN;
ASSERT_EQ(SAI_STATUS_SUCCESS,
sai_fdb_api_table->flush_fdb_entries(1,
(const sai_attribute_t*)flush_attr));
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( 1, fdb_num_notifications);
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_FLUSHED);
ASSERT_EQ( 0, memcmp(&fdb_entry2,¬ification_data[0].fdb_entry, sizeof(sai_fdb_entry_t)));
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_deregister_fdb_entry(&fdb_entry2));
}
TEST_F(fdbInit, sai_fdb_port_change_notification_callback)
{
sai_fdb_entry_t fdb_entry;
sai_attribute_t set_attr;
sai_set_test_registered_entry(0xa,&fdb_entry);
sai_fdb_create_registered_entry(fdb_entry,SAI_FDB_ENTRY_TYPE_DYNAMIC, port_id_1, SAI_PACKET_ACTION_FORWARD);
sai_l2_fdb_register_internal_callback(sai_fdb_test_internal_callback);
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_register_fdb_entry(&fdb_entry));
set_attr.id = SAI_FDB_ENTRY_ATTR_PORT_ID;
set_attr.value.oid = port_id_2;
EXPECT_EQ(SAI_STATUS_SUCCESS,
sai_fdb_api_table->set_fdb_entry_attribute(
(const sai_fdb_entry_t*)&fdb_entry,
(const sai_attribute_t*)&set_attr));
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( notification_data[0].port_id, port_id_2);
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_LEARNED);
ASSERT_EQ( 0, memcmp(&fdb_entry,¬ification_data[0].fdb_entry, sizeof(sai_fdb_entry_t)));
ASSERT_EQ( 1, fdb_num_notifications);
fdb_num_notifications = 0;
memset(notification_data, 0, sizeof(notification_data));
ASSERT_EQ(SAI_STATUS_SUCCESS,
sai_fdb_api_table->remove_fdb_entry(
(const sai_fdb_entry_t*)&fdb_entry));
while(notification_wait) {
usleep(1);
}
notification_wait = true;
ASSERT_EQ( notification_data[0].fdb_event, SAI_FDB_EVENT_FLUSHED);
ASSERT_EQ( 0, memcmp(&fdb_entry,¬ification_data[0].fdb_entry, sizeof(sai_fdb_entry_t)));
ASSERT_EQ( 1, fdb_num_notifications);
ASSERT_EQ (SAI_STATUS_SUCCESS,
sai_l2_deregister_fdb_entry(&fdb_entry));
}
| [
"J.T.Conklin@Dell.Com"
] | J.T.Conklin@Dell.Com |
61a1631a151e95f79a58c2e6b7c48be93ee02e19 | 334558bf31b6a8fd3caaf09c24898ff331c7e2da | /GenieWindow/plugins/GeniePlugin_NetworkProblem/src/QProgressIndicator.cpp | 36aa6848e778a91578a287f3738d0e87b231e375 | [] | no_license | roygaogit/Bigit_Genie | e38bac558e81d9966ec6efbdeef0a7e2592156a7 | 936a56154a5f933b1e9c049ee044d76ff1d6d4db | refs/heads/master | 2020-03-31T04:20:04.177461 | 2013-12-09T03:38:15 | 2013-12-09T03:38:15 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 2,553 | cpp | #include "QProgressIndicator.h"
#include <QPainter>
QProgressIndicator::QProgressIndicator(QWidget* parent)
: QWidget(parent),
m_angle(0),
m_timerId(-1),
m_delay(40),
m_displayedWhenStopped(false),
m_color(Qt::black),
mSizePara(0.7)
{
setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Fixed);
setFocusPolicy(Qt::NoFocus);
}
bool QProgressIndicator::isAnimated () const
{
return (m_timerId != -1);
}
void QProgressIndicator::setDisplayedWhenStopped(bool state)
{
m_displayedWhenStopped = state;
update();
}
bool QProgressIndicator::isDisplayedWhenStopped() const
{
return m_displayedWhenStopped;
}
void QProgressIndicator::startAnimation()
{
m_angle = 0;
if (m_timerId == -1)
m_timerId = startTimer(m_delay);
}
void QProgressIndicator::stopAnimation()
{
if (m_timerId != -1)
killTimer(m_timerId);
m_timerId = -1;
update();
}
void QProgressIndicator::setAnimationDelay(int delay)
{
if (m_timerId != -1)
killTimer(m_timerId);
m_delay = delay;
if (m_timerId != -1)
m_timerId = startTimer(m_delay);
}
void QProgressIndicator::setColor(const QColor & color)
{
m_color = color;
update();
}
QSize QProgressIndicator::sizeHint() const
{
return QSize(50,50);
}
int QProgressIndicator::heightForWidth(int w) const
{
return w;
}
void QProgressIndicator::timerEvent(QTimerEvent * /*event*/)
{
m_angle = (m_angle+30)%360;
update();
}
void QProgressIndicator::setSizePara(qreal c)
{
mSizePara=c;
}
void QProgressIndicator::paintEvent(QPaintEvent * /*event*/)
{
if (!m_displayedWhenStopped && !isAnimated())
return;
qreal width = qMin(this->width()/2, this->height()/2);
QPainter p(this);
p.setRenderHint(QPainter::Antialiasing);
qreal outerRadius = (width-1)*mSizePara;
qreal innerRadius = (width-1)*mSizePara*0.38;
qreal capsuleHeight = outerRadius - innerRadius;
qreal capsuleWidth = (width > 32 ) ? capsuleHeight *.23 : capsuleHeight *.35;
qreal capsuleRadius = capsuleWidth/2;
for (int i=0; i<12; i++)
{
QColor color = m_color;
color.setAlphaF(1.0f - (i/12.0f));
p.setPen(Qt::NoPen);
p.setBrush(color);
p.save();
p.translate(rect().center());
p.rotate(m_angle - i*30.0f);
p.drawRoundedRect(-capsuleWidth*0.5, -(innerRadius+capsuleHeight), capsuleWidth, capsuleHeight, capsuleRadius, capsuleRadius);
p.restore();
}
}
| [
"raylq@qq.com"
] | raylq@qq.com |
a6aa10e71983bc82f8f2d9f851cce74333c03d2a | 2a2ac488626c02c95b2a7b399fea84dda3bfabb2 | /academiaUfba/addpro.cpp | b0ff61177920cb7a3ca6117a4b15db45add25cd5 | [] | no_license | oscaresende/MATA76 | 1bc48dbb7dc0708d939c5f2479e51bbda693a52b | 3411f3f8d1be09f09f476f76330d99b7b743d71b | refs/heads/master | 2020-03-30T02:57:18.720085 | 2018-12-20T20:57:39 | 2018-12-20T20:57:39 | 150,660,150 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,066 | cpp | #include "addpro.h"
#include "ui_addpro.h"
#include "dbmanager.h"
#include "professor.h"
#include "QMessageBox"
#include "QFileDialog"
addpro::addpro(QWidget *parent, Professor *professor, const QString& operacao) :
QWidget(parent),
ui(new Ui::addpro)
{
ui->setupUi(this);
ui->setupUi(this);
db = new DbManager("fitnessUfba");
op = operacao;
connect(ui->pushButton_2, SIGNAL(clicked()),this, SLOT(cadastrar()));
connect(ui->pushButton, SIGNAL(clicked()),this, SLOT(cancelar()));
connect(ui->toolButton, SIGNAL(clicked()),this, SLOT(escolher_arquivo()));
if (professor != NULL)
{
ui->lineEdit_7->setText(professor->matricula);
ui->lineEdit_8->setText(professor->senha);
ui->lineEdit->setText(professor->nome);
ui->lineEdit_2->setText(professor->endereco);
ui->lineEdit_3->setText(professor->telefone);
ui->lineEdit_5->setText(professor->email);
ui->lineEdit_6->setText(professor->cpf);
ui->dateEdit->setDateTime(professor->data_nascimento);
if (op != "ATUALIZAR")
{
ui->pushButton_2->setEnabled(false);
}
else
{
ui->lineEdit_7->setEnabled(false);
ui->pushButton_2->setText("Atualizar");
}
imageFile.load(professor->imagem);
ui->image_label->setPixmap(QPixmap::fromImage(imageFile).scaled(ui->image_label->width(),
ui->image_label->height(),
Qt::KeepAspectRatioByExpanding));
}
}
addpro::~addpro()
{
delete ui;
}
void addpro::cadastrar()
{
bool erro;
erro = false;
QMessageBox mensagem;
mensagem.setWindowTitle("Alerta");
if ((ui->lineEdit_7->text() == "") ||(ui->lineEdit->text() == ""))
{
mensagem.setText("Dados Incompletos!");
mensagem.exec();
erro = true;
}
if (!erro)
{
Professor Pesquisa = db->busca_professor(ui->lineEdit_7->text());
if((Pesquisa.matricula!="") && (op == "INCLUIR")){
mensagem.setText("Matricula existente!");
mensagem.exec();
}
else
{
Professor *novo = new Professor(ui->lineEdit_7->text(),ui->lineEdit_8->text(),ui->lineEdit->text(),ui->lineEdit_2->text(), ui->lineEdit_5->text(),
ui->dateEdit->dateTime(), ui->lineEdit_6->text(), ui->lineEdit_3->text(), this->imagePath);
if (op == "INCLUIR")
{
if(db->addProfessor(*novo))
{
mensagem.setText("Profesor cadastrado com sucesso!");
mensagem.exec();
this->close();
}
else
{
mensagem.setText("Inclusão não realizada.");
mensagem.exec();
}
}
else
{
if(db->atualizarProfessor(*novo))
{
mensagem.setText("Profesor atualizado com sucesso!");
mensagem.exec();
this->close();
}
else
{
mensagem.setText("Atualização não realizada.");
mensagem.exec();
}
}
}
}
}
void addpro::escolher_arquivo()
{
this->imagePath = QFileDialog::getOpenFileName(this, "Open", "/home",
"*.png *.jpg *.jpeg");
if (this->imagePath!= "") imageFile.load(this->imagePath);
ui->image_label->setPixmap(QPixmap::fromImage(imageFile).scaled(ui->image_label->width(),
ui->image_label->height(),
Qt::KeepAspectRatioByExpanding));
}
void addpro::cancelar()
{
this->close();
}
| [
"luis.oscar@syslg.com"
] | luis.oscar@syslg.com |
f28341e1c62672dae9af2fa1336e9746e6c8dd1a | 7be7f32b00df53c10e8f90c6686577a556f5d91d | /Classes/Config/IAPConfig.cpp | df13f8c9903e61ed4296f11027001595f93d0ae2 | [] | no_license | hanxu1210/Aircraft | c598f5008b45195ba3efffc84c807e3aa3ae5681 | 2a0a3e9828ed5730741f46d55ca518968a560dee | refs/heads/master | 2020-03-28T12:02:17.739584 | 2018-09-11T05:34:01 | 2018-09-11T05:34:01 | 148,258,528 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 136 | cpp | #include "IAPConfig.h"
namespace NsAircraft
{
const char* IAPConfig::PayCallbackUrl = "http://infinitychanllenge.nat123.net/Pay";
} | [
"11521142@qq.com"
] | 11521142@qq.com |
561a6d471830e93ab740756366b97f211fa29000 | 838e7a6c843119327e867a1927fc625ff0594ed7 | /apps/3TPlayer/src/sam/3tplayer/shared/Connections.h | 3b46b718ac65ee84728cdc21eb486a1ae655e8d7 | [] | no_license | albarral/sam | 4723c9651047f575e01ef2435302e4a5113a70c7 | 6a2fba2ba4ed98a1ef7da26b56ac6d12efcfa0ce | refs/heads/master | 2020-05-18T07:32:11.981113 | 2016-01-15T21:52:09 | 2016-01-15T21:52:09 | 32,345,569 | 1 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,186 | h | #ifndef __T3PLAYER_CONNECTIONS_H
#define __T3PLAYER_CONNECTIONS_H
/***************************************************************************
* Copyright (C) 2015 by Migtron Robotics *
* albarral@migtron.com *
***************************************************************************/
#include "goon/utils/brooks/control.h"
#include "goon/utils/brooks/controlT.h"
#include "goon/utils/brooks/sensor.h"
#include "sam/3tplayer/data/structs.h"
namespace sam
{
namespace t3player
{
class Connections
{
private:
// Field module
goon::Control coAck;
goon::Sensor soBoardChanged;
// Move module
goon::ControlT<Cell>coPickCell;
goon::Sensor soMoveDone;
public:
Connections();
//~Connections();
// controls
goon::Control& getCOAckBoardChanged() {return coAck;};
goon::ControlT<Cell>& getCOPickCell() {return coPickCell;};
// sensors
goon::Sensor& getSOBoardChanged() {return soBoardChanged;};
goon::Sensor& getSOMoveDone() {return soMoveDone;};
};
}
}
#endif
| [
"albarral@migtron.com"
] | albarral@migtron.com |
fee6c6ba199f764aa84df4dd7c3fdbf49e5f1d00 | 3c3023002f8442f5ff7c1aeb8837b9ef1b4106b0 | /1S/03/1/1.cpp | 717ea043f784f7ac35a2c39686f6c8055baef001 | [] | no_license | kivi239/Homeworks | 410b892b8af3e2be656474988628356463ce4726 | 886a4d77ac5aa774e481f7e6f58f6b7d7f186d96 | refs/heads/master | 2021-01-22T13:41:44.076563 | 2015-05-28T15:08:21 | 2015-05-28T15:08:21 | 15,022,533 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 1,028 | cpp | #include <cstdio>
#include <cstring>
const int alph = 26;
int main()
{
int cnt1[alph];
int cnt2[alph];
for (int i = 0; i < alph; i++)
{
cnt1[i] = 0;
cnt2[i] = 0;
}
printf("Please, enter an integer number n\n");
int n;
scanf("%d", &n);
printf("Please, enter two strings of size n\n");
char *str1 = new char[n];
scanf("%s", str1);
char *str2 = new char[n];
scanf("%s", str2);
for (int i = 0; i < n; i++)
{
cnt1[str1[i] - 'a']++;
cnt2[str2[i] - 'a']++;
}
delete[] str1;
delete[] str2;
bool isequal = true;
for (int i = 0; i < alph; i++)
if (cnt1[i] != cnt2[i])
isequal = false;
if (isequal)
printf("It is possible to transpose symbols in the second string and get the first string\n");
else
printf("It is impossible to transpose symbols in the second string and get the first string\n");
return 0;
} | [
"kivi239@gmail.com"
] | kivi239@gmail.com |
cae7b0392fcaaa76f27ab9ac37fdf038501a9f70 | b65d3857428281466507674f8ca4f376490c81a2 | /src/TowTruckDescriptor.hpp | 60049e5afac8051bd22d49b6e2ac2b950cae9c41 | [] | no_license | DCurro/gtmiami | 24f59311f1769c1b0f33cdee5c02a777f79a53a3 | 02727faa870e61ad9496e5b944ff3d945383e62b | refs/heads/master | 2021-09-24T16:31:07.733654 | 2018-10-12T00:45:29 | 2018-10-12T00:45:29 | 107,069,651 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 436 | hpp | #ifndef TowTruckDescriptor_HPP_
#define TowTruckDescriptor_HPP_
#include "PooledPlayEntityDescriptor.hpp"
#include "Common.hpp"
class TowTruckDescriptor : public PooledPlayEntityDescriptor {
public:
TowTruckDescriptor(int uniqueReferenceId, int floor, float x, float y, float angle);
virtual ~TowTruckDescriptor();
virtual rapidjson::Value* descriptorJsonObjectValue(rapidjson::Document* jsonDoc) override;
};
#endif | [
"domenic.curro@gmail.com"
] | domenic.curro@gmail.com |
8a0f511c6e5f7e9e3ae620ae4764071a53032425 | 29e6b54f59201d6f32d8cc2ff00d930e8b2038cc | /src/choco_2/choco/orm/config.cpp | 46333f3c1ed8c75afea5ddf9e14a3219d6f9ac3f | [] | no_license | pjc0247/choco_for_nnext | 8bb2124a1e411f6156ca531adcf3889a50ce89c8 | 850560f6dff3a8e849f4e5a79e4e916474c23618 | refs/heads/master | 2016-09-02T06:01:27.454036 | 2014-12-02T16:06:06 | 2014-12-02T16:06:06 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 772 | cpp | #include "orm.h"
#include "choco/log/log.h"
using namespace std;
namespace choco{
namespace orm{
map<string,string> configs;
void configure(
const string &key, const string &value){
configs[key] = value;
}
void configure_with_no_override(
const string &key, const string &value){
auto pair = configs.find( key );
if( pair == configs.end() )
configs[key] = value;
}
string &get_config(
const string &key){
return configs[key];
}
error initialize_config(){
configure_with_no_override("host", "127.0.0.1");
configure_with_no_override("port", "3306");
configure_with_no_override("pool_size", "10");
configure_with_no_override("log_query", "false");
log::system(
"orm::config - initialized\n");
return errorno::none;
}
};};
| [
"pjc0247@naver.com"
] | pjc0247@naver.com |
fcf6ed9fb74ef9e804565276c0c2faeafac65ce1 | 527739ed800e3234136b3284838c81334b751b44 | /include/RED4ext/Types/generated/game/data/UpgradingData_Record.hpp | 1ff65960b6d405cc9e403597deefce5568a6ba4c | [
"MIT"
] | permissive | 0xSombra/RED4ext.SDK | 79ed912e5b628ef28efbf92d5bb257b195bfc821 | 218b411991ed0b7cb7acd5efdddd784f31c66f20 | refs/heads/master | 2023-07-02T11:03:45.732337 | 2021-04-15T16:38:19 | 2021-04-15T16:38:19 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 659 | hpp | #pragma once
// This file is generated from the Game's Reflection data
#include <cstdint>
#include <RED4ext/Common.hpp>
#include <RED4ext/REDhash.hpp>
#include <RED4ext/Types/generated/game/data/TweakDBRecord.hpp>
namespace RED4ext
{
namespace game::data {
struct UpgradingData_Record : game::data::TweakDBRecord
{
static constexpr const char* NAME = "gamedataUpgradingData_Record";
static constexpr const char* ALIAS = "UpgradingData_Record";
uint8_t unk48[0x50 - 0x48]; // 48
};
RED4EXT_ASSERT_SIZE(UpgradingData_Record, 0x50);
} // namespace game::data
using UpgradingData_Record = game::data::UpgradingData_Record;
} // namespace RED4ext
| [
"expired6978@gmail.com"
] | expired6978@gmail.com |
705294317696837dd5614b14edbc6a86cf80eef4 | f99d8bd52ceae5270275f7030eb2950d7c17a02c | /caesar/perceptron/mlp.hpp | f5508ec3802065788d5bc09b0923cf20a2da5ab9 | [] | no_license | jancsosz/prog1 | 9a3cf46b6459184ab55f15d8c3d469b920f5ea0d | cf32ac5214c60357e7897739ebc70b61c2aa873a | refs/heads/master | 2021-01-15T04:58:26.329465 | 2020-05-05T01:41:14 | 2020-05-05T01:41:14 | 242,884,981 | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 5,011 | hpp | //#ifndef QL_HPP
//#define QL_HPP
#include <iostream>
#include <cstdarg>
#include <map>
#include <iterator>
#include <cmath>
#include <random>
#include <limits>
#include <fstream>
class Perceptron
{
public:
Perceptron ( int nof, ... )
{
n_layers = nof;
units = new double*[n_layers];
n_units = new int[n_layers];
va_list vap;
va_start ( vap, nof );
for ( int i {0}; i < n_layers; ++i )
{
n_units[i] = va_arg ( vap, int );
if ( i )
units[i] = new double [n_units[i]];
}
va_end ( vap );
weights = new double**[n_layers-1];
#ifndef RND_DEBUG
std::random_device init;
std::default_random_engine gen {init() };
#else
std::default_random_engine gen;
#endif
std::uniform_real_distribution<double> dist ( -1.0, 1.0 );
for ( int i {1}; i < n_layers; ++i )
{
weights[i-1] = new double *[n_units[i]];
for ( int j {0}; j < n_units[i]; ++j )
{
weights[i-1][j] = new double [n_units[i-1]];
for ( int k {0}; k < n_units[i-1]; ++k )
{
weights[i-1][j][k] = dist ( gen );
}
}
}
}
Perceptron ( std::fstream & file )
{
file >> n_layers;
units = new double*[n_layers];
n_units = new int[n_layers];
for ( int i {0}; i < n_layers; ++i )
{
file >> n_units[i];
if ( i )
units[i] = new double [n_units[i]];
}
weights = new double**[n_layers-1];
for ( int i {1}; i < n_layers; ++i )
{
weights[i-1] = new double *[n_units[i]];
for ( int j {0}; j < n_units[i]; ++j )
{
weights[i-1][j] = new double [n_units[i-1]];
for ( int k {0}; k < n_units[i-1]; ++k )
{
file >> weights[i-1][j][k];
}
}
}
}
double sigmoid ( double x )
{
return 1.0/ ( 1.0 + exp ( -x ) );
}
double operator() ( double image [] )
{
units[0] = image;
for ( int i {1}; i < n_layers; ++i )
{
#ifdef CUDA_PRCPS
cuda_layer ( i, n_units, units, weights );
#else
#pragma omp parallel for
for ( int j = 0; j < n_units[i]; ++j )
{
units[i][j] = 0.0;
for ( int k = 0; k < n_units[i-1]; ++k )
{
units[i][j] += weights[i-1][j][k] * units[i-1][k];
}
units[i][j] = sigmoid ( units[i][j] );
}
#endif
}
return sigmoid ( units[n_layers - 1][0] );
}
void learning ( double image [], double q, double prev_q )
{
double y[1] {q};
learning ( image, y );
}
void learning ( double image [], double y[] )
{
//( *this ) ( image );
units[0] = image;
double ** backs = new double*[n_layers-1];
for ( int i {0}; i < n_layers-1; ++i )
{
backs[i] = new double [n_units[i+1]];
}
int i {n_layers-1};
for ( int j {0}; j < n_units[i]; ++j )
{
backs[i-1][j] = sigmoid ( units[i][j] ) * ( 1.0-sigmoid ( units[i][j] ) ) * ( y[j] - units[i][j] );
for ( int k {0}; k < n_units[i-1]; ++k )
{
weights[i-1][j][k] += ( 0.2* backs[i-1][j] *units[i-1][k] );
}
}
for ( int i {n_layers-2}; i >0 ; --i )
{
#pragma omp parallel for
for ( int j =0; j < n_units[i]; ++j )
{
double sum = 0.0;
for ( int l = 0; l < n_units[i+1]; ++l )
{
sum += 0.19*weights[i][l][j]*backs[i][l];
}
backs[i-1][j] = sigmoid ( units[i][j] ) * ( 1.0-sigmoid ( units[i][j] ) ) * sum;
for ( int k = 0; k < n_units[i-1]; ++k )
{
weights[i-1][j][k] += ( 0.19* backs[i-1][j] *units[i-1][k] );
}
}
}
for ( int i {0}; i < n_layers-1; ++i )
{
delete [] backs[i];
}
delete [] backs;
}
~Perceptron()
{
for ( int i {1}; i < n_layers; ++i )
{
for ( int j {0}; j < n_units[i]; ++j )
{
delete [] weights[i-1][j];
}
delete [] weights[i-1];
}
delete [] weights;
for ( int i {0}; i < n_layers; ++i )
{
if ( i )
delete [] units[i];
}
delete [] units;
delete [] n_units;
}
void save ( std::fstream & out )
{
out << " "
<< n_layers;
for ( int i {0}; i < n_layers; ++i )
out << " " << n_units[i];
for ( int i {1}; i < n_layers; ++i )
{
for ( int j {0}; j < n_units[i]; ++j )
{
for ( int k {0}; k < n_units[i-1]; ++k )
{
out << " "
<< weights[i-1][j][k];
}
}
}
}
private:
Perceptron ( const Perceptron & );
Perceptron & operator= ( const Perceptron & );
int n_layers;
int* n_units;
double **units;
double ***weights;
};
| [
"noreply@github.com"
] | noreply@github.com |
74bf794b96961e446f0441894ae968d4d70d980e | 740af44094400a92ce2c7fb14d9def6771eacbfe | /src/libaten/math/vec2.h | 62e842c41d1ecf851b8dfb922ae8ca6b15235cd3 | [
"MIT"
] | permissive | nackdai/aten | 86f2de6b6e5d7931388bd7cbb466ae18f981de7a | a3c8c818be8d72a2267ed4c933ac60b4eb1c4ef4 | refs/heads/main | 2023-09-01T11:02:40.201933 | 2023-08-29T17:23:32 | 2023-08-30T10:02:59 | 81,186,981 | 57 | 4 | MIT | 2023-08-30T10:03:01 | 2017-02-07T08:51:24 | C++ | UTF-8 | C++ | false | false | 1,075 | h | #pragma once
#include "defs.h"
#include "math/math.h"
namespace aten {
struct vec2 {
real x;
real y;
AT_DEVICE_API vec2()
{
x = y = 0;
}
AT_DEVICE_API vec2(const vec2& _v)
{
x = _v.x;
y = _v.y;
}
AT_DEVICE_API vec2(real f)
{
x = y = f;
}
AT_DEVICE_API vec2(real _x, real _y)
{
x = _x;
y = _y;
}
};
inline AT_DEVICE_API vec2 operator+(const vec2& v1, const vec2& v2)
{
vec2 ret(v1.x + v2.x, v1.y + v2.y);
return ret;
}
inline AT_DEVICE_API vec2 operator-(const vec2& v1, const vec2& v2)
{
vec2 ret(v1.x - v2.x, v1.y - v2.y);
return ret;
}
inline AT_DEVICE_API vec2 operator*(const vec2& v, float f)
{
vec2 ret(v.x * f, v.y * f);
return ret;
}
inline AT_DEVICE_API vec2 operator/(const vec2& v1, const vec2& v2)
{
vec2 ret(v1.x / v2.x, v1.y / v2.y);
return ret;
}
}
| [
"newvf91.brjtn579.dn@gmail.com"
] | newvf91.brjtn579.dn@gmail.com |
497965cc124e5cd0db0696fd299fe1dfdc822332 | 9f0b56516a38d56f011bc6e44ee828279b25e49a | /X39_XLib_Modules/X39_XLib_Zeus_disableAi.cpp | 698f7b2ece3c97387f11b9941cab0d2224740caa | [] | no_license | X39/XLib | a8bd71fb903c7d4e3659738f931ab789ba46b7ef | c910e8733a046ef34ccacc11e22d095d8a7d98cf | refs/heads/master | 2016-09-06T05:26:12.959666 | 2015-09-16T14:59:18 | 2015-09-16T14:59:18 | 21,134,900 | 1 | 2 | null | 2015-03-23T21:54:49 | 2014-06-23T17:11:50 | C++ | UTF-8 | C++ | false | false | 694 | cpp | class X39_XLib_Zeus_disableAi: Module_F
{
author = "X39|Cpt. HM Murdock";
scope = 2; // Editor visibility; 2 will show it in the menu, 1 will hide it.
scopeCurator = 2;
displayName = "Resupply"; // Name displayed in the menu
icon = "\X39_XLib_Modules\Res\X39_XLib_Resupply"; // Map icon. Delete this entry to use the default icon
category = "X39_XLib";
side = 7;
curatorCost = 5;
function = "X39_XLib_Modules_fnc_X39_XLib_Zeus_disableAi";
functionPriority = 1;
isGlobal = 1;
isPersistent = 1;
isTriggerActivated = 1;
isDisposable = 1;
class Arguments
{
};
class ModuleDescription: ModuleDescription
{
description = "Creates a resupply position at the given spot";
};
}; | [
"m.silipo@web.de"
] | m.silipo@web.de |
5423d4b20a0c9503ad087edf3eeffdcef00a19a4 | 636f74f90c7152d80d682f253653af2aee6208b1 | /wear/src/main/cpp/pipe.cpp | c9bc86f5dc7e4568793bb30f32312864a7d9cb21 | [] | no_license | XiaoShawnZhu/MPWear | 70e31317bea23f76d434285f18d803024bea7b7b | 73538bcb40ac86c90b6bbfb4494b0ba766b6f27d | refs/heads/master | 2020-04-15T15:24:57.833405 | 2019-01-11T17:32:27 | 2019-01-11T17:32:27 | 164,792,589 | 2 | 1 | null | null | null | null | UTF-8 | C++ | false | false | 2,053 | cpp |
#include "pipe.h"
#include "proxy.h"
#include "proxy_setting.h"
#include "tools.h"
#include "connections.h"
#include "kernel_info.h"
extern struct PIPE pipes;
// set up pipe listener in c++
int PIPE::Setup(){
this->n = 1;
localListenFD = socket(AF_INET, SOCK_STREAM, 0);
struct sockaddr_in serverAddr;
memset(&serverAddr, 0, sizeof(sockaddr_in));
serverAddr.sin_family = AF_INET;
serverAddr.sin_port = htons(PIPE_LISTEN_PORT);
serverAddr.sin_addr.s_addr = htonl(INADDR_LOOPBACK);
int optval = 1;
int r = setsockopt(localListenFD, SOL_SOCKET, SO_REUSEADDR, &optval, sizeof(optval));
MyAssert(r == 0, 1762);
if (bind(localListenFD, (struct sockaddr *)&serverAddr, sizeof(serverAddr)) != 0) return R_FAIL;
if (listen(localListenFD, 32) != 0) return R_FAIL;
Accept();
return R_SUCC;
}
void * AcceptThread(void * arg) {
struct sockaddr_in clientAddr;
socklen_t clientAddrLen = sizeof(clientAddr);
pipes.fd[0] = accept(pipes.localListenFD, (struct sockaddr *)&clientAddr, &clientAddrLen);
if (pipes.fd[0] == -1) return R_FAIL;
pipes.SetCongestionControl(pipes.fd[0], PROXY_SETTINGS::pipeProtocol[0].c_str());
SetSocketNoDelay_TCP(pipes.fd[0]);
SetNonBlockIO(pipes.fd[0]);
int localPort = (int)ntohs(clientAddr.sin_port);
LOGD("Pipe connection established. IP=%s, port=%d, TCP=%s, fd=%d",
inet_ntoa(clientAddr.sin_addr), localPort,
PROXY_SETTINGS::pipeProtocol[0].c_str(), pipes.fd[0]
);
return NULL;
}
void PIPE::Accept(){
// bStarted = 0;
pthread_t accept_thread;
int r = pthread_create(&accept_thread, NULL, AcceptThread, this);
MyAssert(r == 0, 2459);
// while (bStarted != 2) {pthread_yield();}
LOGD("Accept threads started.");
}
void PIPE::SetCongestionControl(int fd, const char * tcpVar) {
if (!strcmp(tcpVar, "default") || !strcmp(tcpVar, "DEFAULT")) return;
int r = setsockopt(fd, IPPROTO_TCP, TCP_CONGESTION, tcpVar, (int)strlen(tcpVar));
MyAssert(r == 0, 1815);
} | [
"shawnzhu@umich.edu"
] | shawnzhu@umich.edu |
6f44ded68e0bc223c864109ec626dcbea72c702b | 4433c23517a0b16fd17ae192e8cd8f46058814f6 | /CodeForces/kbl_didi_ridi/83/A[ Magical Array ].cpp | 62cc9bc214dc42bb020b032f425cb2c3a27dc96e | [] | no_license | navidkpr/Competitive-Programming | 103ca6c40a41658b053be86bd7a27a73e3d64d24 | e47400cf59dea3b224fe7f1007aded347e9320d1 | refs/heads/master | 2023-08-27T22:19:40.019391 | 2019-02-16T21:14:36 | 2019-02-16T21:14:36 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 521 | cpp | #include <iostream>
#define int long long
using namespace std;
const int MAXN = 100*1000 + 1000;
int arr[MAXN];
int32_t main()
{
int n;
cin >> n;
for (int i = 0; i < n; i++)
cin >> arr[i];
int cnt_ans = 1;
int sum = n;
for (int i = 1; i < n; i++)
{
if (arr[i] == arr[i - 1])
cnt_ans++;
else
{
sum += cnt_ans * (cnt_ans - 1) / 2;
cnt_ans = 1;
}
}
// cerr << sum << endl;
// cerr << cnt_ans << endl;
if (cnt_ans > 1)
sum += cnt_ans * (cnt_ans - 1) / 2;
cout << sum << endl;
return 0;
}
| [
"navidkouchakipour@yahoo.com"
] | navidkouchakipour@yahoo.com |
6a34451758c82feaa2bbba792b8e7961f9a3f794 | 2cc369568a15276af548e2fb9de956ae2a176a66 | /P0019/atomic_ref_test.cpp | 09b1dd7222fa3518da6dbaa70ce44be9de420123 | [] | no_license | mbianco/cpp-proposals-pub | 9cfa5049e48f1e300900f940b2e8ab27100b9c80 | 191885b2732f45eca07a59ca702174c365b73bc3 | refs/heads/master | 2020-03-16T02:24:42.695088 | 2018-05-06T19:55:50 | 2018-05-06T19:55:50 | null | 0 | 0 | null | null | null | null | UTF-8 | C++ | false | false | 4,468 | cpp | #include <cstdio>
#include <complex>
#include <array>
#include "atomic_ref.hpp"
// may need to link with -latomic
namespace {
template <class T>
int test_generic(T v1, T v2)
{
using atomic_ref = std::atomic_ref<T>;
int errors = 0;
T val;
atomic_ref ref{val};
ref = v1;
if ( v1 != static_cast<T>(ref) ) {
++errors;
}
ref.store( v2 );
if ( v2 != ref.load() ) {
++errors;
}
ref.store( v1, std::memory_order_relaxed );
if ( v1 != ref.load( std::memory_order_relaxed ) ) {
++errors;
}
if( v1 != ref.exchange(v2) ) {
++errors;
}
if( v2 != ref.exchange(v1, std::memory_order_acq_rel) ) {
++errors;
}
T expected = v2;
if( ref.compare_exchange_weak(expected, v1) ) {
++errors;
}
if( !ref.compare_exchange_strong(expected, v1) ) {
++errors;
}
expected = v2;
if( ref.compare_exchange_weak(expected, v1, std::memory_order_acq_rel, std::memory_order_relaxed) ) {
++errors;
}
if( !ref.compare_exchange_strong(expected, v1, std::memory_order_acq_rel, std::memory_order_relaxed) ) {
++errors;
}
return errors;
}
template <class T>
int test_integral(T a, T b)
{
int errors = 0;
using atomic_ref = std::atomic_ref<T>;
atomic_ref ref(a);
ref += b;
ref -= b;
ref |= b;
ref &= b;
ref ^= b;
ref.fetch_add(b, std::memory_order_relaxed );
ref.fetch_sub(b, std::memory_order_relaxed );
ref.fetch_and(b, std::memory_order_relaxed );
ref.fetch_or(b, std::memory_order_relaxed );
ref.fetch_xor(b, std::memory_order_relaxed );
return errors;
}
template <class T>
int test_float(T a, T b)
{
int errors = 0;
using atomic_ref = std::atomic_ref<T>;
atomic_ref ref(a);
ref += b;
ref -= b;
ref.fetch_add(b, std::memory_order_relaxed );
ref.fetch_sub(b, std::memory_order_relaxed );
return errors;
}
template <class T>
int test_pointer(T a, uintptr_t b)
{
int errors = 0;
using atomic_ref = std::atomic_ref<T>;
atomic_ref ref(a);
ref += b;
ref -= b;
ref.fetch_add(b, std::memory_order_relaxed );
ref.fetch_sub(b, std::memory_order_relaxed );
return errors;
}
} // namespace
int main()
{
int num_errors = 0;
{
char a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
signed char a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
unsigned char a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
short a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
unsigned short a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
int a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
unsigned a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
long a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
unsigned long a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
long long a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
unsigned long long a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
__int128 a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
unsigned __int128 a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_integral( a ,b );
}
{
float a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_float( a ,b );
}
{
double a = 1, b = 64;
num_errors += test_generic( a ,b );
num_errors += test_float( a ,b );
}
{
int a = 1, b = 64;
int * a_ptr = &a;
int * b_ptr = &b;
num_errors += test_generic( a_ptr , b_ptr );
num_errors += test_pointer( a, 10 );
}
{
std::complex<double> a{32,64}, b{128, 256};
num_errors += test_generic( a ,b );
}
{
std::array<double,4> a{{32,64,128,256}}, b{{512, 1024, 2048, 4096}};
num_errors += test_generic( a ,b );
}
if (num_errors > 0) {
printf("FAIL: num errors = = %d\n", num_errors );
}
else {
printf("SUCCESS\n");
}
return 0;
}
| [
"dsunder@sandia.gov"
] | dsunder@sandia.gov |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.