Contribute to Open Source. Search issue labels to find the right project for you!

Segfault on first launch (Debian buster)

SFTtech/openage

I managed to install all dependencies and build everything without any problems.

Then when I try make run, a black window opens, then immediately closes and I get this output: <details> <summary> stack dump </summary>

INFO [py] launching openage v0.4.0-83-g6a5df2ad
INFO [py] compiled by GNU 8.3.0
INFO launching engine with Path(Union(<openage.util.fslike.union.Union object at 0x7fea8c067f98>.root @ (b'cfg',), <openage.util.fslike.union.Union object at 0x7fea8c067d30>.root @ (b'assets',)):) and fps limit 0
INFO SDL audio subsystems initialized
INFO Using audio device: default [freq=48000, format=32784, channels=2, samples=4096]
INFO Initialized SDL video subsystems.
INFO Warning: Ignoring XDG_SESSION_TYPE=wayland on Gnome. Use QT_QPA_PLATFORM=wayland to run on Wayland anyway.
INFO Compiled with Qt 5.11.3 and run with Qt 5.11.3
INFO loading configuration files...
INFO [py] loading config file [Union(<openage.util.fslike.union.Union object at 0x7fea8c067f98>.root @ (b'cfg',), <openage.util.fslike.union.Union object at 0x7fea8c067d30>.root @ (b'assets',))]:cfg/keybinds.oac...
INFO Loading time [engine]: 0.282 s
INFO Loading time   [game]: 0.309 s

SIGSEGV

FATAL: terminate has been called

current stack:

Traceback (most recent call last):
  File ?, in __libc_start_main+0xeb [0x7fea95e8009b]
  File ?, in _Py_UnixMain+0x2e [0x6542de]
  File ?, in ? [0x653f7e]
  File ?, in PyRun_SimpleFileExFlags+0x17f [0x63180f]
  File ?, in PyRun_FileExFlags+0x97 [0x630ba7]
  File ?, in ? [0x630af2]
  File ?, in PyEval_EvalCode+0x23 [0x54dae3]
  File ?, in _PyEval_EvalCodeWithName+0x252 [0x54b7c2]
  File ?, in _PyEval_EvalFrameDefault+0x500 [0x54dff0]
  File ?, in ? [0x64e00d]
  File ?, in _PyEval_EvalFrameDefault+0x441a [0x551f0a]
  File ?, in ? [0x54acf0]
  File ?, in _PyFunction_FastCallKeywords+0x18c [0x5d847c]
  File ?, in _PyEval_EvalFrameDefault+0x42c3 [0x551db3]
  File ?, in _PyMethodDef_RawFastCallKeywords+0x224 [0x5d7b24]
  File ?, in ? [0x7fea9386a5bc]
  File ?, in ? [0x7fea93869bc1]
  File ?, in openage::run_game(openage::main_arguments const&)+0x4e8 [0x7fea92857eeb]
  File ?, in openage::Engine::run()+0x27 [0x7fea9284708d]
  File ?, in openage::Engine::loop()+0x102 [0x7fea928469da]
  File ?, in openage::gui::GUI::process_events()+0xd [0x7fea92915e01]
  File ?, in qtsdl::GuiEventQueue::process_callbacks()+0xc [0x7fea9291b1b4]
  File ?, in qtsdl::GuiEventQueueImpl::process_callbacks()+0x1c [0x7fea929205e2]
  File ?, in ? [0x7fea79b76401]
  File ?, in QEventDispatcherGlib::processEvents(QFlags<QEventLoop::ProcessEventsFlag>)+0xf4 [0x7fea90854824]
  File ?, in g_main_context_iteration+0x2c [0x7fea8f76225c]
  File ?, in ? [0x7fea8f7621c8]
  File ?, in g_main_context_dispatch+0x2ae [0x7fea8f761f2e]
  File ?, in ? [0x7fea90855173]
  File ?, in QCoreApplicationPrivate::sendPostedEvents(QObject*, int, QThreadData*)+0x1cb [0x7fea908064db]
  File ?, in QCoreApplication::notifyInternal2(QObject*, QEvent*)+0x179 [0x7fea908034f9]
  File ?, in QObject::event(QEvent*)+0xe2 [0x7fea9082d0e2]
  File ?, in ? [0x7fea913dc099]
  File ?, in QQmlComponentPrivate::loadUrl(QUrl const&, QQmlComponent::CompilationMode)+0x186 [0x7fea913dbb16]
  File ?, in QQmlComponent::statusChanged(QQmlComponent::Status)+0x3e [0x7fea913d869e]
  File ?, in QMetaObject::activate(QObject*, int, int, void**)+0x8a3 [0x7fea9082c9a3]
  File ?, in QtPrivate::QSlotObject<void (qtsdl::GuiSubtreeImpl::*)(QQmlComponent::Status), QtPrivate::List<QQmlComponent::Status>, void>::impl(int, QtPrivate::QSlotObjectBase*, QObject*, void**, bool*)+0x50 [0x7fea9292438f]
  File ?, in qtsdl::GuiSubtreeImpl::component_status_changed(QQmlComponent::Status)+0x102 [0x7fea92923d3c]
  File ?, in QQmlComponentPrivate::completeCreate()+0x57 [0x7fea913d91d7]
  File ?, in QQmlComponentPrivate::complete(QQmlEnginePrivate*, QQmlComponentPrivate::ConstructionState*)+0x81 [0x7fea913d90b1]
  File ?, in QQmlObjectCreator::finalize(QQmlInstantiationInterrupt&)+0x114 [0x7fea91461054]
  File ?, in QQmlBinding::update(QFlags<QQmlPropertyData::WriteFlag>)+0x213 [0x7fea91454353]
  File ?, in ? [0x7fea91457bc2]
  File ?, in QQmlBinding::evaluate(bool*)+0xd7 [0x7fea914530c7]
  File ?, in QQmlJavaScriptExpression::evaluate(QV4::CallData*, bool*)+0x1ff [0x7fea9144e4ff]
  File ?, in ? [0x7fea91397b94]
  File ?, in QV4::Runtime::method_loadProperty(QV4::ExecutionEngine*, QV4::Value const&, int)+0xa2 [0x7fea913a4712]
  File ?, in QV4::QObjectWrapper::getQmlProperty(QQmlContextData*, QV4::String*, QV4::QObjectWrapper::RevisionMode, bool*, bool) const+0x538 [0x7fea91387088]
  File ?, in ? [0x7fea91385bf3]
  File ?, in ? [0x7fea92a21229]
  File ?, in openage::gui::ActionModeLink::get_selection_size() const+0xc [0x7fea928fd376]
  File ?, in ? [0x7fea95e93840]
  File ?, in ? [0x7fea92930dac]
  File ?, in ? [0x7fea925b6901]
  File ?, in ? [0x7fea925b68c6]
  File ?, in openage::error::terminate_handler()+0x18d [0x7fea9293101f]

handing over to the system...

terminate called without an active exception

</details>

My machine:

CPU: i7 2640M RAM: 16Gb OS: Debian buster kernel: 4.19.0-1-amd64

Updated 20/11/2019 17:08 1 Comments

C++ 左值 亡值 纯右值 泛左值 右值

liuyunbin/note

分类

  • 左值
  • 亡值
  • 纯右值
  • 泛左值:包括左值和亡值
  • 右值:包括亡值和纯右值

左值

性质

  • 见 泛左值性质
  • 可以取左值地址
  • 非常量左值可以作为内置的赋值运算符和复合赋值运算符的左操作数
  • 左值可用于初始化左值引用

左值表达式的例子

  • 变量名,函数名,数据成员名组成的表达式,例如,std::cin
  • 函数调用或重载的运算符表达式,返回类型为左值引用,例如,str1 = str2
  • 内建的赋值和复合赋值表达式,例如,a = ba += b
  • 内建的前置自增自减表达式,例如,++a--b
  • 内建的间接寻址表达式,例如,*p
  • 内建的下标表达式,例如,a[n]n[a](其中,a 为左值)
  • 内建的逗号表达式,例如,a, b 其中 b 是左值
  • 字符串字面值,例如,"abcdef"

亡值

性质

  • 参见 泛左值性质
  • 参见 右值性质

亡值表达式的例子

  • 函数调用或重载的运算符表达式,返回类型为右值引用,例如,std::move(str)
  • 内建的下标表达式,例如,a[n]n[a](其中,a 为右值)

纯右值

性质

  • 见 右值性质

纯右值表达式的例子

  • 常量(除了字符串字面值),例如,'a'123
  • 函数调用或重载的运算符表达式,返回类型为非引用,例如,str1 + str2
  • 内建的算数表达式,例如,a + ba & ba << b
  • 内建的逻辑表达式,例如,a && ba || b
  • 内建的比较表达式,例如,a < ba > ba == b
  • 内建的后置自增自减表达式,例如,a++b--
  • 内建取地址表达式,例如,&p
  • 内建的逗号表达式,例如,a, b 其中 b 是右值
  • this 指针
  • 枚举项
  • lambda 表达式

泛左值

性质

  • 可以转化为纯右值

右值

性质

  • 不能被取地址
  • 不能用作内建赋值运算符及内建复合赋值运算符的左操作数
  • 可以用于初始化 const 左值引用
  • 可以用于初始化右值引用
  • 重载时,如果 右值引用 和 const 左值引用同时存在,优先右值引用

参考资源

  • https://zh.cppreference.com/w/cpp/language/value_category
Updated 19/11/2019 17:13

报错:undefined reference to `pthread_create'

tong-hao/tech-log
  • 问题

    在编译pthread相关的cpp时,报错:undefined reference to pthread_create' ``` ht@ht-dev:~/code/test1$ g++ src/thread2.cpp src/thread2.cpp: In function 'int main()': src/thread2.cpp:23:66: warning: cast to pointer from integer of different size [-Wint-to-pointer-cast] rc = pthread_create(&threads[i], NULL, PrintHello, (void *)i); ^ /opt/nebula/third-party/lib/gcc/x86_64-pc-linux-gnu/8.2.0/../../../../x86_64-pc-linux-gnu/bin/ld: /tmp/ccdVNSME.o: in functionmain': thread2.cpp:(.text+0xd2): undefined reference to `pthread_create' collect2: error: ld returned 1 exit status


- 解决方法

g++ src/thread2.cpp -lpthread ```

Updated 18/11/2019 02:06

LGTM.com - false positive

Semmle/ql

Bogus “you should add a header guard” warning.

Seriously, I get how a public header should have header guards. But a private/project header file does not need such things. You already run the configure script and do a build on Ubuntu, just take the next step and make the install target to examine which headers actually get installed - those are the headers that need guards.

https://lgtm.com/projects/g/michaelrsweet/mxml/snapshot/fcc3bcea7099c38e60e3e0e70d0607bd3fcc84dc/files/mxml-private.h?sort=name&dir=ASC&mode=heatmap#x38846df31d23980:1

Updated 19/11/2019 14:45 5 Comments

LGTM.com - false positive

Semmle/ql

The detector sees a memory allocation of strlen(foo) bytes followed by a function call using both the string pointer and the allocated buffer pointer and assumes the allocated buffer won’t have room for the trailing nul. However, in this case the function that is called is doing a Base64 decode of the original string, so the allocated buffer is actually 1/3 larger than necessary and will always have enough room for a trailing nul.

https://lgtm.com/projects/g/apple/cups/snapshot/9f5e54627ad9177bbc854bc3f6c901a06e363cf6/files/scheduler/auth.c?sort=name&dir=ASC&mode=heatmap#x1efd92d7955f17cb:1

Updated 18/11/2019 13:44 2 Comments

LGTM.com - false positive C++: "Comparison result is always the same" + thread_local

Semmle/ql

Variable declared as thread_local is not detected as changeable and triggers a “Comparison result is always the same”, which is wrong due to line 75 in the same file and function.

<!– Please explain briefly why you think it shouldn’t be included. –>

https://lgtm.com/projects/g/PearCoding/PearRay/snapshot/e2f023be537096d15526e7a46cafd689dbd56b4a/files/src/library/Profiler.cpp?sort=name&dir=ASC&mode=heatmap#xc47b2ee0501fa466:1

<!– 1. Open the project on LGTM.com. For example, https://lgtm.com/projects/g/pallets/click/. 2. Switch to the Alerts tab. For example, https://lgtm.com/projects/g/pallets/click/alerts/. 3. Scroll to the alert that you would like to report. 4. Click on the right most icon View this alert within the complete file. 5. A new browser tab opens. Copy and paste the page URL here. For example, https://lgtm.com/projects/g/pallets/click/snapshot/719fb7d8322b0767cdd1e5903ba3eb3233ba8dd5/files/click/_winconsole.py#xa08d213ab3289f87:1. –>

Updated 19/11/2019 10:56 1 Comments

Multidimensional Hermite polynomials improvements

XanaduAI/thewalrus
  • It would be good to parallelize the calculation of Hermite polynomials which is right now done serially.

  • In line https://github.com/XanaduAI/thewalrus/blob/263189a99b86b70665a86822f34735ca9af13b0c/include/hermite_multidimensional.hpp#L162 it is assumed that the first value of the Hermite polynomials is 1. It would be convenient to be able to set different values for this initial value in the recurrence relation defining the polynomials.

  • It would also be useful to introduce generalized multidimensional Hermite polynomials :math: \tilde H_{n}^{(B)}(\alpha) = H_{n}^{(B)}(\alpha)/\sqrt{\prod_i n_i}. This would require to construct explicitly the recursion relation of these new polynomials and implementing it. It would have the advantage of reducing overflows or underflows in the calculation of properties of Gaussian states and gates.

  • The polynomials should be defined so that they depend on :alpha: and not in :B alpha:. See this line https://github.com/XanaduAI/thewalrus/blob/263189a99b86b70665a86822f34735ca9af13b0c/include/hermite_multidimensional.hpp#L209

This matrix vector multiplication could be done ahead of time a not at each iteration.

Updated 18/11/2019 00:26

Setup more material properties for chunks

Revolutionary-Games/Thrive

The art team would like to add a normal map and metalness parameters for the iron chunks. As the chunk data is in biomes.json this needs changes in quite a few places to get all the data through. Also this probably needs one new script bindings in the engine (if emissive map is wanted).

There is an existing function that should be duplicated / overloaded with a variant like: bs::HMaterial getBasicMaterialWithTexture(const string &in textureName, new parameters....) { bs::HShader shader(bs::BuiltinShader::Standard); bs::HMaterial material(shader); bs::HTexture texture(textureName); material.setTexture("gAlbedoTex", texture); material.setTexture("gNormalTex", texture2); material.setTexture("gRoughnessTex", texture3); material.setTexture("gMetalnessTex", texture4); material.setTexture("gEmissiveMaskTex", texture5); material.setVec3("gEmissiveMaskTex", Float3(1.f, 1.f, 1.f)); // this needs a new binding in the engine return material; }

And then the biomes json handling needs reading for more chunk material properties and some code for propagating those values.

Updated 13/11/2019 15:37

crash on launch (Ubuntu 19.04)

SFTtech/openage

I’m able to import the assets, and the game starts (click start game, everything seems to work) ... INFO [py] asset conversion complete; asset version: 7 INFO launching engine with Path(Union(Directory(/home/xxx/Workspace/openage/cfg).root @ (b'cfg',), Directory(/home/xxx/Workspace/openage/assets).root @ (b'assets',)):) and fps limit 0 INFO SDL audio subsystems initialized INFO Using audio device: default [freq=48000, format=32784, channels=2, samples=4096] INFO Initialized SDL video subsystems. INFO Compiled with Qt 5.12.2 and run with Qt 5.12.2 INFO loading configuration files... INFO [py] loading config file [Union(Directory(/home/xxx/Workspace/openage/cfg).root @ (b'cfg',), Directory(/home/xxx/Workspace/openage/assets).root @ (b'assets',))]:cfg/keybinds.oac... INFO Loading time [engine]: 0.292 s INFO Loading time [game]: 0.314 s INFO [T1] Loading game specification files... INFO [T1] Loaded multi-csv file: 45484 sub-files INFO [T1] Loading textures... ERR Can not profile: gperftools is missing INFO [T1] Loading sounds... INFO [T1] Loading time [data]: 5.120 s INFO Gaia has civilisation Gaia INFO Jonas has civilisation British INFO Michael has civilisation French INFO cya!

but after closing the window, and trying to execute the program again, without further modification, it crashes:

INFO [py] launching openage v0.4.0-71-g9740fcb7
INFO [py] compiled by GNU 8.3.0
INFO [py] running in DEVMODE
INFO launching engine with Path(Union(Directory(/home/xxx/Workspace/openage/cfg).root @ (b'cfg',), Directory(/home/xxx/Workspace/openage/assets).root @ (b'assets',)):) and fps limit 0
INFO SDL audio subsystems initialized
INFO Using audio device: default [freq=48000, format=32784, channels=2, samples=4096]
INFO Initialized SDL video subsystems.
INFO Compiled with Qt 5.12.2 and run with Qt 5.12.2
INFO loading configuration files...
INFO [py] loading config file [Union(Directory(/home/xxx/Workspace/openage/cfg).root @ (b'cfg',), Directory(/home/xxx/Workspace/openage/assets).root @ (b'assets',))]:cfg/keybinds.oac...
INFO Loading time [engine]: 0.271 s
INFO Loading time   [game]: 0.289 s

SIGSEGV

FATAL: terminate has been called

current stack:

Traceback (most recent call last):
  File ?, in __libc_start_main+0xeb [0x7f4fcaa90b6b]
  File ?, in ? [0x5577456df86d]
  File ?, in ? [0x5577456df69e]
  File ?, in PyModule_ExecDef+0x4a [0x7f4fcb06b6ca]
  File ?, in ? [0x5577456def02]
  File ?, in ? [0x5577456ddd2b]
  File ?, in ? [0x5577456ddb7c]
  File ?, in _PyEval_EvalFrameDefault+0x7b95 [0x7f4fcaead9b5]
  File ?, in ? [0x7f4fcaeb04d3]
  File ?, in _PyEval_EvalFrameDefault+0x8bde [0x7f4fcaeae9fe]
  File ?, in _PyCFunction_FastCallKeywords+0x25 [0x7f4fcb0aca05]
  File ?, in _PyMethodDef_RawFastCallKeywords+0x30b [0x7f4fcb0abcdb]
  File ?, in ? [0x7f4fc816d71b]
  File ?, in ? [0x7f4fc816cce9]
  File ?, in openage::run_game(openage::main_arguments const&)+0x523 [0x7f4fc72fda9f]
  File ?, in openage::Engine::run()+0x27 [0x7f4fc72ec41f]
  File ?, in openage::Engine::loop()+0x11b [0x7f4fc72ebd7b]
  File ?, in openage::gui::GUI::process_events()+0xd [0x7f4fc73c16ff]
  File ?, in qtsdl::GuiEventQueue::process_callbacks()+0xc [0x7f4fc73c6e02]
  File ?, in qtsdl::GuiEventQueueImpl::process_callbacks()+0x1c [0x7f4fc73cc83e]
  File ?, in QEventDispatcherGlib::processEvents(QFlags<QEventLoop::ProcessEventsFlag>)+0xf4 [0x7f4fc532b0d4]
  File ?, in g_main_context_iteration+0x2c [0x7f4fc41fad1c]
  File ?, in ? [0x7f4fc41fac88]
  File ?, in g_main_context_dispatch+0x2ae [0x7f4fc41fa9ee]
  File ?, in ? [0x7f4fc532ba43]
  File ?, in QCoreApplicationPrivate::sendPostedEvents(QObject*, int, QThreadData*)+0x1c7 [0x7f4fc52da927]
  File ?, in QCoreApplication::notifyInternal2(QObject*, QEvent*)+0x179 [0x7f4fc52d78e9]
  File ?, in QObject::event(QEvent*)+0xe2 [0x7f4fc5301ca2]
  File ?, in ? [0x7f4fc5dbd589]
  File ?, in QQmlComponentPrivate::loadUrl(QUrl const&, QQmlComponent::CompilationMode)+0x176 [0x7f4fc5dbcf36]
  File ?, in QQmlComponent::statusChanged(QQmlComponent::Status)+0x3e [0x7f4fc5db9a3e]
  File ?, in QMetaObject::activate(QObject*, int, int, void**)+0x8a3 [0x7f4fc5301563]
  File ?, in QtPrivate::QSlotObject<void (qtsdl::GuiSubtreeImpl::*)(QQmlComponent::Status), QtPrivate::List<QQmlComponent::Status>, void>::impl(int, QtPrivate::QSlotObjectBase*, QObject*, void**, bool*)+0x50 [0x7f4fc73d09c7]
  File ?, in qtsdl::GuiSubtreeImpl::component_status_changed(QQmlComponent::Status)+0x125 [0x7f4fc73d034b]
  File ?, in QQmlComponentPrivate::completeCreate()+0x42 [0x7f4fc5dba4e2]
  File ?, in QQmlComponentPrivate::complete(QQmlEnginePrivate*, QQmlComponentPrivate::ConstructionState*)+0x81 [0x7f4fc5dba3d1]
  File ?, in QQmlObjectCreator::finalize(QQmlInstantiationInterrupt&)+0x114 [0x7f4fc5e35f94]
  File ?, in QQmlBinding::update(QFlags<QQmlPropertyData::WriteFlag>)+0x213 [0x7f4fc5e28c53]
  File ?, in ? [0x7f4fc5e2c372]
  File ?, in QQmlBinding::evaluate(bool*)+0xdf [0x7f4fc5e279cf]
  File ?, in QQmlJavaScriptExpression::evaluate(QV4::CallData*, bool*)+0x1d7 [0x7f4fc5e22d77]
  File ?, in QV4::Function::call(QV4::Value const*, QV4::Value const*, int, QV4::ExecutionContext const*)+0x16b [0x7f4fc5cad5eb]
  File ?, in ? [0x7f4fc5d1c297]
  File ?, in ? [0x7f4fc5d17dc4]
  File ?, in QV4::Runtime::method_loadProperty(QV4::ExecutionEngine*, QV4::Value const&, int)+0xc9 [0x7f4fc5d866d9]
  File ?, in QV4::QObjectWrapper::virtualGet(QV4::Managed const*, QV4::PropertyKey, QV4::Value const*, bool*)+0x9c [0x7f4fc5cfabcc]
  File ?, in QV4::QObjectWrapper::getQmlProperty(QQmlContextData*, QV4::String*, QV4::QObjectWrapper::RevisionMode, bool*, bool) const+0x4b3 [0x7f4fc5cfa913]
  File ?, in ? [0x7f4fc5cf9473]
  File ?, in ? [0x7f4fc74d8de9]
  File ?, in openage::gui::ActionModeLink::get_selection_size() const+0xc [0x7f4fc73a7994]
  File ?, in ? [0x7f4fcaaadf60]
  File ?, in ? [0x7f4fc73ddf5a]
  File ?, in ? [0x7f4fcacfa301]
  File ?, in ? [0x7f4fcacfa2b6]
  File ?, in openage::error::terminate_handler()+0x19d [0x7f4fc73de1dd]

handing over to the system...

terminate called without an active exception
zsh: abort (core dumped)  ./run

Is it a know issue? What information can I provide? Notice that deleting and importing the assets again permits me to start again the game, but closing and reopening it makes it crash again.

g++: g++ (Ubuntu 8.3.0-6ubuntu1) 8.3.0 python3: Python 3.7.3

Updated 20/11/2019 12:26 2 Comments

LGTM.com - false positive

Semmle/ql

Description of the false positive

for (Integer i = 0; i < 4; ++i) a.row(i) << sPoints[i].x(), sPoints[i].y(), sPoints[i].z(), 1.0;

LGTM gets confused with operator overloading. Here I am using math library Eigen to assign a row to a given matrix.

https://lgtm.com/projects/g/bjaraujo/ENigMA/snapshot/da9570597b4efec3a581d6b37de8a0e64c919319/files/trunk/src/geometry/GeoSphere_Imp.hpp?sort=name&dir=ASC&mode=heatmap#x6c9591050cc7612b:1

<!– 1. Open the project on LGTM.com. For example, https://lgtm.com/projects/g/pallets/click/. 2. Switch to the Alerts tab. For example, https://lgtm.com/projects/g/pallets/click/alerts/. 3. Scroll to the alert that you would like to report. 4. Click on the right most icon View this alert within the complete file. 5. A new browser tab opens. Copy and paste the page URL here. For example, https://lgtm.com/projects/g/pallets/click/snapshot/719fb7d8322b0767cdd1e5903ba3eb3233ba8dd5/files/click/_winconsole.py#xa08d213ab3289f87:1. –>

Updated 19/11/2019 12:28 1 Comments

C++ 基本内置类型的隐式类型转换

liuyunbin/note

文章说明

本文所讨论的基本内置类型及其假定大小:

  • bool(1 个字节)
  • char,unsigned char,signed char(1 个字节)
  • short,unsigned short(2 个字节)
  • int,unsigned,unsigned int(4 个字节)
  • long,unsigned long(4 个字节)
  • long long,unsigned long long(8 个字节)
  • float(4 个字节)
  • double(8 个字节)
  • long double(8 个字节)

本文所讨论的表达式包括:

  • 二元算数运算符(+-*/%
  • 关系运算符(<<=>>===!=
  • 二元位运算符(&|^
  • 条件运算符(?:

正文

有关初始化和赋值的基本内置类型之间的类型转换(不包括列表初始化,不包括列表赋值)

bool 类型的转换

  1. bool 类型 –> 非 bool 类型,false 表示 0true 表示 1
  2. bool 类型 –> bool 类型,0 表示 false,其它表示 true

整数之间的转换(不包括 bool

整数 –> 整数 1. 如果后者可以表示前者,直接表示即可 2. 否则,如果后者是无符号的类型,后者的值域为 [0, N),前者将不断加 或 减 N,直到结果位于后者的值域中 3. 否则,后者是有符号的类型,由编译器实现定义

浮点数和整数之间的转换(不包括 bool

浮点数 –> 整数 1. 首先,忽略前者的小数部分 2. 如果忽略后的值可以由后者表示,直接表示即可 3. 如果忽略后的值超出了后者所能表示的范围,则是未定义的行为

整数 –> 浮点数 1. 如果前者可以由后者精确表示,直接表示即可 2. 如果前者可以由后者表示,但不能精确表示,结果会丧失精度 3. 如果前者超出了后者所能表示的范围,则是未定义的行为

浮点数之间的转换

浮点数 –> 浮点数 1. 如果前者可以由后者精确表示,直接表示即可 2. 如果前者可以由后者表示,但不能精确表示,结果会丧失精度 3. 如果前者超出了后者所能表示的范围,则是未定义的行为

:对于,列表初始化和列表赋值,对于以下行为,将直接报错 * 损失精度 * 由编译器实现定义的行为

有关表达式中的基本内置类型之间的类型转换

  1. 如果某一运算数是 long double 类型,其将其它运算数转为 long double 类型
  2. 如果某一运算数是 double 类型,其将其它运算数转为 double 类型
  3. 如果某一运算数是 float 类型,其将其它运算数转为 float 类型
  4. 其它情况,即两个运算数都是整数的情况:
    1. 首先,进行整数提升,
      • 如果 int 可以表示源类型的值域,则将其转换为 int 类型
      • 否则,如果 unsigned int 可以表示源类型的值域,则将其转换为 unsigned int 类型
    2. 提升后,如果两个运算数类型相同,直接计算
    3. 否则,如果两个运算数同为负数 或 同为正数,将等级小的类型转化为等级大的类型,然后计算
    4. 否则,如果无符号的运算数的等级大于等于有符号的运算数的等级,将有符号的运算数先转化为无符号的运算数,再计算
    5. 否则,如果有符号的运算数的类型的值域大于无符号的运算数的类型的值域,则,将无符号的运算数转换为有符号的运算数,再计算
    6. 否则,将两个运算数都转化为有符号数对应的无符号类型,然后计算

关于等级的说明: * signed char < short < int < long < long long * 无符号类型的等级和对应的有符号类型的等级相同

:对于两元算术运算符,二元位运算符,条件运算符: * 浮点数的运算结果依旧是浮点数 * 无符号的整数的运算结果依旧是无符号的整数 * 有符号的整数的运算结果依旧是有符号的整数

:在 C++11 中: * 对于整数除法(/),结果将向 0 取整,例如:-1/2 == 0 * 对于取模(%),除数的符号将忽略,例如:-5 % (-2) == -5 % 2 == -(5 % 2) == -1

参考资源

  • https://zh.cppreference.com/w/c/language/conversion
Updated 19/11/2019 14:11

Linking problem with host portion of CUDA kernels for CMake >= 3.15

SixTrack/sixtracklib

It seems that the mangled c++ symbols for the host side of cuda kernels are not exported by the shared library and causes problems during linking of applications (even non-cuda ones):

Scanning dependencies of target dump_cbuffer
[ 27%] Building C object tools/CMakeFiles/dump_cbuffer.dir/dump_cbuffer.c.o
[ 27%] Linking C executable dump_cbuffer
../sixtracklib/libsixtrack.so: undefined reference to `__cudaRegisterLinkedBinary_55_tmpxft_000026c9_00000000_6_managed_buffer_remap_cpp1_ii_da9df0a7'
../sixtracklib/libsixtrack.so: undefined reference to `__cudaRegisterLinkedBinary_57_tmpxft_000026ae_00000000_6_extract_particles_addr_cpp1_ii_90dc0973'
../sixtracklib/libsixtrack.so: undefined reference to `__cudaRegisterLinkedBinary_64_tmpxft_00002678_00000000_6_be_monitors_assign_out_buffer_cpp1_ii_54dd6e05'
../sixtracklib/libsixtrack.so: undefined reference to `__cudaRegisterLinkedBinary_50_tmpxft_000026e4_00000000_6_track_particles_cpp1_ii_c22b58a6'
../sixtracklib/libsixtrack.so: undefined reference to `__cudaRegisterLinkedBinary_65_tmpxft_00002693_00000000_6_elem_by_elem_assign_out_buffer_cpp1_ii_2a58a681'
collect2: error: ld returned 1 exit status
tools/CMakeFiles/dump_cbuffer.dir/build.make:88: recipe for target 'tools/dump_cbuffer' failed
make[2]: *** [tools/dump_cbuffer] Error 1
CMakeFiles/Makefile2:2253: recipe for target 'tools/CMakeFiles/dump_cbuffer.dir/all' failed
make[1]: *** [tools/CMakeFiles/dump_cbuffer.dir/all] Error 2
Makefile:140: recipe for target 'all' failed
make: *** [all] Error 2

The same source code compiles and links successfully under cmake < 3.15. May have something to do with LINKER_LANGUAGE=C setting for sixtrack_cuda_device and sixtrack_cuda_host which always seemed a bit fishy to me.

Updated 07/11/2019 13:06

Struct members of cdef'd classes don't get destroyed

cython/cython

If I create a cdef’d class in a cython file having a struct as class member, and then instantiate that class in python, the structs do not get destroyed when the python object is deleted. Adding an explicit call to the struct destructor in __dealloc__ will do the job however.

Example: cppheader.hpp: ```cpp

include <vector>

typedef struct MyObject { int val; std::vector<double> big_obj; } MyObject;

typedef struct InfoHolder { std::vector<MyObject> v; int some_val; } InfoHolder;

void increase_size(MyObject &my_obj) { my_obj.big_obj.resize(10000000, 1); }

void force_destroy(InfoHolder &info_holder) { info_holder.~InfoHolder(); } cyfile.pyx: python from libcpp.vector cimport vector

cdef extern from “cppheader.hpp”: ctypedef struct MyObject: int val vector[double] big_obj ctypedef struct InfoHolder: vector[MyObject] v int some_val void increase_size(MyObject &my_obj) void force_destroy(InfoHolder &info_holder)

cdef class PyInfoHolder: cdef InfoHolder info_holder def init(self): self.info_holder.v.resize(1); increase_size(self.info_holder.v.at(0)) def say_hello(self): print(“hello”) pyfile.py: python from cyfile import PyInfoHolder

for i in range(100): py_obj = PyInfoHolder() py_obj.say_hello() print(“end”) ```

Watch the memory usage when running python pyfile.py, and then compare against the following alternative cython class: python cdef class PyInfoHolder: cdef InfoHolder info_holder def __init__(self): self.info_holder.v.resize(1); increase_size(self.info_holder.v.at(0)) def __dealloc__(self): force_destroy(self.info_holder) def say_hello(self): print("hello")

(For some reason, the structs also cannot call their destructor explicitly within cython - e.g. self.info_holder.~InfoHolder() fails to compile)

Updated 13/11/2019 14:22 7 Comments

STL以及常用刷题方法总结

happy-yuxuan/blogs

STL 待更新

容器 头文件 方法 备注
vector vector push_back/pop_back resize erase front/back begin/ end size/clear/empty [] resize的参数跟初始化一样
list list push_back/pop_back front/back erase begin/ end size/clear/empty []
string string substr +=/push_back find replace size/length/clear/empty [] getline(cin,s6); 读取字符到遇到换行,空格可读入,知道‘\n’结束. c_str()可以用printf %s输出
stack stack push pop top size/empty 没有clear, 要一个个弹出
queue queue push pop front/back size/empty 没有clear, 要一个个弹出
priority_queue queue push/pop size/clear/empty 默认大根堆 小根堆priority_queue<int, vector<int>, greater<int> > q; 小于的定义是反的
deque deque push_back/pop_back front/back begin/ end size/clear/empty [] deque容器虽然支持随机访问,但是其随机访问速度慢于vector容器。插(删)头尾O(1)
set set insert count / find erase begin/ end size/clear/empty 自动去重升序排序 O(logn)
unordered_set unordered_set insert count / find erase begin/ end size/clear/empty O(1)
map map insert count / find [] erase begin/ end size/clear/empty 基于平衡树O(logn)
unordered_map unordered_map insert count / find erase begin/ end size/clear/empty 基于哈希表O(1)

常用

保留几位小数

printf("%.6f", k);  // 保留6位小数   (double - printf - %f) (doubel - scanf - %lf)

输入字符串包括空格

getline(cin,str);   // str 为 string

输入直到文字流结束 (ctrl + z)

// scanf
while (scanf("%d %d",&a, &b) != EOF) {
    printf("%d\n", a + b);
}

// cin
while (!cin.eof()) {
    cin >> a >> b;
    cout << a + b << endl;
}

pair

  • pair对于排序来说是以first为第一关键字排序, second为第二关键字排序
  • 赋值的时候可以使用花括号代替{1, 2}

sort的比较函数的几种写法 (默认从小到大)

// 对vector排序
sort(v.begin(), v.end(), [](const int& a, const int& b){return a > b;});

// 对数组排序
sort(arr, arr + 100);

自定义结构体并重载小于号

  • 结构体=为赋值操作,是整个结构体赋值过去。 而类只是浅拷贝
  • LeetCode中要写在类的外面
  • 写在类中LeetCode需要在前面加friend。参考
  • 不要对pair进行重载运算符,最好自己定义结构体
  • 遇到priority_queue的时候需要相反定义 (认为大的越小, 小的越大)
struct Node {
    int p1, p2;
    Node(int p1, int p2) : p1(p1), p2(p2) {}
};

// 推荐方式 !!!!!!! 
bool operator<(const Node& a, const Node& b)
{
    if (a.p1 == b.p1) return a.p2 < b.p2;
    return a.p1 < b.p1;
}

// 以p1为第一关键字, p2为第二关键字排序  && 优先级比 || 高
bool operator<(const Node& a, const Node& b)
{
    // return a.p1 < b.p1 || !(b.p1 < a.p1) && a.p2 < b.p2;
    return a.p1 < b.p1 || a.p1 == b.p1 && a.p2 < b.p2;
}

Node n1(1, 2);
  • 为什么重载<号要这样写,而不写成return a.p1 < b.p1 || a.p1 == b.p1 && a.p2 < b.p2?因为p1和p2是int,他们虽然有重载==。但是对于没有重载==来说,只须重载小于运算符. 参考文献

堆之标准比较器构造 (我一般只用重载运算符)


typedef pair<string, int> Node;
typedef function<bool(const Node&, const Node&)> Compare;

int main()
{
    // ...

    Compare comparator = [](const Node& a, const Node& b) {
        if (a.second == b.second)
            return a.first < b.first;    // order by alphabet  ASC
        return a.second > b.second;    // order by freq DESC
    };

    // Min heap by frequency
    priority_queue<Node, vector<Node>, Compare> q(comparator);

    // ...
}
Updated 12/11/2019 07:11

qore cannot be compiled with clang++ 9

qorelanguage/qore
In file included from /export/home2/dnichols/src/qore/git/qore/lib/single-compilation-unit.cpp:122:
/export/home2/dnichols/src/qore/git/qore/lib/thread.cpp:1204:5: error: 'gettid' is missing exception specification 'throw()'
int gettid() {
    ^
             throw()                                                                                                                                                                                      
/export/home2/dnichols/src/qore/git/qore/include/qore/qore_thread.h:68:15: note: previous declaration is here
DLLEXPORT int gettid();
              ^
1 error generated.
Updated 05/11/2019 18:01

Current issue with asan

nodejs/node

Current asan failed using the following config sh ./configure --enable-asan --debug make -j8 make test-only

due to https://github.com/nodejs/node/blob/31217a8e88d7414579284267f8715112bf8a0fc6/src/node.cc#L950-L958

My question is: * Is there a way to fix this ? * If not, can I make the test go on with those failures ?

cc @addaleax @bnoordhuis @devnexen

<details>

Direct leak of 8 byte(s) in 1 object(s) allocated from:
    #0 0x7f6f24a48f1e in __interceptor_realloc (/lib/x86_64-linux-gnu/libasan.so.5+0x10df1e)
    #1 0x55be1f9ceed2 in char const** node::UncheckedRealloc<char const*>(char const**, unsigned long) ../src/util-inl.h:346
    #2 0x55be1f9cdb32 in char const** node::UncheckedMalloc<char const*>(unsigned long) ../src/util-inl.h:361
    #3 0x55be1f9cb8c3 in char const** node::Malloc<char const*>(unsigned long) ../src/util-inl.h:380
    #4 0x55be1f9c77c9 in node::Init(int*, char const**, int*, char const***) ../src/node.cc:953
    #5 0x55be1f81ff9f in NodeTestFixture::SetUpTestCase() ../test/cctest/node_test_fixture.h:79
    #6 0x55be1f7d0d9d in testing::TestSuite::RunSetUpTestSuite() (/root/node/out/Debug/cctest+0x1f87d9d)
    #7 0x55be1f7f27d5 in void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::TestSuite, void>(testing::TestSuite*, void (testing::TestSuite::*)(), char const*) (/root/node/out/Debug/cctest+0x1fa97d5)
    #8 0x55be1f7e327f in void testing::internal::HandleExceptionsInMethodIfSupported<testing::TestSuite, void>(testing::TestSuite*, void (testing::TestSuite::*)(), char const*) (/root/node/out/Debug/cctest+0x1f9a27f)
    #9 0x55be1f7973d2 in testing::TestSuite::Run() ../test/cctest/gtest/gtest-all.cc:4289
    #10 0x55be1f7aee33 in testing::internal::UnitTestImpl::RunAllTests() ../test/cctest/gtest/gtest-all.cc:6752
    #11 0x55be1f7f44e1 in bool testing::internal::HandleSehExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) (/root/node/out/Debug/cctest+0x1fab4e1)
    #12 0x55be1f7e4524 in bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) (/root/node/out/Debug/cctest+0x1f9b524)
    #13 0x55be1f7abea9 in testing::UnitTest::Run() ../test/cctest/gtest/gtest-all.cc:6340
    #14 0x55be1f81ac55 in RUN_ALL_TESTS() ../test/cctest/gtest/gtest.h:14896
    #15 0x55be1f81ab3b in main ../test/cctest/gtest/gtest_main.cc:45
    #16 0x7f6f243ef1e2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x271e2)

Direct leak of 7 byte(s) in 1 object(s) allocated from:
    #0 0x7f6f249d13dd in strdup (/lib/x86_64-linux-gnu/libasan.so.5+0x963dd)
    #1 0x55be1f9c798e in node::Init(int*, char const**, int*, char const***) ../src/node.cc:957
    #2 0x55be1f81ff9f in NodeTestFixture::SetUpTestCase() ../test/cctest/node_test_fixture.h:79
    #3 0x55be1f7d0d9d in testing::TestSuite::RunSetUpTestSuite() (/root/node/out/Debug/cctest+0x1f87d9d)
    #4 0x55be1f7f27d5 in void testing::internal::HandleSehExceptionsInMethodIfSupported<testing::TestSuite, void>(testing::TestSuite*, void (testing::TestSuite::*)(), char const*) (/root/node/out/Debug/cctest+0x1fa97d5)
    #5 0x55be1f7e327f in void testing::internal::HandleExceptionsInMethodIfSupported<testing::TestSuite, void>(testing::TestSuite*, void (testing::TestSuite::*)(), char const*) (/root/node/out/Debug/cctest+0x1f9a27f)
    #6 0x55be1f7973d2 in testing::TestSuite::Run() ../test/cctest/gtest/gtest-all.cc:4289
    #7 0x55be1f7aee33 in testing::internal::UnitTestImpl::RunAllTests() ../test/cctest/gtest/gtest-all.cc:6752
    #8 0x55be1f7f44e1 in bool testing::internal::HandleSehExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) (/root/node/out/Debug/cctest+0x1fab4e1)
    #9 0x55be1f7e4524 in bool testing::internal::HandleExceptionsInMethodIfSupported<testing::internal::UnitTestImpl, bool>(testing::internal::UnitTestImpl*, bool (testing::internal::UnitTestImpl::*)(), char const*) (/root/node/out/Debug/cctest+0x1f9b524)
    #10 0x55be1f7abea9 in testing::UnitTest::Run() ../test/cctest/gtest/gtest-all.cc:6340
    #11 0x55be1f81ac55 in RUN_ALL_TESTS() ../test/cctest/gtest/gtest.h:14896
    #12 0x55be1f81ab3b in main ../test/cctest/gtest/gtest_main.cc:45
    #13 0x7f6f243ef1e2 in __libc_start_main (/lib/x86_64-linux-gnu/libc.so.6+0x271e2)

</details>

Updated 07/11/2019 09:19 5 Comments

CMake + gdb

tong-hao/tech-log

gdb install

sudo apt-get install libgtest-dev

gtest build

cd /usr/src/gtest sudo mkdir build cd build sudo cmake .. #一定要以sudo的方式运行,否则没有写入权限 sudo make #这个也一样要以sudo的方式

sudo cp libgtest*.a /usr/local/lib

test.cpp

#include <gtest/gtest.h>//注意斜杠方向,左斜杠有可能找不到头文件
int Foo(int a,int b)
{
   if(0 == a||0 == b)
   throw "don't do that";
   int c = a%b;
   if (0 == c)
  {
     return b;
  }
  return Foo(b,c);
}

TEST(FooTest,HandleNoneZeroInput)//名称随便
{
   EXPECT_EQ(2,Foo(4,10));
   EXPECT_EQ(6,Foo(30,18));
}
int main(int argc,char*argv[])
{
   testing::InitGoogleTest(&argc,argv);
   return RUN_ALL_TESTS();
}

cmake

mkdir build cd build cmake -DCMAKE_BUILD_TYPE=Debug ../

make

make

gdb

gdb <XXXTest> info b b XXX.cpp:30 r print v

Updated 05/11/2019 02:34

3.无重复字符的最长子串

Gitronlee/Blog

给定一个字符串,请你找出其中不含有重复字符的 最长子串 的长度。

示例 1:

输入: “abcabcbb” 输出: 3 解释: 因为无重复字符的最长子串是 “abc",所以其长度为 3。

AC:

class Solution {
public:
    int lengthOfLongestSubstring(string s) {
        vector<int> dict(256, -1);
        int maxlen = 0, start = -1;
        for(int i = 0; i < s.size(); i++)
        {
            if(dict[s[i]] > start)//我上次记录的值,若比我要起始值还大,则更新我起始值
            {
                start = dict[s[i]];
            }
            dict[s[i]] = i;//记录下来,之后还能遇到则是“上次遇到时的索引”
            maxlen = max(maxlen, i - start);
        }
        return maxlen;
    }
};

思路:

1.一个用来存下遇到这个字符时索引值的数组。 2.用start拿到上一次遇到这个字符的索引。 3.一减一比较。

Updated 04/11/2019 11:00

cxx_indexer reports error for some STL header files from gcc 9.2.0

kythe/kythe

So I am using kythe to index the code of rippled. I have generated a bunch of kzip files. When running cxx_indexer on some of those kzip files, I got the following error: In file included from /home/user/rippled/src/ripple/unity/app_misc.cpp:21: In file included from /home/user/rippled/src/ripple/app/misc/CanonicalTXSet.cpp:20: In file included from /home/user/rippled/src/ripple/app/misc/CanonicalTXSet.h:23: In file included from /home/user/rippled/src/ripple/protocol/RippleLedgerHash.h:23: In file included from /home/user/rippled/src/ripple/basics/base_uint.h:28: In file included from /home/user/rippled/src/ripple/basics/strHex.h:29: In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/string:40: In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/char_traits.h:39: In file included from /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_algobase.h:65: /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_iterator_base_types.h:117:63: error: cannot form a reference to 'void' typename _Pointer = _Tp*, typename _Reference = _Tp&> ^ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_iterator_base_types.h:118:12: note: in instantiation of default argument for 'iterator<std::output_iterator_tag, void, long, void *>' required here struct iterator ^ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_iterator_base_types.h:117:63: error: cannot form a reference to 'void' typename _Pointer = _Tp*, typename _Reference = _Tp&> ^ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_iterator_base_types.h:118:12: note: in instantiation of default argument for 'iterator<std::output_iterator_tag, void, long, void *, std::output_iterator_tag, void, void, void *>' required here struct iterator ^ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_iterator_base_types.h:117:63: error: cannot form a reference to 'void' typename _Pointer = _Tp*, typename _Reference = _Tp&> ^ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/bits/stl_iterator_base_types.h:118:12: note: in instantiation of default argument for 'iterator<std::output_iterator_tag, void, long, void *, std::output_iterator_tag, void, void, void *, std::output_iterator_tag, void, void, void>' required here struct iterator ^ E1103 22:32:31.910046 2134318 IndexerASTHooks.cc:4488] Unable to find TemplateTypeParmDecl for TemplateTypeParmTypeLoc In file included from /home/user/rippled/src/ripple/unity/app_misc.cpp:21: In file included from /home/user/rippled/src/ripple/app/misc/CanonicalTXSet.cpp:20: In file included from /home/user/rippled/src/ripple/app/misc/CanonicalTXSet.h:23: In file included from /home/user/rippled/src/ripple/protocol/RippleLedgerHash.h:23: In file included from /home/user/rippled/src/ripple/basics/base_uint.h:29: In file included from /home/user/rippled/src/ripple/basics/hardened_hash.h:23: In file included from /home/user/rippled/src/ripple/beast/hash/hash_append.h:27: /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/chrono:64:64: error: no type named 'duration' in 'date::local_t' template<typename _Clock, typename _Dur = typename _Clock::duration> ~~~~~~~~~~~~~~~~~^~~~~~~~ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/chrono:626:14: note: in instantiation of default argument for 'time_point<date::local_t>' required here struct time_point ^ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/chrono:64:64: error: no type named 'duration' in 'date::local_t' template<typename _Clock, typename _Dur = typename _Clock::duration> ~~~~~~~~~~~~~~~~~^~~~~~~~ /usr/lib/gcc/x86_64-pc-linux-gnu/9.2.0/include/g++-v9/chrono:626:14: note: in instantiation of default argument for 'time_point<date::local_t>' required here struct time_point ^ 5 errors generated. Error: Errors during indexing. I have uploaded these two header files headers.tar.gz

cxx_indexer generates some output even with this error. Is that output a partial result? Can it be used?

Please let me know if you need anything else. Thanks!

Updated 07/11/2019 07:38 11 Comments

Desenvolvedor Java Junior na [EISA]

devssa/onde-codar-em-salvador

Desenvolvedor Java Junior

A Ericsson Inovação S.A é uma combinação singular de skills e competências na entrega de serviços profissionais na área de Suporte aos negócios e a Operação, atuamos com uma das maiores operações de telecomunicações do mundo, além de ser certificada pelo Great Place to Work, como uma das melhores empresas para se trabalhar no segmento de tecnologia da informação.

O que você vai fazer:

  1. Desenvolvimento, testes e execução de scripts para correção e manipulação de dados em ambiente de produção (BackOffice);
  2. Concepção, modelagem e programação de módulos de software relacionados à customização das regras de negócio da solução de sistemas;
  3. Atuação em escalas de suporte a testes planejados;
  4. Realizar análise de correção de incidentes e defeitos de software.

O que você precisa para desempenhar esta atividade?

  1. Formação superior cusando ou completa em Engenharia da Computação, Análise de Sistemas, Ciência da Computação e áreas afins;
  2. Programação orientada a objetos (Java);
  3. Conhecimento em banco de dados Oracle e desenvolvimento PL/SQL;
  4. Experiência em análise de correção de incidentes e defeitos de software;
  5. Experiência com concepção, modelagem e programação de módulos de software;
  6. Desejável conhecimento nas linguagens C, C++e Shell Script.

Horário de trabalho: 9hs às 18hs.

Onde estamos?

Tecnocentro - Salvador/ BA

Nossos benefícios:

  1. Vale- Refeição e/ ou Alimentação;
  2. Além dos benefícios de alimentação e refeição, cedemos espaço para almoço com copa; Vale- transporte;
  3. Assistência médica;
  4. Assistência odontológica;
  5. Bonificação de férias;
  6. Seguro de vida;
  7. Participação nos lucros e resultados;
  8. Frutas e biscoitos;
  9. Home Office;
  10. Horário flexível.

CANDIDATE-SE:exclamation::exclamation:

Updated 31/10/2019 17:06

EPI code integration

xxks-kkk/shuati

EPI has better C++ code implementation and definition than Leetcode’s. Using leetcode has negative impact on C++ practice. Try to integrate EPI code along with test infrastructure in the repo and point to the EPI implementation whenever we can find the same leetcode problem in EPI.

See PR #168 Todo section on one example.

Updated 30/10/2019 04:00

KISS not seen yet

HenryRLee/PokerHandEvaluator

Guys I have to say: good ideas on how approach the hand ranking problem, but then you lose the audience in the build phase: I mean is good to have unit tests built automatically using googletest, but by any chance we will have a clear idea on how to have something that works? libpheval is yet to be seen declared anywhere…

So this is a general issue on clarity as there are missing instructions on: 1) assemble the code without manual intervention (even using CMake I need to adjust the folders manually); 2) generate any solution, i.e. a .dll or at least tell the uninitiated how to create/see the “ghost library” libpheval…

Cool stuff tough, would be good to be able to use it :)

Updated 29/10/2019 01:54 2 Comments

Not Work C++ Mxnet and opencv integration

apache/incubator-mxnet

How to pass a lot of cv:: Mat to MXDataIter ? ``C++

auto val_iter = MXDataIter("ImageRecordIter")
        .SetParam("data_shape", Shape(3, image_size, image_size))
        .SetParam("batch_size", batch_size)
        .SetParam("shuffle", 1)
        .SetParam("flat", 1)
        .SetParam("ctx", "cpu")
        .CreateDataIter();

int count = 0;
Accuracy acc;
val_iter.Reset();
while (val_iter.Next()) {
    auto data_batch = val_iter.GetDataBatch();
    data_batch.data.CopyTo(&args_map["data"]);
    NDArray::WaitAll();
    exec->Forward(false);
    acc.Update(data_batch.label, exec->outputs[0]);
}

delete exec;
MXNotifyShutdown();

return 0;

``

Updated 18/11/2019 19:45 3 Comments

__sanitizer_cov_trace_pc_guard not inserted when cfi enabled (Bugzilla Bug 2)

asl/llvm-bugzilla

This issue was created automatically with bugzilla2github

Bugzilla Bug 2

Date: 2019-10-26T22:51:06+07:00 From: Joey Jiao <joeyjiaojg@163.com> To: Unassigned Clang Bugs <unassignedclangbugs@nondot.org> CC: blitzrakete@gmail.com, @DougGregor, erik.pilkington@gmail.com, joeyjiaojg@163.com, llvm-bugs@lists.llvm.org, @zygoloid

Last updated: 2019-10-26T22:51:24+07:00

Updated 27/10/2019 20:38 1 Comments

Excel 调用 DLL

topcss/my-notes

这篇帖子[1]可读性极差,图片不清晰,排版让人恼火。将就一下,我们重点是看内容。下面我来复述一遍:

一、分成 2 步来实现:

  1. 在 vs 中创建一个 c++ 项目,用来生成 DLL
  2. 在 Excel 中如何引用这个 DLL 提供的方法

二、踩过的坑:

  1. Excel 报错很迷惑人,明明文件存在,报错说文件不存在。
  2. Excel 的版本和你 DLL 的版本不一致,x86/x64。
  3. 没有设置 模块定义文件 def 文件。
  4. def 文件的内容不对,包括项目名称 LIBRARY ,导出的函数名 EXPORTS 不一致 。
  5. Excel 引用的方法不对,要参照我这样写。
  6. 在 vs 不要用选项目生成,要按 F5。虽然无法用F5调试,但 F5 会生成正确的 DLL(这条非常重要)
Private Declare PtrSafe Function Add Lib "C:\Users\Jack\source\repos\cppDll1\x64\Debug\cppDll.dll" (ByVal x As Long,ByVal y As Long) As Long

参考文章:

[1] EXCEL调用C++生成的DLL文件

Updated 25/10/2019 03:32

Excel 调用DLL实现繁简体相互转换

topcss/my-notes

Excel 调用DLL实现繁简体相互转换

一、调试篇

  1. 在 Excel 中,按 Alt+F11 打开VBA编程环境。点击菜单中“插入”-“模块” 打开编辑框,或按下 ALT+I+M,粘贴下面的代码。
Private Declare PtrSafe Function LCMapString Lib "kernel32" Alias "LCMapStringA" (ByVal Locale As Long, ByVal dwMapFlags As Long, ByVal lpSrcStr As String, ByVal cchSrc As Long, ByVal lpDestStr As String, ByVal cchDest As Long) As Long
Private Declare PtrSafe Function lstrlen Lib "kernel32" Alias "lstrlenA" (ByVal lpString As String) As Long

Public Function 简转繁(ByVal Str As String) As String
    Dim STlen As Long
    Dim STf As String
    STlen = lstrlen(Str)
    STf = Space(STlen)
    LCMapString &H804, &H4000000, Str, STlen, STf, STlen
    简转繁 = STf
End Function

Public Function 繁转简(ByVal Str As String) As String
    Dim STlen As Long
    Dim STj As String
    STlen = lstrlen(Str)
    STj = Space(STlen)
    LCMapString &H804, &H2000000, Str, STlen, STj, STlen
    繁转简 = STj
End Function

Sub test()
    Debug.Print 简转繁("东西"), 繁转简("東西")
End Sub
  1. 选择菜单”视图“-”立即窗口“或按 Ctrl+G 打开立即窗口,用于监控打印结果。
  2. 按 F5 弹出”宏“窗口,选择”test“点击”运行“,即可查看运行结果。如图1所示。

image 图1

二、应用篇

  1. 关闭 VBA 窗口,回到 Excel 主界面
  2. 例如:我们想把 B2 单元格中的简体转换为繁体,在 B3 单元格中显示
  3. B3 单元格 中输入 =简转繁(B2) 即可,实现转换功能
Updated 25/10/2019 03:32

leetcode 周赛159

maninbule/contests

1232. 缀点成线 【gcd】

先任意选两个点求出一个斜率用最简分数a/b来表示,约分需要使用到gcd。然后遍历坐标数组,如果存在两个相邻的元素的斜率c/d不等于a/b就返回false,否则就true 注意所有分数都必须是最简的,0/12最简分数为0/1 cpp class Solution { public: int gcd(int a,int b){ return !b? a:gcd(b,a%b); } bool checkStraightLine(vector<vector<int>>& c) { int son = c[1][0]-c[0][0],mu = c[1][1]-c[0][1],g = gcd(son,mu); son/=g,mu/=g; for(int i = 1;i<c.size();i++){ int s = c[i][0]-c[i-1][0],m = c[i][1]-c[i-1][1],g = gcd(s,m); s/=g,m/=g; if(s!=son || m!=mu) return false; } return true; } };

1233. 删除子文件夹 【排序+暴力】

先把字符串的从小到大排序,对于一个字符串,遍历这个字符串,判断他的每一个前缀是否出现过,若出现过就舍弃,若没有就加入到集合中 假如有/a/b已经在集合中了,因为/a/b/c/d的前缀a/b已经在集合中了,所以就舍弃。 /a/b/c/d的前缀有/a,/a/b,/a/b/c cpp class Solution { public: vector<string> removeSubfolders(vector<string>& f) { set<string> st; vector<string> res; sort(f.begin(),f.end()); for(const auto&s:f){ int exist = 0; for(int i = 0;i<s.length();i++){ if(s[i] == '/' && st.count(s.substr(0,i))){ exist = 1; break; } } if(!exist){ st.insert(s); res.push_back(s); } } return res; } };

1234. 替换子串得到平衡字符串【二分+滑动窗口】

因为答案是一个长度问题,在[0,字符串长度]之间,所以可以尝试用二分来解决,关键是judge函数比较难写,其实也不难,就是一个滑动窗口。 假如已经有一个窗口在字符串中了,窗口中共有t个字符,窗口外Q、W、E、R各有a、b、c、d个.设abcd中最大值为m,dif为abcd与m的差值总和,当t>=dif时,此时的窗口大小是可以的,也就是说此次二分的mid是可以替换出来平衡字符串的。 所以我们的目的就了找长度最小的合法窗口,合法窗口指的是可以替换出平衡字符串

class Solution {
public:
    string str;
    unordered_map<char,int> mp;
    bool judge(int n){
        unordered_map<char,int> mp2;
        mp2['Q'] = mp['Q'];mp2['W'] = mp['W'];mp2['E'] = mp['E'];mp2['R'] = mp['R'];

        for(int i = 0;i<n;i++) mp2[str[i]]--;
        int mx = max(max(mp2['Q'],mp2['W']),max(mp2['E'],mp2['R']));
        int dif = 0; for(auto m:mp2) dif+= mx-m.second;
        if(n>=dif) return true;
        for(int i = n;i<str.length();i++){
            mp2[str[i-n]]++;mp2[str[i]]--;
            int mx = max(max(mp2['Q'],mp2['W']),max(mp2['E'],mp2['R']));
            int dif = 0; for(auto m:mp2) dif+= mx-m.second;
            if(n>=dif) return true;
        }
        return false;
    }
    int balancedString(string s) {
        str = s;
        for(auto c:s) mp[c]++;
        int l = 0,r = s.length(),mid;
        while(l<r){
            mid = (l+r)/2;
            if(judge(mid)) r = mid;
            else l = mid+1;
        }
        return l;
    }
};

1235. 规划兼职工作 【dp】

先把开始时间、结束时间、收益装进一个结构体,按照结束时间从小到大排序。 dp[i]表示第i天的收益。假如一个开始时间s,结束时间e,或者收益w,那么可以想到dp[e] = max(dp[e],dp[s]+w) 但是有可能dp[s] = 0,但是dp[t] (t<s) 不为0,所以我们需要用二分查找第最后一个小于等于s的结束时间t, 然后dp[e] = max(dp[e],dp[t]+w)

struct work{
    int s,e,w;
};
bool cmp(const work & n1,const work & n2){
    if(n1.e != n2.e) return n1.e < n2.e;
    return n1.s<n2.s;
}
class Solution {
public:
    int len;
    unordered_map<int,int> dp;
    int jobScheduling(vector<int>& startTime, vector<int>& endTime, vector<int>& profit) {
        len = startTime.size();
        vector<work> node(len);
        for(int i = 0;i<len;i++){
            node[i] = {startTime[i],endTime[i],profit[i]};
        }
        sort(node.begin(),node.end(),cmp);
        sort(endTime.begin(),endTime.end());
        for(int i = 0;i<len;i++){
            if(i>=1) dp[node[i].e] = dp[node[i-1].e];
            int t = upper_bound(endTime.begin(),endTime.end(),node[i].s) - endTime.begin();
            if(--t>=0){
                dp[node[i].e] = max(dp[node[i].e],dp[endTime[t]]+node[i].w);
            }else{
                dp[node[i].e] = max(dp[node[i].e],dp[node[i].s]+node[i].w);
            }
        }
        return dp[endTime[len-1]];
    }
};
Updated 22/10/2019 09:56

Respect subtypes in RPC

ndsev/zserio

Currently RPC AST node returns compound types directly for its request and response type. Core should however respect subtypes, so that the subtypes can be used by generators.

struct U32
{
    uint32 value;
};
struct Str
{
    string value;
};
subtype U32 Request;
subtpye Str Response;
service Convertor
{
    rpc Response toStr(Request);
};
Updated 21/10/2019 12:09

Incorrect deduction of function object types

cython/cython
cdef extern from "<functional>" namespace "std" nogil:
    cdef cppclass plus[T=*]:
        plus() except +
        T operator()(const T& lhs, const T& rhs) except +

def test(): 
    return plus[int]()(1, 2) 
test.cpp:1244:15: error: non-object type 'int (const int &, const int &)' is not assignable
    __pyx_t_1 = std::plus<int> ();
    ~~~~~~~~~ ^
1 error generated.

A temporary for std::plus<int> is generated as int __pyx_t_1(int const &, int const &), which fails to compile. Explicitly storing it in a temporary works:

def test(): 
    tmp = plus[int]()
    return tmp(1, 2) 
Updated 26/10/2019 04:42 1 Comments

C++按字符位置读取文件

lc-leo/Notes

//读取一个文本文件中每行第StartN到第StopN个字符 ```C++

include <iostream>

include <fstream>

define StartN 47

define StopN 58

using namespace std;

int main() { char buffer[256]; fstream infile; //供读取的文本文件 infile.open(“e:/shield_hit12a_win64_demo_v0.7.4/examples/simple-1/for028”,ios::in);

ofstream ofile("e:/shield_hit12a_win64_demo_v0.7.4/examples/simple-1/ofile.txt");  //供写入的文件

while(!infile.eof()){          //读取直到文件末尾
    infile.getline(buffer,256,'\n'); //按行读取,到第256个字符或遇到回车则停止
    for(int i=StartN;i<StopN;i++){
        ofile << buffer[i];
        //cout << buffer[i];
    }
    ofile << endl;
}
infile.close();
ofile.close();
//cin.get(); //读取回车键

return 0;

}

```

Updated 21/10/2019 07:34

Right-click freezes the game

Revolutionary-Games/Thrive

For some reason right click in the GUI (probably not in the editor) freezes the game on windows. On Linux it spams logs with: ``` [1020/202743.917484:WARNING:x11_util.cc(1422)] X error received: serial 275, error_code 3 (BadWindow), request_code 4, minor_code 0 (Unknown) [1020/202744.433515:WARNING:x11_util.cc(1422)] X error received: serial 402, error_code 3 (BadWindow), request_code 4, minor_code 0 (Unknown)

```

It’s probably some CEF related thing trying to open a non-existing context menu.

Updated 20/10/2019 17:29

ICPC 焦作站I题

maninbule/contests

I. Distance 【贪心+前缀】

2019-10-20 22 22 41 692 得出结论: 当数轴两端选点数相同时,也就是奇数次选点,选最左端未被选过的点,以让下次偶数选点获得的增值最大。所以奇数选点选未选点最左的一个,偶数选点选未选点最右的一个

#include <iostream>
#include <vector>
using namespace std;
const int maxn = 1e6+10;
typedef long long ll;

ll p[maxn];
ll res[maxn];
int main(){
    int T;cin>>T;
    while(T--){
        int N;cin>>N;
        ll dis;
        for(int i = 2;i<=N;i++){
            scanf("%lld",&dis);
            p[i] = p[i-1]+dis;
        }
        res[1] = 0,res[2] = p[N];//初始化
        int l = 2,r = N-1,idx = 3;//
        int tl = 1,tr  = 1;ll suml = 0,sumr = 0;//左右前缀的数量,左右前缀和
        while(l<=r){
            if(idx%2 == 1){ //奇数选左边端点,偶数选右边
                ll sum = (p[l]-p[1])*tl-suml + (p[N]-p[l])*tr-sumr;
                res[idx] = res[idx-1]+sum;
                tl++,suml+=p[l],l++;
            }else{
                ll sum = (p[r]-p[1])*tl-suml + (p[N]-p[r])*tr-sumr;
                res[idx] = res[idx-1]+sum;
                tr++,sumr+=p[N]-p[r],r--;
            }
            idx++;
        }
        for(int i = 1;i<=N;i++){
            printf("%lld",res[i]);
            if(i!=N)putchar(' ');
        }
        puts("");
    }
    return 0;
}
Updated 21/10/2019 09:07

ICPC 焦作站A题

maninbule/contests

A. Xu Xiake in Henan Province

刺裸裸的签到题 ```cpp

include <iostream>

using namespace std;

int main(){ int T;cin>>T; while(T–){ int cur,cnt = 0; for(int i = 0;i<4;i++){ scanf(“%d”,&cur); if(cur>0) cnt++; } if(cnt == 0) puts(“Typically Otaku”); if(cnt == 1) puts(“Eye-opener”); if(cnt == 2) puts(“Young Traveller”); if(cnt == 3) puts(“Excellent Traveller”); if(cnt == 4) puts(“Contemporary Xu Xiake”); } return 0; } ```

Updated 21/10/2019 09:07

ICPC2018 焦作站E题

maninbule/contests

E. Resistors in Parallel 【数论+大数】

image 对于R这个式子,要R最小,那么分母就应该最大,让分母最大,那么让1/Ri的分母尽可能的小,数量尽可能多。本题的主要任务就是去找一个连续素数的乘积最大但小于等于n,证明如下图片 2019-10-20 20 18 18 031 因为要让分母尽可能小,那么素数从最小的2开始,然后依次乘以下一个素数,直到乘积最大但<=n时,此时就满足了让1/Ri的分母尽可能的小,数量尽可能多。且这些质数的乘积组合都是小于等于n的因子

关于大数,使用了一个封装好的大数模板,里面有加减乘除取余,还加入了运算符重载,虽然代码量挺大,但是的确好用 ```cpp

include <iostream>

include <algorithm>

include <cmath>

include <vector>

include <stdio.h>

include <cstring>

include <string>

define FOR(i, a, b) for(int i = a; i <= b; i++)

define _FOR(i, a, b) for(int i = a; i >= b; i–)

using namespace std; const int maxn = 1e6+10; typedef long long ll; struct BigInt { static const int M = 1000; int num[M + 10], len;

BigInt(int x) {
    clean();
    itoBig(x);
}
BigInt() {
    clean();
}

void clean(){
    memset(num, 0, sizeof(num));
    len = 1;
}

void read(){
    char str[M + 10];
    scanf("%s", str);
    len = strlen(str);
    FOR(i, 1, len)
        num[i] = str[len - i] - '0';
}

void write(){
    _FOR(i, len, 1)
        printf("%d", num[i]);
    //puts("");
}

void itoBig(int x){
    clean();
    while(x != 0){
        num[len++] = x % 10;
        x /= 10;
    }
    if(len != 1) len--;
}

bool operator < (const BigInt &cmp) const {
    if(len != cmp.len) return len < cmp.len;
    _FOR(i, len, 1)
        if(num[i] != cmp.num[i]) return num[i] < cmp.num[i];
    return false;
}

bool operator > (const BigInt &cmp) const { return cmp < *this; }
bool operator <= (const BigInt &cmp) const { return !(cmp < *this); }
bool operator != (const BigInt &cmp) const { return cmp < *this || *this < cmp; }
bool operator == (const BigInt &cmp) const { return !(cmp < *this || *this < cmp); }

BigInt operator + (const BigInt &A) const {
    BigInt S;
    S.len = max(len, A.len);
    FOR(i, 1, S.len){
        S.num[i] += num[i] + A.num[i];
        if(S.num[i] >= 10){
            S.num[i] -= 10;
            S.num[i + 1]++;
        }
    }
    while(S.num[S.len + 1]) S.len++;
    return S;
}

BigInt operator - (const BigInt &A) const {
    BigInt S;
    S.len = max(len, A.len);
    FOR(i, 1, S.len){
        S.num[i] += num[i] - A.num[i];
        if(S.num[i] < 0){
            S.num[i] += 10;
            S.num[i + 1]--;
        }
    }
    while(!S.num[S.len] && S.len > 1) S.len--;
    return S;
}

BigInt operator * (const BigInt &A) const {
    BigInt S;
    if((A.len == 1 && A.num[1] == 0) || (len == 1 && num[1] == 0)) return S;
    S.len = A.len + len - 1;
    FOR(i, 1, len)
        FOR(j, 1, A.len){
            S.num[i + j - 1] += num[i] * A.num[j];
            S.num[i + j] += S.num[i + j - 1] / 10;
            S.num[i + j - 1] %= 10;
        }
    while(S.num[S.len + 1]) S.len++;
    return S;
}

BigInt operator / (const BigInt &A) const {
    BigInt S;
    if((A.len == 1 && A.num[1] == 0) || (len == 1 && num[1] == 0)) return S;
    BigInt R, N;
    S.len = 0;
    _FOR(i, len, 1){
        N.itoBig(10);
        R = R * N;
        N.itoBig(num[i]);
        R = R + N;
        int flag = -1;
        FOR(j, 1, 10){
            N.itoBig(j);
            if(N * A > R){
                flag = j - 1;
                break;
            }
        }
        S.num[++S.len] = flag;
        N.itoBig(flag);
        R = R - N * A;
    }
    FOR(i, 1, S.len / 2) swap(S.num[i], S.num[len - i + 1]);
    while(!S.num[S.len] && S.len > 1) S.len--;
    return S;
}

BigInt operator % (const BigInt &A) const {
    BigInt S;
    BigInt P = *this / A;
    S = *this - P * A;
    return S;
}

}; int T; BigInt N,zero(0); vector<int> p; bool vis[maxn];

void init(){ int n = 1e6; for(int i =2;i<n/i;i++){ if(!vis[i]){ p.push_back(i); for(int j = 2*i;j<n;j+=i){ vis[j] = true; } } } }

BigInt gcd(BigInt a,BigInt b){ return b == zero? a:gcd(b,a%b); } int main(){ init(); cin>>T; while(T–){ N.read(); BigInt sum(1),son(1),mu(1); for(int i = 0;i<p.size();i++) { BigInt pi(p[i]), pi_1(p[i] + 1); sum = sum * pi; if (sum > N) break; son = son * pi_1; mu = mu * pi; } BigInt g = gcd(son,mu); son = son/g,mu = mu/g; swap(son,mu); son.write();putchar(‘/’);mu.write();putchar(‘\n’);

}
return 0;

} ```

Updated 21/10/2019 09:08

leetcode 周赛155

maninbule/contests

1200. 最小绝对差 【简单思维】

先对数组进行从小到大排序,两个元素的最小差就一定是排序后的某两个相邻两个元素的差。 所以,先遍历排序后的数组找到最小差,然后再遍历一遍数组,将差值为最小差的元素对放入vector里面就好,并且已经是排好序的 cpp class Solution { public: vector<vector<int>> minimumAbsDifference(vector<int>& arr) { vector<vector<int>> res; sort(arr.begin(),arr.end()); int dif = (int)1e9+7; for(int i = 1;i<arr.size();i++){ dif = min(dif,arr[i]-arr[i-1]); } for(int i = 1;i<arr.size();i++){ if(arr[i]-arr[i-1] == dif){ vector<int> ve = {arr[i-1],arr[i]}; res.push_back(ve); } } return res; } };

1201. 丑数 III 【容斥原理+二分】

对于一个x,可以通过容斥原理来判断他以及之前有多少个丑数 之前丑数的个数 = int cnt = x/a+x/b+x/c-x/ab-x/ac-x/bc+x/abc; ab为a、b的最小公倍数 这样就可以通过二分来算出第n各丑数

typedef long long ll;
class Solution {
public:
    ll a,b,c,ab,ac,bc,abc,n;
    bool judge(int x){
        int cnt = x/a+x/b+x/c-x/ab-x/ac-x/bc+x/abc;
        if(cnt<n) return false;
        return true;
    }
    ll lcm(ll a,ll b){
        return a*b/__gcd(a,b);
    }
    int nthUglyNumber(int n1, int a1, int b1, int c1) {
        n = n1,a = a1,b = b1,c = c1;
        ab = lcm(a,b),ac = lcm(a,c),bc = lcm(b,c),abc = lcm(c,ab);
        ll l = 1,r = 2e9+10,mid;
        while(l<r){
            mid = (l+r)/2;
            if(judge(mid)){
                r = mid;
            }else{
                l = mid+1;
            }
        }
        return l;
    }
};

1202. 交换字符串中的元素 【并查集】

假如可以互换的元素对有[2,3],[3,5] 那么[2,3,5]都是可以互换的,他们同属于一个联通块 所以我们需要使用并查集找出所有的联通块,对每个联通块里对应的字母进行排序,然后把排序后的字符串拷贝回原来的位置就行了。

const int maxn = 1e6+10;
class Solution {
public:
    int fa[maxn];
    map<int,vector<int>> ve;
    string str;
    int find(int x){
        if(x != fa[x])
            fa[x] = find(fa[x]);
        return fa[x];
    }
    void join(int x,int y){
        int fx = find(x),fy = find(y);
        if(fx!=fy) fa[fx] = fy;
    }

    void solve(int id){
        string s = "";int idx = 0;
        for(const auto &i:ve[id]){
            s+= str[i];
        }
        sort(s.begin(),s.end());
        for(const auto &i:ve[id]){
            str[i] = s[idx++];
        }
    }
    string smallestStringWithSwaps(string s, vector<vector<int>>& pairs) {
        str = s;

        for(int i = 0;i<s.size();i++) fa[i] = i;
        for(const auto &v:pairs){
            join(v[0],v[1]);
        }
        for(int i = 0;i<s.size();i++) find(i);
        for(int i = 0;i<s.size();i++){
            if(ve.count(fa[i]) == 0) ve[fa[i]] = vector<int>();
            ve[fa[i]].push_back(i);
        }
        for(int i = 0;i<s.size();i++){
            if(ve[i].size() == 0) continue;
            solve(i);
        }

        return str;
    }
};

1203. 项目管理 【拓扑排序】

这题需要多次拓扑排序,而我只会一次。实在不会写,之后变强了再补

Updated 20/10/2019 09:33

leetcode 周赛156

maninbule/contests

1207. 独一无二的出现次数 [基础]

先基础各个元素出现的次数,然后再对出现的次数进行计数,若有2个以上出现次数相同就为假,否则为真 ps: [-1000,1000] 可以加1000 映射到[0,2000],这样做的原因是数组下标为非负值

class Solution {
public:
    int coun[2500],coun2[2500];
    bool uniqueOccurrences(vector<int>& arr) {
        for(const auto & v:arr) coun[v+1000]++; //元素出现的次数
        for(int i = 0;i<=2000;i++) { 
            if(coun[i] ==0) continue;
            coun2[coun[i]]++; //出现的次数的次数
            if(coun2[coun[i]]>1) return false;
        }
        return true;
    }
};

1208. 尽可能使字符串相等 【双指针】

先假定一个开始坐标L,然后看他最大的结束位置R(剩余可用开销最小);然后重复(L-1,看R是否可以继续向右移动) 。这样就可以遍历完所有剩余可用开销最小的区间

例如: 1 2 3 4,L = 1,R = 4, len = R-L = 3 然后去掉1,剩余可用开销增大|s[1]-t[1]|,然后R看是否能用剩余可用开销继续向右移动

class Solution {
public:
    int equalSubstring(string s, string t, int maxCost) {
        int len = s.length(),res = 0,cur = maxCost;
        int i = 0,j = 0;
        for(;i<len;i++){
            while(j<len){
                if(s[j] == t[j]){ //相等不用开销
                    j++;
                }else if(cur - (int)abs(s[j]-t[j]) < 0){ //剩余可用开销已达到最小
                    break;
                }else{
                    cur -= (int)abs(s[j]-t[j]); 
                    j++;
                }
            }
            res = max(res,j-i);
            cur += (int)abs(s[i]-t[i]);//去掉开头,增加可用开销
        }
        return res;
    }
};

1209. 删除字符串中的所有相邻重复项 II 【栈】

用两个同步的栈,一个记录元素值,一个记录对应元素出现的次数。当栈顶元素出现的次数等于k,两个栈同时pop次数k。 我这题用的数组模拟栈,因为可以进行遍历,比较方便。 cpp class Solution { public: int sk[1000010],coun[1000010],top = -1; string removeDuplicates(string s, int k) { for(const auto &c:s){ if(top == -1 || sk[top] != c){ sk[++top] = c; coun[top] = 1; }else if(sk[top] == c){ sk[++top] = c;coun[top] = coun[top-1]+1; } if(coun[top] == k) for(int i = 1;i<=k;i++) top--; } string res = ""; for(int i = 0;i<=top;i++) res+=sk[i]; return res; } };

1210. 穿过迷宫的最少移动次数 【BFS】

第一次遇见带方向的BFS题,看leetcode题解上有人用的DP,其实差不多的 这题就是在普通的BFS上加了一些特定的移动规则,显得代码特别多,还有一个坑点就是对于一个坐标是可以访问两次的,一个是蛇横向访问,一个是蛇纵向访问。普通的BFS记录步数的数组是dp[x][y],但是这里需要再定义一个方向,dp[x][y][0]表示横向访问(x,y)的步数,dp[x][y][1]表示纵向访问(x,y)的步数

struct node{
    int x,y,st;
};
class Solution {
    public:
    int dp[110][100][2];//0水平 1竖直
    int N;
    vector<vector<int>> G;
    bool judge(int x,int y,int st){
        if(x<0 || x>=N || y<0 || y>=N || dp[x][y][st] != 0 || G[x][y] !=0) return false;
        return true;
    }
    int minimumMoves(vector<vector<int>>& grid) {
        N = grid.size(); G = grid;
        queue<node> q;
        q.push({0,1,0});
        dp[0][1][0] = 0;

        while(q.size()){
            node cur = q.front();q.pop();
            int x,y,st = cur.st;
            //rotate
            if(st == 0){
                x = cur.x+1,y = cur.y-1;
                if(judge(x,y,1) && grid[cur.x+1][cur.y] == 0){
                    q.push({x,y,1});
                    dp[x][y][1] = dp[cur.x][cur.y][st]+1;
                }
            }else{
                x = cur.x-1,y = cur.y+1;
                if(judge(x,y,0) && grid[cur.x][cur.y+1] == 0){
                    q.push({x,y,0});
                    dp[x][y][0] = dp[cur.x][cur.y][st]+1;
                }
            }
            //move
            if(st == 0){
                x = cur.x,y = cur.y+1; // right
                if(judge(x,y,st)){
                    q.push({x,y,st});
                    dp[x][y][st] = dp[cur.x][cur.y][st]+1;
                }
                x = cur.x+1,y = cur.y; //down
                if(judge(x,y,st) && grid[x][y-1] == 0){
                    q.push({x,y,st});
                    dp[x][y][st] = dp[cur.x][cur.y][st]+1;
                }
            }else{
                x = cur.x+1,y = cur.y; //down
                if(judge(x,y,st) ){
                    q.push({x,y,st});
                    dp[x][y][st] = dp[cur.x][cur.y][st]+1;
                }
                x = cur.x,y = cur.y+1; //right
                if(judge(x,y,st)&& grid[x-1][y] == 0){
                    q.push({x,y,st});
                    dp[x][y][st] = dp[cur.x][cur.y][st]+1;
                }
            }
        }
        return dp[N-1][N-1][0] == 0? -1:dp[N-1][N-1][0];
    }
};
Updated 19/10/2019 04:56

optimisers such as FTML in C++ package - am I just missing them or are they not exposed?

apache/incubator-mxnet

I can see from the documentation that MXNet now includes a wide range of modern optimisers, however, I can’t seem to access them from the C++ package.

Currently, I do: mx::Optimizer *opt = mx::OptimizerRegistry::Find("adam");

or similar, but I can’t do, for example: mx::Optimizer *opt = mx::OptimizerRegistry::Find("ftml");

Looking at optimizer.h and optimizer.hpp I can see that only a subset of the optimisers seem to be exposed to the C++ package. Is it actually already possible to try out the newer optimisers such as FTML, FTRL etc.. etc.. using the C++ package, or can this be added? I’m not too keen to try hacking it in myself as I lack sufficient awareness of the MXNet codebase.

Updated 21/10/2019 18:49 2 Comments

mxnet cpp-package complie failed with visual studio 2017

apache/incubator-mxnet

Description

I just get some problem while compiling mxnet1.15.1 and cpp_package on win10 with vs2017. The generated “op.h” file seems incorrect at functions like “multi_sgd_update” missing data type of parameter “lrs” and “wds” which should be “mxnet::Tuple<float>”. And this may cause compile failure of examples in cpp_packages.The information in outputs view is “argument "lrs” of operator “multi_sge_update” has unknown type “, required”“, while Running OpWrapperGenerator.py. This should be a bug because of not register data type like "mxnet::Tuple<T>” for MSVC.

What have you tried to solve it?

  1. As a temporary method, I just comment out Line744 and Line751 in “D:\DevEnvs\mxnet\apache-mxnet-src-1.5.1-incubating\include\mxnet\tuple.h”, which comment is “avoid low version of MSVC” but written as “#if !defined(_MSC_VER)” and “#endif”.

Environment info (Required)

win10x64 visual studio 2017 (_MSC_VER1912) cuda 10.1 cudnn 7.6.3

Updated 21/10/2019 18:50 2 Comments

leetcode 周赛149

maninbule/contests

1154. 一年中的第几天 【基础题】

先把平年的每月的天数写进数组,计算出天数,之后需要特判一下是否是闰年并且月份>=3,是的话就天数再+1 cpp class Solution { public: int d[13] = {0,31,28,31,30,31,30,31,31,30,31,30,31}; int dayOfYear(string date) { int days = 0; int year = stoi(date.substr(0,4)); // 讲字串转换成int int mouth = stoi(date.substr(5,2)); int day = stoi(date.substr(8,2)); if(((year%4 ==0 && year%100!=0) || (year%400 == 0) )&& mouth>=3) days++; //判断闰年+1的情况 for(int i = 1;i<mouth;i++) days += d[i]; days += day; return days; } };

1155. 掷骰子的N种方法 【入门dp】

我们定义DP[i][j]: 投了i个骰子,得分为j的方法数 假如f = 3 dp[0][0] = 1 则状态转移方程为:dp[i][j] = dp[i-1][j-1] + dp[i-1][j-2] + dp[i-1][j-3] 用三重循环就可以实现出来 cpp class Solution { public: typedef long long ll; const ll mod = 1e9+7; ll dp[50][2000]; int numRollsToTarget(int d, int f, int target) { dp[0][0] = 1; for(int i = 1;i<=d;i++){ for(int j = 1;j<=target;j++){ for(int k = 1;k<=f;k++){ if(j-k<0) continue; dp[i][j] = (dp[i][j]+dp[i-1][j-k])%mod; } } } return dp[d][target]; } };

1156. 单字符重复子串的最大长度 【双指针】

先map记录各字母出现的总次数,然后定义一个L,R 从左到右把数组扫一遍就行了。 以 “aaababa"为例:起点为L = R= 0,R扫到第二个b停止,此时扫过的长度为R-L; 然后 L = R = 第一个b的位置,再继续扫 也就是说,从一个起点开始扫,遇到第一个不等于起点元素的进行跳过,第二次不等于起点元素或者已经扫到数组末尾了就计算此次扫过的长度并更新最大长度。注意如果扫过的元素个数大于map中记录的,需要减一。 cpp class Solution { public: int maxRepOpt1(string text) { unordered_map<char,int> mp; for(auto c:text) mp[c]++; int l = 0,r = 0,newi = 0,len = text.length(); int res = 0; for(int i = 0;i<len;i = newi){ int tag = 0; for(int j = i;j<=len;j++){ if(j == len || (text[i] != text[j] && tag == 1)){ //扫一次的结束条件 int t = j-i; if(t > mp[text[i]]) t--; res = max(res,t); if(j == len) newi = len;//特判 break; } if(text[i]!=text[j] && tag == 0) tag = 1,newi = j; //第一次遇到不等于第一个元素的时候 } } return res; } };

Updated 17/10/2019 02:14

leetcode 周赛157

maninbule/contests

1217. 玩筹码 【简单思维】

移动到某个位置偶数步代价为0,奇数步代价为1。所以选定位置时,若选定的是奇数位置,那么代价为所有偶数位置的个数,选定的是偶数位置,那么代价为所有奇数位置的个数。 所有只要记录一下奇数和偶数的个数 ,然后小的那一个就行 cpp class Solution { public: int minCostToMoveChips(vector<int>& chips) { int res[2] = {0,0}; for(auto v:chips) res[v&1]++; return min(res[0],res[1]); } };

1218. 最长定差子序列 【入门dp】

从左到右依次遍历,假如当前的元素是x,那么此时更新以x结尾的定差序列 dp[x] = dp[x-dif]+1 (dif 为定差)。在更新过程中不断的取max就行,然后返回max。这个dp的存储可以用unordered_map来存。 cpp class Solution { public: int longestSubsequence(vector<int>& arr, int difference) { unordered_map<int,int> mp; int res = 0,dif = difference; for(const auto& v:arr){ mp[v] = mp[v-dif]+1; res = max(mp[v],res); } return res; } };

1219. 黄金矿工 【入门DFS】

遍历整个面板,对于一个不为0的位置开始DFS,DFS过程中需要加入访问标记+回溯,因为题目中移动过程中不可以回头。 cpp class Solution { public: bool vis[100][100]; int dir[4][2] = {-1,0,0,-1,1,0,0,1}; int N,M,res = 0; vector<vector<int>> grid2; int getMaximumGold(vector<vector<int>>& grid) { N = grid.size(),M = grid[0].size(); grid2 = grid; for(int i = 0;i<grid.size();i++){ for(int j = 0;j<grid[i].size();j++){ if(grid[i][j] != 0){ vis[i][j] = 1; DFS(i,j,grid[i][j]); vis[i][j] = 0; } } } return res; } void DFS(int i,int j,int cur){ res = max(res,cur); for(int d = 0;d<4;d++){ int x = i+dir[d][0],y = j+dir[d][1]; if(x<0 || x>=N || y<0 || y>=M || vis[x][y] == 1 || grid2[x][y] == 0) continue; vis[x][y]= 1; DFS(x,y,cur+grid2[x][y]); vis[x][y]= 0; } } };

1220. 统计元音字母序列的数目【入门DP】

和第2题一样,需要知道每个字母可以接在什么字母后面。 例如a可以接在i和u后面,更加一个长度,以a结尾的字符串就等于上长度以e,i,u结尾的个数总和 a: e,i,u e: a,i i: e,o o: i u: i,o cpp class Solution { public: const int mod = 1e9+7; int countVowelPermutation(int n) { long long dp[5],f[5],res =0; for(int i = 0;i<5;i++) dp[i] = 1;//n==1 的时候 while(--n){ f[0] = (dp[1]+dp[2]+dp[4])%mod; //更新dp值 f[1] = (dp[0]+dp[2])%mod; f[2] = (dp[1]+dp[3])%mod; f[3] = (dp[2])%mod; f[4] = (dp[2]+dp[3])%mod; for(int i = 0;i<5;i++) dp[i] = f[i];//拷贝回去 } for(int i = 0;i<5;i++) res = (res+dp[i])%mod;//计算总和 return res; } };

Updated 19/10/2019 04:17

Create Queue_DataStructure implementation in C++

Yet-Another-Series/Yet_Another_Algorithms_Repository
  • Please follow the Contributing Guidelines & naming conventions in the guidelines accordingly. 🙂
  • Following naming guidelines is important to maintain consistency.😊
  • Please NOTE: In case, same implementation of an algorithm is submitted by someone else and it gets accepted, then your contribution won’t be merged ( to avoid duplicates )
Updated 24/10/2019 17:22 3 Comments

Create Kadane_Algorithim implementation in C++

Yet-Another-Series/Yet_Another_Algorithms_Repository
  • Please follow the Contributing Guidelines & naming conventions in the guidelines accordingly. 🙂
  • Following naming guidelines is important to maintain consistency.😊
  • Please NOTE: In case, same implementation of an algorithm is submitted by someone else and it gets accepted, then your contribution won’t be merged ( to avoid duplicates )
Updated 24/10/2019 17:22 5 Comments

C++如何记录程序的运行时间

lc-leo/Notes

我们在运行一段C++程序时,有时需要知道运行这个程序花了多长时间.特别是当我们的程序结构很复杂,或者需要处理海量的数据时,高效快速的运行就显得尤为重要.判断一个程序是否高效,最直观的方法就是记录它的运行时间.记录时间一般有两种方法,一种是调用GetTickCount()函数,另一种是调用clock()计时函数.

GetTickCount()函数(不建议)

下面函数的介绍摘自百科: 它返回从操作系统启动到当前所经过的毫秒数,返回值以32位的双字类型DWORD存储,可以存储的最大值是(232-1) ms约为49.71天,因此若系统运行时间超过49.71天时,这个数就会归0.此外这个函数并非实时发送,而是由系统每18ms发送一次,因此其最小精度为18ms.

clock()函数(建议)

它返回的是从“开启这个程序进程”到“程序中调用clock()函数”之间的CPU时钟计时单元(clock tick)数.也就是程序一开始CPU就开始"滴答",直到程序运行到clock()函数,这时就会输出到此为止总共"滴答"了多少下,所以它返回的是一个int整型数,而不是时间.要想知道具体的时间,就必须知道你的CPU一秒钟"滴答"了多少下,而CLOCKS_PER_SEC正是这样一个常量. 首先要在程序中引入time.h这个头文件,然后在程序的结尾调用clock()函数: ```c++

include <time.h>   //引入头文件

int main() { clock_t stop; //定义clock_t变量 //////////////////////////程序具体内容 stop = clock(); //调用clock函数 cout<<“time = ”<<stop/CLOCKS_PER_SEC<<“s”<<endl; //输出时间(单位:s) } 若我们想要知道某一段程序的运行时间,就需要调用两次clock()函数,两次的时间差就是程序运行时间: c++

include <time.h>   //引入头文件

int main() { clock_t start,finish;   //定义clock_t变量 //////////////////////////program start = clock();    //开始时间 //////////////////////////program finish = clock(); //结束时间 cout<<“time = ”<<double(finish-start)/CLOCKS_PER_SEC<<“s”<<endl; //输出时间(单位:s) } ```

Linux下获得CLOCKS_PER_SEC数值的方法

本人在Linux平台下运行上面的程序时,出现CLOCKS_PER_SEC未定义的问题,可能在Linux平台中time.h文件中没有定义这个常量,那如何获得这个常量的数值呢?我用了一个很笨但直接的方法. 在程序中输出finish-start的数值,用秒表记录程序的运行时间(当然运行时间要尽量长一点),比如我的程序运行了65s,而finish-start的值在6.5e7附近,那么就可以得出CLOCKS_PER_SEC=1e6,将这个数值替换上即可.

Updated 21/10/2019 06:47

correctly reference second and subsequent embedded declarators

kythe/kythe

Currently, embedded declarators (tagged types without a visible forward declaration or definition) don’t generate consistent tnominal nodes, e.g.

//- @fwd ref StructFwd1?
void f(struct fwd* dev);
struct S {
  //- @fwd ref StructFwd2?
  struct fwd* dev;
};
//- @fwd ref StructFwd3?
void g(struct fwd* dev);

StructFwd1: EVar(0x0000000001976cc0 = App(vname, (#c#t, “”, “”, “”, c++))) StructFwd2: EVar(0x0000000001977490 = App(vname, (fwd:rat#c#t, “”, “”, “”, c++))) StructFwd3: EVar(0x0000000001977850 = App(vname, (fwd:rat#c#t, “”, “”, “”, c++)))

Those are all the same nominal type, but: 1) The declarator in the declaration of f is wrong (doesn’t include the name) 2) The declarator in the declaration of S is wrong (it includes the lexical parent, but shouldn’t) 3) The declarator in the declaration of g is okay (in that it references the same type as before).

Notably, clang typically treats the first embedded declarator for a given nominal type as “special” and will visit it as it would a regular declaration, which we can use to emit the requisite nominal nodes, rather than at NodeId construction time.

Updated 14/10/2019 21:26

emit named edges to tnominal nodes for C++ type declarations

kythe/kythe

Given:

class A;
class A;

using B = A*;

The two forward declarations of A will be unconnected. The A in the using alias will ref an arbitrary declaration and B will alias tapp<ptr, tnominal<A>> with no relationship between the various declarations of A. While the ref edge is a user-friendliness workaround, the lack of connection between the various redeclarations of A and their uses is confusing.

We should emit named edges from forward declarations to the resulting tnominal node, so the relationships are preserved without losing the uniqueness of the declaration nodes.

Updated 14/10/2019 20:59

Create binary_search implementation in C++

Yet-Another-Series/Yet_Another_Algorithms_Repository
  • Please follow the Contributing Guidelines & naming conventions in the guidelines accordingly. 🙂
  • Following naming guidelines is important to maintain consistency.😊
  • Please NOTE: In case, same implementation of an algorithm is submitted by someone else and it gets accepted, then your contribution won’t be merged ( to avoid duplicates )
Updated 31/10/2019 19:44 7 Comments

Create avl_tree implementation in C++

Yet-Another-Series/Yet_Another_Algorithms_Repository
  • Please follow the Contributing Guidelines & naming conventions in the guidelines accordingly. 🙂
  • Following naming guidelines is important to maintain consistency.😊
  • Please NOTE: In case, same implementation of an algorithm is submitted by someone else and it gets accepted, then your contribution won’t be merged ( to avoid duplicates )
Updated 21/10/2019 07:45 3 Comments

Create radix_sort implementation in C++

Yet-Another-Series/Yet_Another_Algorithms_Repository
  • Please follow the Contributing Guidelines & naming conventions in the guidelines accordingly. 🙂
  • Following naming guidelines is important to maintain consistency.😊
  • Please NOTE: In case, same implementation of an algorithm is submitted by someone else and it gets accepted, then your contribution won’t be merged ( to avoid duplicates )
Updated 22/10/2019 21:28 2 Comments

Create bubble_sort implementation in C++

Yet-Another-Series/Yet_Another_Algorithms_Repository
  • Please follow the Contributing Guidelines & naming conventions in the guidelines accordingly. 🙂
  • Following naming guidelines is important to maintain consistency.😊
  • Please NOTE: In case, same implementation of an algorithm is submitted by someone else and it gets accepted, then your contribution won’t be merged ( to avoid duplicates )
Updated 17/10/2019 13:18 5 Comments

"this" pointer(this指针) in C++

happy-yuxuan/blogs

“this” pointer(this指针) in C++

  • 每一个类的对象来说,成员属性是在每个对象是一个是副本。
  • 而对于每个对象是共享一个类的成员函数。(this是解决区分谁调用了这个成员函数)

通俗来说,this指针是用来区分哪一个对象。this指针作为隐藏参数传递给所有非静态成员变量函数调用,而且可以用作所有非静态函数体内部的局部变量。

静态函数是不能访问有this指针的,他是属于类的。

作用1: 初始化对象的成员变量(本地变量与成员变量重名的时候,当然不重名的时候也可以使用)

#include<iostream> 
using namespace std; 

/* local variable is same as a member's name */
class Test 
{ 
private: 
   int x; 
public: 
   void setX (int x) 
   { 
       // The 'this' pointer is used to retrieve the object's x 
       // hidden by the local variable 'x' 
       this->x = x; 
   } 
   void print() { cout << "x = " << x << endl; } 
}; 

int main() 
{ 
   Test obj; 
   int x = 20; 
   obj.setX(x); 
   obj.print();   // 输出结果:x = 20
   return 0; 
}

作用2: 返回调用对象的引用(从而可以链式设置等)

/* Reference to the calling object can be returned */ 
Test& Test::func () 
{ 
   // Some processing 
   return *this; 
}  

注意这里成员函数func返回的引用 & ```c++

include<iostream>

using namespace std;

class Test { private: int x; int y; public: Test(int x = 0, int y = 0) { this->x = x; this->y = y; } Test &setX(int a) { x = a; return this; } // 返回对象引用 Test &setY(int b) { y = b; return this; } // 返回对象引用 void print() { cout << “x = ” << x << “ y = ” << y << endl; } };

int main() { Test obj1(5, 5);

// Chained function calls. All calls modify the same object // as the same object is returned by reference obj1.setX(10).setY(20); // 链式设置

obj1.print(); // 输出结果:x = 10 y = 20 return 0; } ```

作用3: 删除对象

#include<iostream> 
using namespace std; 

class Test 
{ 
private: 
  int x; 
  int y; 
public: 
  Test(int x = 0, int y = 0) { this->x = x; this->y = y; } 
  void setX(int a) { x = a; } 
  void setY(int b) { y = b; } 
  void destroy()  { delete this; }  // 删除这个对象调用各个成员变量的析构方法
  void print() { cout << "x = " << x << " y = " << y << endl; } 
}; 

int main() 
{ 
  Test obj; 
  obj.print();   // print()一定要在destroy之前
  obj.destroy();   // 删除掉了obj所指的对象
  return 0; 
} 

刷LeetCode时候规范用法

把函数参数赋值给this->成员属性,这样可以再任何地方使用成员属性,就不用作为引用参数传入了。

class Solution {
private:
    vector<vector<int>> a;  // 自己定义成员变量
    int n, m;  // // 自己定义成员变量

    void solve() {
        a[0][0] = 1;
        // ... 正常使用a, m, n
    }

public:  
    int getMaximumGold(vector<vector<int>>& a) {
        this->a = a;    // 把本地变量赋值给同名的数据成员(data member)
        this->n = a.size(), this->m = a[0].size();  // // 把本地变量赋值给同名的数据成员(data member)

        solve();
        // 操作逻辑...

        //return ans;
    }
};

参考文献

geeksforgeeks

Updated 14/10/2019 09:31

Analista de Sistemas SR (.NET) na [CAPGEMINI]

devssa/onde-codar-em-salvador

<!–

POR FAVOR, SÓ POSTE SE A VAGA FOR PARA SALVADOR E CIDADES VIZINHAS!

Use: “Desenvolvedor Front-end” ao invés de “Front-End Developer” \o/

Exemplo: [JAVASCRIPT] [MYSQL] [NODE.JS] Desenvolvedor Front-End na [NOME DA EMPRESA]

–>

Analista de Sistemas Sênior .NET

Local

  • Salvador

Requisitos

Obrigatórios: - Backend, Multi-Threaded Programming, Multi-tier Programming, Object Oriented Programming, JSON, XML, LINQ, Async Programming, Nuget Packages

  • Some knowledge on NOSQL databases is desirable Be Technical Reference for Other Developers
  • Solid Technical Background with HTML Applications (javascript / HTML)
  • Some knowledge on knockout.js, angular.js, sass or webcomponents is desirable
  • Some Experience with Agile Teams (Lean Kanban preferable)
  • Solid Experience with Technical Specification and Architecture Diagrams
  • Some Experience with GIT (or Mercurial)
  • Some Experience on migration of legacy code (C, C++) and refactoring code
  • Some Experience with Unit Testing
  • Solid Write and Read Proficiency in English and Portuguese

CAPGEMINI

Como se candidatar

  • Interessados, encaminhar currículo para: maria-carolina.ferreira@capgemini.com
Updated 13/10/2019 11:17

Review all the files

orestotel/hacktoberfest-ProjectCPlusPlus

To organize the repository, there should be done a review of all files. Every file should be given a status: - #works - #bug or - #TODO The status should be written after the () gaps. E.G:

  1. somefile.cpp ( description ) #STATUS

Every file should be compiled before giving it a specific status. If it is unclear, what status should you assing to that file, describe that in the description and add #TODO tag.

Updated 15/10/2019 11:35

type error with list += and or nothing types

qorelanguage/qore

ex: dnichols@manatee:~/src/qore/git/qore/qlib/DataProvider$ qore -ne 'list<hash<auto>> l; hash h = {}; l += h; printf("%y\n", l);' [{}] dnichols@manatee:~/src/qore/git/qore/qlib/DataProvider$ qore -ne '*list<hash<auto>> l; hash h = {}; l += h; printf("%y\n", l);' unhandled QORE System exception thrown in TID 1 at 2019-10-07 16:46:11.261817 Mon +02:00 (CEST) at <command-line>:1 (Qore builtin code) RUNTIME-TYPE-ERROR: <lvalue for += operator> expects type '*list<hash<auto>>', but got type 'hash' instead

Updated 07/10/2019 14:47

node-ffi 实现node或者electron调用DLL文件

cisen/blog
  • https://github.com/node-ffi/node-ffi
  • https://juejin.im/post/5b58038d5188251b186bc902
  • https://www.jianshu.com/p/7d33a21e43d3

说明

在nodejs里有两种方式去调用dll文件:

  • 第一种:如果有c++的开发经验就可以直接看 Electron使用NodeJS扩展模块调用DLL貌似也是官方推荐的方法,nodejs官网也提供了相关文档 文档链接

  • 第二种:通过node-ffi模块,以下内容都是讲通过这个模块去调用的,比较适合只做前端开发的同学

在nodejs/elctron中,可以通过node-ffi,通过Foreign Function Interface调用动态链接库,俗称调DLL,实现调用C/C++代码,从而实现许多node不好实现的功能,或复用诸多已实现的函数功能。

node-ffi是一个用于使用纯JavaScript加载和调用动态库的Node.js插件。它可以用来在不编写任何C ++代码的情况下创建与本地DLL库的绑定。同时它负责处理跨JavaScript和C的类型转换。

与Node.js Addons相比,此方法有如下优点: 1. 不需要源代码。 2. 不需要每次重编译nodeNode.js Addons引用的.node会有文件锁,会对`electron应用热更新造成麻烦。 3. 不要求开发者编写C代码,但是仍要求开发者具有一定C的知识。 复制代码 缺点是: 1. 性能有折损 2. 类似其他语言的FFI调试,此方法近似黑盒调用,差错比较困难。

Updated 07/10/2019 13:28

Go语言的接口设计哲学

PandyYang/Blog

侵入式接口

Go语言的接口设计与其他语言不太一样. 在Go语言出现之前,接口主要作为不同组件之间的契约存在。对契约的实现是强制的,你 必须声明你的确实现了该接口。为了实现一个接口,你需要从该接口继承: interface IFoo { void Bar(); } class Foo implements IFoo { // Java文法 // ... } class Foo : public IFoo { // C++文法 // ... } IFoo* foo = new Foo; 即使另外有一个接口IFoo2实现了与IFoo完全一样的接口方法甚至名字也叫IFoo只不过位于不同的名字空间下,编译器也会认为上面的类Foo只实现了IFoo而没有实现IFoo2接口。这类接口我们称为侵入式接口。“侵入式”的主要表现在于实现类需要明确声明自己实现了某个接口。这种强制性的接口继承是面向对象编程思想发展过程中一个遭受相当多置疑的特性。我们接下来讨论一下为什么这是个问题,以及为何Go语言的接口设计是一个更合适的选择。 设想我们现在要实现一个简单搜索引擎(SE),它需要依赖两个模块,一个是哈希表(HT), 一个是HTML分析器(HtmlParser)。 搜索引擎的实现者认为,SE对HT的依赖是确定性的,所以不需要在SE和HT之间定义接口,而是直接通过import(或者include)的方式使用HT;而模块SE对HtmlParser的依赖是不确定的,未来可能需要有WordParser、PdfParser等模块来替代HtmlParser,以达到不同的业务要求。为此,他定义了SE和HtmlParser之间的接口,在模块SE中通过接口调用方式间接引用模块HtmlParser。 应当注意到,接口的需求方是SE,只有SE才知道接口应该定义成什么样子,但是接口的实现方是HtmlParser。基于模块设计的单向依赖原则,模块HtmlParser实现自身的业务时,不应该关心某个具体使用方的要求。HtmlParser在实现的时候,甚至还不知道未来有一天SE会用上它。期望模块HtmlParser能够知道需求方需要的所有接口,并提前声明实现这些接口是不合理的。 同样的道理发生在SE自己身上。SE并不能够预计未来会有哪些需求方会用到自己,并且实现它 们所要求的接口。 这个问题在设计标准库时变得更加突出,比如我们实现了File类(这里我们用Go语言的文 法来描述要实现的方法,请忽略文法上的细节),它有下面这些方法: Read(buf []byte) (n int, err error) Write(buf []byte) (n int, err error) Seek(off int64, whence int) (pos int64, err error) Close() error 那么,到底是应该定义一个IFile接口,还是应该定义一系列的IReader、IWriter、ISeeker、ICloser接口,然后让File从它们继承好呢?脱离了实际的用户场景,讨论这两个设计哪个更好并无意义。问题在于,实现File类的时候,我怎么知道外部会如何用它呢? 因为这种不合理的设计,实现JAVA,C#类库中的每个类的时候都要纠结一下两个问题: - 提供哪些接口好一点? - 两个类实现了相同的接口,那么应该将接口放在哪个包中?

Go语言中的非侵入式接口

**接口 在go语言中一个类只需要实现了接口要求的所有函数 就说这个类实现了该接口**
type File struct {

}

//func (f *File) Read(buf []byte) (n int,err error){}
//func (f *File) Write(buf []byte) (n int,err error){}
//func (f *File) Seek(off int64,whence int) (pos int64,err error){}
//func (f *File) Close() error {}

//定义一个File类,并实现有Read(),Write(),Seek(),Close()等方法,设想有如下接口
type IFile interface {
    Read(buf []byte) (n int, err error)
    Write(buf []byte) (n int, err error)
    Seek(off int64, whence int) (pos int64, err error)
    Close() error
}
type IReader interface {
    Read(buf []byte) (n int, err error)
}
type IWriter interface {
    Write(buf []byte) (n int, err error)
}
type ICloser interface {
    Close() error
}

File类没有从这些接口继承,甚至不知道这些接口的存在,但是File类实现了这些接口,可以进行赋值 var file1 IFile = new(File) var file2 IReader = new(File) var file3 IWriter = new(File) var file4 ICloser = new (File) Go语言的非侵入式接口,看似只是做了很小的文法调整,实则影响深远。 其一,Go语言的标准库,再也不需要绘制类库的继承树图。你一定见过不少C++、Java、C# 类库的继承树图。在Go中,类的继承树并无意义,你只需要知道这个类实现了哪些方法,每个方法是啥含义就足够了。 其二,实现类的时候,只需要关心自己应该提供哪些方法,不用再纠结接口需要拆得多细才合理。接口由使用方按需定义,而不用事前规划。 其三,不用为了实现一个接口而导入一个包,因为多引用一个外部的包,就意味着更多的耦合。接口由使用方按自身需求来定义,使用方无需关心是否有其他模块定义过类似的接口。

Updated 07/10/2019 02:17

Defer(?) operations

SFTtech/nyan

Example:


Archer(Unit):
    firerate : float = 0

Crossbowman(Archer)
    firerate = 12

Longbowman(Archer):
    firerate = 10


ThumbRing(Technology):
    ThumbRing1<Longbowman>():
        firerate *= 1.2
    ThumbRing2<Crossbowman>():
        firerate *= 1.2

    patches = {ThumbRing1, ThumbRing2}

This is the correct solution so far, am I wrong ?

If you try to do this:

ThumbRing<Archer>(Technology):
    firerate *= 1.2

Then the stack of calculation would be: firerate = 0 firerate *= 1.2 firerate = 10 V firerate = 10

However there could be something like defer which would move the operation to the end: ThumbRing<Archer>(Technology): firerate defer *= 1.2

And then there would be two stucks: firerate = 0 defer firerate *= 1.2 firerate = 10 V firerate = 0 firerate = 10 firerate *= 1.2 V firerate = 10 firerate *= 1.2 V firerate = 12

Updated 19/10/2019 12:11 1 Comments

Add AI migration to auto-evo

Revolutionary-Games/Thrive

AI species should be able to spread to new patches in an auto-evo step. There is a bit of code already for this, but the actual moving is not implemented. And also an algorithm needs to be added that generates the moves. There’s some discussion happening how the moving should work: https://forum.revolutionarygamesstudio.com/t/population-system-species-splitting/494/31?u=hhyyrylainen

Updated 05/10/2019 10:04

Commas

SFTtech/nyan

Commas between a collection elements and parents are not needed in order for the nyan to be interpreted. So they could be optional.

LeggedCombineCitadel(Building, Unit):
    hp = 1000
    creates = {OverwatchSoldier, Strider}

LeggedCombineCitadel(Building, Unit):
    hp = 1000
    creates = { OverwatchSoldier Strider }

LeggedCombineCitadel ( Building Unit ) :
    hp = 1000
    creates = { OverwatchSoldier Strider }

It looks weird but why not…

Updated 06/10/2019 14:40 2 Comments

Tests

SFTtech/nyan

A suggestion for testing (what I am using in jnyan):

tests
├── 001
│   ├── main.nyan
│   └── sim
│       ├── 001.txt
│       └── 002.txt
└── 002
     ├── engine.nyan
     ├── main.nyan
     └── sim
         ├── 001.txt
         └── 002.txt

Where the root folders are test cases with loaded file being the main.nyan (which may include import statements) and in the sim (= simulation) folders there are files with commands in order to simulate a scenario. Every line is command, mainly assert like commands but also execution of patches.

// optionally set a namespace
namespace main

// asserts
Barracks creates    == [main.Jedi, main.Clone]
Barracks hp         == 4000
Barracks model      == ./models/m1.dat

// assert number of members
Unit     # 3
Infantry # 3

Jedi   hp  == 300
Master hp  == 480

// apply a patch
patch ArmorUpgrade

Jedi   hp  == 310
Master hp  == 490

Source: jnyan/src/test/resources/tests/000

Updated 06/10/2019 14:44 3 Comments

Dict and dict operations

SFTtech/nyan

For openage dicts will me very useful in order to deal with what in the engine are called ResourceBundle.

In nyan creating a set of something like ResourceAmount would be very verbose, but with dict(Resource, float) a collection of resources can encoded very nicely:

Unit():
    cost : dict(Resource, float)

Knight(Unit):
    cost = {Food: 70, Gold: 75}

However, there is a need to be able to access the dict values separately. I would suggest something like that:

CheaperKnights<Knight>():
    cost[Gold] -= 20

Sidenote: Time (training time) could also be modeled as a Resource and be included in the cost

Updated 05/10/2019 23:28 3 Comments

超现实C++

neonmori/neonmori.github.io

C++ 支持Elvis操作: c++ int a = 0; int b = 10; int c = a ?: b; std::cout << c << std::endl;

C++支持字符范围: ```c++ char ch = ‘3’;

switch (ch) { case ‘\0’: std::cout << “ZERO” << std::endl; break; case ‘0’ … ‘9’: std::cout << “NUMBER” << std::endl; break; case ‘a’ … ‘z’: std::cout << “ALPHA” << std::endl; break; default: std::cout << “OTHER” << std::endl; break; } ```

Updated 04/10/2019 22:24

C++ `new(p, f) T[s]` 调用

neonmori/neonmori.github.io
new(p, f) T[s] -> operator new[](sizeof(T) * s + x, p, f)

Here, each instance of x is a non-negative UNSPECIFIED value representing array allocation overhead; the result of the new-expression will be offset by this amount from the value returned by operator new[]. This overhead may be applied in all array new-expressions, including those referencing the library function operator new[](std::size_t, void*) and other placement allocation functions. The amount of overhead may vary from one invocation of new to another.

Updated 04/10/2019 22:20

Desenvolvedor Java/PL/SQL Jr na [EISA]

devssa/onde-codar-em-salvador

<!–

POR FAVOR, SÓ POSTE SE A VAGA FOR PARA SALVADOR E CIDADES VIZINHAS!

Use: “Desenvolvedor Front-end” ao invés de “Front-End Developer” \o/

Exemplo: [JAVASCRIPT] [MYSQL] [NODE.JS] Desenvolvedor Front-End na [NOME DA EMPRESA]

–>

Desenvolvedor Java/PL/SQL Jr

Atividades

  • Desenvolvimento, testes e execução de scripts para correção e manipulação de dados em ambiente de produção (BackOffice);
  • Concepção, modelagem e programação de módulos de software relacionados à customização das regras de negócio da solução de sistemas;
  • Atuação em escalas de suporte a testes planejados;
  • Realizar análise de correção de incidentes e defeitos de software.

Local

  • Tecnocentro - Salvador/ BA

Benefícios

  • Vale- Refeição e/ ou Alimentação;
  • Além dos benefícios de alimentação e refeição, cedemos espaço para almoço com copa;
  • Vale- transporte;
  • Assistência médica;
  • Assistência odontológica;
  • Bonificação de férias;
  • Seguro de vida;
  • Participação nos lucros e resultados;
  • Frutas e biscoitos;
  • Home Office;
  • Horário flexível.

Requisitos

Obrigatórios: - Formação superior completa em Engenharia da Computação, Análise de Sistemas, Ciência da Computação e áreas afins; - Programação orientada a objetos (Java); - Conhecimento em banco de dados Oracle e desenvolvimento PL/SQL; - Experiência em análise de correção de incidentes e defeitos de software; - Experiência com concepção, modelagem e programação de módulos de software; - Desejável conhecimento nas linguagens C, C++e Shell Script.

EISA

A Ericsson Inovação S.A é uma combinação singular de skills e competências na entrega de serviços profissionais na área de Suporte aos negócios e a Operação, atuamos com uma das maiores operações de telecomunicações do mundo, além de ser certificada pelo Great Place to Work, como uma das melhores empresas para se trabalhar no segmento de tecnologia da informação.

Como se candidatar

LINK: https://jobs.kenoby.com/eisa/job/desenvolvedor-javaplsql-jr/5d653aad20fe6d6676cb6fee

Updated 02/10/2019 20:19

Directors code yields badly formatted comparison operators

swig/swig

When trying to wrap a C++ class definition which contains a virtual comparison operator for “==”, “>=”, “<=”, or “!=”, then the generated directors code contains additional spaces around each “=” yielding invalid operator names, eg. “operator = = ”.

Here are the input class definition, the swig command, and the resulting code. The used swig version is current git HEAD (4.0.2 - 97a107ed256b308d).

Input class definition OperatorEQTest.hpp: ```cpp

pragma once

class OperatorEQTest { public: virtual ~OperatorEQTest() {}; virtual bool operator ==(const OperatorEQTest&) const; }; Interface file **OperatorEQTest.i**: cpp %module(directors=“1”) “OperatorEQTest” %{

include “OperatorEQTest.hpp”

%} %feature(“director”);

include “OperatorEQTest.hpp”

**swig command**:

swig -Wall -ruby -c++ -includeall OperatorEQTest.i ```

The interesting part of the resulting code in OperatorEQTest_wrap.h cpp class SwigDirector_OperatorEQTest : public OperatorEQTest, public Swig::Director { public: SwigDirector_OperatorEQTest(VALUE self); virtual ~SwigDirector_OperatorEQTest(); virtual bool operator = = (OperatorEQTest const &arg0) const; }; and in OperatorEQTest_wrap.cxx cpp [...] bool SwigDirector_OperatorEQTest::operator = = (OperatorEQTest const &arg0) const { bool c_result = SwigValueInit< bool >() ; VALUE obj0 = Qnil ; VALUE SWIGUNUSED result; [...]

I noticed that when I apply the following change the error is gone. However my knowledge about the “historic reason” for adding spaces around “=” is nonexistent, so I cannot say for sure that this solution is valid under all conditions or for satisfying all existing test cases which might expect such spaces in other places. ```diff diff –git a/Source/Modules/directors.cxx b/Source/Modules/directors.cxx index a91d5fd9a..c9de1df74 100644 — a/Source/Modules/directors.cxx +++ b/Source/Modules/directors.cxx @@ -177,7 +177,7 @@ String Swig_method_decl(SwigType return_base_type, SwigType *decl, const_Strin

// Reformat result to how it has been historically Replaceall(result, “,”, “, ”); - Replaceall(result, “=”, “ = ”); + //Replaceall(result, “=”, “ = ”);

Delete(args_string); Delete(popped_decl); ```

Updated 17/10/2019 20:28 4 Comments

ANALISTA PLENO DE DESENVOLVIMENTO C/C++ na [RECONCAVO]

devssa/onde-codar-em-salvador

<!–

POR FAVOR, SÓ POSTE SE A VAGA FOR PARA SALVADOR E CIDADES VIZINHAS!

Use: “Desenvolvedor Front-end” ao invés de “Front-End Developer” \o/

Exemplo: [JAVASCRIPT] [MYSQL] [NODE.JS] Desenvolvedor Front-End na [NOME DA EMPRESA]

–>

:star: :star: :star: <kbd>⇥ SALVADOR ↩</kbd> :star: :star: :star:

ANALISTA PLENO DE DESENVOLVIMENTO C/C++

:star: :star: :star: <kbd>⇥ SALVADOR ↩</kbd> :star: :star: :star:

Requisitos

Obrigatórios: - Levantamento de Requisitos - Desenvolvimento nas linguagens C/C++ - Modelagem de Sistemas - Documentação de Sistemas

Como se candidatar :exclamation:

ENVIAR CURRICULO PARA rh@reconcavo.org.br

Updated 01/10/2019 23:35

Likely memory corruption error in bsf

Revolutionary-Games/Thrive

With 0.4.2 released we are starting to get reports from people who have crashes during gameplay (or while switching to or from the editor), inside bsf (only logged in thrive developers can see the log files, and one of the reports is marked as non-public): https://dev.revolutionarygamesstudio.com/report/38 https://dev.revolutionarygamesstudio.com/report/39 https://dev.revolutionarygamesstudio.com/report/45

From a quick comment from bsf discord this seems like something else causes memory corruption. Hopefully it is not our fault and rather some really rare asset loading race condition corrupting bsf memory.

Would be really nice to get this fixed in order to improve the stability of the game.

Updated 05/11/2019 08:24 5 Comments

Boxing game to be developed

orestotel/hacktoberfest-ProjectCPlusPlus

Random boxing game for beginners.

Description: 1) User gets greeted and enters his name 2) User enters the name of the gym 3) User enters the name of the fighter. Randomize Fighter stats; Record a fighter. 4) User is told that today is the first fight night 5)Match starts Return both fighters stats 6) Match continues with description of random actions(“Threw a punch”, “defended”, “blocked a jab” etc.) 7) Record fighter statistics (Win/Lose/Draw count) and return it to the user. 8)Ask to play another match

Default fighter stats: STR, DEF, DEX, STAMINA, HEALTH STR - 1; Damage of the punches DEF - 1; Amount of blocked damage DEX - 1; Chance to block STAMINA - 0.62; Chance to attack HEALTH - 20; health of the fighter.

Attack-Block action queries: Attack:

  • “Threw a jab for (STR1) damage” (Probability 0.5STAMINA);
  • “Threw a punch for (STR*2) damage”;
  • “Threw a hook for (STR*5) damage”

The rest is to be described or it’s up to you since you already understand the concept to program it well.

This text was copied from the project description since it both well describes the issue and the project.

Updated 15/10/2019 19:27 3 Comments

Fork me on GitHub