text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
Return to Installation by tomkis_ » Sun Jun 14, 2009 3:36 pm by ThomasEgi » Sun Jun 14, 2009 6:33 pm by rdb » Mon Jun 15, 2009 1:10 am python makepanda/makepanda.py --everything --installer BuildRequires: python-devel bison flex libtiff-devel libpng-devel gtk2-devel openssl-devel gcc-c++ libstdc++-devel freetype2-develBuildRequires: libjpeg-devel mesa-libOSMesa-devel libXft-devel mesa-libGL-devel mesa-libGLU-devel%ifarch x86_64 amd64 ppc64 s390xBuildRequires: lib64jpeg62-devel lib64mesagl1-devel lib64mesaglu1-devel lib64openssl0.9.8-devel lib64ssh2-devel%endif%ifarch i386 i486 i586 i686BuildRequires: libjpeg62-devel libmesagl1-devel libmesaglu1-devel libopenssl0.9.8-devel libssh2-devel%endif by rdb » Sun Jul 19, 2009 10:37 am by WWTLF » Wed Aug 12, 2009 10:57 am pro-rsoft wrote:For the record, theres are now a Fedora 11 repo for Panda: by rdb » Wed Aug 12, 2009 11:48 am by WWTLF » Wed Aug 12, 2009 1:51 pm pro-rsoft wrote:No, I had to shut them down because of legal issues.Maybe someone around still has a copy, otherwise, you'll have to build it yourself. by scuac » Wed Nov 11, 2009 3:23 pm rdb wrote:Hmm, maybe the packages are named differently in Fedora 11.You can try to download the .src RPM for fc10 and build it - or, download the source tar.gz of Panda3D and build an RPM yourself.It's as easy as untarring the source, and then invoking:Code: Select allpython makepanda/makepanda.py --everything --installerThat will, if it succeeds, generate an .rpm file which you can install. RPMd by rdb » Wed Nov 11, 2009 4:02 pm by skeptic » Wed Nov 11, 2009 4:15 pm rdb wrote:No, I had to shut them down because of legal issues. by scuac » Wed Nov 11, 2009 5:14 pm rdb wrote:Hm, that sounds troubling. How did you compile Panda3D? Did you build it via the source RPM, or by running makepanda with --everything --installer ? by rdb » Thu Nov 12, 2009 12:47 am skeptic wrote:????? by rdb » Thu Nov 12, 2009 12:52 am scuac wrote:I downloaded the 1.6.2 tar file for linux 64bit from panda3d.org and used the makepanda with --everything --installer command. python makepanda/installpanda.py --prefix /usr/local by scuac » Thu Nov 12, 2009 11:37 am rpmbuild --define '_rpmdir /home/scuac/Download/panda3d-1.6.2' -bb panda3d.spec rpmbuild --root /home/scuac/panda3d-1.6.2 --buildroot linuxroot -bb panda3d.spec import direct.directbase.DirectStartrun() $ python test.py DirectStart: Starting the game.Traceback (most recent call last): File "test1.py", line 1, in <module> import direct.directbase.DirectStart File "/usr/share/panda3d/direct/directbase/DirectStart.py", line 3, in <module> from direct.showbase import ShowBase File "/usr/share/panda3d/direct/showbase/ShowBase.py", line 10, in <module> from pandac.PandaModules import * File "/usr/share/panda3d/pandac/PandaModules.py", line 1, in <module> from libpandaexpressModules import * File "/usr/share/panda3d/pandac/libpandaexpressModules.py", line 1, in <module> from extension_native_helpers import * File "/usr/share/panda3d/pandac/extension_native_helpers.py", line 75, in <module> Dtool_PreloadDLL("libpandaexpress") File "/usr/share/panda3d/pandac/extension_native_helpers.py", line 69, in Dtool_PreloadDLL raise ImportError, messageImportError: DLL loader cannot find libpandaexpress. by rdb » Thu Nov 12, 2009 12:32 pm by skeptic » Thu Nov 12, 2009 1:51 pm rdb wrote:skeptic wrote:????? restriction on ffmpeg use is a no-go for me. by rdb » Thu Nov 12, 2009 2:08 pm by skeptic » Thu Nov 12, 2009 2:19 pm rdb wrote:We're linking to ffmpeg and including it's header files, so that means that the Panda3D library is a derivative work of ffmpeg. by scuac » Thu Nov 12, 2009 3:09 pm rdb wrote:A few checks to verify:(1) Does the file /usr/lib/panda3d/libpandaexpress.so exist?(2) Does the file /etc/ld.so.conf.d/panda3d.conf exist and contain the right path to the Panda3D libraries?(3) Is the LD cache updated (e.g. does "sudo ldconfig" fix the problems)? by rdb » Thu Nov 12, 2009 3:21 pm skeptic wrote:It makes me wonder how this will affect any/all future binary distributions including windows and such, as well as commercial games. For example, what does Disney do? by skeptic » Fri Nov 13, 2009 10:25 am by dreamer_ » Sat Nov 14, 2009 10:14 pm by rdb » Sun Nov 15, 2009 2:28 am by madbad » Sun Nov 15, 2009 9:13 am scuac wrote:hi, I just tried creating the RPM for Fedora 11 (downloaded the source from here). I tried the command above, and everything seems to have compiled correctly (except for some warnings saying that _XOPEN_SOURCE was redefined). But when it gets to the part where it is building the RPM it fails with the following error list:Code: Select allRPMdI checked and /home/scuac/rpmbuild/BUILDROOT is empty. Should I put those files there myself from somewhere else?Thanks [madbad@localhost Fireflies]$ echo $PATH/usr/lib64/qt-3.3/bin:/usr/kerberos/bin:/usr/lib64/ccache:/usr/local/bin:/usr/bin:/bin:/usr/local/sbin:/usr/sbin:/sbin:/home/madbad/bin:/home/madbad/bin:/home/madbad/Scrivania/panda3d-1.6.2/built/bin:/home/madbad/Scrivania/panda3d-1.6.2/built/bin:/home/madbad/Scrivania/panda3d-1.6.2/built:/home/madbad/Scrivania/panda3d-1.6.2[madbad@localhost Fireflies]$ python ./Tut-Fireflies.pyTraceback (most recent call last): File "./Tut-Fireflies.py", line 6, in <module> import direct.directbase.DirectStartImportError: No module named direct.directbase.DirectStart[madbad@localhost Fireflies]$ by scuac » Tue Dec 01, 2009 11:55 am makepanda/makepanda.py --everything $ python Tut-Carousel.py Traceback (most recent call last): File "Tut-Carousel.py", line 18, in <module> import direct.directbase.DirectStartImportError: No module named direct.directbase.DirectStart by rdb » Tue Dec 01, 2009 1:13 pm by scuac » Tue Dec 01, 2009 2:18 pm rdb wrote:Hum, the instructions in INSTALL-MK are a bit outdated. You shouldn't put "built" anywhere in the system paths.Instead, invoke makepanda with the --installer option. Alternatively, you can invoke installpanda (which works like "make install"):Code: Select allpython makepanda/installpanda.py --prefix /usr/localThen, invoke "ldconfig" as root and you should be all set. by scuac » Tue Dec 01, 2009 2:23 pm $ makepanda/makepanda.py --installerStoring dependency cache.Elapsed Time: 0 secCannot build installer without python $ pythonPython 2.6 (r26:66714, Jun 8 2009, 16:07:29) [GCC 4.4.0 20090506 (Red Hat 4.4.0-4)] on linux2Type "help", "copyright", "credits" or "license" for more information.>>> by madbad » Tue Dec 01, 2009 3:15 pm cvs -d :pserver:anonymous@panda3d.cvs.sourceforge.net:/cvsroot/panda3d co panda3d makepanda/makepanda.py --installer --everything rpmbuild --root /home/madbad/Development/svn/panda/panda3d --buildroot linuxroot -bb panda3d.spec su root yum localinstall /home/madbad/rpmbuild/RPMS/x86_64/panda3d-1.7.0-1.x86_64.rpm --nogpgcheck /etc/Config.prc plugin-path /usr/lib64/panda3d by rdb » Tue Dec 01, 2009 3:21 pm Users browsing this forum: No registered users and 0 guests
http://www.panda3d.org/forums/viewtopic.php?p=42934
CC-MAIN-2014-41
refinedweb
1,181
51.85
#include <wx/weakref.h> wxWeakRefDynamic<T> is a template class for weak references that is used in the same way as wxWeakRef<T>. The only difference is that wxWeakRefDynamic defaults to using dynamic_cast for establishing the object reference (while wxWeakRef defaults to static_cast). So, wxWeakRef will detect a type mismatch during compile time and will have a little better run-time performance. The role of wxWeakRefDynamic is to handle objects which derived type one does not know. dynamic_castas the last measure (if available from the compiler and enabled when building wxWidgets). For general cases, wxWeakRef<T> is the better choice. For API documentation, see: wxWeakRef<T>.
https://docs.wxwidgets.org/3.1.5/classwx_weak_ref_dynamic_3_01_t_01_4.html
CC-MAIN-2021-31
refinedweb
106
57.16
> I have need of a standalone utility which can create an asset bundle from a folder containing WAV and TXT files. I created an Editor script which uses the AssetDatabase and BuildPipeline classes to do what I need, but then discovered that the UnityEditor namespace is not available in runtime builds. Ouch! So what are my options here? If I knew the internal format of an AssetBundle then I could write an applet (outside of Unity) to accomplish the same thing, but it doesn't look like that format has been published anywhere. Has anyone tried to reference the UnityEditor DLLs from a regular Visual Studio project? Any thoughts? Am I missing something obvious? Answer by Ben 14 · Nov 08, 2011 at 04:46 PM We use a secondary Unity project to store all asset that have no direct link to the scenes and we build them as assetbundles there. If you don't want to do that manually, you can launch the editor in command line mode to do some custom processing; see here: Obviously, it means you need to have these assets as part of a Unity project. Does that help? Any reason why you would not want to have your WAV adn TXT files inside a (other) Unity project? Ben Answer by RickBlick · Nov 09, 2011 at 10:18 PM Thanks Ben, that's interesting. I didn't know we could run the editor from the command line. We might be able to do something with that. The real problem is that the content for our Unity app is created with an editor which runs on Windows, and the users who are creating content typically do not have Unity themselves, nor are they programmers, nor can they be expected to download and run Unity. So we just need a standalone Windows utility that can turn their content into a Unity bundle, which they can then upload via iTunes into the Unity-based. Recursive multiple unity package import and asset bundle build that works in unity 5.6, 2017 and 2018.1.6 does not work in unity 2018.2.X 0 Answers namespace name `UnityEditor' could not be found 4 Answers Create AssetBundle from FBX or GameObjects in your scene 1 Answer Do i need to make asset bundles with upgraded Unity version? 0 Answers How to import the object from server to unity 2 Answers
https://answers.unity.com/questions/173311/standalone-app-for-building-asset-bundles.html
CC-MAIN-2019-22
refinedweb
399
68.7
Hi, means we can’t guarantee now that all the provided changes and fixes will make their way to the final CLion 1.5 release. We’d like to be sure that the quality of the support and the performance is sufficient. If not, we’ll keep on working on this and deliver the fixes as soon as they are ready. As we’ve said above, this build provides support for variadic templates, especially fixing many problems in overload resolution. That means the code should be resolved correctly and code analysis doesn’t show ‘false positives’ on such code constructs, like for example ‘Function recurses infinitely’ for the variadics with termination call: Qt users will find a significant progress in resolve, since Qt C++11 connect calls are now resolved correctly as a result of the variadic templates support: Find the list of issues fixed by the variadic templates support in our tracker. We encourage you to try the build (a patch update will also be available soon), especially in case you are working on a project with vast usage of variadic templates. Please report any issues with parsing/resolve to our tracker, as well as take note of the IDE performance. If you feel it’s gotten worse (compared to the previous EAP build, for example), then please share snapshots and logs with us. Some other fixes this build also delivers: - We continue our work on debugger, and now when debugger reports an error during the evaluation or variable collection, it is reported in UI. This could improve stepping performance and possibly reduce the number of ‘timed out’ errors. - ‘Include parent environment’ option in Run Configurations is now ‘on’ by default (CPP-5453). Full release notes are available by the link. And on the new Preview Next Version page on site you can find the details about all the new features currently making their way to CLion v1.5. The CLion Team JetBrains The Drive to Develop I haven’t tried this EAP (I’m running 3600 using an external Java8), but as a general note about performance since you mentioned it I avoid using most of the refactoring tools. In my project it can sometimes lock up the API for minutes, or long enough that I kill and restart. I also experience intermittent lockups that I can’t track down to a particular action. These vary from seconds to long enough that I assume the system has locked up and I kill and restart. I’m experimenting with running with power save mode to see if that helps. This is on 32 core server hardware with SSD drives. Unfortunately I can’t share many details about my project setup. I’d be happy if there were some guidelines for how to either troubleshoot the GUI performance or maybe CMake constructs to avoid. I wouldn’t be surprised if we are just using some particular CMake construct that has some issue. I still prefer CLion over the alternatives, so keep up the good work. Thanks for your support! Especially for the UI lock ups, and other performance problems, CPU snapshots could be very useful for us to investigate the problems. Could you please make some () and share with our support via submitting a request? We are very sensitive with regards to IP. What information would it contain? Would it be small enough and legible enough that I can read through to guarantee no information leakage? Here’s one piece of information though which I hope might be helpful. It takes about 5 minutes to reload the cmake file. The progress bar at the bottom moves quickly to full, then it gets stuck at “Updating symbols…” with the little spinner. The spinner animates for a little bit and then that’s where it gets stuck for many minutes. During this time the cpu is stuck at around 140% – 160% CPU. Then it wakes up and checks incoming and outgoing VCS changes. That goes pretty fast. After it completes that CPU goes up several hundred percent and tops out at around 1000%. The box is otherwise idle during this. The same cmake file generates an Eclipse project in a second or two. This is with 3600, and it feels as if it has gotten slower lately. The last production release I used was 1.2.2. CPU snapshot will contain only IDE’s internal calls/methods. You can download the demo version of the yourkit and check the snapshot doesn’t contain your sensitive data. I did a snapshot but looking through it I don’t think I could send it. Let me know if there is another way I can help track down this problem. You could try collect thread dumps () and IDE logs and submit them to our support. Will that work? I’ll look into that. In the mean time, I do see this alert when I reload CMake file: “Do not call synchronous refresh under read lock (except from EDT) – this will cause a deadlock if there are any events to fire.” And then I’m stuck with the “0 Updating Symbols” and an almost full progress bar” for a while. Maybe it deadlocks and you have a deadlock timeout thing? Better info: [495014809] ERROR – pi.vfs.newvfs.RefreshQueueImpl – Last Action: CMake.ReloadCMakeProject [495016390] ERROR – pi.vfs.newvfs.RefreshQueueImpl – Do not call synchronous refresh under read lock (except from EDT) – this will cause a deadlock if there are any events to fire. java.lang.Throwable at com.intellij.openapi.diagnostic.Logger.error(Logger.java:127) at com.intellij.openapi.vfs.newvfs.RefreshQueueImpl.execute(RefreshQueueImpl.java:64) at com.intellij.openapi.vfs.newvfs.RefreshSessionImpl.launch(RefreshSessionImpl.java:120) at com.intellij.openapi.vfs.newvfs.RefreshQueueImpl.processSingleEvent(RefreshQueueImpl.java:145) at com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl.a(VirtualDirectoryImpl.java:254) at com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl.a(VirtualDirectoryImpl.java:96) at com.intellij.openapi.vfs.newvfs.impl.VirtualDirectoryImpl.refreshAndFindChild(VirtualDirectoryImpl.java:261) at com.intellij.openapi.vfs.newvfs.VfsImplUtil.refreshAndFindFileByPath(VfsImplUtil.java:136) at com.intellij.openapi.vfs.impl.local.LocalFileSystemBase.refreshAndFindFileByPath(LocalFileSystemBase.java:74) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTableSerializer$80.read(FileSymbolTableSerializer.java:689) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTableSerializer$80.read(FileSymbolTableSerializer.java:635).jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesPack$FileSymbolsPackSerializer.read(FileSymbolTablesPack.java:232) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesPack$FileSymbolsPackSerializer.read(FileSymbolTablesPack.java:219) at com.esotericsoftware.kryo.Kryo.readObject(Kryo.java:672) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTableSerializer.readSymbolTables(FileSymbolTableSerializer.java:864) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache.a(FileSymbolTablesCache.java:713) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache.access$2100(FileSymbolTablesCache.java:73) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache$10$1.compute(FileSymbolTablesCache.java:911) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache$10$1.compute(FileSymbolTablesCache.java:904) at com.intellij.openapi.application.impl.ApplicationImpl.runReadAction(ApplicationImpl.java:981) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache$10.consume(FileSymbolTablesCache.java:904) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache$10.consume(FileSymbolTablesCache.java:889) at com.jetbrains.cidr.lang.symbols.symtable.FileSymbolTablesCache$11.run(FileSymbolTablesCache.java:982) at com.intellij.openapi.application.impl.ApplicationImpl$8.run(ApplicationImpl.java:369)) [495016395] ERROR – pi.vfs.newvfs.RefreshQueueImpl – CLion CL-144.3600.8 Build #CL-144.3600.8 [495016396] ERROR – pi.vfs.newvfs.RefreshQueueImpl – JDK: 1.8.0_71 [495016396] ERROR – pi.vfs.newvfs.RefreshQueueImpl – VM: Java HotSpot(TM) 64-Bit Server VM [495016396] ERROR – pi.vfs.newvfs.RefreshQueueImpl – Vendor: Oracle Corporation [495016396] ERROR – pi.vfs.newvfs.RefreshQueueImpl – OS: Linux [495016396] ERROR – pi.vfs.newvfs.RefreshQueueImpl – Last Action: CMake.ReloadCMakeProject Could you please try the latest EAP, just published. And please check if Invalidate Caches and Restart helps. OK, will try. Don’t know where the “lBPH6mQx” came from. With that new build I no longer get that exception and the cmake file loads faster, but it still takes a minute or two. This wouldn’t be such a big deal except whenever I add a .cpp file I have to reload the cmake files for the entire project to get the .cpp file into the project. file( GLOB_RECURSE SOURCEFILES “*.cpp” “*.h”) Maybe that’s the reason but I don’t think I can change that. Or at least, that’s the only way I know how to do it. Is there another way I can do this? Have you compared the time with cmake command running from the terminal (without CLion)? Is it the same more or less or differs? Besides, GLOB is not recommended by cmake itself – I should have said “We use file(GLOB…” Man, it is easy to respond to the wrong post here. Yeah, a second or two to generate an Eclipse project and a make file structure. Yeah, it takes about a second or two from the command line to generate an eclipse project and a make file structure. I’ll read the link you provided though. We are actually executing CMake on prj reload in the way like: cmake -DCMAKE_BUILD_TYPE= -D CMAKE_C_COMPILER=/usr/bin/gcc -D CMAKE_CXX_COMPILER=/usr/bin/g++ -DCMAKE_BUILD_TYPE=Release -DCMAKE_ARCHIVE_OUTPUT_DIRECTORY=/Users/anastasiakazakova/prj/Counters/bin/Release -DCMAKE_LIBRARY_OUTPUT_DIRECTORY=/Users/anastasiakazakova/prj/Counters/bin/Release -DCMAKE_RUNTIME_OUTPUT_DIRECTORY=/Users/anastasiakazakova/prj/Counters/bin/Release -G “CodeBlocks – Unix Makefiles” /Users/anastasiakazakova/prj/Counters You can measure this command execution on your project running the command from the terminal. That’s all what is done in CLion on cmake reload. So mostly it’s the time for cmake command working by itself. Per CLions reporting, it is the Updating Indices -> Updating Symbols that takes a long time. Reloading the CMake takes about 5 seconds which would be consistent with it taking about one second on the command line if you do it four times. I’ll add one more thing. I tried to restart to see how that performs. The loading of the cmake file at that time from the moment the progress bar at the bottom starts working and says loading the CMake project until it is done takes about 30 seconds. I’ve just tried the new version and I no longer get false positives at some points that I used to get them – however, I still get false positives absolutely everywhere in my project. (the file I’m currently working on; 226 lines long, CLion says there are 144 errors, clang with -wall compiles with no warnings or errors – random other file; 209 lines long CLion; 25 false positives) Various things are causing all these (all reported in your bug database) If I ever dare to use one particular lambda template that has the form SomeTemplate CLion gets totally broken and almost the entire file is failed to parse. Other things are broken with the parser too (also in your bug database) – most annoyingly, if I pre-declare a class then this is the point that the cursor is taken to when I CTRL-click (so I have to use a textual “Find in path” like in the old MS-DOS days) I really want to like CLion (and hoped that it would be a C++ version of IDEA) but this parser is just nowhere near good enough; I dream of the day when you guys switch to the clang parser and turn CLion into the product that it deserves to be. Regards, Marcus. Hi Marcus, Could you please share the tickets link? We’ll recheck. Is the template problem also there? Regarding the libclang, we’d like to rely on it, but there is a bunch of reasons it’s not possible for now. We tried to describe them in this blog post – – C++ parser section. Re; the clang parser thing. Well, of course, it’s up to you how you implement things. I know that the KDevelop team did some work with the clang tooling people when they made clang its default parser for the upcoming KDevelop 5 (and that work is in the upcoming clang 3.8 release) – it may be worth another look now. Re; the parser problems that plague me I would say that about 80% of the false positives that I have relate to; CPP-4987, CPP-4957 and CPP-5842 In code that does SIMD things then I get quite a lot of CPP-790 trouble. The other 20% of parse errors are various different things (that I ran out of time to dig out of your bug database) As for usability; Two things that I use all the time “Go to related symbol” and CTRL-click to a type frequently fail to work; CTRL-click with often go to a pre-declared version of the type “Go to Related symbol” will often hang for ages and then not do anything Don’t think that I have a negative view towards CLion; many things that it does are very clever and way better than other IDEs – right now though, I’m muddling through using CLion because I’m such an optimist. Marcus Thanks for the ticket numbers. We’ll take a look and see what and when we can fix. Re Marcus, Maybe you should initiate a vote for libclang. I will pull all my colleagues to vote up. previous comment didn’t get escaped; the lambda template form should read; SomeTemplate<RETURN_TYPE(PARAM_TYPE…)> Nice, make_shared and make_unique no longer show false errors. Great. Thanks for sharing. Yeah, at least smart pointers are not red anymore, but anything more complicated is still broken :-/ Reported as CPP-5850 Variadic templates inside namespaces: infinite recusrion, wrong number of arguments, feel free to link with other tickets if appropriate. Thanks Yury! We’ll continue our work in that direction. Just swept through one of my projects and reported bugs for which I could easily extract minimal reproducers. I guess I should be looking for a Python job… :-/ Thanks. Your reports are really valuable (as usual). The release notes state “IDEA-69424 Ubuntu global menu integration” as implemented. It’s not been working for me on Ubuntu 14.04, even after manual installation of jayatana. Could you please leave a comment in this issue – we’ll have a look, probably will ask you for some additional details. I have been trying to use Clion for several months now but it has a serious bug in the debugger. It takes several minutes on an i7 Sandybridge CPU to start the debugger. During this time, gdb uses uses a single thread and stays stuck for several tens of minutes. After that, the debugger works without issue. You can test this bug out in this open-source project: Going to PROJECT_ROOT/gtsam/base/tests/testCholesky.cpp and setting a breakpoint on the first line of the first test should reproduce this bug. Since this is a heavily templated project it takes a very long time to build/update symbols especially since I am frequently switching git branches. Is there any way to limit the number of CPU’s Clion uses to build symbols to avoid choking my system so I can continue using the IDE while it’s doing the background tasks? Even with all of this you guys are still the best IDE out there so keep it up! Thanks for the feedback! I’ve put your problem into a report in tracker:. Please, follow to get the update or answer if some additional information needed. Currently CLion uses all the available CPUs for indexing by design. You can upvote this request about providing a setting: Hi guys, great work as usual. Just a note: taking as reference your first example, if I declare func() {} after and not before func(T head, Tail… tail), code doesn’t compile, reporting “no matching function for call to func” when func(args…) is invoked. Same code compiles properly on VS2015 Compiles correctly with clang as well. But what do you expect from the IDE in such a case?
https://blog.jetbrains.com/clion/2016/02/clion-1-5-eap-build-with-variadic-templates-support/
CC-MAIN-2019-51
refinedweb
2,656
56.96
See the Forest for the Trees We had viewstate problems when we rolled out schwans.com using ASP.NET 1.0 (some user agents could not handle the large hidden field and other times we had corruptions that caused the MAC check to fail on postback, read about it at). We solved the problem by writing our own solution for storing the viewstate in Session. ASP.NET 2.0 now provides built in support for this! It utilizes a page adapter and the new SessionPageStatePersister class. The first step is to create a page adapter that simply returns an instance of the SessionPageStatePersister class rather than the default HiddenFieldPageStatePersister class which stores viewstate in a hidden field on the client. Create a class library that contains the following and compile into an assembly: using System;using System.Collections.Generic;using System.Text; using System.Web.UI; namespace RJB{ public class PageStateAdapter : System.Web.UI.Adapters.PageAdapter { public override PageStatePersister GetStatePersister() { return new SessionPageStatePersister(this.Page); } }} Then create a .browser that specifies that the new page adapter should be used for all browsers (example is named pageStateAdapter.browser and placed in App_Browsers folder locally with the web site):<browsers> <browser refID="Default"> <controlAdapters> <adapter controlType="System.Web.UI.Page" adapterType="RJB.PageStateAdapter" /> </controlAdapters> </browser></browsers> Now as requests come in from any type of browser it will use the new adapter which returns a SessionPageStatePersister instance. You can verify that it is working properly by viewing a page on the site then use trace.axd and view the session information and verify that it contains viewstate info (__VIEWSTATEQUEUE and __SESSIONSTATE... entries). Viewing the client page source will also show that the majority of the viewstate is no longer stored on the client (not sure what is left on the client...) Hey, i get the following error when I try to run my application : Parser Error Message: Could not load type 'RJB.PageStateAdapter'. it occurs at this line : Line 4: <adapter controlType="System.Web.UI.Page" adapterType="RJB.PageStateAdapter" /> if anyone can help me, please reply! Did you create a class that contains the class listed above? You can either place the class in the App_Code folder, or place it in another assembly (which can be placed in the bin or GAC). Please email me at robertb@aspalliance.com if you have any other questions. I used your code, and ran my app. It worked(no errors), but I do not have my querystring on the postback. Any ideas? If you comment out the <adapter> line in the .browser file and run your app again does it work now? If it works without that line, but fails with that line, please email me at robertb@aspalliance.com so we can discuss your situation in more detail. PingBack from PingBack from Efficient Server-Side View State Persistence Hi, I have used your method to implement server side viewstate in asp.net3.5,but i am facing a problem:- I have two user controls on the page and rest are drop-downs and a query button. One user control is date control with autopostpack=false; other is with autopostback=True" now what is happening is that when ever i am selecting date from more than 2months,and invoking post back from the other usercontrol, all my drop downs are getting cleared. I have done the following oberservations:- if I comment out the <adapter> line in the .browser file every thing works fine and also If I make the datecontrol autppostback=True. but as its not good to initiate a postback without any reason, I want you to suggest me some remedy to this. I hope for a fast reply plz help How would I implement this if there is a form on a master page... I keep getting corrupted viewstate. Email me at robertb at aspalliance.com and I will help you troubleshoot. We use this on projects that contain master pages and it works fine. Hi, I have a web application based on ASP.NET 3.5, using intensively ASP.NET AJAX Framework (Basically
http://aspadvice.com/blogs/robertb/archive/2005/11/16/13835.aspx
crawl-002
refinedweb
681
65.83
I know that but, what part of the code do I change in order for it to make certain values to become "false" which is supposed to be false, whereas "true" is true. I know that but, what part of the code do I change in order for it to make certain values to become "false" which is supposed to be false, whereas "true" is true. Assignment: isPrime Method A prime number is a number that is only evenly divisible by itself and 1. For example, the number 5 is prime because it can only be evenly divided by 1 and 5. The number... What do I have to change in order for it to happen? Ah, I found out why the output wasn't Upper Case. It was because I didn't put .toUpperCase() in back of it. I think the file would've been... Upper File Converter Write a program that asks the user for the names of two files. The first file should be opened for reading and the second file should be opened for writing. The program should... I have it on my computer, but it somehow can't find it. Where should I be saving it? Assignment: Uppercase File Converter Write a program that asks the user for the names of two files. The first file should be opened for reading and the second file should be opened for writing. The... The assignment says that it should loop 12 times, once for each month. Thus, it should be months<=12. I think I'll have to put an "if-statement" in the inner loop; but what do I put as the boolean... Assignment: Average Rainfall Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years. First the program should ask for the number of years.... package internetserviceproviderpart2; import javax.swing.JOptionPane; /** * * @author Home */ public class Main { /** * @param args the command line arguments This statement got me pretty confused. Can you include the Message Dialog for me so it can clear up my confusion? I've changed up my code: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package internetserviceproviderpart2; import... Task Part 1: An Internet service provider has three different subscription packages for its customers: Package A: For $9.95 per month 10 hours of access are provided. Additional hours are $2.00 per... I changed it just now but it is still the same problem. My file's name is Internet Service Provider Part 2.java I changed public class Main into public class internetserviceproviderpart2 { There is still a red squiggly line under it saying... Here is my code: /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package internetserviceproviderpart2; import javax.swing.JOptionPane; The brackets seem to pair up nicely... The last bracket, isn't it supposed to pair up with the one after "public static void"? package javaapplication11; import javax.swing.JOptionPane; /** ... if(packageLetter!='A' && packageLetter!='B' && packageLetter!='C') { JOptionPane.showMessageDialog(null, "Please enter either A,B, " + "or C)."); }... I've fixed those. Now, whatever I enter...it becomes "Please enter either A, B, or C." package javaapplication11; import javax.swing.JOptionPane; /** * * @author Home */ I've changed it but on the sides, it says identifier expected and I'm not too sure where to put the brackets for the "if-else if-else". package javaapplication11; import... After execution, the message dialog appears for: package A package B the default So...therefore, I have to use else if? When I did that the error on side says that it should be "else without... It works but now I want to change a bit instead of using the switch statement: I'm not too familiar with using if-else if-else statements. Here's the code source: package javaapplication11;... The brackets for the "if statement" makes the variable "additionalHoursFee" not initialized for the statement "totalFee = monthlyFee + additionalHoursFee;" Even when I tried it with another way, it... I've done the things that you've asked me to change. The problem is pretty similar to my question. How do I make the minimum monthly fee appear instead of it being less? e.g. package 'A': 10 hours... All the answers that is above 10 hours for 'A' and 20 hours for 'B' are correct expect the ones that are under 10 hours for 'A' and under 20 hours for 'B' are incorrect. For 'A': I can enter any... Yes, the program works. As you can see, the program is suppose to compute the fee for the current month's internet service. For the first question from my code: It asks me to input the letter of...
http://www.javaprogrammingforums.com/search.php?s=5fd59c4f5f55d4ed25b14cf219a898e5&searchid=1814142
CC-MAIN-2015-40
refinedweb
792
75.5
needed is to heal ecosystems and end poverty. As long as we continue to deplete ecosystems the economy will get worse. As long as the rich get to make the rules the economy will get worse. The corruption and dishonesty (also a lot of illegality) at the top of the USA will never change, never end. For this reason the major economic meltdown still lies ahead as far as the USA and most of the world (especially the UK) is concerned. The rest of the world will, over time, probably save itself by having less and less and less to do with the corrupted financial systems in place in New York and London. Playing the financial ‘game’ in either of these two so-called centres of economic power is like playing blackjack in a rigged casino. A sea-change in geo-economics and geopolitics is coming. I suspect that the centre of economic power will leave both New York and London and may never come back to its previous domicile. You can only deceive and defraud the whole world to this extent (the extent that caused this unfolding crash) ONCE. “Never again!” is going to be the motto of Europe (Old Europe if you like), Asia the Orient, the Middle East, Central and South America, Australasia et cetera. The UK backed the wrong horse. So did Eastern Europe that’s now left up the creek without a paddle. In short nobody’s going to trust the Americans again no matter how many charismatic and personable celebrity leaders they elect. A quarter of a million people in the USA demonstrated their distrust of their own government yesterday. This will spread until a majority of Americans make it quite clear that they don’t trust their own govt. A rising percentage of British people are coming (a bit too late!) to realise that their government is not to be trusted and that the next one should probably be trusted even less. The whole political system is corrupt and has broken down. The governments of the USA and the UK have managed to damage trust in them by the people of the world and by their own citizenry, irreparably. How we are to run a world in which there is no trust in anybody? Rebuilding the global economy with the UK and the USA not at the centre is a process that may take decades to sort out (unless there is some kind of revolution or civil war in the USA and social disorder in the UK, in which case it will be sorted much faster). Until then, there can be no lasting recovery for the global economy. Our planet is in meltdown mode and that’s the way it’s going to stay for quite some time, come what may. The sins of corruption are collapse. The most corrupt regimes of medieval times were arguably not as corrupted as this. Many false dawns yes. A lasting ‘recovery’ anytime in the next five years? Don’t hold your breath. For recovery to happen we need demand, to create which world has traditionally relied on the Americans. Now with them under the weight of massive debts, we need an alternative source to absorb the output produced during the recovery. As if now there is no reliable source in sight but the governments which at the expense of their fiscal healths may stimulate demand in the short term but in the long run unless a substitute for the U.S. consumer is not found the world economy will either not recover to a sustainable level or recovery would be sluggish (to be optimistic). Hence, we maybe at the cross roads the likes of which were last seen in the early twentieth century when the worlds balance of economic power was shifting towards the U.S. from Europe, now it seems to be moving towards Asia. However, its still too early to see how legions of compulsive savers can be proselytized to consumerism. The answer maybe that these economies are still in developing stages and maybe able to absorb their surpluses among themselves in form of various investments in public and private projects focused on the local economy. Whatever happens, recovery in terms we maybe thinking i.e. status quo is not happening in the foreseeable future. Or, for the UK, we can say that the longest period of uninterrupted economic expansion ever recorded has been followed by a serious recession. I will never cease to be "amazed" ;-) p.s. anyone else getting the sense of bereavement from those that predicted the anglo saxons model would implode and smart social europeans model would sail on? I think its palpable. Herein is the very stuff of cycles methinks. Despair, get it while you can! Risk Manager is right. We (the Anglo-Saxons or UKUSA if you prefer) are in a state of denial. It’s like when primitive man sat around the campfire scratching his head and asking “How can we solve the problem of too much pregnancy when we don’t know what’s causing it?” We (UKUSA) try to put lipstick on our pig and figure that’ll make everything all right. We refuse to accept any blame. It’s not like we were leading (and endlessly lecturing) the whole world and we ran the global ship right onto the rocks. Oh no! It’s like, if we share the blame around like jam on a slice of toast, then we can weasel out of any and all responsibility. We can blame the French or the Germans (who compared to our economic insanity were relatively restrained and sane actually), the Chinese, the Japanese, Islamic Fundamentalism, the Nomads in the Sahara, anything and anybody will do nicely when we are lashing out indiscriminately you see. And of course the answer isn’t for us to start living within our means and saving for a rainy day, and for out wild reckless out-of-control spendthrift governments to start living within THEIR means and saving instead of borrowing and printing and quantitatively easing (creating tens of trillions of money electronically out of thin air). Nooo! The answer is for all these Chinese and other people in Asia and the Orient upon whom we look down on and patronise so much endlessly (except when we want to borrow trillions of their money obviously) - the answer is for THEM to start spending like us and living the ‘Champagne Dreams of the Rich and Shameless’ on a soda-water income and running up millions of dollars of debt on assets worth only a couple hundred thousand at best. Here’s how the Anglo-Saxon economic model is operating right now. The Fire Ants of Consumption (aka the US Consumer) have had their backs broken in a dozen places under the weight of their staggering debt, so there’s a global over-production of everything, especially cars and houses. So, should we, like, cut production? Nah. No way José. The answer is for our governments (UKUSA) to keep printing (and quantitatively easing) money by the tens of trillions indefinitely, give half to the big corrupt bankrupt banks and with the other half keep buying these products on an indefinite basis. In fact, in this utopia, nobody has to work anymore as the govt can simply print enough money to make every one of us a millionaire or more. Isn’t life grand? I don’t really want to mention this but we must be very shallow greedy untrustworthy kind of people because we elect very shallow greedy untrustworthy kind of people to lead us ‘Time After Time’. Or if you prefer, the blind electing the blind to lead us blindly into a bind. How divine! Ps. Britain isn’t facing a ‘serious recession’, as The Economist and the govt spinmeisters suggest. It’s facing the ‘Mother of all Great Depressions’, the likes of which it has not seen since the South Sea Bubble (dubbed the ‘Enron of England’) left England bankrupt. As a matter of fact, Britain is already bankrupt as-we-speak, but they are printing money (or creating it electronically) 24/7 to camouflage the fact. In fact, if they turn all those defunct Auto Manufacturing Plants into Printing Presses, Britain’s economic woes will be solved in one fell swoop. Thank you Gordon; thank you Tony; thank you Alistair Campbell (Tony’s brain). Thanks for this 'Brave New World (of bankruptcy)' that you promised me. The New Keynesians emphasised expectations as a fundamental force in contemporary economics but mentioned that the Government must be credible for its statements and published intentions to achieve the desired market reaction. Neither the USA nor the UK are credible in anything, especially economics. Credibility falling to zero in one area tends to cross-contaminate credibility down to near-zero in another area, doesn’t it? George Bush personally said over and over again that the USA does not torture. We now know that the USA is a country that DOES engage in torture most vile and as such is in no position to lecture any other country about human rights violations. And we know that aiding and abetting the USA in all its illegal acts was (and probably still is) its faithful acolyte the UK. So, with respect to the Anglo-Saxons, the world now knows that almost everything we (the Anglo-Saxons) say is a lie. Under these circumstances, is anyone really going to invest in us or buy our bonds or put their money in our banks or have anything to do with our financial services sector? Pretty soon, nobody will trust our Anglo-Saxon Insurance Companies either e.g. Lloyds Insurance in London. Who will buy products (banking services, insurance etc) from companies in countries like the UK or the USA who have lost all credibility with many of their own citizenry and with the international community most certainly? Trust in us is gone. The world looks down on us. Our economies face a dismal future. There is an old saying that when a man (or a country) surrenders his (its) honour, he (it) surrenders everything else of value at the very same place and time. In the boom years we acted without honour. In the bust years we have nowhere to turn. Future's looking grim. We can't even turn to Him. Quote: /.// Link: I too am amazed and disappointed that someone as supposedly intelligent as Obama seems to have fallen for the alchemist sophistry of the economics industry and is heading the Ship of State straight for the rocks of a coming hyperinflationary depression far worse than the 1929 to 1939 economic troubles. Peter Schiff is one of the few economists around today who is not confuddled by the verbosity and pomposity of his own bombosity and who is still able to reason rationally consequently. In January of 2007 I predicted without equivocation that the markets would crash before the end of the year. At that time, all the people upon whom Obama seems to be relying today scoffed at and laughed out of town anyone who said this Ponzi pyramid they were constructing would collapse sooner rather than later. The MORE wrong they were about everything, the HIGHER the position they seem to have been given in the Obama White House. America today is one in which all the dead wood seems to have floated to the top. Or put another way, the lunatics have taken over the aysylum. At least as far as economics is concerned, that seems to be the case. Breaking news: • Herb Allison of Fannie Mae Nominated by Obama to Run Treasury TARP Office Link: See what I mean? Plus ca change, plus c'est la meme chose. @Market Matador, Agree with some of what you said, but not all of it. Sure, given that the roots of this crisis are in overspending and undersaving, it is a flight of fancy to beleive that we will be able to spend our way out of a recession. However, the purpose of public spending during a recession is to ensure the avoidance of a precipitous decline in output, which would make the recession deeper and longer than classical theory allows for. Wasn't the lesson of the Great Depression exactly this? That said it is misleading for President Obama to paint the deficit spending as a sort of panacea that will stimulate the eonomy back to its good (bad?!) old days. However, I don't think that the delusion is that of the President's; rather it is that of the audience he is playing to. Most of us do not want to hear that there is going to be a long painful adjustment in front of us. Debt is going to have to be reduced and spending curtailed, which is going to hobble growth for years to come. For us on the ground it means more sackings for those employed, fewer jobs for those entering the market and lower salaries for those who hold jobs. And there is no solution but to buckle down and pull through for as long as it takes. The day a politician, any politician, is able to say this straight, I'll beleive that the worst is behind us! @Gandalf_the_Grey, God has answered my prayers. At last! A Poster with something intelligent to say and not afraid to say it clearly and eloquently. I'll try to answer this later because I “Agree with some of what you said, but not all of it.” And I'll try to do so intelligently, if I can possibly. Cheers. @Gandalf_the_Grey, I'd like to start with "I don't think that the delusion is that of the President's; rather it is that of the audience he is playing to", if I may. If I'm playing to an audience that's clearly delusional and I join in the delusion most happily and willingly, EITHER I too am as delusional as delusional can be, OR I'm dishonest and insincere completely. Which am I, could you please tell me? I have other questions to ask of thee ... but this one has really puzzled me. Sincerely, Bravo As the onslaught of bad economic data rolls on with no end in sight, we are witnessing increasing desperate attempts to demonstrate the latest trough is in fact a plateau, the Stock Research Portal says: “It will be interesting to see if the Fed still believes U.S. unemployment will peak at 8.5% (where it is now reported to be) … One must seriously wonder what the analysts and commentators who are predicting near term U.S. economic recovery are smoking.” In Michigan unemployment has reached 12.8% and climbing. In the Great Depression, unemployment reached 25% but they did (calculated) things more simply (less dishonestly) back then. If 75% of the available workforce had jobs, then unemployment had to be 25%. Nowadays they disqualify about half those who have lost their jobs for one reason or another (not looking hard enough they figure), so the figure of 12.8% now could easily compare to 25% back then. When Michigan reaches 17% ... it will translate to about 30% unemployment, if we use the method of the 1930s (comparing apples to apples). This will far exceed anything America has ever experienced before. Geithner, Bernanke and Summers do not have a clue what they are saying and doing. "The danger, however, is that too much emphasis on the stock cycle misses the underlying characteristics of this downturn. This is mainly a balance-sheet recession precipitated by a financial crisis. And it is a downturn that it is unusually synchronised around the globe." ----------------- Absolutely!. For example, my friend bought many share of CIti Bank stocks few weeks ago because they are cheap. But of curse it fell after the deal(bought in $5 then down to less than $3. Now although the market up but the stocks are not up much.) I said: "See, I told you so. Don't touch those stocks. The whole economy is very very bad. That particular bank is the largest zombie. How could you do that?" My friend laughed at me and said: " What do you know about the stock market or economy? Stock market is a different animal. It has nothing to do with the real economy. You bet on buy low sell high." When it's the concern of money, people are not change. They always lead by Greed unrealistic expectation luck. I know many people who are playing on the stock market are totally disregard economy. They are like the voodoo mad scientists analyze researching the clue and trend or signals from the data they collected, trying to catch the best timing therefore catch their big fish of the day. They love to make quick big bucks. The problem is when the too big to fall banks doing that, the society have pay for their gambling debts. That's the most painful thing. Not the recovery. "Recovery from the recession, when it comes, will be slow and painful" Krugman said the West owe Japan an apology for their Western More-than-10 years bad mouth the Japanese because the US and the West now are doing much worse. Japan at least were still producing exporting lots of goodies. If the US will end up like Japan we should count ourselves lucky. We should expecting much worse. (You can fast forward to the part Krugman's speaking part.)... IMF report - even Krugman's scared. @Market Matador, "If I'm playing to an audience that's clearly delusional and I join in the delusion most happily and willingly, EITHER I too am as delusional as delusional can be, OR I'm dishonest and insincere completely. Which am I, could you please tell me?" No arguing with that one! I would have to say, given my high regard for the intellect of President Obama, the latter. Not necessarily as a criticism mind you. The dishonesty he exhibits is a price demanded by the system of governance he represents. But I do see where you are coming from. Irrespective of the sincerity of his public stance, once said stand is made he is trapped by it. He will have no choice but to follow up on the delusion, making him "as delusional as delusional can be". As I said, no arguing with you on that. Hello ricecake, You wrote: //My friend laughed at me and said: " What do you know about the stock market or economy? Stock market is a different animal. It has nothing to do with the real economy. You bet on buy low sell high."// These people really make one laugh, don’t they? If you go to study law, one of the first things they teach you (especially if you are training to be a Barrister) is: “Never start believing your own propaganda!” These folks started this “The Stock Market is not connected to the real economy” (also stated as “Wall Street is not connected to Main Street”) propaganda nonsense to confuse the unwary ... and now they have started believing it themselves. Ha ha! Ha ha ha ha ha! There is a God, don’t you know, and he has a terrific sense of humor as this little story doth show. Where’s the money going to come from then? Little aliens bring it in spaceships in the middle of the night maybe? The US transformed itself from a manufacturing-based economy to a ‘Consumer Society’, something I would NOT recommend for any country. Now ‘Consumer Spending’ accounts for more than 70% of GDP. Consumer stops spending (WON'T spend because he/she CAN’T spend) – there goes the whole economy down to the bottom of the sea baby, do you see? (I know you do see. You are one of the very very few with ‘the eyes to see’; not ‘blind-as-a-bat like everybody; I take my hat off to thee.). The way your friend has brainwashed himself to think, even if every man woman and child is out of work in the USA one fine day … IT MAKES NO DIFFERENCE TO WALL STREET which will continue to prosper even if every single city in the USA turns itself into Flint Michigan (see link). With all due respect to your friend, these people are all idiots. Did anybody see the movie ‘Idiocracy’? THAT’S the world we are living in today believe me. We are idiots who elect idiots to lead us who in turn appoint idiots to high positions and the appointed idiots and the leader idiots tell us the idiots idiot nonsense each and every day which being idiots we gobble down right away. There’s C21st Earth in a nutshell for you. Link: Ps. There IS life out there but they go a long way out of their way to avoid us as they know that all the folks on the Blue Planet are crazy. In fact, they call our planet ‘The Asylum’, and the only times they do visit is to drop off any of their own people suffering from insanity. Ps(2). Geithner and the rest of the comedians keep calling on the Am People to resume spending. Calling on somebody with NO MONEY (and nobody will lend him/her any) to spend ... is the very height of stupidity and insanity. Here’s something I wrote last week when everybody was saying that the storm must be abating and the skies turning sunny and blue (‘glimmers of hope’ the President did tell me and you) because the Stock Market was up 25% from where it was previously [note I wouldn’t call that - in early March - a ‘bottom’ unless we say that it is a ‘bottom’ for the time being (pro tempore) i.e. until a new ‘Bottom’ is established below that so-called ‘Bottom’ in the coming months and years of this 15-to-20-year-long so-called ‘downturn’]. Just last week, the Pollyannas were singing like a canary. In fact, they were singing like the canary in the mine. Now they are mostly silent, I think you’ll find. //Looks like another deadcat bounce going on today in the USA and across the UK. The UK and the USA transformed themselves from a manufacturing (or export-driven) economy to a service economy (with everyone serving tea, everything would be just fine and dandy, Mandy) aka the “new Economy’ or the consumer-driven economy. For example, in the USA more than two thirds of GDP comes from consumer spending. No surprise therefore that GDP dropped more than 6% in the USA in Q4 2008. But the ‘Glimmers of Hope’ people are predicting that GDP will return to ‘modest growth’ (positive territory i.e.) in Q4 2009. How, when the back of the US (and his British counterpart) is broken in a dozen places and like Kenny Rogers famously said (to Lucille) “This time the hurtin’ won’t heal”, could this be? How? In Heaven’s name how? How is the USA (or the UK) going to return to ‘positive territory’ in Q4 2009? Remove at least half of two thirds from US GDP and HOW is GDP going to return (in a hurry) to positive territory, pray tell me? And all that rosy stuff about ‘Banks returning to profitability’ is just more govt propaganda designed to mislead you‘n’me. Without the consumer returning to some facsimile of solvency, there can’t be too much ‘E’ over on Sesame Street (E’s for ‘Earnings’, Big Bird did tell me). And without E, for Corporate America (Corporate Britain same story) there can be no return to profitability (other than the usual Enron accounting fantasy occasionally), unless the Govt is going to continue to inject tens of trillions of printed bailout money quarterly, indefinitely. Which will leave the Markets doing a Chernobyl-imitation regularly. So, let’s see. If nobody has no money honey, is the price of a house going to go up or down, irrepressibly? That one is too tough for me. OK, if you think the former it’s going to be ... rush out and buy a dozen Condo, immediately, why don’t thee?// Battle for the Soul of Capitalism rages from sea to shining sea. Only problem is that capitalism a la the USA sold its soul to the Devil a long time ago, I’m sad to say. The people running the US economy think the same as ricecake’s friend. To them all that matters is the Dow, the Nasdaq and the S&P. Given the chance they will spend all the stimulus money ... trying to keep up a sinking S&P. [Even Viagra won’t help actually.] They are fighting to keep the Dow up above 8,000 at all costs. This is a battle that (like the war on drugs) will eventually be lost. They don’t care less about the ‘Real Economy’ (meaning you‘n’me.). [Everybody in the country could be unemployed and starving most egregiously – they won’t care less if they can ‘Stimulate the Crooks’ and get the Dow up with this printed stimulus (monopoly) money.] It’s all going to fail and fail most disastrously. Believe me. I wish it were otherwise but so it has been written, so shall it all come to pass. Heed these warnings, and, if you can, try to save your ***.
http://www.economist.com/node/13496802/comments?sort=2
CC-MAIN-2014-52
refinedweb
4,260
70.73
I've been studying C++ pretty intensely over the past few weeks. I've done tutorials and read books and I have a collection of example code. I want to code something but I have no idea what to do and I'm really bored. I want to do something dynamic but I don't think I'm ready to make a game. The extent of my knowledge of C++ consist of: classes: private,public,protected constructors, destructors variables data types arrays multidimensional arrays functions loops constants if statements switch case statements header files namespaces also if the project requires me to learn a few additional topics, that's ok too. I'll need to learn it sometimes Project Ideas Page 1 of 1 I need some project ideas so that I can practice coding 2 Replies - 4086 Views - Last Post: 14 June 2009 - 03:20 PM #1 Project Ideas Posted 14 June 2009 - 03:14 PM Replies To: Project Ideas #2 Re: Project Ideas Posted 14 June 2009 - 03:19 PM Hey Carbon coder, have a look at martyr2's Project Ideas list you should get some ideas from there tommyflint tommyflint This post has been edited by tommyflint: 14 June 2009 - 03:19 PM #3 Re: Project Ideas Posted 14 June 2009 - 03:20 PM goodness I feel like a newb for not searching. Sry Page 1 of 1
http://www.dreamincode.net/forums/topic/109994-project-ideas/
CC-MAIN-2017-22
refinedweb
231
65.49
It's true. If you haven't used it yet, Redcarpet is the Markdown parser that GitHub uses to work all that magic on their site. So of course, it's awesome. What makes it really awesome is the custom renderers feature. Here's the one from the documentation: # create a custom renderer that allows highlighting of code blocks class HTMLwithAlbino < Redcarpet::Render::HTML def block_code(code, language) Albino.safe_colorize(code, language) end end markdown = Redcarpet::Markdown.new(HTMLwithAlbino) You can guess what that does: uses some library called Albino to render code blocks. There are a whole bunch of hooks you can use to make a custom renderer. They make it super easy to do something neat with markdown. So I did. I'm working on... this project. And it needs to render a bunch of articles that are Markdown files. There will be a sidebar. I want to have links to each section. But I'm a good programmer, which means I'm lazy. So why bother making my own sidebar? Especially when I can abuse Redcarpet to do it. Oh, and disclaimer: normally, I'm all about super clean code. Last night, that wasn't the mood I was in. This code is probably terrible. That's part of the fun! Please feel free to {clean up,obfuscate,golf,unit test} this code, email me, and tell me how awesome you are. With that disclaimer out of the way, round one: class OutlineRenderer < Redcarpet::Render::HTML attr_accessor :outline def initialize @outline = [] super end def header(text, header_level) text_slug = text.gsub(/\W/, "_").downcase self.outline << [header_level, "<a href='##{text_slug}'>#{text}</a>"] "<h#{header_level}#{text}</h#{header_level}>" end end Every time we hit a header, Redcarpet gives us the text and the header level. We grab the text, turn it into a slug, and then append a two-element array to our outline. It keeps track of the level of this header, and makes a link from the slug. Then, we spit out a header tag, adding on an id element that we linked to in our link. Next up, rendering: renderer = OutlineRenderer.new r = Redcarpet::Markdown.new(renderer) content = r.render(some_content) outline = renderer.outline This instantiates our Renderer, creates our Markdown parser, and renders the content. We also grab the outline we made. Sweet. Finally, rendering the outline: def format_outline(outline) prev_level = 2 "<ul>" + outline.inject("") do |html, data| level, link = data if prev_level < level html += "<ul>" elsif prev_level > level html += "</ul>" end prev_level = level html += "<li>#{link}</li>" html end + "</ul>" end This... is amazing. And terrible. Don't drink scotch and code, kids. Or do, whatever. This takes our Array of Arrays that we made with our renderer and runs inject over it. If our previous level is less than the new level, we indent with a <ul>, and if it's greater, we outdent with a </ul>. Then we render our link, and wrap the whole thing in its own set of <ul>s. Done! We can call this helper method in our layout, and bam! We get automatic outlines generated for our Markdown files. Like I said, this is quick and dirty, but for a first pass, I don't feel too bad about it. Get it done, and then get it done right.
http://blog.steveklabnik.com/posts/2011-12-21-redcarpet-is-awesome
CC-MAIN-2016-22
refinedweb
552
68.06
Hmm, Ill have a bash at it. Its better than no protection at all, and its easy enough to do. A function that resolves entities isnt hard to write though, heres one: rentity = re.compile(r"&(\w+);") rhashentity = re.compile(r"&#(\d+);") from htmlentitydefs import entitydefs #escapes entities of the form 'ϧ' and '&aaa;' into ascii strings def unentity(s): s = rentity.sub(lambda m: entitydefs.get(m.group(1), m.group()), s) s = rhashentity.sub(lambda m: chr(int(m.group(1))), s) It's a shame you cant define your own entities in html. -----Original Message----- From: Barry A. Warsaw [mailto:barry@zope.com] Sent: Thursday, 28 February 2002 23:01 To: Paul Schreiber Cc: Damien Morton; mailman-developers@python.org Subject: RE: [Mailman-Developers] Protecting email addresses from spam harvesters "PS" == Paul Schreiber cheesefactory@yahoo.com writes: PS> Yes,, but you can encode the "mailto:" as well, like so: <a PS> href="mailto:jo 1;@aol.com">me</a> PS> I would guess most spambots are pretty dumb, probably using a PS> silly regex like <a href="mailto:([^"]+)">. This /is/ kind of interesting. Anybody want to write a patch? -Barry
https://mail.python.org/archives/list/mailman-developers@python.org/message/65P5YUEHIOOX36YVM4RR5JACGJFTZWFG/
CC-MAIN-2022-33
refinedweb
193
53.17
How to Scrape LinkedIn Profiles without login using Python? How to Scrape LinkedIn Profiles without login using Python? Send download link to: LinkedIn is the best for connecting with business professionals. It contains global business information with millions of users. Most of business professionals use LinkedIn data to expand their business networks and company growth. So use LinkedIn scraping and take benefits of data from it. Looking for Scraped data from LinkedIn then download data of our Linkedin data extractor services. Today we will scrape the data from this particular LinkedIn profile and save the HTML page in a local folder using python. We will scrape data from this profile. Here the main thing is we will scrape the page without login. I want to save the LinkedIn profile page locally in this folder linkedin_page in D drive I created using python. For this, we have to install some packages. This is a website from where you can search and download the required packages. open pypi.org website and here you can search and download required packages. See complete code below or watch video for detailed explanation of LinkedIn data scraping: Import libraries: import requests from time import sleep from selenium import webdriver import chromedriver_binary Here we use selenium to send base request for getting cookie: driver = webdriver.Chrome() sleep(5) driver.maximize_window() sleep(5) driver.get("") sleep(5) Save cookie in variable: cookies_dict = {} for cookie in driver.get_cookies(): cookies_dict[cookie['name']] = cookie['value'] driver.close() Set headers & Send a get request: resp = requests.get("", cookies=cookies_dict, headers={'user-agent': 'Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/87.0.4280.88 Safari/537.36', 'accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'accept-encoding': 'gzip, deflate, br', 'accept-language': 'en-US,en;q=0.9', 'upgrade-insecure-requests': '1', 'scheme': 'https'}) html = resp.text Save Profile page in Local Folder: HtmlPath = "D:/linkedin_pages/1.html" page_fun = open(HtmlPath,'w',encoding='utf-8') page_fun.write(html) page_fun.close() you can parse the data from the response text we get. We can parse the data profile name, the number of employees, location, followers, about us section, website, Industry, company site, headquarters, type, when it was founded, locations. Without login, it will give us the four-employee name in case if you required it. It is just the parsing of data. Now you understand how to send the request in LinkedIn. If you require multiple pages here, I explain one page so you can use it for a loop. You don’t have to open the browser multiple times. you have to send a request with a different URL because the cookie is already saved in the cookies_dict variable and we are applying it here. so, we don’t have to open it again and again only we have to change the LinkedIn profile URL. Hope this tutorial is helpful to scrape LinkedIn public data. Apart from this we can scrape bulk data from LinkedIn.
https://www.worthwebscraping.com/how-to-scrape-linkedin-profiles-without-login-using-python/
CC-MAIN-2021-31
refinedweb
516
60.21
As with visual assets, there are different methods for using audio assets in your application. We will go over the available options next. Embedding Files You can embed sounds in your application by adding them to your Flash library or your Flash Builder project. Embedded files should be small, like the ones used for sound effects or user interface audio feedback. Your application will not display until all of its assets are loaded. Test it. If it sits on a black screen for too long, you may want to group the sounds in an external .swf file that you load as a separate process. Using Flash Professional Unless you place audio on the timeline, you need to give it a linkage name. Go to Library→Properties→Linkage and click on Export for ActionScript. Change the name so that it doesn’t include an extension, and add a capital letter to conform to class naming conventions. For instance, “mySound.mp3” should be “MySound”. Note that the Base class becomes flash.media.Sound: var mySound:MySound = new MySound(); mySound.play(); Using Flash Builder Place your audio file in your project folder. Embed it and assign it to a class so that you can create an instance of it: import flash.media.Sound; [Embed(source=”mySound.mp3″)] public var Simple:Class; var mySound:Sound = new Simple as Sound; mySound.play(); Using External Files Using external files is best for long sounds or if you want the flexibility to replace the files without recompiling your application. import flash.media.Sound; import flash.net.URLRequest; var urlRequest:URLRequest = new URLRequest(“mySound.mp3”); var sound:Sound = new Sound(); sound.load(urlRequest); sound.play(); This example works for a small file, which loads quickly. We will cover how to handle larger files in the section “Loading Sounds” Settings and the Audio Codec The Flash Authoring tool offers the option to modify audio files directly in the library. You can change compression, convert from stereo to mono, and choose a sample rate without requiring an external audio tool. Settings are set globally in the Publish Settings panel and can be overwritten for individual files in the library. If you own Soundbooth, or another external audio application, you can launch it for an individual sound from within the development tools and make changes, which will be applied to the sound in your project. You can, for instance, change the track from stereo to mono or adjust the volume. In Flash Professional, select the track in the library, click the top pull-down menu, and select “Edit with” to launch the audio editing application. In Flash Builder, single-click the asset, right-click, and select “Open with” to launch the sound application. The most professional approach, of course, is to work in an audio application directly, as you have more control over your sound design: all files can be opened together and you can set uniform settings such as volume. Prepare your audio carefully beforehand to remove any unnecessary bytes. For background music, write a small file which loops, rather than a long track. Compression Supported compressed formats are MP3 (MPEG-1 Audio Layer 3), AAC (Advanced Audio Coding), WAV (Waveform Audio File Format), and AIFF (Audio Interchange File Format). MP3 can be imported dynamically using the Sound object. MP3 adds a problematic small silence at the beginning of the track. MP3 encodes incoming audio data in blocks. If the data does not fill up a complete block, the encoder adds padding at the beginning and the end of the track. Read André Michelle’s blog on the issue, and a potential solution, at. AAC audio can also be loaded dynamically using the NetStream class. AAC is considered the successor of the MP3 format. It is particularly interesting to us because it is hardware-decoded in AIR for Android: import flash.net.NetConnection; import flash.net.NetStream; var connection:NetConnection = new NetConnection(); connection.connect(null); var stream:NetStream = new NetStream(connection); var client:Object = new Object(); client.onMetaData = onMetaData; stream.client = client; stream.play(“someAudio.m4a”); To control or manipulate an AAC file, refer to the section “Playing Sounds” Here is some sample code: var mySound:SoundTransform; stream.play(“someAudio.m4a”); mySound = stream.soundTransform; // change volume mySound.volume = 0.75; stream.soundTransform = mySound; You can embed WAV or AIFF files in your project or library. Or you can use one of the third-party tools mentioned earlier. Supported uncompressed settings are Adaptive Differential Pulse Code Modulation (ADPCM), and Raw, which uses no compression at all. Uncompressed formats must be embedded. Bit rate The bit rate represents the amount of data encoded for one second of a sound file. The higher the bit rate, the better the audio fidelity, but the bigger the file size. For mobile applications, consider reducing the bit rate that you would normally choose for desktop applications. Bit rate is represented in kilobits per second (kbps), and ranges from 8 to 160 kbps. The default audio publish setting in Flash Professional is 16 kbps Mono. Sampling rate The sampling rate is the number of samples taken from an analog audio signal to make a digital signal—44.1 kHz represents 44,100 samples per second. The most common rates are 11.025, 22.05, and 44.1; 44.1 kHz/16-bit is referred to as CD-Quality and is the sampling rate Flash Player always assumes is used. Stereo or mono Stereo or mono The external speaker on Android devices is monophonic. The headphones are usually stereo, although the output may not be true stereo.
https://www.blograby.com/developer/audio-assets.html
CC-MAIN-2018-26
refinedweb
929
57.98
How we optimized our DNS server using go tools background with tens of thousands of web sites using our authoritative dns server, we respond to millions of requests every day. dns attacks are getting more and more widespread these days, dns is a crucial part of our system and we must make sure that we can perform well under high pressure. dnsflood is a small tool I found capable of producing huge number of udp requests. # timeout 20s ./dnsflood example.com 127.0.0.1 -p 2053 monitoring our systems showed that memory usage of our service was growing so fast that we had stop our service or we would get into OOM errors. this looks like a memory-leak problem; there are different causes for “Kind-of” memory leaks and “Real ” memory leaks in go: - hanging goroutines - incorrect use of defer & finalizer - substring & subslices - global variables this post has an in-dept explanation of different leak cases. before jumping to any conclusions let’s do some profiling first GODEBUG different debug facilities can be enabled using GODEBUG environment variable by passing a list of comma seperated name=value pairs. scheduler trace scheduler trace can provide information about the runtime behaviour of goroutines. to enable scheduler trace, run the program with GODEBUG=schedtrace=100 the value means output period in ms. $ GODEBUG=schedtrace=100 ./redins -c config.json SCHED 2952ms: ... runqueue=3 [26 11 7 18 13 30 6 3 24 25 11 0] SCHED 3053ms: ... runqueue=3 [0 0 0 0 0 0 0 0 4 0 21 0] SCHED 3154ms: ... runqueue=0 [0 6 2 4 0 30 0 5 0 11 2 5] SCHED 3255ms: ... runqueue=1 [0 0 0 0 0 0 0 0 0 0 0 0] SCHED 3355ms: ... runqueue=0 [1 0 0 0 0 0 0 0 0 0 0 0] SCHED 3456ms: ... runqueue=0 [0 0 0 0 0 0 0 0 0 0 0 0] SCHED 3557ms: ... runqueue=0 [13 0 3 0 3 33 2 0 10 8 10 14] SCHED 3657ms: ...runqueue=3 [14 1 0 5 19 54 9 1 0 1 29 0] SCHED 3758ms: ... runqueue=0 [67 1 5 0 0 1 0 0 87 4 0 0] SCHED 3859ms: ... runqueue=6 [0 0 3 6 0 0 0 0 3 2 2 19] SCHED 3960ms: ... runqueue=0 [0 0 1 0 1 0 0 1 0 1 0 0] SCHED 4060ms: ... runqueue=5 [4 0 5 0 1 0 0 0 0 0 0 0] SCHED 4161ms: ... runqueue=0 [0 0 0 0 0 0 0 1 0 0 0 0] SCHED 4262ms: ... runqueue=4 [0 128 21 172 1 19 8 2 43 5 139 37] SCHED 4362ms: ... runqueue=0 [0 0 0 0 0 0 0 0 0 0 0 0] SCHED 4463ms: ... runqueue=6 [0 28 23 39 4 11 4 11 25 0 25 0] SCHED 4564ms: ... runqueue=354 [51 45 33 32 15 20 8 7 5 42 6 0] runqueue is the length of global runable goroutine queue. numbers in bracket are length of per process queue. an ideal situation is where all processes are busy runnnig goroutines and a reasonable runqueue length evenly distributed between all processes: SCHED 2449ms: gomaxprocs=12 idleprocs=0 threads=40 spinningthreads=1 idlethreads=1 runqueue=20 [20 20 20 20 20 20 20 20 20 20 20] looking at our schedtrace output we can see there are time frames when almost all processes are idle. this means we are not utilizing full cpu power. garbage collector trace To enable the garbage collector (GC) trace, run the program with GODEBUG=gctrace=1 environment variable: GODEBUG=gctrace=1 ./redins -c config1.json . . . gc 30 @3.727s 1%: 0.066+21+0.093 ms clock, 0.79+128/59/0+1.1 ms cpu, 67->71->45 MB, 76 MB goal, 12 P gc 31 @3.784s 2%: 0.030+27+0.053 ms clock, 0.36+177/81/7.8+0.63 ms cpu, 79->84->55 MB, 90 MB goal, 12 P gc 32 @3.858s 3%: 0.026+34+0.024 ms clock, 0.32+234/104/0+0.29 ms cpu, 96->100->65 MB, 110 MB goal, 12 P gc 33 @3.954s 3%: 0.026+44+0.13 ms clock, 0.32+191/131/57+1.6 ms cpu, 117->123->79 MB, 131 MB goal, 12 P gc 34 @4.077s 4%: 0.010+53+0.024 ms clock, 0.12+241/159/69+0.29 ms cpu, 142->147->91 MB, 158 MB goal, 12 P gc 35 @4.228s 5%: 0.017+61+0.12 ms clock, 0.20+296/179/94+1.5 ms cpu, 166->174->105 MB, 182 MB goal, 12 P gc 36 @4.391s 6%: 0.017+73+0.086 ms clock, 0.21+492/216/4.0+1.0 ms cpu, 191->198->122 MB, 210 MB goal, 12 P gc 37 @4.590s 7%: 0.049+85+0.095 ms clock, 0.59+618/253/0+1.1 ms cpu, 222->230->140 MB, 244 MB goal, 12 P . . . as we can see here, inuse memory is increasing and the amount of time needed for gc to do it’s job is also increasing. this means that we are consuming more memory than gc can process. more on GODEBUG and some other golang env variables here. enabling the profiler go tool pprof is the tool for analyzing and profiling data. there are two ways to set up pprof either by directly calling runtime/pprof functions like pprof.StartCPUProfile() in your code or setting up net/http/pprof http listener and getting data from there which is the way we used. pprof has very little overhead so it is safe to use in production, but profile endpoint should not be exposed publicly because they may reveal sensitive data. for the second option all we need to to do is import “net/http/pprof” package: import ( _ "net/http/pprof" ) then add a http listener: go func() { log.Println(http.ListenAndServe("localhost:6060", nil)) }() pprof has several default profiles: - allocs: A sampling of all past memory allocations - block: Stack traces that led to blocking on synchronization primitives - goroutine: Stack traces of all current goroutines - heap: A sampling of memory allocations of live objects. - mutex: Stack traces of holders of contended mutexes - profile: CPU profile. - threadcreate: Stack traces that led to the creation of new OS threads - trace: A trace of execution of the current program. note: trace endpoint unlike all other endpoints is a trace profile not a pprof profile, you can view it using go tool trace instead of go tool pprof. now that we have our tools up and running we can look at the available tools. cpu profiler $ go tool pprof cpu profiler runs for 30 seconds by default (we can change this with seconds parameter) and collect samples every 100 milliseconds then it enters the interactive mode. there are several commands available the most common are top, list, web use top n to view top hottest entries in text format, there are two options to sort the output, -cum for cumulative order and -flat (pprof) top 10 -cum Showing nodes accounting for 1.50s, 6.19% of 24.23s total Dropped 347 nodes (cum <= 0.12s) Showing top 10 nodes out of 186 flat flat% sum% cum cum% 0.03s 0.12% 0.12% 16.7s 69.13% (*Server).serveUDPPacket 0.05s 0.21% 0.33% 15.6s 64.51% (*Server).serveDNS 0 0% 0.33% 14.3s 59.10% (*ServeMux).ServeDNS 0 0% 0.33% 14.2s 58.73% HandlerFunc.ServeDNS 0.01s 0.04% 0.37% 14.2s 58.73% main.handleRequest 0.07s 0.29% 0.66% 13.5s 56.00% (*DnsRequestHandler).HandleRequest 0.99s 4.09% 4.75% 7.56s 31.20% runtime.gentraceback 0.02s 0.08% 4.83% 7.02s 28.97% runtime.systemstack 0.31s 1.28% 6.11% 6.62s 27.32% runtime.mallocgc 0.02s 0.08% 6.19% 6.35s 26.21% (*DnsRequestHandler).FindANAME (pprof) use list to investigate a single function. (pprof) list handleRequest Total: 24.23s ROUTINE ======================== main.handleRequest in /home/arash/go/src/arvancloud/redins/redins.go 10ms 14.23s (flat, cum) 58.73% of Total . . 35: l *handler.RateLimiter . . 36: configFile string . . 37:) . . 38: . . 39:func handleRequest(w dns.ResponseWriter, r *dns.Msg) { 10ms 610ms 40: context := handler.NewRequestContext(w, r) . 50ms 41: logger.Default.Debugf("handle request: [%d] %s %s", r.Id, context.RawName(), context.Type()) . . 42: . . 43: if l.CanHandle(context.IP()) { . 13.57s 44: h.HandleRequest(context) . . 45: } else { . . 46: context.Response(dns.RcodeRefused) . . 47: } . . 48:} . . 49: (pprof) web command can be used to generate a SVG graph of hotsopts and opens it in a browser. (pprof)web handleRequest having lots of time spent in GC functions like runtime.mallocgc often means heavy allocation, which can put extra pressure on garbage collector and increase latency. having lots of time spent on synchronization mechanisms like runtime.chansend or runtime.lock could be a sign of contention having lots of time spent in syscall.Read/Write mean exsessive use of io operations memory profiler $ go tool pprof by default it shows lifetime allocated memory. we can see number of allocated objects using -alloc_objects, other useful options are -iuse_objects and -inuse_space for inspecting live memory. generally if you want to reduce memory consumption you need to look at -inuse_space but if you want to improve latency look at -alloc_objects after a suficient execution time/load. identifying the bottleneck it is important to first identify the type of bottleneck (cpu, io, memory) we are dealing with. aside from profilers, there’s another kind of tool available. go tool trace can show what our goroutines are really doing in details. to collect trace sample we need to send a http request to trace endpoint: $ curl --output trace.out generated file can be viewed using trace tool: $ go tool trace trace.out 2019/12/25 15:30:50 Parsing trace... 2019/12/25 15:30:59 Splitting trace... 2019/12/25 15:31:10 Opening browser. Trace viewer is listening on go tool trace is a web app which uses Chrome DevTools protocol, and only compatible with chrome browsers. main page looks something similar to this : View trace (0s-409.575266ms) View trace (411.075559ms-747.252311ms) View trace (747.252311ms-1.234968945s) View trace (1.234968945s-1.774245108s) View trace (1.774245484s-2.111339514s) View trace (2.111339514s-2.674030898s) View trace (2.674031362s-3.044145798s) View trace (3.044145798s-3.458795252s) View trace (3.43953778s-4.075080634s) View trace (4.075081098s-4.439271287s) View trace (4.439271635s-4.814869651s) View trace (4.814869651s-5.253597835s) Goroutine analysis Network blocking profile (⬇) Synchronization blocking profile (⬇) Syscall blocking profile (⬇) Scheduler latency profile (⬇) User-defined tasks User-defined regions Minimum mutator utilization trace splits trace time to make sure your browser can handle it. there are myriads of data here which makes it almost decipherable if we don’t now what we are looking for. let’s leave it for now. the next link on the main page is “goroutine analysis” which shows different kind of goroutines running in the program during the trace period: Goroutines: github.com/miekg/dns.(*Server).serveUDPPacket N=441703 runtime.gcBgMarkWorker N=12 github.com/karlseguin/ccache.(*Cache).worker N=2 main.Start.func1 N=1 runtime.bgsweep N=1 arvancloud/redins/handler.NewHandler.func2 N=1 runtime/trace.Start.func1 N=1 net/http.(*conn).serve N=1 runtime.timerproc N=3 net/http.(*connReader).backgroundRead N=1 N=40 click on the first item with N=441703 and this is what we get: this is very interesting. most of goroutines spend almost no time in execution and most of the time is spend in Sync block. let’s have a closer look at one of them: it appears our goroutine is almost always inactive waiting on a rwlock. from here we can directly go to block tool; blocking profile is disabled by default, we first need to enable it in our code: runtime.SetBlockProfileRate(1) now we can get our block samples: $ go tool pprof (pprof) top Showing nodes accounting for 16.03wks, 99.75% of 16.07wks total Dropped 87 nodes (cum <= 0.08wks) Showing top 10 nodes out of 27 flat flat% sum% cum cum% 10.78wks 67.08% 67.08% 10.78wks 67.08% internal/poll.(*fdMutex).rwlock 5.25wks 32.67% 99.75% 5.25wks 32.67% sync.(*Mutex).Lock 0 0% 99.75% 5.25wks 32.67% arvancloud/redins/handler.(*DnsRequestHandler).Filter 0 0% 99.75% 5.25wks 32.68% arvancloud/redins/handler.(*DnsRequestHandler).FindANAME 0 0% 99.75% 16.04wks 99.81% arvancloud/redins/handler.(*DnsRequestHandler).HandleRequest 0 0% 99.75% 10.78wks 67.08% arvancloud/redins/handler.(*DnsRequestHandler).Response 0 0% 99.75% 10.78wks 67.08% arvancloud/redins/handler.(*RequestContext).Response 0 0% 99.75% 5.25wks 32.67% arvancloud/redins/handler.ChooseIp 0 0% 99.75% 16.04wks 99.81% github.com/miekg/dns.(*ServeMux).ServeDNS 0 0% 99.75% 16.04wks 99.81% github.com/miekg/dns.(*Server).serveDNS (pprof) here we have two different lock (poll.fdMutex and sync.Mutex) responsible for almost 100% of blocks. this verifies our guess about lock contention, now we only need to find were these happens: (pprof) svg lock this command creates a vector graph of all nodes accounting for contention with focus on lock functions: we can get the same result from our goroutine endpoint: $ go tool pprof and then: (pprof) top Showing nodes accounting for 294412, 100% of 294424 total Dropped 84 nodes (cum <= 1472) Showing top 10 nodes out of 32 flat flat% sum% cum cum% 294404 100% 100% 294404 100% runtime.gopark 8 0.0027% 100% 294405 100% github.com/miekg/dns.(*Server).serveUDPPacket 0 0% 100% 58257 19.79% arvancloud/redins/handler.(*DnsRequestHandler).Filter 0 0% 100% 58259 19.79% arvancloud/redins/handler.(*DnsRequestHandler).FindANAME 0 0% 100% 293852 99.81% arvancloud/redins/handler.(*DnsRequestHandler).HandleRequest 0 0% 100% 235406 79.95% arvancloud/redins/handler.(*DnsRequestHandler).Response 0 0% 100% 235406 79.95% arvancloud/redins/handler.(*RequestContext).Response 0 0% 100% 58140 19.75% arvancloud/redins/handler.ChooseIp 0 0% 100% 293852 99.81% github.com/miekg/dns.(*ServeMux).ServeDNS 0 0% 100% 293900 99.82% github.com/miekg/dns.(*Server).serveDNS (pprof) almost all our goroutines are staying at runtime.gopark, this is go scheduler putting goroutines to sleep; a very common cause for this to happen is lock contention (pprof) svg gopark here we have our two sources of contention: UDPConn.WriteMsg() looks like all responses ended up writing to the same fd (hence the lock), this makes sense because they all have the same source address. we did a little experiment on different solutions, at the end we decided to use multiple listeners to balance the load, this way we let OS balance incoming request between different connection and reduce contention. Rand() looks like there’s a lock underneath generic math/rand functions (more on this here). this can be easily fixed using Rand.New() which creates a random generator without the locking wrapper rg := rand.New(rand.NewSource(int64(time.Now().Nanosecond()))) this is a little better but creating a new source every time is expensive. can we do better? in our case we don’t really need random number. we just need an even distribution for our load balancing and it turns out that Time.Nanoseconds() can do just fine. now that we have eliminated all extra blockings. let’s see the results: looks better but still most of time is spent on sync block. let’s take a look at synchronization blocking profile from trace UI main page: let’s take a look at ccache promote function from pprof’s block endpoint: (pprof) list promote ROUTINE ======================== github.com/karlseguin/ccache.(*Cache).promote in ... 0 9.66days (flat, cum) 99.70% of Total . . 155: h.Write([]byte(key)) . . 156: return c.buckets[h.Sum32()&c.bucketMask] . . 157:} . . 158: . . 159:func (c *Cache) promote(item *Item) { . 9.66days 160: c.promotables <- item . . 161:} . . 162: . . 163:func (c *Cache) worker() { . . 164: defer close(c.donec) . . 165: all ccache.Get() calls end up sending to a single c.promotables channel. cache being a crucial part of our service, we have to consider other options; Dgraph has an excellent article about state of cache in go, they also have an excellent cache module called ristretto. unfortunately ristretto doesn’t support Ttl based eviction yet, we could workaround this problem by using a very large MaxCost and keep a timeout value in our cache struct (we wish to keep stale data in cache). let’s see the result using ristretto: Great! we managed to reduce maximum goroutine runtime from 5000 ms to 22 ms. still most of the execution time is split between “sync block” and “”scheduler wait”. let’s see if there’s anything we can do about that: there’s little more we can do about fdMutex.rwlock let’s now focus on the other one : gcMarkDone which is responsible for 53% of block time. this function is part of go garbage collection process. having these on hot spot are often a sign that we are putting a lot of pressure on gc. alloc optimization at this point it may be useful to see how go garbage collection works; go uses a tri-color mark and sweep collector. it keeps tracking of everything that’s allocated and once it reaches twice (or whatever value GOGC is set to) the size of previous size, GC sweep starts. mark happens in three phases: - Mark Setup (STW) - Marking (concurrent) - Mark Termination (STW) Stop The World phases put the entire exectution to halt, although they’re generally very short, tight loops can extend their duration. that’s because currently (go v1.13) goroutines are only preemptible at function call points, thus it is possible for a tight loop to cause arbitrarily long pause time since GC waits for all goroutines to stop. during marking gc utilizes about 25% of GOMAXPROCS but additional goroutines can be forced into mark assist, this happens when a rapidly allocating goroutine outruns the background marker, in order to reduce the latency caused by gc we need minimize heap usage; there are two things to note: - number of allocations matters more than size (e.g 1000 allocations of a 20 bytes struct puts much more stress on heap than a single 20000 bytes allocation) - unlike languages like C/C++, not all allocations end up in heap. go compiler decides whether a variable escapes to heap or it can be allocated inside stack frame. unlike heap-allocated variables, stack-allocated variables do not put pressure on gc for more information on go memory model and gc design check this presentation. for alloc optimization we use a collection of go tools: - cpu profiler to find hot allocations - memory profiler to track allocations - tracer for GC patterns - escape analysis to find why allocations happen let’s start with cpu profiler: $ go tool pprof (pprof) top 20 -cum Showing nodes accounting for 7.27s, 29.10% of 24.98s total Dropped 315 nodes (cum <= 0.12s) Showing top 20 nodes out of 201 flat flat% sum% cum cum% 0 0% 0% 16.42s 65.73% github.com/miekg/dns.(*Server).serveUDPPacket 0.02s 0.08% 0.08% 16.02s 64.13% github.com/miekg/dns.(*Server).serveDNS 0.02s 0.08% 0.16% 13.69s 54.80% github.com/miekg/dns.(*ServeMux).ServeDNS 0.01s 0.04% 0.2% 13.48s 53.96% github.com/miekg/dns.HandlerFunc.ServeDNS 0.02s 0.08% 0.28% 13.47s 53.92% main.handleRequest 0.24s 0.96% 1.24% 12.50s 50.04% arvancloud/redins/handler.(*DnsRequestHandler).HandleRequest 0.81s 3.24% 4.48% 6.91s 27.66% runtime.gentraceback 3.82s 15.29% 19.78% 5.48s 21.94% syscall.Syscall 0.02s 0.08% 19.86% 5.44s 21.78% arvancloud/redins/handler.(*DnsRequestHandler).Response 0.06s 0.24% 20.10% 5.25s 21.02% arvancloud/redins/handler.(*RequestContext).Response 0.03s 0.12% 20.22% 4.97s 19.90% arvancloud/redins/handler.(*DnsRequestHandler).FindANAME 0.56s 2.24% 22.46% 4.92s 19.70% runtime.mallocgc 0.07s 0.28% 22.74% 4.90s 19.62% github.com/miekg/dns.(*response).WriteMsg 0.04s 0.16% 22.90% 4.40s 17.61% github.com/miekg/dns.(*response).Write 0.01s 0.04% 22.94% 4.36s 17.45% github.com/miekg/dns.WriteToSessionUDP 1.43s 5.72% 28.66% 4.30s 17.21% runtime.pcvalue 0.01s 0.04% 28.70% 4.15s 16.61% runtime.newstack 0.06s 0.24% 28.94% 4.09s 16.37% runtime.copystack 0.01s 0.04% 28.98% 4.05s 16.21% net.(*UDPConn).WriteMsgUDP 0.03s 0.12% 29.10% 4.04s 16.17% net.(*UDPConn).writeMsg we are particularly intereseted in functions linked with mallocgc, this is where mark assists happen (pprof) svg mallocgc we can track allocation using alloc endpoint, alloc_object option means total allocations count, there are other options for in use memory and allocation space. $ go tool pprof -alloc_objects (pprof) top -cum Active filters: show=handler Showing nodes accounting for 58464353, 59.78% of 97803168 total Dropped 1 node (cum <= 489015) Showing top 10 nodes out of 19 flat flat% sum% cum cum% 15401215 15.75% 15.75% 70279955 71.86% arvancloud/redins/handler.(*DnsRequestHandler).HandleRequest 2392100 2.45% 18.19% 27198697 27.81% arvancloud/redins/handler.(*DnsRequestHandler).FindANAME 711174 0.73% 18.92% 14936976 15.27% arvancloud/redins/handler.(*DnsRequestHandler).Filter 0 0% 18.92% 14161410 14.48% arvancloud/redins/handler.(*DnsRequestHandler).Response 14161410 14.48% 33.40% 14161410 14.48% arvancloud/redins/handler.(*RequestContext).Response 7284487 7.45% 40.85% 11118401 11.37% arvancloud/redins/handler.NewRequestContext 10439697 10.67% 51.52% 10439697 10.67% arvancloud/redins/handler.reverseZone 0 0% 51.52% 10371430 10.60% arvancloud/redins/handler.(*DnsRequestHandler).FindZone 2680723 2.74% 54.26% 8022046 8.20% arvancloud/redins/handler.(*GeoIp).GetSameCountry 5393547 5.51% 59.78% 5393547 5.51% arvancloud/redins/handler.(*DnsRequestHandler).LoadLocation from here on we can use list on each function and see if we can reduce memory allocation. let’s check a few : printf-like functions (pprof) list handleRequest Total: 97803168 ROUTINE ======================== main.handleRequest in /home/arash/go/src/arvancloud/redins/redins.go 2555943 83954299 (flat, cum) 85.84% of Total . . 35: l *handler.RateLimiter . . 36: configFile string . . 37:) . . 38: . . 39:func handleRequest(w dns.ResponseWriter, r *dns.Msg) { . 11118401 40: context := handler.NewRequestContext(w, r) 2555943 2555943 41: logger.Default.Debugf("handle request: [%d] %s %s", r.Id, context.RawName(), context.Type()) . . 42: . . 43: if l.CanHandle(context.IP()) { . 70279955 44: h.HandleRequest(context) . . 45: } else { . . 46: context.Response(dns.RcodeRefused) . . 47: } . . 48:} . . 49: line 41 is particularly interesting, even when debug is disabled there’s still memory allocation, we can use escape analysis to investigate it more go escape analysis tool is actually a compiler flag $ go build -gcflags '-m' you can add another -m for more information $ go build -gcflags '-m ' for a better interface use view-annotated-file. $ go build -gcflags '-m' . . .../redins.go:39:20: leaking param: w ./redins.go:39:42: leaking param: r ./redins.go:41:55: r.MsgHdr.Id escapes to heap ./redins.go:41:75: context.RawName() escapes to heap ./redins.go:41:91: context.Request.Type() escapes to heap ./redins.go:41:23: handleRequest []interface {} literal does not escape ./redins.go:219:17: leaking param: path. . . here, all Debugf parameters escape to heap. this happens because of the way Debugf is defined: func (l *EventLogger) Debugf(format string, args ...interface{}) all args parameters convert to interface{} type which always escape to heap. we can either remove debug logs or use a zero allocation log library like zerolog. for more information about escape analysis see “allocation eficiency in golang”. string manipulation (pprof) list reverseZone Total: 100817064 ROUTINE ======================== arvancloud/redins/handler.reverseZone in /home/arash/go/src/arvancloud/redins/handler/handler.go 6127746 10379086 (flat, cum) 10.29% of Total . . 396: logger.Default.Warning("log queue is full") . . 397: } . . 398:} . . 399: . . 400:func reverseZone(zone string) string { . 4251340 401: x := strings.Split(zone, ".") . . 402: var y string . . 403: for i := len(x) - 1; i >= 0; i-- { 6127746 6127746 404: y += x[i] + "." . . 405: } . . 406: return y . . 407:} . . 408: . . 409:func (h *DnsRequestHandler) LoadZones() { (pprof) Since Go’s string is immutable, making temporary string cause allocations. Beginning with Go 1.10 there is a strings.Builder to efficiently build a string. (pprof) list reverseZone Total: 93437002 ROUTINE ======================== arvancloud/redins/handler.reverseZone in /home/arash/go/src/arvancloud/redins/handler/handler.go 0 7580611 (flat, cum) 8.11% of Total . . 396: logger.Default.Warning("log queue is full") . . 397: } . . 398:} . . 399: . . 400:func reverseZone(zone string) string { . 3681140 401: x := strings.Split(zone, ".") . . 402: var sb strings.Builder . 3899471 403: sb.Grow(len(zone)+1) . . 404: for i := len(x) - 1; i >= 0; i-- { . . 405: sb.WriteString(x[i]) . . 406: sb.WriteByte('.') . . 407: } . . 408: return sb.String() since we don’t care about the value of reversed string we can eliminate Split() by simply reversing the whole string. (pprof) list reverseZone Total: 89094296 ROUTINE ======================== arvancloud/redins/handler.reverseZone in /home/arash/go/src/arvancloud/redins/handler/handler.go 3801168 3801168 (flat, cum) 4.27% of Total . . 400:func reverseZone(zone string) []byte { . . 401: runes := []rune("." + zone) . . 402: for i, j := 0, len(runes)-1; i < j; i, j = i+1, j-1 { . . 403: runes[i], runes[j] = runes[j], runes[i] . . 404: } 3801168 3801168 405: return []byte(string(runes)) . . 406:} . . 407: . . 408:func (h *DnsRequestHandler) LoadZones() { . . 409: h.LastZoneUpdate = time.Now() . . 410: zones, err := h.Redis.SMembers("redins:zones") more on string manipulation here. sync.Pool (pprof) list GetASN Total: 69005282 ROUTINE ======================== arvancloud/redins/handler.(*GeoIp).GetASN in /home/arash/go/src/arvancloud/redins/handler/geoip.go 1146897 1146897 (flat, cum) 1.66% of Total . . 231:func (g *GeoIp) GetASN(ip net.IP) (uint, error) { 1146897 1146897 232: var record struct { . . 233: AutonomousSystemNumber uint `maxminddb:"autonomous_system_number"` . . 234: } . . 235: err := g.ASNDB.Lookup(ip, &record) . . 236: if err != nil { . . 237: logger.Default.Errorf("lookup failed : %s", err)(pprof) list GetGeoLocation Total: 69005282 ROUTINE ======================== arvancloud/redins/handler.(*GeoIp).GetGeoLocation in /home/arash/go/src/arvancloud/redins/handler/geoip.go 1376298 3604572 (flat, cum) 5.22% of Total . . 207: . . 208:func (g *GeoIp) GetGeoLocation(ip net.IP) (latitude float64, longitude float64, country string, err error) { . . 209: if !g.Enable || g.CountryDB == nil { . . 210: return . . 211: } 1376298 1376298 212: var record struct { . . 213: Location struct { . . 214: Latitude float64 `maxminddb:"latitude"` . . 215: LongitudeOffset uintptr `maxminddb:"longitude"` . . 216: } `maxminddb:"location"` . . 217: Country struct { . . 218: ISOCode string `maxminddb:"iso_code"` . . 219: } `maxminddb:"country"` . . 220: } . . 221: // logger.Default.Debugf("ip : %s", ip) . . 222: if err := g.CountryDB.Lookup(ip, &record); err != nil { . . 223: logger.Default.Errorf("lookup failed : %s", err) . . 224: return 0, 0, "", err . . 225: } . 2228274 226: _ = g.CountryDB.Decode(record.Location.LongitudeOffset, &longitude) . . 227: // logger.Default.Debug("lat = ", record.Location.Latitude, " lang = ", longitude, " country = ", record.Country.ISOCode) . . 228: return record.Location.Latitude, longitude, record.Country.ISOCode, nil . . 229:} . . 230: . . 231:func (g *GeoIp) GetASN(ip net.IP) (uint, error) { we use maxmiddb functions to get geolocation data. these functions take interface{} as parameters which as we saw earlier can cause heap escapes. we can use sync.Pool to cache allocated but unused items for later reuse type MMDBGeoLocation struct { Coordinations struct { Latitude float64 `maxminddb:"latitude"` Longitude float64 LongitudeOffset uintptr `maxminddb:"longitude"` } `maxminddb:"location"` Country struct { ISOCode string `maxminddb:"iso_code"` } `maxminddb:"country"` } type MMDBASN struct { AutonomousSystemNumber uint `maxminddb:"autonomous_system_number"` }func (g *GeoIp) GetGeoLocation(ip net.IP) (*MMDBGeoLocation, error) { if !g.Enable || g.CountryDB == nil { return nil, EMMDBNotAvailable } var record *MMDBGeoLocation = g.LocationPool.Get().(*MMDBGeoLocation) logger.Default.Debugf("ip : %s", ip) if err := g.CountryDB.Lookup(ip, &record); err != nil { logger.Default.Errorf("lookup failed : %s", err) return nil, err } _ = g.CountryDB.Decode(record.Coordinations.LongitudeOffset, &record.Coordinations.Longitude) logger.Default.Debug("lat = ", record.Coordinations.Latitude, " lang = ", record.Coordinations.Longitude, " country = ", record.Country.ISOCode) return record, nil } func (g *GeoIp) GetASN(ip net.IP) (uint, error) { var record *MMDBASN = g.AsnPool.Get().(*MMDBASN) err := g.ASNDB.Lookup(ip, record) if err != nil { logger.Default.Errorf("lookup failed : %s", err) return 0, err } logger.Default.Debug("asn = ", record.AutonomousSystemNumber) return record.AutonomousSystemNumber, nil } there are many other small optimimazions possible, but at this point it seems we have done enough. for more information about memory optimization techniques check Allocation efficiency in high-performance Go services results two visualize the result of our memory optimizations we use a diagram in go tool trace called “Minimum Mutator Utilization”, here Mutator means not gc. before optimizations: here we have a window of about 500 milliseconds while we have almost no utilization(gc is consuming all resources) and we never get past 80% utilization in the long run. we want to have the zero utilization window as small as possible and get to 100% percent utilization as fast as possible, something like this: after optimizations: conclusion by using go tools we managed to optimize our service to handle high load of requests and better utilize system recources. you can check our source code on github. here is unoptimized version and here is the optimized version.
https://medium.com/@arash.cordi/how-we-optimized-our-dns-server-using-go-tools-d753e1a5e709
CC-MAIN-2020-05
refinedweb
4,919
60.41
- Index was out of range - XmlWriter localization - WCF / wsHttpBinding / Digital Signature Corruption (!!) - radio button problems - Specified Cast is not valid - Image save - Maximum number of Hyperlinks? - Clicking Button on web page using C# - Using C#, I need to get an array of doubles from unmanaged C++. - VB.net button to load form? - Running VBScripts - Transforming a data set to Excel using XSL - DateTime not taking Daylight Savings into consideration - How do I create a Generic.List? - Exporting data to Excel, strange problem - The requested address is not valid in its context ... IpAddress - changing database systems - Any advice on the Proveit.com tests for VB6 or .NET framework? - Converting a mini C# program to a standalone (C++) binary - Images from files shrink? - C# Uninstall Shortcut and Command Line Arguments - WEB XML SERVICE - C#-APP: ListBox Item Custom Background Drawing - .net reportviewer - MDI Forms in C# - Monitor Size - VNC client embedded in Windows Forms - Change Font Family C# - convertion of .aspx page to html page in ftp - invalidoperationexception -cannot commit or quit a cell value change - registering dll in vb.net - convert LPWSTR to LPTSTR - How widespread is .Net Framework 1.1.4322 ? - How widespread is Framework 1.1.4322? - Difficulty when deleting row from a gridview - How to handle a LostFocus Event for a Textbox in webform - Help with WriteFile and ReadFile - dynamic SQl statements in datagrid - VS 2005 upgrade issue - ListBox in dynamically created UserControl loses selected index. - Help regarding cell click event in datagridview - Logins - Re: Visibility of GridView - web service with an xml schema - Hi - [vb.net 2005] Split listbox into textbox? - images - How to deflect a line - NHibernate connection string - Saving Data From Datagrid - the namespace using System.Runtime.Remoting.Channels.http is not coming - C#-APP: how to program the port 80? - pop-ups - How to extract attachment on the .MSG file ? - PDF conversion in tiff - adding rows in gridview - MPP Integration in .NET Application. - hi - Urgent Problem - How can i Upload FCKEditor with my web application - Html Encode Decode - How to add or remove event of ASP.Net control at runtime? - Should i use BackgroundWorker? - WebException Error. Operation has timedout - File Save Event in Web Browser C# - DllImport issue for relative path! - regarding datagrid - how i can check questons which i have posted here and their ansers - Changing the Database - DOT NET Interview Questions and Answers - Printing columns of numbers and align numbers - Error when create application in ASP.NET 2.0 - telnet connection - telnet connection - open an internet explorer - using class file - SplashWindow - i want to check the "mms" url format validation in ASP.NET C# - Form Sequence call Layout - How to load the DLL functions in VC++.net - Cannot declare a class inside a function - transaction scope - Run GUI app in background - Displaying Form on Second Monitor - event and delegate - msbuild with msbee error - How to Populate DataSet With XML Derived Schema? - textbox.text to array or arraylist - Auto fill web page using C# windows application - xml serialization and conditional attributes - A tough question- encoding/charset - Button vs TextBox Height - Session State Error - C# Forms App threading and events - can we use Configuration, ConfigurationManager in Vb.net 2003 - Access violation in AFX_MAINTAIN_STATE2::AFX_MAINTAIN_STATE2 - The .NET "ActiveX" control - treeview event - CrystalReportsViewer with .NET losing objects - Memory Error - DEP stops Windows Mail - w2003s & .NET 1.1 - Migration to 2.0/W2003 causes "has encountered a problem and needs to close' - VS 2008 Beta 2 - Only See HTML Tool Box Group - difference between a console app and a win forms app - Vista security problem - Fatal System Error - Consuming JDeveloper Web Service in ASP.NET C# - Kogon failure after cloning - Failed to map path '/aspnet_client/system_web/2_0_50727/webform.js' - application deployment options - Can not uninstall or update .net framework 1.1 and 2.0 - How to Search Database for valid number? - RDP Virtual Channels - oracle db connectionstring problem - nested dictionaries - better ideas? - Excel Help - Set selected item in combo box - Javascript postback onClick event missing from datagrid update button - A severe error occurred on the current command - help - ds. relations problem with dataset - Bitmap Image Processing - VBCodeProvider & code compilation - are application classes visibl - Database Synchronisation Windows CE - 100,000 calls a minute to a web service - Securig Non-Asp.net files - Sending Mail through SMTP in ASP.Net - Crystal reports without using database/dataset in vb.net 2005 - .Net C# Ascending sort of ArrayList with Hashtables - How Can I open a Exsting PDF File - problem in uploading the FCKEditor - net framework - need a pointer to a struct/class HELP!!! - how to disable selectedindexchanged event of dropdownlist - Set-up file for a web application - MailObj newlines? - Referenced Assemblies in ICodeCompiler.parms (CompileParameters) - flickering image in windows C# application - Saving Images - Add connection using Data Source Configuration Wizard - Product Master Management - Realeasing file lock? - print time and date on button click - Binding a TextBox to Xml ASP.Net - Encryption of QueryString Data in asp.net - How to click a link/button using C# - No changes css in different system resolution - Socket Programming - WndProc - Unlock the drive - Treeview problem(pls send me a solutin i really frustrate) - code to move files from directory to another directory - i need c#.coding to get "login&logout" time and date of user - "Object reference not set to an instance of an object.".....error - IsPostBack problem... - vb.net - "Object reference not set to an instance of an object.".....error - display that xml document as a browser colour - Print by dialog box - Webparts - Is MicrosoftVisualStudio 2005 different from Microsoft VisualStudio .NET - pdf file - Problem checking SQL query result in c# - Help with Visual Studio 2005 Forms.Show and Forms.ShowDialog - Script control - How to read Pop3 email - need help c# conceptual problem - New Solution - C# Running a Word Macro messes up Word Setting - Another can't send email post, pls help - Delete a row from Gridview - addhandler not working? Vb.net - Beginner guide (web service novice wants to become a guru) - MSINET.OCX - Net 2 Serialport OnDataReceived - Data Grid Updation in Vb dot net 2005 - How to check if a file exists in network/ - WCF runtime error: FaultException was unhandled by user code - add schemaLocation - Problem with programmatically adding combo boxes - deleting messages on oulook express - C# PF Usage OutOfMemory with Build version of Application - How to convert a .NET application to webservice? - Web services and incorrect handling of time zones in DateTime - Macro: BuildEvents.OnBuildProjConfigDone and Threading - VC++2003.NET to Visual Studio EXPRESS - SOAP serialization of nullable types and remoting - not supported? - data entry form update using command builder - Please Help me(Send Message using C#) - Unable to delete a row in a gridview - setting label background color with style - XP Silver skin in vb.net - Dual Boot with two SATA HDD - ComboBox - sending email using asp.net with C# - Error - Is Mutex Owned? - NtBackup error invalid drive or no access & specified media not fo - formatnumber is not taking thousands - Progress Bar - data relations - how to get just one record in gridview - Create a Random number be in the Around!!! - how to display one filtered record in gridview (ASP .NET & C#) - C#-Windows: Backgroundworker - Put COM dll in GAC? - XML encoding problems when storing to sql 2005 database. - ADMT v2 test migration changes DOMAIN membership - XML namespaces and XSD.exe - [c# form] debug with command line params vs2003 - cs0117 compilation error - is it possible to run a dts through vb.net? - sending email in asp.net - Installation in vb.net - how can i save the drop downs selected index while going to onw page and coming back - advanced .net - extern "C" is ignored - How to Filling resource files at run time - How do I convert an IPv4 addres to IPv6 in C#? - When Windows is shuting down... - XML storing and Management - "change the location for text" - memorystream.toarray() - SQL Server - Clearing Memory - New form closing error - Generate DLLs in .Net windows applications - vb 2005: scrolltocaret() - Using C# can i have a client on linux and server on windows - Generating xml using enterprise architect - Generating xml using enterprise architect - "The ServicedComponent being invoked is not correctly configured (Use - Component Designer - msddslmp.dll not found failing to insatall .net 2003 - Set-up file for a web application - Calaculation of XIRR by using C#(.net) - long process on Form Load Event cause control to show delay any suggestion ? - VB 2005: Get Caret Position - Would a lack of line breaks in a doc cause parsing problems ? - how to use Media player control in Vb.net Forms - import the decoded information/data into Microsoft Acess - How To Save Check Box Check Values in Button Using C# Web Application - How to convert xml tag data into cdata format - Binding a TextBox to Xml ASP.Net - running a web application from browser - sorting the alphanumeric strings - Versioning of exe - Example of form connection - How to Convert VC6 to C# - Very urgent - Background worker in vb.net - ListView problem - How To Fix Size Of A Page In Printer With The Help Of Application - to solve postback problem in c# windows application - To print Html page using PrintDialog and Print Document - Initializing components on a form to null - import data from vb.net to miscrosoft access - Error while Zipping A folder. - Checking Duplicate Values in a List box.... - Using TAP messaging protocol - class file in c# - problem with serial communication in c# using mscom ocx control - Exception from HRESULT: 0x800A1F52 - Convert C++ to C# - Adding two text box and getting result - Leading and Kerning of the Text - Why This error? code on APP.CONFIG - how to convert 4 bytes to IEEE 32 Bit Floating point format - Xml Serialization the same class may have multiple namespaces - beginner's query - Connecting to Cisco VPN from Windows Mobile - HoW To DeClaRE VaLUe FrOM TeXT BoX To DaTE FoRMaT - New to asp.net - Setting FormView Text and Calendar data from code-behind page - OLEDB update/insert from data array failing data adapter update - Help in using queries from MS Access in Visual C# .NET - How to save/load a Type in Xml - Monitor display - ShowmodalDialog - C++/CLI DateTime method argument - memory usage - please, help - Updating table - Binding TextBox to XML ASP.Net C# - Missing Deprecated Warnings - Formatting Characters - if anybody can help? - Problem with casting - doubt: setting intervals in a loop - InsertParameter in iDictionary but Insert doesn't include all values - Hiding EditCommandColumn - .net 2005 convert from VB to c++ - unmanaged dll calls and locks managed dll - Programmatically triggering a button from another form in C# - Binding scrollbars in C# - c# how to copy all files in temporary internet files folder - Dynamic Powerpoint Slides - Passing values in a gridview to another page when clicking on the link field - C#-P/Invoke: How to call function that's return value is a struct - fixe gridview header - VERY SLOW EXECUTION - VC# APPLICATION with MS SQL 2000 - Outlook Tasks - Just Started Using C# - URL string manipulation - colors in xml - example of Inserting and Retrieving data from xml file - Receive POP3 e-mails as .eml file - doubt in abstract class and interface - ASP.NET / Treeview / Drag and Drop - Defining/accessing xml-rpc webservice structures - ASP.NET with CRYSTAL REPORT in VISUAL STUDIO 2003 - Select File Dialog - User control - NoT Normal Datagrid / ListView - Reg: SQL Query.. - Guidance needed to study web service. - Retrieve data from unmanaged code - IViewObject + SetAdvise Not Working - Asynchronous clash - winforms - Looking for a good reference book - Getting Beta Software on a DVD - .net1.1 and excel automation problem -- "excel has encountered a problem and needs to be closed" - How to find closing brace? - master detail vb.net 1.1 - How can i find names in a textbox in VB.NET - restoring a minimized window - do release builds have the same amount of info in exceptions? e.g. will exceptions cought in release builds contain stack trace etc.? - do release builds have the same amount of info in exceptions? e.g. will exceptions cought in release builds contain stack trace etc.? - .net 2.0 and my application DLL - declaring a string[] question - Buttons on the top right corner of a windows form - C# \ C++ DataGridViewComboBoxColumn Issues - Application update - C# help - .NET 1.0 SP 3 fails to install - Altova's 2008 XML product line is available - Insert Image to a database - Which pdf forms solution should I use? - Managing multiple project in visual studio - C# Win App class problem - Services - Difference between J2EE and .NET - Redistributable package - Activity on this forum - unable to start conversations!! help!! - Problems with Release Version of C++ Web Service - Server Erorr - .NET 2.0 and Windows 2000 - Problems #include'ing a file - How do I make a column in a Gridview visible after checking a checkbox in ASP.NET? - VB.NET: How to Convert Alphabetic Numbers to Integers? - MSVCR80.DLL version conflict - gridviewfill - Update Database using DataSet - program throws not found or not supported exception while using Managment Event - Find Best Match - Need to inner join two tables in a dataset - SetChildIndex at Design Time - loop through tables inside .mdb file using VB.NET - Reference of class - Attach CheckedListBox in DataGridViewColumn Using VB.Net - Windows communication foundation - Thread Pool Vs Thead - Excel - how to copy/paste/insert rows? C# - VB.NET and Class XmlSerialization Errors - ATLAS With FileUpload Control - how to read and write big file using c#? - Upload files to ftp through proxy - Trapping MouseMove outside the application - System.Net.Sockets.TcpListener - Problem with english Windows XP - Form Loadin is slow due to Background Image of Form - generating a crystal report depending on the selected item in a dropdownlist - Doubt with opening the file - returning more than one value....in .NET(C#). - messenger list control - C++/CLI protected delegate - Performance issue due to Background Image of Form - edit or delete xml document in webpage - expression validator - Calling Web form from user control - Attendance information retreival - SQL server - WebBrowser in .Net 3.5? - VB.NET Hex to Color - Show image in crytal report. - SFC Problem - Urgent: How does my VB.Net program detect the computer system time? - Release version crashes on the Multi-CPU system - Response.OutputStream.Write - Date format in DropDown - Sending multiple commands to the serial port - Gridview Calculation - How to create OLE Package with .NET? - C++/CLI static class and literal - Raising a cross application Event - change management / deployment of modifications question - .net controls advice - Downloading Pictures From Cell Phone To PC - My KeyPressEventHandler does NOT fire - MSCONFIG issues privileges error to Administrator account in XP - Vb.net Display Data In Textbox Or Label Through Dataset - ReportViewer:Data instance has not be supplied for DataSource - Using USB in C#? - desk top wallpaper - Resgen.exe error (error PRJ0002 : Error result -532459699 returned from 'C:\Program Files\Microsoft Visual Studio 8\SDK\v2.0\bin\resgen.exe') - code to get all records via store procedure in vb.net - Page cannot be displayed! - Is all this necessary???? - Only Allow Numbers, Periods and minus in a TextBox? (C#) - removing seconds from System.DateTime.Today.Now - Help a NewBeee Out somebody please - Access Session from another class? - DESKTOP ICONS ARE MISSING - Save HTML File - Getting pointer to the memory of MemoryStream - Problem with binding data in listboxes - Socket problem migrating to VISTA - Web Browser Control Locks after ShowDialog - how to do paging in datagrid using vb.net 1.1 - Detecting USB Device - Detecting USB Device - VS2008 b2: "error C2813: #import is not supported with /MP" - word file in sql server 2000 - windows service send xml to web application - c# with autocad - How to pass value in app.config - What am I missing - Retrieve value from Hashtable - How to retrieve query string values.. - what the code for dynemic connection of database in asp.net - Create The Project Of Expert Solution Sys. - asf - vb.net question - dynamic report using store procedure in vb.net - How to get DialogBox BkColor? Thanks!(Win32 SDK) - How to upload file using C# in windows platform - C# Hooking - Office 2003 standard edition upgrade - password rememberer in vb.net - how to connect server using socket ? - debugging xsl in vs2005 - C# 2.0 Push ref object onto stack - how to force a .net application to use .net 2.0 ? - Opening PDF files in publisher - how to force a .net application to use .net 2.0 ? - System.Windows.Controls.Button vs System.Windows.Forms.Button - Impersonation over multiple servers using WCF - Custom attributes in C# for method - simple node name question - Quick Launch Toolbar won't launch on startup - Windows XP - how to unlock design mode in asp.net development environment - Retrieve SelectedText in ComboBox - Retrieve a record from table and display it in a text box. - Self-Update App with GAC - web service with 100% CPU - Oye! serious import namespace problem! - Activesync error message 85010014 (desktop problem)... how to fix? - System.IO.File.Encrypt 2.0 in Windows Vista - Error with Visual Studio Team Suite - page expires on forward button - <input> file - Emulating Find/FindNext in C# via OleDB connection - Swapping Icons on a form -HELP- - MS SQL question - AJAX Question - Process.Start() in Web Service - I don't get it?!? - using brackets to describe root classes in VB.Net - maybe? - VB.NET multithreading, callbacks, and passing events to the main thread - read XML out of a DataSet - DataSet.Tables.Count giving different results on different m/c - Including one aspx page in another - Problems with IEnumerator: Enumerator is not started Exception - Problem opening excel file with ASP.NET - Suggestions for .NET Emails Please - Code to update row in grid view. - archana - Question about Web Service Method Versioning - Accessing COM error info from c# - Asp.Net Error While running in local host - Windows application with internet video streaming - how to use framework 1.1 in framework 2.0- visual studio 2005 - GetPrivateProfileString function - Deployment - Crystal Reports - C# -ASP.NET2.0 - ComponentGoWebCalendar Control - Associating a dropdownlist with datasource - XAMLReader for external xaml files and event handling - Combo box in vb.net windows - Event logging into a single textfile by more than one users at a time - VB .NET Commandline Argument questions - how can i pass a variable from a page to another in asp.net - Slow load of first node, xmltextreader - Database Connection - How to Display Text in TextBox in Web Application - Storing and Retrieving Values from App Config - How can I stream on LAN??? - How to read "long" value from Excel using C# - Problem with public static hashtable in C# - how to use XSD generated classes with infopath - Problem in Binding ArrayList to a dataGrid - Throw without parameter... - Automating software installation using C# - dynamic text align in dynamic - Session TimeOut for Idle User C# 2005 - I need a demo project on inventory database system with the backend SQL server databa - office automation project - I am getting NullReferenceException - To create a binary file library - C# application/octet-stream event - datagrid rowcolor dynamically - Exception from HRESULT : 0x800A03EC when trying to range value - To remove all assemblies from GAC and Native cache of a particular public key - Extracting DropDownList - unable to do sorting - FormLoad is Slow - Microsoft Mail Contacts - Export multiple worksheet to excel - Strange Cookie Format - Obtain parameter values from method - working with Registry in VB.net - how to instantiate a proxy class that has multiple instances - building xalanc using msvc++ 2005 express edition - Problems adding a new row to an ms access database via VB.net - VB.NET - Regex Help - unmountable boot failure - C# make PIC better quality - Using the MS Access Object model in C# - how drag and drop is done in vb.net ? - Using Word Interop Assembly - Windows Defender Classification - Debugging in Visual Interdev - C2440 on COM_INTERFACE_ENTRY - Threads and Looping - Reflecting a Web Service - Local xml resource problem with XmlDocument.Load() - DataRow.Delete() problem - Retaining view state in aspx page - Javascript calculating total in gridview - View State of a .aspx page - client side - retain previous page? - Problems returning an int Array pointer - C# WinForm: Simulate Right Mouse Click - Input string was not in a correct format. - C# and WndProc, Getting closing code to run - Cannot switch views: This end tag has no matching start tag - error reports while using yahoo
https://bytes.com/sitemap/f-312-p-37.html
CC-MAIN-2019-43
refinedweb
3,327
54.63
Reminder : You can find all the DarkRift2 related articles here You can find the entire project on my official GitHub Concept When you’re working in a Server/Client environment, there is some problems that doesn’t exists in a solo game. For exemple, the synchronisation of gameobjects. One diffuculty is to keep a track of each network gameobjects and synchronize them. You get it ? It means that all synchronized game object on the network must have an Unique ID. This unique ID must be the same both on server and on all connected clients Here is the way we’ll proceed : As you can see, we need to identify on the scene wich game object need to be synchronized. After that, when the scene is loaded, we have to check on wich side we are executing the code (Server or Client side) in order to generate an unique network ID or to destroy the gameobject itself. We’ll first focus on identifying where the game is executed. Where game is executed ? There is many ways of doing that. I choosed to use the Singleton pattern to accomplish this task. How it will works ? Both ServerManager and ClientManager will use the singleton pattern. It means that we can access at any time (except on Awake()) to the ServerManager instance by writing : GameServerManager.instance; //Return the unique instance Download my utilities on GitHub I provide you some utilities on my official github repository that you can download right now here : Download it as .ZIP and copy/paste the content on the scripts folder on the unity project. You should have this : (The content may change over time…) We’ll use 2 classes wich are : - MonoBehaviourSingletonNonPersistent : Singleton Pattern that doesn’t persists after scene is destroyed - MonoBehaviourSingletonPersistent : Singleton Pattern that persits after scene is destroyed. It means that the game object will be not destroyed. In our case, we want to keep an instance always alive, so we’ll use the Persistent Singleton. Let’s implement it on both GameServerManager. Modify the class declaration like that : using Utilities; public class GameServerManager : MonoBehaviourSingletonPersistent<GameServerManager> Do the same for the ClientManager class. Generate a unique network ID For each object that needs to e synchronized over network, we want a unique network ID, so… let’s create a specific script that will perform it. Let’s call him NetworkObject in the Network folder : We want from this component that it : - Generates an unique ID if we are on the server and register the object into a the ServerManager gameobject (To be created) - Destroys immediately the gameobject if we are on a client. So simple as it is. Here is the code : using System.Collections; using System.Collections.Generic; using UnityEngine; public class NetworkObject : MonoBehaviour { #region Properties /// <summary> /// Id of the network object /// </summary> [HideInInspector] public int id; #endregion ); } } #endregion } As you can see, i commented the line with the RegisterNetworkObject() because this method doesn’t exists yet on the ServerManager script. We’ll create it on the next article. So now, let’s assign this script to the ball on the MainGameScene and launch both the client and both the server in unity : That’s perfect. We are now ready to tell the server to send a message to the client to tell him to spawn a ball into its own scene. Of course, we’ll need to instantiate gameobject on the fly. There is 2 way to do that : - Using the Resource folder, wich is not an option if we decide to put in production our produce - Using Asset Bundles, wich is the most efficient and elegant way of instanciate objects For our purpose, we’ll use the resources folder because it’s totally appropriate to fastly prototype a game. If you decide to make a production version of your game, you should consider to move to AssetBundles. What about object position synchronization ? Regarding the position of synchronized objects, we will treat this subject later, we first need to instantiate these objects on each connected clients. What’s next ? On the next article of this tutorial, we’ll keep a track of each network gameobject in the server scene and create our message to send to the client when he connects.
http://materiagame.com/2019/02/12/darkrift-2-tutorial-for-unity-3d-part-7-how-about-synchronized-objects
CC-MAIN-2019-30
refinedweb
708
60.75
Do you want to impress your boss and create professional looking hyperlink entry forms for $0 in only 10 minutes? Who wouldn't? With regular .NET TextBox and HyperLink controls combined, that is really easy. Just follow a few simple steps in this article and you'll have your own full featured LinkTextBox control. TextBox HyperLink LinkTextBox Remember how Email and Web Page textbox in Microsoft Outlook work as a hyperlink when they are not focused, and as a regular textbox when they have focus? If you don't, just open your Outlook and then come back to this article... Let's figure out how it works first. The control is actually a combination of TextBox and LinkLabel controls. HyperLink control is positioned so that it overlaps the TextBox's text and intercepts the clicks. But if a user clicks in the TextBox and not on the LinkLabel, the TextBox gets the focus and LinkLabel hides. LinkTextBox acts and looks exactly as a regular TextBox until it loses focus. Then the LinkLabel is made visible again and the user can click on the link. LinkLabel What you want to do is extend the regular TextBox. You can do that in your existing application, in any of your libraries, or create a new project and add a Class Object file and extend the System.Windows.Forms.TextBox. You could also use the Add Inherited Control... wizard, but I usually don't. I can type inheritance declaration faster than click through the wizard. In the constructor, let's create an instance of LinkLabel and position it so that it exactly overlaps the TextBox's text. We also need to show it and copy the TextBox.Text to the LinkLabel so it looks OK at design time. We also need to wire up a Clicked event in here. System.Windows.Forms.TextBox TextBox.Text Clicked namespace DavidVidmar.Windows.Forms { public class LinkTextBox : TextBox { private LinkLabel llLinkLabel; public LinkTextBox() { llLinkLabel = new LinkLabel(); this.Controls.Add(llLinkLabel); llLinkLabel.AutoSize = true; llLinkLabel.Left = -1; llLinkLabel.Top = 1; llLinkLabel.Visible = true; llLinkLabel.Text = this.Text; llLinkLabel.LinkClicked += new LinkLabelLinkClickedEventHandler(ll_LinkClicked); } } } Next, let's prepare an enum for various types of links. We need one that tells the user the link feature is disabled, one for email links, one for FTP links and one for web links or secure web links. enum public enum LinkTypes { None, // act as a regulator TextBox Http, // act as a http:// or https:// hyperlink Ftp, // act as a ftp:// hyperlink } Now, we can add a LinkType property to LinkTextBox. It tells what kind of link the Text property represents and if it is a link at all. By default, the LinkTextBox will work as a regular TextBox and we need to hide a LinkLabel. We'll call this mode edit mode and we'll use a SwitchToEditMode() method that we will create later. But if it is a real LinkTextBox, we need to switch to clickable mode, where LinkLabel is visible, again with SwitchToEditMode() just with a different parameter value. We also need to copy the information from TextBox to LinkLabel. Let's assume for a moment FillLinkData() method does just that. LinkType Text SwitchToEditMode() FillLinkData() private LinkTypes ltLinkType = LinkTypes.None; [DefaultValue(LinkTypes.None)] public LinkTypes LinkType { set { this.ltLinkType = value; if (value == LinkTypes.None) { SwitchToEditMode(true); } else { SwitchToEditMode(false); FillLinkData(); } } get { return this.ltLinkType; } } The SwitchToEditMode() method only needs to show or hide the LinkLabel. We can easily do that in just one line of code: protected void SwitchToEditMode(bool _bEditMode) { llLinkLabel.Visible = !_bEditMode; } The FillLinkData() method we used in the property setter is a little more complicated. We need to copy the value of Text property from TextBox to LinkLabel, try to figure out what protocol to use in our link, and update the Links array of LinkLabel. The easiest way to do that is to create a new entry each time around. Links private void FillLinkData() { llLinkLabel.Text = this.Text; string sLinkType = ""; switch (ltLinkType) { case LinkTypes.Http: if (this.Text.ToLower().IndexOf(@"http://") < 0 && this.Text.ToLower().IndexOf(@"https://") < 0) { sLinkType = @"http://"; } break; case LinkTypes.Ftp: if (this.Text.ToLower().IndexOf(@"ftp://") < 0) { sLinkType = @"ftp://"; } break; case LinkTypes.Email: if (this.Text.ToLower().IndexOf("mailto:") < 0) { sLinkType = "mailto:"; } break; } llLinkLabel.Links.Clear(); llLinkLabel.Links.Add(0, llLinkLabel.Text.Length, sLinkType + this.Text); } We could figure out when exactly to copy the text from TextBox to LinkLabel, but the easy way out is every time the Text property on TextBox changes. It's not optimal, but I don't think anybody will notice that. protected override void OnTextChanged(EventArgs e) { base.OnTextChanged (e); if (ltLinkType != LinkTypes.None) { FillLinkData(); } } Now, let's cover the switching from editable to clickable mode. If TextBox control gets the focus, user must have clicked to the right of the LinkLabel in TextBox, so we need to switch to edit mode. If control loses focus, we need to switch to clickable mode. We already created SwitchToEditMode() method that will do everything. All we need to do is override the OnGetFocus() and OnLostFocus() methods. OnGetFocus() OnLostFocus() protected override void OnGotFocus(EventArgs e) { base.OnGotFocus(e); if (ltLinkType != LinkTypes.None) this.SwitchToEditMode(true); } protected override void OnLostFocus(System.EventArgs e) { base.OnLostFocus(e); if (ltLinkType != LinkTypes.None) this.SwitchToEditMode(false); } It's not very obvious but later on you will realize that some strange focus related issue will surface. If you give focus to a control through tab it will be different than if you shift-tab to the control. With some tricky focus handling, the issue is resolved. private void llLinkLabel_GotFocus(object sender, EventArgs e) { // if control got focus with tab and not because user clicked a link // then transfer focus to TextBox and clear the flag if (!bLinkClicked) { this.Focus(); bLinkClicked = false; } } private void llLinkLabel_MouseDown(object sender, MouseEventArgs e) { // remember that user clicked on the label, // so we can correct the focus of a label bLinkClicked = true; } Now, let's make this thing clickable! In the constructor, we already wired the event, now let's code it. We need to check if we should use a link at all and then call a UserHyperlink() method that will actually open the link. UserHyperlink() private void ll_LinkClicked(object sender, LinkLabelLinkClickedEventArgs e) { if (ltLinkType != LinkTypes.None) UseHyperlink(); } Now, let's figure out how to open a link. Don't even start thinking about directly interacting with IE, Outlook, or any other browser or mail application. Let's use the OS to figure out what to do with the link. This way, we just execute the link, and Windows will open either a default mail application or default browser. This is the right way to do it. Just create a new Process class, call Start() method with the link, and keep your fingers crossed. The bad part is that you don't really know if it will work. Just catch an exception and throw a new one. In an application, just catch this exception, show a MessageBox, and give the user a chance to figure out what's wrong with the link. Process Start() MessageBox private void UseHyperlink() { try { if (llLinkLabel.Links.Count > 0) { string sLink = llLinkLabel.Links[0].LinkData.ToString(); System.Diagnostics.Process.Start(sLink); } } catch (Exception ex) { throw new ArgumentException("Link error!", ex); } } We can easily build in one more feature. If the control is in the edit mode (LinkLabel is hidden), we can help the user test the link. If the user clicks in the control while the Ctrl key is pressed, he can launch the link. protected override void OnMouseDown(MouseEventArgs e) { if (ltLinkType != LinkTypes.None) { if (e.Button == MouseButtons.Left && (Control.ModifierKeys & Keys.Control) == Keys.Control) { UseHyperlink(); } else { base.OnMouseDown(e); } } else { base.OnMouseDown(e); } } And that's it. The control is ready for use. Just set the LinkType property and the control is ready for some serious clickin'! Or you could even let the user decide if the text in the LinkTextBox is a link with a ComboBox next to it! ComboBox I hope you realized how you can create quite powerful controls that could be easily a part of an expensive UI library, with a simple combination of two basic controls and some simple UI processing. So, before you start Googlin' or even throwing couple of bucks out the window for a commercial control, think about writing your own control. It's the best in terms of control, and when it's this simple, it's really fun. Keep checking this page out to see if anyone has found a bug or got an idea of how to extend the LinkTextBox. You can also come over to my blog and see if there is anything new.
http://www.codeproject.com/Articles/9151/LinkTextBox-a-quick-solution-for-entering-emails-a?fid=138772&df=90&mpp=10&sort=Position&spc=None&tid=1239569
CC-MAIN-2014-52
refinedweb
1,452
67.04
MQTT Under the hood, Meeo uses MQTT (Message Queue Telemetry Transport) as its communications protocol. You need to know the following terminologies when it comes to MQTT: topic— this is a concept in MQTT where messages will pass through. Think of it as a classroom. If you want to learn (receive) or teach (send) Geometry, you must go to the Geometry Room. In Meeo, a topicis prefixed by your namespace and then the channel (i.e. es-d3uleiqm/room-temperaturewhere es-d3uleiqmis your namespace and room-temperatureis your channel). payload— this is the data or information that you want to send or receive. publish— this is the action to send data to the topic. subscribe— this is the action to receive data from the topic. Widgets Widgets are components that can display data from your devices or send data to your devices. Meeo features a wide variety of widgets. These widgets can be used for displaying data: - Chart — use this widget to display sensor data over time. - Location — use this widget to display GPS coordinates (latitude and longitude) on Google Map. - Level — use this widget to display sensor data that can be described as a percentage (0% to 100%) - Temperature — use this widget to display temperature data in Celsius or Fahrenheit. - Text Feed — use this widget to display textual data from your device. - On/Off State — use this widget to display sensor data that can be described with only two states (on or off, 1 or 0). These widgets can be used for sending data: - Toggle — use this widget to control your appliances. This widget acts like an on/off switch. - Color Picker — use this widget to control the color of your lights. - Slider — use this widget like a potentiometer. You can use this to indicate speed or threshold. - Text Field — use this widget to send textual data to your device. The easiest way to get started with Meeo is to add a new widget! Adding a widget is very easy, just click/press the “Add Widget” button from the Navigation Bar as shown on the image below: After pressing the “Add Widget” button, you can now choose the widget you would like to add from the Widget Menu: For the next steps in adding a widget, you can check these guides depending on the widget you have chosen:
https://medium.com/meeo/introduction-to-meeo-1796bf418c8c
CC-MAIN-2018-39
refinedweb
389
63.9
This is just a simple wrapper - you probably want to be looking at LedEngine. More... #include <LedMC.h> This is just a simple wrapper - you probably want to be looking at LedEngine. This is handy if all you want to do is control the LED's, but since other MotionCommands will probably also want to make use of the LEDs, they can just use the engine component to do all the work. Definition at line 19 of file LedMC.h. List of all members. constructor Definition at line 22 of file LedMC.h. [virtual] destructor Definition at line 29 of file LedMC.h. Override this if you want to run some startup code after being added to the MotionManager. Reimplemented from MotionCommand. Definition at line 31 of file LedMC.h. used to prune "dead" motions from the MotionManager note that a motion could be "paused" or inactive and therefore not dirty, but still alive, biding its time to "strike" ;) Implements MotionCommand. Definition at line 57 of file LedMC.h. returns true if there are changes since the last updateLEDs() Reimplemented from LedEngine. Definition at line 55 of file LedMC.h. Referenced by isAlive(). Definition at line 36 of file LedMC.h. Sets the JointCmd::weight of the LEDs specified by leds to weight. Definition at line 61 of file LedMC.h. Referenced by LedMC(). updates the cmds from LedEngine::updateLEDs() Definition at line 39 of file LedMC.h. [protected] needed to store weight values of LEDs (useful to mark LEDs as unused) Definition at line 70 of file LedMC.h. Referenced by setWeights(), and updateOutputs(). set to true when we've posted a status event for completion of a flash/cflash Definition at line 71 of file LedMC.h. Referenced by updateOutputs().
http://tekkotsu.org/dox/classLedMC.html
CC-MAIN-2016-36
refinedweb
292
68.26
Re: compiling windows CE kernel - From: dk <dk@xxxxxxxxxxxxxxxxxxxxxxxxx> - Date: Sat, 2 Sep 2006 02:58:02 -0700 yes Agreed , I did install the shared code in PRIVATE folder but when we try to compile the PRIVATE folder files lots of files are not there and we cannot build the nk.lib . Is the shared source licence easily availible to all or we need to be a big OEM and Gold partner of MS or something ....... "Anthony Pellerin" wrote: Note that all the code is not available. You can install some of the. private code when installing PB (and agree the shared source licence). You can have more sources (almost all) with the shared source premium program but you have to contact MS for that. HTH -- -- ---------------------------------------------------------------- Anthony Pellerin (eMVP) ADENEO (ADESET) Windows Embedded Consultant <apellerin AT adeneo DOT adetelgroup DOT com> Tél : +33 (0)4.72.18.57.77 ---------------------------------------------------------------- dk wrote: I am trying to compile the existing source code of winCE 5.00 specifically the kernel implementation and folders D:\WINCE500\PRIVATE\WINCEOS\COREOS\NK\KERNEL but am finding that lot of files seems to be missing like if I compile the NKNORMAL folder which results in the creation of the nkmain.lib but I found that the files #include <KmodeEntries.hpp> #include <GweApiSet1.hpp> seem to be missing and the folder #include "../../../core/acl/accchk.c" doesnot seems to be there , somehow I tried removed the functions like DoAccessCheck,DoPrivilegeCheck in the file D:\WINCE500\PRIVATE\WINCEOS\COREOS\NK\KERNEL and was able to move ahead but the #include <KmodeEntries.hpp> #include <GweApiSet1.hpp> were missing and these file seem to contain the structure KmodeEntries_t , If I disable and go ahead I am some how able to compile and build the nkmain.lib and then SYSGEN to get the Nk.bin but I find that the filysys.exe and verifier call KmodeEntries possibly to get the hooks to the functions implemented ( SC_EventModify ... ) in NK.exe ,and it the system starts to generate the unhandled exceptions and DataAborts 1) Is there a way I can get the header files specfically the #include <KmodeEntries.hpp> and #include <GweApiSet1.hpp> so that atleast the filesys.exe can use the calls provided through KmodeEntries_t . 2) It seems that possbily the nk.exe gets generated by combiantion of the (nk.lib= nkmain.lib + nkcomp.lib+nomapfile.lib ) , Is it possible that I can use the Nmake to compile nkmain.lib + nkcomp.lib+nomapfile.lib to generate the Nk.lib and then compile to get the NK.exe and then do a MakeImage , beacuse the Sysgen seems to consume a lot of time . what should be the arguments for Nmake or any other Tool - Follow-Ups: - Re: compiling windows CE kernel - From: Yannick Chamming's [eMVP] - References: - Re: compiling windows CE kernel - From: Anthony Pellerin - Prev by Date: Re: What's differents "Sysgen", "Build and Sysgen" and "Build and - Next by Date: Re: CSR Bluetooth over UART - Previous by thread: Re: compiling windows CE kernel - Next by thread: Re: compiling windows CE kernel - Index(es):
http://www.tech-archive.net/Archive/WindowsCE/microsoft.public.windowsce.platbuilder/2006-09/msg00045.html
crawl-002
refinedweb
511
63.9
Type: Posts; User: vcstarter This can be done very easy, but I assume there is a better way to do it. assume that I have a vector or a signal like x=[1 1 1 1 1] want to shift it by one unit to the right I have x[n+1]... Take a look of the project to see the overlapping It means that when tab1 is visible, the form in tab2 does not show like any other tab application I tried to show one at a time. The idea is to show one tab at a time similar to C# winform m_TabOne member variable first table m_TabTow member variable second tab I tried to display a tab, but it looks like I make some mistake in the initialization; see the code below afx_msg LRESULT CDisplayData::OnInitdialog(WPARAM wParam, LPARAM lParam) { CTabCtrl... That was the problem. I realized that now. It was in the wrong place. thanks I created the test project from the wizard. When I added the handler for the button, it looks like it choose the CDialog class, so that may be the problem. Maybe it should be in CView. you can... ID_BUTTON2 is the ID of the button in the ribbon. I tried to zip the project and attached it, but it is too big after I zip it. It looks like the wirzard created a big SQL Compaq file. The following has been added to message map ON_COMMAND(ID_BUTTON2, &CAboutDlg::OnButton2) and the function implementation here void CAboutDlg::OnButton2() { MessageBox(L"my data", L"my... I haven't worked with MFC for a long time. I just tried a simple ribbon application. After adding a button to a group and add a handler for the button. I added a value in the string table for the... I am using the following code to add a menu to visual studio here is the complete function (see below) it works fine; the problem is when i take it to a test station (I mean when I move the dll),... I try to implement the code from this link to count the files downloaded from my site It works fine only for a single... it works fine; the oly problem is that I wonder if it is possible to change the color of the menu item separator. I coulfn't find a way to change its color. It is possible to check the for the separator and change that color as well. Wile the bacground color of the menu changes, but it will be nice to identify the separator and change its color sorry, I did not copy it. I commetted the line out. Still crashed on the same spot event when commented out your suggestion comment this line out and remove the separator you can see it works fine if (!item is ToolStripSeparator) it crashed somewhere here foreach (ToolStripMenuItem item in items) after interacting through the menu and encounter a menu separator I try to change the background color of a menu, but the program crashed when the menu item is a separator. I try to check to see if there is a separator before I make the change, but I cannot get... I try to write an add in for visual studio. Currently, I can only add one command at a time to the tools menu. I want to know how can I add a menu item with dropdown command to the tools menu or... Did you check the attribute to make sure the file is not protected? You may need do that or clear the attribute for the file first. There are other ways to do it, but you can do it this way by using the applicationdirectory class in using System.Security.Policy; I think you approach the problem the wrong way. You have to use the stream class to write the file line by line then read it line by line then delete specific line that you want. The way you have... I don't know if i answer your question, but you have to click on the property of the specified combobox column and populate it. For instance if your combobox is column3, then you select it by... OK I will do so, this is basically what I am working on now
http://forums.codeguru.com/search.php?s=00307e971b5cde438824b6077fb6a7bc&searchid=7002579
CC-MAIN-2015-22
refinedweb
721
78.99
Cake is a build automation system for .NET Developers to script their build processes using a C# Domain Specific Language (DSL). In this post, we’ll explore the benefits of Cake and its major features with a concrete working example to achieve a flexible, maintainable, automated build process. You might have heard about Make and makefiles in the past, but don’t worry if you haven’t because you are about to. Make is a build automation tool, and a makefile is a file that contains the instructions Make needs to build an application. It can also be used to run related tasks like cleaning the build directory. Many variants of Make have appeared over the years as developers want to use their preferred languages to define their build processes. Rake (Ruby Make) became very popular alongside Ruby on Rails. In the .NET world, you have a few options based on your language of choice. There’s PSake (PowerShell), FAKE (F#), and Cake (C#). We’re focusing on Cake today, but check out the others if you’d rather script with PowerShell or F#. Benefits of Cake One of the main benefits of using Cake is that your build scripts will be written in a C# DSL. Your team can use the language they’re most familiar with to automate their builds instead of using XML, JSON, or YAML. Another benefit not to be overlooked is the ability to execute Cake scripts locally and from your CI server. Think about that for a second. Barring any environmental issues on your build agent, the same Cake script will run on your machine, your team member’s machine, and on your CI server. Your CI project configuration could be simplified to: - Run this Cake script. Speaking of source control, your Cake script lives in your project repository. Your build process is versioned and can be changed and reviewed with the same code review process as your application code. Committing your script also couples your application code with the build process so you don’t have to change the build steps separately in your CI server. This linking of the application and build script is one of the reasons YAML is becoming a popular choice for modeling build pipelines. Cake has the added benefit of running those build steps right on your machine. Cake has built-in support for lots of tools (including Octopus Deploy) and many others through community-contributed add-ins. There’s a good chance the tools you’re using for your build are supported and if not, you can create an add-in to use in your script. Example Cake script Our sample project, OctoPetShop, has a full example Cake script that we’ll explore in this post. That link is to the version used at time of writing. If you want to review the latest version you can check this link. Tools, add-ins, and modules The first section in your Cake script imports any external tools, add-ins, or modules you use in your build process. In our case, we’ve added a #tool directive and specified that we want OctopusTools version 6.13.1 from NuGet. Then we’ve add a using statement for the Cake.Common.Tools.OctopusDeploy namespace: #tool "nuget:?package=OctopusTools&version=6.13.1" using Cake.Common.Tools.OctopusDeploy; We’re only using the Octopus Deploy tooling in this script so far, but Cake has built-in support for many tools including NuGet, testing frameworks, and more. Arguments and global variables In the next section, we set up some arguments and variables to use during the script execution. With the Argument alias, Cake will give you the value of an argument that was provided from the command line or a default value that you specify. We have arguments for the target task to run, what build configuration to use, which version and prerelease tag to use for versioning, and information for integrating with our Octopus server. After that, we have a simple class for collecting information on our projects and a few variables that we’ll populate in Setup: var target = Argument("target", "Default"); var configuration = Argument("configuration", "Release"); var version = Argument("packageVersion", "0.0.1"); var prerelease = Argument("prerelease", ""); var databaseRuntime = Argument("databaseRuntime", "win-x64"); var octopusServer = Argument("octopusServer", ""); var octopusApiKey = Argument("octopusApiKey", "hey, don't commit your API key"); class ProjectInformation { public string Name { get; set; } public string FullPath { get; set; } public string Runtime { get; set; } public bool IsTestProject { get; set; } } string packageVersion; List<ProjectInformation> projects; Setup Let’s take a look at that Setup method. We check if we’re running the build locally, if we are and no prerelease tag was provided, we set the prerelease tag to "-local." Then we set our global variables packageVersion and projects: Setup(context => { if (BuildSystem.IsLocalBuild && string.IsNullOrEmpty(prerelease)) { prerelease = "-local"; } packageVersion = $"{version}{prerelease}"; projects = GetFiles("./**/*.csproj").Select(p => new ProjectInformation { Name = p.GetFilenameWithoutExtension().ToString(), FullPath = p.GetDirectory().FullPath, Runtime = p.GetFilenameWithoutExtension().ToString() == "OctopusSamples.OctoPetShop.Database" ? databaseRuntime : null, IsTestProject = p.GetFilenameWithoutExtension().ToString().EndsWith(".Tests") }).ToList(); Information("Building OctoPetShop v{0}", packageVersion); }); Tasks Tasks define your build process. They are analogous to build steps in your traditional Continuous Integration (CI) project or pipeline. Let’s take a look at our first task, Clean. We define it with the Task method and provide a name. Then we use the Does method to define what this task does. In this case, we’re cleaning our publish and package directories and then calling DotNetCoreClean for our projects: Task("Clean") .Does(() => { CleanDirectory("publish"); CleanDirectory("package"); var cleanSettings = new DotNetCoreCleanSettings { Configuration = configuration }; foreach(var project in projects) { DotNetCoreClean(project.FullPath, cleanSettings); } }); Dependencies Let’s skip down to the Build task. It looks similar to Clean, but it has a new piece: IsDependentOn. This method lets us create a dependency chain between our tasks. When we call the Build task, Cake will make sure that both Clean and Restore have been called first: Task("Build") .IsDependentOn("Clean") .IsDependentOn("Restore") .Does(() => { foreach(var project in projects) { var buildSettings = new DotNetCoreBuildSettings() { Configuration = configuration, NoRestore = true }; if (!string.IsNullOrEmpty(project.Runtime)) { buildSettings.Runtime = project.Runtime; } DotNetCoreBuild(project.FullPath, buildSettings); } }); We have another task named RunUnitTests that depends on Build. Running the RunUnitTests task will trigger Clean, Restore, and Build: Task("RunUnitTests") .IsDependentOn("Build") .Does(() => { foreach(var project in projects.Where(p => p.IsTestProject)) { DotNetCoreTest(project.FullPath, new DotNetCoreTestSettings { Configuration = configuration }); } }); If you continue reading through the script, you’ll see tasks for publishing the apps, packaging them using the Octopus tools, pushing the packages to Octopus, and creating and deploying a release with Octopus. Finally, we have these lines at the end of our script. This creates a Default task that will run the RunUnitTests task and its dependencies. The last line calling the RunTarget method kicks off the build process. Here we pass in the global variable target which is provided by the user, CI server, or defaults to the task named Default: Task("Default") .IsDependentOn("RunUnitTests"); RunTarget(target); Executing Cake locally Cake provides a PowerShell or shell bootstrap script that you can use to execute your Cake script: .\build.ps1 -Target Pack -ScriptArgs '--packageVersion=1.2.3 --prerelease=-dev' That’s it! The script starts up, and after a short wait, we have our NuGet packages built locally and this handy report: Task Duration -------------------------------------------------- Setup 00:00:00.1432566 Clean 00:00:05.4768163 Restore 00:00:06.1162465 Build 00:00:09.6114684 RunUnitTests 00:00:04.3110846 Publish 00:00:06.9924016 Pack 00:00:12.7274733 -------------------------------------------------- Total: 00:00:45.3787473 We can upload those packages to our Octopus server directly or commit our changes, knowing that our build works. There are also extensions for Visual Studio and Visual Studio Code that provide IntelliSense, syntax highlighting, and the ability to run your script from the IDE. Executing Cake from a CI server Now that we have our Cake script running locally, we can take it to our CI server. In this example, we are using Azure DevOps, which has an extension to run Cake scripts. Here’s a snippet of the steps generated when you create a new ASP.NET Core build pipeline. It’s very similar to the steps we created in our Cake script. After installing the Cake extension, we can add a Cake step to our build, and in this case, it’s the only step that we need. We provide the path to the cake script, the target we want to run, and some additional arguments for the version number and Octopus server information. After running a build, not only do we get the full output of the Cake script in the logs, we also get our task summary just as we did when running locally: Task Duration -------------------------------------------------- Setup 00:00:00.0434025 Clean 00:00:18.1795863 Restore 00:01:07.9769173 Build 00:00:36.6475174 RunUnitTests 00:00:21.3958462 Publish 00:00:06.2555954 Pack 00:00:12.0804766 PushPackages 00:00:16.0161892 CreateRelease 00:00:05.4893287 DeployRelease 00:02:09.6799635 -------------------------------------------------- Total: 00:05:13.7648231 Conclusion Build automation frameworks like Cake offer many benefits to you and your team. With Cake, you can script your builds using a familiar C# DSL. It enables you to apply your development process to your build. You can run the same steps locally and from your CI server. And Cake’s extensive built-in tooling support and community add-ins should cover most, if not all, of your scripting needs. This post was originally published at octopus.com. Discussion (0)
https://dev.to/octopus/using-cake-build-scripts-for-your-net-core-web-apps-lab
CC-MAIN-2022-27
refinedweb
1,602
57.47
ConcurrentHashMap public class ConcurrentHashMap<K,V> extends AbstractMap<K,V> implements ConcurrentMap<K,V>, Serializable { ... } 1. Some important parameters 1.1 MAXIMUM_ Capability parameter /** * The largest possible table capacity. This value must be * exactly 1<<30 to stay within Java array allocation and indexing * bounds for power of two table sizes, and is further required * because the top two bits of 32bit hash fields are used for * control purposes. */ private static final int MAXIMUM_CAPACITY = 1 << 30; MAXIMUM_ The capability parameter indicates the maximum capacity of the map. The default value is 1 < < 30. 1.2 DEFAULT_ Capability parameter /** * The default initial table capacity. Must be a power of 2 * (i.e., at least 1) and at most MAXIMUM_CAPACITY. */ private static final int DEFAULT_CAPACITY = 16; DEFAULT_ The capability parameter indicates the default capacity of the map, which is 16. 1.3 MAX_ARRAY_SIZE parameter /** * The largest possible (non-power of two) array size. * Needed by toArray and related methods. */ static final int MAX_ARRAY_SIZE = Integer.MAX_VALUE - 8; MAX_ ARRAY_ The size parameter indicates the maximum length of the map array, which may be used in toArray() and its related methods. The size is Integer.MAX_VALUE - 8. 1.4 DEFAULT_CONCURRENCY_LEVEL parameter /** * The default concurrency level for this table. Unused but * defined for compatibility with previous versions of this class. */ private static final int DEFAULT_CONCURRENCY_LEVEL = 16; DEFAULT_ CONCURRENCY_ The level parameter indicates the default concurrency level. It has been deprecated in the current version JDK13, but this parameter is reserved for compatibility with previous versions. 1.5 LOAD_FACTOR parameter /** * The load factor for this table. Overrides of this value in * constructors affect only the initial table capacity. The * actual floating point value isn't normally used -- it is * simpler to use expressions such as {@code n - (n >>> 2)} for * the associated resizing threshold. */ private static final float LOAD_FACTOR = 0.75f; LOAD_ The factor parameter indicates the loading factor, which is 0.75 by default, the same as HashMap. 1.6 TREEIFY_THRESHOLD parameter /** * The bin count threshold for using a tree rather than list for a * bin. Bins are converted to trees when adding an element to a * bin with at least this many nodes. The value must be greater * than 2, and should be at least 8 to mesh with assumptions in * tree removal about conversion back to plain bins upon * shrinkage. */ static final int TREEIFY_THRESHOLD = 8; TREEIFY_ The threshold parameter represents the threshold value of converting the linked list in the array into a red black tree. It is used to compare with the length of a linked list. 1.7 UNTREEIFY_THRESHOLD parameter /** * The bin count threshold for untreeifying a (split) bin during a * resize operation. Should be less than TREEIFY_THRESHOLD, and at * most 6 to mesh with shrinkage detection under removal. */ static final int UNTREEIFY_THRESHOLD = 6; UNTREEIFY_ The threshold parameter represents the threshold value for the red black tree in the array to be transformed into a linked list. It is used to compare with the size of a red black tree. 1.8 MIN_ TREEIFY_ Capability parameter /** * The smallest table capacity for which bins may be treeified. * (Otherwise the table is resized if too many nodes in a bin.) * The value should be at least 4 * TREEIFY_THRESHOLD to avoid * conflicts between resizing and treeification thresholds. */ static final int MIN_TREEIFY_CAPACITY = 64; MIN_ TREEIFY_ The capability parameter indicates the minimum capacity of the hash table to treelize the linked list. Only when the capacity of the entire ConcurrentHashMap is greater than this value can the specific linked list be treelized. If it is not greater than this value, it will be expanded instead of treelized. (capacity expansion will also reduce the number of elements in a single linked list). 1.9 MIN_TRANSFER_STRIDE parameter /** * Minimum number of rebinnings per transfer step. Ranges are * subdivided to allow multiple resizer threads. This value * serves as a lower bound to avoid resizers encountering * excessive memory contention. The value should be at least * DEFAULT_CAPACITY.STR */ private static final int MIN_TRANSFER_STRIDE = 16; In the capacity expansion operation, the transfer step allows multiple threads to be performed concurrently, min_ TRANSFER_ The stride parameter indicates the minimum number of tasks of a worker thread in a transfer operation. That is, the minimum number of consecutive hash buckets to be processed. The default is 16, that is, at least 16 consecutive hash buckets should be transferred. See the analysis of the transfer() method below for details. 1.10 RESIZE_STAMP_BITS parameter (not understood) /** * The number of bits used for generation stamp in sizeCtl. * Must be at least 6 for 32bit arrays. */ private static final int RESIZE_STAMP_BITS = 16; RESIZE_ STAMP_ The bits parameter is used to generate a unique generation stamp in each capacity expansion. 1.11 MAX_RESIZERS parameter (not understood) /** * The maximum number of threads that can help resize. * Must fit in 32 - RESIZE_STAMP_BITS bits. */ private static final int MAX_RESIZERS = (1 << (32 - RESIZE_STAMP_BITS)) - 1; This parameter defines the maximum number of worker threads when resizing, but I don't understand the calculation method. MAX_ RESIZERS = (1 << (32 - resize_STAMP_BITS)) - 1; 1.12 RESIZE_STAMP_SHIFT parameter (not understood) /** * The bit shift for recording size stamp in sizeCtl. */ private static final int RESIZE_STAMP_SHIFT = 32 - RESIZE_STAMP_BITS; This parameter defines the bit shift of the record size mark in sizeCtl, but I don't understand the calculation method. MAX_RESIZERS = 32 - RESIZE_STAMP_BITS; 1.13 hash status parameters of special nodes /* * Encodings for Node hash fields. See above for explanation. */ static final int MOVED = -1; // hash for forwarding nodes static final int TREEBIN = -2; // hash for roots of trees static final int RESERVED = -3; // hash for transient reservations Normally, the hash value should be positive. If it is negative, it indicates that it is an abnormal and special node. - When the hash value is - 1, it means that the current node is a Forwarding Node. - ForwardingNode is a temporary node that only appears during capacity expansion, and it does not store actual data. - If all the nodes in a hash bucket of the old array are migrated to the new array, the old array will place a ForwardingNode in the hash bucket - When a ForwardingNode is encountered during a read operation or iterative read operation, the operation is forwarded to the new table array after capacity expansion for execution. When a write operation encounters it, it attempts to help with capacity expansion. - When the hash value is - 2, it means that the current node is a TreeBin. - TreeBin is a special node in ConcurrentHashMap for agent operation of TreeNode. It holds the root node of the red black tree that stores actual data. - Because the red black tree performs write operations, the structure of the whole tree may change greatly, which has a great impact on the read thread. Therefore, TreeBin also needs to maintain a simple read-write lock, which is an important reason for the new introduction of this special node compared with HashMap. - When the hash value is - 3, it means that the current node is a reserved node, that is, a placeholder. - Generally, it will not appear. 1.14 HASH_BITS parameters static final int HASH_BITS = 0x7fffffff; // usable bits of normal node hash HASH_BITS is also seen in HashTable. Through bit operation with bits, the hash value of negative numbers can be transformed into positive numbers. 1.15 NCPU parameters /** Number of CPUS, to place bounds on some sizings */ static final int NCPU = Runtime.getRuntime().availableProcessors(); The NCPU parameter can obtain the number of processor cores that can be used by the current JVM. 2. Some important attributes It is worth noting that the key attributes in ConcurrentHashMap are basically volatile variables. 2.1 table attribute /** * The array of bins. Lazily initialized upon first insertion. * Size is always a power of two. Accessed directly by iterators. */ transient volatile Node<K,V>[] table; The table attribute is used for storage nodes and is a collection of buckets. 2.2 nextTable attribute /** * The next table to use; non-null only while resizing. */ private transient volatile Node<K,V>[] nextTable; The nextTable property indicates the next array to be used. It is used to assist the resize operation. It is only non empty when resizing. 2.3 baseCount attribute /** * Base counter value, used mainly when there is no contention, * but also as a fallback during table initialization * races. Updated via CAS. */ private transient volatile long baseCount; The baseCount property is the basic counter value when there is no contention. It is also used in the contention of the initialization table. 2.4 sizeCtl attribute /** * Table initialization and resizing control. When negative, the * table is being initialized or resized: -1 for initialization, * else -(1 + the number of active resizing threads). Otherwise, * when table is null, holds the initial table size to use upon * creation, or 0 for default. After initialization, holds the * next element count value upon which to resize the table. */ private transient volatile int sizeCtl; The sizeCtl attribute plays a role in table initialization and resize operation control. - When sizeCtl is negative, it indicates that the table is initializing or resizing. - Table initialization is - 1. - When the table resize s, it is - (1 + number of capacity expansion threads). - When sizecl is positive. - Initial table size or 0 when the table is null. - When the table is not null, it is the next count value to resize. 2.5 transferIndex attribute /** * The next table index (plus one) to split while resizing. */ private transient volatile int transferIndex; The index of the next table to split in resize. 2.6 cellsBusy attribute /** * Spinlock (locked via CAS) used when resizing and/or creating CounterCells. */ private transient volatile int cellsBusy; Spin locks used during the resize process and / or the creation of counter cells. 2.7 counterCells array /** * Table of counter cells. When non-null, size is a power of 2. */ private transient volatile CounterCell[] counterCells; Obviously, this is the array of counter cells, that is, the array of counting units. 3. Internal class 3.1 Node internal class The Node inner class is an abstraction of ordinary nodes in the ConcurrentHashMap class. /** * Key-value entry. This class is never exported out as a * user-mutable Map.Entry (i.e., one supporting setValue; see * MapEntry below), but can be used for read-only traversals used * in bulk tasks. Subclasses of Node with a negative hash field * are special, and contain null keys and values (but are never * exported). Otherwise, keys and vals are never null. */ static class Node<K,V> implements Map.Entry<K,V> { final int hash; final K key; volatile V val; volatile Node<K,V> next; Node(int hash, K key, V val) { this.hash = hash; this.key = key; this.val = val; } Node(int hash, K key, V val, Node<K,V> next) { this(hash, key, val); this.next = next; } public final K getKey() { return key; } public final V getValue() { return val; } public final int hashCode() { return key.hashCode() ^ val.hashCode(); } public final String toString() { return Helpers.mapEntryToString(key, val); } public final V setValue(V value) { throw new UnsupportedOperationException(); } public final boolean equals(Object o) { Object k, v, u; Map.Entry<?,?> e; return ((o instanceof Map.Entry) && (k = (e = (Map.Entry<?,?>)o).getKey()) != null && (v = e.getValue()) != null && (k == key || k.equals(key)) && (v == (u = val) || v.equals(u))); } /** * Virtualized support for map.get(); overridden in subclasses. */ Node<K,V> find(int h, Object k) { Node<K,V> e = this; if (k != null) { do { K ek; if (e.hash == h && ((ek = e.key) == k || (ek != null && k.equals(ek)))) return e; } while ((e = e.next) != null); } return null; } } significance The Node internal class is the implementation of the ConcurrentHashMap Node. Implementation of hashCode() Note the implementation of hashCode(): Objects.hashCode(key) ^ Objects.hashCode(value); find() Here, the find() method of the Node internal class will not be called in general business methods such as get(), because it will be traversed directly in those places. This method will be called in the find() method of the ForwardingNode class. 4. Tools and methods 4.1 spread method /** * Spreads (XORs) higher bits of hash to lower and also forces top * bit to 0. spread(int h) { return (h ^ (h >>> 16)) & HASH_BITS; } The hash conflict is reduced by taking the high bit and then performing mask calculation (ensuring that the hash value is positive). This method is called perturbation method. 4.2 tableSizeFor method /** * Returns a power of two table size for the given desired capacity. * See Hackers Delight, sec 3.2 */ private static final int tableSizeFor(int c) { int n = -1 >>> Integer.numberOfLeadingZeros(c - 1); return (n < 0) ? 1 : (n >= MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : n + 1; } The tableSizeFor method is used to calculate the resize threshold corresponding to parameter c. It often appears as the following statement. 4.3 comparable class for method /** * Returns x's Class if it is of the form "class C implements * Comparable<C>", else null. */ static Class<?> comparableClassFor(Object x) { if (x instanceof Comparable) { Class<?> c; Type[] ts, as; ParameterizedType p; // If it is a String, it returns directly if ((c = x.getClass()) == String.class) return c; if ((ts = c.getGenericInterfaces()) != null) { for (Type t : ts) { if ((t instanceof ParameterizedType) && ((p = (ParameterizedType)t).getRawType() == Comparable.class) && (as = p.getActualTypeArguments()) != null && as.length == 1 && as[0] == c) // type arg is c return c; } } } return null; } If parameter x is an implementation class of a Comparable interface, its type is returned. 4.4 compareComparables method /** * Returns k.compareTo(x) if x matches kc (k's screened comparable * class), else 0. */ @SuppressWarnings({"rawtypes","unchecked"}) // for cast to Comparable static int compareComparables(Class<?> kc, Object k, Object x) { return (x == null || x.getClass() != kc ? 0 : ((Comparable)k).compareTo(x)); } If the object x matches the comparable class kc of K, k.compareTo(x) is returned; otherwise, 0 is returned. 4.5 list element access method 4.5.1 tabAt method static final <K,V> Node<K,V> tabAt(Node<K,V>[] tab, int i) { return (Node<K,V>)U.getReferenceAcquire(tab, ((long)i << ASHIFT) + ABASE); } The tabAt() method can obtain the Node at the i position. 4.5.2 casTabAt method static final <K,V> boolean casTabAt(Node<K,V>[] tab, int i, Node<K,V> c, Node<K,V> v) { return U.compareAndSetReference(tab, ((long)i << ASHIFT) + ABASE, c, v); } The casTabAt() method can update the Node at the i location in the form of CAS 4.5.3 setTabAt method static final <K,V> void setTabAt(Node<K,V>[] tab, int i, Node<K,V> v) { U.putReferenceRelease(tab, ((long)i << ASHIFT) + ABASE, v); } The setTabAt method can set the Node at the i position. Note: methods like Unsafe.getReferenceAcquire() and Unsafe.putReferenceRelease() are actually the release versions of volatile methods in Unsafe. For example, the latter is the release version of putReferenceVolatile(). 4.6 initTable method private final Node<K,V>[] initTable() { Node<K,V>[] tab; int sc; while ((tab = table) == null || tab.length == 0) { if ((sc = sizeCtl) < 0) // If the sizeCtl attribute is less than 0, it indicates that initialization or resize is in progress Thread.yield(); // lost initialization race; just spin else if (U.compareAndSetInt(this, SIZECTL, sc, -1)) {// If SIZECTL is still sc, it is set to - 1. It indicates that initialization is entered try { if ((tab = table) == null || tab.length == 0) { // Get the initial size (when sc is positive, it is the initial size) int n = (sc > 0) ? sc : DEFAULT_CAPACITY; // Create a node array @SuppressWarnings("unchecked") Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n]; // Assign a value to the table property table = tab = nt; sc = n - (n >>> 2); } } finally { // Finally, remember to update sizeCtl sizeCtl = sc; } break; } } return tab; } The initTable() method initializes an empty table. 4.7 hashCode method public int hashCode() { int h = 0; Node<K,V>[] t; if ((t = table) != null) { Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length); for (Node<K,V> p; (p = it.advance()) != null; ) h += p.key.hashCode() ^ p.val.hashCode(); } return h; } The hashCode() method is to traverse each key value pair, make their key and value hash codes different or, and then stack them all. 4.8 addCount method The addCount() method will be called when the number of ConcurrentHashMap elements changes. The first of the two parameters is the number change value, and the second is the parameter that controls whether expansion check is required. private final void addCount(long x, int check) { // Create counter cell CounterCell[] cs; long b, s; /** 1.If counterCells is null: Then, it indicates that there has been no concurrency conflict before. Then, U.compareAndSetLong(...,b+x) will be executed to directly update the count value baseCount. If the local method is executed successfully, it will return true, and if it is reversed, it will be false. Then, the whole if determines that the two conditions are false, and the contents in the if block are not executed. 2.If couterCells is not null: It indicates that concurrency conflicts have occurred before, and the following if block processing is required. Here, if the first condition is true, the update method of the second condition will not be executed. */ if ((cs = counterCells) != null || !U.compareAndSetLong(this, BASECOUNT, b = baseCount, s = b + x)) { // Enter the if block, indicating that there has been a concurrency conflict, then add the value to the CounterCell CounterCell c; long v; int m; boolean uncontended = true; if (cs == null // cs becomes null again in concurrency || (m = cs.length - 1) < 0 // cs length less than 1 || (c = cs[ThreadLocalRandom.getProbe() & m]) == null // The corresponding CouterCell is null || !(uncontended = U.compareAndSetLong(c, CELLVALUE, v = c.value, v + x))) {// Attempt to update the value of the found count cell c // If the update fails. Generally, the method in the last condition above returns false, and the reverse is true // Description there is a concurrency conflict in the CounterCells array, which may involve the expansion of the array. Call the fullAddCount method fullAddCount(x, uncontended); return; } if (check <= 1)// If there is no need to check, return directly return; // Count and save it in s. the following is used for inspection s = sumCount(); } // Check whether capacity expansion is required if (check >= 0) { Node<K,V>[] tab, nt; int n, sc; while (s >= (long)(sc = sizeCtl) // The number of elements is greater than the capacity expansion threshold: capacity expansion is required && (tab = table) != null // Table is not empty && (n = tab.length) < MAXIMUM_CAPACITY) {// Table length does not reach the upper limit int rs = resizeStamp(n) << RESIZE_STAMP_SHIFT; // If you are performing resize if (sc < 0) { // Give up some conditions to help expand capacity if (sc == rs + MAX_RESIZERS || sc == rs + 1 || (nt = nextTable) == null || transferIndex <= 0) break; // sc+1 indicates that a new thread is added to help expand the capacity if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) transfer(tab, nt); } // Currently, resizing is not being executed. Try to become the first thread to enter the capacity expansion. Set sc to rs+2 else if (U.compareAndSetInt(this, SIZECTL, sc, rs + 2)) transfer(tab, null); // Recalculate the number of elements s = sumCount(); } } } See the code comments for detailed logic. Here are a few separate points. - The first if judgment condition is wonderful. Check whether the value should be added directly to baseCount or to the corresponding counter cell according to whether the counter cells array is null. - Note how to find the slot position in the counter cells array: C = CS [threadlocalrandom. Getprobe() & M]) = = null. - When the check parameter is less than or equal to 1, exit without checking. When it is greater than 1, check whether capacity expansion is required after the main logic of addCount is completed. When the put method calls addCount, the check parameter passed in is actually the number of nodes traversed during the put process, so the logic is connected: if there is only one node or it is empty, it is not necessary to consider whether to check the expansion again; Otherwise, check in addCoumt. 4.9 helpTransfer method The helpTransfer method can assist in data migration and return a new array when the node is resizing. This method is called in business methods such as put and remove. /** * Helps transfer if a resize is in progress. */ final Node<K,V>[] helpTransfer(Node<K,V>[] tab, Node<K,V> f) { Node<K,V>[] nextTab; int sc; // Three conditions need to be met simultaneously to enter the main logic of the method if (tab != null// Table is not empty && (f instanceof ForwardingNode)// f is a Forwarding Node && (nextTab = ((ForwardingNode<K,V>)f).nextTable) != null) // nextTable is not empty { // Calculate the mark "stamp" during this resize int rs = resizeStamp(tab.length) << RESIZE_STAMP_SHIFT; while (nextTab == nextTable // nextTab unchanged && table == tab // table unchanged && (sc = sizeCtl) < 0) // Sizecl remains less than 0 (resizing) { if (sc == rs + MAX_RESIZERS // The number of worker threads is full || sc == rs + 1 // In the addCount method, if there is the first capacity expansion thread, sc=rs+2. If it becomes rs+1, the expansion is over. || transferIndex <= 0) // If transferIndex is less than or equal to 0, it actually indicates that the expansion has been completed and the subscript adjustment has been entered. break; // Enable sc + + to enter capacity expansion if (U.compareAndSetInt(this, SIZECTL, sc, sc + 1)) { transfer(tab, nextTab); break; } } // Return to new table return nextTab; } // Return to original table return table; } 4.10 transfer method The function of the transfer method is to move and / or copy the nodes in each bin to a new table. There are calls in addCount() and helpTransfer(), which are the core implementation classes of capacity expansion. If there is a specific number in the following example, the length of the incoming tab shall be 16. private final void transfer(Node<K,V>[] tab, Node<K,V>[] nextTab) { // Define n as the table length. int n = tab.length, stride; /** stride Represents the number of tasks of a worker thread in a transfer, that is, the number of consecutive hash buckets to be processed. Initialize stripe: if the number of available CPU cores is greater than 1, initialize to (n > > > 3) / ncpu; otherwise, initialize to n. If the initialized stripe is less than MIN_TRANSFER_STRIDE, set it to this minimum. */ if ((stride = (NCPU > 1) ? (n >>> 3) / NCPU : n) < MIN_TRANSFER_STRIDE) stride = MIN_TRANSFER_STRIDE; // subdivide range if (nextTab == null) { // If nextTab is not initialized, initialize the array first try { @SuppressWarnings("unchecked")' // Create a nextTab array with the length of the original array * 2 Node<K,V>[] nt = (Node<K,V>[])new Node<?,?>[n << 1]; nextTab = nt; } catch (Throwable ex) { // Failed to create a new array. sizeCtl is set to the maximum value of int sizeCtl = Integer.MAX_VALUE; return; } // This array is assigned to nextTable nextTable = nextTab; // Update transfer subscript transferIndex = n; } int nextn = nextTab.length; // Create ForwardingNode fwd and pass in nextTab as the parameter ForwardingNode<K,V> fwd = new ForwardingNode<K,V>(nextTab); // The first advance is true. If it is equal to true, it indicates that a subscript (i --) needs to be pushed again. On the contrary, if it is false, the subscript cannot be pushed. The current subscript needs to be processed before proceeding boolean advance = true; // Mark whether the expansion has been completed boolean finishing = false; // to ensure sweep before committing nextTab /** It is also a for loop to process the linked list elements in each slot */ for (int i = 0, bound = 0;;) { Node<K,V> f; int fh; /** This while loop continuously tries to allocate tasks to the current thread through CAS until the allocation succeeds or the task queue has been fully allocated. If the thread has been allocated a bucket area, it will point to the next pending bucket through -- i and exit the loop. */ while (advance) { int nextIndex, nextBound; // --i indicates entering the next bucket to be processed. Greater than or equal to bound after subtraction indicates that the current thread has allocated buckets, and advance=false if (--i >= bound || finishing) advance = false; // All bucket s have been allocated. Assign value to nextIndex. else if ((nextIndex = transferIndex) <= 0) { i = -1; advance = false; } // CAS modifies TRANSFERINDEX to assign tasks to threads. // The processing node interval is (nextBound,nextINdex) else if (U.compareAndSetInt (this, TRANSFERINDEX, nextIndex, nextBound = (nextIndex > stride ? nextIndex - stride : 0))) { bound = nextBound; i = nextIndex - 1; advance = false; } } // Processing process // CASE1: the old array has been traversed, and the current thread has processed all responsible bucket s if (i < 0 || i >= n || i + n >= nextn) { int sc; // Capacity expansion completed if (finishing) { // Delete the member variable nextTable nextTable = null; // Update array table = nextTab; // Update capacity expansion threshold sizeCtl = (n << 1) - (n >>> 1); return; } // Use the CAS operation to subtract 1 from the lower 16 bits of sizeCtl, which means that you have completed your own task if (U.compareAndSetInt(this, SIZECTL, sc = sizeCtl, sc - 1)) { if ((sc - 2) != resizeStamp(n) << RESIZE_STAMP_SHIFT) return; // If the above if is not executed, i.e. (SC - 2) = = resizestamp (n) < < resize_ STAMP_ SHIFT // This indicates that there is no thread for capacity expansion, and the capacity expansion is over finishing = advance = true; i = n; // recheck before commit } } // CASE2: if node i is empty, put it into the ForwardingNode just initialized else if ((f = tabAt(tab, i)) == null) advance = casTabAt(tab, i, null, fwd); // CASE3: the current hash value of this location is MOVED, which is a ForwardingNode. It indicates that it has been processed by other threads, so it is required to continue else if ((fh = f.hash) == MOVED) advance = true; // already processed // CASE4: execute transfer else { // Lock the head node synchronized (f) { // Check again if (tabAt(tab, i) == f) { Node<K,V> ln, hn; // The head node in the slot is a chain head node if (fh >= 0) { // First calculate the current fh * n int runBit = fh & n; // Stores the lastRun that traverses the final position Node<K,V> lastRun = f; // Traversal linked list for (Node<K,V> p = f.next; p != null; p = p.next) { int b = p.hash & n; // If hash&n changes during traversal, runBit and lastRun need to be updated if (b != runBit) { runBit = b; lastRun = p; } } //If lastRun refers to a low-level linked list, make ln lastRun if (runBit == 0) { ln = lastRun; hn = null; } // If lastrun refers to a high-order linked list, make hn lastrun else { hn = lastRun; ln = null; } // Traverse the linked list, put the hash & n with 0 in the low-level linked list and those not with 0 in the high-level linked list // Loop out condition: current loop node= lastRun for (Node<K,V> p = f; p != lastRun; p = p.next) { int ph = p.hash; K pk = p.key; V pv = p.val; if ((ph & n) == 0) ln = new Node<K,V>(ph, pk, pv, ln); else hn = new Node<K,V>(ph, pk, pv, hn); } // The position of the low linked list remains unchanged setTabAt(nextTab, i, ln); // The position of the high-order linked list is: original position + n setTabAt(nextTab, i + n, hn); // Mark current bucket migrated setTabAt(tab, i, fwd); // If advance is true, return to the above for --i operation advance = true; } // The head node in the slot is a tree node; } // The head node in the slot is a reserved placeholder node else if (f instanceof ReservationNode) throw new IllegalStateException("Recursive update"); } } } } } The transfer() method is the core method for concurrent HashMap to perform capacity expansion. Its capacity expansion and transfer operation is actually similar to HashMap, which splits the original linked list into two linked lists. However, there are many differences in implementation details. See the source code Notes for details. 4.11 resizeStamp method /** * Returns the stamp bits for resizing a table of size n. * Must be negative when shifted left by RESIZE_STAMP_SHIFT. */ static final int resizeStamp(int n) { return Integer.numberOfLeadingZeros(n) | (1 << (RESIZE_STAMP_BITS - 1)); } The resizeStamp(int n) method can calculate stamp bits when a table of size n is expanded 5. Business methods 5.1 construction method // Default construction method public ConcurrentHashMap() { } // Construction method of providing only initial capacity public ConcurrentHashMap(int initialCapacity) { this(initialCapacity, LOAD_FACTOR, 1); } // Provides the construction method of map public ConcurrentHashMap(Map<? extends K, ? extends V> m) { this.sizeCtl = DEFAULT_CAPACITY; putAll(m); } // Provides the construction method of default capacity and load factor public ConcurrentHashMap(int initialCapacity, float loadFactor) { this(initialCapacity, loadFactor, 1); } // Provides the construction method of default capacity, load factor and number of Concurrent update threads. public ConcurrentHashMap(int initialCapacity, float loadFactor, int concurrencyLevel) { if (!(loadFactor > 0.0f) || initialCapacity < 0 || concurrencyLevel <= 0) throw new IllegalArgumentException(); // If the initial capacity is smaller than the number of Concurrent update threads, assign a new value to it if (initialCapacity < concurrencyLevel) // Use at least as many bins initialCapacity = concurrencyLevel; // as estimated threads long size = (long)(1.0 + (long)initialCapacity / loadFactor); // cap is assigned as the maximum capacity or expansion threshold int cap = (size >= (long)MAXIMUM_CAPACITY) ? MAXIMUM_CAPACITY : tableSizeFor((int)size); this.sizeCtl = cap; } 5.2 methods // Count cell array private transient volatile CounterCell[] counterCells; public int size() { // Call sumCount() long n = sumCount(); return ((n < 0L) ? 0 : (n > (long)Integer.MAX_VALUE) ? Integer.MAX_VALUE : (int)n); } final long sumCount() { // Get count cell array CounterCell[] cs = counterCells; long sum = baseCount; if (cs != null) { // The values in all counting units are added up for (CounterCell c : cs) if (c != null) sum += c.value; } return sum; } // A very simple counting unit with only one volatile counter value @jdk.internal.vm.annotation.Contended // This annotation ensures that the object of the current class has exclusive cache lines static final class CounterCell { // Only constructors are provided, but get/set methods are not provided. That is, the value of value is determined during initialization and will not be changed later volatile long value; CounterCell(long x) { value = x; } } The implementation of the size() method is to first obtain baseCount, which is the counter value obtained when there is no contention. Then the count values in the counting unit array are accumulated above. He has the following measures to ensure thread safety: - Set the value variable in the counterCells array and the CounterCell class to volatile. - The get/set method is not set for the value variable in the CounterCell class. So how is the counter cells array created and initialized, and how is baseCount increased. Later, we will explain the source code of business methods that change size, such as put(). 5.3 isEmpty method public boolean isEmpty() { return sumCount() <= 0L; // ignore transient negative values } See 5.2 for sumCount() method 5.4 get method public V get(Object key) { Node<K,V>[] tab; Node<K,V> e, p; int n, eh; K ek; // DP Hash int h = spread(key.hashCode()); if ((tab = table) != null // Table is not empty && (n = tab.length) > 0 // Table length is not 0 && (e = tabAt(tab, (n - 1) & h)) != null) {// The specified location is not null // The first position is the key to be found if ((eh = e.hash) == h) { if ((ek = e.key) == key || (ek != null && key.equals(ek))) return e.val; } else if (eh < 0)// The hash value of the current linked list header is less than 0, indicating that it is a special node // Call the find method of the special node e return (p = e.find(h, key)) != null ? p.val : null; // A normal node, normal linked list, normal traversal while ((e = e.next) != null) { if (e.hash == h && ((ek = e.key) == key || (ek != null && key.equals(ek)))) return e.val; } } return null; } Note that first, we calculate the hash position of the key to be searched in the hash table. Then do different processing according to the hash value of the found node. - If the hash value is the value to be found, it is returned directly. - If the hash value is less than 0, it means that the current node is a special node. Refer to 1.13 hash status parameters of special nodes. In this way, the find() method of special nodes will be called, such as the find() method of ForwardingNode class and TreeNode class. - If the hash value is greater than or equal to 0, traverse the current linked list. 5.5 containsKey method public boolean containsKey(Object key) { return get(key) != null; } 5.6 containsValue method public boolean containsValue(Object value) { if (value == null) throw new NullPointerException(); Node<K,V>[] t; if ((t = table) != null) { Traverser<K,V> it = new Traverser<K,V>(t, t.length, 0, t.length); for (Node<K,V> p; (p = it.advance()) != null; ) { V v; if ((v = p.val) == value || (v != null && value.equals(v))) return true; } } return false; } The Traverser class encapsulates the traversal logic of the containsValue method. The code is complex. The following table is not included here for the time being. 5.7 test method public V put(K key, V value) { return putVal(key, value, false); } final V putVal(K key, V value, boolean onlyIfAbsent) { // Air judgment if (key == null || value == null) throw new NullPointerException(); // DP Hash int hash = spread(key.hashCode()); // Counter for current bucket int binCount = 0; // Spin insert node until successful for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; K fk; V fv; // CASE1: if the table is empty, call the initialization method first if (tab == null || (n = tab.length) == 0) tab = initTable(); // CASE2: if the hash location node is empty, it is unlocked when inserting into the empty location else if ((f = tabAt(tab, i = (n - 1) & hash)) == null) { // Try to put the key value pair to put directly here if (casTabAt(tab, i, null, new Node<K,V>(hash, key, value))) break;// sign out } // CASE3: if the hash value of the hash location node is - 1, it is a Forwarding Node. Call helperTransfer() else if ((fh = f.hash) == MOVED) // Assist in transferring data and getting new arrays tab = helpTransfer(tab, f); // CASE4: if onlyIfAbsent is true and the header node is the required node, return it directly else if (onlyIfAbsent && fh == hash && ((fk = f.key) == key || (fk != null && key.equals(fk))) && (fv = f.val) != null) return fv; // CASE5: the specified location was found and is not empty (hash conflict occurred). else { V oldVal = null; synchronized (f) {// Lock the current node (chain header) if (tabAt(tab, i) == f) {// Then judge whether f is the head node to prevent it from being modified by other threads // if - is not a special node if (fh >= 0) { binCount = 1; for (Node<K,V> e = f;; ++binCount) {// Note that the counter is incremented during traversal K ek; // In the process of traversal, the value you want to insert is found. It will be returned according to the situation if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { oldVal = e.val; if (!onlyIfAbsent) e.val = value; break; } // If the tail is reached, a new node built by the current key value is inserted Node<K,V> pred = e; if ((e = e.next) == null) { pred.next = new Node<K,V>(hash, key, value); break; } } } // elseIf - is a tree node else if (f instanceof TreeBin) { Node<K,V> p; binCount = 2; if ((p = ((TreeBin<K,V>)f).putTreeVal(hash, key, value)) != null) { oldVal = p.val; if (!onlyIfAbsent) p.val = value; } } // else - if it is a reserved node else if (f instanceof ReservationNode) throw new IllegalStateException("Recursive update"); } } // After the insertion, check whether you need to treelize the current linked list if (binCount != 0) { if (binCount >= TREEIFY_THRESHOLD) treeifyBin(tab, i); if (oldVal != null) return oldVal; break; } } } // Counter plus one addCount(1L, binCount); // Return null return null; } See the notes for the specific logic, which are explained in detail. The putVal method keeps spinning with a for loop and keeps trying to insert the required key value pair. There are the following cases in the loop, which are embodied as five branches in the if else block. - The table is empty. Call the initialization method. - Hash position is empty. put directly without lock. - The hash location is a ForwardingNode. Call helpTransfer. - The hash position header is the current key, and onlyIfAbsent is true, which is returned directly. - The hash position is not empty, indicating a hash conflict. Pay attention to the update of binCount during traversal. Finally, add one to the object with addCount() and use binCount as the check parameter. 5.8 remove method public V remove(Object key) { return replaceNode(key, null, null); } final V replaceNode(Object key, V value, Object cv) { int hash = spread(key.hashCode()); // spin for (Node<K,V>[] tab = table;;) { Node<K,V> f; int n, i, fh; // CASE1: cases where you can exit directly: the array is empty or the hash result position is null. if (tab == null || (n = tab.length) == 0 || (f = tabAt(tab, i = (n - 1) & hash)) == null) break; // CASE2: the node is moving. Help to move else if ((fh = f.hash) == MOVED) tab = helpTransfer(tab, f); // CASE3: hash conflict occurs. Look it up in the linked list else { V oldVal = null; boolean validated = false; // Lock the head node synchronized (f) {// The internal specific logic will not be repeated, which is similar to the put method above if (tabAt(tab, i) == f) { if (fh >= 0) { validated = true; // e represents the current loop processing node, and pred represents the previous node of the current loop node for (Node<K,V> e = f, pred = null;;) { K ek; // find if (e.hash == hash && ((ek = e.key) == key || (ek != null && key.equals(ek)))) { V ev = e.val; if (cv == null || cv == ev || (ev != null && cv.equals(ev))) { oldVal = ev; if (value != null) e.val = value; else if (pred != null) pred.next = e.next; else setTabAt(tab, i, e.next); } break; } pred = e; if ((e = e.next) == null) break; } } else if (f instanceof TreeBin) { validated = true; TreeBin<K,V> t = (TreeBin<K,V>)f; TreeNode<K,V> r, p; if ((r = t.root) != null && (p = r.findTreeNode(hash, key, null)) != null) { V pv = p.val; if (cv == null || cv == pv || (pv != null && cv.equals(pv))) { oldVal = pv; if (value != null) p.val = value; else if (t.removeTreeNode(p)) setTabAt(tab, i, untreeify(t.first)); } } } else if (f instanceof ReservationNode) throw new IllegalStateException("Recursive update"); } } if (validated) { if (oldVal != null) { // If it is a deletion, the number of elements is reduced by one if (value == null) addCount(-1L, -1); return oldVal; } break; } } } return null; } The key is to lock the linked list header to achieve thread safety. Just look at the source code directly.
https://programmer.help/blogs/jdk-source-code-reading-concurrent-hashmap-class-reading-notes.html
CC-MAIN-2021-49
refinedweb
6,363
56.35
Jeff Turner wrote: > > Sorry to be so slow responding. After playing with it for a > bit, the short > > answer is "no". IMO, the web site is simply a "view" of the > documentation, > > and its structure should be independent of the physical > arrangement of the > > content files. > > Not particularly relevant to the tabs discussion but.. Well, I am misunderstanding something then. I guess I am thinking of tabs as being a first-level menu. I am also assuming that site.xml is book.xml writ large, i.e. for the whole site. > The website is already completely independent of filesystem structure. > We have a Cocoon sitemap.xmap file that does the mapping. site.xml has > no effect on the actual URI space - it just defines the menu. I don't follow. The menu that is associated with a file (i.e. the one that is pasted on the left side of the document) is built from the book.xml file that is in that document's directory. The selected tab is determined from the file's URI. In both cases, those are tied to a physical URI, not to anything defined in book.xml or site.xml. > > So, preferably, the site.xml would have something like this > > (I posted something similar in a previous message, but am > expanding on it a > > bit here): > > > > <site> > > <tab> > > <menu-item> > > <menu-item> > > ... > > </tab> > > <tab> > > ... > > </tab> > > </site> > > Yes, that could be done. Hmm.. perhaps a tab attribute would work better > than a custom element? Well, tabs are two-way. 1) When you click a tab, you see menu items under it. 2) When you click a menu item that opens a document, that document needs to know which tab and related menus it should display. The first concept is many-to-one, i.e. more than one tab & related menu could point to the same document. By definition (unless using frames), the second concept is one-to-one, i.e. a given document can only point to one tab & related menu -- forrest hard-codes the tab & menu information right into the file. The tab attribute is exactly what I proposed further down in the original email, but that only works for identifying the second concept. You still need something to define the relationship between tabs (high-level menus), menus, optional submenus, and documents. Since it is a hierarchical relationship, it seems natural to define it explicitly in the xml. > <menu tab="Foo"> > ... > <menu tab="Bar"> > ... > > Tabbiness is more a property of a node (and it's children) than a > separate thing. Can't have a tab without an associated page. You are correct that a tab needs to have an associated page. That can easily be an attribute of the tab element, or could default to the first subordinate document item. > > After thinking about this for a while, I see that the problem is that a > > document could appear in more than one menu, which could be ambiguous in > > terms of building a menu & tab bar for it. > > I think having a @tab attribute would solve this problem. We could say > that @tab works like namespaces: inherit from the parent, unless defined. I agree, as long as you deal somehow with the many-to-one aspect. > <menu tab="Foo"> > ... > <!-- These menu items all have @tab="Foo" --> > <menu tab="Bar"> > ... > <!-- @tab="Bar" --> > <menu href="special/index.html" tab="Foo"> > <!-- This entry has overridden @tab="Foo" --> > > Would that work? Only if, as I said, you allow a document to appear only once within this structure, or otherwise deal with the ambiguity of having the same document point to different tabs. Victor Mote
http://mail-archives.apache.org/mod_mbox/forrest-dev/200304.mbox/%3CPAEOKILLLBAPHPPDDBNLAEOFDMAA.vic@outfitr.com%3E
CC-MAIN-2015-14
refinedweb
605
67.76
Many times, we would like to collect information for reporting, or measure and alert on something. Normally, we use Windows Performance Monitors to do this. But, what do we use when a perfmon object/counter/instance doesn't exist? This post is an example of how to collect WMI information, and insert it into OpsMgr as performance data. From there we can use it in reports and create threshold monitors. For starters... we need to find the location of the data in WMI. We can use wbemtest to locate it and test our query. Hit "Connect" and connect to root\cimv2. For this example - I am going to look at the Win32_OperatingSystem class. Using Enum Classes, Recursive, I find the class. I notice the class has a property of "NumberOfProcesses". That will do well for this example since the output will be an Integer. I form the query.... select numberofprocesses from win32_operatingsystem Ok.... we know our WMI query we want.... now lets dive into the console. We will start by creating a performance collection rule.... for this query output. Authoring pane, Create a New Rule, Collection Rules, Performance Based, WMI Performance. Give the rule a name (in accordance with your documented custom rule naming standards), then change the Rule Category to "PerformanceCollection", and then choose a target. I am using Windows Server for this example. Click Next, and on the WMI Namespace page, enter your namespace, query, and interval. The interval in general should be no more than every 15 minutes, unless you really need a large amount of raw data for reporting. I am using every 10 seconds for an example only.... this is not recommended generally because of the large amount of perf data that will flood the database if we targeted all Agents, or Windows Servers. The last screen, and most confusing.... is the Performance Mapper. This is where we will give the rule the information it needs to populate the data into the database as ordinary performance data. First - we need to make up custom names for Object, Counter, and Instance. Just like data from collected from perfmon, we need to supply this.... so I will make up a name for each that makes sense. I will use "NULL" for Instance, as I don't have any instance for this type of data in my example. For the Value field, this is where we will input a variable, which represents our query output. In general, following this example, it will be $Data/Property[@Name='QueryObject']$ where you replace "QueryObject" with the name of your instance name that you queried from the WMI class. So for my example, we will use: $Data/Property[@Name='NumberOfProcesses']$ $Data/Property[@Name='NumberOfProcesses']$ Click "Create" and we are done! How do we know if it is working? Well, we can create a new Performance view and go look at the data it is collecting: Create a new Custom Performance View in My Workspace. Scope it to Windows Server (or whatever you targeted your rule to). Then check the box for "collected by specific rules" and choose your rule from the popup box. As long as you chose "PerformanceCollection" as the rule category, it will show up here. And check out the Performance view - we have a nice snapshot and historical record of number of processes from WMI: Also not the custom performance Object, Counter, and Instance being entered from our rule: Ok - fun is over. Lets use WMI to monitor for when an agent has more than 40 processes running! Create a Unit Monitor. WMI Performance Counters, Static Thresholds, Single Thresholds, Simple Threshold. We will fill out the Monitor wizard exactly as we did the Rule above. However, on Interval, since this monitor will only be inspecting the data on an agent, and not collecting the performance data into the database, we can use a more frequent interval. Checking every 1 minute is typically sufficient. Fill out the Performance Mapper exactly as we did above. Now.... on the threshold value... I want to set a threshold of 40 processes in this example. Over 40 = Critical, and under = Healthy. Sounds good. On the Configure Alerts pane, I am going to enable Alerts, and then add Alert Descirption Variables from Create it - and lets see if we get any alerts: Yep. Works perfectly: A quick check of Health Explorer shows it is working as designed:? So first I have to ask - if you are monitoring memory use from a specific process - why wouldnt you use the built in performance counter for that?!!! Process \ Private Bytes \ ProcessName=Instance Sweet Thanks Process\Working Set\Process! You dont need to use WMI for that. A simple perf monitor... Process, % Processor Time, dllhost* That works beautifully and is what I wanted all along. I have asked this question (i.e. can you use wildcards in the instance name) in a number of places, and you're the first one who answered. I figured no reply meant 'no, you can't'. Thanks! So i'm guessing you cant' edit this after saving? I haven't found a way Hello, i need to monitor all %processor time for all services on a server. How can i do that? Thanks.
http://blogs.technet.com/b/kevinholman/archive/2008/07/02/collecting-and-monitoring-information-from-wmi-as-performance-data.aspx
CC-MAIN-2015-14
refinedweb
870
66.44
Audio recording and playback Overview The ISD1100 voice chip is a single chip solution which allows for both the recording and playback of a 10 second audio clip, either in its entirety or in small pieces. Using only an electret microphone, a speaker and minimal circuitry a simple system can be developed. Our circuit used a 16 Ohm mini-tone transducer and a typical electret microphone with two wire leads. An electret microphone is easy to use with the chip. For more information on electret microphone theory and operation visit the microphones page. A 16 ohm speaker is recommended for use with the ISD1110. The chip can be run under PIC control. Using the code below, a user can start the recording process, enable the playback and even address specific locations of the recording by using the RS-232 connection to the PIC. Both recording and playback are enabled by connecting the corresponding pin on the chip to ground or digital low. A specific portion of the recording is accessed by sending an address to the ISD1110 chip. The recording can be accessed at increments of 125 milliseconds. There have been some issues with amplification to an easily audible level. If this is the case an external audio amplifier may be necessary to achieve the desired results. Circuit The circuit to the right shows the suggested configuration of the ISD1110 chip, as shown in the chip data sheet. When using the PIC to control the chip, the push buttons can be removed. The PLAYL, PLAYE and REC pins (pins 23, 24 and 27) should be connected to a digital output from the pic. In the code provided, these three pins correspond to outputs CO, C1 and C2 respectively. Also, to utilize the addressing capabilities of the chip, pins 1-6, 9-10 (labeled A0-A7 on the ISD1110) need to be connected to pins D0-D7 on the PIC. When testing the circuit, the desired voltage level at the microphone input is approximately 20 mV peak-to-peak, and the voltage across the speaker pins should be roughly 1.25V. As mentioned above, if the desired amplification is not achieved with this circuit, an external audio amplifier may be necessary between the speaker output pins and the speaker itself. Adjusting the values of the components in the circuit may help to remove noise from the signal and get a better signal quality, however, the values given are as specified in the data sheet for normal operation. Parts Electret Microphone - x1 16 Ohm Speaker - x1 ISD1110 - x1 LED - x1 1 kOhm Resistor - x2 5.1 kOhm Resistor - x1 10 kOhm Resistor - x2 470 kOhm Resostor - x1 0.001 uF Capacitor - x1 0.1 uF Capacitor - x4 4.7 uF Capacitor - x1 220 uF Capacitor - x1 Code The code below should be programmed onto the PIC, and operated using the RS-232 connection. The code basically takes one of four input commands and changes the 11 digital output pins (PLAYL, PLAYE, REC and A0-A7) to implement the desired command on the ISD1110 chip. For example, holding the REC pin low starts and continues the recording process until the output goes high, or all of the recording time is used up. Each of the commands can be implemented with an address ('a') and a duration ('d'). An address is an integer 0-80 which selects a specific 125 millisecond interval to start at, and a duration is given in milliseconds. The commands are as follows: rec a d; This will start recording at an address 'a' and record for a duration 'd' NOTE: The end of recording marker will be placed at the end of this recording and any information stored at a later time will be lost. play a; This will play a recording at an address 'a' loop d; This will continuously play the recording for a duration 'd' chunk a d; This will play a recording starting at an address 'a' and last for a duration 'd' Here are some examples: rec; Records for the entire 10 seconds starting at the beginning. rec 40 2000; Records for 2 seconds starting at 5 seconds. NOTE: The end of recording marker is placed at 7 seconds, and seconds 7-10 are inaccessible. play 40; Plays the recording starting at 5 seconds. loop 40000; Loops the entire recording for 40 seconds. chunk 40 30000; Plays the portion of the recording from 5 seconds to 8 seconds. #include <18f4520.h> #include <string.h> #include <stdlib.h> #fuses HS,NOLVP,NOWDT,NOPROTECT #use delay(clock=40000000) #use rs232(baud=9600, UART1) // hardware setup #define HIGH 1 #define LOW 0 #define REC_PIN PIN_C2 #define PLE_PIN PIN_C1 #define PLL_PIN PIN_C0 // software setup #define BUFFER 100 #define IS_CMD(i, c) (!stricmp((i), (c))) #define ENTER 0x0D #define DUR_PER_MEM_LOC 125 // ms #define MAX_MEM_LOC 80 #define MAX_DURATION 10000 // ms #define BASE 10 #define PULSE_ENABLE 10 // ms #define LOOP_ENABLE 0b11001000 // A7, A6, & A3 on (see ISD1100 data sheet) char REC_CMD[] = "rec"; char PLAY_CMD[] = "play"; char LOOP_CMD[] = "loop"; char CHUNK_CMD[] = "chunk"; /** * activates the play pin with a level signal */ void play_l(int8 a, int16 d) { printf("<<>> you sent a play segment @ %u for %lu command\r\n", a, d); output_d(a); output_bit(PLL_PIN, LOW); delay_ms(d); output_bit(PLL_PIN, HIGH); output_d(LOW); } /** * activates the looping feature */ void loop(int16 d) { printf("<<>> you sent a loop @ %u for %lu command\r\n", a, d); output_d(LOOP_ENABLE); output_bit(PLE_PIN, LOW); output_bit(PLE_PIN, HIGH); delay_ms(d); output_bit(PLL_PIN, LOW); output_bit(PLL_PIN, HIGH); output_d(LOW); } /** * activates the play pin with pulse signal */ void play_e(int8 a) { printf("<<>> you sent a play @ %u command\r\n", a); output_d(a); output_bit(PLE_PIN, LOW); delay_ms(PULSE_ENABLE); output_bit(PLE_PIN, HIGH); output_d(LOW); } /** * activates the record pin with a level signal */ void record(int8 a, int16 d) { printf("<<>> you sent a record @ %u for %lu command\r\n", a, d); output_d(a); output_bit(REC_PIN, LOW); delay_ms(d); output_bit(REC_PIN, HIGH); output_d(LOW); } /** * parses a command from an RS-232 prompt */ void run_cmd(char *input) { int16 addr, dur; char *delim = " ;"; char *cmd; cmd = strtok(input, delim); addr = strtoul(strtok(NULL, delim), NULL, BASE); dur = strtoul(strtok(NULL, delim), NULL, BASE); if(!dur) { dur = MAX_DURATION; } if(addr > MAX_MEM_LOC) { printf("<<>> oops address is out of range (0 <= addr <= %u).\r\n", MAX_MEM_LOC); } else if(IS_CMD(cmd, REC_CMD)) { record(addr, dur); } else if(IS_CMD(cmd, PLAY_CMD)) { play_e(addr); } else if(IS_CMD(cmd, LOOP_CMD)) { loop(dur); } else if(IS_CMD(cmd, CHUNK_CMD)) { play_l(addr, dur); } else { printf("<<>> oops invalid command \"%s\", try again!\r\n", cmd); } } /** * event loop */ void main(void) { int i; char input[BUFFER + 1]; // need to make space for the null character output_d(LOW); output_bit(REC_PIN, HIGH); output_bit(PLE_PIN, HIGH); output_bit(PLL_PIN, HIGH); while(TRUE) { // reset parameters i = 0; memset(input, '\0', sizeof(input)); // gather input while(i < BUFFER && (input[i] = getc()) != ENTER) { putc(input[i]); i++; } printf("\r\n"); // check input if(i == BUFFER) { printf("<<>> ERROR: your input is too long\r\n"); } else { run_cmd(input); } } }
http://hades.mech.northwestern.edu/index.php?title=Audio_recording_and_playback&amp;action=history
CC-MAIN-2019-22
refinedweb
1,163
56.08
: For applications using ASP.NET 4.0 Ajax Extensions:. For applications using ASP.NET 3.5 Ajax Extensions: 1. Change the <scriptmanager> tag to the following: <asp:ScriptManager <scripts> <asp:ScriptReference <asp:ScriptReference </scripts> </asp:ScriptManager> 2. Make sure that the <script> tag that loads the Messenger Web Toolkit loader occurs after the <scriptmanager> tag in the page. Offir Bakshitz Software Design Engineer Windows Live Messenger Platform Team Awesome, even though I already spent 5-6hrs troubleshooting this issue, you definitely saved my next 10s of hours. Now that there is a newer release of this, what should the proper path to the AJAX library be? Is the Messenger Connect stuff still using an old beta version of the library? I found one issue, SCRIPT5022: Sys.InvalidOperationException: Invalid attribute 'sys:attach', the type 'wlsignin' is not a registered namespace. MicrosoftAjax.debug.js, line 9224 character 29 In Internet Explorer 9 with your solution. Any idea? Hello Offir Bakshitz, I am using ASP.NET 4.0. I have implemented the solution. I am able to see see Windows Live Signin button and it is working fine. But I am getting error in pages where I am using Response.Redirect. Error: A potentially dangerous Request.Path value was detected from the client (:). I have added <httpRuntime requestValidationMode="2.0" requestPathInvalidCharacters="" /> in webconfig file . Now it is showing another file not found error! will there be any inbuilt solutions included in Windows Live ID SDK for this or we have to implement all these solutions? Regards, Damodar_K I am still getting following error Microsoft JScript runtime error: Sys.InvalidOperationException: Operation is not valid due to the current state of the object. source file : MIcrosoftAjax.js
https://blogs.msdn.microsoft.com/messenger/2010/06/24/resolving-a-conflict-with-asp-net-ajax-extensions/
CC-MAIN-2016-40
refinedweb
282
52.46
Revert to original widget color On 05/07/2015 at 05:17, xxxxxxxx wrote: When I override the default color for a color ID for a widget, how am I supposed to revert it to the original color? Until now, I used GeDialog.GetColorRGB() to get the original color value, but that is kind of clunky. :-( On 05/07/2015 at 05:47, xxxxxxxx wrote: del it On 05/07/2015 at 06:16, xxxxxxxx wrote: I should've been more clear, I'm talking about the color associated with color IDs for widgets in a GeDialog plugin. I'm not sure how you understood my question. On 05/07/2015 at 06:32, xxxxxxxx wrote: Argh, sorry I reread initial post, "revert" seems for me as "invert" On 06/07/2015 at 03:33, xxxxxxxx wrote: Hi Niklas, Originally posted by xxxxxxxx I should've been more clear, I'm talking about the color associated with color IDs for widgets in a GeDialog plugin. Do you mean calling GeDialog.SetDefaultColor() with a custom color then calling it with a color from GeDialog.GetColorRGB()? On 06/07/2015 at 07:09, xxxxxxxx wrote: Hi Yannick, yes it's possible with GeDialog.GetColorRGB(), but it's just so inconvenient. GeDialog.SetDefaultColor() wants a color vector, but GetColorRGB() returns a dictionary with values in RGB space. def get_color(dlg, color_id) : col = dlg.GetColorRGB(color_id) return c4d.Vector(col['r'], col['g'], col['b']) * (1.0 / 255) if engine in SUPPORTED_RENDERERS: self.SetDefaultColor(res.STR_RENDERER, c4d.COLOR_TEXT, c4d.Vector(1.0, 0.2, 0.0)) else: self.SetDefaultColor(res.STR_RENDERER, c4d.COLOR_TEXT, get_color(self, c4d.COLOR_TEXT)) It would be nice if the SetDefaultColor() function would just accept None or the dialog would have a function to get the color as a Vector already. This is just something that makes the programmers life unpleasent and its only one part where I think things could be improved to make them easier. Passing None would be logical, you could just pass None and if it works you're fine, but otherwise you have to look into the SDK how to do it otherwise. Best regards, Niklas On 07/07/2015 at 02:20, xxxxxxxx wrote: Hi Niklas, Thanks for your input. It will help us design better functions in the future. But we can't change the behavior of existing functions as this would break plugins.
https://plugincafe.maxon.net/topic/8904/11811_revert-to-original-widget-color
CC-MAIN-2020-50
refinedweb
400
56.45
I just installed a new video card (GTX 680) in my computer (64-bit ubuntu linux v12.04) and installed the latest nvidia driver (v310.19) and updated my GLEW files to v190. I updated my GL and GLX include files from the nvidia driver, and updated my GLEW include and source files from the new GLEW files. Now my 3D engine doesn't work. BTW, it did run on the new graphics card before I updated the drivers and GLEW (I'm about 99% sure of that). The problem is, the OpenGL function glGenVertexArrays(1, &vaoid) always returns a value of zero no matter how many times I call the function, and no matter how many VAO identifiers I ask the function to generate. Does anyone know what this problem is... or might be? I cut and paste the section of code where the problem occurs. Note that I just added all those glGetError() calls to debug what's happening. Note that ALL of the glGetError() calls return zero, indicating no errors. However, it seems to me that glGetVertexArrays() returning a value of zero IS an error (at least on its part). Note that it does return valid identifiers for the IBO and VBO (values == 1 and 2). Note that this error is happening the first time glGetVertexArrays() is being called after my program starts up. Also note that the same problem happens whether I compile the program into a 32-bit executable or a 64-bit executable (both of which ran before). My current code is OpenGL v3.20 level. I upgraded my GPU to update my engine to OpenGL and GLSL v4.30 level. Hmmmm. During startup I print out a whole pile of xwindows, GLX and GL values, and I notice the following string prints out for glGetString(GL_VERSION): 2.1.2 NVIDIA 313.09 What is the 2.1.2 supposed to be? The version of OpenGL? If so, that appears to be a version before the VAO was supported. If so, is there some new call that's now required to specify what version of OpenGL my program intends to access... and maybe it defaults to v2.12 if nothing is specified? (Of course, I don't think there ever was a version 2.12 of OpenGL). Also, what is the 313.09 supposed to be? The driver was supposed to be 310.19 on the nvidia website (and that is still the version on their website today, so I don't think v313.09 even exists yet). Code :u32 vaoie = 0; u32 vaoif[4]; vaoif[0] = 0; vaoif[1] = 0; vaoif[2] = 0; vaoif[3] = 0; error = glGetError(); error = glGetError(); glGenBuffers (1, (GLuint*)&iboid); // OpenGL - create IBO identifier error = glGetError(); glGenBuffers (1, (GLuint*)&vboid); // OpenGL - create VBO identifier error = glGetError(); glGenVertexArrays (1, (GLuint*)&vaoid); // OpenGL - create VAO identifier error = glGetError(); glGenVertexArrays (1, (GLuint*)&vaoie); error = glGetError(); glGenVertexArrays (4, (GLuint*)&vaoif[0]); error = glGetError(); if (iboid <= 0) { return (CORE_ERROR_INTERNAL); } // error - invalid IBO identifier if (vboid <= 0) { return (CORE_ERROR_INTERNAL); } // error - invalid VBO identifier if (vaoid <= 0) { return (CORE_ERROR_INTERNAL); } // error - invalid VAO identifier ------------------------------------------------------------------------------
http://www.opengl.org/discussion_boards/showthread.php/180544-help-problem-with-glGenVertexArrays()?p=1246431&viewfull=1
CC-MAIN-2014-10
refinedweb
517
74.49
You can subscribe to this list here. Showing 10 results of 10 --- David <mpe501@...> wrote: > So how can i make python halt immidiatly when there > has been an error in > any of the callbacks? import sys ... try: <python code> except ExceptionType: <python code - Exception handle> sys.exit() []'s Cadu Moreira KaduSoft President ---------------------------- [...give me a beer...] __________________________________________________ Do You Yahoo!? Yahoo! - Official partner of 2002 FIFA World Cup If an error occurs in the display function my python opengl demos python doesn't halt and give me an error, instead it gives me an error but calls the display function again and again and again. If you have glPushMatrix():es in your code this means you will get a xterm full of "stack overflow" errors instead of the actual error that is causing the problem. So how can i make python halt immidiatly when there has been an error in any of the callbacks? The fix? Is anyone using stereo with PyOpenGL? I've had absolutely no success with it, so far. I started out with a rather complex program, where my PyOpenGL code was basically embedded in a large C-based OpenGL infrastructure (basically my Python code is only the redraw callback, all the double-buffer and left-right juggling and perspective matrices and such are handled for me in C). This worked fine for the mono case, but when I ran the program in stereo I got to see the both viewpoints sort-of interspersed, with a lot of flickering and not in sync with the glasses. I've slowly worked back, taking out bits and pieces of the system to narrow down the culprit, and I'm now at a minimal PyOpenGL GLUT-based program, which is basically the PyOpenGL GLE example with stereo turned on and the do_display() routine replaced by glDrawBuffer(GL_BACK_LEFT) glClearColor(0, 0, 1, 0) glClear(GL_COLOR_BUFFER_BIT) glDrawBuffer(GL_BACK_RIGHT) glClearColor(1, 0, 0, 0) glClear(GL_COLOR_BUFFER_BIT) # [see below] glutSwapBuffers() and I see a blue background, nothing more. However, if I wiggle the mouse (which causes draw events, because the original GLE.py example code used that to rotate the tube) I see flashes of red. To make matters more unintellegible, if I insert drawing code at the [see below] I do see what I draw here, but against the blue background! So, what I see is a non-stereo image consisting of the background color of the left buffer and the graphics in the right buffer??!? None of these problems exist with C OpenGL code, so I tend towards blaming something PyOpenGL does for this. What would be really helpful to me at this moment is a PyOpenGL script that is known to work, at least for someone on some machine, at some time:-) This is all with PyOpenGL from the CVS HEAD (built with swig 1.3.9, later versions don't seem to work) with a few mods needed to make it compile (missing semicolons!). The machine is a dual 1.6GHz Pentium Linux box (2.4.9 kernel) with an ATI Rage XL graphics board. Please reply to me directly (as well as possibly ccing to the list if it's deemed of general interest), I'm not on this list yet, -- - Jack Jansen <Jack.Jansen@...> - - If I can't dance I don't want to be part of your revolution -- Emma Goldman - On Thursday 09 May 2002 06:44 am, David wrote: > Where can i find samples for using PyOpenGl? Preferably about using > PyOpenGl with glut, but any samples would be greatly appriciated. I kno= w > GL, so that's not a problem. Something I hacked on last December: This includes some optimisation work - try running with and without the C= =20 extension modules. Richard Where can i find samples for using PyOpenGl? Preferably about using PyOpenGl with glut, but any samples would be greatly appriciated. I know GL, so that's not a problem. Regards, David > From: Peter Lundh <simran@...> > >@... If that's your command above, you need to supply an action for the setup.py script: The following is the common usage: python setup.py build (see if everything goes ok) python setup.py install HTH, DAve@... 2.0.0.44 doesn't work with Mac yet. The ambitious may try CVS as it works better, but still fails at some point. Tarn I have problems installing PyOpenGL on MacOSX. I have installed Python with Fink and have downloaded "PyOpenGL-2.0.0.44". When I try to run the python setup.py command I get the following message: > [laptop1:~/PyOpenGL-2.0.0.44] peter% python setup.py > Traceback (most recent call last): > File "setup.py", line 54, in ? > from setup import togl_setup > File "setup/togl_setup.py", line 16, in ? > tk = Tkinter.Tk() > File "/sw/lib/python2.2/lib-tk/Tkinter.py", line 1487, in __init__ > self.tk = _tkinter.create(screenName, baseName, className) > TclError: couldn't connect to display "localhost:0.0" > [laptop1:~/PyOpenGL-2.0.0.44] peter% What am I doing wrong? -- Peter Lundh von Leithner Sweden E: simran@...
http://sourceforge.net/p/pyopengl/mailman/pyopengl-users/?viewmonth=200205&style=flat
CC-MAIN-2016-07
refinedweb
845
73.88
Yes, you read it right. In this article, I will give you a hands-on experience of GPT3. I was lucky enough to get access to private beta after waiting for 8 months 🙂 Introduction Last week I was exploring with GPT-3. I was thinking I will learn it in a data it two. But boy it took me a lot of time to learn it. I was very surprised by the concept of this model. I was amazed and I really felt this is a big deal. I will talk about this in a bit. First, let me tell you what GPT-3 is. What is GPT3? GPT-3 is a language model. It predicts the next word of a sentence given the previous words in a sentence. I was pretty aware of the GPT3. But I was not aware of it’s working. Many of my friends were talking about it. I was not aware of how it works. So, I started to research it. I read a lot of articles about it. And I learned it. I was amazed. I was totally surprised by the concept. I will share with you the GPT-3 theory. It will be very helpful. This theory will help you understand the principle of the GPT-3. Now, let’s start with the GPT-3 theory or the GPT-3 principle. The GPT-3 principle is very easy to understand. As I said earlier, GPT-3 predicts the next word of a sentence given the previous words in the sentence. But how does it predict the next word? How does it understand the previous word? This is the tricky part of the GPT-3. GPT-3 uses a very different way to understand the previous word. The GPT-3 uses a concept called the hidden state. The hidden state is nothing but a matrix. In this hidden state, each cell represents a probability of each possible output. Now coming to configuration, GPT3 has 175 Billion parameters. It is a big number. This is the reason it took me a lot of time to configure it. Now coming to the architecture, the GPT-3 architecture has two layers. The bottom layer is the memory layer. The Memory layer contains the hidden state. The memory layer has 900 Million parameters. The memory layer uses the LSTM for memory. The second layer is the output layer. The output layer has a layer of 512 nodes. It is a big layer. The output layer uses the LSTM for the output layer. Found something unusual? Actually, the paragraphs above was not written by me but GPT3! I didn’t have to do anything except some minor grammar errors. The article from now onwards will be my words, I guarantee! I know most of you don’t have API access but in case you’re wondering, this paragraph was generated using this piece of code: import os import openai openai.api_key = os.getenv("OPENAI_API_KEY") response = openai.Completion.create( engine="davinci", prompt="Kaustubh's Analytics Vidhya ArticlennBlognn May 16, 2021n Title: Hands-on Experience With GPT3!n tags: machine-learning, gpt3, hands-on with-gpt3, gpt3 example coden Summary: I am sharing my early experiments with OpenAI's new language prediction model (GPT-3) beta. I am giving various facts about the GPT-3, its configuration. I am explaining why I think GPT-3 is the next big thing. I am also adding various example codes of the GPT3. In the end, I conclude that it should be used by everyone.n Full text: ", temperature=0.7, max_tokens=1766, top_p=1, frequency_penalty=0, presence_penalty=0 ) Hands-on Examples I tried to explore this API to its full potential. When you’re allotted the API key, you have a limit on how many requests you can make. The metric to measure these requests is different and varies from model to model. There are 4 four models offered by GPT3 and Davinci is the best model among them with 175 billion parameters, around 700 GB in size, and trained over 45 TB data. 1. Let’s see what the GPT3 has to say about Analytics Vidhya 🙂 The reviews are pretty positive! 2. I tried to get myself a good introduction for Medium and this is what the model generated. It has a lot of unnecessary information but provided more information and controlling the hyperparameters of the model, I think I will get my desired output. 3. Building an image classification model for a car vs truck using Keras. The code can be a bit buggy but it can give an idea about the implementation. 4. Linear regression model for tips dataset of the seaborn library. 5. Let’s put the model to produce a data science resume cover letter template so that next time you have the required material! 6. Lastly, we will instruct GPT3 to produce a chessboard using the Turtle library in Python! Conclusion GPT3 is a way too advanced and powerful tool. There are so many use cases I can think of. Now, you can have a human-like bot for conversational marketing. I wanted to add some of the examples of my conversation with the AI but it would make the article long. I hope you had fun watching the bot doing all the manual works. It can also create SQL queries, convert JS code to Python, convert movie titles into emojis, and much more! The media shown in this article are not owned by Analytics Vidhya and is used at the Author’s discretion.You can also read this article on our Mobile APP
https://www.analyticsvidhya.com/blog/2021/05/hands-on-experience-with-gpt3/
CC-MAIN-2021-25
refinedweb
938
68.57
#include <MNodeMessage.h> This class is used to register callbacks for dependency node messages of specific dependency nodes. There are 4 add callback methods which will add callbacks for the following messages Callbacks that are registered for attribute changed/addedOrRemoved messages will be passed an AttributeMessage value as a parameter. This value indicates the type of attribute message that has occurred. See the AttributeMessage enum for all available messages. Each. Pointer to an AttributeMessage callback which takes two plugs. Pointer to an AttributeMessage callback which takes a single plug. Pointer to a change in keyability callback function. The type of attribute changed/addedOrRemoved messages that has occurred. Allows you to prevent attributes from becoming (un)keyable. This method registers a callback for attribute changed messages. See the AttributeChanged enum for a list of all possible messages that will trigger the callback. Note: Attribute Changed messages will not be generated while Maya is either in playback or scrubbing modes. If you need to do something during playback or scrubbing you will have to register a callback for the timeChanged message which is the only message message that is sent during those modes. The callback function will be passed the type of attribute message that has occurred, the plug(s) for the attributes, and any client data that the user wishes to pass in. Example callback ( prints out a message when a connection is made or broken ) : void userCB( MNodeMessage::AttributeMessage msg, MPlug & plug, MPlug & otherPlug, void* ) { if ( msg & MNodeMessage::kConnectionMade ) { cout << "Connection made "; } else if ( msg & MNodeMessage::kConnectionBroken ) { cout << "Connection broken "; } else { return; } cout << plug.info(); if ( msg & MNodeMessage::kOtherPlugSet ) { if ( msg & MNodeMessage::kIncomingDirection ) { cout << " <-- " << otherPlug.info(); } else { cout << " --> " << otherPlug.info(); } } cout << endl; } Registers callbacks for attribute add/removed messages. This is a more specific version of addAttributeChanged as only attribute added and attribute removed messages will trigger the callback. This method is obsolete. This method is not available in Python. Registers a callback for node dirty messages. This callback provides the plug on the node that was dirtied. Only provides dirty information on input plugs. This method is obsolete. This method is not available in Python. Registers a callback for name changed messages. This method is obsolete. This method is not available in Python. The callback registered with this method will only get called when the deletion operation is first performed. If you also wish to receive notification of deletion events when they are redone, you should register an additional callback using addNodePreRemovalCallback(). Registers a callback which will get called before a node is deleted. This callback is called before connections on the node are removed. Unlike the aboutToDelete callback, this callback will be invoked whenever the node is deleted, even during a redo. Pre-removal and aboutToDelete callbacks serve different purposes. If DG changes need to be made when a node is deleted, the aboutToDelete callback should be used to add undoable operations to an MDGModifier to perform these changes. When the desired actions cannot be accomplished using the MDGModifier passed to the aboutToDelete callback, this callback can be used to receive notification of the deletion event, even during redo. Note that this callback method should not perform any DG operations. NodeDestroyed callback. Registers a callback which will get called when a node's destructor is called. Attribute keyable state change override. This method registers a callback that is invoked by any class that changes the keyable state of an attribute. When the callback is invoked, the API programmer can make a decision on how to handle the given keyable change event. The programmer can either accept the the keyable state change by returning a decision == 'true' or reject it by returning decision == 'false'. Note: you can only attach one callback keyable change override callback per attribute. It is an error to attach more than one callback to the same attribute.
http://download.autodesk.com/us/maya/2009help/api/class_m_node_message.html
CC-MAIN-2014-42
refinedweb
642
65.83
Hide Forgot In the file /usr/include/rpm/rpmlib.h, it includes four headers, three of which are in the same directory at rpmlib.h. Unfortunately, they are specified as: #include <header.h> #include <dbindex.h> which causes gcc to not find them unless /usr/include/rpm/ is added to the includepath, which is difficult (to me) when using autoconf to automatically detect the presence of the rpmlib devel tools. The proposed change is: #include <rpm/header.h> #include <rpm/dbindex.h> (and so forth for any other such) The change as suggested would prevent building rpm within it's own tree. The right thing to do is use #include "rpmio.h" in /usr/include/rpm/rpmlib.h. This is the way that rpm used to do things, was changed for some crazy reason having to do with automagically generated perl bindings, is now in the process of being changed back. Or, use -I/usr/include/rpm appropriately, that works too.
https://bugzilla.redhat.com/show_bug.cgi?id=11458
CC-MAIN-2019-09
refinedweb
161
59.7
Hi Olemis, A bit too much in that message to comment sensibly in a single email but I will try to cover some points. The first part is a particularly confusing as I do not see the common module in bloodhound_multiproduct/multiproduct, I wonder if you are looking at the right code. Meanwhile I didn't follow the p prefix idea but instead decided on req.path_info.startswith('/products') so that it is more obvious what it is for. I don't mind variations on that but I think that /p is not enough to retain clarity. Even if google use it. > 2- IMO import statements in `multiproduct.__init__` should be absolute I have no problem with that change. > 3- I wonder whether it'd be a good idea to Possibly but it could be overkill if there are not going to be that many additional models to support. > 4- Product table key is ['prefix', 'name'] . Why ? Well, certainly both are considered unique. We can look at whether this is correct usage. > 5- It's cool to have models ! :) I agree it would probably be better to use a pre-existing ORM - I would quite like to see the whole of bloodhound including trac to use such an approach so that more of the system can be taken a consistent step away from raw SQL. I don't know if I am on my own in liking good ORMs of course which is why I have not made too much of it. I do have a secret desire to be using django's model and query system though! I'll have to consider the rest later but there is not a huge amount to actually disagree with. Things do need moving around and the code has languished a little while I have been distracted by other concerns. I think we are placing a higher priority on getting the basic interface right than getting multi-product fully working (product namespaces, permissions etc). I can see that work slipping to the next milestone if we are not able to get more people interested in working with us and up to speed in the short term. Cheers, Gary On 06/14/2012 06:03 AM, Olemis Lang wrote: > Hi ! > :) > > I've been reviewing the code in multiproduct plugin these days . I > have some doubts | comments | ... I thought I'd share them with you . > > 1- I've noticed that function `multiproduct.common.match_product_path` is not > used anywhere else . What is it for ? > a) After a while I found > `multiproduct.ticket_web_ui.ProductTicketModule.match_request` > method and I confirmed my intuition was correct. > As far as I can say *NOW* (<= i.e. I can change my mind if > there're strong arguments supporting that approach ;) > that's something I do not recommend . > `IRequestHandler.match_request` should decide quickly > (<= and that means **really** quick) whether the > handler will process the request or not. > I even notice the execution of a SQL > select statement . IMO that's far too much to belong in > `match_request` method. Besides that approach may lead > to collisions with paths matched by other plugins . > That's the reason why I suggested in t.e.o site , and > trac-dev ML to use ''/p/'' prefix similar to Google > Code (which is short and simple) to reduce the scope > of web request to the context of a particular > product / project. Sample ticket URL would be e.g. > > and (initially ;) may be matched using a simple regex > like ` r'^/p/(?P<pid>[^/]+/ticket/(?P<tid>\d+)$)' `. > 2- IMO import statements in `multiproduct.__init__` should be absolute i.e. > `from multiproduct.model import MultiProductEnvironmentProvider` > instead of `from model import MultiProductEnvironmentProvider` > 3- I wonder whether it'd be a good idea to > a) ... populate `MultiProductEnvironmentProvider.SCHEMA` considering > `SomeModel.__meta__` (e.g. `SomeModel` may be `Product` , > `ProductResourceMap`, ...) > b) ... make `MultiProductEnvironmentProvider` capable of discovering > existing classes dynamically i.e. in such a way that it won't be > necessary to update that class if new models are introduced . > 4- Product table key is ['prefix', 'name'] . Why ? > 5- It's cool to have models ! :) > Is it a good idea to consider using ORMs like SqlAlchemy [1]_ > (... or maybe other ...) ? > 6- IMO we should add multi-product version to '''System Information''' > table in ''About Trac'' page (i.e. ) > 7- I also suggest the following changes in files (relative to > ''multiproduct'' folder) : > > || Current file path || Suggestions || > ||-------------------||--------------------------------|| > || product_admin.py || admin/product.py , admin.py || > || ticket_web_ui.py || web_ui/ticket.py || > || web_ui.py || web_ui/__init__.py || > ||<create new> || api.py || > > ... and the following simple refactorings to move classes > and change their names : > > || From || To > || > ||---------------------------------------||----------------------------------------|| > || model.MultiProductEnvironmentProvider || > api.MultiProductSystem || > || ticket_web_ui.ProductTicketModule || > web_ui.ticket.MultiProductTicketModule || > > 8- IMO `multiproduct.model.MultiProductEnvironmentProvider` should > not implement `trac.web.api.ITemplateProvider` as it is not related with > request handling at all . It doesn't even make use of any ''Genshi'' > template included in the plugin. Usually this is the kind of things > defined in `web_ui` modules . > 9- I suggest merging current `multiproduct.product_admin.ProductPermissions` > class with `multiproduct.model.MultiProductEnvironmentProvider` (... or > `multiproduct.api.MultiProductSystem` especially if §7 is ok ;). > 10- There's a lot of great stuff in multi product plugin . IMO it > deserves some test cases , so we should have a ticket for that > scheduled for RC1 ... or some other milestone ... that's > something we should decide ;) > > PS: I could not finished ... so maybe there's a second message on this > subject ;) > > .. [1] Trac SQLAlchemy Bridge > () >
http://mail-archives.apache.org/mod_mbox/incubator-bloodhound-dev/201206.mbox/%3C4FD9DEF5.5090903@wandisco.com%3E
CC-MAIN-2015-35
refinedweb
902
59.3
Opened 7 years ago Closed 3 years ago #5916 closed bug (fixed) runST isn't free Description While optimizing some code I discovered that runST isn't free. I had a function on the form: f ... = ...let x = runST in (f x)... Manually transforming it into f ... = runST (g ...) where g ... = do ... x <- ... g x ... (The real example is at) improved performance quite a bit on this, already highly tuned, function. Unfortunately, combining all the calls to runST into one and pulling them "up" is not all good. The code is now less modular, has a somewhat over specified evaluation order, and generally looks more imperative. The cause of the decrease in performance is that runSTRep cannot be inlined, which causes allocation of closures inline in the code (where none should be necessary.) The comment next to runSTRep explains why it's implemented the way it is, but I wonder if matters could be improved by making it a primop. If we create a fresh state token every time, instead of reusing realWorld#, it should be impossible for mutable structures to let-float and become CAFs (which is what runSTRep tries to avoid.) Change History (25) comment:1 Changed 7 years ago by comment:2 Changed 7 years ago by I can't make sense of the exmaple in the intro. Could you make a tiny test case that demonstrates the problem? comment:3 Changed 7 years ago by I'm afraid I'm too stuck in my current use case to think of examples from some other domain. This is not a standalone test case, but hopefully it at least makes the problem clear. Imagine we want to write a function: -- | /O(n)/ Update the element at the given position in this array. update :: Array e -> Int -> e -> Array e where Array is some simple wrapper around Array#. We can write this function using another function, update', in ST. -- | /O(n)/ Update the element at the given position in this array. update' :: Array e -> Int -> e -> ST s (Array e) update' ary idx b = do mary <- thaw ary 0 count -- Copies all elements into a mutable array write mary idx b -- Update the one element unsafeFreeze mary -- Return as an immutable array where !count = length ary update ary idx b = runST (update' ary idx b) Now, say we have a function that calls update many times in a loop: data RoseTree a = Rose a (Array (Rose a)) | Nil insert :: a -> RoseTree a -> RoseTree a insert x Nil = Rose x ... insert x (Rose y subtrees) | x == y = Rose x subtrees | otherwise = Rose y $ update subtrees idx (insert x subtreeToUpdate) where idx = subtreeIndex x y -- Pick the right subtree to update subtreeToUpdate = index subtrees idx index :: Array a -> Int -> a index = ... (If you find insert hard to understand, it might be helpful to consider what insert would look like if we were using a tuple of fixed size (e.g. 2 for a binary tree) instead of an Array.) insert will end up calling runST many times. If we want to avoid the cost of runST at each level of the tree, we could structure the code like so: insert :: a -> RoseTree a -> RoseTree a insert x0 t0 = runST (go x0 t0) go x Nil = return $ Rose x ... go x (Rose y subtrees) | x == y = return $ Rose x subtrees | otherwise = do st <- go x subtreeToUpdate ary <- update' subtrees idx st return $ Rose y ary where idx = subtreeIndex x y -- Pick the right subtree to update subtreeToUpdate = index subtrees idx N.B. We have replace the call to update, which embeds a call to runST, with a call to update', which doesn't. We have now reduced the number of calls to runST from O(log n) to 1, which turns out to be a performance improvement since runST allocates. comment:4 Changed 7 years ago by Thanks for the example. What I don't understand is why does runST allocate. That's the example I'd like to see. In your code update ary idx b = runST (update' ary idx b) = {- inline runST; g is a coercion between ST and STRep -} runSTRep (update' ary idx b) |> g) = {- inline the wrapper on update' runSTRep ($wupdate' ary idx b) = {- inline runSTRep, admittedly late -} case $wupdate' ary idx b realWorld# of (# s', _ #) -> s' No allocation. So where am I wrong? A tiny repro case of this phenomenon would be great. I understand about not wanting to take the runST outwards... apart from anything else it makes it sequential and it should not be! comment:5 Changed 7 years ago by This is wrong I think, runSTRep is NOINLINE: {-# NOINLINE runSTRep #-} runSTRep :: (forall s. STRep s a) -> a runSTRep st_rep = case st_rep realWorld# of (# _, r #) -> r We thus need to create a closure containing the arguments to $wupdate' and give it as an argument to runSTRep. comment:6 Changed 7 years ago by Conclusion: inline runSTRep, but very late. The comments suggest this is difficult. Perhaps we could arrange it so full laziness (which is what causes the wrong let floating according to the comment) happens before the last inliner phase. But this feels a bit brittle still, we have to be really careful so any optimizations we run won't result in things becoming shared CAFs. comment:7 Changed 7 years ago by I locally defined my own versions of runST and runSTRep, which I inlined in the last phase. I looked at the core and validated that in my particular case nothing bad had happened. This let me measure the actual performance difference: 7% on my particular benchmark. In addition it let me move back to nice, clean code. comment:8 Changed 7 years ago by comment:9 Changed 6 years ago by comment:10 Changed 6 years ago by comment:11 Changed 5 years ago by Just noting down some idée fixe: The reason we are not inlining runSTRep is that we don’t want to expressions using the realWorld# token to become shared, right? How about runSTRep gets a special inlining that mentions all free variables of its argument, using a special token of type stWorld# :: a -> RealWorld#. So runSTRep (f x (z x)) would get unfolded to case f x (z x) (stWorld# (f,x,z)) of (# _, r #) -> r The variables mentioned in stWorld#’s argument prevent this from being floated out, and I believe it ouldn’t that solve tibbe’s problem, right? It might also enable more CPR-related optimizations. When generating STG, the argument of stWorld# would of course be ignored. (In fact, it seems it would be correct ot have runSTRep e = case e (stWorld# e) of (# _, #r) -> r, which could be formulated as a plain RULE, but that would blow up the core expressions during compilation too much, I’d expect.) comment:12 Changed 5 years ago by Using {-# INLINE runSTRep #-} runSTRep :: (forall s. STRep s a) -> a runSTRep st_rep = case st_rep (stWorld# st_rep) of (# _, r #) -> r {-# NOINLINE stWorld# #-} stWorld# :: a -> State# RealWorld stWorld# _ = realWorld# it validates. But do we actually have a test for this? Here would be one: import Control.Monad.ST import Data.STRef main = let f n = runST $ do ref <- newSTRef 0 modifySTRef ref (+n) readSTRef ref in print (f 1 + f 2) returns 3 in master, returns 4 if I inline runSTRep, and returns 3 with the stWorld#-trick. So unless someone says that this is not worth it (which would be strange, given that this bug is about an unexpected real-world performance issue), I suggest to give runSTRep a custom unfolding in MkId that replaces runSTRep e by case e (stWorld# $(all free local variables of e)) of (# _, r #) -> r. comment:14 Changed 5 years ago by Turns out I spoke too soon (and that the test suite really does not cover this): This code main = let f () = runST $ do ref <- newSTRef 0 modifySTRef ref (+1) readSTRef ref in print (f () + f ()) will be broken by my approach (output 3 instead of 2), as there are no free variables that differing – obvious, now that I see it. Too bad, was hoping to produce something usable today... at least I’ll add a possibly useful testcase. comment:15 follow-up: 16 Changed 5 years ago by I think the Right Thing here is to add a case to CorePrep that (in effect) inlines runSTRep on the spot. At that point there are no further transformations to worry about.). comment:16 Changed 5 years ago by). Not exactly: (1) evaluates r, but (2) doesn't. comment:17 Changed 5 years ago by comment:18 Changed 5 years ago by comment:19 Changed 5 years ago by Moving to 7.10.1. comment:20 Changed 4 years ago by comment:21 Changed 4 years ago by Moving to 7.12.1 milestone; if you feel this is an error and should be addressed sooner, please move it back to the 7.10.1 milestone. comment:22 Changed 3 years ago by comment:23 Changed 3 years ago by comment:24 Changed 3 years ago by Milestone renamed comment:25 Changed 3 years ago by The new runRW# primop is just what the doctor ordered. See 351de169e14ad9277aaca653df4a3753c151f7bb I chatted with tibbe a little on IRC about this, and one conclusion is that we should probably try harder to inline runSTRep. It has to be inlined very late in order to avoid bad things happening; indeed we used to try to do that, but it didn't work (see the comment on runSTRep). If we did this, then the allocation of the function closure for passing to runSTcould disappear, which might be critical in an inner loop.
https://ghc.haskell.org/trac/ghc/ticket/5916
CC-MAIN-2019-04
refinedweb
1,621
66.78
This post is about how Java 10 introduced a new release pattern on time-based. This includes releases based on new features, updated release, longterm support of java and JDK present and future releases.JDK enhancement proposal number is JEP 322- time-based release new version schema. This allows end users to take a decision based on the release whether to upgrade to latest release or not. There are different major or minor versions on every year based on the features, bug fixes, and critical fixes. This release will be happened for every 6 months - March and September. This includes major changes of Java SDK and JDK for the following changes. This release includes fixes for bug and regression testing issues and minor issues. This will be released for every quarter - Jan, Apr, Jul, Oct. The Existing release version information B:\>java -version java version "10.0.2" 2018-07-17 Java(TM) SE Runtime Environment 18.3 (build 10.0.2+13) Java HotSpot(TM) 64-Bit Server VM 18.3 (build 10.0.2+13, mixed mode) This will be changed to new version format as below $FEATURE.$INTERIM.$UPDATE.$PATCH There are four parts of a new version format $FEATURE - This will be a version number of a feature, starting number is 10. This will be incremented for every six $INTERIM - This is a number representing interim release. This includes bug fixes, no major API changes. The counter number starts from zero for every six months. $UPDATE - update release versioning number. This occurs for every quarter. If it is July 2018 release - It will be 10.0.2 If it is Oct 2018 release - It will be 10.0.3 If it is Dec 2018 release - It will be 10.0.4 $PATCH- Patch release or emergency release for priority one or critical issues $EMERG - Emergency release With Java 10 release, We can get version information with below classes. using Runtime. Version java class, we can get new version information java.lang.Runtime.Version public class VersionDemo { public static void main(String[] args) { Runtime.Version version = Runtime.version(); int feature = version.feature(); int interim = version.interim(); int update = version.update(); int patch = version.patch(); System.out.println(" feature:" + feature); System.out.println(" interim: " + interim); System.out.println(" update: " + update); System.out.println(" patch: " + patch); } } output is feature:10 interim: 0 update: 2 patch: 0 java.version.date This is the the release date of the release java.vendor.version Version information of an implemented vendor Customers have long-term support from Oracle for any major feature. From Sep 2018, Every major or feature release has an update for a release for at least three years. Please share/like/comment it in facebook/twitter. Recent posts Related posts
https://www.cloudhadoop.com/2018/08/learn-java10-features-time-based
CC-MAIN-2020-24
refinedweb
460
61.43
This tutorial describes how to troubleshoot latency problems of apps that use Spanner by using OpenCensus and Cloud Trace. This tutorial demonstrates how to identify common problems related to complex transactions, large payloads, and full table scans. The example app generates random load and intentionally exposes issues to demonstrate troubleshooting techniques. This tutorial assumes that you are familiar with Go development, Cloud Spanner API, and OpenCensus tracing APIs. The following diagram shows a schematic configuration of the test app used in this tutorial. The app is instrumented with the OpenCensus library. The trace and metrics data generated is stored and visualized in Cloud Logging. Objectives - Add OpenCensus trace and metrics instrumentation to an app that uses Spanner. - Interpret trace data to identify sources of latency. - Add trace-log correlation to enable a deeper understanding of app behavior. In the Cloud Console, go to the project selector page. Go to the project selector page Select or create a Cloud project. Make sure that billing is enabled for your Google Cloud project. Learn how to confirm. - Enable the Cloud Trace, Cloud Logging, Compute Engine, and Cloud Spanner APIs: gcloud services enable stackdriver.googleapis.com \ cloudtrace.googleapis.com \ spanner.googleapis.com \ logging.googleapis.com \ compute.googleapis.com Setting up your environment In Cloud Shell, clone the GitHub project. git clone Import the environment variables contained in the setup.envfile into your Cloud Shell environment: cd opencensus-spanner-demo source ./setup.env Setting up Spanner In the following steps, you set up Spanner and create some tables for the test app with the same schema as Getting started with Spanner in Go. There are two tables: Singers and Albums. Albums has a reference to Singers in the SingerId field. In Cloud Shell, create a Spanner instance: gcloud spanner instances create $SPANNER_INSTANCE \ --config=regional-us-central1 \ --description="Test Instance" \ --nodes=1 Create a database: gcloud spanner databases create $DATABASE --instance=$SPANNER_INSTANCE The tables in the test app represent singers and albums. In the Cloud Console, go to Spanner. To create the Singerstable, click Create table. Click Edit as text, and then enter the following in the DDL statements field: CREATE TABLE Singers ( SingerId INT64 NOT NULL, FirstName STRING(1024), LastName STRING(1024), BirthDate DATE, LastUpdated TIMESTAMP, ) PRIMARY KEY(SingerId); Click Create. To create the Albumstable, click Create table. Click Edit as text, and then enter the following in the DDL statements field: CREATE TABLE Albums ( SingerId INT64 NOT NULL, AlbumId INT64 NOT NULL, AlbumTitle STRING(MAX), MarketingBudget INT64, ) PRIMARY KEY(SingerId, AlbumId), INTERLEAVE IN PARENT Singers ON DELETE CASCADE; Click Create. To add an index for LastName, complete the following steps: - Click the Singerstable. - Click Create index. Click Edit as text, and enter the following information in the DDL statements field: CREATE INDEX SingersByFLastName ON Singers(LastName) Click Create. Install the app on a Compute Engine instance In Cloud Shell, create a Compute Engine instance to run the test app from: gcloud compute instances create $CLIENT_INSTANCE \ --zone=$ZONE \ --scopes= \ --boot-disk-size=200GB Find the email address of the service account associated with the instance: gcloud compute instances describe $CLIENT_INSTANCE --zone=$ZONE \ --format="value(serviceAccounts.email)" Make a note of the service account email address for the next step. Grant the role of roles/spanner.databaseUserto the instance service account: SA_ACCOUNT=service-account-id gcloud projects add-iam-policy-binding $GOOGLE_CLOUD_PROJECT \ --member serviceAccount:$SA_ACCOUNT \ --role roles/spanner.databaseUser Replace the following: service-account-id: your service account email address that you retrieved in the preceding step. Connect to the instance with SSH: gcloud compute ssh --zone $ZONE $CLIENT_INSTANCE Install Git on the instance: sudo apt-get update sudo apt-get install -y git Install Go version 1.12. Get the source code for this tutorial: git clone cd opencensus-spanner-demo Run the app In Cloud Shell, set your Google Cloud project ID: export GOOGLE_CLOUD_PROJECT=your project-id Replace the following: your project-id: your Google Cloud project ID. Initialize the environment: source ./setup.env Build the code: go build Run the test app: nohup ./oc-spannerlab --project=$GOOGLE_CLOUD_PROJECT \ --instance=$SPANNER_INSTANCE \ --database=$DATABASE \ --command=simulation \ --iterations=10000 & This command runs 10,000 iterations of the test app in simulation mode, which executes a random combination of queries and updates to generate metrics and trace data. This command takes about ten minutes to run. You can track progress: tail -f nohup.out In the Cloud Console, go to the Logs Viewer page. Go to the Logs Viewer page Check for errors in the logs. In the Cloud Console, go to the Trace list page. Review the trace data. The test app code structure The following sections show how to use Cloud Trace to solve problems that the test app is intentionally designed to show. The approach of using the OpenCensus Spanner integration, as described in this tutorial, requires a relatively small amount of code to enable tracing of app code that uses Spanner. OpenCensus has a built-in integration with gRPC, which enables Spanner client API instrumentation. However, some issues might require app instrumentation beyond gRPC. For more information, see the OpenCensus Quickstarts and other resources in the what's next section of this tutorial. Google Cloud collects and displays monitoring data for most services, including storage services. However, it's important to instrument your code to provide app performance data that reflects your users' experience. The OpenCensus Google Cloud integration guide describes how to instrument app code. In some cases, you can export the stats, and the trace data is already instrumented in the client libraries. Currently, only Java and Go Spanner clients are instrumented with OpenCensus tracing. To send app logs to Logging, this tutorial uses Cloud Client Libraries for Go. The applog package is included to correlate traces with logs. Trace-log correlation is discussed in the following section. The OpenCensus Logging exporter, the OpenCensus gRPC plug-in, and the stats and trace packages are imported in the following Go code snippet: import ( "bytes" "context" "flag" "fmt" "os" "cloud.google.com/go/spanner" "contrib.go.opencensus.io/exporter/stackdriver" "go.opencensus.io/plugin/ocgrpc" "go.opencensus.io/stats/view" "go.opencensus.io/trace" log "github.com/GoogleCloudPlatform/opencensus-spanner-demo/applog" "github.com/GoogleCloudPlatform/opencensus-spanner-demo/query" "github.com/GoogleCloudPlatform/opencensus-spanner-demo/testdata" "github.com/GoogleCloudPlatform/opencensus-spanner-demo/update" ) The app must call the Logging exporter. The app initializes the exporter: func initOC(project string) *stackdriver.Exporter { se, err := stackdriver.NewExporter(stackdriver.Options{ ProjectID: project, MetricPrefix: "spanner-oc-test", }) if err != nil { ctx := context.Background() log.Fatalf(ctx, "Failed to create exporter: %v", err) } trace.RegisterExporter(se) view.RegisterExporter(se) if err := view.Register(ocgrpc.DefaultClientViews...); err != nil { ctx := context.Background() log.Fatalf(ctx, "Failed to register gRPC default client views: %v", err) } trace.ApplyConfig(trace.Config{DefaultSampler: trace.AlwaysSample()}) return se } The preceding code initializes the Logging exporter, the gRPC view, and sets tracing to AlwaysSample. In OpenCensus, a trace is a tree of spans. Top-level spans are created for each of the transactions, as illustrated in the following Go code: ctx, span := trace.StartSpan(ctx, "query-albums") defer span.End() For more information, see tracing. The preceding StartSpan() call is an example of a custom span that is added to the app. The Spanner client library also creates spans by using the gRPC integration with OpenCensus. The queryAlbums() function in query.go contains an example of these custom spans. The following code snippet from queryAlbums() calls the Spanner ReadOnlyTransaction() method, which creates a span. The span closes when the ReadOnlyTransaction object ro goes out of scope. ro := client.ReadOnlyTransaction() defer ro.Close() Interpreting the data The following sections explain the reasons for differences in latency measures and how those sources appear in the trace data. In these steps, you compare data for different traces. The details that you see in your own traces might be different, but the same basic principles apply. Check transaction latency The sequence the app follows to add a singer and album: - The AddAllTxn()function opens a read-write transaction to contain the database reads and writes. - The getSingerId()command checks if the singer is in the database based on the singer's first and last name. If the singer is in the database, this command retrieves the singer's ID for later use. If the singer isn't in the database, then this command adds the new singer. - The getAlbumId()command uses the singer ID and album title to check whether the album is in the database. If the album is in the database, the app takes no further action. - If the singer ID and album aren't in the database, the app adds the new album. The preceding oc-spannerlab command for the test app runs 10,000 generated iterations, randomly selecting between these different functions to simulate a real app. To review the trace data, complete the following steps: In the Cloud Console, go to the Trace list page. To explore the scatter plot, click four trace points. You can identify the different code paths in the test app with the span names. Compare the latency values for the different spans. The root span at the top of the trace detail shows that the complete time for the add-singertrace, including child spans, takes 101.925 ms. The start of the read-write transaction is at the beginning of the request. The following screenshot shows multiple transactions in a single span. For more information on transactions, see Transactions. The read-write transaction is now mid-way through the sequence. The complete task for add-singernow takes only 42.747 ms. Check the effect of a large payload Payload size is closely related to latency because a larger amount of data needs to be transmitted over the network and processed by the app. The example app loads enough data into Spanner to demonstrate the effects of response payload size. For more information on other factors affecting latency, see Latency metrics. The following query in the app code returns all rows in the table: SELECT SingerId, AlbumId, AlbumTitle FROM Albums To check the effect of payload size on latency, complete the following steps: In the Cloud Console, go to the Trace list page. In the Request filter field, enter query albums, and then press Enter. Click one of the points in the scatter plot. Click Show events. You can identify the query by the trace name. The number of bytes received (109,560) is also shown in the trace detail. Use a secondary index instead of full table scans If you query a field other than the primary key, it can be expensive for large tables without secondary indexes. These queries have high latency due to the need to read the full table to find qualifying rows. Creating a secondary index avoids scanning the table and can reduce the latency by directly looking up qualifying rows using indexed columns. In the example app, a secondary index is created on the Singers table for the field LastName with the following statement in the preceding instructions: CREATE INDEX SingersByLastName ON Singers(LastName) Use of secondary indexes like the preceding index is a best practice to speed up common queries. The secondary index is helpful for queries such as the following: SELECT SingerId, FirstName, LastName FROM Singers WHERE LastName = 'Zero' In many cases, Spanner automatically uses any secondary indexes that are likely to make the query more efficient. In other cases, Spanner doesn't automatically use an index or might choose an index that causes query latency to increase. In a few cases, though, Spanner might choose an index that causes query latency to increase. If you've followed the troubleshooting steps for performance regressions and confirmed that you want to try a different index for the query, you can specify the index as part of your query with the FORCE_INDEX directive as follows: SELECT SingerId, FirstName, LastName FROM Singers@{FORCE_INDEX=SingersByLastName} WHERE LastName = 'Zero' To check the query execution time, complete the following steps: In the Cloud Console, go to Spanner. Click the name of your instance. In this tutorial, it's Test Instance. Click the name of your database. In this tutorial, it's test. Click the Query stats tab. Select a 1-hour time interval that includes the test run. Select the preceding query to view the Query stats. View the stats in the Details pane, including average latency (sec) and average rows scanned. This query does a back-join to the base table to find the SingerIdand FirstNamecolumns. You can improve the query further by following the suggestions in Spanner SQL best practices. Correlating traces with logs To see whether the best practices in query optimization impact your app, you might need detailed information on code paths and the actual Spanner queries executed. The queries aren't available in the Spanner log, but are added to the app logs in the test app. You can add this information to the trace annotations; however, logging is typically a first choice for debugging. By using trace-log correlation, you can view log messages directly in the trace detail. If the trace ID is added to the Entry struct in the Cloud Client Libraries for Go, you can correlate trace and log data. The test app demonstrates this correlation. The following example code for trace-log correlation is located in the applog package: func printf(ctx context.Context, severity logging.Severity, format string, v ...interface{}) { span := trace.FromContext(ctx) if client == nil { log.Printf(format, v...) } else if span == nil { lg := client.Logger(LOGNAME) lg.Log(logging.Entry{ Severity: severity, Payload: fmt.Sprintf(format, v...), }) } else { sCtx := span.SpanContext() tr := sCtx.TraceID.String() lg := client.Logger(LOGNAME) trace := fmt.Sprintf("projects/%s/traces/%s", projectId, tr) lg.Log(logging.Entry{ Severity: severity, Payload: fmt.Sprintf(format, v...), Trace: trace, SpanID: sCtx.SpanID.String(), }) } } View log messages in traces In the Cloud Console, go to the Trace list page. Click one of the points. In the Timeline chart, click Show logs. To see the related log entry in the logs viewer, click Open in logs viewer . The log detail also has a link to the related entries in the Logs Viewer. Click Open in Logs Viewer to see the log detail. Copy the following query from the log to use in a later step. Use queries extracted from logs The filter constructed is useful because it can link all the log entries in a single request, which is hard to do without a trace ID. The query executed and the number of results returned are in the log detail because they were added to a log statement in the app's code. You can take the query from there and execute it in Spanner to find the query execution plan. In the Cloud Console, go to the Trace list page. In the Request field, enter query-limit. To see the log detail, follow the steps in the section View log messages in traces. Click Test instanceand then click the testdatabase. Click Query. In the Query database: test field, enter the query that you copied from the log. Click Run query. The query execution plan includes a table scan. This query is fine for small tables, but is a problem with large tables. If only a few rows are required, a full table scan is an expensive way to obtain results and can lead to high latency. The Rows scanned field is important to check. This trace shows only 10 rows scanned. For more information on query optimization, see SQL best practices, Query execution plans, and Query execution operators. Viewing metrics Metrics are collected and stored in aggregate rather than individual measurements. Aggregations are more useful to observe trends, whereas traces are better for debugging specific requests. Spanner provides a set of metrics, including CPU utilization metrics and latency metrics. You can combine Spanner metrics with metrics collected by OpenCensus, which provide a client view, to diagnose problems. To compare client and service latency metrics, follow these steps. - In the Google Cloud Console, go to Monitoring or use the following button: Go to Monitoring - If Metrics Explorer is shown in the navigation pane, click Metrics Explorer. Otherwise, select appsResources and then select Metrics Explorer. - Ensure Metric is the selected tab. - Click in the box labeled Find resource type and metric, and then select from the menu or enter the name for the resource and metric. Use the following information to complete the fields for this text box: - For Resource, enter opencensus. - For Metric, enter roundtrip_latency. - For Filter, click grpc_client_methodequals ExecuteSQL, and then click Apply. - For Aggregator, select 50th percentile. - Click Add Metric. - Repeat the preceding steps to add the same Resource, Metric, and Filter. For Aggregator, select 95th percentile. - Click Save chart. - In the Chart title field, enter Spanner E-E Latency. - Click New dashboard and enter Spanner Metrics. - Click Save. - To view the dashboard you created, go to Dashboards > Spanner Metrics. Click Show all legends. The chart filters for the ExecuteSqlmethod. Compare app and Spanner view of metrics Now that you've created a chart from the app's perspective, you create another chart from Spanner's perspective to compare the latency. - In the Cloud Console, click Add Chart. - In the Find resource type and metric text box, type spanner. - Click the metric spanner.googleapis/api/request_latency. - In the Filter field, click methodequals ExecuteSQL, and then click Apply. - In the Aggregator drop-down list, click 50th percentile. - Click Add Metric - Repeat the preceding steps to add the same Resource, Metric, and Filter. For Aggregator, select 95th percentile. - Click Add Metric. - In the Chart title field, enter Spanner latency (backend). Click Save Chart. Click the line in the chart at any point. For the purposes of this tutorial, 9:27 is the point clicked in the preceding chart to check the median values. At that time, the value for the client is 8.9 ms, compared to the median value reported by Spanner of 6.1 ms. This difference is 2.8 ms, which is consumed in network transmission and gRPC client processing. If the difference was large, you can start by checking the relative distance between the app client and the Spanner service regions, and the size of the payloads. The latter can be judged from the metrics for bytes received and bytes sent to Spanner. However, if the latency reported by Spanner is high, check the rows scanned and query plan and also the metrics for Spanner node CPU utilization. individual resources If you prefer not to delete the entire project, you can delete individual resources. However, you cannot delete the monitoring and trace data without deleting the project. In Cloud Shell delete the Spanner instance: gcloud spanner instances delete $SPANNER_INSTANCE Delete the Compute Engine instance: gcloud compute instances delete $CLIENT_INSTANCE --zone=$ZONE What's next - Read more about Spanner best practices. - Review the Spanner API documentation. - See the OpenCensus Go API documentation and gRPC integration guide. - Check out these Google research publications to learn about the theoretical foundations of Spanner: Spanner: Google's Globally-Distributed Database and Spanner, TrueTime and the CAP Theorem. - Learn how to capture Cloud Bigtable tracing and metrics using Logging and OpenCensus - See the related tutorial Monitoring slow queries in MySQL - Try out other Google Cloud features for yourself. Have a look at our tutorials.
https://cloud.google.com/solutions/troubleshooting-app-latency-with-cloud-spanner-and-opencensus?hl=bn
CC-MAIN-2020-29
refinedweb
3,226
57.77
Although this chapter will discuss attaching code to Outlook forms, rather than creating and modifying Outlook forms themselves, we’ll begin by looking at how the Outlook object model views the Outlook user interface and by briefly examining how you access and work with Outlook forms in design mode; both topics provides provide background that is necessary in order to begin coding. Then we’ll look at Outlook’s rather primitive VBScript environment. Figure 6.1 shows a more-or-less standard Outlook window with Outlook displaying a mail folder. The Outlook window is divided into three parts, which correspond to four elements of the Outlook object model. Figure 6-1. The Microsoft Outlook interface On the left of the Outlook window is the Folder List. In the Outlook object model, this corresponds to the NameSpace object, which has a Folder collection in which each Folder object represents a folder in the MAPI store. On the upper right of the Outlook window is the Explorer pane. (The term “Explorer” here is unrelated to Windows Explorer, the utility for displaying the Windows namespace and filesystem.) The Explorer pane is responsible for listing the items in the current folder. Each type of item has its own Explorer object, which is a member of the Explorers collection. On the lower-right ... No credit card required
https://www.safaribooksonline.com/library/view/vbscript-in-a/1565927206/ch06s02.html
CC-MAIN-2018-34
refinedweb
222
53.41
Hi, Here are some ideas for extended attribute tracking, I'm just throwing them in for comments before attempting to implement. First off -- does anyone think this is desirable at all? Or just a stupid idea I'm having here? Anyway, here I go: extended attributes have their own namespace, somewhat like dirs: user.mime_type system.posix_acl_access ... There can be arbitrary data attached to each item, and each item should be handled separately. The question is what should happen to the content of the extended attribute. Maybe it would suffice to just copy it over, but it would probably be possible to diff it as well. In the case of ACLs, that wouldn't help much, because they're just a single line (for all I've seen). It would be possible to pick ACLs apart, but I'm not sure how feasible this is. I don't think they should be. The storage in changesets needs to take into account the name of an attribute and also the fact that it can contain binary data. Here's a proposal: Pretend that each attribute that is present is just another file that can be diffed. These will always have the tagging method "names". They are diffed just like normal files (need to save temp files for this). I'm not sure how to store these things into the changeset while keeping it simple yet avoid possible clashes with names. Maybe a new "xattr" directory should be added to the changeset, which only keeps information about attributes. All files within that tree are either .patch files or .{original,modified} pairs depending on whether the attribute value was binary or text. If an attribute belongs to a file, then a directory is created whereever the file belongs that has the name of the file, and files below it belong to its attributes. For directories, it is possible to have both files and dirs below it (the dirs belong to other dirs/files below them). The names of the .{patch,original,modified} files will need to be encoded to avoid problems with slashes or binary names. This should be something that is invariant if you don't use binary or slashes in the name, maybe something like URL encoding. Conflict resolution will likely consist in saving old and new value or patch and letting the user decide on an attribute basis. Oh, and for those file systems that don't have EA just don't do anything, don't create patches because they're gone all of a sudden etc.
http://lists.gnu.org/archive/html/gnu-arch-users/2003-12/msg00979.html
CC-MAIN-2016-22
refinedweb
427
72.46
Hi there, I recently update to Unity 5 and now working on a project on mobile platform. I tried to play around with the new CrossPlatformInput in Unity 5 and implement the "MobileSingleStickControl" prefab that built in under 2D asset. But I unable to get the control to work, the controller UI did shown in the screen but user cannot interact with the controller. I can't find any related example on using the control, mostly what I found are joystick control in Unity 4. Please provide me some example or suggestion on the controller. Thanks All works now BUT i cant move and the same time jump! Help please! Answer by Thiago Baptista · Apr 07, 2015 at 12:10 PM You've got to have an EventSystem game object in your scene in order to make the virtual joystick work. Just create one in the hierarchy and you`re set. sorry if this is the wrong spot to post this question. I have got the Joystick to work by adding the Event System. Now my Problem is that every time I touch the sprite it moves all the way to screen location (0,0)? it works but is stuck in the corner. Answer by ShawnFeatherly · Apr 15, 2015 at 08:08 PM The most common issue is the joystick popping into a corner, this is fixed by changing Joystick.cs's OnEnable() to Start(). A demonstration of this fix is covered at 5:30 in this video. For other issues, watch this video from the start. Thanks for all the help, awesome I really appreciate the response. Answer by Textfield272 · Apr 01, 2015 at 08:49 AM I haven't played around with any of the input prefabs and scripts in the standard assets, but I implemented a single-stick control pretty easily with a basic script. The property Input.touches is a Touch[] that holds all touch input that frame. The state of each Touch can tell you whether it just began or was there the previous frame, and each touch also has a finger id associated with it that allows you to track the movement of individual fingers. And of course you can get the position on the screen. Input.touches Touch[] Touch A bit of basic logic will allow you to determine if there is a new touch inside the bounds of the control stick, and by subtracting the center of the control stick from the position of the touch, you can get an Vector2 representing the offset. Of course that offset will be in pixels, so you'll probably want to divide that by the radius of the stick in pixels; otherwise the magnitude the control stick gives will vary depending on the DPI of the device. Vector2 Hope that helps. Answer by ulissescad · Jan 07, 2016 at 07:00 PM Looking at the examples of vehicles made this script and fucionou well for what was proposed . First import the library of standard assets and then simply recall the position as was done in script below. MOVX is a variable for managing the movement by the inspector . using UnityEngine ; using UnityStandardAssets.CrossPlatformInput ; using System.Collections; public class Mov : { MonoBehaviour public float MOVX ; // Use this for initialization void Start ( ) { // Joystick. } // Update is called once per frame void Update () { Debug.log ( Input.GetAxisRaw ( " Horizontal ")); this.transform.Translate ( CrossPlatformInputManager.GetAxis ( " Horizontal " ) * * MOVX Time.deltaTime , 0 , 0); } } Answer by danifou · Nov 10, 2016 at 11:48 AM i have a simlar problem but its a bit diferent i can t cheak the box at the left corner at the top i got that asset from standar. Mobile joystick not moving player 0 Answers Does AssetBundle work on mobile? 0 Answers Profiler Alpha Mobile 0 Answers Suppress Autocorrect in GUI.TextField 1 Answer Unity iOS and Android content download from url 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/936658/unity-5-mobile-single-stick-control.html
CC-MAIN-2022-21
refinedweb
646
63.39
Provided by: manpages-dev_4.13-3_all NAME seccomp - operate on Secure Computing state of the process SYNOPSIS #include <linux/seccomp.h> #include <linux/filter.h> #include <linux/audit.h> #include <linux/signal.h> #include <sys/ptrace.h> int seccomp(unsigned int operation, unsigned int flags, void *args); DESCRIPTION The caller will fail and return-zero. Filters When, it is usually necessary to. blacklist blacklist, task exiting immediately without executing the system call. The task terminates as though killed by a SIGSYS signal (not SIGKILL). Even if a signal handler has been registered and otherwise catches SIGSYS, the handler will be ignored in this case and the task always terminates. Before Linux 4.11, any process terminated this way would not trigger a coredump (even though SIGSYS is documented in signal(7) as having a default action of termination with a core dump). Since Linux 4.11, single threaded processes follow standard core dump behavior, but multithreaded processes still do not. There is no workaround currently for multithreaded processes. SECCOMP_RET_TRAP This value results in the kernel sending a SIGSYS signal to the triggering process without executing the system call.., it_ALLOW This value results in the system call being executed. RETURN VALUE se prctl(2) PTRACE_SECCOMP_GET_FILTER operation can be used to dump a process's seccomp filters. Seccomp-specific BPF details Note. EXAMPLE blacklist use cases. Use ⟨⟩ COLOPHON This page is part of release 4.13 of the Linux man-pages project. A description of the project, information about reporting bugs, and the latest version of this page, can be found at.
http://manpages.ubuntu.com/manpages/artful/man2/seccomp.2.html
CC-MAIN-2020-34
refinedweb
260
52.97
In part 1 of our journey into react we got our windows work environment set up; we installed ConEmu to set up a pretty windows console, the text editor Atom.io to improve our coding experience, and then from within that console we installed Node.js and git. After that we learned how to navigate using the command line, and we created our project directory, and initialized our project with the npm init command. Lastly, we got a feel for how installing dependencies works by installing React itself. In this part of the tutorial we’ll get a working development server set up, and our first react app to display in the web browser. To do this we are going to install several new dependencies, set up our webpack.config file, and of course get our first taste of programming in React. So let’s dive right in! If you’d like to review only the code for this tutorial, you can find it on it’s own branch on my GitHub. Let’s start with something familiar Before delving into the nitty gritty of our first react app, let’s work first with some basic HTML to get us warmed up. We’re going to make the index.html file that our app will be mounted into. In your console, navigate to the root folder of your project and create the index.html file. It’s important that you keep the extensions in mind when making these files as there will be multiple different index files down the road. $ echo.>index.html Setting up the index.html is pretty straight forward and follows the conventions of the language that you’re already familiar with. So make you html, head, and body. Inside the body, you’re going to create an empty div with a unique id: <!DOCTYPE html> <html> <head> <title>Journey into React</title> </head> <body> <div id="app"></div> </body> </html> This div is going to be where we’ll mount our application, which we’ll get to a little bit further on. For now, save this file and let’s get to making our first component. Creating our first component React is made up of blocks of code called components. This is one of the many things that makes React such a powerful language for application development. We are able to create different parts of the program independently of each other, then call them only when we need them. This is also great for organization, working in a team, scalability, and debugging. The first component that we are going to make is going to be the primary one, the one that all other components are mounted into. Our app.js component should be placed in its own directory, which we’ll do right now. By convention, you’ll want to start with a src directory, and inside that your components directory, where you’ll make your app.js file – like so: $ mkdir src $ cd src $ mkdir components $ cd components $ echo.> app.js Now that we have our file made, let’s import React so that we can start working with it. At the top of your app.js file add: import React, { Component } from "react"; Not only can we import just the resources we need, but we can also pick and choose which functions from that resource to bring into our file. That’s what we did just now – we imported the Component function from the react dependency that we installed earlier. This will save us some valuable space in the next part of our code, where we will actually create our component, and share it with the rest of program: export default class App extends Component { render() { return ( <div> Hello World </div> ); } } There’s a lot going on here, so let’s break it down. First, we are creating a Component with the function we imported from React, and we’re exporting it as a default class with the name App. Now anything inside this object will be be called when we import it into our other components. So what did we create here? Inside our render() function we are going to return a div with the contents “Hello World”. Easy as that! It might feel weird at first writing our HTML inside JavaScript, but you’ll get used to it pretty quickly. It’s incredibly powerful to be able to mix our JS and our HTML, as we’ll be able to call variables, and perform logic on what our clients are seeing on their screen. We are able to do this because of something called webpack, and some particular settings we’ll implement below. But first, let’s take it one step at a time and now call this component to the screen so we can see it. Rendering our components with ReactDOM The next step in our first react is to call in the dom dependency. In your console, install ReactDom and save it, like so: $ npm install react-dom --save After a few moments, you’ll have the react-dom module installed and saved to your package.json file so that others can use your application without you transferring your node_modules file. By simply typing npm install from the root of your application, npmwill install all the dependencies in your package.json file. Alright, so next let’s create a new file in our src directory named index.js. $ echo.> index.js Then let’s make the imports that we’ll need so that everything works: import React from 'react'; import ReactDom from 'react-dom'; Also, we’ll want to import the component we just built, so import that as well. Notice that with the component we built, we want to include the relative file path to it: import App from './components/app'; Let’s tell our application to render our component into the #app element we made on our index.html file. ReactDom.render( <App />, document.querySelector('#app')); This little bit of code here is telling your clients screen to render the App component (noted by the tags we put on either side of it) inside a document element with the id of app. Now we’re almost there. We’ve created our webpage itself, our app component which we then imported it into our index.js file. We’ve told index.js to render our app in the webpage. Next we’ll set up our server so that we can view our application. Creating a local development server with Webpack We’ve got some more dependencies to install for our first react app: $ npm install webpack webpack-dev-server --save-dev You’ll notice I did something a little different here. We’ve told npm to install two different packages, and save them to a special list of dependencies in our package.json file that we’ll need only for development. Webpack is one of the most complicated, yet most important part of our application. It’s a module bundler, which means it takes all of the dependencies we’re using, all of our static assets, and bundles them together into one minified file that we then serve our client. It reduces transfer sizes, and has some pretty incredible features that are invaluable, such as “loaders”. Remember when we were writing HTML inside our JavaScript? It’s through the use of loaders inside webpack that we are able to do this. A loader is an extension of webpack that preprocesses our code and converts it into JavaScript. We are going to use a large number of loaders called babel in our application to set up our next file: webpack.config.js. Navigate to your root directory and create it: $ echo.>webpack.config.js Now before we go any further let’s get babel and all it’s additions installed. This might take a few minutes, but sit tight, we only have this one more file to write before we get to see all of our hard work in action! I would recommend copying the below code into your package.json file to save yourself some time. It should go right above your webpack devDependencies, like so: "devDependencies": { "babel-core": "^6.7.6", "babel-loader": "^6.2.4", "babel-plugin-add-module-exports": "^0.1.2", "babel-plugin-react-html-attrs": "^2.0.0", "babel-plugin-transform-class-properties": "^6.3.13", "babel-plugin-transform-decorators-legacy": "^1.3.4", "babel-preset-es2015": "^6.3.13", "babel-preset-react": "^6.3.13", "babel-preset-stage-0": "^6.3.13", "webpack": "^1.13.0", "webpack-dev-server": "^1.14.1" } Now that we have all of those in there, we can save it and run npm install to install them all for us. We are preemptively installing a few of these for future use. They all convert the array of programming languages in our application into JavaScript so that it works properly. After those are all installed, open your webpack.config.js file and define the webpack variable like so: var webpack = require('webpack'); Now let’s configure our webpack file. It’s going to look a bit complicated, but stick with it, and we’ll talk about it more below: module.exports = { context: __dirname, entry: "./src/index.js", module: { loaders: [ { test: /\.js|.jsx?$/, exclude: /(node_modules|bower_components)/, loader: 'babel-loader', query: { presets: ['react', 'es2015', 'stage-0'], plugins: ['react-html-attrs', 'transform-class-properties', 'transform-decorators-legacy'] } } ] }, output: { path: __dirname, filename: "bundle.js" } }; Okay, so there’s a few things going on here. Let’s start at the entry: object, it’s here that we’re telling webpack which part of our first react app to bundle for us. It’s going to read this file, take all of it’s dependencies (and all of their dependencies), apply our loaders, then compress them, and output them as a single file. This file is defined as bundle.js in our output:object, and it’s output path: is our parent directory. Now for the loaders. Loaders can be complex, and have a great number of options, parameters, and plugins that we can use with them, so unfortunately that is something we’re going to want to get into in more depth later. So for our first react app let’s take a look at the one we have typed up here. Basically, what it’s saying is that we are going to look for ( or test:) any files that end in the js or jsx extension, with the exception of ( exclude:) anything in our node_modules folder, and then apply the babel-loader to them. The babel-loader itself then takes some presets and plugins that will make sure we catch all the HTML we’ve written and convert it into JavaScript. Whew! That was a lot, but as you continue to work with and see webpack configuration files, they will begin to make more sense. We only have one last thing to do before we see our first react app greet us on our web browser. If you want to read more about Webpack take a look at my other tutorials here. Add a dev script, and start our first react app Before going any further in our first react app we have to add one last thing to our index.html file. We told webpack that we wanted to output our application in a minified file called bundle.js, so we better get that pulled into our web page. In the body of our html (in our index.html file) add the following: <script type="text/javascript" src="bundle.js" charset="utf-8"></script> The great part about the webpack-dev-server is that it not only it creates a local server for us to view our project on, but it also allows it be edited in real time. We won’t have to stop the server and start it again to view what our changes have done, it will do all of that for us. Technically we could do this and run our application right this second by typing in this monster of a command into our console: $webpack-dev-server --inline --hot But, who wants to do that every time they want to start their server? Nobody does, so let’s make it much easier. Open your package.json and near the top you should see a "scripts" object with a "test" option within it. Erase it, and replace it with this: "dev": "webpack-dev-server --inline --hot" Now, every time we type npm run dev it’ll call that line of code, starting our server and getting us ready for development. We can also type in webpack to create our bundle.jsfile. We would do this if we were say, deploying our app. Finally, we’ve reach the moment of truth! Time to open your browser, navigate to localhost:8080 and start our server with npm run dev. Webpack, by default will always serve our application to port 8080. With any luck, and of course all of your hard work, you should see the simple tiny words “Hello World” displayed in your browser. You’ve done it! You’ve officially created your first React app. Granted it doesn’t do much and it took a long time to get those simple words up on a single web page, but it’s ready to be scaled up and built upon. You and I will begin doing that in the next tutorial where we’ll implement routing so we can change pages, our navigation bar, and add Sass styling! If you have any questions feel free to leave them below and until next time, happ coding! Now that your first react app is done, why not head over to Part 3 where we learn to navigate around with react-router?
https://www.davidmeents.com/blog/journey-into-react-part-2-creating-your-first-react-app/
CC-MAIN-2017-26
refinedweb
2,309
71.95
3 Lightweight React Alternatives: Preact, VirtualDom & Deku Free JavaScript Book! Write powerful, clean and maintainable JavaScript. RRP $11.95 This article was peer reviewed by Craig Bilner and Bruno Mota. Thanks to all of SitePoint’s peer reviewers for making SitePoint content the best it can be! React’s declarative components and virtual DOM rendering have taken the world of frontend development by storm, but it’s not the only library built on those ideas. Today we’ll explore what it’s like to build an application in three other React-like alternatives. We’re going to assume that you’re already familiar with React and the terminology that’s used in its ecosystem. If you need to get up to scratch or just refresh, then check out one of our earlier articles. Overview Let’s get started with a high level overview of the libraries we’ll be comparing. Deku (2.0.0-rc15) Deku aims to be a more functional alternative to React. It prevents components from having local state, which allows all components to be written as pure functions that communicate with an external state management solution like Redux. Preact (4.1.1) Preact is an attempt to emulate the core functionality of React using as little code as possible. Assuming that you will be using ES2015, Preact takes some shortcuts and trims down React’s original feature set to produce a tiny library which weighs in at only 3KB. Virtual-DOM (2.1.1) Where React, Deku and Preact give you a component abstraction above a virtual DOM, the virtual-dom package gives you the lower level tools you’ll need to create, compare and render trees of virtual DOM nodes yourself. (This isn’t the same thing as the virtual DOM that React and Preact are built on!) A low level library like Virtual-DOM might seem like an odd alternative to React, but if you’re interested in writing performant mobile web experiences, then watching Pocket-sized JS is a great place to start. In fact, this talk is the reason we’ve included Virtual-DOM as a comparison. We’ll use each of these libraries to build a component, structure our data flow and finally look at the size and performance of each application. Components Here’s a React component that will render some Markdown, using the marked library. import React from 'react'; import marked from 'marked'; const Markdown = React.createClass({ propTypes: { text: React.PropTypes.string }, getDefaultProps() { return { text: '' }; }, render() { return ( <div dangerouslySetInnerHTML={{ __html: marked(this.props.text) }}> </div> ); } }); We’re using prop validation to have the component warn us if it receives a prop of the wrong type. It also implements a getDefaultProps() method which allows us to provide default values for our component, in the event that none are passed in. Finally, we implement a render method, which returns the user interface for this component. To prevent React from escaping our Markdown when we render it, we need to pass it to the dangerouslySetInnerHTML property. Deku Next up, we’ll implement the same component with Deku. /** @jsx element */ import { element } from 'deku'; import marked from 'marked'; const Markdown = { render({ props: { text='' } }) { return <div innerHTML={marked(text)}></div>; } }; The first line is a compiler pragma which tells our compiler to transform JSX like <h1>Hello</h1> into element('h1', null, 'Hello') rather than React.createElement('h1', null, 'Hello'), which allows us to use JSX with Deku instead of React. This option can also be configured with a .babelrc file. Compared to React, our Deku component is definitely simpler. Deku components don’t have an instance you can reference with this, meaning that all the data the component might need will be passed into the method as an object called model. This object contains our component’s props and we can use destructuring syntax to extract the text prop. Deku doesn’t have prop validation, but we can at least simulate getDefaultProps() by providing default values in these destructuring assignments. Preact Next up is Preact. /** @jsx h */ import { h, Component } from 'preact'; import marked from 'marked'; class Markdown extends Component { render() { const { text='' } = this.props; return ( <div dangerouslySetInnerHTML={{ __html: marked(text) }}> </div> ); } } Again, we need to tell the compiler to turn JSX into something Preact understands. Preact components are very similar to React’s ES2015 class components and we were able to copy most of our rendering code from earlier. Like Deku, Preact does not support prop validation or default properties, but we can again simulate default props with destructuring assignments. Virtual-DOM Finally, we’ll take look at Virtual-DOM. /** @jsx h */ import { h } from 'virtual-dom-util'; import marked from 'marked'; function Markdown({ text='' }) { return <div innerHTML={marked(text)}></div>; } We aren’t provided with any tools for structuring our components, so you won’t see constructs like this, props or state here. In fact, these “components” are just functions which return trees of virtual DOM nodes. The native way to create virtual DOM nodes isn’t compatible with JSX, so we’re using the virtual-dom-util package to provide us with a JSX compatible alternative. We don’t actually need to import the virtual-dom package until we render our component. Rendering A Component Next we’ll look at how to render a component into the DOM. All of these libraries render into a target node, so we’ll create one in our HTML file. <div id="app"></div> React import { render } from 'react-dom' render( <Markdown text='Hello __world__' />, document.getElementById('app') ); To render a React component we need to use the react-dom package, which provides a render function that understands how to turn a tree of React components into a tree of DOM nodes. To use it, we pass an instance of a React component and a reference to a DOM node. ReactDOM handles the rest. Deku /** @jsx element */ import { createApp, element } from 'deku'; const render = createApp( document.getElementById('app') ); render( <Markdown text='Hello __world__' /> ); Deku has a slightly different way of rendering a component. Because Deku components aren’t stateful, they won’t re-render themselves automatically. Instead we use createApp() to build a render function around a DOM node, that we can call each time our external state changes. Now we can pass instances of Deku components to render them in that node. Preact /** @jsx h */ import { h, render } from 'preact'; render( <Markdown text='Hello __world__' />, document.getElementById('app') ); Preact provides us with a similar interface for rendering components into DOM nodes, however it’s found inside the core Preact package, unlike ReactDOM. Like so much of the Preact API, there’s nothing new to learn and the concepts from React are readily transferable. Virtual-DOM /** @jsx h */ import { create } from 'virtual-dom'; import { h } from 'virtual-dom-util'; const tree = <Markdown text='Hello __world__' />; const root = create(tree); document .getElementById('app') .appendChild(root); Virtual-DOM gives us much more flexibility around how we create and use our component. First we create an instance of a virtual tree, which we realize as a DOM node with the create function. Finally we’re free to add this child to the DOM in whatever way we want. Data Flow Across the three libraries we’re considering, there are two distinct approaches to managing our application state. Inside Like React, Preact also allows components to manage their own state. Each component keeps track of a reference to an immutable state object that can updated through a special component method called setState. When this function is called, the component will assume that something has been changed and attempt to re-render. Any components that receive props from the component whose state was updated will also be re-rendered. Preact also provides us with a mechanism for overriding the default behaviour with fine grained control, in the form of shouldComponentUpdate. Outside Deku makes the deliberate decision to move state management outside of components and Virtual-DOM is too low level to be concerned with abstractions like state. This means that if we want to build applications with it, then we need to keep the state elsewhere. When this is the case, our state moves out into an external container, which the root component uses to provide data for the rest of the application. We’ll need to re-render the whole application each time the state container updates. To update the state, the components must communicate changes with the state container. In Flux-like systems, this communication often comes in the form of actions. It’s important to remember that although React and Preact support component local state, they can also be used with an external state management solution too. Application Structure This section will look at how we implement these ideas about state, data flow and re-rendering as actual code. In the course of this we’re going to build out our Markdown component into a realtime Markdown editor. You can see a demo of the finished components in the next section. Deku A Deku application is usually made up of two main parts: a component tree and a store. We’ll use Redux as a store as it works well with Deku, out of the box. The components in the tree dispatch actions which our Redux reducers will use to change the state, and we’ll use the subscribe mechanism to re-render the component tree whenever the state changes. First we’ll set up a simple Redux store. import { createStore } from 'redux'; const initState = { text: '' }; const store = createStore((state=initState, action) => { switch(action.type) { case 'UPDATE_TEXT': return { text: action.payload }; default: return state; } }); Without going into too much detail, a Redux store is built up of a reducer function which takes the current state and an action as arguments. The function should return a new state, based on the data in the action. Now we’ll revisit the rendering code to let Deku know about our Redux store. const render = createApp( document.getElementById('app'), store.dispatch ); Because Deku is expecting you to use an external state management solution, its createApp function accepts a dispatch function as the second parameter. In turn, Deku will provide this dispatch function to all of its components, so that they can speak to the Redux store. We’ll also pass the current state of our store into the render function. Deku will provide this value to each component as context, allowing any component in our tree to read from the store. render( <MarkdownEditor />, store.getState() ); We can use the store.subscribe() method to listen for changes to state, so that we can re-render our component tree. store.subscribe(() => { render( <MarkdownEditor />, store.getState() ); }); To update the state, components should pass actions to their dispatch function. However, creating our actions inside our components can easily lead to bloated component code, so instead we’ll create middlemen functions that dispatch parameterized actions for us. These functions are often known as “action creators”. const actions = { updateText: dispatch => text => { dispatch({ type: 'UPDATE_TEXT', payload: text }); } }; The action creator takes a dispatch function and a parameter, then uses them to create and dispatch an appropriate action object. For the sake of convention, we’re designing our actions so that they comply with Flux Standard Actions. To tie this altogether, our component will read from the state in context and dispatch actions using the new action creator. const MarkdownEditor = { render({ context, dispatch }) { return ( <main> <section> <label>Markdown</label> <hr /> <Editor onEdit={actions.updateText(dispatch)} /> </section> <section> <label>Preview</label> <hr /> <Markdown text={context.text} /> </section> </main> ); } }; Preact Once a Preact component has been rendered, it will manage it’s own re-rendering by listening out changes to it’s internal state. import { Component } from 'preact'; import { bind } from 'decko'; class MarkdownEditor extends Component { constructor() { super() this.state = { text: '' }; } @bind onEdit(text) { this.setState({ text }); } render() { return ( <main> <section> <label>Markdown</label> <hr /> <Editor onEdit={this.onEdit} /> </section> <section> <label>Preview</label> <hr /> <Markdown text={this.state.text} /> </section> </main> ); } } We use the constructor to initialize the state for this component. Then we create an onEdit method for updating the state based on a parameter. You might also notice that we’ve used a @bind decorator here. This decorator comes from a library called Decko (not Deku!) and we’re using it to make sure that the onEdit method has the correct value of this, even when it is called from outside of the component. Finally, we’re passing this.state.text down to our <Markdown /> component as a prop. Each time the onEdit callback is called, we’ll update the state and the component will re-render. Virtual-DOM Unlike React, Deku and Preact, Virtual-DOM makes no assumptions about how you manage state, or where the virtual nodes receive their data. This means we’ll have to do a bit of extra work to set this up. Thankfully, Redux is unopinionated enough that we can use it here too. In fact, we can borrow the code for creating the store from the Deku example. import { createStore } from 'redux'; const store = createStore((state = initState, action) => { switch (action.type) { case 'UPDATE_TEXT': return { text: action.payload }; default: return state; } }); Rather than passing our store’s dispatch function down to our components, we’ll refer to it directly from our action creators. const actions = { updateText(text) { store.dispatch({ type: 'UPDATE_TEXT', payload: text }); } } This might feel simpler than our other action creators, but it makes them much harder to isolate and test, as they all have uninterceptable dependency on the Redux store. We’ll pass the initial state to our component for the first render. let tree = <MarkdownEditor state={store.getState()} />; let root = create(tree); document .getElementById('app') .appendChild(root); Then we’ll make use of the subscription mechanism to listen for changes to state. import { diff, patch } from 'virtual-dom'; store.subscribe(function() { let newTree = <MarkdownEditor state={store.getState()} />; let patches = diff(tree, newTree); root = patch(root, patches); tree = newTree; }); Rather than simply rendering the new tree, we perform the diff manually, then we used the returned set of patches to apply the minimal number of changes necessary to make the rendered DOM nodes reflect the virtual DOM nodes in our newTree. Finally we overwrite our old tree ready for the next render. Demos We put these components together and created an simple splitscreen, realtime Markdown editor with each framework. You can see the code and play with the finished editors on Codepen. Size When we’re developing lightweight applications designed to be used on desktop and mobile devices, the amount of data we have to transfer from the server is an important factor when picking a view layer. In each case, we’re creating a minified bundle containing both our application code and our dependencies, for comparison. 4. React - Lines of Code: 61 - Dependencies: react, react-dom, marked - Bundle Size: 154.1kb - Gzipped: 45.3kb As per the recommendation of the React team, we’re using the prebuilt production versions of React, rather than minifying it ourselves. A standalone minified version of Marked comes in at ~17kb. Together the minified versions of React and ReactDOM clock in at ~136kb. 3. Deku - Lines of Code: 80 - Dependencies: deku, redux, marked - Bundle Size: 51.2kb - Gzipped: 15.3kb Our Deku bundle already comes in 100kb lighter than React and we’ve also included a full blown state manager in the form of Redux. Together Redux and Marked weigh in at roughly ~30kb. Leaving our application code and our dependency on Deku at ~21kb. 2. Virtual-DOM - Lines of Code: 85 - Dependencies: virtual-dom, virtual-dom-util, redux, marked - Bundle Size: 50.5kb - Gzipped: 15.2kb Despite its minimalist, low level nature, our Virtual-DOM bundle weighs in at ~50kb (roughly the same size as Deku). Again, Redux and Marked are responsible for ~30kb of that size. Together the virtual-dom packages and the application code responsible for ~20kb. 1. Preact - Lines of Code: 62 - Dependencies: preact, decko, marked - Bundle Size: 30.6kb - Gzipped: 10.5kb Staying true to its purpose, our Preact bundle comes in at an impressive 30.6kb. Together, Decko and Marked are responsible for ~19kb of that, leaving Preact and our application code at a mere 11kb. Performance For the mobile web we should be equally aware that not all mobile device processors are created equal. We’ll take a look at how quickly our application gets its first frame onto the screen. 4. React The browser starts evaluating the JavaScript at around the 30ms mark. Then after a style recalculation, a reflow and an update to the layer tree, we get a paint event at 173.6ms, then the layers are composited and finally the first frame lands in the browser at 183ms. So we’re looking at roughly a 150ms turnaround. 3. Deku The browser starts evaluating JavaScript at around 55ms. Then we see the same style recalcuation, reflow and layer tree update, before we see the paint event at 111ms, layers are composited and the first frame lands at 118ms. Deku more than halves React’s turnaround time, bringing it down to roughly 70ms. 2. Preact We’re seeing the browser start to evaluate the scripts at about 50ms and the paint event appears at 86.2ms, and the first frame lands at 102ms, with a turnaround time of 50ms. 1. Virtual-DOM Browser starts evaluating at 32ms and the paint event lands at 80.3ms (interestingly the browser takes nearly 10x longer to composite the layer than the other frameworks) and then the frame lands at 89.9ms. The turnaround is nearly 60ms. So although Virtual-DOM has the fastest time-to-frame, it’s rendering process would seem to be slower than Preact. Of course we’re looking a performance on a micro scale here and the overall takeaway, is that all of these libraries are very fast (for this application). They all have their first frame on screen within 200ms. These test results were also captured on a Chromebook, not a mobile device, so they’re only designed to compare the relative performance between these libraries. You can find the code for these tests here on GitHub. Conclusion React has changed the entire landscape around how we think about developing applications. Without React, we wouldn’t have any of these fantastic alternatives and it remains uncontested when it comes to ecosystem, tooling and community. There are already hundreds if not thousands of React packages available over npm, with a ReactJS community organization created around a collection of more than 20 high quality open source projects, to ensure that they receive long term support and maintenance. React caters for most of the programming styles we’ve seen with the other libraries. If you want to move your state out into a store like Redux and work with stateless components, React will allow you to do that. Likewise, React also supports functional stateless components. The library itself has been battle tested, with a huge number of progressive tech companies (including Facebook) using React in production and the npm package getting hundreds of thousands of downloads each week. But we’re here to consider the alternatives to using React. So let’s see, where, when and why you might want to consider using a different library. Deku If Redux is an important part of your workflow then you may want to experiment with Deku. It weighs less and (in our case) runs a bit faster than React, with an opinionated approach which allows it to cut out a lot of the original feature set. Deku is a great fit for programmers who wish React enforced a more functional style. Virtual-DOM Virtual-DOM is perfect for building your own abstractions. The tools it provides out of the box are not enough to structure full applications and it’s a shame that it doesn’t support JSX by default, but these qualities make it ideal as a target for higher level abstractions that aren’t a good fit for React itself. Virtual-DOM will continue to be a great target for language developers who want to work with declarative, component based models, without worrying about getting their hands dirty with DOM manipulation. For example, it’s currently used to great effect as part of Elm. Preact Preact is the surprise here. Not only does it bundle up into the smallest application, but it also has a very low turnaround for getting frames out onto the screen. It’s lightweight, it has a small but growing ecosystem and there are an increasing number of React packages that can be used wholesale with Preact. Whether you’re building high performance apps, or pages that need to be delivered over low speed network connections, Preact is a great project to keep an eye on. Get practical advice to start your career in programming! Master complex transitions, transformations and animations in CSS!
https://www.sitepoint.com/react-alternatives-preact-virtualdom-deku/
CC-MAIN-2020-50
refinedweb
3,492
54.73
Introducing Joystick: The Full-Stack JavaScript Framework October 27th, 2021 Today, I'm beyond thrilled to introduce you to Joystick. Joystick is a full-stack JavaScript framework. Right now, that consists of a front-end UI library @joystick.js/ui, a back-end library @joystick.js/node, and a command-line interface @joystick.js/cli. The ui and node packages can be used independently, but are designed and intended to be used together. Joystick is free and MIT-licensed. No, you won't have to sell me your soul to access it or worry about financing my future ambitions in eugenics or authoritarianism. Consider this my thank you gift to all of the developers who came before me, all of the developers just getting started, and everyone in between. If you want to dig in, head over to the repo on Github and check out the docs. The front-end @joystick.js/ui brings a component-based approach to writing HTML, CSS, and JavaScript in a more organized, friendly way. It does not introduce any new languages or syntax. Components built with @joystick.js/ui look like this: Example Joystick Component import ui from "@joystick.js/ui"; import Quote from "../../components/quote"; const Index = ui.component({ methods: { handleLogHello: () => { console.log("Hello!"); }, }, events: { "click .say-hello": (component) => { component.methods.handleLogHello(); }, }, css: ` div p { font-size: 18px; background: #eee; padding: 20px; } `, render: ({ component, i18n }) => { return ` <div> <p>${i18n("quote")}</p> ${component(Quote, { quote: "Light up the darkness.", attribution: "Bob Marley", })} </div> `; }, }); export default Index; The render() function for components piggybacks on JavaScript's template literal convention. You return a string of HTML from it, using JavaScript interpolation to embed one of a few render functions: component(), each(), i18n(), and when(). component()allows you to render another component (enabling composition of components), each() helps you loop over and render data in arrays, i18n() helps you render internationalization strings, and when() helps you conditionally render HTML based on some variable. In addition to the render() method, components have a few other options: csswhich can be set to a string of CSS (or a function which takes in the component instance and returns a string of CSS) that's dynamically scoped to your component and injected into the page. eventswhich are JavaScript DOM events dynamically scoped to your component. methodswhich are miscellaneous, domain-specific functions for your component (and can be called by accessing the component instance passed to all other options). lifecyclewhich is a fixed set of methods— onBeforeMount, onMount, and onBeforeUnmount—that fire in relation to the lifecycle of the component. statean object (or function returning an object) that represents the default state of the component and can be modified via the .setState()method on the component instance. @joystick.js/ui also exports a get() and set() function for performing HTTP GET requests and HTTP POST requests to your API (more on this below), using input validation and Joystick's SelectiveFetch to customize the output returned from the API. They look like this in use: get() example get('posts', { input: { category: 'tutorials', }, output: ['title', 'author.name', 'publishedAt'] }).then((data) => { // Use data returned here... }); set() example set('createPost', { input: { title: 'A new blog post', body: 'The body of the post.', }, output: ['_id'] }).then((data) => { // Use data returned here... }); For user accounts, an accounts object is also exported from @joystick.js/ui with five methods on it: login()which is used to login existing users. logout()which is used to logout an existing user. recoverPassword()which is used to initiate a password reset. resetPassword()which is used to reset a password. That's the front-end. The goal is to keep this API fixed, only adding things (if absolutely necessary) as time passes. Components you write in Joystick today will work with Joystick in 10 years. My foot is down on this. The back-end On the back-end, @joystick.js/node is a thin layer over Express.js along with some other features. The centerpiece being the .app()method accessible via the object exported from the package (you will most commonly see this in boilerplate and example code as node.app()). The node.app() function is responsible for: - Registering your routeswhich are normal Express.js routes with a thin layer of syntactic sugar over them to keep things organized. Routes are assigned a special res.render()function to help you render Joystick components. - Registering your apibuilt using @joystick.js/node's getter and setter functions. - Registering any custom middlewareto run before each route. - Registering any listeners for standard Node.js eventslike uncaughtExceptionor unhandledRejection. More functionality will be added to node.app() as Joystick approaches a 1.0.0. For routes, res.render() is the only magic trick in the framework (the rest is just plumbing with pants pulled up). This function takes in the path to a Joystick component in your ui/pages directory and does a few things: - Server-side renders the page as static HTML and CSS. - Automatically embeds the script representing the compiled JavaScript version of the component to be loaded in the browser. - Utilizes the automatically injected mount script in @joystick.js/clito automatically "hydrate" the component on the client (swap the SSR rendered HTML with the dynamic JavaScript version). For you, this means super-fast mostly hands-free rendering of pages/components. The only thing sent to the browser is what's needed to render that page. For the API portion of node.app(), Joystick introduces the concept of getters and setters. They look like this: Defining a schema in Joystick { getters: { posts: { input: { category: { type: "string", }, }, get: (input, context) => { const query = {}; if (input.category) { query.category = input.category; } return context.mongodb.collection('posts').findOne(query).toArray(); }, }, }, setters: { createPost: { input: { title: { type: "string", required: true, }, body: { type: "string", }, }, set: async (input, context) => { const postId = joystick.id(); await context.mongodb.collection('posts').insertOne(input); return { _id: postId, }; }, }, }, } All of your getters and setters are organized into one object (referred to as your API's schema), with each getter or setter nested under the object of its respective type. Getters and setters are nearly identical save for their intent. They allow you to define validation for any input passed to them and a function get() or set() to respond to the request. Input validation uses a library that's built-in to Joystick. You'll also notice that the get() and set() functions receive a context argument alongside the input. This gives you access to the HTTP req and res objects from Express.js (getters and setters are implemented using Express.js routes just like your other routes) as well as any databases you've loaded via the CLI (more on this below) and, if applicable, the current user. The final piece of string tying all of this together is @joystick.js/cli, a command-line interface (CLI) that helps you to create new Joystick projects and start a development server for existing ones. It also helps you to start databases in development and communicate with @joystick.js/node to load the appropriate driver so your database is automatically available in your app. Project creation is simple. After installing @joystick.js/cli via NPM ( npm i -g @joystick.js/cli), just run joystick create <project> where <project> is the name of the directory your project will be created (e.g., joystick create banana-stand). To start your development server, cd into your Joystick project's folder and run joystick start to start your app at (if you're not an Atari fan, you can run your app on any available port with joystick start --port <port>). The databases @joystick.js/cli starts up for your app in development are determined by the config.databases array in your app's settings.development.json file (automatically created for you via joystick create). Once started, the native Node.js driver for each database started will be accessible in one of three ways (each equal and purely existing for convenience): - On your routesdefined via node.app()as part of the req.contextobject. Each database is available by its name here (e.g., req.context.mongodbor req.context.postgresql). - On the contextobject passed to the getand setfunctions on your getters and setters in the API. - Globally via the Node.js processobject with each database being defined by name (e.g., process.mongodbor process.postgresql). Joystick makes the conncetion to your database (which can be configured as part of the config.databases array in your settings) but does not modify the native behavior of the database or its driver. Once connected, you're at the mercy of the driver and its documentation (and my benevolence). As part of this setup, Joystick can also selectively map your user accounts to the databsae of your choice. Just set users to true in your config.databases array and Joystick will handle the plumbing. That's the framework. There are more, smaller features explained in the documentation. Joystick is proprietary I've had enough bullets ricochet off my helmet in the trenches to know that an Apple-style "walled garden" approach to Joystick's development is best. As much as possible—and makes sense—Joystick will be focused on giving you what you need out of the box with usage of third-party libraries being reserved for the truly esoteric, uncommon stuff. The goal of this is two-fold: to reduce the amount of messy, fragile code in your app and to offer a stable, long-term focused framework that doesn't leave you out in the cold on functionality that should be built-in. This concept will be foreign to and rejected by many people, but in time I hope to slam my scepter down at the base of my throne and hear the electorate cheer in approval. Joystick is opinionated Joystick is highly opinionated. The battlefield trauma I've experienced as a mentor to developers has led me to develop a "get off my lawn" attitude towards how things should be done. What I've learned over the years is that, without a clear, definitive process, Murphy's law kicks in and any code that can be written, will be written. Folder and file structure are specific and forced. The feature set will be 100% driven by my own mental illness and input from developers actively using the framework (not will-o-the-wisp computer science graduates who've failed to wipe the ketchup off their shirt having a bad morning). For now, pull requests will be turned away unless they're carrying a supreme pizza and delivered by an attractive brunette woman. Joystick's API will not be subject to random change. At worst, I'll add features, but no "Hey, guess what?! You have to refactor your entire codebase to keep using the framework! Awesome!" The design of Joystick was and is highly intentional and highly labored over. I sincerely don't care if you think you're better than or know more than me. I will handle people like this with far less tact than Steve Jobs. Joystick will be in beta for now Why a beta? Well, up until now, barely anybody knew I was working on this (and I'm fairly certain the ones that did thought I was full of 💩), which was intentional. As a result, I only know about the problems I know about. While things do work in general, I'm careful to give them my final stamp of approval as I'm certain there are plenty of bugs lurking in the bushes. Today's release is less about perfection and more about coming out of obscurity. I want to spend the next few months writing tests, clarifying APIs and documentation, and thinking about any loose ends in terms of feature set before I say "this is a 1.0." Expect a dash of chaos while I stitch the bird up before putting it in the oven. If you're looking to build a mission critical app: wait until the 1.0 drops (unless you have a gambling problem, then go for it). That said, you're encouraged to play. Find stuff that doesn't work. Find stuff that doesn't make sense. But for the love of God, don't leave me passive aggressive comments on Github: I won't be pleasant and will go out of my way to publicly embarass you. If you're kind and honest: I will climb over mountains for you. And here...we...go Admittedly, this is picking a fight. But it's a fight I feel is necessary and meaningful. To be blunt: web development with JavaScript has gone off the rails. It's left its family, bought a bunch of Tommy Bahama shirts, moved to South America and impregnated a young Peruvian girl. Having a midlife crisis is fine—acceptable, even, if done tastefully—but it's not conducive to building great software. Developers old and new need stable software that's easy to understand and keeps them productive—not a never-ending rug pull with passive shouts of condescension. This will absolutely piss some people off and I welcome their discontent. If JavaScript is going to move in a positive, sane direction long-term (and I'm going to avoid jail time), it's necessary. Ante up. Start building with Joystick Get the latest free JavaScript and Node.js tutorials, course announcements, and updates from CheatCode in your inbox. No spam. Just new tutorials, course announcements, and updates from CheatCode.
https://cheatcode.co/meta/introducing-joystick-the-full-stack-javascript-framework
CC-MAIN-2022-21
refinedweb
2,249
57.67
Re-usable currency item renderertanyagray01 Jul 14, 2009 8:50 PM Currently trying to find the best way to 'currency format' multiple datagrid cells. Apologies in advance if I'm overlooking an obvious solution. Each row has 3 columns which need to be formatted as currency. The datagrid's data provider is an object with values purchaseCurrency, purchasePrice ; costCurrency, costPrice etc, as the actual currency may not be consistent between the various different prices. I already have a component as an item renderer which is working fine, but it uses data.purchaseCurrency and data.purchasePrice to produce the label text to display. What I would like to know is if there is a way to pass the currency and price values into the item renderer, rather than the renderer having an absolute path to the values, so that I could re-use the same renderer across all the columns. If anyone could point me to any resources explaining how to pass the renderer multiple values that would be great. Thanks 1. Re: Re-usable currency item renderer*Prashant Shelke* Jul 14, 2009 10:16 PM (in response to tanyagray01)1 person found this helpful use <mx:DataGridColumn <mx:CurrencyFormatter public function formatCurrency(value:Object, column:AdvancedDataGridColumn):String { try { if(value != null ) { /** value.dataField * For which formatting will be applicable. **/ if(value.currency != null && !isNaN(Number(value.currency)) && value.currency!= "") { return currencyFormatter.format(value.currency); } else { /** Here you can return "-" if column has NULL or EMPTY string. **/ return "$0"; } } } catch(error : Error) { Alert.show("error : " + error.getStackTrace()); } return "$0"; } 2. Re: Re-usable currency item renderertanyagray01 Jul 15, 2009 2:48 PM (in response to *Prashant Shelke*) Hi Prashant, thanks for your reply, but I'm not sure that it will fit all of my needs. When you define a CurrencyFormatter, you set the currencySymbol to a specific symbol. The application I am working on is to be used in multiple countries, and so will have different currency symbols. For each row in my datagrid, the item renderer would need to be passed both data.currency and data.amount. That would be fine, if there was only one column, but for each row there are multiple columns which need to be formatted as currency, and each one will have a different currency symbol and a different amount/price. This code will obviously not work but it may help to explain what I am trying to achieve: <mx:DataGridColumn <mx:DataGridColumn <mx:DataGridColumn ---------------------------------------- <CurrencyRenderer> <mx:Script> public var currency:String = //need a way to set this dynamically from thisRow.purchaseCurrency etc; public var amount:int = //need a way to set this dynamically from thisRow.purchaseAmount etc; </mx:Script> <mx:Label </CurrencyRenderer> -------------------- I am relatively comfortable with extending components if I really need to, but at least a hint on the direction I should be heading or what overrides I should consider would be helpful. 3. Re: Re-usable currency item rendererGregory Lafrance Jul 15, 2009 2:50 PM (in response to tanyagray01)1 person found this helpful Each column could have its own labelFunction, and those label functions could use the same CurrencyFormatter, but change the currencySymbol within the functions. If this post answered your question or helped, please mark it as such. 4. Re: Re-usable currency item renderertanyagray01 Jul 15, 2009 3:27 PM (in response to Gregory Lafrance) Thanks Greg, You are right, I could do it that way and I did consider it, but I was trying to be 'tidy' and cut back on duplicate code. It's not only an item renderer for each column, there's also an item editor where the user can select from a dropdown the currency and enter into a textInput the amount, so I was hoping to apply the same concept to both the itemRenderer and editor, and to have just one standalone component for each. I may have misunderstood but my interpretation of your suggestion is that each column would have a different labelFunction, making 3 in total. I guess that's not so bad... I will probably do it that way if I have to, but it wouldn't solve my problem of still having to create multiple itemEditors. Would there be a way to make an itemEditor or renderer accept arguments? <mx:DataGridColumn I don't expect that there would be an EASY way, but I guess this is the best place to ask. 5. Re: Re-usable currency item rendererGregory Lafrance Jul 15, 2009 3:30 PM (in response to tanyagray01) I'm not knowledgable enough on item editors to be able to answer your second question. Perhaps someone else will be able to chime it. 6. Re: Re-usable currency item renderertanyagray01 Jul 15, 2009 3:34 PM (in response to Gregory Lafrance) Thanks, I will leave it for now and work on other parts of my project, will credit your reply if I end up coding it that way. Tanya 7. Re: Re-usable currency item renderertanyagray01 Jul 15, 2009 6:54 PM (in response to tanyagray01) <mx:DataGridColumn package{ import mx.controls.DataGrid; import mx.controls.Label; import mx.controls.dataGridClasses.*; public class CurrencyRenderer extends Label { override protected function updateDisplayList(unscaledWidth:Number, unscaledHeight:Number):void { super.updateDisplayList(unscaledWidth, unscaledHeight); // the dataField of the current column var dataField:String = DataGridListData(listData).dataField; // find the var reference by dataField + "Currency" // eg. "purchase" + "Currency" references to data[purchaseCurrency] var currency:String = data[dataField + "Currency"]; // same as above for dataField + "Amount" to make purchaseAmount var amount:String = data[dataField + "Amount"]; // combine the two for the final string to display this.text = currency + amount; } } } This is the solution I've come up with, it will allow me to use the same renderer in each column with the same results. Haven't yet tried it with an item editor but I believe it should follow the same general rules. Thanks to both of you for your help
https://forums.adobe.com/thread/462461
CC-MAIN-2017-51
refinedweb
987
51.28
Conservapedia talk:What is going on at CP?/Archive168 Contents - 1 Panto and Conservapedia - 2 Do we have anyone watching the CBP? - 3 Karajou is taking a long time... - 4 Oh dear - 5 About to get banned on CP, a worthy cause - 6 Ken's incoherence - 7 Challenge on! - 8 Interesting news story - 9 Conservapedia and SCOTUS - 10 Ed's still an idiot - 11 SamF is in over his head - 12 InTKrigue - 13 More TK/Jensen dust-up - 14 New Weakly toon (intresting thing about God) - 15 Conservative movie - 16 TK went Al Gore? - 17 There, there, TK - 18 Ed Poor - 19 I'm coming out - 20 WIGO fail - 21 Wandal Spree - 22 TK WIGO's = fucking boring - 23 "Bailed-out General Electric" - 24 Time out's make me bored - 25 TK has a small penis - 26 If in doubt, poke Ken with a stick - 27 RJJensen's got a project. - 28 Wait, what? Professor? - 29 "The age of reason" - 30 is it just me... - 31 Negroes - 32 Andy is a jaywalker - 33 March - 34 Anon? - 35 Blog - 36 Andy and ethnicity - 37 "Like belongs with like" - 38 Thought this was funny... - 39 "Saint Ronnie?" - 40 The register misses the point. - 41 Expert WIGO - 42 Tea Paaarrrtay - 43 It begins - 44 DWiggins - 45 Oh, please, TK, make my day! - 46 Eisenhower - 47 Laager mentality - 48 Tim Tebow - 49 Hey Rob? - 50 Wordy "Obama's an elitist" - 51 Article - 52 "Many of the most influential people in history were writers... - 53 Can anyone tell me the difference...? - 54 TK, hope you'll report this! - 55 Liberal Cyber Bullies Panto and Conservapedia[edit] Conservapedia is seemingly agin cross dressing. The article mentions cross dressing in pantomime. Anyone care to do 'Conservapedia - the Panto' (possibly involving kilts, or tights). Jackiespeel (talk) 16:49, 20 January 2010 (UTC) - wouldn't a Panto in tights lead to a Codpiece size war ? that would not be a pretty sight :( The male lead is of course played by a woman, so what woman would play Andy ? or would the lead be TK or maybe Uncle ED ? I vote for Paris Hilton or maybe Miley Cyrus. Hamster (talk) 17:22, 20 January 2010 (UTC) - Conservapedia, the panto, would suffer badly from the lack of stock characters (oh no it wouldn't). Who's the dame for a start? Bob Soles (talk) 17:32, 20 January 2010 (UTC) - Phylis Schlafly? TKEtoolshedFrag Out! 17:33, 20 January 2010 (UTC) - played of course by Alan Alda or perhaps Kirk Cameron, a gold lame dress, strapless of course with a small tiara blinking Conservapedia. Hamster (talk) 17:45, 20 January 2010 (UTC) - Or the woman from Fight Club who says crazy yet insightful quotables? TKEtoolshedFrag Out! 17:50, 20 January 2010 (UTC) - No! Speak not her name, or she will appear! Either way, Ken would have to play Bottom. --PsygremlinTal! 17:55, 20 January 2010 (UTC) - Are there any female contributors on CP (after Kate Sorenson facted her way right out of there!) to play the lead? DeltaStarSenior SysopSpeciationspeed! 18:10, 20 January 2010 (UTC) - Only little Phy and Taj (if she's still around). As far as I know HSMom, Bethany (& sister) and Justine have all seen the light and left CP as Andy likes it - white and male. --PsygremlinTala! 18:19, 20 January 2010 (UTC) - From the lack of female contributors, how does one infer that the Wiki lacks editors who have darker skin? And how does it possibly infer that Mr. Schlafly likes it white? ListenerXTalkerX 19:36, 20 January 2010 (UTC) - I believe that Mr Schlalalfly likes his men like his coffee... DeltaStarSenior SysopSpeciationspeed! 19:46, 20 January 2010 (UTC) - Black and bitter, or ground up and in the freezer? Unemployed philosopher (talk) 20:53, 20 January 2010 (UTC) (UI)Before you guys all said it I kinda realized the same thing... other than homskollars doing homework and tests, CP seems to have become an exclusively male province. ħuman 21:09, 20 January 2010 (UTC) - That's not exactly a surprise, given the rampant misogyny. Tetronian you're clueless 22:37, 20 January 2010 (UTC) @Human: It's called "the best of the public." Buh-dum-pshhh.-- Antifly Merged with Infinity 23:26, 21 January 2010 (UTC) - It's not that CP is an exclusively male province but that it is a middle to old-aged, white, misogynistic, misanthropic, reactionary, male province. And while you guys fantasize about Conservapedia - The Panto all we are really left with is Conservapedia - The Pants. E.J.Thribb 23:47, 21 January 2010 (UTC) Do we have anyone watching the CBP?[edit] Is there anything happening besides Ecclesiastes to watch? --Opcn (talk) 19:54, 20 January 2010 (UTC) - Mr. Schlafly has been trying to insert conservative buzzwords into the Gospels again. ListenerXTalkerX 19:55, 20 January 2010 (UTC) - Seems like the pace has slowed a lot. Andy does the main editing on the New Testament Gospels, while TerryH is working on the Old Testament at a crawl. My take on the CBP is that Andy's real interest is in making sure he's the only one interpreting what Jesus says in the four main Gospels - outside of that he's showing about as much interest as he does for any project he starts once the first few weeks have passed, i.e. none. - I wish he would write a book, that would be great. --Opcn (talk) 20:55, 20 January 2010 (UTC) - I would jump at the opportunity of doing a side-by-side on that. Tetronian you're clueless 22:39, 20 January 2010 (UTC) - Andy's book already exists 82.23.209.253 (talk) 22:41, 20 January 2010 (UTC) - The pdf file see pages 25 to 39. Muchly good info in the first two dozen pages...outstrips CP by a mile, (1.2K). 22:54, 20 January 2010 (UTC) CЯacke® - Anyone notice Ecclesiastes 5:3img? --Opcn (talk) 02:20, 21 January 2010 (UTC) - Looks a little too obvious, I'm afraid. The only person who could get away with such a blatant case of applied SchlaflySpeak would be... Andy. Unfortunately, it looks like ChrisY has answered the shout-out for help with this page, and he's cleaning up the crapremoving the laughs again. --04:27, 21 January 2010 (UTC) The OT will never be done by anyone who isn't a poser, if you can read ancient Hebrew then you have a real skill, why use it on the CBP? ECC is easily the best book of the bible, Solomon was probably a little manic depressive (or just depressive). Also if you look at the basically schlafly article about word analysis in the bible it seems to indicate that the bible needs moar schlafly! --Opcn (talk) 09:46, 21 January 2010 (UTC) - I was going to point out his edits to Eccles as an example of how to do the CBP right, but what's the difference really - his "translations" may be more poetic, scan better, and stay truer to the text than Andy's, but they're both still playing Bible Telephone. Going over CBP edits with the handy Parallel Bible has just given me a new appreciation for how careful and exact the KJV translators were. WodewickWelease Wodewick! 12:45, 21 January 2010 (UTC) I try to continue the general effort...I managed to get some pretty big stuff approved. Alas, I can't talk about it, so you'll have to see for yourself. --Ireon (talk) 16:35, 21 January 2010 (UTC) Karajou is taking a long time...[edit] creating his Massachusetts junior senator 'toon isn't he. Internetmoniker (talk) 13:03, 21 January 2010 (UTC) - True art takes time, and is worth the waiting. Which doesn't explain why Karajou's latest is delayed. MDB (talk) 13:09, 21 January 2010 (UTC) - Darwin's a God-bashing idiot, part II. Was it worth the wait? --Irrational Atheist (talk) 20:53, 21 January 2010 (UTC) - That's... the first Karajou cartoon that's not even worth making fun of. WodewickWelease Wodewick! 00:26, 22 January 2010 (UTC) Oh dear[edit] I wonder if Andy's ever seen his own Victor Jara article. It sure makes his hero, Pinochet, look bad. I know Andy doesn't read this, but maybe you could point out a whitewash is needed here, TK. Liberal claptrap in Conservapedia? Surely it cannot stand! Oh, and see if you can get Andy to use the term "liberal claptrap" in his edit summary. Thanks. DickTurpis (talk) 15:06, 21 January 2010 (UTC) About to get banned on CP, a worthy cause[edit] Ok, I'm about to get banned on CP again, with my best account yet, for trying to discuss something with both Assfly and TK. This concerns the recent despicable Supreme Court decision to make government by Monsanto, of Pfizer, and for Walmart (corporations no longer have limits on campaign contributions). As things continue you can see them hereimg. ScientificRigor (talk) 19:31, 21 January 2010 (UTC) - If you want to make it on CP, you have to use facts less and agree more. Nice post, though. Make sure to use the <capture></capture> tags for links to anything particularly good on CP. — Sincerely, Neveruse / Talk / Block 19:39, 21 January 2010 (UTC) - I. for one, welcome our SAME OLD corporate overlords. --Gulik (talk) 20:10, 21 January 2010 (UTC) - And the banhammer has fallen. It feels strangely comforting knowing that I can get banned for pointing out Andy's grammar errors. Oh yeah, and for a fact here and there. ScientificRigor (talk) 20:29, 21 January 2010 (UTC) - JacobB is just trying to prove himself. I wonder who he is here... — Sincerely, Neveruse / Talk / Block 20:33, 21 January 2010 (UTC) - Irritating parodist, he should have let Andy try to answer, so we can laugh. Andy usually hands out short blocks, too. Broccoli (talk) 20:38, 21 January 2010 (UTC) - I am JacobB! --Irrational Atheist (talk) 20:43, 21 January 2010 (UTC) - (EC4)He's not even a good parodist. A real CP sysop would have made up a reason like last-wordism or 90/10 or Trolling/Liberal Trolling. Or the classic Schlafly "bye". — Sincerely, Neveruse / Talk / Block 20:43, 21 January 2010 (UTC) - How can we ever get the old Spartacus joke going when someone asks who someone is, if no one participates? --Irrational Atheist (talk) 20:53, 21 January 2010 (UTC) Nice to know we can get anybody banned, at any time, by claiming here to be them. 21:03, 21 January 2010 (UTC) - I forget who did it, but someone got TK to ban his own IP...or conservapedia's IP...or something hilarious. Taking responsibility for a random CP users actions is great fun. Let's you know who's watching. Let's them know their your bitch. Jacob, step your game up. — Sincerely, Neveruse / Talk / Block 21:07, 21 January 2010 (UTC) - Someone got TK to ban CP's actual IP, and I got TK to ban the Eagle Forum's IP. --Irrational Atheist (talk) 21:12, 21 January 2010 (UTC) - I never blocked my own IP, that I can remember, and since you don't have check user here, I doubt anyone knows it, and since I could unblock myself, doing that would do what? As for the Eagle Forum, do you honestly believe their server tries to post on CP? --TK/MyTalk"Editor 23:47, 21 January 2010 (UTC) - - The reference was to Conservapedia's IP, not your own. The block of the Eagle Forum server was intended, I believe, to demonstrate that you are prone to blocking IPs that are unassociated with vandals. ListenerXTalkerX 23:51, 21 January 2010 (UTC) - Well, whaddayouknow? TK concedes that we don't have checkuser. 86.134.119.71 (talk) 00:10, 22 January 2010 (UTC) Concedes? You cannot recognize sarcasm? --TK/MyTalk"Editor 01:11, 22 January 2010 (UTC) - Should have realized that posting here would have led to a ban. I think it was because I called dear leader Assfly (not on CP, of course; that would be liberal namecalling), honestly, although initially I thought I'd get it from the open mind and godspeed parts, which were pretty clear mockery. The ban expires tomorrow and I'll get back to correcting grammar errors and spelling mistakes like a good CP user, although I don't have it in me to feign conservative ideology. I was just very upset by the ruling, and still am. Also, I get a kick out of the fact that Daniele is Italian for Daniel (if I were a girl it would be Daniela), and that it was immediately assumed that I'm a girl. ScientificRigor (talk) 00:24, 22 January 2010 (UTC) Wow, hard up for kicks much? Perhaps you need a good hobby! --TK/MyTalk"Editor 01:11, 22 January 2010 (UTC) - π 01:15, 22 January 2010 (UTC) - Like messin with Conservapedia? TKEtoolshedFrag Out! 03:27, 22 January 2010 (UTC) Ken's incoherence[edit] How can an article in an encyclopaedia, be a good use of an encyclopaedia?img - π 04:12, 21 January 2010 (UTC) - He's talking to himself...again. δij 04:14, 21 January 2010 (UTC) - aSK is down, so he can't attract our attention that way. - π 04:16, 21 January 2010 (UTC) - I wonder if he made those videos himself. The quality is certainly low, but the familiarity with the material is high. ħuman 04:18, 21 January 2010 (UTC) - I suppose these were the waves he was going on about. So much build up for so little. To be honest I have come to expect that from him now. Three YouTube videos that will probably never get more that 1,000 views. It is sad to see him try so hard for such little results. - π 04:23, 21 January 2010 (UTC) - Right, I haven't watched the YT video as I have an extremely slow connection at the moment, but I can already see the production values in the first few seconds (a camera pointed at a PC screen, with "conservapedia" written in notepad - with the YT star pointing at the screen with a pen...). Given the shiteness of the video, and the shiteness of the five comments (Ken's one actually says "good use of encyclopedia~ " (sic), why is Ken so keen to highlight it? Really, Kenny-boy, it's nowt to be proud of! DeltaStarSenior SysopSpeciationspeed! 05:23, 21 January 2010 (UTC) - Resistance is futile, Ken has already won. Acei9 05:40, 21 January 2010 (UTC) - (EC)Not that guy again. He also did a video on the evolution article for Ken. Then when Ken posted that on the front page, the guy did a video about how his video was on the front page. Which Ken then posted on the front page and the cycle went around once more. - I sent the guy an email begging him to use Capture Fox, but he never replied. He heavily moderates all comments, so unless you are blowing smoke up his arse, your comment won't get approved. - π 05:44, 21 January 2010 (UTC) - All religionist youtubers seem to be like that - ratings disabled and comments heavily moderated (if enabled). I like the thought of Ken getting in to that perpetual loop though, how did it end? Do you think it will happen again. DeltaStarSenior SysopSpeciationspeed! 09:46, 21 January 2010 (UTC) - The guy didn't make a fourth video. - π 09:53, 21 January 2010 (UTC) - Isn't it possible, or even probable, that Ken and this YT guy is the same person? Etc 20:52, 21 January 2010 (UTC) - Oops, that question has already been asked. My guess is yes, he makes these videos himself. Etc 20:54, 21 January 2010 (UTC) - I usually roll my eyes at these guys who can't even manage to clean their houses or put on a clean shirt when they're trying to talk about serious shit - but Shockogod takes the cake for lazy production value. And it's fucking brilliang. Why bother using your noodle when all you have to do is read someone's shitty article. This will be my big YouTube break. 16:05, 22 January 2010 (UTC) Challenge on![edit] Right then, who fancies making a YT video about CP, then trying to get Ken to feature it on the main page? (SuperJosh need not apply) DeltaStarSenior SysopSpeciationspeed! 09:46, 21 January 2010 (UTC) - Damn. I really want to, but I don't have a video camera. DickTurpis (talk) 15:08, 21 January 2010 (UTC) - Woe with me! My spectacularly bad YouTube videos I posted about 5 months ago have yet to be recognised by the great Conservative! SJ Debaser 15:10, 21 January 2010 (UTC) - Go for it then, Josh! Your videos are certainly of the standard enjoyed by Ken, I'm sure he'd like the "British conservative praises conservapedia" angle. Can you do a David Cameron voice? (Not that Andy would consider him to be a 'conservative', despite being leader of the Conservative party. Anyway, I'm rambling a bit now) DeltaStarSenior SysopSpeciationspeed! 15:54, 21 January 2010 (UTC) - I wouldn't actually mind trying that, though I don't think I'd like the negative attention from the YouTube community, it has too much of a massive religious vs. atheist and conservative vs. liberal userbase. SJ Debaser 16:21, 22 January 2010 (UTC) - Set up another account to use for your CP vid. Open it now and look at it now and favourite a few bible-bashing/right-wing vids so Ken doesn't spot that it's just been opened to make his video. (Is he that clever?) DeltaStarSenior SysopSpeciationspeed! 19:32, 22 January 2010 (UTC) Interesting news story[edit] 'the two church-goers from New Jersey had the best intentions in the world when they arrived in Port-au-Prince this week to help victims of Haiti’s killer earthquake.' ...'Trouble was, that was all they had' — Unsigned, by: 131.107.0.112 / talk / contribs & stiltontalk 18:28, 21 January 2010 (UTC) - Goddamned liberal commie Haitians don't appreciate the value of prayer. That's obviously what the New Jersey folk brought, AND THEY CENSORED IT! This wouldn't have happened if Reagen were in charge. You know what, I bet that news story was published by gay lesbian atheists. Perhaps they brought memorized verses of the most logical book in the world, the Bible. Hey, speaking of which, I just got a brand new insight! *Runs off to rewrite another portion of the most logical book ever written* NorsemanCyser Melomel 19:36, 21 January 2010 (UTC) - But..but.. this is impossible. Not only are they the Best of The PublicTM, but they're also good Chrisjuns. Norseman is right. This is surely a liberal conspiracy, and I'm certain that Andy will get to the bottom of it as soon as Ed and Karajou return home. -- Ask me about your mother 20:54, 21 January 2010 (UTC) - The sheer weight of all the aid workers, even if they dont actually have aid with them, will help stabilize the fault that caused the first quake. The Haitians should not grieve for the dead , after all the voodoo preists will have them back up and moving in no time at all. :( Hamster (talk) 16:48, 22 January 2010 (UTC) Conservapedia and SCOTUS[edit] The US Congress has been behaving like the legislature of a failed state. No matter what issue/problem we present to Congress, by the time it comes out the other end of the sausage machine it's been reduced and repacked into a series of corporate welfare measures. This happens no matter whether the agenda is right-wing or left-wing. Bush proposes Medicare Part D, it turns into a handout to PhRMA. Obama proposes a public option, it turns... into a handout to PhRMA. No matter who wins elections, the public interest loses. When you look at it that way, why should Conservapedia be so happy about more corporate money in politics? Exxon will be able to spend moar money to defeat those dirty hippies, true. But who do you think is going to win in a fight between homeschoolers and Prentice Hall? How about anti-vaccine nutsos and Merck? How about small government teabaggers and Goldman Sachs or ADM? Corporations militate against the political agendas of both the grassroots right AND the grassroots left. WodewickWelease Wodewick! 05:56, 22 January 2010 (UTC) - I don't know, Lipton might be on the teabaggers side. - π 06:45, 22 January 2010 (UTC) Ed's still an idiot[edit] Geez, Ed, really? You're still on about that? --Irrational Atheist (talk) 22:46, 22 January 2010 (UTC) - Sorry about that. I have no idea why this double-posted twice when I only clicked submit once. Test test? --Irrational Atheist (talk) 22:50, 22 January 2010 (UTC) SamF is in over his head[edit] Looking just at this edit: "The mammalian whale lacks plausible ancestors along points of a proposed evolutinary pathway." - Are there other whales besides mammalian ones? What happened to ambulocetus, protocetus, rodhocetus, basilosaurus and others? "the enormous gaps and lack of intermediate species between kinds in the fossil record." What's a kind? And why is a lack of an intermediate species a counterexample of evolution? "No clear transition from unicellular to multicellular organisms." It's been known for about a decade. "A lack of any evolution from prehistoric forms has been demonstrated for many species." How can anyone "demonstrate" a lack of something? The whole page is absurd. There's no reason to dig for "facts" to back up those absurd arguments. --Irrational Atheist (talk) 23:24, 22 January 2010 (UTC) - EvanW brings some more DUHR to the talk page. "It seems to me that what the article's saying is precisely that it is a mystery - so no natural process could have created it; since atheistic evolution allows only natural processes, but consciousness exists, atheistic evolution can't be all there is." It's not known how something works, therefore evolution-atheistic evolution to boot!- is wrong? And creationists wonder why we all laugh at them and their arguments? --Irrational Atheist (talk) 23:28, 22 January 2010 (UTC) - Apparently you have never heard of whittling. --Opcn (talk) 00:21, 23 January 2010 (UTC) - I like the reason for his block. Couldn't find any specific reason to block him, so a vague excuse is the best TK could get. NorsemanCyser Melomel 00:55, 23 January 2010 (UTC) "Are there other whales besides mammalian ones?" He could be thinking of the Whale Shark, which is a fish, not a mammal. </devil'sadvocate> X Stickman (talk) 03:59, 23 January 2010 (UTC) - Maybe he just didn't want to get blocked, but wanted the sentence to have a good meter too it. --Opcn (talk) 06:27, 23 January 2010 (UTC) InTKrigue[edit] I can't find any edit of AlexWD's to DouglasA's talk page or anywhere else, so I assume the whole shebang has been oversighted. TK also oversighted this edit to Joaquin's talkpage. Busy little bee aren't we. WodewickWelease Wodewick! 03:28, 23 January 2010 (UTC) - Deceit, thy name is TK. Keegscee (talk) 03:37, 23 January 2010 (UTC) More TK/Jensen dust-up[edit] TK oversights one of Jensen's edits and calls him liberalimg after DanielPulido edited some talk page comments of Jensen's.img Coarb (talk) 23:15, 18 January 2010 (UTC) - TK smells blood - he knows RJ is vulnerable. I thought some estimates of a week were quite optimistic, but then, I don't expect to see RJ still there in a month - particularly with the continued baiting over dimwitted professors. MaxAlex Swimming pool 00:21, 19 January 2010 (UTC) - You never know - all it takes is one flame war with TK or Andy to end it all. It could happen at any time. Tetronian you're clueless 00:35, 19 January 2010 (UTC) The pile on begins[edit] RobSmith questions Jensen's conservative bone fides, with real evidenceimg -- Coarb (talk) 06:16, 19 January 2010 (UTC) - This is getting a little Red Guard ish don't you think? WodewickWelease Wodewick! 06:36, 19 January 2010 (UTC) - No more so than what happens here, nearly every week. --TK/MyTalk404 Blocked! 07:26, 19 January 2010 (UTC) - That's simply because there's no secret discussion group to hide all the edits/comments, which in thanks to you, we know exists. :3 And besides, the arguing is usually about following policy (from what I can tell), something Conservapedia can't seem to grasp. NorsemanCyser Melomel 15:49, 19 January 2010 (UTC) - Clearly Rob was absent the day MYOB became a blockable offence Entering into disputes not involving editor (MYOB) . Oh wait... he's an admin - rules and commandments don't apply to them. Silly me. --PsygremlinPraat! 17:18, 20 January 2010 (UTC) - I do have a dog in this fight. The discussion began here. I needed time to study the Ben Bernanke & Larry Summers cites Dr. Jensen uses. RobSmithdon't bother me 04:05, 21 January 2010 (UTC) - Wow Rob, that "dog" is six months old. Nothing like digging up old bones is there. --PsygremlinParla! 08:51, 23 January 2010 (UTC) Pot/Kettle much? --TK/MyTalkEditor 11:46, 23 January 2010 (UTC) - Aw! are we all butthurt agwain? C'mere I kiss it all better for you. --PsygremlinKhuluma! 12:17, 23 January 2010 (UTC) New Weakly toon (intresting thing about God)[edit] Notice how he subtracts God the first time (thus making evolution anti-God), but then he subtracts God a Second time, only this time, God has a "no" sign around it (or whatever they are called), meaning they subtracted the negative of God, which would make the amount of God in Evolution = zero. Which is certainly not what they are arguing, but is the truth, that the theory of evolution is pro or anti-God. Unless karajou is sending us messages that he is secretly a liberal, it was just a screw up, but I am selectively OCD, so I just needed to say that. (I am a Christian, and I do believe in God, but I don't see any reason why God and Evolution have to be mutually exclusive, but then again, I am not completely batshit insane) EDIT: I would also like to point out that he did the same thing for common sense.--Passerby25 (talk) 18:48, 22 January 2010 (UTC) - I dunno, that cartoon does explain conservative's view of evolution: "I don't understand it so it's wrong". CrundyTalk nerdy to me 18:52, 22 January 2010 (UTC) - Crundy, that sums up CP perfectly. (In addition to "I don't like it so it's wrong") DeltaStarSenior SysopSpeciationspeed! 19:49, 22 January 2010 (UTC) - Hmmm... it seems that once Karajerk gets into his groove, it's hard to get out of it. Hot on the heels of dozens of Climategate & Climate summit cartoons, we're now getting "evolution on a blackboard" cartoons. This is almost identical to last week's and even less funny. Please, snookums, punchline, baby, punchline. --PsygremlinKhuluma! 09:17, 23 January 2010 (UTC) Conservative movie[edit] Besides "Pillow Talk" getting Andy all hot when he watches the women getting slapped around, I'm surprised that a conservative movieimg has a gay leading man, who engaged in liberal deceit by staying in the closet. Obviously, the wife beating was important enough to win out. Actually, to add to that, it won an Oscar and has been added to the National Film Registry for being “culturally, historically or aesthetically” significant (thanks to WP for telling me that). Now things like that would make it a good conservative movie, but for Andy, it's all about the uppity bitch getting slapped around. Oh - and "no distortions by feminist ideology" - it was made in 1959 ffs. Feminist ideology hardly existed back then. --PsygremlinHable! 09:35, 23 January 2010 (UTC) - Unless you count that lady on the dollar coin, and few other thousand suffragettes. Sorry if I hear a Bowie song in my head when I type that. ħuman 09:40, 23 January 2010 (UTC) - What are you talking about? It is a rumor that Rock Hudson was gay, clearly he was straight, don't you read anythingimg?--Opcn (talk) 09:58, 23 January 2010 (UTC) - S-S-S-Suffragette City! Bowie was the best stutterer ever. What was that other song? Oh, yeah, I forget, but I dreamed about it last night. ħuman 10:02, 23 January 2010 (UTC) - Ch-ch-ch-ch-changes! ħuman 10:05, 23 January 2010 (UTC) - (I now have Rebel Rebel playing the background). Lol - I see it's a classic case of right hand / left hand over on CP. First we have Homosexual Historical Revisionism claiming it was false that Rock Hudson was gay, then under his (1 line) articleimg we have category:Homosexuality. --PsygremlinSprich! 10:12, 23 January 2010 (UTC) - Your face is a mess! ħuman 10:26, 23 January 2010 (UTC) - Are you forgetting The Who's My Generation? Several stutters including "Why don't you all f-f-f-fade away?" ГенгисGum disease 11:29, 23 January 2010 (UTC) TK went Al Gore?[edit] Go green! But why is that important for Conservapedia? That's the opposite of "Drill, baby, drill!" --Irrational Atheist (talk) 23:45, 23 January 2010 (UTC) - The argumentum ad populum, it hurts! ListenerXTalkerX 23:59, 23 January 2010 (UTC) - My favorite is still the frequent "Majority of people don't want new taxes!" Well... duh? Majority of people don't want to pay bills, either. And most people in the US don't want Congress. --Irrational Atheist (talk) 00:27, 24 January 2010 (UTC) - Although sometimes the majority is right; as in: "The majority of people think Conservapædia is hilariously funny". I have just eaten & stiltontalk 00:35, 24 January 2010 (UTC) - Something must be lost in the translation for non-US readers. --TK/MyTalkEditor 00:46, 24 January 2010 (UTC) - Yeah, but the fish still bite when we cast the bait. I have just eaten & stiltontalk 00:54, 24 January 2010 (UTC) - Most people don't want to pay tax, but people with a mental age over 15 see it as an essential part of governance. - π 00:56, 24 January 2010 (UTC) Except that the poll didn't really have to do with taxes. It has to do with preferences for alternative energy sources, versus more fossil fuels, or cutting back our use of energy. --TK/MyTalkRW User #45 01:59, 24 January 2010 (UTC) - TK, you're an asshole and an idiot. How's that for a poll? --Irrational Atheist (talk) 02:28, 24 January 2010 (UTC) What is TK? - All of the above. Vulpius (talk) 02:54, 24 January 2010 (UTC) - I'm reminded of George Carlin's game show, "Asshole, Jackoff, Scumbag". --Kels (talk) 03:37, 24 January 2010 (UTC) - That sounds like RobS' night in.-- Spirit of the Cherry Blossom 04:33, 24 January 2010 (UTC) There, there, TK[edit] [1]img. TK opens up the Obama article to editing after criticism of one of the sources. This is, of course, a honey pot -- anyone removing the bizarre speculation will surely be banned. Anyway, when the original critic keeps complaining rather than editing the Obama article, TK loses his cool. Coarb (talk) 02:18, 24 January 2010 (UTC) - Been hanging around here so much our language has seeped its way into his edits on CP, I guess. Aboriginal Noise What the ... 02:25, 24 January 2010 (UTC) - [2]img TK must be grumpy tonight. Nick Heer 04:06, 24 January 2010 (UTC) - Wingers really are incapable of understanding the fallacies of their own argument. When Bush won, it was "a mandate" of the people. When Obama wins, it's "Why won't he listen to the people?" When the Democrats win Congress on, among the promises, a platform of making a public option for health care, the wingers shout, "Socialism!" When one senator wins against another who ran a terrible campaign, it's "The people have spoken!" So why is it "the people" speaking when it agrees with them, but not what "the people" want when it disagrees with them? I know! It's because wingers are utter morons incapable of rational thought, and thus perceive anyone who disagrees with them as an enemy. Nixon never died, he just transferred the creepiness to future generations. --Irrational Atheist (talk) 05:01, 24 January 2010 (UTC) Ed Poor[edit] Insinuations that Ed Poor is a sex pest or paedophile, I mean, WTF? Come ON! On what basis are these insinuations made? What possible justification is there? If there is none, and it would have to be pretty damn convincing if there is, then it's simply outrageous and totally inappropriate. Ajkgordon (talk) 18:53, 23 January 2010 (UTC) - I have to agree. It's one thing to comment on Ed's posts when they stray into creepy territory, but it's another to imply that he's a pedophile. Let's keep the comments appropriate, folks. --SpinyNorman (talk) 18:58, 23 January 2010 (UTC) - I agree - he is down right creepy sometimes but creepy =/= pedo. Acei9 18:59, 23 January 2010 (UTC) - Censorship is such a liberal trait. Keegscee (talk) 19:18, 23 January 2010 (UTC) - Censorship? Ajkgordon (talk) 19:53, 23 January 2010 (UTC) - It's obvious that Ed is a pedophile. I bet you don't think smoking causes cancer either. Keegscee (talk) 19:59, 23 January 2010 (UTC) - Or abortion. --Kels (talk) 20:10, 23 January 2010 (UTC) - Tut, tut. It's much more important that the word is spelt paedophile 'cos it's of Greek extraction, you ignorant Merkins.-- Spirit of the Cherry Blossom 22:13, 23 January 2010 (UTC) - <da>to be fair, he strays beyond the 'creepy' territory on a frequent basis. A list of topics he 'contributes' substantively to is pretty short.</da> Of course, it doesn't _make_ him anything, but I don't think there's much of an issue of insinuating stuff for comic effect when he writes things which cry out for mockery in that vein. MaxAlex Swimming pool 22:46, 23 January 2010 (UTC) - Insinuating that somebody is a paedophile based on nothing more than a subjective view that much of his editing is "creepy" has no comic effect. Get a grip. Ajkgordon (talk) 22:57, 23 January 2010 (UTC) - By your use of the word 'subjective' I assume you know what it means. Would you not agree that comedy is also subjective? Just because you don't find it funny doesn't mean that it's not funny to others. Keegscee (talk) 23:04, 23 January 2010 (UTC) - You're right, hyperbole and exaggeration just aren't funny. Who knew. MaxAlex Swimming pool 23:40, 23 January 2010 (UTC) - Yes, of course, it's only my view that it isn't funny. But that's not my primary objection. My objection, which you seem to be unable to grasp, is that calling an opponent a paedophile based on nothing more than a vague "creepiness factor" is just plain wrong. Having a private snigger about it is not the same as making those insinuations on a public website. You see? Ajkgordon (talk) 09:15, 24 January 2010 (UTC) Ed creeps me out. X_X Pedobear (talk) 23:58, 23 January 2010 (UTC) - Where did this come from anyway/ My comments above? Because I'd say they pretty much imply that he isn't a pedo. However, somebody who calls himself "Uncle" teaches children and who claims to have lots of "information" on hard-corn porn needs watching. --PsygremlinRunāt! 09:27, 24 January 2010 (UTC) - No, not your comments - they just reminded me. - Interesting point you make though. The way I see it is that, as a culture (well, certainly in the UK), we seem to be obsessed with paedophilia. And it's become toxic. "Must be a paedo" seems to be the default position many people take when adults take in interest in children. And it doesn't take much imagination to think that Ed might teach children and be genuinely worried about the effects of pornography on them. Indeed, it takes rather more imagination to conclude that he might be a paedophile. Ajkgordon (talk) 09:41, 24 January 2010 (UTC) I'm coming out[edit] I think the trick to getting someones sock banned is to come out as them over here as soon as they get into just the tiniest little bit of trouble. Thus poor Sam is vaporized. --Opcn (talk) 22:27, 23 January 2010 (UTC) - I am everyone. Jaxe (talk) 23:20, 23 January 2010 (UTC) - I was once CharlieT, but I handed that account off. --Irrational Atheist (talk) 23:43, 23 January 2010 (UTC) - Actually I was (and still am 0_o) CharlieT. I can only presume Geo doesn't read this site as much as he should. EddyP (talk) 11:22, 24 January 2010 (UTC) WIGO fail[edit] Pravda in the post-soviet press is an entirely different publication, only the name has been retained. The Russian press (although becoming less and less so) is pretty free, and the Russian press in the 90's was the freest in the world, so Pravda's reporting shouldn't be mocked in a WIGO... JeffD (talk) 14:48, 24 January 2010 (UTC) - But what makes the whole thing especially funny, is that Pravda becomes a perfectly acceptable source for Rob "Reds Under The Bed" S, when it latches onto some bizarre conspiracy theory regarding Pres Barry. No barrel is too deep to scrape when it comes to digging up "dirt" on the Pres. I wonder how many other Pravda sources there are on CP. --Psygremlin講話 14:52, 24 January 2010 (UTC) Wandal Spree[edit] Looks like Andy has got his hands full. -- 15:52, 24 January 2010 (UTC) TK WIGO's = fucking boring[edit] I added TK to one just to see if it would bring the total vote down. It did. Based on my unscientific observation of this and other WIGO's mentioning TK, I conclude that mentioning TK in a WIGO, even without using his name, is the kiss of death. I propose that the WIGO vote code automatically permablock and promote any editor who adds a WIGO involving TK unless the user affirms under oaht that TK's presence in the WIGO is not simply to illustrate that he's a dick. We already knew that. CP is about Andy and his hillbilly pals' crazy, not TK's trollery. 18:22, 24 January 2010 (UTC) - As the author of the most recent TK WIGO, my feelings are hurt. Girlish whinge over, you have a point, as Terry Koeckritz is some kind of parodist/troll/thing, and WIGOing him only serves whatever kind of superiority complex he suffers from. SJ Debaser 19:11, 24 January 2010 (UTC) - I only try to WIGO TK if he makes a ridiculous edit, but some other ones obviously slip through. ListenerXTalkerX 19:15, 24 January 2010 (UTC) - TK's not a a dick. He's the Puck to CP's A Midsummer Night's Dream. Okay, he is a dick, but it's all in-character. -- Ask me about your mother 19:17, 24 January 2010 (UTC) - I think the problem is that TK is getting bored with CP, he's thrown so many toys out of his pram that he's got nothing to play with. I would suggest that it is also the reason that he's started hanging around here again. Lily Inspirate me. 19:25, 24 January 2010 (UTC) - I honestly don't see what the point is in WiGOing anything regarding TK, except when Andy actually says something supporting his actions. He's clearly not on board with CP's so-called mission, so it's basically the same as just about any other parodist/troll/wandal. --Kels (talk) 22:41, 24 January 2010 (UTC) "Bailed-out General Electric"[edit] And here I thought it was General Motors that got bailed out... ListenerXTalkerX 18:40, 24 January 2010 (UTC) - Clearly you were mistaken, because TK only posts the truthiest of truths. I also didn't know that NBC, while owned by GE, was the exact same company as GE. Glad he cleared that up for me. JazzMan 18:56, 24 January 2010 (UTC) PS: If you Google the phrase "General Electric bailout" you will find some, um, very reliable blog sources about how Obama is secretly bailing out GE through various evil green initiatives. - Perhaps the GE/GM confusion should be added to the WIGO? ListenerXTalkerX 18:58, 24 January 2010 (UTC) - Is the New York Times a sketchy blog? Not quite a "bailout," but is seems as if parts of GE are set up to suck on the government tit. TheoryOfPractice (talk) 19:00, 24 January 2010 (UTC) - (EC) That looks like insurance for some of their debt rather than a bailout payment. ListenerXTalkerX 19:03, 24 January 2010 (UTC) - Heh, sometimes I would argue that yes it is, but that's another discussion. As LX said, it's not a bailout so much as extending FDIC. Also, it's a little fuzzy whether a bailout of GE Capital (their lending division) would really count as a bailout of NBC (a subsidiary). The blogs I was talking about are more like this one. JazzMan 19:10, 24 January 2010 (UTC) - What's worse is that NBC is owned by NBCU, a joint corporation owned by GE and Universal Vivendi. It's being sold off to Comcast, at least 51% of the company. So it's NBCU, not GE, paying the bills. --Irrational Atheist (talk) 19:51, 24 January 2010 (UTC) Time out's make me bored[edit] I just noticed the most revisions special page Big surprise, Obama>Alger Hiss>Evolution>Homosexuality>Atheism ...--Opcn (talk) 06:30, 23 January 2010 (UTC) - Keep in mind a few months, nearly a year ago ♥ K e n D o l l ♥ deleted Evolution and restored it without its history, because he didn't know how to purge the cache. - π 06:36, 23 January 2010 (UTC) - It had been undeleted again, though. --Sid (talk) 12:38, 23 January 2010 (UTC) - It doesn't resurrect the page counter though. ГенгисGum disease 13:28, 23 January 2010 (UTC) - "This page has been accessed 412,933 times"? I have just eaten & stiltontalk 13:40, 23 January 2010 (UTC) - Those views are all bumped from zero. ГенгисGum disease 23:20, 23 January 2010 (UTC) - Ours is also quite interesting. I should note that a lot of the Phelps stuff must be reverting the Fred spam. moral 17:34, 25 January 2010 (UTC) TK has a small penis[edit] Wow, TK... Someone wants to improve CP, you rollback the edit. Andy signs off on the project, you ban the user. How small is your cock that you have to abuse that much power? Your 90/10 ratio is more like 100/0 at this point. What substantial edits do you make there? For you it's rollback, burn, ban and bitch. What an asshole you are. --Irrational Atheist (talk) 14:10, 23 January 2010 (UTC) - The prissy one won't respond to any questions, unless you e-mail him with your real name, and even then he won't, because he's scared of the truth. Which reminds me, just why is the colossal cunt hanging around here anyway, besides the fact that he's proving that CP's rules don't apply to admins? He doesn't engage in discussion, he makes what he thinks are witty comments. can't we just block him, like in the good old days, so he can crawl back to CP and carry on trolling everybody there? --PsygremlinHable! 14:21, 23 January 2010 (UTC) - Could be worse: we could work for him. TheoryOfPractice (talk) 14:35, 23 January 2010 (UTC) - sigh* Hookers don't count as employees even though you pay them, dude. --Kels (talk) 15:05, 23 January 2010 (UTC) - Maybe they do if you own the ranch. After all, he does live in Nevada. ГенгисGum disease 15:09, 23 January 2010 (UTC) - (EC) Ooh, labour camps are not part of the capitalist model. How convenient to forget the capitalist model of the southern plantations with their slaves. Lily Inspirate me. 15:10, 23 January 2010 (UTC) - - That sending money home sounds a lot like our migrant workers here. I wonder how many of TK's employees are legal immigrants? Oh and if it was a choice between working for TK or letting Ed babysit my daughters, Ed would win 9 times out of 10. --PsygremlinTala! 15:20, 23 January 2010 (UTC) Calm down, it's my fault not TK's. Could someone get me Andy's e-mail addy?--Opcn (talk) 23:26, 23 January 2010 (UTC) - It's all over the internet, like on his user page perhaps, and certainly on the articles about the bus trip to DC. I think it's Aschlafly@aol.com but I might be wrong. ħuman 02:52, 24 January 2010 (UTC) If in doubt, poke Ken with a stick[edit] After Ed triedimg (without lastingimg success) to essay-fy one of Ken's satellite articles in 2007, TK tries againimg with a more epic edit summary. Oh please, Ken, revert the move. We could use some wheel war entertainment. =D --Sid (talk) 19:55, 24 January 2010 (UTC) - "This is not an article, but rather an essay, so more properly belongs in the Essay name space. Still. Once again. Always." - It's true and it has good rhythm. I like it. -- =w= 19:58, 24 January 2010 (UTC) - It's not like anyone is going to rush to Ken's defense. Tetronian you're clueless 20:04, 24 January 2010 (UTC) - TK's bored. After his little anon stunt, he's trying to stir up some internal dissension for the lulz of it. I have just eaten & stiltontalk 20:17, 24 January 2010 (UTC) - Ken replies in an almost predictable way: Delete years (creation date: June 24, 2007) of edit historyimg and paste current version into the old place.img --Sid (talk) 22:26, 24 January 2010 (UTC) - The TK I know and fear wouldn't take that shit. EddyP (talk) 22:38, 24 January 2010 (UTC) - I'd call that a direct finger in TK's eye from Ken. You gonna take that shit? --Kels (talk) 22:39, 24 January 2010 (UTC) - Looks more like the cowardly way out to me. He could have just moved it back. Doing it like this is just kinda childish. -- =w= 22:41, 24 January 2010 (UTC) - You expected someone to do the more honorable thing? Specifically, Conservative? On Conservapedia? Yeah, right. - Oh, what am I saying. I can't comment against someone so cute. I agree with Mei. (Dance, Konami, dance!) NorsemanCyser Melomel 00:35, 25 January 2010 (UTC) - I'm sure the RW archives are full of the TK vs. Conservative feud since forever. TK's opinion of Ken doesn't differ so much from ours. Editor at CPmały książe 10:49, 25 January 2010 (UTC) - Evidence of ♥ K e n D o l l ♥ pussyfooting around can be seen in the fact that the talk page from the mainspace article will redirect you to the talk page for the essay, because Ken fails at wiki. Does this butt pirate have a youtube channel of his own? --Opcn (talk) 20:53, 25 January 2010 (UTC) RJJensen's got a project.[edit] And it has to do with NatGeo book covers for images of colonial states?img "Fair use" my butt. --Irrational Atheist (talk) 20:52, 24 January 2010 (UTC) - I know it's CP, and I know he's slapped a "fair use" disclaimer on it, but does this actually count as fair use? He's using it to illustrate an encyclopedia article on New France, not making any sort of commentary or parody on the work he's using. I was under the understanding that fair use of an image involved actually commenting on the image itself in a critical fashion, or parodying it. Am I way off the track here? --Kels (talk) 21:08, 24 January 2010 (UTC) - I've told Random House (publishers of the editions copied). Let's see. I have just eaten & stiltontalk 21:13, 24 January 2010 (UTC) - Joaquin Martinez would be worse if anyone could be sure he knew better. He's putting blatantly stolen images as window dressing on the American Jews article in the last few days. 02:11, 25 January 2010 (UTC) Wait, what? Professor?[edit] So, RJJensen wants to prove that there is no "Jewish conspiracy" by writing an article that shows how "very elaborately organized" the Jewish community is. Wow. Just, wow. TheoryOfPractice (talk) 04:58, 25 January 2010 (UTC) - I'm more amused by Andy's response. "I don't think we even referred to Barack Obama as the "first black president"". I think he's correct because they called him the first affirmative action president. YorickIs Joe Biden Eva Braun? 06:01, 25 January 2010 (UTC) - I think he actually went to lengths to claim that Obama didn't deserve the title of first black president, by claiming that we didn't know if any of the other presidents were black (yes really)76.121.56.100 (talk) - You mean this? -RedbackG'day 08:10, 25 January 2010 (UTC) - Astonishing how shameless he is sometimes. H. Randolph Twist (talk) 14:07, 25 January 2010 (UTC) - Not quite, that seems to discredit the claim that other presidents were black (and besides was written by Bharlan). See here: Quote: - )' - I see where you're coming from now. That's a bit of a turn around, in the version of the article I linked which has the Schlafly seal of approval, the article claims "President-elect Obama is multiracial; his father was part Arab and part black, and his mother was white". Andy himself tinkered with that sentence, and in an article explaining how extremists want us to believe certain US presidents were black, it comes across as "No he's not black, well, maybe a little but it's dilluted so it doesn't count!". See what happened there? A bit of time passes, and he goes from "Obama may be black but the other presidents may have been too" to "there were no former black presidents and Obama isn't black". Weirdos. -RedbackG'day 02:57, 26 January 2010 (UTC) - I think the only thing that matters to Andy here is to deny Obama acknowledgment of any sort of achievement, including being "the first black president".76.121.56.100 (talk) "The age of reason"[edit] "Also, more than half of the users claiming to belong to Christianity or otherwise are only mocking it, with added quips like 'Until the age of reason.'" How dare those covert anti-Christians mock Christianity with such obviously anti-Christian terminology! - Cuckoo (talk) 14:27, 25 January 2010 (UTC) - I was Catholic until the age of reason is also out of a George Carlin bit. Although I would think that this was a claim about not being Christian, rather than being a Christian. --Opcn (talk) 19:23, 25 January 2010 (UTC) is it just me...[edit] ... or does Karajou's explanation of Devils Towerimg (with no mention at all of Close Encounters! Sacrilege!) fly in the face of a 6,000 year old earth? --PsygremlinPraat! 18:41, 25 January 2010 (UTC) - Devils Tower was formed by molten igneous rock forcing its way into the area's sedimentary rock, cooling before reaching the surface, and the sedimentary rock being eroded away. What's wrong with that? obviously plenty of time in the last 6000 years for the forcing, cooling and eroding. I have just eaten & stiltontalk 18:51, 25 January 2010 (UTC) - Igneous, schmigneous; everyone knows that all rock is sedimentary and was deposited by the Deluge. ListenerXTalkerX 18:52, 25 January 2010 (UTC) - Yes, all rocks were placed as sediments. That doesn't mean that God didn't make all the different kinds of pretty rocks for us to enjoy. — Sincerely, Neveruse / Talk / Block 19:01, 25 January 2010 (UTC) - You forget your Flood Geology ! The flood laid all the sedimentry rocks and while it was still a bit moist a comet of water ice returned from its orbit and punched a hole through the drying sediment. The layer of water that supported the crust was now gone (waters of the deep) so there was just MOLTEN MAGMA ! underneath and it bubbled up through the new hole. This dried the mud to rock and formed the tower. See how Creation Scince solves these small mysteries. :) Hamster (talk) 19:06, 25 January 2010 (UTC) - I'm not a close follower of the Schlafly bros but wasn't erosion of Devil's Tower by the great flood one of Andy's pet topics on those pre-CP Talk Origins discussion boards? Lily Inspirate me. 19:54, 25 January 2010 (UTC) - Devils Tower: Andy v. the geologists! Epic pwnage. --Robledo (talk) 21:27, 25 January 2010 (UTC) - Wow. Andy: Here is something that's impossible to explain! That means God did it! Geologists: Explanation, and by the way the Catholic Church disagrees with you. Andy: Blasphemy! If I had my own private blog I could block you from replying to me. - And so, Conservapedia was born.... WodewickWelease Wodewick! 22:01, 25 January 2010 (UTC) - Hehe, yeah, what I loved was his continual insistence that it was "obviously" formed by erosion, without having a clue that such a claim would require explaining "how". ħuman 22:49, 25 January 2010 (UTC) - The question is, did Andy start CP to have somewhere he'd always be right under cover of a homeschoolers' project, or did he pervert a homeschoolers' project for that reason? --Kels (talk) 23:13, 25 January 2010 (UTC) - The latter. Before the world found CP, there was little use of the banhammer. When the world found it, he circled the authoritarian wagons, under the prodding vigilance of helpful centrists like TK, and now has his little corner of the blogosphere where he's always right. ħuman 23:41, 25 January 2010 (UTC) Negroes[edit] The CP article on African Americansimg has some classic parody. My favorites are: - "Colored" was popular until the 1950s, but now is generally out of favor except among some left groups. - Blacks were Republicans from the 1860s to the 1960s, but few who lived in the South voted. - The standard practice since Reconstruction is for black ministers to be political power brokers... Excellent. — Sincerely, Neveruse / Talk / Block 21:08, 25 January 2010 (UTC) - Capt -- =w= 21:10, 25 January 2010 (UTC) - (EC) The first two are correct (although the modern version of the term is "persons of color" rather than "colored people"). I suppose they got the idea for the "power brokers" business because the only black ministers they know are the politically active ones, like Al Sharpton and Jeremiah Wright and the Martin Luther Kings. ListenerXTalkerX 21:13, 25 January 2010 (UTC) - I know of a another group of people who still refer to blacks as "colored". And, gee, I wonder why blacks weren't voting in the south in the 1860s-1960s? Why the fuck would that be? Huh... — Sincerely, Neveruse / Talk / Block 21:15, 25 January 2010 (UTC) - That lot prefer "n****r," I think... ListenerXTalkerX 21:20, 25 January 2010 (UTC) Andy is a jaywalker[edit] I shit you not, Andy Schlafly jaywalked in front of my car on D St. on my drive home. He runs exactly like you would think after hearing him talk. More of a prance, really.Cooter (talk) 23:38, 22 January 2010 (UTC) - Please tell me that you rolled down your window and did a shout out --Opcn (talk) 23:42, 22 January 2010 (UTC) - Oh, I wish. I didn't realize who it was until he had pranced across the street and it was too late to do anything. I yelled out, "Holy Fuck!" to my baby daughter, but she didn't appreciate the gravity of the sighting. I should say that while traffic was completely screwed on the way home, the anti-abortionites sure do a lot better job cleaning up than the dirty hippies that are usually behind the protests around here.Cooter (talk) 13:48, 23 January 2010 (UTC) - I could imagine Cooter doing that: Andy stops in the middle of the street, pauses for a moment, turns around slowly (without effort, like he spins on a swivel), and gives cheeky smile with the closed eyes from the Colbert Report. He then proceeds to laugh, really low-like, then another moment of pause. He turns around, and slowly continues jaywalking. NorsemanCyser Melomel 23:58, 22 January 2010 (UTC) - It's more of a cluck than a laugh --Opcn (talk) 00:14, 23 January 2010 (UTC) - "Ha! Ha! Ha!"WodewickWelease Wodewick! 03:04, 23 January 2010 (UTC) - He didn't walk in front of your car, stop, turn and look and say "Motherfucker!"? CrundyTalk nerdy to me 12:40, 25 January 2010 (UTC) March[edit] Nothing yet on the massed hordes of Conservapædians on the March for Life Fundy march. We want photos! I have just eaten & stiltontalk 13:27, 23 January 2010 (UTC) - probably went as well as Andy's university talk, which has been conveniently forgotten. Not to mention the National Strike - hey, TK, how'd your day at home go? --PsygremlinHable! 13:38, 23 January 2010 (UTC) - Ask and ye shall receive. --PsygremlinParlez! 15:11, 23 January 2010 (UTC) - Thta's an old one. From the EXIF - "Date and time of data generation 00:01, 1 January 1980". Or else he only gets his camera out once a year and then finds the badderies are flat. Lily Inspirate me. 15:19, 23 January 2010 (UTC) Nah, it's a recent shot, regardless of the date stamp--he must be the kind of guy whose VCR flashes 12:00 all the time. TheoryOfPractice (talk) 16:22, 23 January 2010 (UTC) - Come off it, did you think I was serious? Digital cameras didn't even exist back in 1980. Lily Inspirate me. 08:14, 24 January 2010 (UTC) - Hehe, since my camera resets itself every time I change the batteries, I don't bother to dig through the menus and fix things like the date and time it thinks it is. I suppose if there was a critical reason to have that meta-data be correct I might though. Why don't they make these things so they remember through battery removal? Hell, they've got a great big memory card in them most of the time... why not add a few k of non-volatile memory for the clock? ħuman 01:38, 25 January 2010 (UTC) Anon?[edit] There's an (alleged) anon assault taking placeimg. I have just eaten & stiltontalk 14:35, 24 January 2010 (UTC) - Hmmm takes place at the one moment of the day when even TK and his banhammer are absent. Coincidence? --PsygremlinHable! 14:39, 24 January 2010 (UTC) - My word Psy, you're more suspicious than me, but Hmmm? I have just eaten & stiltontalk 14:42, 24 January 2010 (UTC) - Database is locked--was gonna have a helpful sock start to clean up. Then I saw that over 500 pages had been messed with. Wow. Nasty. TheoryOfPractice (talk) 14:43, 24 January 2010 (UTC) - [3]img link. I have just eaten & stiltontalk 15:04, 24 January 2010 (UTC) - I lol'd at Andy's actions. He takes all that time to block one wandal (last 500 edits anyway), then locks the database for only 90 minutes? "I did my part. Fuck it. I'll let someone else fix it later." Who wants to bet Andy will do little or no cleanup at all? NorsemanCyser Melomel 15:23, 24 January 2010 (UTC) - That's a lot of damage. Two questions: how an it be undone, and while the database is locked, can they block the accounts? EddyP (talk) 15:35, 24 January 2010 (UTC) Won't it be easier to just restore from the last backup or something? Who cares if a few good faith edits by the plebes get undone? TheoryOfPractice (talk) 15:45, 24 January 2010 (UTC) - Backups are for whimps and Liberals. StarFish (talk) 15:46, 24 January 2010 (UTC) - Exactly (almost) one year later. IIIIIIIInnnnterrrressstiiing. TheoryOfPractice (talk) 15:57, 24 January 2010 (UTC) - Anyone know if anything on this scale has happened to CP before? StarFish (talk) 16:10, 24 January 2010 (UTC) - Call the Cinncinati office of the FBI, they willwon't be able to help. DogPMarmite Patrol 16:36, 24 January 2010 (UTC) - Hundreds of articles vandalized, but Andy still needs to fuel a light persecution complex: "clearing out vandalism; not surprising that vandals repeated attacked this entry"img --Sid (talk) 16:57, 24 January 2010 (UTC) - Karajou, Joaquin, and Wuhao1911 are cleaning up the mess. Nice to see some articles haven't been updated since I've been there, almost a year. Aboriginal Noise What the ... 16:59, 24 January 2010 (UTC) - I'm loving how Andy made a few token reversions and is leaving the vast majority of the work to others. Maybe he's planning a new article: Liberal Anonymity EddyP (talk) 17:05, 24 January 2010 (UTC) - What a total douchebag. He's got the nuke extension installed for his permission level. He can rollback all of a user's edits with a single click, yet he has Woohoo5iu134 toiling away there like a field hand. 17:13, 24 January 2010 (UTC) - I think NUKE only allows deletion of all articles createed by a user. I have just eaten & stiltontalk 17:19, 24 January 2010 (UTC) - Yep. It's mass delete, not mass rollback. --Sid (talk) 17:22, 24 January 2010 (UTC) - Oh. Then I take back the douchebag remark. He's a kindly and beneficent leader. It's only through hard work that one truly learns the meaning of thrift. Or some shit like that. 18:15, 24 January 2010 (UTC) - I'm surprised they don't use a bot to correct the vandalism. Is it that hard to write one for this sort of cases? — Pietrow ☏ 19:13, 24 January 2010 (UTC) - Yes, this would be a splendid opportunity for Uncle Ed to put his wiki-programming skills to good use. Lily Inspirate me. 19:21, 24 January 2010 (UTC) - There's only been one "/24" and one "/16" IP block since and them by JPatt. TK mustn't want to block himself for when he wants to do it again. I have just eaten & stiltontalk 20:21, 24 January 2010 (UTC) - I could write a mass rollback bot for them. Hey TK, I'll trade you a bot for an admin account. CrundyTalk nerdy to me 08:54, 26 January 2010 (UTC) Blog[edit] It's hard to say it's not a blog when you get 'articles' like the March For lifeimg - just showing Andy's personal photos and not much else. Also comparing the photos from 2009 to 2010, it would appear this year's event was much mroe low key. Maybe it's just the weather but everyone is looking cold and pissed off. StarFish (talk) 19:21, 24 January 2010 (UTC) - Somebody should explain the "gallery" tag to Andy sometime. ħuman 01:23, 25 January 2010 (UTC) - The weather in the DC area Friday was nice, for January. MDB (talk) 10:55, 25 January 2010 (UTC) - I also like that "A stunning new report with new pictures is available here" - at TerryH's blog. Lily Inspirate me. 16:39, 25 January 2010 (UTC) - That article is funny. You want to know what the real tragedy is? Missing the Molly Hatchet concert because you had to spend your beer money on an abortion. 17:14, 25 January 2010 (UTC) - Hehe... and "New Jersey conservative activist Andrew P. Schlafly," someone should direct Terry to our article so he can get Andy's MI right - or better yet, stop using it, since Andy doesn't use it. ħuman 23:50, 25 January 2010 (UTC) Andy and ethnicity[edit] Andy sez: "The reality is that almost any ethnic group today holds political positions that span the spectrum from left to right. Indeed, a strong argument can be made that race is no longer directly relevant [to politics]." Coming from the same guy whose blog has special sections on Hollywood values, mainstream media bias, a 50-cite article on ACORN, and an article on Barack Obama that specifically mentions the "Black liberation theology" of his church as well as what percentages of the Muslim and Black votes he received. No racial overtones there? Ultimately I think Andy's problem with the article had less to do with ethnocentrism and more to do with the fact that the article talks about a lineage of American intellectualism that, inexplicably, doesn't trace itself back to stalwart Protestant Values. WodewickWelease Wodewick! 17:26, 25 January 2010 (UTC) - (1) Mr. Schlafly is a Catholic. (2) Racial identity politics (e.g., "black liberation theology") are entirely different from race. (3) The racial overtones are in the "Affirmative Action President" article. ListenerXTalkerX 17:36, 25 January 2010 (UTC) - There is no evidence that Andy is a practicing Catholic. In fact, there is evidence that he is not a Catholic. — Sincerely, Neveruse / Talk / Block 17:51, 25 January 2010 (UTC) - Not this again. Of course he's Catholic. His mother's a catholic. His son is too. Internetmoniker (talk) 18:09, 25 January 2010 (UTC) - And his brother is gay. None of this proves he's a Catholic. He takes many positions that are not Catholic. He apparently goes to a Congregationalist church. — Sincerely, Neveruse / Talk / Block 18:14, 25 January 2010 (UTC) - I used to be a Catholic. It started innocently with petting a cute kitten, but I ended up not getting through the day without like a dozen cats. I lived in squalor, throwing cats at random passers-bys. Remember kids, it just takes a single purr to get addicted. --GTac (talk) 18:18, 25 January 2010 (UTC) - The minister at that Congregational church said explicitly that Mr. Schlafly is not a member. ListenerXTalkerX 18:22, 25 January 2010 (UTC) - That's good to know. Have any priests claimed responsibility for him? — Sincerely, Neveruse / Talk / Block 18:26, 25 January 2010 (UTC) - "[Dara] Ó Briain has said he sees himself as an atheist, but “ethnically Catholic”: “I’m staunchly atheist, I simply don’t believe in God. But I’m still Catholic, of course." found all over the web. He once quipped(!love that word): "A Catholic who joined the Taliban would still be a Catholic, albeit a bad Catholic." The point being: Once a Catholic, always a Catholic. I have just eaten & stiltontalk 18:45, 25 January 2010 (UTC) - According to the Catholic Church, yes, but not anyone else. ListenerXTalkerX 18:53, 25 January 2010 (UTC) - There's not much question that he was Catholic, but a lot of things changed for Andy over the years. He had many insights. Discovered a lot of truth. Got set free. — Sincerely, Neveruse / Talk / Block 18:57, 25 January 2010 (UTC) - If Mr. Schlafly had removed himself from the Catholic Church upon becoming a creationist ten years ago, I doubt his son would identify as Catholic. ListenerXTalkerX 19:00, 25 January 2010 (UTC) - Baseless speculation. Here's more of it: Andy Jr. could be trying to stay on the good graces of Phyllis. — Sincerely, Neveruse / Talk / Block 19:02, 25 January 2010 (UTC) - It's actually speculation based on circumstantial evidence if you say he is Catholic. The opposite however, is baseless. Internetmoniker (talk) 19:35, 25 January 2010 (UTC) - By the way it is possible to leave the Catholic church. You have to ask the church you were baptised in to strike you from the baptism records. Excommunication by higher ups would also do the trick. Internetmoniker (talk) 19:36, 25 January 2010 (UTC) - It was an argument from incredulity. His argument is as devoid of logic as mine. I guess I was taking "baseless" as "not based in logic". — Sincerely, Neveruse / Talk / Block 19:41, 25 January 2010 (UTC) - (EC) Excommunication removes you from the Catholic communion, but does not remove you from the Catholic Church. Also, since Mr. Schlafly was raised a Catholic and married in a Catholic ceremony, it is perfectly reasonable to suppose he is one — albeit one flirting with heresy — until given hard evidence to the contrary. - Neveruse, it is perfectly reasonable to suppose that if Mr. Schlafly had converted to Protestantism while his children were still young, he would have made them convert as well. ListenerXTalkerX 19:44, 25 January 2010 (UTC) - There's an old joke about someone who was caught up in an argument between a bunch of Catholics and Protestants in Glasgow. When challenged by one of the diisputers he replied that he was an atheist. Ah, but are you a Catholic or a Protestant atheist? Lily Inspirate me. 19:49, 25 January 2010 (UTC) - It's reasonable, but not a logical argument. I'm a little shocked you don't understand this, but I think it's just trolling. — Sincerely, Neveruse / Talk / Block 19:50, 25 January 2010 (UTC) - Anyway, I don't see how Andy's "official" faith affects the argument. He is profoundly a Protestant in his social and theological outlook. He believes in the Bible as sole authority, grace as sole source of salvation, I've never seen evidence that he's too fussed about sacraments or saints, he is a young earth creationist. That all points to Protestant. - Andy, like many Christians, is fundamentally an authoritarian, that is: he believes what he's told to believe and then he reads the Bible and thinks it proves that what he already believes is true. WodewickWelease Wodewick! 21:53, 25 January 2010 (UTC) - He has also said that the Pope speaks with the authority of St. Peter, contrary to the historical Protestant position that the Pope is the Antichrist. This put him in conflict with PJR. [4] ListenerXTalkerX 21:56, 25 January 2010 (UTC) - He's also brushed off what the Pope says. Telling the Pope he was wrong about the death penalty comes to mind. I believe he concluded that papal encyclicals are only true if he agrees they are true. — Sincerely, Neveruse / Talk / Block 21:57, 25 January 2010 (UTC) - Mr. Schlafly could not have called the Pope infallible if he were not still a Catholic. ListenerXTalkerX 22:18, 25 January 2010 (UTC) - Therefore Mr. Schlafly is not Catholic. — Sincerely, Neveruse / Talk / Block 22:28, 25 January 2010 (UTC) - He's a Cafeteria Catholic, like most of 'em (probably including the pope) I have just eaten & stiltontalk 22:30, 25 January 2010 (UTC) - I don't believe in such a thing, but still...No evidence he is a Catholic, lots of evidence that he is not. Doesn't Andy think everyone who wrote the Bible did so with the power of infallibility? God...wouldn't it be a lot easier if we could just ask him? — Sincerely, Neveruse / Talk / Block 22:34, 25 January 2010 (UTC) - Technically Andy's position is not that the Pope is right, it's incredulity that the Pope would ever disagree with Andy, that would be a reversal of the natural order of the universe. "I'm sure no pope" has endorsed evolution, then when proven wrong by an encyclical he says it is "logically contrary to faith." - Like I said above, he believes X then he goes to find authorities and reads X into whatever they have said. The Pope was just an innocent bystander of Andy's craziness. WodewickWelease Wodewick! 22:44, 25 January 2010 (UTC) - Andy is just a catholic who practices doublethink at times. But he would certainly never rebel and convert to another denomination. I just don't see that happening. Do you honestly believe he has the guts to do something like that? Saying things on his blog is one thing, but doing something drastically life-changing in support of his developing twisted views, nah. Internetmoniker (talk) 22:59, 25 January 2010 (UTC) - In a rare upset CP has a passable article on something religious/political --Opcn (talk) 01:28, 26 January 2010 (UTC) - Except their examples only include liberal deviations from Catholic theology. It doesn't include conservative deviations, like supporting the Iraq War or the death penalty. (Although, to be fair, it's my understanding that, strictly speaking, the RCC does not oppose the death penalty; it just believes there is no place for it in a society where life imprisonment is a realistic alternative.) MDB (talk) 13:43, 26 January 2010 (UTC) "Like belongs with like"[edit] I think TK is objecting to balkanization there... ListenerXTalkerX 21:54, 25 January 2010 (UTC) - I think balkanization is splitting up by ethnic groups. TK objects in that diff to splitting up of ethnic groups. Coarb (talk) 22:09, 25 January 2010 (UTC) - A conservative inveighing against balkanization? Ethnocentrism is one of the defining elements of authoritarian conservatism. Read this whole book, or here for the tldr version. Here's an insightful quote from the book:. (The Authoritarians, p. 87) - Sound like anyone we know? - Dr. Altemeyer then explains why parody works: authoritarian conservatives rely deeply on social reinforcement to reassure themselves of their beliefs. So anyone who comes along and sings the right tune.... The need for social reinforcement runs so deeply in authoritarians, they will believe someone who says what they want to hear even if you tell them they should not... they rely on the authorities in their lives to provide their opinions...! - In other words you can email Andy all you like that TK is a parodist (as PJR vainly attempted), but Andy has a deep psychological need to surround himself with people like TK. - Conservapedia itself is a massively ethnocentric place of course, with an "us vs them" bunker mentality that's out of control. The vast majority of Americans would be to Andy, if they dared to start editing, Deceitful Liberals. WodewickWelease Wodewick! 22:26, 25 January 2010 (UTC) - Spare me the quotes from Bob ("People Who Take Too Much Exception to My Politics Have a Mental Disorder") Altemeyer, if you please. Nevertheless, as paradoxical as it may seem, there is an element of ethno-centrism in this case; the American national identity involves the melting pot, which means that making a big deal out of one's pre-melting-pot ethnic identity is frowned upon. See Hyphenated American. ListenerXTalkerX 03:50, 26 January 2010 (UTC) - Authoritarian conservatism is not a political identity, it's a psychological orientation - "conservatism" here meaning defending the moral authority of the establishment, the status quo. The Soviet party faithful were authoritarians, in fact studies showed that the hawks on both sides of the Cold War were psychologically horses of the same color. - As for the retarded "melting pot" metaphor, it conveniently ignores that at every step of the way conservatives fought to keep ingredients out of the bowl - Irish, Jews, Blacks, Mexicans, you name it, at different points in history every ethnic minority group in America was assailed by conservatives as being unworthy of "mixing" its genes with the WASP establishment. Even today. - Evangelicals can claim they believe "We're all God's children" as much as they want, I'll believe them when they stop tuning in to TV hosts worrying about America's white-minority future. WodewickWelease Wodewick! 04:57, 26 January 2010 (UTC) - "Authoritarian conservatism is not a political identity..." Moving the goalposts much? - "As for the retarded 'melting pot' metaphor..." It ignores no such thing. The concerns (at least with the Irish and the Jews) were more cultural in nature. - "Evangelicals can claim they believe 'We're all God's children'..." Funny thing about that; evangelicals tend to be one of those multi-racial bunches... ListenerXTalkerX 05:38, 26 January 2010 (UTC) - LX, on 2 you're just wrong and on 3 you're so far from right you must be as am as drunk I ħuman 09:20, 26 January 2010 (UTC) - 2: How so? The primary reason for opposition to Irish immigrants was that they were Catholics, and it was only the Nazis who tried to portray Jews as a "race." Once the groups had assimilated (and American culture had altered itself in the process, which is what the melting pot was all about) only fringe groups remained very much opposed to them. - 3: Are you speaking from experience, from statistics, or from an ignorant generalization that some hack plucked out of the air in aid of pulling a Godwin's? ListenerXTalkerX 18:09, 26 January 2010 (UTC) Thought this was funny...[edit] ...so I thought I'd capture itimg Aboriginal Noise What the ... 02:19, 26 January 2010 (UTC) - eeeerrrr, can you give me a hint? Acei9 02:22, 26 January 2010 (UTC) - If you insist. Mostly because the word "Asshole" appears in the statement, on CP, which means that he has somehow surpassed the filter; and as a secondary aside, the user is in the same state of mind as I am currently. Aboriginal Noise What the ... 02:38, 26 January 2010 (UTC) - I think ace saw this instead. I did too when I first pressed your link. Internetmoniker (talk) 03:00, 26 January 2010 (UTC) - The link you posted before was not the same as the one above now. Acei9 03:00, 26 January 2010 (UTC) - I suspect that Drunk is an operative word --Opcn (talk) 04:16, 26 January 2010 (UTC) - And you'd be correct. I did stick the wrong link there, saved from an earlier edit. You folks are quick on the draw, as I changed the link within a minute. Some people are good at drunk-editing, some fail miserably. I guess I'm the latter. Aboriginal Noise What the ... 11:58, 26 January 2010 (UTC) "Saint Ronnie?"[edit] This WIGO should be commented out; it is obvious that Mr. Schlafly is talking about the word rather than the economic policy it denotes. ListenerXTalkerX 03:52, 26 January 2010 (UTC) - No, it should be voted down. Best way to get rid of lame WIGOs is through shaming their writers. TheoryOfPractice (talk) 04:15, 26 January 2010 (UTC) - True; I suppose this is not quite in the libel range. ListenerXTalkerX 04:21, 26 January 2010 (UTC) - Because there have been a plethora of bad WIGOs lately so I am going to save it. This is more of an excuse to use the word plethora though, so I take no credit for the result. YorickIs Joe Biden Eva Braun? 05:20, 26 January 2010 (UTC) - Thanks for providing me an excuse to make the pedantic point that it should be "has been a plethora". Silly twit (talk) 10:32, 26 January 2010 (UTC) - This one was mine, as I continue a string of negative WIGO's...I totally misread the linked diff. 17:07, 26 January 2010 (UTC) CЯacke® The register misses the point.[edit] I'm pretty sure that Rational wiki is responsible for the bulk of the grad school traffic at conservapedia. Not everyone who visits a site supports it. --Opcn (talk) 07:43, 26 January 2010 (UTC) - I got the joke and voted it up. ħuman 08:16, 26 January 2010 (UTC) - How does the Register even know the education levels of website viewers? They must have a very small sample from which to base conclusions. Since Andy is Conservapedia and Andy has two degrees, I guess that makes a pretty high lvel of education coupled with an extremely high level of idiocy. But of course, the only people we know actually use CP are his homeschoolers, that should bring the average down a lot. Also, does that article actually say that the teatards are an intelligent group of people? That is wrong on so very many levels. DickTurpis (talk) 13:59, 26 January 2010 (UTC) - Various site traffic trackers have some concept of education level of the household or machine. It implies you've got that extension installed in your browser. --Shagie (talk) 18:02, 26 January 2010 (UTC) - ♥ K e n D o l l ' s ♥ favourite tool for these statistics is Quantcast. They give Conservapedia 120% of the average number of grad school visitors and RationalWiki 134%. - π 23:06, 26 January 2010 (UTC) Expert WIGO[edit] Awesome. Watch the reply get reverted and oversighted as soon as possible. Andy has a weird habit of pwning himself. CrundyTalk nerdy to me 13:27, 26 January 2010 (UTC) - I think it would have been better if the user didn't include the Lenski part in his reply. "Do you accept only the opinions of experts?" would be enough to trigger BotP backtracking by Andy. Now I think he's just getting a Trolling/Liberal Trolling: Bye. Internetmoniker (talk) 13:55, 26 January 2010 (UTC) - No way, andy actually repliesimg with an attack against Lenski's education. CrundyTalk nerdy to me 13:58, 26 January 2010 (UTC) - Remember, Andy thinks he won against Lenski. But has BotP been downgraded to just not relying on experts? Broccoli (talk) 15:01, 26 January 2010 (UTC) - DanL added Andy's handling of the Lenski debacle as an example of the best of the public. It hasn't been removed since DanL was outed as a prodst. Does Andy really think he handled the Lenski affair well? There aren't many links to the correspondence on CP; I think Andy's only grudgingly keeping the letters on CP because he has to. 62.56.68.180 (talk) 00:03, 27 January 2010 (UTC) Tea Paaarrrtay[edit] Laugh at the teabaggers. Want to see a true grassroots movement's convention? Try this one. More than half the cost with much bigger names. --Irrational Atheist (talk) 14:00, 26 January 2010 (UTC) - "Less than", Shirley? MaxAlex Swimming pool 15:14, 26 January 2010 (UTC) - Sure, I was running out the door when I finished that, and meant that the cost more than halves the price tag of the teabagger orgy. My error, but I'll leave it so people don't get confused by your reply. --Irrational Atheist (talk) 15:22, 26 January 2010 (UTC) It begins[edit] Andy has started the lectures on writing.img MDB (talk) 15:10, 26 January 2010 (UTC) - - His explainations of why writing is important is cringeworthy. E.g. "Writing is essential to Christianity. Each week there are readings from the Bible that help enlighten everyone and strengthen our faith. Someone wrote the books in the Bible to make this possible." CrundyTalk nerdy to me 15:12, 26 January 2010 (UTC) - Anyone spotted the typos in his article about how to write property? Here's your starter for 10: - "Houghton College in New York recently recently started taking the highest critical reading and math scores for the SAT" - CrundyTalk nerdy to me 15:16, 26 January 2010 (UTC) - Andy's going to be full of lulz with this one. "Example 4: In the beginning was the 'λόγος', and the 'λόγος' was with God, and the 'λόγος' was God. (John 1:1). What does the Greek word 'λόγος' mean? (a) evil (b) light (c) universe (d) chaos (e) word" Let's see... Nope, no Bible passages in the SATs. No Greek translating in the SATs. Anyone mind if I setup a page to rip apart, as an English major, the writing lectures? --Irrational Atheist (talk) 15:21, 26 January 2010 (UTC) - Please do! I have just eaten & stiltontalk 15:26, 26 January 2010 (UTC) - That question, while not SAT-style, is an interesting problem, though based purely on textual analysis, I think either b or e are reasonable choices, and c is a decent one, though not as good as the other two. Of course, if you know that passage, as Andy's students are likely to, its a slam-dunk to fill in e. It would be kind of like asking "Mary had a little _______; its fleece was white as snow" to anyone who had gone through American nursery school and kindergarten. MDB (talk) 15:29, 26 January 2010 (UTC) - I'm looking forward to the homework assignments. - Explain why Phyllis SchlaflySarah Palin has been far more important than the following "women": - Hillary Clinton - Oprah Winfrey The Virgin MaryEleanor Roosevelt - Discuss the lack of humor before Christianity. - Disprove evolution. - Imagine you are running for President. Explain how you will - Hire the best of the public to work on your campaign. - Overcome liberal media bias. - Appeal to the tea party movement. - Take a long-accepted translation of an ancient work and remove liberal bias from it. - MDB (talk) 15:23, 26 January 2010 (UTC) - Does he actually know what the syllabus is for the SATs or is he making it up (or both)? CrundyTalk nerdy to me 15:29, 26 January 2010 (UTC) - I second that, Irrational Atheist. I just ran λόγος through Google translate, for what it's worth, and the translation is "reason", not one of the listed options. However, that may be because of context.Nick Heer 15:30, 26 January 2010 (UTC) - Looks like it's translated as the word (of God, in this context). My mistake. Nick Heer 17:13, 26 January 2010 (UTC) - This is cringeworthy: And it's still 11 months to Christmas!img But we get our presents in January! --Irrational Atheist (talk) 15:31, 26 January 2010 (UTC) - "example of paralyzed person in church" - What the FUCK? CrundyTalk nerdy to me 15:37, 26 January 2010 (UTC) - It's too funny! Public speaking is really nothing more than reading what has been written down?img Please, Andy, more of your stupid insights! I need the humor. --Irrational Atheist (talk) 16:09, 26 January 2010 (UTC) - No, no, a thousand times no. Unless you are someone whose entire job revolves around public speaking (minister, politician), the absolute surest way to guarantee a dull speech is to just "read what is written". I've set through a talk given by someone who was obviously reading the presentation directly from a sheet of paper. It was so dull, I found myself hoping for a massive coronary just to get me out of the auditorium. MDB (talk) 16:37, 26 January 2010 (UTC) - Exactly. Even speech classes emphasize how to speak to people, how to maintain eye contact, how to use your hands properly, how to speak to the back of the room and the front of the room at the same time, how to deal with a question and answer approach, and so forth. Which is why I found it hilarious that Andy feels that public speaking is nothing more than reading what has been written. No wonder he tanked on Colbert. --Irrational Atheist (talk) 17:19, 26 January 2010 (UTC) Ugh. I haven't looked too much at the other courses Conservapedia offers, but aren't lectures supposed to offer information that is actually useful? This lecture has zero useful information, apart of a) common sense morale boosting (yes, writing is important; yes, you can do a whole lot of stuff just by writing; yes, if you write you'll get better and you're able to use fancier words eventually), and b) stuff that's pretty irrelevant as far as writing itself goes (I don't remember darn about the "tips" and requirements that were part of our equivalent of SAT, 10-and-some years ago, but I sure remember a lot of stuff that were said in our language and literature classes). I'd like to ask Andy: Where's the big plan? Where's the awesome, overwhelming display of erudition? Where's the part where you show that this course is going to be informative? Right now, all I know is that a) writing sure is important, b) SATs are confusing, but some people paid good money to get their kids educated, hence this course exists, and c) this course takes 15 weeks. Come on! Give us a reason to care! --wwwwolf (barks/growls) 16:15, 26 January 2010 (UTC) - Give him time. This is just the introduction, and a certain degree of fluff is to be expected. (Great googaly moogaly, I'm defending Andy.) MDB (talk) 16:33, 26 January 2010 (UTC) - Slightly related, DMorris needs a refresher course in punctuation marks. --Irrational Atheist (talk) 17:24, 26 January 2010 (UTC) - he left a bit out. "Someone wrote the books in the Bible to make this possible. However, they didn't talk English as good as I do, which are why I are writings the Bible all overs again and learning yous how to writes proper too." --PsygremlinTala! 17:28, 26 January 2010 (UTC) I'm sorry, but shouldn't AndyPandy's lectures on writing be limited only to: Don't Do It. 'Cause as we all know, the more you write the more liberal you are.-- Spirit of the Cherry Blossom 18:56, 26 January 2010 (UTC) - I see Andy's flipflopping gain. Before it was "Don't read a book, write a book!", then it was "Don't write a book!"img, now he's back to his old way. I guess the only consistency is that he always against the reading of books. Go forth and learn, young homeschoolers. DickTurpis (talk) 19:31, 26 January 2010 (UTC) A Brief History of Logos[edit] Before Christianity were the stoics. One of the earliest stoics was Heraclitus who used the word logos as a core part of the philosophy. Logos was what separated humans from animals - the ability to talk, to use words, to understand reason. It was an attempt to understand the reason of the universe. Things come and go in accordance with logos. The good times and the bad times are both part of the larger balance of the universe, and logos. Being good in stoic philosophy was to be in accordance with logos - in harmony with the universe. Good things happen, bad things happen. And thus, we have a stoic person today - that takes the good with the bad. Anyways, when the Gospel of John was being written it was trying to appeal to the greek intellectuals (Matthew was written for the Jewish people - showing a close alignment of Jesus with the OT prophecies). And thus, the author of the Gospel of John wrote "In the beginning was logos and logos with God and logos was God" - trying to draw stoicism and Christianity together. Word and Reason are both acceptable translations of Logos. For a good read of stoicism, I suggest Heraclitus [5][6] Epictetus (born a slave) [7] and Marcus Aurelius (Roman emperor) [8]. --Shagie (talk) 18:36, 26 January 2010 (UTC) DWiggins[edit] Just blocked by TK "Troublemaker / Prevaricator: talk,talk, talk, argue, argue, argue. Bye-bye, Brit". I thought they'd made a lot of good edits no? CrundyTalk nerdy to me 15:35, 26 January 2010 (UTC) - TK must not have taken his meds today. Shortening a ban on a university in a liberal city? Tsk tsk. --Irrational Atheist (talk) 15:56, 26 January 2010 (UTC) - "password thief"? CrundyTalk nerdy to me 16:03, 26 January 2010 (UTC) Oh, please, TK, make my day![edit] A MYOB ban on User 188. PLEASE!img I'll stop calling you an asshole for the length of the ban. Pinky swear! --Irrational Atheist (talk) 16:15, 26 January 2010 (UTC) Eisenhower[edit] was liberalimg? --PsygremlinRunāt! 18:37, 26 January 2010 (UTC) - He did say something to the effect that a political figure who opposes social security and farm programs will become persona non grata, and he said that we should guard against the Military-Industrial Complex. ListenerXTalkerX 18:42, 26 January 2010 (UTC) - Andy rewrites history with his magic hands once more. EddyP (talk) 18:45, 26 January 2010 (UTC) - If he strikes too many more Founding Fathers off the "conservative" list, he will alienate most other right-wingers; his removal of Jefferson, who believed in small government and made attempts to pay down the national debt, speaks volumes. ListenerXTalkerX 18:51, 26 January 2010 (UTC) - Eisenhower wasn't exactly liberal, but he wasn't terribly conservative. I'm surprised he removed Lincoln from the list. Isn't that one of the Republicans go-to guys to show what a great party they are? Hasn't Andy tried to claim Lincoln as one of his own? Of course, Lincoln was hardly conservative, but that never stopped them before. DickTurpis (talk) 18:53, 26 January 2010 (UTC) - Lincoln, the conservative. Jefferson, the fiscal conservative. ListenerXTalkerX 18:58, 26 January 2010 (UTC) - For his day, Ike was a centrist. I remember hearing once that the only reason he ran as a Republican was that they talked him into it first; both parties wanted him, because his election was a sure thing, because of that whole "winning World War II" thing. MDB (talk) 19:19, 26 January 2010 (UTC) - Let's face it, if you're not Reagan, then you're a libral. No argument. Conservatism was invented in 1981 and anything else is a poor imitation of the One True Conservative. Worm(t | c) 21:38, 26 January 2010 (UTC) Laager mentality[edit] I think Andy said in his transcript of that radio talk with mummy, that "anybody can edit CP". Well, I see 48-hours after TK allowed Anon to run amok, account creation is still turned off. (and no, Ace, nobody mentioned lager). --PsygremlinSpeak! 19:00, 26 January 2010 (UTC) - By "laager" do you mean the military fortification? ListenerXTalkerX 19:03, 26 January 2010 (UTC) Tim Tebow[edit] Tim Tebow is in the news because he will be starring in an anti-abortion ad during the Superbowl. It got me thinking: given that Tebow was a homeschooler and is a figure that almost everyone recognizes, Andy doesn't talk about him that much. CP's article on cp:Tim Tebow is about as stubby as a non-Ed article gets. Any thoughts? Keegscee (talk) 01:04, 27 January 2010 (UTC) - I think he is mentioned on Example of bias on Wikipedia and one of the Conservative Parables is a fairly obvious biography of the guy. - π 01:51, 27 January 2010 (UTC) Hey Rob?[edit] What's with the title of this horrific image?img Who's Kara? Can we see her in her yellow dress? TheoryOfPractice (talk) 19:15, 23 January 2010 (UTC) - It looks like he got his CP uploads confused with his private pretty girl pictures. The 'Kara Yellow Dress 08 Cover' refers to (Warning: Kinda NSFW, definitely creepy) this picture (which has that exact title) I'm sure it's in plenty of other places. What this tells us about Rob's mind I shudder to think. EDIT Looks like she's Kara Duhe - a porn star. Thanks for that unintentional glimpse into your life Rob. StarFish (talk) 19:29, 23 January 2010 (UTC) - Oh, dear. Well, if you'll excuse me, I'm off to clear my cache and cookies after clicking on that link. Rob, I'm looking forward to your explanation of this. someone wanna WIGO our friend's browsing habits? TheoryOfPractice (talk) 19:35, 23 January 2010 (UTC) - I can't see any other explanation than Rob's been caught red handed (sorry!) Looks WIGOable to me but I'll leave to someone more able to check and create one if they want to. My Wigos usually get minus several million. Thanks for the NSFW thing - looks like it is a porn site. Go Rob! StarFish (talk) 19:46, 23 January 2010 (UTC) - Deleted and moved. EddyP (talk) 20:17, 23 January 2010 (UTC) - Busted. Utterly, totally busted Rob. You, despite being a "Christian", like and collect teh porno. Oh well. Internet 1 Rob Smith 0. DogPMarmite Patrol 20:27, 23 January 2010 (UTC) - I couldn't resist. EddyP (talk) 20:32, 23 January 2010 (UTC) - Hahaha awesome. Acei9 20:35, 23 January 2010 (UTC) - It is a blog with "non-nude" in the name and the guy post pictures of attractive women with their clothes on. Is this some kind of weird Christian porn? It is okay, so long as you don't see her boobies. Reminds me of those jokes about Puritans getting excited by the sight of woman's ankle. - π 22:52, 23 January 2010 (UTC) - Did you read the copy underneath the picture? "Kara is multi-orgasmic, which means she can have as many as 4 orgasms within five minutes." Although it does then prattle on about how 'glamour girls' increasingly look like porn stars. Whatever. DogPMarmite Patrol 22:56, 23 January 2010 (UTC) - To be honest, I lost interest after the non-nude bit. All this talk about NSFW got my hopes up. - π 23:03, 23 January 2010 (UTC) - The blog is dedicated to a guy named Ron Harris. His [WP article]has links that'll bring you to the good stuff. TheoryOfPractice (talk) 23:27, 23 January 2010 (UTC) - - I see you have been researching the issue at length. - π 23:30, 23 January 2010 (UTC) - "Length" indeed! Get it? Length? TheoryOfPractice (talk) 23:32, 23 January 2010 (UTC) - Personally, I'm just surprised his porn includes females. --Kels (talk) 23:23, 23 January 2010 (UTC) Fair enough. Imma burn a sock to tease him about it later. Suggest we all try to keep this alive until they call the FBI. TheoryOfPractice (talk) 20:36, 23 January 2010 (UTC) - The best bit is the fucking idiot posts it on CP of all places. He must have been copy / pasting the image title and got the wrong one. StarFish (talk) 20:45, 23 January 2010 (UTC) - Simply Epic. Thieh[Talk needed] 20:54, 23 January 2010 (UTC) - Huh, I always thought that Karajou is male. Vulpius (talk) 22:36, 23 January 2010 (UTC) - Rob's clearly enjoying a game of "Masturbation Minefield". You start with a selection of pornographic pictures, and hide a few pictures of things like death camps, bloated corpses, and nasty injuries in there. After arranging the images in to a random slideshow, Rob will begin pounding his pud and hoping that he doesn't hit an atrocity at the wrong time. The risk is that he bends his brain to the point where he's unable to get wood without switching on the History Channel.-- Ask me about your mother 22:55, 23 January 2010 (UTC) Boy, Man,I mean Wow. You guys take the bait everytime, GARR-AUN-TEED. Watta ya gonna do, oversite the last WIGO? RobSmithdon't bother me 22:59, 23 January 2010 (UTC) - Oh I see you were doing it as joke to get our attention. Nice post hoc, Rob. - π 23:00, 23 January 2010 (UTC) - Rob, are you making your little soldier cough custard while editing CP, or do you take breaks for that specific purpose? Either way, Matthew 5:28 is worth a look. JC will not be impressed. -- Ask me about your mother 23:04, 23 January 2010 (UTC) - (ec)Um, excuse me Rob? So you're saying that you - Got the idea to pull one over on us, - Found a creepy almost-porn site, - Uploaded a Holocaust pic and intentionally gave it the same name as a pic on said almost-porn site, - Sat back and twiddled your thumbs waiting for us to figure it out? - It sounds about as plausible as Obama being born in Kenya and covering it up the whole time just to be president! Junggai (talk) 23:07, 23 January 2010 (UTC) - About as plausible as Obama's explanation why his approval and agenda are going down in smoke and flames. RobSmithdon't bother me 02:47, 24 January 2010 (UTC) Meh. Change the subject all you want. Who cares about Obama? Not when we can be looking at more pictures of the lovely Miss Duhe.TheoryOfPractice (talk) 02:50, 24 January 2010 (UTC) - Errr Rob, yeah hi there. Sorry, all your Obama bluster aside, but this section was detailing your sordid teen fantasies. It was a joke, right? Acei9 02:51, 24 January 2010 (UTC) - Oh Rob. It's nice to know that you take time out of your busy commie hunting schedule to play a quick game of flog the dolphin. No really..... Without mentioning Obama or communist or liberals, explain what the joke is in this whole debacle. SirChuckBOne of those deceitful Liberals Schlafly warned you about 04:10, 24 January 2010 (UTC) - "HAHA! YOU TOTALLY PLAYED RIGHT INTO MY HANDS! YOU SEE, IT WAS MY PLAN ALL ALONG TO GET YOU TO REACT, YOU'RE ACTUALLY ALL PUPPETS DANCING TO MY STRINGS!". Awesome. That's just a classic response of a twelve year old when they don't want to admit that they were wrong. I just read about this specific archetype in an article the other day (was it cracked? Can't find it atm), it's hilarious to see RobS trying to pull it off. --GTac (talk) 11:32, 25 January 2010 (UTC) I for one like it when JC watches me--Opcn (talk) 23:10, 26 January 2010 (UTC) - That's exactly the one I was talking about, Pi. Quick, someone send it to Rob! --GTac (talk) 17:52, 27 January 2010 (UTC) Time to turn to Christ, Rob[edit] He's always watching, you know. WodewickWelease Wodewick! 01:05, 24 January 2010 (UTC) - All things in moderation (how does one fornicate in moderation?). RobSmithdon't bother me 02:47, 24 January 2010 (UTC) - If you don't know how, ask her. ħuman 04:22, 24 January 2010 (UTC) Stick it in halfway Stop at second base Cyber her online. NorsemanCyser Melomel 14:32, 24 January 2010 (UTC) - *frantically taking notes* --PsygremlinSermā! 14:37, 24 January 2010 (UTC) Wordy "Obama's an elitist"[edit] Yes, Obama's an elitist.img Hey, wingers, you know what? You should want a president who is smarter than you. You should demand the president surround himself with intellectual heavyweights who may, at times, disagree with the president. You should want someone who puts everyone's interests ahead, rather than some good ol' boy you can have a beer with. Haven't 2001-2009 taught you anything yet? American politics has gotten to the point that short-term-memory eight-year-olds are running the show and being damned petulant about it. --Irrational Atheist (talk) 14:09, 25 January 2010 (UTC) - - What is it with capitalizing the every word in the first sentence? I find it really hard on the eye, as I. Read. It. Like. This. And. It's. Very. Stacatto. DeltaStarSenior SysopSpeciationspeed! 15:53, 25 January 2010 (UTC) - I think it's supposed to be like a newspaper headline, which I think usually would be all-capped like a book title. ħuman 23:31, 25 January 2010 (UTC) - Of course, TK's the only one who does it, or at least they don't all do it. And he capped one "The" and not the other... ħuman 23:32, 25 January 2010 (UTC) - I'm getting frustrated with the stupidity that emanates from the wingers. Earlier I saw a report quoting Fox that stated that Air America Radio's bankruptcy shows that America is ditching liberal ideas. No, it's not. It's showing that a network with few high profile voices, an inability to sell advertisement and a lack of good programming is doomed to failure. Their previous bankruptcy was due to management issues. There are other liberal syndication networks still in good standings. - It would be great if we could have adults being adults, and discussions about rational, reasonable issues. Instead we get very immature ideas and filler, and a whole bunch of hyperbole and ignorance. America doesn't want an elitist president, for example; they want a guy they could have a beer with. Democrats take 60 seats in the senate, but they should listen to what the people want; one Republican wins a senate seat held by a Democrat who passed away, against a poorly run campaign to boot, and the people have spoken. It's ridiculous and it's only getting worse. Conservapedia is just part of that infuriating faction of the American public. --Irrational Atheist (talk) 16:26, 25 January 2010 (UTC) - This is exactly it. Look at the whole goddamned teabagging movement. A democrat wins the presidential election soundly, and the democrats win overwhelmingly in congress. What does this prove? We have to speak truth to power! We have to make the people's voices heard! We the people cannot allow these elitist despots to push through the agenda they were elected on! Here's a fun game: try to imagine what America would look like if the wingers got their way: Obama fails miserably, Republican ideologues hold congress for ages with a more puritanical nut than Bush in charge. 16:44, 25 January 2010 (UTC) - And they can't even be honest about the Tea Party movement itself. It's billed as a "grassroots" movement by FoxNews, which created it! It's promoted as a bipartisan or non-political movement, when it's all wingers. It's got extremists and nationalists heading up TP groups throughout the country, but somehow it's simply "the people's movement." Honesty, rationality and critical thinking seem not to apply to the very people this kind of shit brings out from under their rocks. And they fill the 24 hour news networks with it. - You want to know what people want? See at the elections. And stop forcing your opinion onto everyone because you have a media empire with which to do it. And TK? You're still an asshole. --Irrational Atheist (talk) 16:59, 25 January 2010 (UTC) Intellectual Dishonesty and the Right[edit] The claims that the Tea bagging Party movement are "grassroots" are belied by its own attendance numbers. When Fox News relentlessly promotes them (the original Tax Day protests, Glenn Beck's 9/12 rally) they get decent to impressive numbers. When Fox doesn't promote them, like the 4th of July rallies, the numbers are laughable. To give another example of intellectual dishonesty... moveon.org sponsored a "Bush in 30 Seconds" video contest. One video was submitted that compared Bush to the Nazis, protests ensued, and moveon.org pulled it, rather quickly. But all you heard was "moveon said George Bush was a Nazi! Those awful liberals!" But now, people of the same political philosophy, if not the exact same people, claim Obama is simultaneously a Socialist, a Nazi and Muslim. MDB (talk) 18:13, 25 January 2010 (UTC) - Or the people who intentionally darken Obama's photos... It's a bunch of children who can't grow up, think for themselves or even bother living in reality. And it's growing because it has a network, a political party and many formerly-underground groups who want legitimacy. --Irrational Atheist (talk) 18:36, 25 January 2010 (UTC) - See...I've always kind of wondered about that. Not to paint with a broad brush. I know both sides of the isle have their respective shares of idiots. But the more I read of the so called "conservatives," the more I see them in the news and read their ramblings and hear their words, the more I wonder about something. I know its been joked about before and mentioned and mulled, but honestly...is there really some kind of requirement to being a conservative today that you have to be a hypocrite? Looking back I see it more and more. The same person who says adulterers will burn in hell is also the one who gets caught having an affair (Swaggart). The same person who says drug users are losers we wouldn't waste money on rehabilitating goes into rehab for a dependency on pills (Rush). Then we have the preacher who decries gay marriage and then gets caught buying drugs and getting massages from gay prostitutes (Haggard). A senator tries to get a nude beach closed on the grounds he wants to protect children and then gets busted sending lewd texts to senate pages (Foley). Abortion is a society destroying sin but its ok to shoot the doctors and bomb the clinics. When their president is in office those who disagree with him are traitors, but when our president is in office doing everything you can to defame, discredit, or decry him is a patriotic duty. Its ok for the government to tell people who they can marry but heavens forbid you try to regulate the sale of handguns. Etc...etc...etc... - I guess my point is its one thing to stand at the podium and say you should be in charge because you want to serve the public interest and do right for the country and better our society and meanwhile be boinking your secretary, taking under the table hand outs, so on and so forth. That person is a crook and liar. But the person who stands at the podium and says he should be in charge because he so much more moral than everyone else and believes in traditional family values, yadda yadda, and HE is boinking his secretary, taking under the table hand outs...this person is a hypocrite and theocrat. Maybe its just me but I can at least stomach and work with the first guy. The other guy I have nothing but contempt for. And maybe its just me, and maybe I'm off my rocker, but I've been seeing that guy more and more in the conservative ranks lately. -Tygrehart - I would submit that the people who murder abortion providers are not hypocrites. They are extremist zealots, to be sure, but if someone honestly believes that abortion is the taking of a human life, then it is not hypocritical to use violence to stop abortion. (It's wrong for a whole host of other reasons, but at least its not hypocritical.) - Now, if you want some intellectual amusement, try to get a pro-lifer to answer whether or not they think doctors who perform abortions should receive whatever penalty they feel is appropriate for first degree murder. I tried it once. He avoided the question repeatedly, but finally, after essentially demanding he answer, he admitted they would not support that, but still tried to argue he thought a fetus was a human life. MDB (talk) 13:13, 26 January 2010 (UTC) - I could split the hair about one of the usual arguements from pro-lifers being that abortion is murder and murder is wrong, thus making those who think its ok to kill the doctors and staff involved hypocrites, but your observation is noted and will be considered should I ever engage in this topic of discussion again. Still, I ask again if anyone else has noticed an upswing in the "do as I say, not as I do" mentality amoungst the right these days. -Tygrehart - Just playing Devil's Advocate here... I don't think they view killing an abortion provided as "murder", per se; I think they view it as justifiable homicide. I'm not defending that view, mind you; I'm just pointing out what I perceive their logic to be. - As for an upswing in "do as I say, not as I do"... hhhmmm... I'm not sure. One of the things you learn from reading Shakespeare is "great men have great flaws" (great in the "influential" sense). From Shakespeare, Caesar was overly ambitious, Hamlet was indecisive, etc. From recent history, Nixon was paranoid, Clinton couldn't keep his dick in his pants, etc. Couple that with a media that will expose your flaws eventually. Add in an American right that's set itself up as the nation's moral guardians, many of whom have very prominent voices (can you name a left wing moral critic -- all I can think of are Jim Wallis and C. Weldon Geddy), and "do as I say..." cases are inevitable. - And lets not kid ourselves... liberals aren't immune from moral failings. Bill Clinton's sex scandals are obvious (though I personally suspect Bill and Hillary have an open relationship, but they could never admit that in public. And if I'm feeling catty, I'll add "they're both allowed to sleep with other women.") And John Edwards ought to be fucking ashamed of himself -- cheating on a wife who has cancer, knocking up his mistress, getting a staffer to take the blame, lying about it for months. He's a disgrace. Article[edit] So whereabouts should I dump this? I presumed it belonged somewhere in the CP namespace with a link to it from assfly's main page but I don't know what the nomenclature is that we use. CrundyTalk nerdy to me 10:33, 26 January 2010 (UTC) - Conservapedia:Disappointed homeschoolers? I have just eaten & stiltontalk 14:01, 26 January 2010 (UTC) - Whooee! Crundy took my suggestion! I have just eaten & stiltontalk 17:18, 26 January 2010 (UTC) - Why is that such a surprise? CrundyTalk nerdy to me 12:04, 27 January 2010 (UTC) "Many of the most influential people in history were writers...[edit] ...starting with Matthew, Mark, Luke and John, the authors of the four Gospels." Not the first time Andy has pissed off the ghost of Aristophanes. WodewickWelease Wodewick! 18:03, 26 January 2010 (UTC) - Not to mention most of the Old Testament, which was passed down as oral history and mythology before anyone got round to writing it down. Totnesmartin (talk) 18:06, 26 January 2010 (UTC) - Isn't it kind of a dumb thing to say anyway? People who write stuff are going to be more influential than people who don't write stuff (on average) simply because more people get to hear (read) what they're saying. X Stickman (talk) 18:14, 26 January 2010 (UTC) - (EC) Even if he is going to pooh-pooh the ancient Greeks, someone should at least tell him that (according to Christian tradition, anyway) Moses preceded the Apostles as a well-known and influential writer. ListenerXTalkerX 18:16, 26 January 2010 (UTC) - (ECx3 bastards!) Of course it's dumb, but Andy has to justify the $120 he fleeces from the poor kids' parents. Anyway, surely we're only a hop, skip and a jump from cp:Greatest Works of Literature Written by Teenagers/Homeschoolers/Conservatives? --PsygremlinПоговорите! 18:19, 26 January 2010 (UTC) - Stickman that's an interesting point. I guess it would be MOST accurate to say that the most influential people in history were either writers (Horace, Ovid) or written about (Socrates, Jesus) or both (Julius Caesar). - I wonder if you gave Andy a list of ancient names, what he would make of them. "Ovid? Oh, yes, the Battle of Ovid. Ignored by public schools because they suppress how important military history is." WodewickWelease Wodewick! 18:20, 26 January 2010 (UTC) - Anybody with a sock to burn want to mention Homer et al. It'll be funny to watch Andy claim there were no writers before Jesus, like he did with comedy. --Psygremlin講話 18:25, 26 January 2010 (UTC) - X Stickman, that is a conclusion that is firmly supported by memetics (or whatever you might prefer to call it) which was named by Richard Dawkins, who is an atheist; Atheists are always wrong.--Opcn (talk) 22:16, 26 January 2010 (UTC) - What did Jesus write? ГенгисGum disease 11:13, 27 January 2010 (UTC) Can anyone tell me the difference...?[edit] "This image is considered copyrighted by its creator, who has specifically authorized free use of this image anywhere world-wide." and "This image is considered copyrighted by its creator, who has specifically granted permission for free use of this image in Conservapedia."? If it's "free use" "in Conservapedia," and Conservapedia's license is "Your contribution of information here irrevocably waives any personal claims to copyright that you may have in that information, except as provided in the Conservapedia:Copyright disclaimer..." That disclaimer reads, "By contributing information to Conservapedia, you irrevocably consent to the display, copying, reuse or editing of your information, edits and entries, with or without attribution." Am I wrong, or is giving "free use" for use "in Conservapedia" granting "free use" "anywhere world-wide?" --Irrational Atheist (talk) 20:57, 26 January 2010 (UTC) - If the image was licensed as a condition of posting then I believe that license applies to any subsequant use. The site should have rejected it if the license terms were not acceptable. (Not a lawyer - legal opinion worthless :) )Hamster (talk) 23:00, 26 January 2010 (UTC) - The problem I see is that the general copyright notice doesn't appear to allow for other licences. Our equivalent says the following: - "RationalWiki may include material which is not original content, and this does not necessarily fall under the CC-BY-SA. Unless released by the author(s), such material falls under the terms under which it was released by the original authors. Under these circumstances, the use of the material on RationalWiki is per allowance in the original license, or in some circumstances, per fair use." - CP has nothing comparable to that, so they'll end up with conflicting copyright/licence statements. --Thor's Mighty Phallus (talk) 23:39, 26 January 2010 (UTC) - Dang! We should have got a lawyer to write our copyright notice as well. ГенгисGum disease 11:18, 27 January 2010 (UTC) TK, hope you'll report this![edit] The man who brought the hidden video of ACORN people to the right wing has been arrested for trying to illegally tap Senator Landrieu's phones. If it's important that the "liberal media" report on the problems of ACORN, then shouldn't it be just as important to expose those who attempt crimes against our lawmakers? --Irrational Atheist (talk) 23:30, 26 January 2010 (UTC) - Oh, come now; everyone knows that one only condemns crimes of that sort if they do not share the political sympathies of the criminal. ListenerXTalkerX 23:35, 26 January 2010 (UTC) Liberal Cyber Bullies[edit] So apparently a girl killed herself after being taunted online by "liberal" cyber bullies. It is currently unknown how Andy knows they are liberal, but expect a hilarious response.--Ericm6 (talk) 00:10, 27 January 2010 (UTC) un-WIGOed[edit] Well I put a WIGO up about it, but Terry Koeckritz put up a story about a 15yo girl who was bullied to the point of taking her life, never attempted to connect it with liberals, except to say it was all the liberals fault. --Opcn (talk) 00:15, 27 January 2010 (UTC) - Once you seize the moral high ground by defining "liberal" as "people who do bad things," it's pretty easy for Andy to do what he does. SockityMcSockSock (talk) 00:18, 27 January 2010 (UTC) make me a sysop, dammit. - Per this discussion and not wanting to turn a tragedy into a WIGO, I removed it. But I could be wrong. Keegscee (talk) 00:19, 27 January 2010 (UTC) Turning a tragedy into a WIGO = bad. Pointing out that a tool is turning a tragedy into political fodder in a stupid and hurtful way = why we're here, IMHO. SockityMcSockSock (talk) 00:23, 27 January 2010 (UTC) - Did I mention TK is a fucking pig? - π 00:25, 27 January 2010 (UTC) - Yup, but some things bear repeating. Could be a ripe opportunity for bans if anyone should object to such an obvious case of exploitation. TK, you may well be the first person to actually die from a lack of class. -- Ask me about your mother 00:29, 27 January 2010 (UTC) - I feel ill after reading that. I'm no stranger to watching Conservapedia manipulate horrific things like that to their own ends, but it doesn't make it any less disgusting when they do it repeatedly. In fact, it makes it more disgusting. SJ Debaser 00:30, 27 January 2010 (UTC) - ...aaaaand he follows up with a sexist Godwin's Lawimg violation. Dude's on a roll. SockityMcSockSock (talk) 00:33, 27 January 2010 (UTC) I think the comments on this page, and elsewhere, about me and others, prove what liberal sensibilities are quite clearly. The same kind of taunting and vile name calling, in place of reasoned arguments against what a person believes, is shown here daily, like the taunts described in the news article about that girl. --TK/MyTalkRW User #45 01:04, 27 January 2010 (UTC) - You called the bullies liberal without any sources. Name calling anyone? Keegscee (talk) 01:10, 27 January 2010 (UTC) - Your argument is that Liberals do X there for X is only done by liberals? If it rains the road is wet, so since the road is wet it must be raining, no one could have washed their car or anything --Opcn (talk) 01:19, 27 January 2010 (UTC) - Doing that, however repugnant to someone, isn't an excuse to use personal attacks and name calling. Straying off point, using one thing to excuse another, isn't rational. The name calling and personal attacks here offer circumstantial proof that what I said is true. --TK/MyTalkRW User #45 01:27, 27 January 2010 (UTC) - I think it was you using this tragedy to advance an agenda that has brought on the name calling, not that you are calling anyone names or using fallacies of weak correlation --Opcn (talk) 01:33, 27 January 2010 (UTC) - There's no rational discussion to be done with anyone who believes the world is only 6,000 years old, that Obama was born in Kenya, and that liberals want the terrorists to defeat us. When you make up stuff beyond the evidence that is openly available, you've dismissed reality and rationality. So why bother being rational, when it's more fun riling you up by using dirty words and laughing at your stupidity? --Irrational Atheist (talk) 01:36, 27 January 2010 (UTC) - TK, you guys berate gays, liberals, minorities, non-Christians, non-Americans, and so forth. How fucking stupid are you to say that liberals are the only ones name-calling, when you make labels your name calling? "He's a socialist!" "He's a Marxist!" "Homosexuals are sinners!" and so forth. Your ignorance of your own hypocrisy is staggering, but that you feel it necessary to play holier-than-thou here is hilarious. You're still an asshole and an idiot, and now a pig. --Irrational Atheist (talk) 01:30, 27 January 2010 (UTC) - Ah TK, learn to read Aurebesh.-- Spirit of the Cherry Blossom 01:35, 27 January 2010 (UTC) At least I am not personally attacking, in public, and calling people vile names, unless you are saying "Socialist", "Marxist" are vile names? You cannot see the difference? But of course you do, and merely post here to obsfucate and drive the subject matter off track. --TK/MyTalkRW User #45 01:38, 27 January 2010 (UTC) - No, you are simply maligning whole categories of people --Opcn (talk) 01:41, 27 January 2010 (UTC) - They may not be vile names, TK, but your intent is clear. Just because you try to hide it doesn't mean that you aren't attacking people. Keegscee (talk) 01:45, 27 January 2010 (UTC) - Oh, sorry Terry, did your widdle feelings get hurt? I never knew you were such a sensitive widdle flower. Listen, dickhead, there's nothing wrong with calling a spade a spade, so saying you're a vile pile of filth is nothing more than pointing out the obvious. Making broad, sweeping attacks against groups of people based on nothing but your prejudices is another matter entirely. Now go back to trolling CP where you're actually wanted (for some reason). DickTurpis (talk) 01:47, 27 January 2010 (UTC) - If you're saying, "Marxists dictated this economic theory," that's one thing. If you're saying, "Obama is a Marxist!" because he does something you don't like, that's name-calling. How can this not be clear? Obama has never instilled a single Marxist idea of economics. The bailout was under Bush's watch, but it was the government *loaning* money, which it has done since the US formed as a country. The government loaning money is in the Constitution! So when you stop being a complete asshole and the turd in Assfly's bowl, hoping to keep your bullshit powers at CP because no one else wants you around, we'll stop making fun of how much of an internet troll you are. If your feelings get hurt, too fucking bad. --Irrational Atheist (talk) 02:00, 27 January 2010 (UTC) - This is pretty disgusting, and TK, you are a worm who isn't half as smart as he likes to think he is. But then again, this is par for the course... remember Andy's obsession with school shootings all being the fault of liberals? H. Randolph Twist (talk) 02:05, 27 January 2010 (UTC) - You must be new here. School shootings are a liberal trait. TheoryOfPractice (talk) 02:06, 27 January 2010 (UTC) Oh come on guys, leave TK alone. After all, liberals are trying to invite more Muslims into the country, which will make the US morally depraved like the UK. NorsemanCyser Melomel 02:34, 27 January 2010 (UTC) TK, shit like this gets you mocked. Look above. You blame the liberal media for not reporting on the overblown ACORN story, which is landing quite a few people in court for wiretapping charges, but where are the links for the court cases, or the guy getting arrested for attempting to wiretap a senator's office? You claim the liberal media doesn't want to cover stories you find important, even when they're completely false (as the teleprompter-with-kids story is), but you neglect to mention anything that goes against your ideology. In other words, stop tossing the rocks in your own glass house, asshole. --Irrational Atheist (talk) 02:51, 27 January 2010 (UTC) - Being mocked is one thing, Irrationalatheist. Logical refutation is another. But name calling, outing of a persons full name for no other reason than hating them, and personally attacking someone for their own opinions is totally different. Please stop dressing up your distaste for CP in some false intellectual wrapping. The motivations anyone can read above have nothing to do with political or intellectual disagreements, and everything to do with hate and intolerance. I am talking about things happening here, not on CP. --TK/MyTalkRW User #45 03:25, 27 January 2010 (UTC) - Don't you understand, IrrationalAtheist? TK fights the powah! Now he's playing victim on his talk page. "Waah! I was blocked for 30 seconds! RW is an autocratic regime!" What's the matter TK, are you frustrated we're not WIGOing your awful attempts at parody? Take my advice Terry and leave the funny to the pros. WodewickWelease Wodewick! 03:27, 27 January 2010 (UTC) - TK if you don't want people to comment on it, don't put it out there. This includes your real name, which you gave to a journalist, and you diatribes on the main page. As for abusing a tragic event to make a "point", if you give hate, you will receive hate. - π 03:30, 27 January 2010 (UTC) - TK hates it when people out others real namesimg Acei9 03:33, 27 January 2010 (UTC) Ace and Pi, nowhere in the article RW used to say that was my name, did the reporter state that user was the CP Admin known as TK. Nowhere. You made the connection totally on supposition, and over my objections. One Bureaucrat here agreed, and removed all such reference's, and after he apparently left RW, he was reversed, and the community guidelines were changed, post facto. How is that fair? And Ace, both Trent and Ames have publicly, in many places outed their own names, with links to RW and CP. For Ace to equate and claim that is the same thing is a lie. --TK/MyTalkRW User #45 04:01, 27 January 2010 (UTC) - Gee, how did we work out Terry Koeckritz is TK, there is no obvious hints? This reminds me of ♥ K e n D o l l ♥. You also use that article to claim we are a vandal site, if you want to split hairs what was actually said was some of the members participated in vandalism, not that the site was for vandals. This is a wiki you dumb motherfucker, things change on it; including policy which we are constantly debating, refining and revising. - π 04:11, 27 January 2010 (UTC) - Absolutely wrong once again, Pi. Here is the Los Angeles Times quote, in full:." [10] - So, as I always point out, it was the Los Angeles Times stating this was a vandal site. Why did they do that? Because of the things members here told the Times reporter! As for things changing, you dumb Mofo, changing things post facto to make violating the rules here okay isn't logical or rational, just mean-spirited, and I am sad most of you posting here keep proving what this place is really about. --TK/MyTalkRW User #45 06:59, 27 January 2010 (UTC) - "changing things post facto to make violating the rules here okay isn't logical or rational" yet you block people for being editors, despite the fact you edit here yourself, because you changed the rules "post facto". TK the whole vandal site thing is played out. We, as a community, don't condone vandalism, but yes I am sure people who are members have vandalised the site. Now stop getting your panties in a twist just because we monitor and comment on the site. - π 07:21, 27 January 2010 (UTC) - I care nothing about monitoring or commenting. I care when people like you keep posting lies, Pi. Several on this page, like saying I am calling this a vandal site, when it was the Times, saying I was calling people (plural) at work, getting them in trouble, when I have never, not ever, done such a thing. The only Rational Wiki user I have spoken to at work (or anywhere else) was at his email invitation to do so. Quit using distortion to obfuscate legitimate complaints. Attack ideas, if you must, but stop with the personal hate. You should stop getting your panties in a twist...and stick to the facts. --TK/MyTalkRW User #45 07:47, 27 January 2010 (UTC) - I suppose all those mentions of the term "vandal site" in your block log were added by the Times as well? -RedbackG'day 07:54, 27 January 2010 (UTC) As I have posted here, Pi, I can only go by my personal knowledge, and the personal destruction hate here, a liberal site, and the comments I read here, show me that is a pretty common liberal trait. I am not talking here about generalities about conservatives or liberals, which I don't mind, but very personal vituperation aimed at one person because you disagree with them, where their family can come across it, unlike those of you who are permitted by the rest to hide in anonymity like cowards, as you bash those of us who cannot, only due to your own actions. I have shown enough here to others who had doubts about my assessment of RW, as to if this is a serious and notable place. Through many of the members own comments (see Irrational just below) and actions you have shown it isn't, and will never be. --TK/MyTalkRW User #45 08:46, 27 January 2010 (UTC) - - No, TK, I mock you because you're simply an asshole. You're predictable and paranoid, which makes you even more entertaining. You're stupid in wisdom, meaning you don't even realize when your arguments fall flat because they're so hypocritical. And attacking someone for their opinions? I'm attacking you for your trolling, you fucking moron. I could care less what kind of ice cream you like or which band you prefer on long drives. But I will point, laugh and ridicule because you think Obama's a marxist socialist muslim manchurian candidate seeking to overthrow the country. I mean that shit is right up there with L. Ron Hubbard's paranoia. Whether or not you truly believe half of what you say doesn't matter. You say it and therefore you get made fun of harshly. If you don't like it, get the fuck off the internets. --Irrational Atheist (talk) 03:42, 27 January 2010 (UTC) - Entertaining? I think it's the opinion of most observers that Conservapedia would be a more entertaining place without TK. This is one of the key similarities between Conservapedia and RationalWiki. WodewickWelease Wodewick! 03:46, 27 January 2010 (UTC) - The LA Times article also states that Terry Koeckritz is 56. I think that is no longer the case. Just like the few RW members who admitted to having vandalised CP 30 months ago are no longer active editors here. Of course what is demonstrably true is that Terry Koeckritz is a liar - witness the UCLA plagiarism case, the "self-made" Christmas neon image, and numerous other examples, not to mention PJR's indictment. Now Terry, will you lie again and deny that you set up the "Godspeed" discussion board where you attempted to recruit, aid and abet people to help vandalise CP and that you have actively engaged in editing here under the pseudonyms of User:E.Wig and User:NightTrain? Lily Inspirate me. 13:01, 27 January 2010 (UTC) - Despite all TK's protestations here, he remains the cunt who tried to gain some kind of leverage (only he knows what) out of Dean's wife's death, by posting that disgusting message on his own user page (and maybe Dean's too?). The man is lower than scum and deserves the same respect accordingly. --PsygremlinSnakk! 13:18, 27 January 2010 (UTC) - TK: Explain to me how this does not constitute "name-calling?" Love and kisses, Irrational Atheist (talk) 16:55, 27 January 2010 (UTC)
https://rationalwiki.org/wiki/Conservapedia_talk:What_is_going_on_at_CP%3F/Archive168
CC-MAIN-2020-50
refinedweb
22,528
71.95
You can use a "named pipe" or "FIFO" (first in, first out) on Linux and Mac OS X (see man -S 7 pipe) or a network connection (for remote connections) on Windows, Linux, and Mac OS X. You need a program that gets values from the input device, and outputs them into a file specified in Filename or a Network port. Your custom program writes formatted messages into the file or port, and the Pipe In CHOP reads it, creating the channels specified in the messages. Networking into Houdini You can receive network data from another server (e.g. from a Houdini Pipe Out CHOP running remotely). A connection must be established between the server and the Pipe In CHOP before data is sent. Do this by changing the Source from Pipe to Network). You must supply the Server Address and Port from which to receive incoming data to a channel. The server should be listening for connections on the port that this CHOP is using. To setup a link between two Houdini processes, one process should have a Pipe Out CHOP active (thus listening for connections) on an arbitrary port (i.e. port #5010). The second Houdini uses a Pipe In CHOP with the network address set to the name of the machine that the first Houdini process is running on. The network port should be set to the same port as the server (in this case, 5010). The port number can be any number between 5000 and 10000, as long as it is consistent between the Pipe In and Pipe Out CHOPs. For more than one connection, use distinct port numbers. Pipe In/Out CHOPs with matching port numbers on different machines should automatically sense one another. If you just want to send data from a local process to Houdini, set the server address to localhost. Programming the Pipe In CHOP The Pipe In chop is designed to allow you to program an interface to chops that do not require a Houdini Developers Kit. The Pipe In CHOP allows Houdini to read information in a special formats described here from a FIFO (First In, First Out) file and create CHOP channels. As long as the correct formats are used, Houdini will be able to get data from any source including devices such as a joystick, microphone or PuppetWorks' hardware. The Pipe In CHOP has two parameters and parses three command formats. The first parameter specifies which file to read from and the second toggles between active (reading) and inactive (discards data) modes. The formats supported allow the following functionality: upload the most current sample data, upload all sample data and create a full waveform, and upload the channel names. Using the Pipe In CHOP In order to read information with this chop, a separate application has to be developed to write to a FIFO in the proper format. The following sections describe and give sample code (written in C) for opening a file and writing values that will be accepted by the Pipe In CHOP. Opening a Fifo File To create a file that the Pipe In CHOP will read from, use the following code to open a new FIFO called FIFO_NAME. Define FIFO_NAME to be the desired file name to create. The output stream that is used for writing will block until a reader is connected to the file. #include <sys/types.h> #include <sys/stat.h> #include <stdio.h> mode_t prev_mask; FILE *output = 0; /* Create a new fifo */ prev_mask = umask(0); mkfifo (FIFO_NAME, 0666); umask(prev_mask); /* Open the file for writing */ fprintf(stderr, "Awaiting reader of FIFO %s\n\r", FIFO_NAME); output = fopen(FIFO_NAME, "wb"); Writing To The File The Pipe In chop reads information from the FIFO in eight-byte big endian chunks of data called tokens, so it is necessary to write to the file in the same format. There is also a method in place for sending an escape character in case a reset is required in the middle of parsing a command. Note In versions prior to Houdini 12, 4 byte tokens were used instead of 8 byte tokens. The reset character is an integer value of 170. When this byte is received, followed by a byte with a value of zero, the current parsing is reset. In order to send a value of 170 without the command being reset, two bytes with a 170 value must be sent consecutively so that the Pipe In CHOP will disregard the first value. #define ESCAPE_CHARACTER 170 void write_byte(char b, FILE *output) { /* Prepend escape character */ if (b == ESCAPE_CHARACTER) fputc(ESCAPE_CHARACTER, output); fputc(b, output); } void write_values(const char *p, int size, FILE *output) { int i; for(i=0; i<size; i++) write_byte(p[i], output); } void send_reset(FILE *output) { fputc(ESCAPE_CHARACTER, output); fputc(0, output); fputc(ESCAPE_CHARACTER, output); fputc(0, output); fputc(ESCAPE_CHARACTER, output); fputc(0, output); fputc(ESCAPE_CHARACTER, output); fputc(0, output); fflush(output); } Using these functions, any 8 bytes of data (e.g. 00000001, 3.141, Chan, …) can be sent to the file. To send a reset signal, four escape sequences are written to pad to 8 bytes. It is a good idea to send a reset signal before the command and flush the FIFO at the end of a command. int64 token; double sample; send_reset(output); /* Send a command here */ write_values((char *)&token, sizeof(token), output); write_values((char *)&sample, sizeof(sample), output); fflush(output); Note An escape character (170) can be sent, followed by any other character, to stop the current command parsing and begin again. If the 170-170 sequence is sent, the first character is ignored and the value is sent normally. Command Type #1: Current Values The first type of command that the Pipe In CHOP will read is used to get the most recent channel data. It has a default sample rate of 30 samples per second, CHOP length of 1, and a start position of 0. This command allows the number of channels to be set and the samples associated with those channels to be read. (int64) 1 Command Type. (int64) Number of Channels. (double) Sample Data, one sample for each channel. Command Type #2: Upload The second type of command that can be parsed is used to upload a full set of samples to create a waveform. The sample rate, track length, start position, number of channels, and samples for each channel to fill the track length must be provided. The channel samples must be interleaved so that all the channels for one index are filled before moving forward to the next index. (int64) 2 Command Type. (int64) Track Length. (double) Sample Rate. (double) Start Index. (int64) Number of Channels. (double) Sample Data, one sample for each channel for each index. Command Type #3: Channel Names This command allows the channels to be assigned names before they are created. Since the names are usually strings, it is important to remember to write them as eight-byte tokens (padded with zeroes at the end if necessary) so they will be parsed correctly. This format requires the number of names to be set, followed by the name length (in number of eight-byte tokens) and name data for each channel. (int64) 3 Command Type (int64) Number of Names For each name, the following data is read: (int64) Name Length, one per name (char*) Name Chunks (char\/nodes/chop/8\ * Name Length) Command Type #4: Disconnect This command causes the Pipe In CHOP to disconnect the network connection. It is typically sent by the Pipe Out CHOP when its Active parameter is turned off or if the node is bypassed. (int64) 4 Command Type Additional commands delay refresh (int64) 5 - command type (int64) - seconds to delay script (int64) 6 - command type (int64) - Script Length (char*) - Script Chunks (char[8] * Script Length) Writing a Command Using command type 1 as an example, the following function could be used to send a command to the FIFO which will be read by the Pipe In CHOP. void send_current_values(FILE *output, int num, double *samples) { int64 token; int j; send_reset(output); /* just to be safe */ /* Command Type */ token = 1; write_values((char *)&token, sizeof(token), output); /* Number of Channels */ token = num; write_values((char *)&token, sizeof(token), output); /* Sample Values */ for(j=0; j<num; j++) write_values((char *)&samples[j], sizeof(samples[j]), output); fflush(output); } Source Code Example You can find a compilable example of a Pipe In application in: $HH/public/PPD.tar.Z One device that is implemented using this protocol the Puppetworks device, and its driver can be installed via the proto_install application. Parameters PipeIn Source Data can be piped in through a UNIX pipe or a Network port. Filename The file that the device data will be read from. The file must not be a regular file. It must be a "named pipe" or "FIFO". In UNIX, see "mknod". Server Address The network address of the server computer. This address is a standard WWW address, such as 'foo' or 'foo.bar.com'. Server Port The network port of the server. The port is a number between 5000 and 10000, which both the server and the client use to connect with. Active While active, the CHOP receives information from the pipe or server. When off, no updating occurs. Data sent by a server is lost, but a pipe will store the data until active is turned on again. If in Network mode, turning this parameter on initiates a connection, and turning it off breaks the connection. Reset Channels Clears all channels and.
https://www.sidefx.com/docs/houdini/nodes/chop/pipein.html
CC-MAIN-2020-45
refinedweb
1,592
60.14
/** 33 * HTTP HEAD method. 34 * <p> 35 * The HTTP HEAD method is defined in section 9.4 of 36 * <a href="">RFC2616</a>: 37 * </p> 38 * <blockquote> 39 * The HEAD method is identical to GET except that the server MUST NOT 40 * return a message-body in the response. The metainformation contained 41 * in the HTTP headers in response to a HEAD request SHOULD be identical 42 * to the information sent in response to a GET request. This method can 43 * be used for obtaining metainformation about the entity implied by the 44 * request without transferring the entity-body itself. This method is 45 * often used for testing hypertext links for validity, accessibility, 46 * and recent modification. 47 * </blockquote> 48 * 49 * @since 4.0 50 */ 51 public class HttpHead extends HttpRequestBase { 52 53 public final static String METHOD_NAME = "HEAD"; 54 55 public HttpHead() { 56 super(); 57 } 58 59 public HttpHead(final URI uri) { 60 super(); 61 setURI(uri); 62 } 63 64 /** 65 * @throws IllegalArgumentException if the uri is invalid. 66 */ 67 public HttpHead(final String uri) { 68 super(); 69 setURI(URI.create(uri)); 70 } 71 72 @Override 73 public String getMethod() { 74 return METHOD_NAME; 75 } 76 77 }
http://hc.apache.org/httpcomponents-client-ga/httpclient/xref/org/apache/http/client/methods/HttpHead.html
CC-MAIN-2017-17
refinedweb
197
52.7
When. A floor wax _and_ a dessert topping ?! Incredible. I’ve also found using to be helpful for things you really really would like released ‘deterministically’, i.e. limited, expensive resources – I implemented a wrapper class for Websphere MQ (customer choice, not mine) and implemented IDisposable for the MQReader and MQWriter classes so that the resources would get freed up as soon as the logic was done with them – handy – but I’d never thought of managing state like the article you linked….. Can be used for exception handling too: Yes, deterministic destruction is very useful. Coming from a C++ background I *love* how .net makes tons of things easier but real destructors is the one thing I miss the most (well, that and templates but I just got my VS 2005 beta DVD so I’m not allowed to complain about that anymore :)). Anyway thanks for the pointer! speaking of such things, has any1 found any way at all to determine, in the disposer, whether or not you are being disposed because of an exception or not? We’ve basically used using as a poor man’s anonymous method -eg: > using (Transaction.Named("Save the thing")) > { > … > } and similar, because we want the behaviour to always be the same, so don’t want people to create their own try/catch blocks… however since we can’t workout whether it’s an exception or not (I tried searching the stackframe and everything! 🙁 ) we ACTUALLY have to write: > using (Transaction.Named("Save the thing")) > { > … > Transaction.Commit(); // geez would I like to remove this > } any1 succeeded in doing that? Darren, Have a look at this link: It might give you some ideas about a different approach. >speaking of such things, has any1 found any way at all to determine, in the disposer, whether or not you are being disposed because of an exception or not? That would be cool. Like you, I had a look at it and gave up. Something like Delphi’s ExceptObject would be the idea – a function that you can call in your Dispose method that returns "the current exception", or null if there isn’t one. Eric, is this fundamentally impossible, because of the way the MSIL draws a distinction between catch blocks and finally blocks? I’m hoping to sort out an alternative with anonymous methods once I start using Whidbey. Samuel – that approach is exactly identical to mine (except I’m using a much cleaner syntax :)) – and they both have the same disadvantage – you have to have that last line (for me ransaction.Commit, for system.transactions: ts.Consistent = true ) – they are doing exactly the same thing. My point is, that last line SHOULDN’T be necessary! If we could determine _in any way_ that an exception has occurred, it wouldn’t be. I tried doing things like replacing the default thread error handler, but that didn’t give me exactly what I wanted because it only gets called wayyy too late.. I’ve tried searching the stack – putting markers in and all sorts of things – but there seems to be no easy way to do it. Basically, we are in a "Finally" block, and need to determine whether it was triggered by an exception or not. In the new version of whidbey, we would be able to do it, because we can get events on exceptions – but then we have anonymous methods, so can do the whole thing in a much better way. My problem is – I’m using (and have been for months) the above syntax right NOW in tons of production code – and I would desperately like a way of not requiring the Transaction.Commit – because people can and do forget to put it in. I searched for ages, and ran across some people who hinted it could be done, but it was some weird com interop thing – and I wasn’t sure it was actually relevant. All I want is "I’m in a finally block (|dispose of using variable) – is there currently an exception being handled?" – If I get that, "using" suddenly becomes 100x more powerful, because it provides a generic way of encapsulating a try catch finally block, and the processing involved. John, I don’t know enough about the exception handling internals to know for sure, but I don’t think that we have the exception context around in the finally block. I just found another interesting use for using 🙂 I developed a reference management class that allows for certain types of object references to transit between strong and weak reference states – the idea being that when I’m not actively using the object, if it has to go away I can make another one, but that if it stays around, that’s cool too. The reference manager object holds a pair of references, a strong reference (not always present) and a weak reference. I implemented IDisposable for this so that it nulled out the strong reference, and then started using it in using statement in the form using(SomeObject obj = (SomeObject) refMgr.StrongReference()) { < do things> } The strong reference method will use the weak ref if it’s valid, or create it and return the target if not – on exit from the using scope, the strong reference pointer is cleared by IDisposable. This pattern seems to work well, cuts down on the job of managing weak/strong references whatcha think ? uhh – typo that should be using (StrongReference sr = refMgr.StrongReference()) What I always wanted for using/IDisposable is the counterpart method to Dispose. E.g. Acquire or whatever. So that I can write using (resource) { … } and on entering using clause it would call Acquire and on exit it would call Release, both are methods of (some) IUsable interface. Darren, You are not alone in the request, we also have a same kind of issue..one of the demos from the PDC was managing transactions through attributes to class / methods from System.Transactions namespace..similar to AutoCommit from EnterpriseServicess..these probably would be part of Indigo.. Krishna [][][][][][][][][][][][][][][][][][][] [][][][][][][][][][][][][][][][][][][] PingBack from PingBack from
https://blogs.msdn.microsoft.com/ericgu/2004/07/28/using-its-not-just-for-memory-management/
CC-MAIN-2017-22
refinedweb
1,011
59.94
Official Sentry SDK for GatsbyJS Register the package as a plugin in gastby-config.js: { // ... plugins: [ { resolve: "@sentry/gatsby", options: { dsn: process.env.SENTRY_DSN, // this is the default } }, // ... ] } Options will be passed directly to Sentry.init. See all available options in our docs. The environment value defaults to NODE_ENV (or 'development' if NODE_ENV is not set). GitHub Actions The release value is inferred from GITHUB_SHA. Netlify The release value is inferred from COMMIT_REF. Vercel To automatically capture the release value on Vercel you will need to register appropriate system environment variable (e.g. VERCEL_GITHUB_COMMIT_SHA) in your project. Sentry Performance To enable tracing, supply either tracesSampleRate or tracesSampler to the options and make sure you have installed the @sentry/tracing package. This will also turn on the BrowserTracing integration for automatic instrumentation of pageloads and navigations. { // ... plugins: [ { resolve: "@sentry/gatsby", options: { dsn: process.env.SENTRY_DSN, // this is the default // A rate of 1 means all traces will be sent, so it's good for testing. // In production, you'll likely want to either choose a lower rate or use `tracesSampler` instead (see below). tracesSampleRate: 1, // Alternatively: tracesSampler: samplingContext => { // Examine provided context data (along with anything in the global namespace) to decide the sample rate // for this transaction. // Can return 0 to drop the transaction entirely. if ("...") { return 0.5 // These are important - take a big sample } else if ("...") { return 0.01 // These are less important or happen much more frequently - only take 1% of them } else if ("...") { return 0 // These aren't something worth tracking - drop all transactions like this } else { return 0.1 // Default sample rate } } } }, // ... ] } If you want to supply options to the BrowserTracing integration, use the browserTracingOptions parameter. { // ... plugins: [ { resolve: "@sentry/gatsby", options: { dsn: process.env.SENTRY_DSN, // this is the default tracesSampleRate: 1, // or tracesSampler (see above) browserTracingOptions: { // disable creating spans for XHR requests traceXHR: false, } } }, // ... ] }
https://www.gatsbyjs.com/plugins/@sentry/gatsby/
CC-MAIN-2021-10
refinedweb
308
50.84
Good afternoon, I have been working on a simple problem for a long time because I am really not sure how to approach it. I need a user to type in a sentence at a command prompt, after that I trim the String and place it into an array to make it all lower case but the first letter of that sentence, that is why I take the String^ and place it into the array, I thought it would be the cleanest approach. Example of the command prompt result needed. The user types: this IS a TEST Once processed the output should be: This is a test My code: #include "stdafx.h" using namespace System; int main(array<System::String ^> ^args) { // User input Console::WriteLine(L"Please enter a sentence: "); String ^ userSentence; userSentence = Console::ReadLine(); //Triming Console::WriteLine(); String^ newStr = userSentence->Trim(); Console::WriteLine("Sentence trimmed applied:"); Console::WriteLine(newStr); //array section array<String^>^ data; data = gcnew array<String^>{newStr}; Console::WriteLine("from array:"); //loop through each character and make it lower-case. int i =0; for(int i = 0; data[i] != '\0'; i++) { data[i]->ToLower(data[i]); } data[0]->ToUpper(data[0]); Console::WriteLine(data); return 0; } However things don't workout the way I would hope and I get this error message on line 24: error C2446: '!=' : no conversion from 'int' to 'System:: String ^' I see that my data array content is trying to be used as an "int" but I don't how to fix this? I would greatly appreciate your help. John
https://www.daniweb.com/programming/software-development/threads/259155/clr-string-manipulation
CC-MAIN-2017-09
refinedweb
257
54.76
Hi, I am looking for a common and simple formula that would govern the value of a hypothetical financial instrument. Imagine that the hypothetical financial instrument's value is determined by the academic performance of a student. It would have to reward both consistent high performance and progress over time. The formula would have to have the following properties: Y = rate of return X = absolute score Z = change in score over a period of time 1) Rate or return (Y) is a function of both absolute score (X) and change in score (Z) 2) The financial instrument would reward performance both in absolute terms and in terms of change. For example, if a student begins the year below average and makes progress throughout the year then the financial instrument should have a positive payout. If a student begins and ends the year as a strong student, that too should have a positive payout. 3) The inverse should have lower payouts. That is, if a student begins and ends the year as a low performer, he should have a low or negative return; and if a student begins the year as a strong student but ends it as a week student, then he should have negative or low returns. 4) Lastly, the formula should accommodate different levels of risk tolerance. That is, lets say I want to use this for a low-risk class, then the payout would be between 0% and 5% with an average of 2.5%. On the other hand, if it were for a high-risk class, I would want to make the variability around the rate of return bigger (e.g., -95% to +100% with an average of 2.5%. Thank you for any help you can provide. Also, if you can tell me where and how the formula you recommend is being used today in real-life, that would be very helpful. Kindly, Jon
http://mathhelpforum.com/business-math/165504-formula-financial-instrument-print.html
CC-MAIN-2015-18
refinedweb
319
65.76
Why did the control center and notification area of my Redmi Note 8 have an opaque gray background after upgrading to Miui 12.0.4? Proxies-free.com: 100% Free Daily Proxy Lists Every Day! Get Free Proxies Every Day Why did the control center and notification area of my Redmi Note 8 have an opaque gray background after upgrading to Miui 12.0.4? I have created a script for modifying the chromium browser’s behavior when it starts. If the browser is freshly installed and if anyone opens it for the first time, the user will get a welcome note and sign-in form, which I want to suppress. According to my findings, the solution is to replace the /data/data/org.chromium.chrome/shared_prefs/org.chromium.chrome_preferences.xml file with a version that is generated after skipping the welcome note and sign-in form. The script changes the folder’s permission successfully, replaces the file, and again changes back the folder’s permission. But when I open the browser after reboot or without rebooting, that file is overwritten again and I still get the welcome note and sign-in form in both cases. But if I manually replace that file through the Android device monitor and reboots the device, it works. The browser I am using is Chromium v73.0.3674.0 for android. And here is the script #!/system/bin/sh su -c "chmod 777 /data/data/org.chromium.chrome" su -c "chmod 777 /data/data/org.chromium.chrome/shared_prefs" su -c "rm -r /data/data/org.chromium.chrome/shared_prefs/*.*" su -c "cp /mnt/internal_sd/MokiMDM/org.chromium.chrome_preferences.xml /data/data/org.chromium.chrome/shared_prefs/" su -c "chmod 660 /data/data/org.chromium.chrome/shared_prefs/org.chromium.chrome_preferences.xml" su -c "chown root:root /data/data/org.chromium.chrome/shared_prefs/org.chromium.chrome_preferences.xml" su -c "chmod 771 /data/data/org.chromium.chrome/shared_prefs" su -c "chown root:root /data/data/org.chromium.chrome/shared_prefs" su -c "chmod 751 /data/data/org.chromium.chrome" su -c "chown root:root /data/data/org.chromium.chrome" I was faking my location using FakeFree gps app and forgot to turn it off before the updates Feb/March 2021 were scheduled to be installed. After the update, I cannot get a GPS fix using any app (GPS status, GPS Test, GPSFix ). I have tried restarting it but still no gps Is there will be something command line or boot parameters which will make it suddenly work again ? I unlocked bootloader on my Xiaomi Redmi Note 9 and tried to Root it with Kingo Root mobile and desktop. Both keep failing and mobile gives error code 0x11f116. Now mobile version crashes when lauching. I couldn’t find any information about that code, so can anyone help? This is a website Question on Hackrrank called Hash Tables: Ransom Note: Given the words in the magazine and the words in the ransom note, print “Yes” if we can replicate the ransom note exactly using whole words from the magazine; otherwise, print “No”. Here is an example input: 6 4 give me one grand today night give one grand today Output: Yes And another: 6 5 two times three is not four two times two is four Output: No def checkMagazine(magazine, note): #Creating 2 Empty Dictionaries for the "Magazine" and the "Note" then filling them up UniqueWordsMag = set(magazine) UniqueCountMag = (0)*len(UniqueWordsMag) UniqueWordDictMag = dict(zip(UniqueWordsMag, UniqueCountMag)) UniqueWordsNote= set(note) UniqueCountNote = (0)*len(UniqueWordsNote) UniqueWordDictNote = dict(zip(UniqueWordsNote, UniqueCountNote)) for i in magazine: if i in list(UniqueWordDictMag.keys()): UniqueWordDictMag(i) += 1 for i in note: if i in list(UniqueWordDictNote.keys()): UniqueWordDictNote(i) += 1 #Checking for existance in the magazine then checking for the correct count, print no if it does not fulfil conditions Success = False DesiredCount = len(note) Count = 0 for index,i in enumerate(UniqueWordsNote): if i in list(UniqueWordDictMag.keys()): if UniqueWordDictNote(i) <= UniqueWordDictMag(i): Count += UniqueWordDictNote(i) else: break else: break if Count == DesiredCount: Success = True print("Yes") else: print("No") It’s called from this main program, that’s provided by the challenge: def main(): mn = input().split() m = int(mn(0)) n = int(mn(1)) magazine = input().rstrip().split() note = input().rstrip().split() checkMagazine(magazine, note) if __name__ == "__main__": main() My code is currently taking too long on some lists (e.g. lists of size 30,000 or more). Are there any optimisations I can make to make this a bit more legible and faster? my Samsung note 3 went on bootloop after my battery died tried charging to 50% then boot up but no hope i also tried wipe cash and disconnect the battery for 10 min an no hope I’ve got a locked Samsung Galaxy Note 10+ 5G (running the latest android 10 and patches) The phone is locked with a pattern (unknown) What are my chances of any data extraction with cellebrite or other forensics tools while I can not unlock the phone? Also how secure is Knox efuse? will it damage the phone/data when an untrusted bootloader is detected? It’s pretty self-explanatory. I need a new phone and i’ve narrowed it to these four phones that i think is suitable for my price range, which one is the best and also what are the pros and cons on each phone? I have locked by screen via Find my Mobile (which is what my phone screen says) I tried a million ways to unlock it without doing factory reset. I desperately need the Samsung Notes account because I have several medical notes in there. Could you please tell me if there is a way to access them before I have to do a factory reset. Unless, of course, you could tell me how to unlock the screen. I greatly appreciate your help. If you’ve run into this issue while building a rust application error[E0463]: can't find crate for core| = note: the "wasm32-unknown-unknown" target may not be installed To solve this error run rustup target add wasm32-unknown-unknown in the file and that should correct the issue
https://proxies-free.com/tag/note/
CC-MAIN-2021-17
refinedweb
1,026
62.38
Slashdot Log In Core Python Programming Posted by samzenpus on Mon Nov 06, 2006 01:54 PM from the code-it dept. from the code-it dept.. This discussion has been archived. No new comments can be posted. Core Python Programming | Log In/Create an Account | Top | 148 comments | Search Discussion The Fine Print: The following comments are owned by whoever posted them. We are not responsible for them in any way. On the cheap side ... (Score:5, Informative) ( | Last Journal: Monday November 18 2002, @09:30AM) One might try out Alan Gald's fine Learning to Program [freenetpages.co.uk] site. Short on pretty. Long on usefulness. Oh, and all the thick books in the world will never help a budding python coder more than the tutor mailing list [python.org]. Re:On the cheap side ... (Score:4, Informative) ( | Last Journal: Wednesday February 07 2007, @11:04AM) For younger children... (Score:4, Informative) ( | Last Journal: Friday January 20 2006, @01:41PM) An interactive (has an immediate mode prompt) language like Python is very helpful for first learning. BASIC used to fill that role, but I like starting with structured concepts. Kids have no problem "getting" that indentation marks blocks. Some experts hate python because while the grammar is "context free", the lexing isn't. The grammar is defined in terms of INDENT and OUTDENT taking the place of '{' and '}' (or BEGIN and END). However, whether a given indent is an INDENT or OUTDENT depends on context. So you can't use a traditional lexical analyzer when programmatically generating/modifying python code. You have to translate leading whitespace to INDENT and OUTDENT based on lexical context when parsing, and translate INDENT and OUTDENT to the appropriate amount of leading whitespace when pasting code blocks. Personally, I don't find that this is a problem. Sure 'lex' doesn't work out of the box, but the custom lexing code is pretty trivial. And the indentation sure is intuitive. Maybe that means I'm not an expert. Python is easy to learn (Score:1) python.org (Score:2) () Got and Older Edition (Score:2) () Nice book report (Score:2) It's no wonder I skip straight to the comments -- these reviews are just about the most content-free section of slashdot. My favorite Python joke (Score:2) () A: That joke's not funny. portable gui (Score:3, Interesting) () After a year of fiddling with Python, I find I quite like it for some things, and it's not the right fit for other things. That's fine, there's no reason to be rabid pro- or rabid con- about any language. I happen to use Linux, OSX and Windows, and the number one annoyance for me is a lack of clear "native-looking" GUI or OpenGL toolkit offering that is reachable by scripting languages like Perl and Python. I'd like to see PyGame in a MacPort. The Images module was pretty easy to build but it should be in MacPorts too. I don't want to rely on X11 when on a Mac, but to use X11 when on Linux, which seems to be like bringing antimatter and matter together in the same universe. A GladeXML-like module that relies only on Aqua would be great. Similarly on Windows, you're relegated to some fugly Tk choice if you want portable GUI. I can't think of a toolkit that looks less native than Tk, unless you count the early Java Swing "Metal" theme. The fact that OSX still isn't standardized on python2.4 makes it hard to support python-rich applications like Blender, and we still run into problems where a 2.3 parser can't let scripts use 2.4 features (even smart scripts that try:except: to fall back gracefully). I think Leopard will be python2.4 but don't recall seeing official confirmation on that. I'm sure I've misstated something technically-- I don't have my notes from home to double-check a few things from my last gui toolkit search a couple weeks ago. Re:portable gui (Score:4, Informative) () Re:portable gui (Score:4, Informative) () wxPython [wxpython.org] is native on X11, Windows and Mac OS X. I used PyOpenGL [sourceforge.net] a few years ago and it was a very pleasant experience. It was easy to translate C examples to Python, without all the annoyances of using C. Obviously you wouldn't want to write a full game engine using Python, but it is nice for experimenting with OpenGL. Re:portable gui (Score:4, Informative) () QT [trolltech.com] with python bindings PyQt [riverbankcomputing.co.uk] will give you native looking GUI on all three platforms you are interested i.e windows, linux and OSX. Now QT4 is available as GPL even on windows, so its truly "free". QT also comes with QT-designer which IMHO is the best rapid GUI designer app. BN is overpriced (Score:3, Informative) () Amazon.com [amazon.com] $32.99 Overstock.com [overstock.com] $31.34 Half.com [ebay.com] $28.95 use the O'Reilly Pocket Reference first (Score:2) Python Tutorial (Score:1) Chapter 13?!?!? (Score:2) () System requirements for Python web dev seem high (Score:2) Popular frameworks like TurboGears, or Django, also require mod_python 3.x and apache 2.x. No problem if you are developing internally, but if you want a hosted solution, I'm not sure if python is practical. WTH?! (Score:1, Troll) () "Python, the dynamic object oriented programming language created by Guido van Rossum is known to deliver both the power and general applicability of traditional compiled languages without the complexities accompanying them." Sounds like a typical spamvertisement really! "Coupled with its ease of use" umm hell, python is notoriously known for bad coders, writing broken applications based on underdeveloped and unmature modules, breaking forward compatibility. Sadly enough, in the last two years, I have not seen any progress making python-based applications more stable. Programs like BitTorrent(!) have serious issues running on python-2.5(!) "programs written in Python can be run on multiple Operating systems and system architectures which gives it the same portability of any interpreted language." nothing new here, move along... "My first brush with Python was when I tried out a beautiful game called PySol" FOR CRYING OUT LOUD!!! Pysol is the ultimate proof that python programs are incredibly impossible to maintain forward because the library/module layer is so incredibly unmature. Pysol is no longer developed ! It doesn't even work with Python-2.4 !!! Even if the original developer stopped working on it, somebody should have been able to pick it up and maintain it easily, and the fact that this didn't happen is proof again that python is barring its own progress. See [pysol.org] - last release was in 2003. Python has wasted my time as a packager/distro developer many many times, and ruined quite some weekends for me. The world would be a better place without Python. Verily? (Score:2) Bloat, bloat, bloat... (Score:2) () Yawn. Send the author back when they can get the size down to something the size of K & R while maintaining the same level of usefulness. Python not easy to use due to reference counting. (Score:2) Yahoo mail..... (Score:2) ( | Last Journal: Tuesday January 22 2002, @05:54AM) - The search function never works as intended (I want to look for messages only in one folder, damnit!). So assuming this guy is very clever, Python must be broken or too dificult to use. Re:Python is SLOW (Score:3, Insightful) In this case, would you really care about execution speed? I'll just go for the ease of string/files/array/hashes manipulation, write a powerful script in 10 minutes and go drink a coffee while my script works for me and you're still struggling with your char str[80];. Re:Python is SLOW (Score:1) Re:Python sucks (Score:3, Interesting) () Regarding the indentation-as-syntax, consider the following C code, where someone tried to add the baz() function to a loop: while (foo()) bar(); baz(); This code has an obvious bug. Baz() is not in the loop body, because the braces are missing. It's obvious from the indentation that that was the coder's intention. Why does one need an orthogonal and error-prone syntax for marking basic blocks, when the formatting already makes the intention obvious? Or, consider this example from the paper Algorithm Education in Python [uci.edu]: Here is the Insertion Sort algorithm exactly as presented in Cormen, Leiserson, Rivest, and Stein's "Introduction to Algorithms": Insertion-Sort(A) for j <- 2 to length[A] do key <- A[j] i <- j - 1 while i > 0 and A[i] > key do A[i+1] <- A[i] i <- i - 1 A[i + 1] <- key Here is the same algorithm, implemented in Python: def InsertionSort(A): for j in range(1, len(A)): key = A[j] i = j - 1 while (i >=0) and (A[i] > key): A[i+1] = A[i] i = i - 1 A[i+1] = key I haven't left anything out. Paste that into a Python interpreter and run it: >>> x = [2,7,3,8,1] # create test case >>> InsertionSort(x) # call routine >>> x # look at result [1, 2, 3, 7, 8] There are about a thousand other cool things, and of course there are inevitably some warts and poor design decisions too. Bottom-line for me, at least, it's the power of Perl, but at the extreme other end of the spectrum in terms of readability. The Google folks think so too. Re:Python is SLOW (Score:2) Meanwhile, I can whip up apps in Python in no time and they run far faster and with less nonsense and hassle. Slower than C? Yes. Better for rapid prototyping and quick problem solving on the fly? Yes. Best language I know to bridge structured and object oriented paradigms? Yes. If I haven't already bought this book, and I may have and just not remember given the stacks of them on my various desks, I will then do so and give a copy to my godson who is just learning about computers. The archaic school system might still be teaching LOGO and I want him to see something that he can actually use. Re:Python is SLOW (Score:5, Interesting) () Also, keep in mind Python does not use a virtual machine at all in the same way Java does -- which means it is somewhat like comparing apples to oranges. I was a full time J2EE engineer for a while and a recent convert to Python for general programming. The things I noticed are: - Java is great for large teams of programmers working together across the globe but as good as Python for smaller groups in the same place. - Python's web frameworks are amazingly fast and very powerful. - Java is almost text book perfect when it comes to programming. Unlike most other languages kids can come out of university and not have to change hardly anything to get started in the real world of Java. - It's very rare to see stock Tomcats or even stock JVM's meaning that most (commercial) Java apps send the entire 'Java OS' (VM) with their products. - Java web apps are very slow on startup, but scale well after the startup time. - Python has a better RORA system, though Java isn't to far behind. - Java terminology is very confusing compared to Pythons esp. since it is generally termed by marketers (Java2 is Java1.4 and then we hit Java 5 which is Java1.5 Here is how it seems companies leverage the languages 1. Java Manager's reason for Java: "I have a large IT infrastructure and want to do enterprise applications with teams across the globe." Engineer Translation for Java: "I have an over all large group of engineers and want to make an application designed by the business with at least some of the team out sourced." 2. Python Manager's reason for Python: "I have a small IT budget and want to agile and business reactive application development." Engineer Translation for Python "I don't have a budget to get more engineers and the requirements state that we need to be able to change and update the application on the business whim." In scenario number 1 it is a growing company who wants to hire lots of new engineers so the plus side of using Java is: 1. Just about every engineer (good or bad) knows it 2. It enforces C++ like development cycles 3. If done right, the objects are reusable and simple for an architect to understand 4. You can hire fresh outs In scenario number 2 it's a growing company who is not investing more money in the IT department but expects better results for the buck put into it. The plus side of Python would be: 1. It's a RAAG language (read at a glance) which means you can skim through the code quite quickly without needing tracers or debuggers. 2. By design each engineer is a mini architect 3. If done right, the objects are reusable and simple for engineers to grasp quickly 4. The quality of engineers you get tend to be quite high since most Python engineers are converts from other languages with X years of experience in the field. (though it also means you can't hire as quickly). Bottom line there is no right or wrong answer as to which is better or faster. Python is faster in some cases and Java is faster in others and it largely depends on how you run your business and the money that you want to spend in IT as to which one would help your company. Re:Python is SLOW (Score:2, Informative) () ...and it need not be said. Between Pyrex [canterbury.ac.nz] and Psyco [sourceforge.net], there's really very, very few applications that a language like Python isn't appropriate for. Premature optimization is the far more common programmer sin these days than choosing a language that's "too slow." Except for a few, specific application domains (that only a minority of coders are writing) dynamic languages like python are an excellent choice on today's hardware. And if you need it to be faster, just profile, find the couple of spots that matter, and pull out Pyrex.. or even the C/Python API if it makes you feel manlier. :-) Plus, with things like PyPy [codespeak.net] + LLVM, Parrot [parrotcode.org], and IronPython [ironpython.com] emerging, things are only going to get better.. don't be the last one on the dynamic boat! Re:Python is SLOW (Score:1) Ruby is easily, measurably, slower than Python - its a big topic of discussion in the Ruby community and the subject of numerous projects to address. Re:Python is SLOW (Score:5, Informative) Really? hmmm, my team runs a huge data warehouse in which all data is transformed via python programs. This means 40+ million rows a day get hash table lookups, business rule validations, type changes and various transformations. Then most of that data goes through an additional metadata-driven validation process that checks and confirms every single field. Again, metadata-driven - so a oouple hundred lines of various hash table lookups to determine exactly what validation applied to each field. Ok, now let's talk performance: 1. io performance (most critical factor here) a. same as c, in other words, extremely fast 2. cpu performance a. much slower than c, but workable b. psycho helps a ton c. the ability to rewrite key functions and classes is cool Let's also talk about productivity 1. great for ease in training part-time or junior programmers 2. great for immediately understanding old code 3. great for writing robust test-driven code 4. good for very quickly assembling a solution The above combo of ease of writing, ease of maintaining puts it far ahead of perl, tcl and java. Ruby is really the one other one in this niche I can think of off the top of my head. And even there Python appears stronger on the maintenance side. So, yeah - I'm sure there are many applications that have more significant performance requirements than ours does. But for this large application it is completely fine. Re:Python is SLOW (Score:2, Insightful) () The key to getting good performance out of Python is to know and use the libraries well. Most of the performance sensitive library calls are implemented in C and have been optimized. As long as you use those instead of reinventing the wheel, you will get pretty decent performance from Python. Python's standard library is very complete ("batteries included"), for example it includes a unit testing framework and a profiler. Additionally, by being able to implement things in a small amount of code, you'll get a better overview of what your program is doing. This means it is easier to spot where the performance bottlenecks are. If your program is so complex that you don't realize you're using an O(N*N) algorithm where O(N*ln(N)) is also possible, no fast compiler will be able to compensate for that unless your data sets are really small. Ruby is SLOWER (Score:3, Funny) () Re:Python (Score:3, Interesting) () <pre>print '%(imperative)s, a %(adjective)s %(noun)s!' % {'imperative': 'Look!', 'adjective': 'built-in', 'noun': 'templating system'}</pre> Re:Python is SLOW (Score:2) That simple stupidity just made everyone who knows anything about Ruby and Python dismiss your post as utter nutjobbery. Java is indeed faster than Python by a large margin (unless the runtimes are short, in which case the sheer monstruosity of the JVM's startup time kills Java's perfs). TCL compares very favourably to Python, even though it's mostly slightly slower, unless you're using Regexp (the Tcl regex engine is just wicked fast). But Ruby on the other hand, is one of the slowest languages available today. The current baseline implementation is a piece of crap, it's wasteful, it doesn't have any optimization, it's more or less the slowest and worst way to implement an interpreted language. Even though Ruby is a quite nice language, speed is definitely not it's forte. The only way for Python to be slower than Ruby would be to code Ruby in Ruby while you're coding Java in Python (using Java idioms and techniques while producing Python code, which is a bad idea). Re:Python is SLOW (Score:1) ( | Last Journal: Tuesday November 14 2006, @11:20AM) This is why there is so much interest in a Python compilier--compiliers are much faster than interpeters. There are some starting projects--such as psycho and Python 2 C Module Generator [sourceforge.net] Java and TCL have certainly had many more years and manpower to optimize thier implementations. I don't know much about Ruby. I'm sure in a few years, Python will improve too. Re:Python is SLOW (Score:1) Re:Python is SLOW (Score:2, Interesting) () Matplot is slow (Score:2)
http://books.slashdot.org/books/06/11/06/159250.shtml
crawl-002
refinedweb
3,210
72.16
pcibios_find_class, pcibios_find_device − find a PCI class or device #include <linux/bios32.h> int pcibios_find_class(unsigned int class_code, unsigned short index, unsigned char* bus, unsigned char* device_fn); int pcibios_find_device(unsigned short vendor, unsigned short device_id ",unsigned short "index, unsigned char* bus, unsigned char* device_fn); The pcibios_find_class function searches for a certain class of device on the PCI bus. In this instance, class is used to represent a few different categories of devices. Some examples are storage, network, display, and memory classes. The classes are defined by the PCI Specification, and the class_code is matched with the dword in the configuration space of the device at offset 0x08. The pcibios_find_device function finds a device on the PCI bus that has the matching device and vendor ids. The vendor ids are assigned to the PCI Sig to vendors, who in turn assign device ids to the devices they develop. The vendor and device ids are encoded in dword 0x00 of the configuration space. Both pcibios_find_class and pcibios_find_device include an extra index parameter, which is used to select the specific device if there are multiple matches. An index of 0 matches the firts located board, 1 the second, and so on. The bus and device_fn parameters are PCI specific cookies that are passed to other pcibios functions to access the configuration space of the located device. On success, the functions return PCIBIOS_SUCCESSFUL. Otherwise, one of the following error codes is returned: PCIBIOS_DEVICE_NOT_FOUND There is no device that matches the search criteria, PCIBIOS_BAD_VENDOR_ID The vendor id is invalid. (0xffff is not a valid id.) PCIBIOS_FUNC_NOT_SUPPRTED The PCI subsystem is not available Linux 1.0+ pcibios_present(9) /usr/include/linux/pci.h, /usr/include/linux/bios32.h PCI Local Bus Specification Kirk Petersen (kirk AT speakeasy DOT org)
http://man.sourcentral.org/MGA3/9+pcibios_find_class
CC-MAIN-2017-47
refinedweb
292
54.83
In our previous example, we output an amended string to the browser within the printBR() function. Sometimes, however, you will want a function to provide a value you can work with yourself. If your function has transformed a string you have provided, you might want to get the amended string back so you can pass it to other functions. A function can return a value using the return statement in conjunction with a value. return stops the execution of the function and sends the value back to the calling code. Listing 6.4 creates a function that returns the sum of two numbers. 1: <!DOCTYPE html PUBLIC 2: "-//W3C//DTD XHTML 1.0 Strict//EN" 3: ""> 4: <html> 5: <head> 6: <title>Listing 6.4 A Function That Returns a Value</title> 7: </head> 8: <body> 9: <div> 10: <?php 11: function addNums( $firstnum, $secondnum ) { 12: $result = $firstnum + $secondnum; 13: return $result; 14: } 15: print addNums(3,5); 16: // will print "8" 17: ?> 18: </div> 19: </body> 20: </html> The script in Listing 6.4 prints the number 8. Notice in line 11 that addNums() should be called with two numeric arguments (line 15 shows those to be 3 and 5 in this case). These are stored in the variables $firstnum and $secondnum. Predictably, addNums() adds the numbers contained in these variables together and stores the result in a variable called $result. The return statement can return a value or nothing at all. How a value passed by return is arrived at can vary. The value could be hard-coded: return 4; It could also be the result of an expression: return ( $a/$b ); Finally, it could be the value returned by yet another function call: return ( another_function( $an_argument ) );
http://books.gigatux.nl/mirror/php24hours/0672326191_ch06lev1sec4.html
CC-MAIN-2018-09
refinedweb
289
72.76
Tools PMC Meeting 2010-12-22 - Doug Schaefer, David Williams Agenda - What's up with (re)using other project's namespaces? Anything left to discuss? - Doug and I agreed its primarily up to JDT (in this case) to complain, but we discussed concerns about the general case and what ObjectTeams was doing about this case, and wondered if we should invite them to a PMC meeting to discuss outlook/plans? - Why isn't the new "performance tools" proposal in TPTP? Suspect we know the reason but should we assume too much? - Action Item: dw to ask on proposal pages what package names new windowsbuilder and perf tools project plan to use (we hope they plan to convert to "org.eclipse....". - Action Item: dw to ask (encourage?) if VE project should get to good "stopping point" and then join forces with windowBuilder efforts ... maybe provide bridge/migration tools? Just to ask. - Proposed next year's December meeting be held on second Wednesday of December, instead of the fourth Wednesday ... December 14, instead of December 28! :) Next Meeting - January 26th, 2011 Calendar
http://wiki.eclipse.org/index.php?title=Tools_PMC_Meeting_2010-12-22&redirect=no
CC-MAIN-2016-40
refinedweb
180
75.1
Drools is used everywhere and it grows rapidly, it is almost a standard. It is easy to find someone with Drools experience since it is frequently used by students and developers. There are many conferences, books and blogs about it. It is integrated in Spring, Camel (see Blog chapter 6), but it is also used in commercial products like Security Identity and Governance from IBM. Drools was developed by companies JBoss and RedHat on Java platform. It is available under free ASL 2 license which allows developers to do any changes or fixes. Development environment is available as an open source plug-in for Eclipse. RedHat provides professional support in many countries. Drools Guvnor is a centralized storage for the Drools Knowledge Base (see Blog chapter 2). It contains editors and tools for execution of many rules. Guvnor development environment is open source and integrated in Eclipse. Drools and Guvnor can also be integrated in application servers such as Oracle Weblogic or IBM Websphere and not only in JBoss. Another development tool for rules is Corticon. Its development environment is open source as well and integrated in Eclipse. Engine is written in Java and .NET. Corticon uses SOA services. Big companies such as IBM, Oracle, SAP, TIBCO use Corticon in their products. Corticon is however not an expert system, its decision table is only a simple sequence engine. The decision table is described in this Blog, chapter 5. It means that rules aren't coded, they are written in the decision table. It is not a problem, but it hasn't got so many options as Drools, which I have chosen to look at. Example 1. Imagine that you apply for a mortgage. The bank, which evaluates your application, also controls whether you are at least 18 years old and whether your income is high enough to pay back the money, etc. If you meet these requirements you get the mortgage. If you don't, your application will be canceled. Example 2. Imagine that you own an e-shop. You want to prefer regular and registered customers. The new and registered customers get the discount of 2% and regular and registered customers get the discount of 5%. The next example describes this situation. Drools is an expert system based on knowledge. Gained knowledge is processed to create a Knowledge Base, which is then used to infer the solution. Rule engine processes unambiguous rules against a set of facts given as input. Rules are basically knowledge described as "When condition is true Then take the desired action". Rules in Drools are usually defined in the MVEL expression language. At the beginning of the rule use the keyword rule and specify the rule name. After naming the rule you can list rule attributes and their values and then define the actual rule logic with the condition and action. Variables start with dollar symbol $ by convention. Rule attributes: Knowledge base is an interface that manages a set of rules and processes. The main task of the knowledge base is to store and re-use rules because creation of rules is very expensive. Knowledge base provides methods for creating a Session. A session keeps the rules, facts and other resources. Data (facts) and rules are separated. Facts are rules data, from Java perspective they are implemented as POJO (Plain Old Java Object). There are two types of knowledge sessions: We use development environment Eclipse with open source Drools plug-in. It allows for editing and managing of rules and getting prompt feedback in debug mode. Let's code an example of an e-shop from the chapter 1. The customer adds items to the card. These products (items) are of a certain quantity (qty). If the customer is new, isNew == true. public class Customer { private Cart cart; private String coupon; private boolean isNew; public static Customer newCustomer() { Customer customer = new Customer(); customer.isNew = true; return customer; } public void addItem(Product product, int qty) { if (cart == null) { cart = new Cart(this); } cart.addItem(product, qty); } //getters and setters for all variables } How to call the rules: //create session - compare below "Session_For_DRL_File.java" and Session_For_DecisionTable.java KieSession kSession = createKieSession(); Customer newCustomer = Customer.newCustomer(); // isNew == true Product p1 = new Product("Laptop", 15000); Product p2 = new Product("Mobile", 5000); newCustomer.addItem(p1, 1); newCustomer.addItem(p2, 2); kSession.insert(newCustomer); kSession.fireAllRules(); kSession.dispose(); There are two options how to store rules: For each of these options a new session must be created, this is described in next two chapters. package com.javacodegeeks.drools import com.javacodegeeks.drools.model.Customer; import com.javacodegeeks.drools.model.Product; rule "Discount for registred customer" when $customer:Customer($coupon: coupon == "DISC01") then $customer.getCart().addDiscount(((double)$customer.getCart().getTotalPrice())*0.05); end rule "Discount for new customer" when $customer:Customer($coupon: isNew == true) then $customer.getCart().addDiscount(((double)$customer.getCart().getTotalPrice())*0.02); end Configuration file kmodule.xml defines the rules folder. How to create a session in drools file: KieServices ks = KieServices.Factory.get(); KieContainer kContainer = ks.getKieClasspathContainer(); kSession = kContainer.newKieSession("ksession-rules"); How to create session for Decision table: KieServices kieServices = KieServices.Factory.get(); KieFileSystem kieFileSystem = kieServices.newKieFileSystem(); Resource resource = kieServices.getResources().newClassPathResource("shopping_cart_customer.xls"); kieFileSystem.write(resource); KieBuilder kbuilder = kieServices.newKieBuilder(kieFileSystem); kbuilder.buildAll(); KieRepository kieRepository = kieServices.getRepository(); KieContainer kContainer = kieServices.newKieContainer(kieRepository.getDefaultReleaseId()); KieSession kieSession = kContainer.newKieSession(); The simplest way to call Drools rules via REST web services is probably to use Spring Boot. Create a singleton bean with knowledge base. When a validation request is received, create new knowledge session, insert facts and execute the rules. If Spring is not used make sure the knowledge base is created only once. See this link for more info. The Guvnor rules can be called via REST web services as well. The source files of the above examples for Eclipse: Dools_DecisionTable.zip. To run rules in rules files use DroolsDrlFileExample.java. To run rules in Decision Table use DroolsDecisionTableExample.java. Java 8 was used in this example. DSL in Drools & recommended and related post Publikované: 26. nov 2015 14:56 | Počet prečítaní: 15069Publikované: 26. nov 2015 14:56 | Počet prečítaní: 15069 Do you see yourself working with us? Check out our vacancies. Is your ideal vacancy not in the list? Please send an open application. We are interested in new talents, both young and experienced.Join us
https://blog.davincisoftware.sk/how-to-code-rules-in-drools
CC-MAIN-2018-39
refinedweb
1,057
52.15
My Omnipytent plugin for Vim is a central part of my workflow, but it seems to be a bit hard for other people to grok it. More specifically - to understand why would they need something like that. So - I'm making this post to explain the rationale behind Omnipytent and to demonstrate it's worth. The problem: running commands TL;DR - this section explains why I needed to create a plugin for something most developers just... do. If you don't care about justifications, just skip it and go directly to the next session - "Using Omnipytent". This may look like a solved problem - you have ran commands before you ever heart of Omnipytent. Heck - you probably ran commands before you even heard of Vim! Why do you need a plugin for that? That's what the command line is for! As Vimmers we tend to adhere the "Unix is my IDE" philosophy - every development task has a command line tool, and we just run it with the arguments we need. So - my project can be built and ran with simple commands. And I know these commands. But... - Do I really have to type the same command each and every time I want to run it? - And if I need to build with different arguments - do I add them every time I type the build command? Or do I change the actual build file to make them the default? - I want to run a specific test - do I need to type it's name every time? Or, I can paste it - but then I need to keep it in the clipboard, or copy it each time... - I need to run the tool with certain arguments(yes, this should be a test, I'll make this a test, I promise!) - do I type these arguments every time? You get the idea - I'm lazy and I don't want to keep typing the same command line commands over and over again. What can I do? So... map some keys? An obvious choice - if there is a command you use a lot and want quick access to, just set a keymap. A simple solution - but for me, at least, it was not flexible enough: I work on several projects in different languages and environments, and I need different commands to build each project. The usual Vim solutions is to use :nnoremap <buffer>s :autocmds or in filetype plugins - but what keys will I set, for example, for XML files? I may want to build while in one of those! Even in the same environment, I need different ways to run(and sometimes build) different projects. Each project has it's own entry point, and unless you only work on single-file scripts that entry point will not be the file in your current buffer. Having different config for each project does not scale. Even in the same project, I often want to change these commands. Build with a different flag, run with different arguments. Changing the keymap each time is too much trouble. No... I want something I can easily change - without touching my .vimrc! Just use the command line history like everyone else A straightforward solution - if you use a command a lot, it's going to be in the history, so just Ctrl+r in Bash to find it. That's good and all when you work a single project, but with many projects - they are just going to override each other's history. So... I'd still like something better. Also, I may be risking getting my Vim card revoked - but I really don't want to context-switch to a terminal emulator every time I want to build or run what I'm working on. And Vim's own history as not as easy to navigate - not to mention I need it for command-mode commands... You spoiled brat! Put these commands in .sh files and get it over with! That's another common solution(though apparently not as common as the first two) - creating simple scripts for the commands. From the shell, or from Vim's :!, it's easy to tab-complete and launch these scripts. And I can even set keymaps to the different scripts, and have the same keymap do project-specific stuff in different projects! But... all these files scattered all over the project create a huge mess. So we need to: Have a single file containing all these commands Now we are getting somewhere! It can be a simple bash script with case on the first argument, and you could just set it to have as many commands as you want. Or - you could go fancy and abuse a build system, which usually have nicer syntax, and use their tasks as commands. So that's what I did - I chose Rake, because it wasn't colliding with existing build systems(it's mainly used with RoR, and I didn't really need to have build and run commands there(at least not at first)), and I get to write my tasks in Ruby instead of Bash. Yey! But I still wanted more. What if, I thought, I had a plugin to ease the creation of new tasks, autocomplete task names for me, help me easily use a different file than the one rake targets without additional args, etc. etc. And then I realized - Rake is a Ruby library! If I can load it into Vim with the Ruby interface, I can run my tasks inside Vim, and they'll have access to my Vim instance! This opens a new world of possibilities - I can make a task run with regular :!, or with Erroneous to fill the quickfix list, or in a VimShell terminal(Vim did not have :terminal back then, and Neovim was not even conceived), or load a log file in a buffer, or... or anything I wanted! And that's how Integrake was born. And when I had to abandon Ruby so I can move to Neovim - I rewrote the whole thing in Pyhton - and that's Omnipytent. Using Omnipytent To demonstrate Omnipytent I will use this example Java Spring project. Simple tasks and commands So, after cloning the repository, let's say I want to run tests. This is a Maven project, so we run tests with mvn test. I'm going to do it with Omnipytent: So... what happened here? First thing first - I have set these in my .vimrc: let g:omnipytent_filePrefix = '.idanarye' let g:omnipytent_defaultPythonVersion = 3 This means I want my tasks file to begin with my name and be hidden( .idanarye) and I want to use Python 3(you can write your tasks files in Python 2 or Python 3). The tasks file is supposed to be personal, so we won't have to invest effort in making it portable to allow other developers to use it. We don't check it in to source control, and even if we do - other developers that happen to use Omnipytent will have their own tasks file with a different name. So, with Vim opened in the repository's root, I run :OPedit test and it opens the task file for that project - .idanarye.omnipytent.3.py. Because the file did not exist before it added some imports, and because I wanted to edit a non-existing task it created a skeleton for that task - and all that's left is to write the task's body: import vim from omnipytent import * @task def test(ctx): BANG << 'mvn test' So, what do we have here? Imports are imports - we have vim - the built-in interface for Vim from Pyhton - and a start import from omnipytent with the common things you are going to want to use in a tasks file. One of the is task - a decorator we use to - surprise surprise - create tasks. The other is BANG - a Shell Command Executor. Shell command executors are handles for running shell commands - BANG specifically is using Vim's bang command( :!). There are other shell command executors, and you can define your own - it's all in the docs. The << operator in shell command executors can be used to execute a string as a shell command. And once I save the tasks file and run :OP test - Omnipytent executes the code of the test task and runs all the tests. The << operator executes the string as is. You can also use it as a function - and it'll quote each argument(which is better if you get them from a variable): @task def test(ctx): BANG('mvn', 'test') The third way to use shell command executors is with Plumbum - a shell combinator library for composing shell commands with Pythonic syntax. If you have it installed, and import omnipytent.interation.plumbum in your tasks file, you can use the shell command executors like Plumbum's background and foreground modifiers BG and FG. Since you usually want Plumbum's local to start the commands, you can import that from omnipytent.interation.plumbum: from omnipytent.integration.plumbum import local local['mvn']['test'] & BANG Since we are going to be using Maven quite a lot, might as well bind local['mvn'] globally: import vim from omnipytent import * from omnipytent.integration.plumbum import local mvn = local['mvn'] @task def test(ctx): mvn['test'] & BANG OK - but :! is not a very convenient way to run a test - certainly not with a tool that spans you with text like Maven. How about we run it with a terminal emulator instead? It's simple - all we have to do is use a different shell command executor - TERMINAL_PANEL - and it'll create a Vim 8 or Neovim's terminal emulator: OK... but why? So far, we didn't really need Omnipytent - couldn't we just run these commands, right from Vim's command mode? Well, yes, but running them with Omnipytent has two advantages: This is a Maven project, so the command is :!mvn test. If it was a Gradle project, I'd need :!gradle test. And with Ant I'd need :!ant test. Or maybe :!ant junit? Ant is free-spirited like that, so it can be anything. And what about flags you sometimes need to set? And that's just Java - other languages have their own various build systems... With Omnipytent, it's always :OP test- because you don't depend on what build system the project's creator picked and how they chose to configure it - you always create your own Omnipytent task testto run it. You can even map a key to it, and it'll work with any project(after your created the task for it). Personally, I mapped many short generic verbs to an "Omnipytent leader" followed by their first letter: They don't all do something on all my projects, but as projects get big I tend to have many different useful tasks and it's nice to have keymaps available for them. Sometimes commands need arguments - like the test's name when you want to run a specific test. You can't bind that in your global .vimrcbecause it's constantly changing - but it's easy to edit an Omnipytent file: import vim from omnipytent import * from omnipytent.integration.plumbum import local mvn = local['mvn'] @task def test(ctx): mvn['test']['-Dtest=ClinicServiceTests#shouldFindOwnersByLastName'] & TERMINAL_PANEL So - we can use :OP test(or the key(s) we mapped to it) to run this test, and when we want to work on a different test - we can just edit the tasks file. OK - but what if we want something more dynamic? Maybe we don't want to edit the tasks file each time, and prefer to give the test to the command? We can do that too - with task arguments: Task arguments and completion @task def test_specific(ctx, testname): mvn['test']['-Dtest=' + testname] & TERMINAL_PANEL And now, we just need to give that argument to our task with: :OP test_specific ClinicServiceTests#shouldFindOwnersByLastName Aaaaannnd... we are back to square one - because if we are going to type the test's name anyways we could have just used: :terminal mvn test -Dtest=ClinicServiceTests#shouldFindOwnersByLastName So, why use Omnipytent? As you may have guessed from the subsection's title - completion! Omnipytent already gives you command mode completion for task names, and if you want to you can easily define completions for the task arguments. If I were to create a generic completion plugin for Java tests, I would need to make it super-robust to account for the different styles and conventions. Maybe even run Maven/Ant/Gradle with some injected target that emits them. But here I just need them for one specific project - so I don't need to put all that effort, and can just depend on the characteristics of the tests: - They are all inside src/test/java. - They are all voidmethods. - They all have @Testin the line above them. So - all I have to do is grep for the @Test lines, get the lines after them, and extract the filename and the method name from those lines. I can quickly write something like this: import re pattern = re.compile(r'(\w+)\.java-.*void (\w+)') for line in local['rg']['-e', '@Test']['--after-context', 1]['src/test/java']().splitlines(): m = pattern.search(line) if m: class_name, test_name = m.groups() yield '%s#%s' % (class_name, test_name) This is definitely not plugin-grade - but for a personal search snippet just for me and just for this project it's acceptable. And now all that's left is to make it the completion function for test_specific: @task def test_specific(ctx, testname): mvn['test']['-Dtest=' + testname] & TERMINAL_PANEL @test_specific.complete def test_specific__completion(ctx): import re pattern = re.compile(r'(\w+)\.java-.*void (\w+)') for line in local['rg']['-e', '@Test']['--after-context', 1]['src/test/java']().splitlines(): m = pattern.search(line) if m: class_name, test_name = m.groups() yield '%s#%s' % (class_name, test_name) Interacting with Vim Running tests is nice - but we also want to build the project, don't we? "use :make" - a thousand Vim users would scream at once(if... they were reading this at the same time). OK, let's use :make: Oh, right - my &makeprg is set to Gradle for Java files, and this is a Maven project. Well - I don't want to change my .vimrc to use Maven - so let's use an Omnipytent task! I run :OPedit compile to scaffold the compile task, and write this: @task def compile(ctx): with OPT.changed(makeprg='mvn', errorformat=r'[ERROR] %f:[%l\,%v] %m'): CMD.make.bang('compile') What's going on here? OPT- the helper for setting Vim options. We could use OPT.makeprgor OPT['makeprg'] to get and set the&makeprg` option. OPT.changed(...)a context manager for temporarily changing the values of some Vim option. In this case - &makeprgand &errorformat. CMD- the helper for running Vim commands. CMD.make- Vim's :makecommand - can be used like a function. CMD.make.bang- this is :make!(because I don't like to get jumped to the first error) All together - when we run the compile task, it'll temporarily set &makeprg and &errorformat, run :make! compile, and then set &makeprg and &errorformat back. This will result with executing mvn compile and running it's output through the proper error format to populate the quickfix list: Of course - instead of CMD.make you can use :make alternatives - e.g. you can install dispatch.vim and use CMD.Make. Or you can use CMD to do other things, unrelated to building the project... Extensions Writing the error format in each tasks file makes little sense. Chances are I'll use the same error format in many different projects. Same thing may be true for other things we define in our tasks files. To allow easy reuse of such things, Omnipytent supports an extension mechanism. A plugin can put a Python source file under it's omnipytent/ directory, and it'll become a child module of omnipytent.ext. For example, my MakeCFG plugin exposes such interface - a makecfg function for setting &makeprg and &errorformat for entries in it's database. So - if I have MakeCFG installed, I can write my compile task like this: ` @task def compile(ctx): from omnipytent.ext.makecfg import makecfg with makecfg('mvn'): CMD.make.bang('compile') Combining tasks together During development we often want to interact with the application we are working on. The one we chose is a web application, so we will want to run it, send commands to it, and stop it. Omnipytent can automate that as well! Let's start with running. The README says we need to use ./mvnw spring-boot:run - so let's write a task to run it in a Vim terminal: @task.window def launch(ctx): mvn['spring-boot:run'] & TERMINAL_PANEL Noticed anything new? Instead of @task I've used @task.window. This creates a special type of test called window task. Inside window tasks you can create new Vim windows which can be used in other tasks(we'll see that later). On it's own, it acts like a normal task - expect: - If you go to a different window during that task(you are expected to create one), when the window task is over you will be moved back to the window where you started. - If you run the task when the window it created last time is still open - it will be closed before the task runs. OK - so we can start the server whenever we want, and we will only have one running at a time. But what about when we don't need it? Do we have to kill it manually? No - we write a task: @task(launch) def kill(ctx): from omnipytent.util import other_windows with other_windows(ctx.dep.launch): CMD.bdelete.bang() There are several new things here: @taskgets an argument - launch! This makes the launchtask a dependency of the killtask - so it will be invoked whenever we call kill. ctx.dep.launch- that weird ctxargument we always had in our tasks is the task's execution context - it provides methods for interacting with Omnipytent itself, and is useful when we want to combine tasks -like we do now. ctx.depis the access point for Python objects passed to us from dependencies - in this case, because launchis a window task it automatically passes the window object( :help python-window) it created. other_windowsis a context manager which allows us to travel to other windows and promises to return us to where we started. It also accepts a window object argument, and when it does it brings us to that window - so we can do stuff in it. Window tasks have a special behavior when used as dependencies - when the window they were supposed to create already exists, they don't execute and instead pass the same thing they passed before. So when we call kill, launch will pass to it the window that the previous launch task created. We then go to that window with other_windows and delete that buffer to terminate the program and close the window: OK - so we have our server running - how do we use it? This server accepts JSON requests for finding a vet - let't create something to query it: @task.window def queries_terminal(ctx): shell = local['sh'] & TERMINAL_PANEL.vert.size(50) ctx.pass_data(shell) @task(queries_terminal) def find_vet(ctx, name): import json name = json.dumps(name) cmd = local['curl']['-s'] cmd = cmd['localhost:8080/vets.json'] cmd = cmd | local['jq']['.[] | map(select(.firstName == %s))' % name] cmd & ctx.dep.queries_terminal OK... this is starting to get complex. queries_terminal creates a terminal we can use to run our queries with curl. To make the results easier to read, it makes it a vertical terminal this time( .vert) and sets it to 50 columns( .size(50)). The it calls ctx.pass_data with the result of the terminal-opening command? What's going on here? The result of a terminal opening is a shell command executor you can use for interacting with the terminal. We then use ctx.pass_data to pass it to dependent tasks. A window task will automatically pass the window - but in this case we want to pass the terminal handler so that dependent tasks will be able to run things in it. Which leads us to find_vet, that constructs a curl& jq command to find a vet with a given name, and executes this command using ctx.dep.queries_terminal - the shell command executor we got from queries_terminal. Let's see it in action(I've moved the server's terminal to a tab because screen real estate): Easy! JSON is nice, but apparently PetClinic also supports XML. What if we want to tinker with both? We can make it an argument, or duplicate the task, or... use an options task! @task.options def query_format(ctx): json = dict(suffix='.json', filter=lambda name: local['jq']['.[] | map(select(.firstName == %s))' % name]) xml = dict(suffix='.xml', filter=lambda name: local['xmllint']['--xpath', '//vetList[firstName=%s]' % name, '-'] | local['xmllint']['--format', '-']) @task(queries_terminal, query_format) def find_vet(ctx, name): import json name = json.dumps(name) cmd = local['curl']['-s'] cmd = cmd['localhost:8080/vets' + ctx.dep.query_format['suffix']] cmd = cmd | ctx.dep.query_format['filter'](name) cmd & ctx.dep.queries_terminal WHOA! What's that? Don't be alarmed - most of it are just shell pipes stuff for filtering the data. Let's focus on the main new thing - @task.options. This creates an options task - a task used for choosing an option. This task uses a weird syntax - every local variable it creates is an option. In this case - xml and json. If you run find_vet without picking an option first, Omnipytent will prompt you to pick one. After that it'll remember your choice - but you may change it by invoking query_format directly(with an argument to pick the option or one to get prompted). Conclusion If you know some basic Vimscript, you could have created commands for all the things I demonstrated. But... you probably wouldn't. Too much hassle for things you can just type in the terminal. And even if you would, you wouldn't go the extra mile to add completion and choice-cache. Too much work for something you can only use in one project... Omnipytent's power is not in allowing you to do things - it's in making these things more accessible. When adding tasks is so easy(just :OPedit <task-name> and code it in Python), they suddenly worth the effort - even if you are only going to run a task a few times. So automate your workflow - because you can! Discussion (2) :) :)
https://dev.to/idanarye/omnipytent-5g5l
CC-MAIN-2021-21
refinedweb
3,783
73.17
0 Hi, I want to create a matrix containing 20 rows and 2 cols. I know how to do this, but I have these two files; number and amount (each file contains 1 col and 20 rows) and I don't know how to add these files into this matrix that I'm creating like this, import numpy as ny M = ny.zeros((20,2),float) M[:,0] = number M=[:,1] = amount Do I need a for loop to be able to add all the information into all the rows in the matrix? Because now I get this error message saying ValueError: setting an array element with a sequence. Also it complains about my files is not number, e.g. number-file rows looks like this Edited by sofia85: n/a
https://www.daniweb.com/programming/software-development/threads/392658/create-matrix
CC-MAIN-2017-26
refinedweb
131
76.56
. struct SBugData { float x; float y; }; Also I want to use one of microsoft's template classes. Templates are C++ things that allow you to write a function for an arbitrary data type. The one I like to use is the CArray class. Include the afxtempl.h before your structure declaration: #include <afxtempl.h> and then in a public area of your class declare a CArray template class as follows: CArray <SBugData, SBugData> m_BugDataArray; Yea, it looks funny, but that is the way you want to type it. This is sort of like declaring a data type of CArray CArray class when we want to add a new element. Since we have a list of data points, it is obvious that we want to have an array of SBugData. The second parameter is also SBugData meaning we will just pass the data to the array. (Alternatively we could have passed a 'reference' to the data, but that is another lesson). Let's go to the .cpp file for the document and add the code now. Expand the CBugTracksDoc in the ClassView. You should see the member functions for the document. Double click on OnNewDocument(). You will jump to the function in the .cpp file. This function is called every time a new document (file) is opened. All we want to do here is to clear out the array so it will be ready for the new data. Where you see the //TODO comment, add this line of code: m_BugDataArray.RemoveAll(); Now to fill up the array, jump to the Serialize() function. This is a function called when a new file is opened or saved. Instead of the good old FILE pointers you use in C with fopen, we are going to use microsoft's CArchive class. You will notice that a CArchive is passed (by reference) to the Serialize() function. This class has the same functionality as we get with the fread and fwrite functions. void CBugTracksDoc::Serialize(CArchive& ar) { // if not storing the data, read it if (!ar.IsStoring()) { SBugData Data; CString strOneLine; // read data in, one line at a time while(ar.ReadString(strOneLine)) { // convert the text to floats sscanf(strOneLine,"%g %g\n",&Data.x,&Data.y); // add the data to the array m_BugDataArray.Add(Data); } } } For the very basic display, we just need to add some code to draw the data. Go to the function OnDraw() in the view class CBugTracksView. This is the function that is called every time the window needs refreshed. All drawing is done through the CDC class. The CDC class has several drawing functions, here we will only use the MoveTo and LineTo calls. void CBugTracksView::OnDraw(CDC* pDC) { // get a pointer to the document class CBugTracksDoc* pDoc = GetDocument(); // get the total number of data points int N=pDoc->m_BugDataArray.GetSize(); // draw all of the connecting lines for(int i=0; i < N-2; i++) { pDC->MoveTo(pDoc->m_BugDataArray[i].x, pDoc->m_BugDataArray[i].y); pDC->LineTo(pDoc->m_BugDataArray[i+1].x, pDoc->m_BugDataArray[i+1].y); } } InitInstance() function in our CWinApp class CBugTracksApp. Near the end of the function add this line: // Enable drag/drop open m_pMainWnd->DragAcceptFiles(); Now let's take advantage of the status bar and put some useful text in it. The status bar is managed by the CStatusBar class, which is a protected member of CMainFrame. This means that we can't touch it from other classes. We can either move its declaration to a public part of the class or just a public member function to CMainFrame to change the status bar text. We will do the later. Right click on CMainFrame in the class view and select 'Add Member Function'. A dialog will pop up to help add the member function. Type in " void" (without the quotes) for the function type -- this is the return value of the function, and type in " ChangeStatusText(LPCTSTR text)" as the function declaration. Make sure that the 'access' is set to public. Press OK. This will automagically add the declaration to the .h file and a blank function to the .cpp file of CMainFrame. The LPCTSTR is one of many microsoft defines for data types. We could have alternately have typed " ChangeStatusText(const char *text)". LPCTSTR stands for Long Pointer to a Constant T STRing. A T-string is just a string that will work on computers with different character sets (like Japanese). On computers in the US, a T-string is just the same as a char *. CMainFrame .cpp file and add the code to change the text on the status bar. To do this we'll just use the CWnd function SetWindowText. CStatusBar is derived from CWnd so we can always use any of the CW: void CMainFrame::ChangeStatusText(LPCTSTR text) { m_wndStatusBar.SetWindowText(text); }. #include "MainFrm.cpp" Next go to our Serialize() function and modify the reading code to spit some text out to the status bar. We first get a pointer to the main window, which is the CMainFrame window in SDI applications. Since the function AfxGetMainWnd() returns a CWnd*, we cast it to a CMainFrame*. Then we use the CString's Format function and CArray's GetSize function to create a text string for the status bar. void CBugTracksDoc::Serialize(CArchive& ar) { if (!ar.IsStoring()) { SBugData data; CString line; CString strStatus; // get a pointer to the main window // (which is the mainframe for SDI applications) CMainFrame *pMain = (CMainFrame*) AfxGetMainWnd(); while(ar.ReadString(line)) { sscanf(line,"%g %g\n",&data.x,&data.y); // tell the user your reading points strStatus.Format("Reading point %d",m_BugDataArray.GetSize()); pMain->ChangeStatusText(strStatus); m_BugDataArray.Add(data); } // tell the user the total number of points strStatus.Format("Loaded %d points.", m_BugDataArray.GetSize()); pMain->ChangeStatusText(strStatus); } } IDR_MAINFRAME. ` ID_TRACK_ANIMATE', though this will be filled in automatically if you ever forget. In order to make Alt-A our hot key, go to the Accelerator resources and double-click on IDR_MAINFRAME. In the edit window, double-click on the empty box at the end of the list. From the drop list for the ID, select the ID of your new menu item ( ID_TRACK_ANIMATE). ' int' as the data type and ' m_nBugPosition' as the variable name. Make sure that it is public and press OK. OnNewDocument() in the document class. Add this line to initialize the new variable to -1. We will use the value -1 to designate that the track is not being animated. m_nBugPosition = -1; Next let's add the message handler for our 'Animate' hot key and menu. Press Ctrl-W to bring up the class wizard. In the class name drop box select the view class ( CBugTracksView) and in the Object ID list, select the ID of our new menu and hot key command ( ID_TRACK_ANIMATE). You'll see the two possible choices in the Messages list. Double-click on COMMAND to add a function to handle our new command. You will be prompted for a function name. Just accept the default one OnTrackAnimate() and press OK. You will see the function appear in the Member Function list near the bottom of the dialog. Double-click on the function to jump directly to the code. We set m_nBugPosition to zero and start a timer that will redraw the bug tracks in intervals of 0.2 seconds. void CBugTracksView::OnTrackAnimate() { // get the document CBugTracksDoc* pDoc = GetDocument(); // set the position to the first data point pDoc->m_nBugPosition=0; // create a timer with id=1 and delay of 200 milliseconds SetTimer(1,200, NULL); Next we need to handle the timer message. Ctrl-W back to the class view. Make sure you are looking at the view class, select the class as the Object ID, then double-click WM_TIMER in the message list to handle the timer message. Again, double-click on the function name to jump to the code. In the OnTimer function we will first check the ID of the timer to make sure we are responding to the correct timer. In this case we set the timer ID to 1. Then we will invalidate the window so that it will be repainted. void CBugTracksView::OnTimer(UINT nIDEvent) { if(nIDEvent==1) { // tell windows the view needs redrawn // note: the last parameter is the erase flag. // if it is TRUE, things will flicker like crazy. InvalidateRect(NULL,FALSE); } CView::OnTimer(nIDEvent); } All that is left now is to fix up the OnDraw() function in the view class. We need to first draw the red tracks, then the blue ones, then increment the position m_nBugPosition. If m_nBugPosition is larger than the number of positions we will set it to -1 and kill the timer. One of the new things in this code is the CPen class that is needed to change the color of the line. The way these graphical objects work is that you 'select' the object in to the CDC class. When you are done with it, you select the old one that was in there previously and delete the one you just used. void CBugTracksView::OnDraw(CDC* pDC) { CBugTracksDoc* pDoc = GetDocument(); ASSERT_VALID(pDoc); // make pens for solid lines of thickness 2 CPen RedPen(PS_SOLID, 2, RGB(255,0,0)); CPen BluePen(PS_SOLID, 2, RGB(0,0,255)); CPen *pOldPen = pDC->SelectObject(&RedPen); int i, N=pDoc->m_BugDataArray.GetSize(); // draw any tracks which need animated for(i=0; i < pDoc->m_nBugPosition-1; i++) { pDC->MoveTo(pDoc->m_BugDataArray[i].x,)pDoc->m_BugDataArray[i].y); pDC->LineTo(pDoc->m_BugDataArray[i+1].x,pDoc->m_BugDataArray[i+1].y); } // change pens pDC->SelectObject(&BluePen); // start drawing non animated tracks, but need to check for a // valid starting postion int start=pDoc->m_nBugPosition; if(start<0) start=0; for(i=start; i < N-2; i++) { pDC->MoveTo(pDoc->m_BugDataArray[i].x,)pDoc->m_BugDataArray[i].y); pDC->LineTo(pDoc->m_BugDataArray[i+1].x,pDoc->m_BugDataArray[i+1].y); } // deselect pens and delete them pDC->SelectObject(pOldPen); RedPen.DeleteObject(); BluePen.DeleteObject(); // move to next position or quit animating if(pDoc->m_nBugPosition!=-1) pDoc->m_nBugPosition++; if(pDoc->m_nBugPosition>=N) { pDoc->m_nBugPosition=-1; // stop timer 1 KillTimer(1); // redraw and erase so all lines are in initial state (blue) InvalidateRect(NULL); } }) Change static text color and sizePosted by Legacy on 11/15/2003 12:00am Originally posted by: Frank Hi,Reply I have a static text on the dialog. Can you show me how to change the text size and color? Greatly appreciate your help. Frank 7Posted by Legacy on 11/13/2003 12:00am Originally posted by: KRISHNADEVAN Database Pgmm ???Posted by Legacy on 11/03/2003 12:00am Originally posted by: Shailesh Good intro but give database programming also. Reply Changing a text colorPosted by Legacy on 10/28/2003 12:00am Originally posted by: Stella Silina Hello, I just have a question. I am working with Visual Studio 6.0 I have a static text in my Dialog Window. I need to change its color. Can you give me any suggestions on how to do it? Thank you very much in advance. Sincerely,Reply Stella Silina. Excellent tutorialPosted by Legacy on 10/17/2003 12:00am Originally posted by: KKamenov It is a truly difficult task to summarize into a short and clear tutorial something as complex as MFC , but the author did an exellent job.Reply Very helpfull tutorial. Exellent examples. Really great tutorialPosted by Legacy on 08/16/2003 12:00am Originally posted by: hub Hi, I must say that Your tutorual is just what I was looking for! It covers some stuff that was either skipped in books (one book to be precise...) or explained pretty confusing (like timers in the manuals). It is really great for a beggining and really easy to understand... MoveTo and LineTo Functions in Lesson 7Posted by Legacy on 06/18/2003 12:00am Originally posted by: Sathish Hi,Reply I was trying to run the program after typing your code. I am getting errors saying that MoveTo and LineTo are not members of the class CBugTracksDoc. How do I add those functions. They are also not listed in the popup box when I type pDoc-> Please help me in this regard. Thanks, Sathish. Help on Multi Frame display using SDIPosted by Legacy on 06/06/2003 12:00am Originally posted by: Chandra Mohan Hi All, Thanks for having a look. I want to have a SDI window, but on clicking a button next, should be able to display some other frame over this. (Similar to installation screens). Its an SDI Window and not dialog. Your suggestions will be highly useful. RegardsReply Chandra Cheers.Posted by Legacy on 02/18/2003 12:00am Originally posted by: Shazrul Thank you.Reply Cheers.Posted by Legacy on 02/18/2003 12:00am Originally posted by: Shazrul Thank you.Reply
http://www.codeguru.com/cpp/cpp/cpp_mfc/tutorials/article.php/c885/Visual-CMFC-Tutorial--Lesson-7-Data-Viewer.htm
CC-MAIN-2014-42
refinedweb
2,125
66.03
The QTimeLine class provides a timeline for controlling animations. More... #include <QTimeLine> Inherits QObject. This class was introduced in Qt 4.2. (e.g.,())); ... You can also use QTimeLine with the Graphics View framework for animations. The QGraphicsItemAnimation class implements animation of QGraphicsItems with a timeline.,().: This property holds the total duration of the timeline in milliseconds. By default, this value is 1000 (i.e., 1 second), but you can change this by either passing a duration to QTimeLine's constructor, or by calling setDuration(). The duration must be larger than 0. Access functions: This property holds the number of times the timeline should loop before it's finished. A loop count of of 0 means that the timeline will loop forever. By default, this property contains a value of 1.(). Resumes the timeline from the current time. QTimeLine will reenter Running state, and once it enters the event loop, it will update its current time, frame and value at regular intervals. In contrast to start(), this function does not restart the timeline before is resumes. See also start(), updateInterval(), frameChanged(), and valueChanged().(). If you want to resume a stopped timeline without restarting, you can call resume() instead. See also resume(),.().
http://doc.trolltech.com/4.5-snapshot/qtimeline.html
crawl-003
refinedweb
201
60.41
Q. C Program to Print Fibonacci Series upto N terms. Here you will find an algorithm and program in C programming language to print fibonacci series. First let us understand what fibonacci series means. Explanation : The Fibonacci sequence is a sequence consisting of a series of numbers and each number is the sum of the previous two numbers. For Example :- 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55, 89, 144, ……. Fibonacci Series Algorithm START Step 1->Declare variables i, a, b, nextTerm Step 2->Initialize the variables, a=0, b=1, and nextTerm = 0 Step 3->Initialize or Enter the number of terms of Fibonacci series to be printed Step 4->Repeat below steps n times -> print the value of a -> nextTerm = a + b -> a = b -> b = nextTerm STOP C Program to Print Fibonacci Series #include <stdio.h> int fib(int n) { int a, b, nextTerm, i; a = 0; b = 1; for (i = 1; i <= n; ++i) { printf("%d ", a); nextTerm = a + b; a = b; b = nextTerm; } } int main () { int n = 9; fib(n); return 0; } Output 0 1 1 2 3 5 8 13 21
https://letsfindcourse.com/c-coding-questions/c-program-to-print-fibonacci-series
CC-MAIN-2022-40
refinedweb
189
62.41
I am using a Logitech G9 mouse and running VMWare Workstation 6.5.3 on Vista x64. The guest OS is Win XP, and has the most current version of VMWare Tools installed. Left / right buttons and mouse wheel scrolling work fine in the guest OS, but the back / forward buttons are apparently not recognized. I have tried installing the Logitech software inside the guest OS as well, but it still did not recognize the back / forward buttons. (I didn't really expect this to work since the guest OS doesn't actually see the mouse hardware as a Logitech G9 directly anyway.) I vaguely remember seeing something a while back about editing the virtual machine config file to specify a 5-button mouse rather than the default 3-button setup, but I can't seem to find any specifics on how to do so in the VMWare documentation. Does anyone know if such a workaround exists, or is 5-button mouse functionality just not supported? After adding usb.generic.allowHID = TRUE to the vmx file, just enable USB for that VM and then go to the Hardware Manager (guest system) and "scan for hardware changes". New USB Devices will then be recognized by the VM and after that your back/forward buttons should work without deactivating the mouse in the host system. It won't work directly. Because VMware only emulates 6 states with it's generic mouse. (left, right and middle mouse button, scroll wheel up, down, pressed) But as a workaround you can use my tool I've just written in AutoIt for I really needed this function as well. #include <Misc.au3> $dll = DllOpen("user32.dll") Opt("WinTitleMatchMode", 2) Opt("TrayIconHide", 1) $vm = WinWait("VMware Workstation") While True If WinActive($vm) Then If _IsPressed("06", $dll) Then Send("{AltDown}{Right}") While _IsPressed("06", $dll) Sleep(1) WEnd Send("{AltUp}") ElseIf _IsPressed("05", $dll) Then Send("{AltDown}{Left}") While _IsPressed("05", $dll) Sleep(1) WEnd Send("{AltUp}") EndIf ElseIf _IsPressed("05", $dll) And _IsPressed("06", $dll) Then If MsgBox(1 + 262144, "Exit", "Do you really want to exit...?") == 1 Then ExitLoop EndIf Sleep(1) WEnd DllClose($dll) Just compile this on your own with AutoIt or download the compiled executable from my webspace: This will wait for a window including "VMware Workstation" in it's Title and if any of the Thumb Mouse buttons are pressed (Code 05 + 06) the KeyCombination of Alt+Left/Alt+Right is pressed. If you press both buttons together the tool will exit if you confirm the appearing dialog box. Add this parameter in your VM's VMX file. usb.generic.allowHID = TRUE Your buttons should now work - no installation of logitech software or anything required. For Windows host use AutoHotKey to change mouse button mapping: XButton1 :: !^+{NumpadLeft} XButton2 :: !^+{NumpadRight} Then in guest OS map them back: !^+{NumpadLeft} :: XButton1 !^+{NumpadRight} :: XButton10 times active 11 months ago Get the weekly newsletter! see an example newsletter
http://superuser.com/questions/35830/back-forward-mouse-buttons-do-not-work-in-vmware-workstation-6-5-guest-os/145972#145972
crawl-003
refinedweb
492
61.06
SETRESUID(2) Linux Programmer's Manual SETRESUID(2) setresuid, setresgid - set real, effective and saved user or group ID . An unprivileged process may change its real UID, effective UID, and saved set-user-ID, each to one of: the current real UID, the current effective UID or the current saved set-user-ID. A privileged process (on Linux, one having the CAP_SETUID capability) may set its.. These calls are available under Linux since Linux 2.1.44. These calls are nonstandard; they also appear on HP-UX and some of the BSDs. Under HP-UX and FreeBSD, the prototype is found in <unistd.h>. Under Linux, the prototype is provided by glibc since version 2.3.2. those for setRESUID(2) Pages that refer to this page: syscalls(2), credentials(7), nptl(7), user_namespaces(7)
https://man7.org/linux/man-pages/man2/setresgid.2.html
CC-MAIN-2020-40
refinedweb
135
56.76
masking scala.Seq. Defaulting to immutable sequence would be good for apps and fresh code. The situation is a bit more complicated for library authors. - If you have a cross-built library, and - if your users are using your library from multiple Scala versions - and your users are using Array(...) this change to immutable Seq could be a breaking change to your API. An example of such breakage is scopt/scopt#218. I cross-published scopt, and now it won't work with args. Even in Scala 2.13.0-M5, args is an Array[String]. A simple fix is to import scala.colletion.Seq in all source code. But I want to make it such that using Seq won't compile the code. unimporting scala.Seq First thing I thought of is unimporting the name scala.Seq, so I would be forced to import either scala.collection.Seq or scala.collection.immutable.Seq. import scala.{ Seq => _, _ } This does not work, since the name Seq is bound by the default import scala._ in the outermost scope. Even if it did work, this would require remembering to put the import statement in all source code, so it's not good. Jasper-M reminded me about -Yno-imports, which might be an option to consider. defining a dummy Seq Next, I tried defining a trait named Seq under my package: package scopt import scala.annotation.compileTimeOnly /** * In Scala 2.13, scala.Seq moved from scala.collection.Seq to scala.collection.immutable.Seq. * In this code base, we'll require you to name ISeq or CSeq. * * import scala.collection.{ Seq => CSeq } * import scala.collection.immutable.{ Seq => ISeq } * * This Seq trait is a dummy type to prevent the use of `Seq`. */ @compileTimeOnly("Use ISeq or CSeq") private[scopt] trait Seq[A1, F1[A2], A3] I am using nonsensical type parameters so the existing code won't compile. For example, Seq[String] in my code will be caught as follows: [info] Compiling 3 Scala sources to /scopt/jvm/target/scala-2.12/classes ... [error] /scopt/shared/src/main/scala/scopt/options.scala:434:19: wrong number of type arguments for scopt.Seq, should be 3 [error] def parse(args: Seq[String])(implicit ev: Zero[C]): Boolean = [error] ^ [error] one error found As long as the code is within scopt package, this should prevent the use of Seq. To use actual Seqs, we would import them as follows: import scala.collection.{ Seq => CSeq } import scala.collection.immutable.{ Seq => ISeq } If you care about your API semantics being the same across cross builds you might opt for CSeq for anything public. And maybe when you bump your API, you can change them all to ISeq. addendum: scala.IndexedSeq is affected too Sciss (Hanns) pointed out that scala.IndexedSeq are affected in the same way. So if you're doing this for scala.Seq you might as well check for scala.IndexedSeq too. addendum: Heiko Seq Sciss (Hanns) also reminded me about Heiko Seq, which Heiko wrote in Seq is not immutable! post back in 2013: package object scopt { type Seq[+A] = scala.collection.immutable.Seq[A] val Seq = scala.collection.immutable.Seq type IndexedSeq[+A] = scala.collection.immutable.IndexedSeq[A] val IndexedSeq = scala.collection.immutable.IndexedSeq } This will adopt the scala.immutable.Seq across all Scala versions. If you want to stay on scala.collection.Seq, you can use the Sciss variation: package object scopt { type Seq[+A] = scala.collection.Seq[A] val Seq = scala.collection.Seq type IndexedSeq[+A] = scala.collection.IndexedSeq[A] val IndexedSeq = scala.collection.IndexedSeq } If you don't want to go through your source deciding whether to use CSeq, ISeq, or List, this might be a solution for you. addendum: vararg Dale reminded about related Scala 2.13 migration issue, which is vararg. Given that Scala specification specifies that scala.Seq is passed on, vararg parameters will expect scala.collection.immutable.Seq. This matters if your users are calling your API as something(xs: _*), and xs happens to be an array etc. This is a Scala wide change, and it's something everyone has to change if you migrate to Scala 2.13.
http://eed3si9n.com/masking-scala-seq
CC-MAIN-2019-04
refinedweb
695
60.92
no it's still wrong, during the first pass it should find all the delimiters in the code that i'm looking for then compare them with the delimiters in the stack. It is only finding one of them... no it's still wrong, during the first pass it should find all the delimiters in the code that i'm looking for then compare them with the delimiters in the stack. It is only finding one of them... ok, so i added it into the catch block, and found the error. it was just an error where i had placed code to display what was being stored in strLine for debugging, don't need that anymore as i... the pass number is just a variable i called x that i incremented after each time through the while and printed so i knew how many times it is reading the text file and what is being seen with each... ok, here is it broken down a little better, i added another println stating the pass it was in during each loop of the while along with the pass number: run: Enter a file to be read: (EX:... Ok, i did the println() portion and it looks like it is reading in the entire text file. haha, i read it and did some text, using it with a variable that i tried to increment after each readLine call. int x = 0; after the readLine did x++; and then it went into: ... so what would you attach charAt() too? Would you simple say if(strLine.charAt() = "{") then do this.....? how would you implement charAt()? because i don't know exactly where the braces, brackets, etc will be? ok, so would i need to convert each line during the while loop into an array of characters before passing them into the if statements checking for proper types? I thought using the readLine() method would automatically read the entire line until it found no more words/characters then move to the next line? That would be the issue I am having, I can't make it find brackets, braces, etc on a line that has characters already on it. I'll look into it, either way i'm still at a loss for why it's not finding all the parameters i'm looking for in the first pass. I don't think the second pass is effecting this at all. I wrote it for two haha, didn't know a way to make it read twice without opening the file and closing then reopening and closing. New code after adding print statements after every push or pop with the stack /* * A Java program can have the following type of delimiters: {, }, (, ), [, * and ]. In a correct Java... how do you actually do the tag trick, i've never done that before. I will go through and add println() Updated code is below, it seems it is holding a value in the stack which is good, we are getting a error null for some reason, but the code still runs, only other problem is it is only holding one of... After adding a print statement right below the code while((strLine = br.readLine()) != null) { during the first read file cycle it prints out: run: I will go ahead and apologize for the massive code slice, but I am stuck on a problem. The code compiles and runs, but is not acting properly. I have tried to comment as best I can throughout the... Nevermind, managed to clear the error, code will compile and run, but gets stuck in an endless loop when it enters the TraverseMerge() method and i'm not sure why: package hw3_vinson; import... Here is the full code, the only error i'm getting is trying to use .next during my traverseMerge() method at the bottome package hw3_vinson; import java.util.LinkedList; import javax.xml.*;... What do you think of this: public Node get(int x) { int searchLoc = x; Node ref = firstElement; int counter = 0; I'm still at a bit of a loss as to what would be inside the: public Node get(int x) { int searchLoc = x; So.....: public int size() { int count = 0; Node ref = firstElement; while(ref != null) { Well right now an error, because where i declare temp1 and temp2 right under LinkedList LL03 i don't assign anything because i'm stuck there. I need a way to retrieve the starting node of each list... i meant it to be the built in .next not a method i create shouldn't have placed the (). When the end of one of the list is found it will jump to another if that says if (LL01 == null) { ...
http://www.javaprogrammingforums.com/search.php?s=27a7107eec829085389d36271688d488&searchid=1814070
CC-MAIN-2015-40
refinedweb
786
78.18
The MSDN documentation on the subject of Defining Inline C++ Functions with dllexport and dllimport was written with compiler-colored glasses. The statements are perfectly true, but they use terminology that only compiler-writers understand. The short version is that all modules which share an inline function are considered to be part of the same program, so all of the C++ rules regarding inline functions in programs need to be followed. Let's look at the paragraphs one at a time and translate them into English. You can define as inline a function with the dllexport attribute. In this case, the function is always instantiated and exported, whether or not any module in the program references the function. The function is presumed to be imported by another program. Okay, first of all, what is instantiation? In this context, the term instantiation when applied to an inline function means "The code is generated (instantiated) for the function as if it had not been marked inline." For the purpose of discussion, let's say that you have a function written as __declspec(dllexport) inline int times3(int i) { return i * 3; } Suppose that you compile this into a DLL, and that DLL also calls the inline function. int times9(int i) { return times3(times3(i)); } What code gets generated? The times9 function sees that the times3 function is inline, so it inlines the function body and there is no trace of a times3 function at all. The compiler generates the code as if it had been written int times9(int i) { return (i * 3) * 3; } That would normally be the end of it, except that the times3 function was marked dllexport. This means that the compiler also generates and exports a plain old function called times3 even though nobody in the DLL actually calls it as such. The code is generated and exported because you told the compiler to export the function, so it needs to generate a function in order to export it. This is not anything special about the dllexport keyword. This is just a side-effect of the rule that "If you generate a pointer to an inline function, the compiler must generate a non-inline version of the function and use a pointer to that non-inline version." In this case, the dllexport causes a pointer to the function to be placed in the export table. Okay, next paragraph:. What this is trying to say is that if you declare an inline function as dllimport, the compiler treats it just like a plain old inline function: it inlines the function based on the usual rules for inlining. But if the compiler chooses to generate code for the function as if it were not inline (because the compiler decided to ignore the inline qualifier, or because somebody took the address of the inline function), it defers to the generated code from the original DLL, because you said, "Hey, the non-inline version of this function is also available from that DLL over there," and the compiler says, "Awesome, you saved me the trouble of having to generate the non-inline version the function. I can just use that one!" The "I can just use that one!" is not just an optimization. It is necsesary in order to comply with the language standard, which says [dcl.fct.spec] that "An inline function with external linkage shall have the same address in all translation units." This is the compiler-speak way of saying that the address of an inline function must be the same regardless of who asks. You can't have a different copy of the inline function in each DLL, because that would result in them having different addresses. (The "with external linkage" means that the rule doesn't apply to static inline functions, which is behavior consistent with static non-inline functions.) Okay, let's try paragraph three:). The first part of the paragraph is just saying that an inline function defined as part of a class definition counts as an inline function for the purpose of this section. No big deal; we were expecting that. Update: On the other hand, it is a big deal, because it results in inline functions being exported when you may not realize it. Consider: class __declspec(dllexport) SimpleValue { public: SimpleValue() : m_value(0) { } void setValue(int value); int getValue() { return m_value; } private: int m_value; }; The SimpleValue constructor and the SimpleValue:: method are exported inline functions! Consequently, any change to the constructor or to getValue requires a recompilation of all code that constructs a SimpleValue or calls the getValue method. End update. The second part says that if the inline function uses a static local variable or a string literal, it is the same static local variable or string literal everywhere. This is required by the standard [dcl.fct.spec] and is what you would naturally expect: int inline count() { static int c = 0; return ++c; } You expect there to be only one counter. And the final paragraph:. This is just working through the consequences of the language requirement [dcl.fct.spec] that an inline function "shall have exactly the same definition" everywhere. If you change the definition in the exporting DLL and don't recompile the importing DLL with the new definition, you have violated a language constraint and the behavior is undefined. So there you have it. The rules of inline exported functions translated into English. I wonder who screwed this up. From past experience here it's almost always somebody. The penultimate paragraph leads us to a different conclusion: Don't mark inline functions as dllexport. If you need the definition to change ever, or it does something complicated, make it a non-inline function; that way when you edit it all of your clients will automagically pick up the change. If you /don't/ ever need it to change, make it as inline and leave it at that. You might end up with two non-inlined versions in your process (one in yours.dll and one in client.dll), but you'll also not be calling that through a pointer, so it's all swings and roundabouts. If a feature makes it impossible to update your code without asking your clients to rebuild, what that really means it makes it impossible for you to update your code PERIOD. Ergo, don't mark inline functions as dllexport, at which point all of this discussion is moot. This is similar to optional parameters in C#, and why you should not use optional parameters in a library. The default value of the optional parameter is placed in the client's code at compile time, not the library code. To change the default value in the library, you have to recompile all the clients. @Shelby: IIRC, optional parameters work that way in C++ too. The "function defined as part of a class definition counts as an inline function" part of C++ standard is evil, unexpected and confusing. Whoever decided that must have had a bad day. Or week. Conclusion: avoid defining functions as part of a class definition. @Shelby That's a rather maximalist position to hold. Perhaps instead of banning optional/default parameters from public methods in libraries, you should apply a softer rule that actually solves the problem of default parameter values being compiled in client code: don't use constants as default values; use sentinel values instead. In other words: public void Frob(string value = "Bits") // BAD { DoSomething(value); } public void Frob(string value = null) // Good { DoSomething(value ?? "Bits"); } Later version: public void Frob(string value = "Bytes") // Fails! { DoSomething(value); } public void Frob(string value = null) // Success! { DoSomething(value ?? "Bytes"); } I come to a very different conclusion: inline is fine… DLLs are evil. DLLs were designed as a binary API based on C. They were not designed for C++. Extending them for C++ creates this sort of issue. DLLs should be used for C interfaces, period. If you use them for C++, then you have a lot of subtle issues that have to be considered carefully. Plus, DLLs lead to DLL hell, so we avoid them. They're great for hosting resources, but no code. I have never understood other developer's adherence to a technology that was designed when memory was scarce, and C binary interfaces were the only well-defined & stable binary-interface available. Now, compile it all into your EXE and you're guaranteed to load what you actually use out of a library, instead of the entire library, the OS is good about paging in just what's needed, your installer is hugely simplified, and your dependency tree is massively simplified (DLL hell just doesn't exist). @Evan: What happened in old C++ if the compiler had to de-inline you got static. Steve Wolf: If you don't use DLLs, how do you handle plug-ins? OK, so maybe you make exceptions for plug-in architectures. Even worse then, how do you handle updates? Let's say your program can view images, so you use a 3rd-party library to decode them. However, most images are compressed, so the image decoding library uses a 3rd-party compression library. Now let's say that there's a bug in the compression library that allows a malformed image to execute code and take over your machine. If that compression library is loaded as a DLL, your users can search their hard drives for all instances of it, update them to make sure they're all versions that contain the bug fix, and they'll be safe. If that library is statically linked, there's no way to know what software is vulnerable. The security vulnerability could be embedded within any EXE that is capable of compression, whether it's viewing images, managing compressed archives, or just using compression in a file format or network protocol. Instead of being able to get a bug fix directly from the library vendor, users have to go to the app vendors, who may not even exist anymore or (more likely) just don't care about any software that isn't the current version. Even if it's all open source, you have to recompile every single binary affected by the bug, meaning you have to have a build environment for every one of those programs. Good luck with that. Now there is another can of worms called template classes and functions… Anyone who tries to export a template class or function from a DLL is a programmer to be feared. My standard practice for C++ DLLs is to have dllexported extern "C" functions to create an interface object. This interface object then has nothing but virtual functions exposed externally, with no two functions having the same name. In other words, it's similar to COM rules. @Ken – that's called "DLL Hell" – because there's no such thing as changing code with only positive side-effects in the real world. @Kantos – our software doesn't need to support plug ins. If it did, then I would restrict the plug-ins to a well-understood binary interface in C. And in that case, the DLL is dependent on the app, not the other way around, so not a problem. It is everyone else who is stuck in 95/9x view thinking that DLLs actually do anything of value for them… when they mostly cause DLL hell, introduce security vulnerabilities, and increase support headaches. DLLs have their uses… but they're few and far between. Windows developers were taught that DLL = goodness early on, and are still failing to grock why that is untrue and has been untrue since NT. Beyond plug-ins, I see no place where their value outweighs their negatives. The usual list of "reasons" are well-known to be flat-out untrue – such as memory footprint, "fixing" bugs across multiple applications, or providing security. They do none of those things reliably or better than linking a monolithic exe, while creating a long and very anti-stability list of problems. @Steve Wolf: DLLs are useful if you have codebases whose namespaces conflict. Each module has its own symbol table, so things won't conflict. (In UNIX, the run-time symbol table is shared, but you can use -fvisibility=hidden and such to resolve that.) It would be nice to be able to have link.exe build with separate symbol tables within a single .exe file. Basically, link each module individually, then cross-link the imports to make a single .exe file. Other than with horribly hacky solutions, I haven't seen such a feature. @Steve: Memory footprint isn't flat out untrue. Windows does keep a DLL loaded only once if there isn't any rebasing involved. So linking via a DLL does save memory when you use shared code. Also, think of the case of static CRT vs. shared CRT. You have an executable at around 32KB that uses the DLL version and that DLL is loaded as few times as possible, vs. an executable where the same code is loaded multiple times as part of the executable, is that really a case where the DLL doesn't have a lower footprint? For fixing bugs across multiple applications. That is more likely to do with how well designed the DLL is. In my own experience, several applications have used the same DLL for some shared code. A couple of times a bug has been found in that DLL and it was the only thing updates. The updated version was distributed and that fixed the problems. However, when I see people bemoaning this, I usually notice that they do not use well designed DLLs. Also, I don't see where the DLL hell is involved with modern design, since you would be using private DLLs most of the time. This means that your application would be loading the DLL from its own private set of libraries most of the time, or a well controlled set, so it can be well tested. This is something that can't be done with people stuck in a 9x view because this is a more modern thing. In fact, with the things that NT brought with it, especially the changes in the search paths added in KB959462/Windows 7 I would say that DLL = goodness even more now. Made a mistake, the update is KB959426, I managed to transpose the last two digits. One of the rare days when I get a mild headache. When I read quoted text, it gets worse. When I read Raymond's explanation, it goes away. Free medical care. Thank you! @kantos: Since when does the Windows kernel support ELF files? @Azarien I was curious if I could figure out why that was, so I took a look at Stroustrup's "The Design and Evolution of C++". I got part of the way to an answer, but still unsatisfactory. Early versions of C++ ("C With Classes") didn't have an inline keyword, but *did* support indicating that member functions should be inline by putting them into the class definition. So when later revisions to C++ came along to introduce inline, that behavior "had" to stay. Unfortunately, I don't see a description of why *that* was true. I can speculate though. Until relatively recently in the history of C and C++, the only way to get inline functions most of the time was to have the definition available to the *compiler*. (I'm not sure how popular LTO is even now.) That means that the definitions of the functions must be in the headers, which is the same place the definition of the class itself must be (if you want to share the class across translation units). So if you don't have "inline" available, how do you indicate whether a function should be inline? Putting the function definitions into the class definition actually *makes sense* — it means that the compiler has a way of telling inline from non-inline, and is still reasonably natural in the sense that inline defs have to go into the header anyway. In addition, making def'ns in the class definition *not* inline starts presenting problems, because what compilation unit would the code be generated to? Linkers at that time I don't think had the ability to collapse repeated definitions across compilation units*. You "can't" use "the definition still appears in the header but outside of the class definition", because the compiler just sees one big translation unit and doesn't know where the boundaries of the header and not-header are**. So the only other option I can think of would be to say that functions that are definined in the class definition are *static*, which seems equally confusing and surprising as making them inline. Anyway, like so many things in C++ that are awful if you look at them from the standpoint of today, I'd say that aspect actually developed pretty naturally if you accept a pretty dogmatic amount of "must maintain backwards compatibility!" as your goal. * Though now that I'm thinking this through more, I don't know what would happen when compilers at that time would refuse to inline a function defined in the class definition, so something has to give in this part of my argument, and maybe it's not so good. Maybe you'd just get a linker error and have to move that function out of the class. ** Yeah, practically speaking it kind of does, but it never actually *uses* that information except for out-of-band information like error messages and debugging info. Making the meaning of something change depending on whether it appears in a header or source file would probably be the most surprising option out of all of these. :-) @Steve: If you have a common library implemented as a DLL, you can fix bugs in that library for all applications that use it, whether you are aware of the applications or not. @Evan: a very good point about inline and old linkers. In fact, most of the confusions surrounding inline would have been avoided if the keyword had been named "duplicate" (or "selectany"!). The only *sure* thing about such a function is that you can define it in several translation units and the compiler/linker is allowed to assume that they are all identical. Actual inlining is then merely a permitted optimisation for the code generator. @Steve: You might want to re-learn how DLLs are loaded on Windows as you seem to be stuck in a 9x/XP era of assumptions. Any DLL marked as being without a Fixed Base Address and With ALSR enabled is considered to basically be Virtually Position Independent Code (vPIC)*. The OS will load that DLL into physical memory once when it is first loaded by a user mode process, and then keep a reference count of how many processes are using it. Because the DLL is vPIC it can load that DLL into the virtual address space of any user mode process where ever it needs to. Thus many processes share a single Page for a dll, the relocation table is the only non-shared data, any global variables are copy on write and will be shared until modified. So unless you're building your DLLs for an ancient version of windows they are probably not as heavy as you think. * The PE format doesn't actually support Position Independent Code in the truest definition. Theoretically the kernel does as it supports ELF binaries, but I'm not sure what's involved with getting an ELF binary to load on Windows and DLLs are by specification PE. @Steve: you're not entirely alone; I'm also of the opinion that DLLs Are Bad. Perhaps we should form a club. :-) @Crescens2k: sure you save a small amount of memory. When was the last time that mattered? @Gabe: note that newer architectures generally put plug-ins into a separate process anyway. >Anyone who tries to export a template class or function from a DLL is a programmer to be feared. Too late. See MSVCPxx.DLL kantos: Programs on Windows can be position-independent if the compiler generates such code. The PE format supports relocation, but there is very little in PE that actually *requires* relocation. The only things I can immediately think of that require the use of a relocation table are __security_cookie and /SAFESEH. That's only because IMAGE_LOAD_CONFIG_DIRECTORY_2 has pointers instead of RVAs for these fields, and these values are needed by ntdll.dll prior to a single instruction of the DLL executing. No machine code has to be relocated, just an .rdata table. I'd like to see how all of those people suggesting the death of DLLs interact with Windows APIs if not through some kind of DLL interface. I can only presume they are writing inline assembler to do syscalls directly against the kernel, have never programmed an application for Windows, or spend their time in the lofty heights of JavaScript, VB and C#-sans-pinvoke and have never questioned how their fluffy languages interact with the cold hard metal of the system as a whole. DLLs might be evil, but I defy you to come up with a better solution to the problem they solve; namely the ability to modularize code and have updates for the modules independent of the application. Even Linux has DLLs; they just call them Shared Objects (.so files). With some C++11 Wizardry you can even use DLL's to share objects easily between Visual C++ Debug/Release and GCC and use std::string, vector, tuple, etc in the interface between the two. This can save you the headache of having to rebuild libraries multiple times when you want to upgrade/change compilers on Windows. Harry Johnston: Newer architectures may run plug-ins in a separate process, but that doesn't mean each plug-in is a separate process! The standard pattern is to use a single plug-in container process (like audiodg or splwow64) to load all plug-in DLLs. Can you imagine if plug-ins were all separate EXEs that had to run in their own process? Photoshop would be 100 processes instead of 1! Each plug-in would have to have the code to communicate with its host. "Each plug-in would have to have the code to communicate with its host." Microkernels done in userspace? @JRB "With some C++11 Wizardry you can even use DLL's to share objects easily between Visual C++ Debug/Release and GCC and use std::string, vector, tuple, etc in the interface between the two." Now that makes me genuinely curious how you would do that? Release/Debug tend to have different class definitions, violating the ODR across modules, and VC and gcc have a different ABI. Could you elaborate on that part or link to an explaining article? @Gabe: Well, even 100 processes wouldn't be that bad if there was a way to reliably bring down the whole tree of child processes. Otherwise, Windows already has a built-in message passing, and shared memory regions. So not entirely unreasonable, but yeah — in-proc is still way faster. Mainly because all border-crossing checks'n'security isn't present. Isn't it the case that if I write "inline" before a normal function definition, then it is still up to the compiler whether or not it inlines that function or not? The wording of the dllexport documentation you quoted seems to indicate that dllexport-ed functions marked inline are ALWAYS inlined — is that right? Also, are function definitions appearing within a class definition "inline" in the sense that it is as if they were marked inline (ie. they might be inlined and might not), or they are guaranteed to be inlined? Just to balance the discussion on using optional parameters in C#: if you use method overloads in C# interfaces, and export these to COM, then this interface is ugly and brittle, because COM doesn't support overloads so it has to mangle the names; on the other hand, if you use optional parameters, then you can provide a cleaner interface safe to expose via COM. On the third hand you can just customise the names you export from C# to give them unique names. On the fourth hand, why are people so down on optional parameters? Surely you just make sure you don't change the default values, and everything is fine. @Matt: We actually have that in Linux. The syscall ABI never gets breaking changes, so anybody who preferred the static link rules could have them. I prefer to keep a static set of tools around. One of my older systems has 3 different sets of libraries to run software from 3 eras. @JDT: Inline functions are not ALWAYS inlined. For example if you create a pointer to the function (let's say you want use it as a callback method somewhere): It's plain impossible to do that. Same applies to recursive functions: The function might be inlined (helps performance if the recursive part is only rarely called) but any recursive call will not be. I'm not sure how (or if) this works in C++, but if you want to be able to call the function by RTTI you also need a non-inlined version. About optional paramters: It's plain impossible (except for trivial cases) to define a default value that never changes. (The same as it's impossible to write a detailed specification without actually before starting to develop an application: The user always will find some necessary changes later on) DLL Hell: I think may of the defenders of DLL's don't realize what exactly a DLL hell is… While there are some good reasons for DLL's (like accessing the system API) there are serious issues if you depend on shared DLL's (And yes. I've seen "Shared by several processes" in almost all comments): Let's say you have 4 applications that use 4 shared dll's with 2 versions each (And every developer knows that 2 versions per dll is EXTREMELY low). This makes a total of 16 combinations between DLL's so you now test each your application with 16 different DLL-configurations. You might be able to eliminate some combinations by checking the version at startup (Apps will fail fast due to "unsupported" dll version). But you still cannot guarantee that all applications will play by the rules (an one may just install an older DLL version on top of a new one…) So the only way to play safe is to use "private" dll's. But in that case you can also ship a monolithic exe. (If anything changes for the app, you need to send some module(s) anyway. So you could always ship an exe instead). So finally: As I said there are a few reasons for dll's: – Plugin architectures – 3rd party components supplied in different languages (COM interfaces…) – System/OS Libraries (well, still DLL hell, but at least not our responsibility) @AC I presented the underlying techniques at C++Now. The link to the presentation is github.com/…/easy_binary_compat.pdf The cppcomponents project at github.com/…/cppcomponents takes that and builds on it to produce a full component system with factories, Constructors and static functions, delegates, and events. It is basically like C++/CX except it works on Windows 7 as well as Linux, and only uses standard C++ so it works across multiple compilers. Take a look at plugin under examples. It demonstrates a simple way to write plugins. The build script will make the exe with g++ and the dll with Visual C++ (you need the 2013 version). The unit tests cover the the supported features are tested with g++ exe/ Visual C++ dll and vice versa. I am working on writing better documentation for this. When it comes to DLLs, it helps if you can actually tell what version something is. One product from the vendor my company supports has just shy of 200 binaries (EXE/DLL/OCX/etc). 20% of those do not have a VERSIONINFO resource at all. Another 20% have a resource, but have said "1.0.0.1" since forever. And all of them have had multiple revisions over time without updating the version number. Any more, if I have to know for sure which is the newest, I end up having to dig into the IMAGE_FILE_HEADER to find the TimeDateStamp. @_@ @Daniel RE: DLL Hell I'm pretty sure most people reading this site do realize what DLL hell is, however the defenders of DLLs are talking about a different use case than you are. DLLs are perfectly good when (for instance): a) You have multiple applications that rely on the same library that *you* wrote and is under your control. E.g. Office b) You're in a more complicated setup, where the user is responsible for the necessary libraries (mostly happens with other developers/dev tools), and the user can update a bunch of components by updating the library. And yes, we all realize that there can be tons of fun that can be had by everyone when some application comes along and installs its own version of DirectX that is 5 years outdated on your lovely 9x box, but that's largely been solved by Windows not letting applications do that anymore and making them keep their private DLLs to themselves. Ok, I'll bite on the off-topic about DLL benefits. Here's a few more to consider: 1) Ability to have different exception handling rules (throw vs non throw) 2) Ability to use different runtimes 3) CoCreateInstance 4) Delay loading and the subsequent ability to have fallback code (Oh you haven't downloaded <foo>? No worries.) 5) Namespace resolution, as already stated, such as the hInstance parameter in your RegisterClass WNDCLASS struct. One more for DLLs – Better link times. With DLL one can optimize significant amount of code isolated as one or several libs with LTCG (LTO) – for example WebKit, Qt, etc. Such libraries are quite big to fit into the daily compile / link (statically) routine. I'd better have small .exe with lots of big dlls, rather than one big exe that I need to recompile everytime. Another + for DLL's is FFI (foreign function interface). Luajit, Python, Common Lisp and many other runtime implementations of the said languages deal much better with compiled DLL, rather than going through a lot of hoops to link statically with foreign code (like Go, and some other systems). Having lived through the bad ol' days of building a multi-million line application on a pre-shared-library AIX platform, I can assure you of one thing: dynamically-loaded libraries are a _very_ good thing. Be careful what you wish for… @mcmcc and @Dimitir: that's all down to how efficient (or not) your build tools are. @Anil: common wisdom says that having a DLL with a different runtime than the exectuable is bad news, because (for example) you might allocate memory in the DLL and try to free it in the exectuable, hence boom. My opinion is that if the library is properly designed this shouldn't happen anyway, but it does mean one more thing to worry about. In any case, there's no fundamental reason why you couldn't do this at build time if you really wanted to. Same with exception handling. Also, there's no need for fallback code if all the code you want is already in your executable. And so on. @Gabe: I don't see any reason why Photoshop's built-in "extensions" couldn't be statically linked. I wonder how many different third-party extensions the typical user has installed? But, yes, in Windows you sometimes have no realistic option other than DLLs. That doesn't make them a good thing, just a necessary one – and only because Windows doesn't provide better alternatives. @Matt: I don't know about Steve, but I don't object much to the Windows API being provided by way of DLLs. They work reasonably well for that particular purpose and in that particular context. (The only annoying thing I can think of at the moment is that they sometimes start up threads, but so long as you're aware that this may happen it isn't all that big a deal.) Photoshop, Autodesk, XSI, etc. based plugins are whole business on it's own. There are companies (rendering, simulation, asset management, etc) that their main business are these plugins. And often they have to provide for many different versions of the products, and make sure they are compiled with the same compiler the original product was compiled with. Harry: I don't really see how static linking would practically work? In our gamedev studio we do plugins for our artists that export model/animation/etc. data for our pipeline. I can't imagine giving them new compiled version of Photoshop/Maya/MotionBuilder so they could work with. And why would Autodesk allow us to do so? DLLs (and .so, .dylibs) are really something that enables people to make money, without them, you would've been constricted to some form of IPC mechanism, which while it sounds great and maybe the right choice (in very long term), it would be terrible for certain solutions – for example imagine that you have to ask your host application (say 3D modelling one) for all your bones, weights, constraints, etc. – to perform some kind of real-time simualation or something like that – going through IPC would work, but it would complicate the whole thing, and might slow it down to a crawl. Once you are in RPC land, you also have to openly deal with broken communications (even if it's on the same computer) – for example the main application was shut down, or your plugin was killed – you have to come with plans to restart, re-establish connection, get data again, etc., etc. And then imagine a Photoshop effect written as DLL that deals with 100 of megabytes of data doing all through the IPC instead of directly touching the data. @John Doe: Right now, they change in service packs. @Harry Johnston: In general, I disagree with you about dynamic libraries and executables with different runtimes being bad. I also don't think much of "common wisdom/sense" because quite often it is not so common sense and wisdom that is more abundant in these circles. Anyway, the biggest problem is sharing things across the boundary assuming that both sides are using the same runtime. If you are in control of everything, then this isn't so bad. But if you aren't then there are simple ways of doing this without too much thought. Providing a deallocation function, and if you are using C++, then smart pointers would deal with a lot of this. @Dimitir: I was talking specifically about the plugins that are shipped with Photoshop. Obviously, third-party plugins can't (usually) be statically linked. I'm no expert, but doesn't COM already provide solutions to most of the IPC problems you discuss? You can also use shared memory to avoid having to transfer large amounts of data over IPC. As a counter-example, consider what happens when a DLL-based plugin is built with a compiler that changes the FPU settings. (Based on a true story!) All that said, it may well be that, despite the problems, DLLs are still the best currently available solution for these particular scenarios. That doesn't mean we need to use them for everything. (Note in particular that plugins are unlikely to be trying to import or export inline functions!) @Crescens2k: no, I agree with you, it shouldn't be necessary for the DLL and the exectuable to use the same runtime. But a lot of people do get incensed about this, and it does create some risks which need to be managed. @Crescens2k: the other case, of course, is where the DLL and the executable really do need to use different runtime versions, but can't because both of the runtime DLLs have the same name. For the purpose of full static linking, the Windows syscalls would have to be documented. Would it really be such a bad thing? I can see a few more things, other than static linking, where having syscalls documented would be *extremely* useful. Of Course™, Win32, COM, GUI et al would be a no-no in such applications.
https://blogs.msdn.microsoft.com/oldnewthing/20140109-00/?p=2123/
CC-MAIN-2016-40
refinedweb
6,115
60.45
Pratt Parsers: Expression Parsing Made Easy↩ ↪ March 19, 2011 Every now and then, I stumble onto some algorithm or idea that’s so clever and such a perfect solution to a problem that I feel like I got smarter or gained a new superpower just by learning it. Heaps (just about the only thing I got out of my truncated CS education) were one thing like this. I recently stumbled onto another: Pratt parsers. When you’re writing a parser, recursive descent is as easy as spreading peanut butter. It excels when you can figure out what to do next based on the next chunk of code you’re parsing. That’s usually true at the top level of a language where things like classes are and also for statements since most start with something that uniquely identifies them ( if, for, while, etc.). But it gets tricky when you get to expressions. When it comes to infix operators like +, postfix ones like ++, and even mixfix expressions like ?:, it can be hard to tell what kind of expression you’re parsing until you’re halfway through it. You can do this with recursive descent, but it’s a chore. You have to write separate functions for each level of precedence (JavaScript has 17 of them, for example), manually handle associativity, and smear your grammar across a bunch of parsing code until it’s hard to see. PB & J, The Secret Weapon Pratt parsing fixes just that. If recursive descent is peanut butter, Pratt parsing is jelly. When you mix the two together, you get a simple, terse, readable parser that can handle any grammar you throw at it. Pratt’s technique for handling operator precedence and infix expressions is so simple and effective it’s a mystery why almost no one knows about it. After the seventies, top down operator precedence parsers seem to have fallen off the Earth. Douglas Crockford’s JSLint uses one to parse JavaScript, but his treatment is one of the very few remotely modern articles about it. Part of the problem, I think, is that Pratt’s terminology is opaque, and Crockford’s article is itself rather murky. Pratt uses terms like “null denominator” and Crockford mixes in extra stuff like tracking lexical scope that obscures the core idea. This is where I come in. I won’t do anything revolutionary. I’ll just try to get the core concepts behind top down operator precedence parsers and present them as clearly as I can. I’ll switch out some terms to (I hope) clarify things. Hopefully I won’t offend anyone’s purist sensibilities. I’ll be coding in Java, the vulgar Latin of programming languages. I figure if you can write it in Java, you can write it in anything. What We’ll Be Making I’m a learn-by-doing person, which means I’m also a teach-by-doing one. So to show how Pratt parsers work, we’ll build a parser for a tiny little toy language called Bantam. It just has expressions since that’s where Pratt parsing is really helpful, but that should be enough to convince of its usefulness. Even though it’s simple, it has a full gamut of operators: prefix ( +, -, ~, !), postfix ( !), infix ( +, -, *, /, ^), and even a mixfix conditional operator ( ?:). It has multiple precedence levels and both right and left associative operators. It also has assignment, function calls and parentheses for grouping. If we can parse this, we can parse anything. What We’ll Start With be: NAME "a" PLUS "+" NAME "b" LEFT_PAREN "(" NAME "c" RIGHT_PAREN ")" Likewise, we won’t be interpreting or compiling this code. We just want to parse it to a nice data structure. For our purposes, that means our parser should chew up a bunch of Token objects and spit out an instance of some class that implements Expression. To give you an idea, here’s a simplified version of the class for a conditional expression: class ConditionalExpression implements Expression { public ConditionalExpression( Expression condition, Expression thenArm, Expression elseArm) { this.condition = condition; this.thenArm = thenArm; this.elseArm = elseArm; } public final Expression condition; public final Expression thenArm; public final Expression elseArm; } (You gotta love Java’s “please sign it in quadruplicate” level of bureaucracy here. Like I said, if you can do this in Java, you can do it in any language.) We’ll be building this starting from a simple Parser class. This owns the token stream, handles lookahead and provides the basic methods you’ll need to write a top-down recursive descent parser with a single token of lookahead (i.e. it’s LL(1)). This is enough to get us going. If we need more later, it’s easy to extend it. OK, let’s build ourselves a parser! First Things First Even though a “full” Pratt parser is pretty tiny, I found it to be a bit hard to decipher. Sort of like quicksort, the implementation is a deceptively-simple handful of deeply intertwined code. To untangle it, we’ll build it up one tiny step at a time. The simplest expressions to parse are prefix operators and single-token ones. For those, the current token tells us all that we need to do. Bantam has one single-token expression, named variables, and four prefix operators: +, -, ~, and !. The simplest possible code to parse that would be: Expression parseExpression() { if (match(TokenType.NAME)) // return NameExpression... else if (match(TokenType.PLUS)) // return prefix + operator... else if (match(TokenType.MINUS)) // return prefix - operator... else if (match(TokenType.TILDE)) // return prefix ~ operator... else if (match(TokenType.BANG)) // return prefix ! operator... else throw new ParseException(); } But that’s a bit monolithic. As you can see, we’re switching off of a TokenType to branch to different parsing behavior. Let’s encode that directly by making a Map from TokenTypes to chunks of parsing code. We’ll call these chunks “parselets”, and they will implement this: interface PrefixParselet { Expression parse(Parser parser, Token token); } An implementation of this to parse variable names is just: class NameParselet implements PrefixParselet { public Expression parse(Parser parser, Token token) { return new NameExpression(token.getText()); } } We can use a single class for all of the prefix operators since they only differ in the actual operator token itself: class PrefixOperatorParselet implements PrefixParselet { public Expression parse(Parser parser, Token token) { Expression operand = parser.parseExpression(); return new PrefixExpression(token.getType(), operand); } } You’ll note that it calls back into parseExpression() to parse the operand that appears after the operator (i.e. to parse the a in -a). This recursion takes care of nested operators like -+~!a. Back in Parser, the chained if statements are replaced with a cleaner map: class Parser { public void register(TokenType token, PrefixParselet parselet) { mPrefixParselets.put(token, parselet); } public Expression parseExpression() { Token token = consume(); PrefixParselet prefix = mPrefixParselets.get(token.getType()); if (prefix == null) throw new ParseException( "Could not parse \"" + token.getText() + "\"."); return prefix.parse(this, token); } // Other stuff... private final Map<TokenType, PrefixParselet> mPrefixParselets = new HashMap<TokenType, PrefixParselet>(); } To define the grammar we have so far (variables and the four prefix operators), we’ll make this helper method: void prefix(TokenType token) { register(token, new PrefixOperatorParselet()); } And now we can define the grammar like: register(TokenType.NAME, new NameParselet()); prefix(TokenType.PLUS); prefix(TokenType.MINUS); prefix(TokenType.TILDE); prefix(TokenType.BANG); This is already an improvement over a recursive descent parser because our grammar is now more declarative instead of being spread out over a few imperative functions, and we can see the actual grammar all in one place. Even better, we can extend the grammar just by registering new parselets. We don’t have to change the Parser class itself. If we only had prefix expressions, we’d be done now. Alas, we don’t. Stuck In the Middle What we have so far only works if the first token tells us what kind of expression we’re parsing, but that isn’t always the case. With an expression like a + b, we don’t know we have an add expression until after we parse the a and get to +. We’ll have to extend the parser to support that. Fortunately, we’re in a good place to do so. Our current parseExpression() method will parse a complete prefix expression including any nested prefix expressions and then stop. So, if we throw this at it: -a + b It will parse -a and leave us sitting on +. That’s exactly the token we need to tell what infix expression we’re parsing. The only difference between an infix expression and a prefix one here is that there’s another expression before the infix operator that it needs to have as an argument. Let’s define a parselet that supports that: interface InfixParselet { Expression parse(Parser parser, Expression left, Token token); } The only difference is that left argument, which is just the expression we parsed before we got to the infix token. We’ll wire this up to our parser by having another table of infix parselets. Having separate tables for prefix and infix expressions is important because we’ll often have both a prefix and infix parselet for a single TokenType. For example, the prefix parselet for ( handles grouping in an expression like a * (b + c). Meanwhile, the infix parselet handles function calls like a(b). Now, after we parse the prefix expression, we hand it off to any infix one that subsumes it: class Parser { public void register(TokenType token, InfixParselet parselet) { mInfixParselets.put(token, parselet); } public Expression parseExpression() { Token token = consume(); PrefixParselet prefix = mPrefixParselets.get(token.getType()); if (prefix == null) throw new ParseException( "Could not parse \"" + token.getText() + "\"."); Expression left = prefix.parse(this, token); token = lookAhead(0); InfixParselet infix = mInfixParselets.get(token.getType()); // No infix expression at this point, so we're done. if (infix == null) return left; consume(); return infix.parse(this, left, token); } // Other stuff... private final Map<TokenType, InfixParselet> mInfixParselets = new HashMap<TokenType, InfixParselet>(); } Pretty straightforward. We can implement an infix parselet for binary arithmetic operators like + using something like: class BinaryOperatorParselet implements InfixParselet { public Expression parse(Parser parser, Expression left, Token token) { Expression right = parser.parseExpression(); return new OperatorExpression(left, token.getType(), right); } } This also works for postfix operators. I’m calling them “infix” parselets, but they’re really “anything but prefix”. If there’s some expression that comes before the token, it will be handled by an infix parselet, and that includes postfix expressions and mixfix ones like ?:. Postfix is as easy as a single-token prefix parselet: it just takes the left expression and wraps it in another expression: class PostfixOperatorParselet implements InfixParselet { public Expression parse(Parser parser, Expression left, Token token) { return new PostfixExpression(left, token.getType()); } } Mixfix is easy too. It’s pretty much a familiar recursive descent parser: class ConditionalParselet implements InfixParselet { public Expression parse(Parser parser, Expression left, Token token) { Expression thenArm = parser.parseExpression(); parser.consume(TokenType.COLON); Expression elseArm = parser.parseExpression(); return new ConditionalExpression(left, thenArm, elseArm); } } Now we can parse prefix expressions, postfix, infix, and even mixfix. With a pretty small amount of code, we can parse expressions like a + (b ? c! : -d). We’re done, right? Well… almost. Excuse You, Aunt Sally Our parser can parse all of this stuff, but it doesn’t parse it with the right precedence or associativity. If you throw a - b - c at it, it will parse it like a - (b - c), which isn’t right. (Well, actually it is right—associative that is. We need it to be left.) And this last step is where Pratt parsers go from pretty nice to totally radical. We’ll make two simple changes. We’ll extend parseExpression() to take a precedence—a number that tells which expressions can be parsed by that call. If it encounters an expression whose precedence is lower than we allow, it just stops parsing and returns what it has so far. To make that check we need to know the precedence of any given infix expression. We’ll do that by letting the parselet specify it: public interface InfixParselet { Expression parse(Parser parser, Expression left, Token token); int getPrecedence(); } Using that, our core expression parser becomes: public Expression parseExpression(int precedence) { Token token = consume(); PrefixParselet prefix = mPrefixParselets.get(token.getType()); if (prefix == null) throw new ParseException( "Could not parse \"" + token.getText() + "\"."); Expression left = prefix.parse(this, token); while (precedence < getPrecedence()) { token = consume(); InfixParselet infix = mInfixParselets.get(token.getType()); left = infix.parse(this, left, token); } return left; } That relies on a tiny helper function to get the precedence of the current token or default if there’s no infix parselet for it: private int getPrecedence() { InfixParselet parser = mInfixParselets.get( lookAhead(0).getType()); if (parser != null) return parser.getPrecedence(); return 0; } And that’s it. To use this, we’ll set up a little precedence table: public class Precedence { public static final int ASSIGNMENT = 1; public static final int CONDITIONAL = 2; public static final int SUM = 3; public static final int PRODUCT = 4; public static final int EXPONENT = 5; public static final int PREFIX = 6; public static final int POSTFIX = 7; public static final int CALL = 8; } To make our operators correctly handle precedence, they’ll pass an appropriate value back into parseExpression() when they call it recursively. For example, the BinaryOperatorParselet instance that handles the + operator will pass in Precedence.SUM when it parses its right-hand operand. Associativity is easy too. If an infix parselet calls parseExpression() with the same precedence that it returns for its own getPrecedence() call, you’ll get left associativity. To be right-associative, it just needs to pass in one less than that instead. Go Forth and Multiply I’ve rewritten the parser for Magpie using this and it worked like a charm. I’m also working on a JavaScript parser based on this and again it’s been a great fit. I find parsing like this to be simple, terse, extensible (Magpie, for example, uses this to let you extend its own syntax at runtime), and easy to read. I’m at the point where I can’t imagine writing a parser any other way. I never thought I’d say this, but parsers are easy now. To see for yourself, just take a look at the complete program.
http://journal.stuffwithstuff.com/2011/03/19/pratt-parsers-expression-parsing-made-easy/
CC-MAIN-2021-43
refinedweb
2,377
56.35
This Tech Tip reprinted with permission by java.sun.com J2SE 5.0 introduced many new language features. These include support for generics and the enhanced for loop. Previous Tech Tips covered generics and the enhanced for loop. Another important new feature in J2SE 5.0 is annotations. This tip explores the annotations that are built into J2SE 5.0. First, what is an annotation? Defined as part of JSR 175: A Metadata Facility for the Java Programming Language, annotations offer a way to associate metadata with program elements (such as classes, interfaces, and methods). They can be thought of as additional modifiers without changing the generated bytecode for those elements. The concept of introducing metadata to source code isn't new with J2SE 5.0. You can add an @deprecated tag to a method's javadoc comments and the compiler treats this as metadata about the method. This ability has been in place since the 1.0 release of J2SE. The initial release of the platform already had deprecated methods, with the getenv() method of System (though this wasn't in the Java Language Specification until the 1.1 addendum). The concept is almost the same now, at least the @ part of the syntax. Only the location has changed -- an annotation tag goes in source, not comments. The main point here is that annotations are a systematic way to support a declarative programming model. This leads to the first annotation that comes with J2SE 5.0: @Deprecated. Notice the capital D here. Functionally, @Deprecated in source works the same as @deprecated in the javadoc associated with a class or method. By flagging methods with the @Deprecated tag, you're alerting the compiler to warn the user when the method or class is used. The following Main class has a method named deprecatedMethod() that is flagged with the @Deprecated annotation and a, @deprecated comment: public class Main { /** * @deprecated Out of date. Use System.foobar() instead. */ @Deprecated public static void deprecatedMethod() { System.out.println("Don't call me"); } } You compile a class with annotations the same way as you do for one without annotations: > javac Main.java As expected, this produces Main.class. If you use the deprecated method, it produces a compilation-time warning -- just like using the @deprecated tag in a javadoc. Here's an example: public class User { public static void main(String args[]) { Main.deprecatedMethod(); } } Compile the class: > javac User.java and you'll see the following warning about using a deprecated method: Note: User.java uses or overrides a deprecated API. Note: Recompile with -Xlint:deprecation for details. Adding the -Xlint to the compilation line shows specifically what is wrong: > javac -Xlint:deprecation User.java User.java:3: warning: [deprecation] deprecatedMethod() in Main has been deprecated Main.deprecatedMethod(); ^ 1 warning The change from the @deprecated comment to the @Deprecated annotation doesn't introduce anything really new to the system. It only slightly changes the way of doing the same thing. The other two new annotations available to the J2SE 5.0 platform, @Override and @SuppressWarnings, do introduce new functionality to the platform. The @Override annotation can be used with method declarations. As its name implies, you use the @Override annotation to flag a method that is supposed to override a method of the superclass. Why use it? To catch errors sooner. How many times have you meant to override a method, but either misspelled the method name, specified the wrong arguments, or had a different return type? In other words, how often have you defined a new method when what you really wanted to do was override an existing one? By using @Override, you'll find the problem in the following class sooner rather than later: public class Overrode { @Override public int hashcode() { return 0; } @Override public boolean equals(Object o) { return true; } } The problem here is that the method name should be hashCode, not hashcode. Suppose the method declaration is buried in the source for a much larger class definition. Without the first @Override annotation, how long would it take you to realize that your hashCode() method (with camel-case for spelling, not all lowercase) is not being called, and you're getting the default behavior of the parent Object class? Thanks to the @Override annotation, compiling the class produces a compile time error, alerting you to the problem: > javac Overrode.java Overrode.java:2: method does not override a method from its superclass @Override ^ 1 error The sooner you can find errors of this nature, the cost of correction becomes drastically reduced. Note that the hashCode() method should never return a constant. For a fuller description of the proper usage of hashCode() and equals(), see Item 8 in the book Effective Java Programming Language Guide by Joshua Bloch. The final of the three new annotations in J2SE 5.0, @SuppressWarnings, is the most interesting. It tells the compiler not to warn you about something that it would normally warn you about. Warnings belong to a category, so you have to tell the annotation what types of warnings to suppress. The javac compiler defines seven options to suppress: all, deprecation, unchecked, fallthrough, path, serial, and finally. (The language specification defines only two such types: deprecation and unchecked.) To demonstrate, let's look at the suppression of the fallthrough option. Let's start with the following class. Notice that the class is missing a break statement for each case of the switch statement: public class Fall { public static void main(String args[]) { int i = args.length; switch (i) { case 0: System.out.println("0"); case 1: System.out.println("1"); case 2: System.out.println("2"); case 3: System.out.println("3"); default: System.out.println("Default"); } } } Compile the class with javac. You'll see that it simply creates the .class file, and displays no warnings: javac Fall.java If you want the compiler to warn you about switch statements that fall through (that is, one or more break statements are missing), you compile with the -Xlint:fallthrough option: javac -Xlint:fallthrough Fall.java This produces the following warnings: Fall.java:6: warning: [fallthrough] possible fall-through into case case 1: System.out.println("1"); ^ Fall.java:7: warning: [fallthrough] possible fall-through into case case 2: System.out.println("2"); ^ Fall.java:8: warning: [fallthrough] possible fall-through into case case 3: System.out.println("3"); ^ Fall.java:9: warning: [fallthrough] possible fall-through into case default : System.out.println("Default"); ^ 4 warnings But what if you want to ignore the fact that the switch statement is missing a break statement for each case? That's where the @SuppressWarnings annotation comes into play. If you add the following line before the main() method declaration: @SuppressWarnings("fallthrough") Compiling the class with the -Xlint:fallthrough option: will just generate the .class file and display no warnings. @SuppressWarnings annotations can also be used to suppress other warnings such as those that would be displayed if you used a collection without specifying the data type of the collection elements. Don't use the @SuppressWarnings annotation simply to avoid the compilation-time warning. Use it where an unchecked warning is unavoidable, such as when using a library that isn't built with generics in mind. That's really about it for the built-in annotations. However one additional thing to note, annotations (with any arguments) are typically specified on a line by themselves. There is much more that can be done when you define your own annotations, rather than using the ones already defined in J2SE 5.0. For information on defining annotations see Annotations. You can share your information about this topic using the form below! Please do not post your questions with this form! Thanks.
http://www.java-tips.org/java-se-tips/java.lang/introducing-annotations-3.html
crawl-001
refinedweb
1,287
57.77
Red Hat Bugzilla – Bug 21594 Anaconda has an error on 1st step install. Last modified: 2005-10-31 17:00:50 EST Hi, I've dowloaded the ISO image for the Redhat 7 installation and burned it into a CD, the copy was just fine. When I start the installation, no matter on which machine I do it (I've tried, IBM Netfinity, IBM PC 300, white brands or clone PCs, etc) I get the following error: I boot from CDROM or from floppy and I go into normal install or expert install or text install then it loads vmlinuz, then it comes to the blue screen and after a while I get: Running anaconda - May take some time to load ... Traceback (innermost last): File "/usr/bin/anaconda", line 210, in ? from kickstart import Kickstart Value error: bad marshall data install exited abnormally sending termination signals ...done sending kill signals ...done disabling swap unmounting filesystems... /mnt/runtime /mnt/source umount failed (16) /dev/pts /proc you may safely reboot your system What can be happening and what is the solution ? Thank you Pepito. ----- Passing to QA to reproduce. this sounds very much like a bad cd medium ... please verify the md5sum of your iso image, and re-try a new cd burn ... we have not seen this problem here in our tests, and many bad medium problems are similar to what you describe above ... additionally, we are working to try to make the install handle possible defective media better for future releases ... thanks for your report! Nope, I've downloaded the ISOs several times burned it in different brands of media, different speeds and burners, but same error. I've mounted the iso image on a ftp dir and tried to install it from the network with ftp, and it worked.
https://bugzilla.redhat.com/show_bug.cgi?id=21594
CC-MAIN-2017-47
refinedweb
301
71.24
How To Retrieve Remote JVM Monitoring And Management Information By daniel on Mar 09, 2007 How to use JMX to programatically retrieve the information that JConsole displays is easy. Here is a small JMX Client Program that shows how you can programatically retrieve the JVM Management and Monitoring information from a remote JVM. I haven't got the time today to do a longer text explanation - but if you'd like one leave me a comment. Cheers, -- daniel Update Note 1: The example uses JDK 6 Attach API. If you're using JDK 5 then simply comment the 'Attach/PID' code. Update Note 2: The Attach API is in tools.jar, so you will need to add <JDK_HOME>/lib/tools.jarin your CLASSPATHto compile and run the example on JDK 6. Update Note 3: see also How to retrieve JVM information using JRuby in jconsole. Update Note 4: see also A small program that prints the attributes of all JVM MBeans Update Note 5: if you're trying to retrieve the JVM Monitoring And Management Information from a GlassFish server then you should read this post on How to Use JMX to Monitor JVM under GlassFish V1, V2 ... by Kedar. Posted by luc duponcheel on March 09, 2007 at 11:24 AM CET # Posted by fred on March 12, 2007 at 04:18 PM CET # You just can't do VirtualMachine.list() in 1.5. JConsole uses a sun private API to do that, and it can only sees those JVM which have been started by you and with the magic -Dcom.sun.management.jmxremote flag. (note that VirtualMachine.list() also only shows the JVM that you have started. You won't be able to see the JVMs started by an other user). Posted by daniel on March 13, 2007 at 04:45 AM CET # Posted by Juriy on March 22, 2007 at 04:33 AM CET # As soon as you have created the proxy for the M&M MBean you want to access, you can call whatever methods it exposes. So if it exposes a setter, you can call it, and if it exposes a method, you can invoke it. Disclaimer: I haven't compiled this code. Syntax errors expected ;-) cheers, -- daniel. Posted by daniel on March 22, 2007 at 05:26 AM CET # It is also worth mentioning that with JDK 1.5, for platform MXBeans you can obtain proxies by using the java.lang.management.ManagementFactory class (JDK 1.5 and above), and that for regular MBeans you can obtain proxies by using the javax.management.MBeanServerInvocationHandler class (JDK 1.5 and above). The method newMBeanProxy defined in the javax.management.JMX class (JDK 1.6 and above) is equivalent to calling MBeanServerInvocationHandler.newProxyInstance. cheers, --daniel Posted by daniel on March 22, 2007 at 05:42 AM CET # Posted by guest on March 22, 2007 at 09:16 AM CET # Posted by khizer on March 26, 2007 at 01:20 AM CEST # You can do whatever JConsole is doing. Just have a look at all the data exposed by platform MXBeans at -- daniel Posted by daniel on March 26, 2007 at 04:42 AM CEST # Posted by Khizer on March 27, 2007 at 02:08 AM CEST # Posted by Khizer on March 29, 2007 at 02:43 AM CEST # Posted by Bohemian on April 02, 2007 at 10:16 AM CEST # You can't use the Attach API to connect to remote processes. Also the Attach API is not available on JDK 5. You need JDK 6 to use it. If you want to manage a remote JVM (a JVM on a remote machine) then you need to start that JVM with -Dcom.sun.management.jmxremote.port=<port-number>, and that is the port-number you will use to connect to it. See JDK 5 or JDK 6 management guides for more info. Hope this helps, -- daniel Posted by daniel on April 02, 2007 at 11:59 AM CEST # Posted by khizer on April 16, 2007 at 12:13 AM CEST # Concerning turning your java program into a .exe, this is something I have never tried. If you're using gcj - you'll be pretty much on your own. Depending on your motivation for making a .exe you could also try some other alternatives, like using Java Web Start - or using the technique described here: Using Java Classes in Windows Batch Files. I'd be curious to learn why you would like to turn your java application into .exe, rather than making it an executable jar (i.e a jar that can be executed with "java -jar <myjar.jar>"). Concerning total physical memory etc..., these are Sun Management Platform Extension. They are documented here. To get the TotalPhysicalMemorySize simply create an MXBean proxy for the OperatingSystemMXBean, using the com.sun.management.OperatingSystemMXBean class (instead of java.lang.management.OperatingSystemMXBean). cheers, --daniel Posted by daniel on April 17, 2007 at 07:06 AM CEST # Posted by khizer on April 17, 2007 at 09:40 AM CEST # The overview says that an application can be launched from desktop icons or the Start Menu. The FAQ may help you decide whether this is what you actually need... See the section about autodownloading the JRE. Hope this helps, -- daniel Posted by daniel on April 17, 2007 at 10:47 AM CEST # Posted by khizer on April 18, 2007 at 09:24 AM CEST # On JDK 1.6 you can use javax.management.JMX.newMBeanProxy (for regular MBeans) or javax.management.JMX.newMXBeanProxy for MXBeans. cheers, --daniel Posted by daniel on April 18, 2007 at 09:41 AM CEST # Posted by khizer on April 18, 2007 at 09:47 AM CEST # Basically the client side should look like that: Posted by daniel on April 18, 2007 at 09:59 AM CEST # Posted by khizer on April 18, 2007 at 10:12 AM CEST # Posted by daniel on April 18, 2007 at 10:32 AM CEST # Posted by khizer on April 19, 2007 at 08:11 AM CEST # Posted by daniel on April 19, 2007 at 09:00 AM CEST # Posted by guest on May 02, 2007 at 05:01 AM CEST # @anonymous: writing a text-based display of arrays of composite data or tabular data shouldn't be too difficult. How to do it mostly depends on what you intend to do with it. Is it simply for logging purpose? Is the display supposed to be 'human-friendly'? Is it intended to be consumed by a tool? Depending on what your purpose is you could use: Arrays.toString() to display arrays, and regular .toString() to display anything else. This will give you one single line of ugly output but it should be sufficient for a log trace. If it's going to be post processed by a tool you could use a 'property-like' dot notation - eg: I am sure there are also plenty of other alternatives - like using an XML-like syntax etc... Posted by daniel on May 02, 2007 at 06:20 AM CEST # Posted by daniel on May 04, 2007 at 03:53 PM CEST # Posted by Matmus on May 11, 2007 at 02:45 PM CEST # If the JMX Agent is not yet started in the target application, but if the target application runs with JDK 6, on the same machine than the client, and was started by the same user, then the cient will be able to start the agent in the target application by using the attach API. This is exactly what JConsole does. Hope it makes it clear, -- daniel Posted by daniel on May 13, 2007 at 06:18 AM CEST # Hi Daniel, How can i get CPU utilization of remote application using programmatic client ?? and what mechanism I should use to get CPU details every 5 seconds at client side. One way is Thread running at the client side. Can I use Agent's Timer or notification service ??? Posted by Bhimji Khokhani on October 17, 2007 at 07:05 PM CEST # Hi Bhimji, To get the CPU utilization you have to use sun's JVM extension of the OperatingSystemMXBean. In Sun's JDK implementation the OperatingSystemMXBean that you see in JConsole is in fact a com.sun.management.OperatingSystemMXBean. Simply pass the class com.sun.management.OperatingSystemMXBean.class instead of java.lang.management.OperatingSystemMXBean.class when creating your proxy through the ManagementFactory and that's it. Concerning Notifications, it depends what you want to do with the data. If you want to plot the data on the client side then there's not much difference between getting the data every 5 seconds, or sending a notification every 5 seconds. I would even say that getting the data is probably easier and less resource consuming. However, if your goal is not plotting, but for instance, detecting that a threshold has ben crossed, then Notifications are definetely the way to go. In that case you should look at creating a monitor MBean on the server side - see Hope this helps, -- daniel Posted by daniel on October 18, 2007 at 03:29 AM CEST # Hi Daniel, Thanks for your quick reply. You answer helped but I have one questions. The following is my code I am using to get CPU usage. It prints in nano second. 1) how can I print CPU % (percent) utilization ? 2) During single run, It gives same output everytime. When I print the output every 5 second (code not included), it gives same output. Appreciate your help ! MBeanServerConnection mbsc = ManagementFactory.getPlatformMBeanServer(); OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy( mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); System.out.println("CPU utilization is : "+osMBean.getProcessCpuTime()); CPU utilization is : 265625000 ----- Bhimji Khokhani Posted by guest on October 23, 2007 at 03:17 AM CEST # Hi Daniel, One additional example to my previous blog is: System.out.println("CPU : "+osMBean.getProcessCpuTime()); Thread.sleep(5000); System.out.println("CPU : "+osMBean.getProcessCpuTime()); Thread.sleep(5000); System.out.println("CPU : "+osMBean.getProcessCpuTime()); ---- Output----- CPU : 171875000 CPU : 171875000 CPU : 171875000 Can you guide me how can I convert this number into percent utilization ? Posted by guest on October 23, 2007 at 04:05 AM CEST # Hi, This is perfectly normal. An application that sleeps does nothing, and therefore uses no CPU time. To convert to percent simply do something like this: long nanoBefore = System.nanoTime(); long cpuBefore = osMBean.getProcessCpuTime(); // for the sake of the example do some // CPU consuming task here - e.g. // use BigInteger and Math.sqrt() // BigInteger acc = new BigInteger("0"); final int max = 1000000; for (long i=0; i<max; i++) { ... final double d = Double.parseDouble("1"+i); ... final double sq = Math.sqrt(d); ... final BigInteger b = ... ... new BigInteger(""+(long)sq); ... acc = acc.add(b); } long cpuAfter = osMBean.getProcessCpuTime(); long nanoAfter = System.nanoTime(); long percent; if (nanoAfter > nanoBefore) ... percent = ((cpuAfter-cpuBefore)\*100L)/ ... ... (nanoAfter-nanoBefore); else percent = 0; System.out.println("Cpu usage: "+percent+"%"); Note that depending on the accuracy of nanoTime on your System/VM you may have more or less surprising results... Hope this helps, -- daniel Posted by daniel on October 23, 2007 at 11:14 AM CEST # Hi Daniel, you example was helpful. I like clarify one related thing. Based on your example It seems like it returns CPU time taken by JVM process, Not the all processes on that system. For example if osMBean is the proxy of OperatingSystemMXBean of remote JVM and if I execute osMBean.getProcessCpuTime() at client. Then will it return CPU time taken by remote JVM OR all the processes including jvm. Thanks for your time and help Posted by Bhimji Khokhani on October 24, 2007 at 11:16 PM CEST # Hi Daniel, To get proxy of remote jvm Mbean (e.g OperatingSystemMXBean), the following code is used. It returns single proxy and it works fine. OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy( mbsc, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, OperatingSystemMXBean.class); BUT, How can get proxy (for remote management) of MemoryPoolMXBean as it returns list of MBeans.? The method, ManagementFactory.getMemoryPoolMXBeans() gives List of MemoryPoolMXBean of LOCAL JVM. Thanks for your time ! --- Bhimji Posted by Bhimji Khokhani on October 25, 2007 at 04:52 AM CEST # Hi Bhimji, This is hinted at in the API documentation at: Here is how you do: final Set<ObjectName> mp = ... server.queryNames( ... ... new ObjectName(ManagementFactory. ... ... ... MEMORY_POOL_MXBEAN_DOMAIN_TYPE+",\*"), ... ... ... null); final int size = mp.size(); final List<MemoryPoolMXBean> pools = ... new ArrayList<MemoryPoolMXBean>(size); for (ObjectName n : mp) { ... final MemoryPoolMXBean proxy = ... ... ManagementFactory. ... ... ... newPlatformMXBeanProxy(server, ... ... ... ... n.toString(), ... ... ... ... MemoryPoolMXBean.class); ... pools.add(proxy); } -- daniel Posted by daniel on October 25, 2007 at 05:32 AM CEST # Hi Bhimji, Concerning your question regarding osMBean.getProcessCpuTime(), here is the answer: Posted by daniel on October 25, 2007 at 05:39 AM CEST # hi Daniel, when i do import com.sun.tools.attach.VirtualMachine; I get a error message say that com.sun.tools.attach does not exist. I already included <jdk>/lib/tools.jar in my CLASSPATH. Thanks Bing Posted by bing on January 04, 2008 at 03:28 PM CET # Hi Bing, This is most probably a classpath issue. Maybe you misspelled the path to tools.jar in your CLASSPATH? Which version of the JDK are you running on? -- daniel Posted by daniel on January 07, 2008 at 02:25 AM CET # Thanks Daniel, nice blog But I have one doubt still. After I deployed customized MBean on an application server, how should I invoke it? Should I use an instance from java.lang.management.xxMXBean to invoke it? Thank -Ray- Posted by Ray_Lu on January 07, 2008 at 10:37 AM CET # I found the answer to my question. we can use createMBean(String className, ObjectName name, Object[] params, String[] signature) to Instantiates and registers an MBean in the MBean server, and use invoke(ObjectName name, String operationName, Object[] params, String[] signature) to invokes an operation on an MBean. Thanks -Ray- Posted by Ray_Lu on January 07, 2008 at 12:51 PM CET # Hi Ray, Yes that's it. Note that if you have a direct reference to the MBeanServer (local) you can use registerMBean instead of createMBean. Also you can use JMX.newMBeanProxy (or JMX.newMXBeanProxy) to create a proxy and invoke methods on your MBeans, rather than using the raw MBeanServerConnection.invoke(...) method. regards, -- daniel Posted by daniel on January 07, 2008 at 01:38 PM CET # Thanks for response! Posted by Ray_Lu on January 08, 2008 at 02:49 PM CET # Hi Daniel, C:\\Program Files\\Java\\jdk1.6.0_03\\lib\\tools.jar this is my classpath. I am running jdk1.6 Thanks Bing Posted by guest on January 14, 2008 at 05:21 PM CET # Hi Bing, I suspect that the space character is what causing trouble. Also - the classpath must be specified on jconsole command line with -J-Djava.class.path=<classpath> - using the environment variable doesn't work. Try to put quotes ("") around the classpath option when calling jconsole - to see if it works... Hope this helps, -- daniel Posted by daniel on January 16, 2008 at 02:21 AM CET # Hi Daniel, Thanks for the advice. I set the classpath in netBeans then it compiled. I am running the program through NetBeans, I can start the program, but i get the following error message Exception in thread "main" java.lang.SecurityException: Authentication failed! Credentials required at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticationFailure(JMXPluggableAuthenticator.java:193) at com.sun.jmx.remote.security.JMXPluggableAuthenticator.authenticate(JMXPluggableAuthenticator.java:145) at sun.management.jmxremote.ConnectorBootstrap$AccessFileCheckerAuthenticator.authenticate(ConnectorBootstrap.java:172) at javax.management.remote.rmi.RMIServerImpl.doNewClient(RMIServerImpl.java:214) at javax.management.remote.rmi.RMIServerImpl.newClient(RMIServerImpl.java:181) at sun.reflect.GeneratedMethodAccessor451.invoke(Unknown Source) javax.management.remote.rmi.RMIServerImpl_Stub.newClient(Unknown Source) at javax.management.remote.rmi.RMIConnector.getConnection(RMIConnector.java:2309) jvmruntime.JVMRuntimeClient.main(JVMRuntimeClient.java:259) I am trying to connect from a windows box to a linux box. Thanks Bing Posted by guest on January 16, 2008 at 01:18 PM CET # Hi everyone, i'm trying to use the newPlatformMXBeanProxy function from the ManagementFactory in order to get the OperatingSystemMXBean (to get all the system informations). I try it locally in my jboss server like that : OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(ManagementFactory.getPlatformMBeanServer(), osMBeanName,OperatingSystemMXBean.class); System.out.println(osMBean.getProcessCpuTime()); It works very well but if i try to access my MBean Jboss Server by rmi : ... server = (MBeanServerConnection) ctx.lookup("jmx/invoker/RMIAdaptor"); OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy(server,osMBeanName,OperatingSystemMXBean.class); System.out.println(osMBean.getProcessCpuTime()); ... I get an error like this one : java.lang.IllegalArgumentException: java.lang:type=OperatingSystem not found in the connection The only difference between the code which works and the one which doesn't work is the RMI connection. I try to access other mbeans with the rmi connection like "jboss.system:type=ServerInfo" and it works. Thank you in advance for your help ! Antoine Posted by Antoine Verger on May 13, 2008 at 11:04 AM CEST # Hi Antoine, My guess is that your JBoss server uses its own MBeanServer - and not the platform MBeanServer. An application may have several MBeanServers, but only the platform MBeanServer will provide access to the JVM MBeans. It looks like the MBeanServer which is served by your server's RMI connector is not the platform MBeanServer. I am not sure whether there's a way to make your JBoss server use the platform MBeanServer for its own MBeans. You might try to specify -Dcom.sun.management.jmxremote on the server command line and see if it changes anything. If it doesn't, try to look at the JBoss documentation and see if you can find something there. Hope this helps, -- daniel Posted by daniel on May 13, 2008 at 11:24 AM CEST # Thank you Daniel, Well, I try to specify some options for JBoss : -Djavax.management.builder.initial=org.jboss.system.server.jmx.MBeanServerBuilderImpl -Djboss.platform.mbeanserver -Dcom.sun.management.jmxremote Previously, the JConsole didn't work with the JBoss Server but with this options it works. But I still have my problem with the RMI connection. That seems a little odd because if I don't make a mistake, JConsole must also connect my JBoss Server by the RMI connector ?! Isn't it ? In any event, if I don't find the solution before the end of the day, I will access this MBeans remotely by calling a remote function on the JBoss Server ! Antoine Verger Posted by Antoine Verger on May 14, 2008 at 04:10 AM CEST # Hi Antoine, JConsole has two modes - local management and remote management. When you use local management it connects to the server's process using a connector started by the default M&M agent. This connector serves the platform MBeanServer - and is a connector instance which is different from the RMI connector that JBoss may have started. Both connectors may be serving the same MBeanServer or different MBeanServers. Can you see JBoss MBeans through JConsole, or do you only see the JVM M&M MBeans? When connecting using 'remote management' you can specify any JMXServiceURL, and in particular the URL of a RMI connector which may serve a different MBeanServer. In that case all the Overview,Memory,etc. tabs will be greyed - because that MBeanServer will not contain the JVM MBeans - but only the application MBeans. In that case you should still be able to use the MBeans Tab though. This is why we usually recommend that an application registers its MBean in the platform MBeanServer, rather than its own MBeanServer. Applications which were using JMX prior to Java SE 5.0 (JBoss is one of those) may not have this logic though - and may still be using their own private MBeanServer. I would however be surprised if JBoss didn't have a configuration mode were the JBoss MBeans are registered directly in the platform MBeanServer. Anyway - if it doesn't you will have to use two client connections: one to get at the JVM MBeans (through the default JMX agent), and one to get at the JBoss MBeans (through the JBoss RMI connector). Hope this helps, -- daniel Posted by daniel on May 14, 2008 at 04:31 AM CEST # Sorry Daniel, I indeed use JConsole locally and not by using RMI Adaptor of JBoss ! If I try to use it, it doesn't work. I'm always trying to find a solution. I've also post a message on Sun forum for JMX technologies ! In any case, thank you very much for the time you spend trying to help me. Cordially. Antoine Verger Posted by Antoine Verger on May 14, 2008 at 04:42 AM CEST # Hi Daniel, The company i work for uses an application called PEGA Rules Processing Commander for development, and in this application there is a monitor that keeps track of Memory usage and total memory. This information is provided by JMX and MBeans. My goal is to do the same thing just dispaly the information using AJAX on a web page. I know the names of the MBeans on the JVM; however i am new to JMX and can't seem to find a simple example to use. I only need to call one MBean obj to return XML data, unfortunetly i don't know how to call this infomation. Any examples you could provide me with would be greatly appreciated. Thanks, --Ron Posted by Ron on July 09, 2008 at 03:27 PM CEST # Hi Ron, In which environment are you running? If you are running in an application server - or web container (Tomcat/GlassFish) then the natural way to go would probably be to use Java Server Faces - or something similar to create your HTML page and get the data exposed by the application using the regular RMI connector. If you really need to connect the client (web browser) directly to the application with AJAX, then you will need to modify the application so that it provides a direct HTTP access to the MBeans. In that case you might want to have a look at the small Restful Adaptor for JMX prototype: or go down the more standard route with the JMX WebServices connector (AKA JSR 262): Hope this helps, -- daniel Posted by daniel on July 17, 2008 at 09:58 AM CEST # Can I use MBeanServerConnection.createBean() if I have a remote jvm running and want to create a new bean on the remote server. The MBean I want to create is not existed on the remote server when it is started up. The code I use is try{ ObjectName name = new ObjectName("com.example:type=Echo"); connection.createMBean("com.example.Echo", name );// connection is MBeanServerConnection instance EchoMBean proxyx = JMX.newMXBeanProxy(connection, name, EchoMBean.class); System.out.println("echo: "+proxyx.echo()); }catch(Exception e ){e.printStackTrace();} When using this code it throws "javax.management.ReflectionException: The MBean class could not be loaded by the default loader repository." How to solve it? Many thanks, Posted by everyman on September 09, 2008 at 07:49 AM CEST # Hi, You need to put the jar that contains EchoMBean in the classpath of your remote server. regards, -- daniel Posted by daniel on September 09, 2008 at 08:01 AM CEST # Thanks for this great code, although I need to be able to access attributes of custom mbeans. I am a bit of a JMX newbie and I am unsure of how to go about this. I need to be able to specify a -mbean parameter that will return the attributes of an mbean but I do not know how to integrate this into my code. Please have a look and let me know how I can do this. Ideally I would like to be able to do the following: java -jar jmxclient.jar -url jmxrmi://url -mbean com.myapp.model.jpa.modelattribute:HitProbability and return some result. The ordering of where the mbean resides in the tree (as viewed with jconsole) is as follows: Coherence->Cache->com.myapp.model.jpa.modelattribute->1->back CacheHits CacheMisses HitProbability.... So I need to add another argument to be parsed, -mbean, and I need to know how to get the attributes for a custom mbean by name or specified verbatim. Any help is appreciated, Matt Posted by Matthew on October 06, 2008 at 12:56 PM CEST # Hi Matt, With JDK6 JConsole, if you click on the node that represents your custom MBean, you will see its ObjectName displayed in the first line of the "Info" table. With JDK5 JConsole, it should be on the "Metadata" tab. I believe the ObjectName will also appear as a tool-tip if you hoover the mouse over the custom MBean node. Once you know the ObjectName you can compose a getAttribute request like that: ObjectName myCustomName = new ObjectName("<the name you saw displayed in jconsole>"); System.out.println(myCustomName+": "+"MyAttrName = "+ remote.getAttribute(myCustomName,"MyAttrName")); Beware not to add any extraneous white space in the ObjectName: "d:x=y,z=z" is the same name than "d:z=z,x=y" but not the same name than "d:x=y, z=z". Hope this helps, -- daniel Posted by daniel on October 07, 2008 at 03:23 AM CEST # Hi Daniel I have used the attach api in desktop application with success. However I noticed that when I use the attach api in a web application running in a tomcat container, the VirtualMachine.list() returns a zero sized list. Can you please explain why is it so? Posted by Shashank Sardana on December 22, 2008 at 06:12 AM CET # Hello Daniel, First of all, congratulations on such an informative blog. The knowledge being shared here is just excellent. I am in a similar situation as some of the folks above. I am developing a load balancer application (SIP protocol) which is deployed on JBOSS AS. I tried the code above for calculating the CPU utilization of the system. I wish to collect this CPU data periodically at the cluster nodes (JBOSS cluster) and send it to the load balancer over RMI. This information will then serve as a criteria to select the best possible node by the load balancer. One of the important points I noticed in this discussion was that JBOSS might not be using the Platform MBean server, but rather its own private MBean server instance. If JBOSS does not provide a way for using the platform MBean server, can i write my own application, that creates an instance of an MBean server, registers its MBeans and collects CPU infor and sends it across over RMI ? I can deploy this application as a SAR file in each of the Jboss cluster nodes. Does this approach sound feasible ? Posted by aayush bhatnagar on May 11, 2009 at 01:48 AM CEST # Can anyone let me know what's the correct set of arguments/argument to be passed to run this application. I tried several options some with -url option and some with -port number and both without success. Even with pid, but did not work. my arguments is -url service:jmx:rmi:///jndi/rmi://cawcremdd6:9044 where cawcremdd6 is the server name and 9044 is the jmx port. Would appreciate quick help on it. Thanks & Best Regards Harish Posted by Harish Vembu on July 06, 2009 at 08:05 PM CEST # Hi Daniel Great articles (including). Very clear explanation. Thank you :) Vlad Posted by Vlad on April 23, 2010 at 04:28 AM CEST # Hi Daniel, Very helpful and to the point article. Well, one thing i need to ask that how to get CPU utilization for JVM running remotely? I used this piece of code to get cputime-- JMXServiceURL url = new JMXServiceURL("service:jmx:rmi:///jndi/rmi://102.97.186.5:8999/jmxrmi"); JMXConnector cntor = JMXConnectorFactory.connect(url); MBeanServerConnection connection = cntor.getMBeanServerConnection(); com.sun.management.OperatingSystemMXBean osMBean = ManagementFactory.newPlatformMXBeanProxy( connection, ManagementFactory.OPERATING_SYSTEM_MXBEAN_NAME, com.sun.management.OperatingSystemMXBean.class); System.out.println(osMBean.getProcessCpuTime()); Posted by Ranu on May 03, 2010 at 02:01 AM CEST #
https://blogs.oracle.com/jmxetc/entry/how_to_retrieve_remote_jvm
CC-MAIN-2014-15
refinedweb
4,653
56.25
Project fails to compile in debug mode My project compiles and runs perfectly in release mode, but when I use debug mode, i get around 22 errors @ in function qwait. undefined reference to Qtest::qsleep. undefined reference to Qtest::defaultkeyDelay@ I havent used qwait or qtest lib anywhere in my program. - koahnig Moderators What is your OS and IDE you are using? Ubuntu 12.04 and Qt Creator , Qt 4.8.2 I have been using Qt since last year, this is the first time i am seeing this error - koahnig Moderators I have not a lot of experience qith creator and linux. Assuming that you tried already rerunning qmake, you may want to check the pro file and its includes if there is a reference to testlib. Another possibility could be that you are using a header which is testing a macro settings you are defining only in debug compile. But all is poking into the fog from my side. Did you put #include <QTest> in source file?
https://forum.qt.io/topic/19365/project-fails-to-compile-in-debug-mode
CC-MAIN-2017-51
refinedweb
169
71.75
- Prerequisite for GitLab self-managed - How it works - Requirements for user-mapped contributions - Import your Bitbucket repositories - Troubleshooting Import your project from Bitbucket Cloud to GitLab Import your projects from Bitbucket Cloud to GitLab with minimal effort. The Bitbucket importer can import: - Repository description - Git repository data - Issues - Issue comments - Pull requests - Pull request comments - Milestones - Wiki When importing: - References to pull requests and issues are preserved. - Repository public access is retained. If a repository is private in Bitbucket, it’s created as private in GitLab as well. Prerequisite for GitLab self-managed To import your projects from Bitbucket Cloud, the Bitbucket Cloud integration must be enabled. If it isn’t enabled, ask your GitLab administrator to enable it. By default it’s enabled on GitLab.com. How it works When issues/pull requests are being imported, the Bitbucket importer uses the Bitbucket nickname of the author/assignee and tries to find the same Bitbucket identity in GitLab. If they don’t match or the user is not found in the GitLab database, the project creator (most of the times the current user that started the import process) is set as the author, but a reference on the issue about the original Bitbucket author is kept. The importer will create any new namespaces (groups) if they don’t exist or in the case the namespace is taken, the repository will be imported under the user’s namespace that started the import process. Requirements for user-mapped contributions For user contributions to be mapped, each user must complete the following before the project import: Verify that the username in the Bitbucket account settings matches the public name in the Atlassian account settings. If they don’t match, modify the public name in the Atlassian account settings to match the username in the Bitbucket account settings. Connect your Bitbucket account in GitLab profile social sign-in. - Import your Bitbucket repositories - On the top bar, select New (). - Select New project/repository. - Select Import project. - Select Bitbucket Cloud. Log in to Bitbucket and grant GitLab access to your Bitbucket account. Select the projects that you’d like to import or import all projects. You can filter projects by name and select the namespace each project will be imported for.. User mapping fails despite matching names For user mapping to work, the username in the Bitbucket account settings must match the public name in the Atlassian account settings. If these names match but user mapping still fails, the user may have modified their Bitbucket username after connecting their Bitbucket account in the GitLab profile social sign-in. To fix this, the user must verify that their Bitbucket external UID in the GitLab database matches their current Bitbucket public name, and reconnect if there’s a mismatch: Use the API to get the currently authenticated user. In the API’s response, the identitiesattribute contains the Bitbucket account that exists in the GitLab database. If the extern_uiddoesn’t match the current Bitbucket public name, the user should reconnect their Bitbucket account in the GitLab profile social sign-in. Following reconnection, the user should use the API again to verify that their extern_uidin the GitLab database now matches their current Bitbucket public name. The importer must then delete the imported project and import again.
https://docs.gitlab.com/14.10/ee/user/project/import/bitbucket.html
CC-MAIN-2022-27
refinedweb
546
51.78
Types Of Functions In C++ Along With Their Uses. In our earlier tutorials until now, we have seen the various concepts in C++ like variables, storage classes, operators, arrays, strings, etc. In this tutorial, we will move ahead and discuss the concept of functions. Functions are also called methods, subroutines or procedures. => Read Through The Extensive C++ Training Tutorial Series Here. What You Will Learn: - How Do We Define A Function? - Types Of Functions In C++ - Function Declaration - Function Definition - Calling A Function - Formal And Actual Parameters - Return Values - Void Functions - Passing Parameters To Functions - Default Parameters - Const Parameters - Inline Functions - Using Structs In Functions - Conclusion - Recommended Reading How Do We Define A Function? A function is a set of statements that are put together to perform a specific task. It can be statements performing some repeated tasks or statements performing some specialty tasks like printing etc. One use of having functions is to simplify the code by breaking it into smaller units called functions. Yet another idea behind using functions is that it saves us from writing the same code again and again. We just have to write one function and then call it as and when necessary without having to write the same set of statements again and again. Types Of Functions In C++ In C++, we have two types of functions as shown below. Built-in Functions Built-in functions are also called library functions. These are the functions that are provided by C++ and we need not write them ourselves. We can directly use these functions in our code. These functions are placed in the header files of C++. For Example, <cmath>, <string> are the headers that have in-built math functions and string functions respectively. Let us see an Example of using built-in functions in a program. #include <iostream> #include <string> using namespace std; int main() { string name; cout << "Enter the input string:"; getline (std::cin, name); cout << "String entered: " << name << "!\n"; int size = name.size(); cout<<"Size of string : "<<size<<endl; } Output: Enter the input string: Software Testing Help String entered: Software Testing Help! Size of string: 21 Here we are using the headers <iostream> and <string>. The data types and other input/output functions are defined in <iostream> library. String functions used like getline, size are a part of the <string> header. User-Defined Functions C++ also allows its users to define their own functions. These are the user-defined functions. We can define the functions anywhere in the program and then call these functions from any part of the code. Just like variables, it should be declared before using, functions also need to be declared before they are called. Let us discuss user-defined functions in detail. The general syntax for user-defined functions (or simply functions) is as given below: return_type functionName(param1,param2,….param3) { Function body; } So as shown above, each function has: - Return type: It is the value that the functions return to the calling function after performing a specific task. - functionName : Identifier used to name a function. - Parameter List: Denoted by param1, param2,…paramn in the above syntax. These are the arguments that are passed to the function when a function call is made. The parameter list is optional i.e. we can have functions that have no parameters. - Function body: A group of statements that carry out a specific task. As already mentioned, we need to ‘declare’ a function before using it. Function Declaration A function declaration tells the compiler about the return type of function, the number of parameters used by the function and its data types. Including the names of the parameters in the function, the declaration is optional. The function declaration is also called as a function prototype. We have given some examples of the function declaration below for your reference. int sum(int, int); Above declaration is of a function ‘sum’ that takes two integers as parameters and returns an integer value. void swap(int, int); This means that the swap function takes two parameters of type int and does not return any value and hence the return type is void. void display(); The function display does not take any parameters and also does not return any type. Function Definition A function definition contains everything that a function declaration contains and additionally it also contains the body of the function enclosed in braces ({}). In addition, it should also have named parameters. When the function is called, control of the program passes to the function definition so that the function code can be executed. When execution of the function is finished, the control passes back to the point where the function was called. For the above declaration of swap function, the definition is as given below: void swap(int a, int b){ b = a + b; a = b - a; b = b - a; } Note that declaration and definition of a function can go together. If we define a function before referencing it then there is no need for a separate declaration. Let us take a complete programming Example to demonstrate a function. #include <iostream> using namespace std; void swap(int a, int b) { //here a and b are formal parameters b = a + b; a = b - a; b = b - a; cout<<"\nAfter swapping: "; cout<<"a = "<<a; cout<<"\tb = "<<b; return; } int main() { int a,b; cout<<"Enter the two numbers to be swapped: "; cin>>a>>b; cout<<"a = "<<a; cout<<"\tb = "<<b; swap(a,b); //here a and b are actual parameters } Output: Enter the two numbers to be swapped: 5 3 a = 5 b = 3 After swapping: a = 3 b = 5 In the above example, we see that there is a function swap that takes two parameters of type int and returns nothing. Its return type is void. As we have defined this function before function main, which is a calling function, we have not declared it separately. In the function main, we read two integers and then call the swap function by passing these two integers to it. In the swap function, the two integers are exchanged using a standard logic and the swapped values are printed. Calling A Function When we have a function in our program, then depending on the requirement we need to call or invoke this function. Only when the function is called or invoked, the function will execute its set of statements to provide the desired results. The function can be called from anywhere in the program. It can be called from the main function or from any other function if the program is using more than one function. The function that calls another function is called the “Calling function”. In the above example of swapping numbers, the swap function is called in the main function. Hence the main function becomes the calling function. Formal And Actual Parameters We have already seen that we can have parameters for the functions. The function parameters are provided in the function definition as a parameter list that follows the function name. When the function is called we have to pass the actual values of these parameters so that using these actual values the function can carry out its task. The parameters that are defined in the function definition are called Formal Parameters. The parameters in the function call which are the actual values are called Actual Parameters. In the above example of swapping numbers, we have written the comments for formal and actual parameters. In the calling function i.e. main, the value of two integers is read and passed to the swap function. These are the actual parameters. We can see the definitions of these parameters in the first line of the function definition. These are the formal parameters. Note that the type of formal and actual arguments should match. The order of formal and actual parameters should also match. Return Values Once the function performs its intended task, it should return the result to the calling function. For this, we need the return type of the function. The function can return a single value to the calling function. The return type of the function is declared along with the function prototype. Let’s take an Example of adding two numbers to demonstrate the return types. #include <iostream> using namespace std; int sum(int a, int b){ return (a+b); } int main() { int a, b, result; cout<<"Enter the two numbers to be added: "; cin>>a>>b; result = sum(a,b); cout<<"\nSum of the two numbers : "<<result; } Output: Enter the two numbers to be added: 11 11 Sum of the two numbers: 22 In the above example, we have a function sum that takes two integer parameters and returns an integer type. In the main function, we read two integers from the console input and pass it to the sum function. As the return type is an integer, we have a result variable on the LHS and RHS is a function call. When a function is executed, the expression (a+b) returned by the function sum is assigned to the result variable. This shows how the return value of the function is used. Void Functions We have seen that the general syntax of function requires a return type to be defined. But if in case we have such a function that does not return any value, in that case, what do we specify as the return type? The answer is that we make use of valueless type “void” to indicate that the function does not return a value. In such a case the function is called “void function” and its prototype will be like void functionName(param1,param2,….param 3); Note: It is considered as a good practice to include a statement “return;” at the end of the void function for clarity. Passing Parameters To Functions We have already seen the concept of actual and formal parameters. We also know that actual parameters pass values to a function which is received by the format parameters. This is called the passing of parameters. In C++, we have certain ways to pass parameters as discussed below. Pass by Value In the program to swap two integers that we discussed earlier, we have seen that we just read integers ‘a’ and ‘b’ in main and passed them to the swap function. This is the pass by value technique. In pass by value technique of parameter passing, the copies of values of actual parameters are passed to the formal parameters. Due to this, the actual and formal parameters are stored at different memory locations. Thus, changes made to formal parameters inside the function do not reflect outside the function. We can understand this better by once again visiting the swapping of two numbers. #include <iostream> using namespace std; void swap(int a, int b) { //here a and b are formal parameters b = a + b; a = b - a; b = b - a; cout<<"\nAfter swapping inside Swap:\n "; cout<<"a = "<<a; cout<<"\tb = "<<b; return; } int main() { int a,b; cout<<"Enter the two numbers to be swapped: "; cin>>a>>b; cout<<"a = "<<a; cout<<"\tb = "<<b; swap(a,b); cout<<"\nAfter swapping inside Main:\n "; cout<<"a = "<<a; cout<<"\tb = "<<b; } Output: Enter the two numbers to be swapped: 3 2 a = 3 b = 2 After swapping inside Swap: a = 2 b = 3 After swapping inside Main: a = 3 b = 2 We have simply modified the earlier program to print the values of formal parameters & actual parameters before and after the function call. As seen from the output, we pass values a=3 and b=2 initially. These are the actual parameters. Then after swapping inside the swap function, we see that the values are actually swapped and a=2 and b=3. However, after the function call to swap, in the main function, the values of a and b are still 3 and 2 respectively. This is because the actual parameters passed to function where it has a copy of the variables. Hence although the formal parameters were exchanged in the swap function they were not reflected back. Though Pass by value technique is the most basic and widely used one, because of the above limitation, we can only use it in the cases where we do not require the function to change values in calling the function. Pass by Reference Pass by reference is yet another technique used by C++ to pass parameters to functions. In this technique, instead of passing copies of actual parameters, we pass references to actual parameters. Note: References are nothing but aliases of variables or in simple words, it is another name that is given to a variable. Hence a variable and its reference share same memory location. We will learn references in detail in our subsequent tutorial. In pass by reference technique, we use these references of actual parameters and as a result, the changes made to formal parameters in the function are reflected back to the calling function. We modify our swap function for our readers to understand the concept better. : 25 50 a = 25 b = 50 After swapping inside Main: a = 50 b = 25 Note: The pass by reference technique shown in the above example. We can see that the actual parameters are passed as it is. But we append an ‘&’ character to the formal parameters indicating that it’s a reference that we are using for this particular parameter. Hence the changes made to the formal parameters in the swap function reflect in the main function and we get the swapped values. Pass by Pointer In C++, we can also pass parameters to function using pointer variables. The pass by pointer technique produces the same results as that of pass by reference. This means that both formal and actual parameters share the same memory locations and the changes made in function are reflected in the calling function. The only difference that in a pass by reference we deal with references or aliases of parameters whereas in a pass by pointer technique we use pointer variables to pass the parameters. Pointer variables differ with the references in which pointer variables point to a particular variable and unlike references, we can change the variable that it points to. We will explore the details of the pointer in our subsequent tutorials. We present the swapping of two integers again to demonstrate the Pass by Pointer technique. : 23 54 a = 23 b = 54 After swapping inside Main: a = 54 b = 23 Thus as already said, there is no difference in the output of the program. The only difference is in the way in which the parameters are passed. We can notice that formal parameters are pointer variables here. Default Parameters In C++, we can provide default values for function parameters. In this case, when we invoke the function, we don’t specify parameters. Instead, the function takes the default parameters that are provided in the prototype. The following Example demonstrates the use of Default Parameters. #include <iostream> #include <string> using namespace std; int mathoperation(int a, int b = 3, int c = 2){ return ((a*b)/c); } int main() { int a,b,c; cout<<"Enter values for a,b and c: "; cin>>a>>b>>c; cout<<endl; cout<<"Call to mathoperation with 1 arg : "<<mathoperation(a); cout<<endl; cout<<"Call to mathoperation with 2 arg : "<<mathoperation(a,b); cout<<endl; cout<<"Call to mathoperation with 3 arg : "<<mathoperation(a,b,c); cout<<endl; } Output: Enter values for a,b and c: 10 4 6 Call to mathoperation with 1 arg: 15 Call to mathoperation with 2 arg: 20 Call to mathoperation with 3 arg: 6 As shown in the code example, we have a function ‘mathoperation’ that takes three parameters out of which we have provided default values for two parameters. Then in the main function, we call this function three times with a different argument list. The first call is with only one argument. In this case, the other two arguments will have default values. The next call is with two arguments. In this case, the third argument will have a default value. The third call is with three arguments. In this case, as we have provided all the three arguments, default values will be ignored. Note that while providing default parameters, we always start from the right-most parameter. Also, we cannot skip a parameter in between and provide a default value for the next parameter. Now let us move onto a few special function related concepts that are important from a programmer’s point of view. Const Parameters We can also pass constant parameters to functions using the ‘const’ keyword. When a parameter or reference is const, it cannot be changed inside the function. Note that we cannot pass a const parameter to a non-const formal parameter. But we can pass const and non-const parameter to a const formal parameter. Similarly, we can also have const return-type. In this case, also, the return type cannot be modified. Let us see a code Example that uses const references. #include <iostream> #include <string> using namespace std; int addition(const int &a, const int &b){ return (a+b); } int main() { int a,b; cout<<"Enter the two numbers to be swapped: "; cin>>a>>b; cout<<"a = "<<a; cout<<"\tb = "<<b; int res = addition(a,b); cout<<"\nResult of addition: "<<res; } Output: Enter the two numbers to be swapped: 22 33 a = 2 b = 33 Result of addition: 55 In the above program, we have const formal parameters. Note that the actual parameters are ordinary non-const variables which we have successfully passed. As formal parameters are const, we cannot modify them inside the function. So we just perform the addition operation and return the value. If we try to modify the values of a or b inside the function, then the compiler will issue an error. Inline Functions We know that in order to make a function call, internally it involves a compiler storing the state of the program on a stack before passing control to the function. When the function returns, the compiler has to retrieve the program state back and continue from where it left. This poses an overhead. Hence, in C++ whenever we have a function consisting of few statements, there is a facility that allows it to expand inline. This is done by making a function inline. So inline functions are the functions that are expanded at runtime, saving the efforts to call the function and do the stack modifications. But even if we make a function as inline, the compiler does not guarantee that it will be expanded at runtime. In other words, it’s completely dependent on the compiler to make the function inline or not. Some compilers detect smaller functions and expand them inline even if they are not declared inline. Following is an Example of an Inline Function. inline int addition(const int &a,const int &b){ return (a+b); } As shown above, we precede the function definition with a keyword “inline” in order to make a function inline. Using Structs In Functions We can pass structure variables as parameters to function in a similar way in which we pass ordinary variables as parameters. This is shown in the following Example. #include <iostream> #include <string> using namespace std; struct PersonInfo { int age; char name[50]; double salary; }; void printStructInfo(PersonInfo p) { cout<<"PersonInfo Structure:"; cout<<"\nAge:"<<p.age; cout<<"\nName:"<<p.name; cout<<"\nSalary:"<<p.salary; } int main() { PersonInfo p; cout << "Enter name: "; cin.get(p.name, 50); cout << "Enter age: "; cin >> p.age; cout << "Enter salary: "; cin >> p.salary; printStructInfo(p); } Output: Enter name: Vedang Enter age: 22 Enter salary: 45000.00 PersonInfo Structure: Age:22 Name: Vedang Salary:45000 As shown in the above program, we pass a structure to function in a similar manner as other variables. We read values for structure members from the standard input and then pass a structure to a function that displays the structure. Conclusion This was all about the basics of functions in C++. We will explore more about the static functions in C++ in our upcoming tutorials. => Check Complete C++ FREE Training Series Here.
https://www.softwaretestinghelp.com/functions-in-cpp/
CC-MAIN-2021-17
refinedweb
3,366
61.97
expression ? expression : expression The conditional operator (? :) is a ternary operator (it takes three operands). expressions: If both expressions are of the same type, the result is of that type. If both expressions are of arithmetic or enumeration types, the usual arithmetic conversions (covered in Arithmetic Conversions) are performed to convert them to a common type. If both expressions are of pointer types or if one is a pointer type and the other is a constant expression that evaluates to 0, pointer conversions are performed to convert them to a common type. If both expressions are of reference types, reference conversions are performed to convert them to a common type. If both expressions are of type void, the common type is type void. If both expressions are of a given class type, the common type is that class type. Any combinations of second and third operands not in the preceding list are illegal. The type of the result is the common type, and it is an l-value if both the second and third operands are of the same type and both are l-values. // expre_Expressions_with_the_Conditional_Operator.cpp // compile with: /EHsc // Demonstrate conditional operator #include <iostream> using namespace std; int main() { int i = 1, j = 2; cout << ( i > j ? i : j ) << " is greater." << endl; }
http://msdn.microsoft.com/en-us/library/e4213hs1(VS.80).aspx
crawl-002
refinedweb
212
53.81
2006 Filter by Day: 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 Prevent "click to activate and use this control" Posted by mchi528 at 11/30/2006 11:23:59 PM Latest Microsoft security update is causing flash in web pages viewed in Internet Explorer to show a frame border with a message saying "click here to activate and use this control". Is there any workaround to prevent this messgae? Thanks. ... more >> IE and Flash Posted by Mister Peanut at 11/30/2006 11:01:31 PM Does anyone know why my published swf has a light grey border around it in IR? :grin;... more >> Cover up a rollover Posted by tommy53 at 11/30/2006 10:48:55 PM I am creating a short training module in Flash 8. I have a few invisible buttons over some of the text - when the user rolls over that text, a movie clip displays some visual information pertinent to that text. I also have a few other "on-release" buttons that open up movie clips that contain... more >> Posted by Purplehaze at 11/30/2006 10:14:04 PM I am just getting back into using flash and justr downloaded Flash 8. I am trying to open a flash file to edit it but when I do it says Seek Failed on c://documents......etc....... more >> Flash optimizers Posted by mzanime.com at 11/30/2006 9:18:23 PM Does anyone here use any of these? And do they really work? I currently have an animated gif which I created using Adobe Illustrator, and the GIF came out to be about 93kb, then I decided to export the GIF as a flash movie from Illustrator, but whoa! The SWF came out to be about 130kb. So i... more >> Allow user to bookmark individual flash page Posted by bellycats29 at 11/30/2006 8:57:18 PM Hi there, I would like to know how I can create a whole website in flash but still allow the user to copy the url of a certain page and use that as a link to jump back to that exact page again or bookmark it as a favourite. I've seen it done, generally the url will look something like ... more >> need help building things into flash Posted by kinnsi at 11/30/2006 8:53:52 PM The riddle that has been given to my class is: Complex interactivity (buttons, navigation, etc.) can be built into Flash using this computer programming language... more >> Download a music file in Flash MX2004 Posted by rqwefrv at 11/30/2006 8:44:43 PM Hi, Can anyone help me with this problem. I have developed a music site using Flash MX2004 and would like to offer a small download facility. After searching forums it seemed that the best way to do this was to use PHP and ASP because MX2004 did not have the inbuilt ability to do this. Unf... more >> Don't see what you're looking for? Search DevelopmentNow.com. Movie and audio not synchronized... Posted by Alexis Schneider at 11/30/2006 7:15:44 PM Hello, I have a main movie that call and display movies from the library. In each of those library's movies i have an animation on a layer and a sound (about 15 secondes) on another layer which i want synchronize. When i check each movie on my .fla devlopment file, everything works perfec... more >> Urgent! Cannot save file in Flash Professional 8 Posted by johnny_mango at 11/30/2006 6:47:38 PM Hi there, I urgently require some help! All I need to do is save a .fla file in flash 8 and it is coming up with the error Could not save as...... The file may be read-only or is already open in another application. Save using a different name, or close the document and try again. I ... more >> Flash question on website using Explorer Posted by makarios58 at 11/30/2006 5:58:45 PM I have a problem when using Flash on explorer for a particular website. When I access my website using explorer, I have to click once to enter the flash area then I can access the flash sequence. I cannot just click on the flash and go. Is this a setting problem in dreamweaver or what? Why... more >> flash form Posted by shorshnut at 11/30/2006 4:38:21 PM Original message: >> FLV Export From Final Cut Pro Posted by Fish Stalker at 11/30/2006 3:42:32 PM Hi Folks, I've been reading and reading and just want to know what is the right way to go about exporting video from a third party application like Final Cut Pro. Yes, the easy way is to Export>quicktime conversion and go from there. If this is the best way then great, But i'm wondering if ... more >> Flash intro Posted by BullocksTroy at 11/30/2006 3:32:35 PM I uploaded a Flash intro to my site in HTML format, but it will not play when i go to my site. the animation played fine when i tested it in Flash, but when I uploaded it, it would not play in Firefox or IE. why might this be happening? I didn't see any pop-ups in IE regarding ActiveX co... more >> import flash.external.*; Posted by HisHeir at 11/30/2006 3:30:06 PM Have a flash project originaly developed in Flash 7. I now am working on the this project in flash 8 IDE. When attempting to use the external API; import flash.external.*; presents a syntax error when attempting to debug / publish the project, yet projects developed in flash 8 do not present... more >> Flash audio player Posted by akwatters at 11/30/2006 2:57:49 PM Hi Do you know of an embedded flash audio player (open source, commercial or instructions on how to build one) that supports streaming of various different formats (MP3, windows media etc.) and that allows the URL of the stream to be passed in? Any help or pointers would be greatly app... more >> Video to FLV console converter Posted by srib at 11/30/2006 2:51:50 PM Hi All, How to convert avi and other video formats to FLV using console (command prompt) application. So my .Net application can convert avi to FLVs using console. When ever new video file uploads it should convert to FLV formate. Thanks & Regards, Sridhar B ... more >> Jpg rotation distortion Posted by rhouck at 11/30/2006 2:48:13 PM I have numerous pictures that have photo border (white) coming into the my main movie. The Jpg look great! But if I rotate the movie clips (I have each jpg in a MC), the edges between the border and the photograph become jagged looking. Is there something I am do incorrectly? ... more >> Flash Fail to Go Live! Posted by Knutsford at 11/30/2006 2:27:06 PM I am a total newbie of Flash (and web design). I have tis problem:- 1. I created a Flash file (a banner with text and graphic) and imported to Dreamweaver. I can view it when I click the play button on property inspector. However, it appears blank when viewed through IE; duno why? 2. I... more >> FLV Doesn't work!!!!!!! Posted by edd at 11/30/2006 2:21:28 PM Hi everyone!!! My site goes through the follow structure: (startpage) that loads the (mainpage) in a new container MC (alvo) but in the same level (0). From within the (alvo).(mainpage), I call another container MC (movies), now in level (2). This new MC has a FLV component that should ... more >> FLV's in Flash Player 6 Posted by setra1001 at 11/30/2006 2:08:16 PM Hi, I am trying to get progressive FLV's to work in Flash Player 6,0,65,0. I have read in a number of places that it is possible for Flash Player 6,0,65,0 to recognise the FLV if encoded with 'Sorenson Spark Video Codec'. Has anyone had any experience with this, or could point me in the... more >> Global var Posted by Bill_from_Wales at 11/30/2006 2:04:04 PM Can a var be set as global for use by all functions in a single fla file? I would like to set a var in any one of 3 functions (dependant upon user choice) and then be able to read it's value in a fourth and fifth function. something like this: //--------------------------------------... more >> Video not working when online - HELP! Posted by rustler2001 at 11/30/2006 12:44:46 PM I am putting video into flash, to go online and am pretty new to it. I followed a couple of discussions in here to the letter, but it doesnt see to work once i upload it all. I did this: 4&threadid=1208495&high... more >> textArea component Posted by shree_shiralkar at 11/30/2006 12:00:00 AM Hi, I have used TextArea component in flash (mx/2004) by using built in components of flash. I have set html to true for the html text to be displayed by XML. But I think only some of the tags are supported with this component. Tags like table and other supporting tags are not displayed pr... more >> Fliping a Bitmap Posted by sunSETian at 11/30/2006 12:00:00 AM I was looking for a mirror effect but I didn't find any function to flip an image, so I did a double "for" to copy each pixel of the video, that I'm taking live from a webcam, to a new bitmapdata object in the dessired new location. My problem now is that this code causes a huge delay at ... more >> How do I import a swf slideshow into my macromedia Flash MX homepage? Posted by motomelissa at 11/30/2006 12:00:00 AM I have a macromedia flash mx homepage that I have been working on. I made a custom slideshow through this company anvsoft that they say that you can put the slideshow into the macromedia flash. I can not get anyone to help me do this there though..... Is there anyone here that can help... more >> flash asp form Posted by shorshnut at 11/30/2006 12:00:00 AM >> flash mx -ScrollPane - scroll bar issue Posted by shree_shiralkar at 11/30/2006 12:00:00 AM If we create some dynamic content and display it using scrollPane and if the width and height of the clip( the clip displayed in ScrollPane) changes dynamically by clicking on a button then refreshPane method does not work properly. We have to set original position of the clip to (0, 0) when ... more >> Dynamic textField settings Posted by shree_shiralkar at 11/30/2006 12:00:00 AM Hi, I have been using dynamic textField in a movieclip in one of my projects. I used dynamic textfield by using createTextField method and created one textField in a movieclip. But If we have to set _alpha property of the movieclip to zero it doen't work for textField inside it. I think we c... more >> Auto advance or play Posted by Ricky at 11/29/2006 11:29:52 PM How can I get a slide show to loop through each slide automatically without user intervention. I am totally new at this. Sorry for the dumb question. thanks,... more >> site test!!! Posted by edd at 11/29/2006 11:12:23 PM Please, could everyone go to this site,, in the seccion portfolio\ demo AND \comerciais, click on the links and tell me if the videos are working fine??? Thanks for everyone that could help!!!... more >> Simple Quiz Resource Posted by easirider at 11/29/2006 10:30:35 PM Looking for a tutorial or resource to develop a simple Quiz in Flash 8 Pro. I know about the templates,....the library questions but need a jump start .....let's say a simple quiz example (type of question not important.).....just need something to show the way in setting it up and getting on... more >> Flash Site Posted by Nickels55 at 11/29/2006 9:36:28 PM From Digg: Trippy flash site. You may want to poke your eyes and ears out after about 10 seonds.... more >> MP3 Posted by Fracm at 11/29/2006 9:31:49 PM Hi, I have many songs listed on a page, each one has a rollover button next to it I'd like each mp3 song to star playing when one clicks on the button next to it....what would be the best way to implement that? (a free mp3 player, a flash code?) Any help or recommendations would be appr... more >> installation problem??? Posted by haddocck at 11/29/2006 9:07:35 PM i still have a problem to install flash 9, it's possible to download it and install it from my PC? i'm be able to install shockwave player directly on the page but with flash, notting appear. Thank to help me!! ... more >> Re: .mov + flash Posted by edd at 11/29/2006 9:01:49 PM Hi!! I have a MC with a link to download a *.mov file (quicktime). I've used getURL to point the target to download, but when I click on the link the .mov file opens in the web browser. I'd like to make it go for download whithout play through the browser!! Thanks!!! Sorry for the englis... more >> Re: Text artifacts in FP 9.18? Posted by phirewall at 11/29/2006 8:57:49 PM I hope I'm not the only one experiencing this?... more >> Linking Scenes Not Working Properly Posted by yellowlilx at 11/29/2006 8:50:08 PM Should be a simple, easy thing. I can't get this to work inside my subnavigation. Could someone email me at nikki at imicci.com so I can show you this file? Or is there a way to post it here. This has held me up all day and should be an easy fix. All I need to do is link my subnavigation ... more >> Importing Dicom Images into flash Posted by sameer666 at 11/29/2006 7:56:56 PM i am trying to import dicom images into flash. as this is not a standard format, images must be rendered pixel by pixel. to do this though, the images must be imported to the library. however, flash will not import this to the library as it does not recognise the file format. any ideas on ... more >> Error message when saving Posted by Brenton07 at 11/29/2006 7:38:00 PM "An attempt was made to access [location] past it's end" I'm getting this message while trying to save. It happened after I pulled out my USB drive on accident, which contained the file I was working on. The file is still up, but when I save, it gives me that message. Can anyone tell me how ... more >> duping Posted by Balloony2 at 11/29/2006 7:28:46 PM is there a way to dupe a movie clip on key press or on press which will dupe the movie clip where my character pushed space.... more >> Controlling appearance of the DataGrid Posted by TorIRislaa at 11/29/2006 7:12:24 PM How to control the appearance of the columns and rows of a DataGrid I have the code below where I controlling the Column width I also want the text of column at index 1 to be aligned to left. Is it possible to have an alternating row color and also removing the lines between the columns? ... more >> Quicktime File, No Convert watch in flash Posted by pMi11 at 11/29/2006 7:03:14 PM hey. i was just wondering if anyone new how to play an outward quicktime file in an flash applet, without having to convert it to FLV or .swf. just play the direct ..mov file. we are able to preview .gif's so i don't see why we couldnt do .mov ... more >> looking for an old DevNet component .as file Posted by toadwack at 11/29/2006 6:58:08 PM :confused; Hi, I am looking for an actionscript file that is for a component ( com/macromedia/validation/DataValidation.as ). I beleive that it belongs to the textField component from the UI component set 5. Does anyone have this, that would be kind enough to send me? ... more >> CONTEXT MENU with chinese characters? Posted by atlacatl at 11/29/2006 6:45:16 PM Here is the synopsis of the problem: I built this tool that makes use of global variables from an external .AS file for localization purposes. I have the require //!-- UTF-8 setting atop. So far all the text imported from the.as file works fine, I do see chinese characters, but when I try upda... more >> Progressive downloading Posted by vanleurth at 11/29/2006 6:20:45 PM Hello, I wonder if someone could send me to a tutorial about how to make a progressive downloading audio player. Thank you in advance, V.... more >> Very Basic Question Posted by fwitt at 11/29/2006 5:40:21 PM How would I get the width and height properties to show properly for a sfw once embedded into an HTML page? If I make a colored box that's 100x100 in dimensions, why is it showing up much smaller once it's contained within a page? I've tried changing some of the publish settings and several di... more >> help please Posted by jeff spires at 11/29/2006 5:15:00 PM Hi to one and all. I am just about to build my first flash video player. however, i need to get the avi, mov or mpeg file from a database using php. (this is no problem) But to play the flash movie i need to convert them into FLV files. I there a way of doing this through code. e... more >> Test player detection IE7 without uninstalling flash Posted by createmedia at 11/29/2006 4:49:28 PM Hello all, I'm trying to test Falsh Player detection code. Trying to see if there's a way to test IE7 without uninstalling the Flash player.... I'd like to see what it looks like to users without the correct version of Flash... Anyway, want to temporarily turn off Flash in a page so I can s... more >> Using FH9 files in dreamweaver Posted by The Death at 11/29/2006 4:41:15 PM I have an .fh9 file that i want to insert in dreamweaver. I need to know if .fh9 files are the correct format to use for web pages or should a different format be used.... more >> · · groups Questions? Comments? Contact the d n
http://www.developmentnow.com/g/68_2006_11_0_0_0/macromedia-flash.htm
crawl-001
refinedweb
3,196
80.51
Code::Blocks User forums => General (but related to Code::Blocks) => Topic started by: chihwahli on May 10, 2013, 10:11:38 am Title: Freeglut with code blocks Post by: chihwahli on May 10, 2013, 10:11:38 am I have been trying to get the first Opengl super-bible version 4 exercise working in Code blocks 12.11. I think I am very close. The thread is long, it's located in another forum, and thought, wait a minute, maybe I did smething wrong in Code blocks, who to better ask than HERE?! I guess it's better to paste the link instead copying all thread info back into Code blocks forum.... Been trying real hard to solve the problem myself as you can see, I know you guys have been answering the same question over and over again... If I have the answer. I don't mind typing one code blocks 12.x openGL with Freeglut tutorial for windows 7... Then sticky in on top and direct people towards there.... Title: Re: Freeglut with code blocks Post by: koonschi on May 10, 2013, 12:05:19 pm Hey, Reading the other topic made me slightly confused :D What I can tell you is, how to decipher those errors: "XXX was not declared in this scope" The compiler simply can't find XXX, it doesn't even know about its existance. Reason: Maybe an undeclared function or variable. Fix: Usually including the right headers, using the correct namespace or simply declaring the function. "undefined reference to XXX" The compiler found a declaration of a function, but not the implementation. Reason: You declared it somewhere, but missed implementing it. You did not link the library where the function is defined. Fix: If you made that function, implement it. If it's from a library, In the build options of you project, in 'Linker settings' add the correct libaries to the list. I already came across cases where the order of those libraries is important, so you might try that out too. "ld.exe: cannot find -lXXX" Reason: You told the linker to link a certain library, but it can't find it. Fix: In the build options of you project, in 'Search Directories' -> 'Linker' add the correct directories where your libs are located to the list. If gcc can't find headers, you need to tell it where they are (in project -> build options -> search directories -> compiler) This is similar to the lib directories. What usually suffices to build a project with libs is to - specify where your headers lie (in project -> build options -> search directories -> compiler) - specify where your libs lie (in project -> build options -> search directories -> linker) - add the libs you want to link to to the linker settings' list (in project -> build options -> linker settings) Hope to help, Koonschi Title: Re: Freeglut with code blocks Post by: chihwahli on May 10, 2013, 07:27:21 pm Thanks Koonschi for taking the effort of reading! :) And I thought I wrote my trials very stepwise.... :-\ I tried that, I kee getting the same errors. Perhaps if someone gave me the correct files and, then at least I know the source files areall working and correct... Someone must have a working IDE (opensource) enviroment.... (althought I read that sometimes 7/10 example progs don't work at all) SMF 2.0.15 | SMF © 2017 , Simple Machines
http://forums.codeblocks.org/index.php?action=printpage;topic=17898.0
CC-MAIN-2020-50
refinedweb
565
68.81
sensor_event_get_xyz() Retrieve the x, y, and z data values from a sensor event. Synopsis: #include <bps/sensor.h> BPS_API int sensor_event_get_xyz(bps_event_t *event, float *x, float *y, float *z) Since: BlackBerry 10.0.0 Arguments: - event The sensor event to get the x, y, and z data values from. - x The pointer to the x-axis value. - y The pointer to the y-axis value. - z The pointer to the z-axis value. Library:libbps (For the qcc command, use the -l bps option to link against this library) Description: The sensor_event_get_xyz() function gets the data values of the x-axis, y-axis, and z-axis from the specified sensor event. The sensor event that you pass to this function must be SENSOR_ACCELEROMETER_READING, SENSOR_MAGNETOMETER_READING, SENSOR_GYROSCOPE_READING, SENSOR_LINEAR_ACCEL_READING, or SENSOR_GRAVITY_READING, because these are the only sensor events with x, y, and z data components. The units that are used for x, y, and z depend on which sensor event was passed in. For accelerometer and linear accelerometer events, the values are in G forces. For magnetometer events, the values indicate the strength of the magnetic field along a particular vector, in microteslas. For gyroscope events, the values are in radians per second. For gravity events, the values are in meters per seconds squared (m/s^2). Returns: BPS_SUCCESS upon success, BPS_FAILURE with errno set otherwise. Last modified: 2014-09-30 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.bps.lib_ref/topic/sensor_event_get_xyz.html
CC-MAIN-2019-35
refinedweb
244
58.69
The analytics platform for all your metrics Grafana allows you to query, visualize, alert on and understand your metrics no matter where they are stored. Create, explore, and share dashboards with your team and foster a data driven culture. Trusted and loved by the community. Thousands love Grafana, read why Open Grafana gives you options. It’s completely open source, and backed by a vibrant community. Use Grafana Cloud, or easily install on any platform. Extend Discover hundreds of dashboards and plugins in the official library. Thanks to the passion and momentum of our community, new ones are added every week. Collaborate Bring everyone together, and share data and dashboards across teams. Grafana empowers users, and helps foster a data driven culture. Get a complete picture with 30+ data sources Grafana supports over 30 open source and commercial data sources. Pull together your data wherever it lives, and build the perfect dashboard. Built-in Graphite Support a to Graphite function documentation - Rich templating support Built-in InfluxDB Support - Rich query editor with measurement, tag and tag value completion - Automatic handling of group by time - Templating queries for generic dashboards - Alias patterns for short readable series names - Ad hoc filters for exploration dashboards Built-in Prometheus Support - Query editor with metric name lookup - Templating queries for generic dashboards - Alias patterns for short readable series names Built-in Elasticsearch Support - Rich query editor with automatic property name lookup - Extract many types of metrics from documents like: Avg, Min, Max, Percentiles, Std Dev, etc. - Group by multiple terms or filters - Query only relevant indicies based on time pattern - Alias patterns for short readable series names Built-in Cloudwatch Support - Rich editor with auto completion for metric names, namespaces and dimensions - Templating queries for generic dashboards - Alias patterns for short readable series names Data source plugins Beside the plugins that ship with Grafana we provide an extensive set of data source plugins via our Plugin Repository. Grafana seamlessly integrates into your workflow. Authentication LDAP, Google Auth, Grafana.com, Github. However your company handles auth, Grafana makes it work easily with your existing workflow. Organizations Rolling Grafana into your offering? Prefer the look of your own logo? Officially brand your Grafana instance. User Preferences Grafana includes power user preferences including the option to select from dark or white themes, set your home dashboard, change timezones and more. Feature Gallery Visualize Fast and flexible visualizations with a multitude of options allow you to visualize your data any way you want. Dynamic Dashboards Create dynamic & reusable dashboards with template variables that appear as dropdowns at the top of the dashboard. . Works best with our Loki data source but support for more are coming very soon. Mixed Data Sources Mix different data sources in the same graph! You can specify a data source on a per-query basis. This works for even custom datasources. Annotations Annotate graphs with rich events from different data sources. Hover over events shows you the full event metadata and tags. Ad-hoc Filters Ad-hoc filters allow you to create new key/value filters on the fly, which are automatically applied to all queries that use that data source. The largest unexpected benefit of adapting Grafana, however, is that it empowers so many other teams to create dashboards with the data. – Chris Madden, Storage Architect, NetApp Annotations Annotate graphs with rich events from different data sources. Hover over events shows you the full event metadata and tags. Sharing Share a dashboard or fullscreen panel. Automatically includes current time range and variables. Create a public or internal snapshots. Server side render API makes chat integration possible. Light Theme If you do not prefer the default dark theme you can switch to a light theme. This is a user preference that can be changed on the profile page.
https://grafana.com/grafana/?pg=plugins&plcmt=featured-undefined
CC-MAIN-2021-10
refinedweb
633
55.34
We have many, many tests in our suites. Each of them is a single method, starting with the 'test' prefix. But where do we put them? In several Testcase Classes. There are several alternatives for choosing how to name the Testcase Classes and how many should be created. These patterns can be used in different parts of your suite, and today we will see the most natural one: Testcase Class per Class. "When" is the right question According to this pattern, you should create a Testcase Class for each class in the production code that you want to test. The tests in this class will exercise the production code class, as much as possible by maintaining an object in isolation, and inserting Test Double where necessary. This pattern requires a clear correspondence between tests and classes: thus it is "adapt" for unit tests and less for functional and integration one. For end-to-end tests or acceptance tests written in the domain language, the simmetry is often lost. For example, when you're testing a model class, it's likely that you can find test scenarios that works well on an object of the class in isolation. When you're testing the user interface instead, you do not have a strict correspondence between test scenarios and production classes (although a loose correspondence can be made with controllers in MVC frameworks). ImplementationUsually the naming convention followed for this pattern on a medium/large scale is to replicate the hierarchical structure of the production code: library/ My/ CoolClass.php tests/ My/ CoolClassTest.php CoolClassTest contains in this case a My_CoolClassTest (or My\CoolClassTest if you use namespaces) class extending PHPUnit_Framework_TestCase or a subclass of it. This simple convention aids you in mapping from one test class to the related production one, and vice versa; even when thousands of classes are involved the mapping remain straightforwards, ans we can say it is O(1). Zend Framework 1 for example mostly uses this pattern and this convention. If you have always used this pattern, you probably think that this is the norm. It is, but there are alternatives which trades off the simmetry of code and tests in order to build more cohesive tests (for example when a Testcase Class grows too much, it can be broken down in smaller classes which do not corresponde anymore to different production classes.) Example In this series, we presented mostly examples as unit tests, since they are the simplest to setup and transport to your computer for running. As so, most of the various pieces of code follows the convention of Testcase Class per Class. Thus the sample code of today is more related to the structure of the tests than to their content. The folder contains two parallel trees of production code classes and test cases. For each class: <?php class MyClass { } you have a Testcase similarly named: <?php // in reality this would be done via autoloading and bootstrap file require_once __DIR__ . '/../classes/MyClass.php'; class MyClassTest extends PHPUnit_Framework_TestCase { public function testCanInstanceAnObjectOfTheClassUnderTest() { $object = new MyClass; $this->assertTrue($object instanceof MyClass); } } And if the class is under a hierarchy: <?php class Component_OtherClass { } the Testcase follows the same hierarchy in order to be found easily: <?php // in reality this would be done via autoloading and bootstrap file require_once __DIR__ . '/../../classes/Component/OtherClass.php'; class Component_OtherClassTest extends PHPUnit_Framework_TestCase { public function testCanInstanceAnObjectOfTheClassUnderTest() { $object = new Component_OtherClass; $this->assertTrue($object instanceof Component_OtherClass); } } You can take a look at the Github repository to see the folder structure. {{ parent.title || parent.header.title}} {{ parent.tldr }} {{ parent.linkDescription }}{{ parent.urlSource.name }}
https://dzone.com/articles/practical-php-testing/practical-php-testing-patterns-47
CC-MAIN-2018-09
refinedweb
596
52.19
Welcome to the Pycom forum! Welcome to your brand new Pycom forum! Please check the announcement section for new and updates. Best regards, The Pycom Team LoPy Beta Release (version='v1.8.1-53-ga8a6e4b on 2016-06-29') First of all, make sure you have followed the getting started instructions, which can be found in: The actual IP address for FTP and telnet is: 192.168.4.1 A new release is available which bring bug fixes and a newly added LoRa class as part of the network module. IMPORTANT_0<< These are the release notes for version='v1.8.1-53-ga8a6e4b on 2016-06-29' New features: - LoRa class contructor permits to invert the Tx and Rx IQ signals. - Minimal time module Example code: from network import LoRa lora = LoRa() # initialize with recommended settings lora.send('LoRa packet test', False) # Send data in a synchronous way lora.recv() # get any data pending in the receive queue In order to send LoRa packets between your 2 LoPys: - In LoPy # 1: from network import LoRa # initialize LoRa as a node (with Rx IQ inversion) lora = LoRa(tx_iq=False, rx_iq=True) for i in range(10): lora.send('LoRa packet test #{}'.format(i), False) # Send data in a synchronous way - In LoPy # 2: from network import LoRa import time # initialize LoRa as a Gateway (with Tx IQ inversion) lora = LoRa(tx_iq=True, rx_iq=False) for i in range(10): print(lora.recv()) # just receive time.sleep(1.5) # wait for 1500 milliseconds The releases are available here: (868MHz band) (915MHz band) Tip: use os.uname() to get the software version information. Q&A on MicroPython Multi-threading and Garbage Collector As we completed the MicroPython Multi-Threading and Garbage collector features with Damien George we sat down with our CTO Daniel to take a look at what that means for the use of the scripting language. Here’s the resulting Q&A. >>IMAGE let’s. Pymakr Beta Release2.0 includes iOX, Windows and Linux LoPy Beta Release (version='v1.8.1-59-g22cefbb on 2016-07-30')._3<<. socket.fileno() Hi, my local micropython installation exposes a fileno() method on socket objects whereas the mircopython installation on WiPy/LoPy does not. Is that by design or does that method remain to be ported? I am trying to use the select package (from micropython) and asyncio package (from micropython-lib) but both appear to depend on that method to be available. Thanks, Hans LoPY WIFI connections keeps reconnecting Hi, this boot.py code works on the WiPy but results in a reconnect loop on LoPy. import machine from network import WLAN wlan = WLAN(mode=WLAN.STA) wlan.connect("myssid", auth=(WLAN.WPA2, 'password'), timeout=5000) print("Connecting to WLAN") while not wlan.isconnected(): print(".", end="") machine.idle() print('WLAN connected') On LoPy the following is printed repeatedly to the console: state: 0 -> 2 (b0) reconnect Can you help please? Thanks, HC Extension board's PIN Hi, I am struggling to find out which PIN the extension board's button is connected to. I've tried every PIN I found in machine.PIN.boards but without success. Could you help please? Thanks, Hans LiPo Battery Recommendation? What LiPo Battery do you recommend? How much capacity? Volts? Thx. Adding cheap GPS sensor? Is it possible to add a cheap GPS sensor directly to the UART component? As reported, there are 2 UARTS built inside the module. Thx.
https://forum.pycom.io/search
CC-MAIN-2018-17
refinedweb
573
58.48
kubuntu - qDebug is missing Having used Qt on Windows, I am now porting the application to Linux Kubuntu 16.10. Qt5 is installed, qtcreator is launched and detects Qt version 5.6.1 , the test project is well-configured, but I'm getting an impossible error : error: qDebug: No such file or directory #include <qDebug> I searched the entire disk, and the file qDebug is indeed missing. All the other headers are found in /usr/include/x86_64-linux-gnu/qt5/QtWidgets, except for qDebug. The problem is probably a missing package, but I cannot for the life of me find out which one. #include <QDebug> the file should be located in /usr/include/x86_64-linux-gnu/qt5/QtCore @Harry123 said in kubuntu - qDebug is missing: probably a missing package I doubt it Thanks for your answer I found the file and the bug : It should be QDebug and not qDebug. This is an error that can only happen when porting from Windows, that doesn't care about case, to Linux that does.
https://forum.qt.io/topic/73412/kubuntu-qdebug-is-missing
CC-MAIN-2018-09
refinedweb
172
57.61
Apple announced on Monday that it has developed a successor to its venerable Objective C with a language it's calling Swift. Providing a new language with "none of the baggage of C," Swift code can still be mixed with standard C and Objective C code in the same project. Swift seems to get rid of Objective C's reliance on defined pointers; instead, the compiler infers the variable type, just as many scripting languages do. At the same time, it provides modern features similar to those found in C++ and Java, like well-defined namespaces, generics, and operator overloading. From the few fragments of code shown during the demo, Swift appears to rely heavily on the dot-notation that Apple introduced in an earlier iteration of Objective. It also showed off a Swift "playground," where code is compiled as it's typed and the output is displayed in a separate pane of the editing window. The goal here is to allow developers to test code fragments without having to recompile an entire complex project. Use of Swift will be supported as soon as the next version of Xcode is released—it's currently available in beta form to registered developers, and will presumably see more widespread release during OS X Yosemite's public beta later this year. Apple also promises to release a free iBook on the language's syntax later today. Promoted Comments ... 6329?mt=11 281.
http://arstechnica.com/apple/2014/06/apple-shows-off-swift-its-new-programming-language/?comments=1&post=26952735
CC-MAIN-2014-52
refinedweb
239
54.26
The ReSharper 3.0 EAP has been in progress for about two weeks now. This is the first post in a series that will look in detail at some of the new features that will be available in this latest version of ReSharper. The To-do Explorer In Visual Studio.NET 2005, you can use the Task List window to show comments with the keyword todo in it. However, this only works with files that are open in the IDE; it’s not going to show you TODOs in other parts of your solution that you don’t currently have open, or any other keyword EXCEPT todo. The Visual Studio.NET 2005 Task List window In ReSharper 3.0, you get the much more useful To-do Explorer. When you open this window (found in ReSharper -> Windows -> To-do Explorer), by default you see a solution-wide listing of all comments with the prefix NOTE, TODO or BUG. The new To-do Explorer window The default keywords that the To-do explorer looks for can be changed or added to by clicking the “To-do settings†icon in the window. In the settings window, you can create new keywords to search for or edit the existing keywords as you’d like. This could be useful, for example, if you have a references to JIRA tickets in your comments, like: //PROJ-1655: The following code block was added because of a change request from a client You could add a pattern to match the keyword “ PROJ-####†and see all JIRA tickets mentioned in your code. Editing keywords in the To-do explorer These To-dos can also be exported to a text file and can also be grouped to make the To-dos easier to read, so you can find which projects, namespaces, directories, etc … contain To-dos. The To-do Explorer view options This is a nice feature which could be very useful, if there is a way export the completed work items (for subversion commits). I would be much more impressed by a blog post about support for the new Orcas language features. Where’s the beef in the 3.0 release if I’m not stuck in Visual Basic world? Jürgen “(…)it’s not going to show you(…)any other keyword EXCEPT todo” This isn’t correct. The keywords “hack”, “undone” and “todo” are predefined, and you can add/customize keywords using Options -> Environment -> Task list. The requirement that files must be open is a huge drawback though, and I’m looking forward to try your implementation. Juergen: I dont believe there is any way to track “completed” work items with the to-do explorer. However, off the top of my head, you could always export the outstanding todos to an xml file, commit that to SVN and then DIFF the files every time you want to see what’s changed. As for Orcas, while there are a ton of nice features coming in that release, it’s still not going to be released for a while. On top of that, I think you’d be surprised just how many people are stuff in the Visual Basic world still Dag: Good catch on Visual Studio’s task list keyword customization. Juergen: If something isn’t implemented or supported the way you’d like, then fill out our little questionnaire at: Let the developers know what you want! (or would be helpful!) Will ReSharper 3 support .NET 3.0 in all its XAML goodness? Dmitry, according to the ReSharper 3.0 EAP roadmap, there is basic support for XAML already. I do not know if the plan is for full XAML support in 3.0, but you can probably expect more XAML support to be added in the near future. I don’t know if this is the right place to post this, but I’d love it if Resharper 3 gave us full text search on all files in the loaded solution. Thanks for a great product! hey andres, what full text search are you talking about? Andres: answer him!
https://blog.jetbrains.com/dotnet/2007/04/18/resharper-30-eap-in-action-the-todo-explorer/?replytocom=60635
CC-MAIN-2019-13
refinedweb
686
70.73
For the last couple of days, I am observing the question pattern in TCS. I would like to share some tricks and tips to crack the question in less time. I hereby declare that these shots are only helpful for some type of questions in the Exam. As of now Quick Shots are available in only Python Programming Language. Good to Know ### Quick Inputs name = raw_input() # for Strings number = int(input()) # for Integers Yes or No Questions def yes_or_no(): reply = str(raw_input('(y/n):')).lower().strip() if reply[0] == 'y': return True if reply[0] == 'n': return False else: return None isMember = yes_or_no() if(isMember == None): print("Invalid Input") Accepting Values in Same line (with Spaces) values = [int(x) for x in raw_input().split()] print(values) # input: 1 2 3 4 # output: [1, 2, 3, 4] Accepting Values in Same line (with Commas) values = [int(x) for x in raw_input().split(', ')] print(values) # input: 1, 2, 3, 4 # output: [1, 2, 3, 4] Percentage Questions # 85% of 2043.43 def percentage(part, whole): return (part * whole)/100 print(percentage(85,2043.43)) # output: 1736.9155 Invalid Input INVALID INPUT Note: Input and Output should be formatted as given for the example. For any wrong value input display “INVALID INPUT” def inv(): print("INVALID INPUT") inv() # This helps you in code reusability # avoid this if have one possibility Float decimal value after a point value = 3282.2548 print("%.f"%value) # 3282 print("%.1f"%value) # 3282.3 print("%.2f"%value) # 3282.25 Stay Tuned If you like to improve your App Development Skills, even more in Flutter and SwiftUI. Feel free to dm me on Instagram or tweet to me on Twitter if you have any additional tips or feedback. Thanks for reading! Top comments (2) Good Thanks of lot:D
https://dev.to/irangareddy/tcs-quick-shots-4ci6
CC-MAIN-2022-40
refinedweb
299
64.2
Customizing the 2007 Office Fluent Ribbon for Developers (Part 1 of 3) Summary: Learn how to customize the 2007 Office Fluent user interface. Also learn how new features in Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System support RAD development of Ribbon customizations. (40 printed pages) Frank Rice, Microsoft Corporation Ken Getz, MCW Technologies, LLC Published: May 2006 Updated: October 2006 Applies to: Microsoft Office Access 2007, Microsoft Office Excel 2007, Microsoft Office Outlook 2007, Microsoft Office PowerPoint 2007, Microsoft Office Word 2007, Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System, Microsoft Visual Studio 2005 Contents An Improved User Interface New Ways to Enhance the User's Experience What About Existing Solutions? Customizing the Fluent UI for Most Office Applications Using Callbacks Two Ways to Customize the Fluent UI Adding Document-Based Add-ins to the Fluent UI UI Customization in Access 2007 Creating an Access Application-Level Custom Ribbon Ribbon Customization Scenarios for Other Applications Using COM Add-ins to Modify the Fluent UI Working with Existing Command-Bar Add-Ins Dynamically Updating the Fluent UI Conclusion Additional Resources An Improved User Interface Many of the applications in the 2007 Microsoft Office system have a new look. The new Microsoft Office Fluent user interface (UI) replaces the current system of layered menus, toolbars, and task panes with a simpler system optimized for efficiency and discoverability. The new Fluent UI has improved context menus, Enhanced ScreenTips, a Mini toolbar, and keyboard shortcuts that help to improve user efficiency and productivity. New Ways to Enhance the User's Experience Developers have taken advantage of the tools and programming structures in earlier versions of Office to extend the Fluent UI in creative ways. For example, the command bars object model enabled developers to build rich solutions in their custom Office applications. Continuing in that tradition, UI extensibility introduces an innovative model that you can use to enhance the user experience. You use extensible markup language (XML) and one of several conventional programming languages to manipulate the components that make up the Fluent UI. Because XML is plain text, you can create customization files in any text editor, which simplifies work with the Fluent UI. You can also reuse custom Fluent UI files with a minimum of adjustments because each application uses the same programming model. Figure 1. The Fluent UI in applications in the 2007 Office release .gif) Using XML markup files to customize the Fluent UI greatly reduces the need for complex add-ins based on the command bars object model. However, add-ins written for previous versions of Office will continue to work in the Fluent UI with little or no modification. What About Existing Solutions? In previous versions of Office, developers used the command bars object model to build the Visual Basic code that modified the Fluent UI. In the 2007 release of Office, this legacy code continues to work in most cases without modification. However, changes made to toolbars in Microsoft Office 2003 now appear on an Add-Ins tab. The type of customization that appears depends on the original design of the add-in. For example, Office creates a Menu Commands group that contains items added to the previous menu structure (such as the File menu, the Insert menu, and the Tools menu). Office also creates a Toolbar Commands group that contains items added to the previous built-in toolbars (such as the Standard toolbar, the Formatting toolbar, and the Picture toolbar). In addition, custom toolbars that are added by an add-in or document appear in the Custom Toolbars group on the Add-Ins tab. Customizing the Fluent UI for Most Office Applications You can create a custom application-level Fluent UI in Word 2007, in Excel 2007, or in PowerPoint 2007 in the following ways: By using COM add-ins in managed or unmanaged code By using application-specific add-ins, such as .ppam and .xlam files By using templates (.dotm files) in Word 2007 In a typical scenario, code in a COM add-in contains a procedure that returns XML markup from an external customization file or from XML contained in the code itself. When the application starts, the add-in loads and runs the code that returns the XML markup. The code validates the XML markup against an XSD schema (though that is optional), and then loads the XML into memory and applies it to the Fluent UI. The modified Fluent UI then appears. Fluent UI commands and controls use callback procedures to run code in the add-in. Document-level customizations use the same XML markup and an Office Open XML Formats file with one of these extensions: .docx, .docm, .xlsx, .xlsm, .pptx, or .pptm. For these solutions, you create a customization file that contains the XML markup and save it to a folder. You then modify the parts in the Office Open XML Formats container to point to the customization file. When you open the document in the Office application, the application loads the customization file into memory and applies it to the Fluent UI. The commands and controls then call code contained in the document to provide functionality. Using Callbacks You specify callbacks to update properties and perform actions from your Fluent UI at run time. For example, to specify an action that occurs when the user clicks a button on the Ribbon, you must supply the onAction callback function for the button. The Ribbon extens!"); } } The MyButtonOnAction procedure must be declared as public. The control parameter carries the unique id and tag properties of the control, which enables you to use the same callback procedure for multiple controls. Two Ways to Customize the Fluent UI Applications that support the Ribbon (except Access 2007, as described Creating an Access Application-Level Custom Ribbon) provide two ways to customize the Fluent UI by using XML markup: by using Office Open XML Formats files that contain XML markup, or by using COM add-ins that contain XML markup. (In the case of Outlook, only COM add-ins can customize the Fluent UI.) Any changes that you specify in this XML markup add incrementally to the existing Fluent UI. For example, providing XML markup that identifies a custom tab adds a single tab to the existing tabs in the host application. All controls in Ribbon extensibility markup must include one of the following identifiers. Table 1. One of these identifiers must be used with all controls General Format of XML Markup Files You can use XML markup to customize the Fluent UI. The following example shows the general format of an XML markup file that customizes the Fluent UI in Word 2007. Examples in the following sections use this markup. <customUI xmlns=""> <ribbon> <tabs> <tab idMso="TabHome"> <group idMso="GroupFont" visible="false" /> </tab> <tab id="CustomTab" label="My Tab"> <group id="SampleGroup" label="Sample Group"> <toggleButton id="ToggleButton1" size="large" label="Large Toggle Button" getPressed="ThisDocument.MyToggleMacro" onAction="ThisDocument.MyActionMacro" /> <checkBox id="CheckBox1" label="A CheckBox" screentip="This is a check box" onAction="ThisDocument.MyCheckboxMacro" /> <editBox id="EditBox1" getText="ThisDocument.MyTextMacro" label="My EditBox" onChange="ThisDocument.MyEditBoxMacro"/> <comboBox id="Combo1" label="My ComboBox" onChange="ThisDocument.MyComboBoxMacro"> <item id="Zip1" label="33455" /> <item id="Zip2" label="81611" /> <item id="Zip3" label="31561" /> </comboBox> <dialogBoxLauncher> <button id="Launcher1" screentip="My Launcher" onAction="ThisDocument.MyLauncherMacro" /> </dialogBoxLauncher> </group> <group id="MyGroup" label="Sample My Group" > <button id="Button1" label="My Large Button" size="large" onAction="ThisDocument.MyButtonMacro" /> <button id="Button2" label="My Normal Button" size="normal" onAction="ThisDocument.MyOtherButtonMacro" /> </group > </tab> </tabs> </ribbon> </customUI> This XML markup results in a modified Fluent UI, as the following figure shows. Figure 2. Sample of Fluent UI customization in Word .gif) This sample makes the following changes to the Fluent UI in Word 2007, in the order shown: The sample declares the default namespace for the XML markup. The sample hides the built-in GroupFont group that is located on the built-in Home tab. The sample adds a new CustomTab tab to the right of the last built-in tab, with the label My Tab. markup is to use a validating XML editor. Microsoft Visual Studio 2005 provides such an editor that you can use, if you can provide the necessary schema (XSD) file. In this case, you need a current copy of customUI.xsd, which is available in several places. For example, when you install Microsoft Visual Studio 2005 Tools for the 2007 Microsoft Office System (also known as Visual Studio 2005 Tools for Office Second Edition), it adds the schema to the Visual Studio schema catalog, so the schema is available by default in a Visual Studio project. You can also find the schema at the 2007 Office System: XML Schema Reference Web site. In Visual Studio, create a new XML file, and in the Properties window, set the Schemas property to include the customUI.xsd file (or enter the schema reference in the code, as shown in the previous XML document). Then, as you enter XML content into the file, you can take advantage of Microsoft IntelliSense technology. You might also find the XML Notepad 2006 download useful; it is available from the Microsoft Download Center. This tool enables you to edit and view XML content in a tree-based format. Customizing the Fluent UI by Using Office Open XML Formats Files At the document level, the process for customizing the Fluent UI by using XML markup involves the following steps. For more information, see Adding Document-Based Add-ins to the Fluent UI later in this article. You can follow these steps, using the XML markup described in the previous section. To customize the Fluent UI by using Office Open XML Formats files Create a folder on your desktop named customUI. Create the customization file in any text editor by writing XML markup that adds new components to the Fluent UI, modifies existing components, or hides components. You can use the XML markup from the previous example, to test the behavior. Save the file as customUI.xml (or any other name) in the folder you just created. Validate the XML markup against your custom Fluent UI schema (optional). Create a document in the Office application, and then save it as an Office Open XML Formats file with one of these extensions: .docx, .docm, .xlsx, .xlsm, .pptm, or .pptx. File name extensions for files that contain macros have an "m" suffix. These files can contain procedures that can be called by Ribbon extensibility commands and controls. Exit the Office application. In Microsoft Windows Explorer, add the file name extension .zip to the document file name, and then double-click the file to open it as a compressed folder. Add the customization file to the container by dragging the customUI folder from the desktop to the compressed folder. Drag the _rels folder to the desktop. A folder named _rels containing the .rels file appears on the desktop. Open the new folder, and then open the .rels file in a text editor. Between the final <Relationship> element and the closing <Relationships> element, add a line that creates a relationship between the document file and the customization file. Ensure that you specify the folder and file names correctly (the Id attribute supplies a unique relationship ID for the customUI—its value is arbitrary). <Relationship Type=" relationships/ui/extensibility" Target="/customUI/customUI.xml" Id="customUIRelID" /> Save the .rels file. Drag the .rels file from the desktop to the _rels folder in the compressed file, replacing the existing .rels file. Remove the .zip extension from the container file. When you open the file in the Office application, the UI appears with your customizations. Depending on your application settings, if you use the markup from the previous section in this example, you might receive several warning messages as you open the document. Because you have not supplied the code that corresponds to the various callback procedures, you have not really created a complete custom UI yet. Adding Document-Based Add-ins to the Fluent UI The following steps outline the basic process for creating a document that contains a simple custom UI in Excel 2007 that can call a custom macro: Create a macro-enabled Excel workbook with one macro. Create a file to customize the Fluent UI by adding one tab, one group, and one button. Create a procedure in VBA that the Fluent UI calls, in response to the button being clicked. Specify the onAction callback attribute in the button's markup, so that it calls the macro you created in the document. Modify the contents of the macro-enabled document container so that it contains the file that customizes the Fluent UI. Save the macro-enabled file, and then open it in Excel 2007.. Note If you save the document as a standard .xlsx document, you will not be able to run the macro code. When you save the document, you must explicitly select the Save As menu option, and then select Excel Macro-Enabled Workbook (*.xlsm). Exit Excel. To create the file that contains the XML markup to modify the Fluent UI Create a folder on your desktop named customUI. Create a new text file, add the following XML, and then save the file as customUI.XML in the customUI folder on your desktop. > To modify files contained in the macro-enabled file container In Windows Explorer, find the macro-enabled file you created. Rename the file by adding the .zip extension. In Windows Explorer, double-click the file to open it. Add the customization file to the container by dragging the customUI folder from the desktop to the compressed folder and clicking the Add button when prompted. Drag the _rels folder to the desktop. Open the new folder, and then open the .rels file in a text editor. Add the following text between the last <Relationship> element and the </Relationships> element, and then save and close the file. <Relationship Id="customUIRelID" Type="" Target="customUI/customUI.xml" /> Drag the .rels file from the desktop to the _rels folder in the compressed folder, replacing the existing .rels file. Remove the .zip extension from the container file name. Open the macro-enabled file in Excel 2007. The custom UI replaces the built-in Fluent UI. Click Large Button. Clicking the button triggers the onAction callback, which calls the macro in the workbook, which displays the "Hello World" message. Customizing the Fluent UI with COM Add-Ins Customizations at the application level result in a modified Fluent UI that appears in the application regardless of which document is open. Generally, COM add-ins make these modifications. You generally have two options for creating COM add-ins by using managed code: You can use the Shared Add-In template that is included with Visual Studio 2005, or you can use Visual Studio 2005 Tools for Office Second Edition, which makes it even easier to create add-ins. The following steps describe the underlying method call sequence for a COM add-in that customizes the Ribbon. Although the concepts are the same no matter how you create the add-in, the specific code that you need to write will be different, as you will see in later sections of this article that walk you through examples that create add-ins, by using both techniques. To customize the Fluent UI by using COM add-ins Create a COM add-in project. The add-in you create must implement the Extensibility.IDTExtensibility2 interface and the IRibbonExtensibility interface (found in the Microsoft.Office.Core namespace). Build the add-in and Setup project and then install the project. Start the Office application. When the add-in loads, the IDTExtensibility2::OnConnection event is triggered, which initializes the add-in, just as in previous versions of Office. Next, Office calls either the QueryInterface method (for unmanaged add-ins) or the QueryService method (for managed add-ins), which determines whether the add-in implements the IRibbonExtensibility interface. If it does, Office calls the IRibbonExtensibility::GetCustomUI method, which returns the XML markup (from an XML customization file or from XML markup embedded in the procedure), and then Office loads the customized Fluent UI into the application. Finally, the customized UI is ready for the user. Each control specified in the XML markup exposes its functionality by calls to callback procedures. For example, the XML markup for a button control can specify an onAction attribute that points to a procedure that is executed when the user clicks the button. In most cases, the callback procedure exposes an IRibbonControl interface that identifies the control. The callback might pass other arguments as well, such as a Boolean object that specifies the state of a toggle button as pressed or not pressed. The IRibbonControl interface implements three properties: the Context object, the Id object, and the Tag property. The Context object is the active window that contains the Ribbon that triggers the callback. The Id object is the string identifier of the custom control specified in the markup. The Tag property is a non-unique property that you can optionally specify in the markup. UI Customization in Access 2007 Ribbon extensibility customizations in Access 2007 share some of the same options that the other Office applications have, but with some important differences. Just as with the other applications, you customize the Fluent UI in Access by using XML markup. And like the other applications, you can use external files that contain XML markup or COM add-ins to integrate Ribbon customizations into your application. However, unlike the other Office applications, because Access database files are binary and cannot be opened as Office Open XML Formats files, you cannot customize the Access Ribbon by adding parts to the database file. Access does provide flexibility in customizing the Fluent UI. For example, customization markup can be stored in a table, embedded in a VBA procedure, stored in another Access database, or linked to from an Excel worksheet. You can also specify a custom UI for the application as a whole or for specific forms and reports. The following scenarios can give you an idea of how to customize the Access UI. Customizing the Fluent UI in Access When customizing the Access UI, you have two choices: You can store your customizations in a special table and have Access automatically load the markup for you, or you can store the customizations in a location of your choosing and load the markup manually by calling the Application.LoadCustomUI method. If you choose to have Access load the customizations for you, you need to store them in a table named USysRibbons. The table should have at least two columns: a 255-character Text column named RibbonName, and a Memo column named RibbonXML. You place the Ribbon name in the RibbonName column, and the Ribbon markup in the RibbonXML column. After you close and re-open the database, you can select the default Ribbon to use in the Access Properties dialog box. You can select a Ribbon to appear when any form or report is selected as a property of the form or report. If you decide to use a more dynamic technique, you can call the LoadCustomUI method, which loads Ribbon customizations whether the XML content is stored in a table or not. After you have loaded the customizations by calling LoadCustomUI, you can programmatically assign the named customization at run time. The signature for the LoadCustomUI method is as follows. expression.LoadCustomUI(CustomUIName As String, CustomUIXML As String) expression returns an Application object. CustomUIName is the name of the Custom Ribbon ID to be associated with this markup. CustomUIXML contains the XML customization markup. There is an example of using the LoadCustomUI method Loading Customizations at Run Time. The following procedure describes, in a generalized manner, how to add application-level customizations in Access. A later section includes a complete walkthrough. To apply a customized application-level Ribbon at design time Create a table named USysRibbons with columns as described earlier. Add rows for each different Ribbon you want to make available. Close and then reload the database. Click the Microsoft Office Button, and then click Access Options. Click the Current Database option and then, in the Ribbon and Toolbar Options section, click the Ribbon Name drop-down list and click one of the Ribbons. To remove an existing customization (so that your database uses the default Fluent UI), delete the existing Ribbon name from the Ribbon Name list, and leave an empty value for the name of the Ribbon. The following procedure describes, in a generalized manner, how to add form-level customizations or report-level customizations in Access. To assign a specific custom Ribbon to a form or report Follow the process described previously to make the customized Ribbon available to the application, by adding the USysRibbons table. Open the form or report in Design view. On the Design tab, click Property Sheet. In the Property window, on the Other tab, click the Ribbon Name drop-down list, and then click one of the Ribbons. Save, close, and then re-open the form or report. The UI you selected is displayed. To explore this process further, work through the following examples. The first part of the example sets an option that reports any errors that exist when you load custom UI (although you are performing these steps in Access, you can perform similar steps in other applications). Creating an Access Application-Level Custom Ribbon To create an Access application-level custom ribbon Start Access. Open an existing database, or create a new database. Click the Microsoft Office Button, click Access Options, and then click the Advanced tab. In the General section, select the option Show add-in user interface errors (this option might be in a different location, in different applications). Click OK to close the Access Options dialog box. Next, create a table that contains your customization XML markup. With a database open in Access, right-click the Navigation pane. Point to Navigation Options, and then click Show System Objects. (You cannot view the USysRibbons table in the Navigation pane unless this option is set.) Click OK to dismiss the dialog box. The Access system tables appear in the Navigation pane. On the Create tab, click Table Design. Add the following fields to the table. Table 2. USysRibbons table field definitions Select the ID field. On the Design tab, select Primary Key. Click the Microsoft Office Button, and then click Save. Name the new table USysRibbons. Right-click the USysRibbons tab, and then click Datasheet View. Add the following data to the fields you created. Table 3. USysRibbons table data This markup sets the startfromScratch attribute to False, and then hides the built-in Create tab. Next, it creates a custom tab and a custom group, and adds the built-in Paste control to the group. Close the table. Close and then re-open the database. Click the Microsoft Office Button, and then click Access Options. Click the Current Database tab, and scroll down until you find the Ribbon and Toolbar Options section. In the Ribbon Name drop-down list, select HideData. Click OK to dismiss the dialog box. Close and re-open the database. The Edit group is no longer displayed, and the Fluent UI includes the A Custom Tab tab, which contains the A Custom Group group with the Built-in Paste button. Figure 3. The Access application-level UI To clean up, repeat the previous few steps to display the Access Options dialog box. Delete the contents of the Ribbon Name option, so that Access displays its default Fluent UI after you close and re-open the database. If you want to load static customizations at run time, you can store those customizations in the USysRibbons table, and set a form or report's RibbonName property as necessary. But, if you need to create dynamic customizations, call the Application.LoadCustomUI method. The following example creates a Ribbon customization that displays a button for each form in the application, and handles the onAction callback for each button to load the requested form. To create a dynamic Ribbon customization Load the database that you worked with in the previous section into Access 2007. If your database does not already include more than one form, create a few forms, and add a control or two to each form. On the Create tab, in the Other group, click the drop-down list of the Macro button, and then click Module. In the Visual Basic Editor, on the View menu, click Properties Window. In the Properties window, in the Name property box, change the name of the module to RibbonLoader. In the code window, insert the following code. Even though this method does not return a value, it must be a function—otherwise, you cannot call it from an Access macro. Function CreateFormButtons() Dim xml As String xml = _ "<customUI" & _ "office/2006/01/customui"">" & vbCrLf & _ " <ribbon startFromScratch=""false"">" & vbCrLf & _ " <tabs>" & vbCrLf & _ " <tab id=""DemoTab"" label=""LoadCustomUI Demo"">" & _ vbCrLf & _ " <group id=""loadFormsGroup"" label=""Load Forms"">" & _ vbCrLf & _ "{0}" & vbCrLf & _ " </group>" & vbCrLf & _ " </tab>" & vbCrLf & _ " </tabs>" & vbCrLf & _ " </ribbon>" & vbCrLf & _ "</customUI>" Dim template As String" & vbCrLf Dim formContent As String Dim frm As AccessObject For Each frm In CurrentProject.AllForms formContent = formContent & _ Replace(template, "{0}", frm.Name) Next frm xml = Replace(xml, "{0}", formContent) Debug.Print xml On Error Resume Next ' If you call this code from the AutoExec macro, ' the only way it can fail is if you have a ' customization with the same name in the ' USysRibbons table. Application.LoadCustomUI "FormNames", xml End Function When you run the code, it creates markup that might look like the following XML, if your application contains two forms named Form1 and Form2. > This markup creates a new LoadCustomUI Demo tab that contains a Load Forms group. Within the group, the Ribbon displays a button for each form in the application (Form1 and Form2), and indicates that each button should call the HandleOnAction callback procedure when clicked. In addition, the markup sets the Tag attribute for each button so that it contains the name of the Access form that your code should open. Add the following procedure to the same module. This procedure supplies the callback behavior. It opens the selected form and sets its RibbonName property to the FormNames Ribbon customization. Public Sub HandleOnAction(control As IRibbonControl) ' Load the specified form, and set its ' RibbonName property so that it displays ' the custom UI. DoCmd.OpenForm control.Tag Forms(control.Tag).RibbonName = "FormNames" End Sub Save the database, and close the Visual Basic Editor. If your application does not contain at least two forms, create forms until the application contains at least two forms. Decide which one of your forms should be your application's startup form, and open that form in Design view. In the Properties window, on the Event tab, find the onLoad event property. Click the ellipsis (...) button to the right of the property value, select Code Builder in the list of options, and then click OK. (If you do not see the Properties window, on the Design tab, click Property Sheet.) In the Visual Basic Editor, modify the Form_Load procedure so that it looks like the following code.. The startup form opens, along with a custom tab that contains a group that displays a button for each form in your application. Click any of the buttons: Access opens the corresponding form, maintaining the same custom UI. In addition to the described techniques, you can add Ribbon customizations to Access by using a COM add-in. COM add-ins provide the benefit of adding custom Ribbon extensibility functionality as a package without the need to add VBA code to each application. Add-ins are implemented in Access just as they are in other Office applications. Ribbon Customization Scenarios for Other Applications Consider the following scenarios that illustrate ways to modify the Fluent UI to fit your needs. Creating Custom Solutions Although each example you have seen so far modifies the existing Ribbon, you can create your entire UI from scratch. You might do this if you want to build your own UI and design your own custom layout for the Ribbon. If you set the Ribbon element's startFromScratch attribute to True, the Ribbon hides all of its content (so you do not have to do the work to hide everything manually). When you set the startFromScratch attribute to True, it makes the following changes: Hides all the existing Ribbon tabs, including the Add-Ins tab Modifies the Microsoft Office menu to include only the New, Open, Save, Application Options, and Exit commands Setting the startFromScratch attribute makes no changes to the status bar, which remains present. The following sample XML markup uses the startFromScratch attribute to customize the Fluent UI. <customUI xmlns="" > <ribbon startFromScratch="true" > <tabs> <tab id="CustomTab" label="My Tab" > <group id="SimpleControls" label="My Group"> <toggleButton id="ToggleButton1" size="large" label="Large Toggle Button"/> <button id="Button2" label="My Button " /> <comboBox id="Combo1" label="ComboBox"> <item id="Month1" label="January" /> <item id="Month2" label="February" /> <item id="Month3" label="March" /> </comboBox> </group> </tab> </tabs> </ribbon> </customUI> This sample hides all of the built-in components in the Fluent UI and replaces them with a custom tab, one group, and various controls. Showing and Hiding Tabs Showing and Hiding Groups> Adding Custom Tabs You can use the following code sample to add custom tabs. <tab id="CustomTab" label="My Tab" /> Adding Custom Groups with Controls to add a custom group, and then add custom controls. <group id="CustomGroup" > <toggleButton id="MyToggleButton" size="large" label="Insert My Object"/> <checkBox id="AllowChanges" label="Allow Changes" /> <dropDown id="ChooseDepartment" showLabel="true" label="Choose Department"> <item id="Dept1" label="Shipping" /> <item id="Dept2" label="Accounting" /> <item id="Dept3" label="Engineering" /> </dropDown> </group> Creating a Custom Menu with Nested Menus and Controls You can use the following code sample to create a custom menu, and then add nested built-in menus and controls and custom menus and controls. This markup also includes two menu separators, with and without text. <menu id="MyMenu" label="Test Menu" itemSize="normal"> <toggleButton idMso="Bold"/> <button id="MenuButton1" label="Button1" /> <menuSeparator id="separator1"/> <toggleButton id="MenuToggleButton1" label="ToggleButton" /> <button idMso="FileExit"/> <menu id="Nested1" label="Advanced" itemSize="normal"> <button idMso="Cut"/> <button idMso="Copy"/> <button idMso="Paste"/> <menuSeparator id="separator2" title="Large Buttons Below"/> <menu id="Nested2" label="Large" itemSize="large"> <button idMso="Cut"/> <button idMso="Copy"/> <button idMso="Paste"/> </menu> </menu> </menu> Adding Combo Boxes or Drop-Down Boxes with Nested Items> Adding Custom Gallery Controls with Items You can use the following code sample to add gallery controls with items, and then add a custom button control. <gallery id="MonthGallery" imageMso="DateAndTimeInsert" label="Pick a Month:" columns="3" rows="4" onAction="InsertMonth" > <item id="Month1" label="January"/> <item id="Month2" label="February"/> <item id="Month3" label="March"/> <item id="Month4" label="April"/> <item id="Month5" label="May"/> <item id="Month6" label="June"/> <item id="Month7" label="July"/> <item id="Month8" label="August"/> <item id="Month9" label="September"/> <item id="Month10" label="October"/> <item id="Month11" label="November"/> <item id="Month12" label="December"/> <button id="InsertMonthButton" label="Insert current month" onAction="InsertCurrentMonth"/> </gallery> The following VBA procedures provide callback behavior for the gallery items and the button within the gallery. Sub InsertMonth(control As IRibbonControl, _ selectedId As String, selectedIndex As Integer) Dim text As String Select Case control.ID Case "MonthGallery" text = monthName(selectedIndex + 1) End Select Selection.InsertAfter text End Sub Sub InsertCurrentMonth(control As IRibbonControl) Select Case control.ID Case "InsertMonthButton" text = monthName(DatePart("m", Date)) End Select Selection.InsertAfter text End Sub You can populate gallery controls at run time by using callbacks. You can use the getItemCount callback to determine the number of items to display, the getItemHeight and getItemWidth callbacks to retrieve the height and width of the items in the gallery, the getItemImage and getItemLabel callbacks to retrieve the image and label for each item, and the getSelectedItemID or getSelectedItemIndex callback to retrieve the selected ID or index. Filling a Drop-Down List Dynamically You might not know which items to display in a Ribbon control until run time. Callbacks make it possible to supply the values based on current conditions. For example, you might want to display a list of document headings. The following example demonstrates how you might provide a list of current document headings. Include the following control in your Ribbon customization. <dropDown id="HeadingsDropDown" getItemCount="GetItemCount" getItemID="GetItemID" getItemLabel="GetItemLabel"/> Then, in your code (in this case, in a module within the Word document's Visual Basic Editor), add the following callback procedures. Sub GetItemCount(control As IRibbonControl, ByRef count) Dim varItems As Variant varItems = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading) count = UBound(varItems) End Sub Sub GetItemLabel(control As IRibbonControl, index As Integer, _ ByRef label) Dim varItems As Variant varItems = ActiveDocument.GetCrossReferenceItems(wdRefTypeHeading) label = varItems(index + 1) End Sub Sub GetItemID(control As IRibbonControl, index As Integer, ByRef ID) ID = "heading" & index End Sub Now, when you open the drop-down list, it shows all the headers in your document. Grouping Individual Controls By default, the Ribbon determines the positions of controls that you add to a group. If you want to define the layout of the controls with more precision, you can group the controls within one or more boxes. When you create a box, you specify its orientation (horizontal or vertical). A group can contain multiple boxes, and you can include vertical dividers between the boxes. (The vertical dividers are created by using the separator control, which is used only for vertical boxes.) The following example sets up three groups, one that uses horizontal boxes, one that uses vertical boxes, and one that uses no boxes. Figure 4 shows the results. <group id="CustomGroup1" label="Horizontal Boxes" insertBeforeMso="GroupClipboard"> <box id="box1" boxStyle="horizontal"> <button id="buttonA1" label="Button1"/> <button id="buttonA2" label="Button2"/> </box> <box id="box2" boxStyle="horizontal"> <button id="buttonAA" label="ButtonA"/> <button id="buttonAB" label="ButtonB"/> <button id="buttonAC" label="ButtonC"/> </box> </group> <group id="CustomGroup2" label="Vertical Boxes" insertBeforeMso="GroupClipboard"> <box id="box3" boxStyle="vertical"> <button id="buttonB1" label="Button1"/> <button id="buttonB2" label="Button2"/> </box> <separator id="separator2"/> <box id="box4" boxStyle="vertical"> <button id="buttonBA" label="ButtonA"/> <button id="buttonBB" label="ButtonB"/> <button id="buttonBC" label="ButtonC"/> </box> </group> <group id="CustomGroup3" label="No Boxes" insertBeforeMso="GroupClipboard"> <button id="buttonC1" label="Button1"/> <button id="buttonC2" label="Button2"/> <button id="buttonCA" label="ButtonA"/> <button id="buttonCB" label="ButtonB"/> <button id="buttonCC" label="ButtonC"/> </group> Figure 4. Different box styles .gif) Using COM Add-ins to Modify the Fluent UI You can use COM add-ins to modify the Fluent UI. When you decide to create a COM add-in that incorporates Ribbon customization and uses managed code, you have two distinct choices. You can create a standard shared add-in, using the Shared Add-In template that comes with Visual Studio 2005. Or, if you have installed Visual Studio 2005 Tools for Office Second Edition, you can create a COM add-in that has several advantages over the standard shared add-in. Among other advantages, add-ins that you create by using Visual Studio 2005 Tools for Office Second Edition run in separate application domains, and the programming model for these add-ins is simpler, and more maintainable, than that used by the shared add-in template. For more information, see Migrating a Shared Add-in to a Visual Studio 2005 Tools for the Office System SE Add-in.. InsertCompany InsertCompanyAddIn for the name and Insert Company Name 2007 and the Ribbon object model, add references to two type libraries. To add references Word = Microsoft.Office.Interop.Word using Microsoft.Office.Core; using Word = Microsoft.Office.Interop.Word; To create an XML customization file On the Project menu, click Add New Item. In the Add New Item dialog box, select XML File. Name the new file Ribbon.xml, and then click Add. In the new XML file, add the following XML markup. <customUI xmlns=""> <ribbon> <tabs> <tab id="CustomTab" label="My Tab"> <group id="SampleGroup" label="Sample Group"> <button id="Button" label="Insert Company Name" size="large" onAction="InsertCompanyName" /> </group> </tab> </tabs> </ribbon> </customUI> Save and close the file. It is easiest to use the XML file if it is treated as a resource within the project's resource file. To create the XML resource In Solution Explorer, select Ribbon.xml. In the Properties window, select the Build Action property, and then select Embedded Resource in the list of options. On the Project menu, click InsertCompanyAddIn Properties. Click the Resources tab. From Solution Explorer, drag Ribbon.xml onto the Resources design surface. This action creates a new file-based resource that contains the XML content. From now on, the Ribbon.xml file is automatically stored as an application resource, and you can retrieve this content by using Visual Basic or Visual C# language features. Close the Resources window. When prompted, click Yes to save the resources. To access the host application and work with the Ribbon In Solution Explorer, right-click Connect.cs or Connect.vb, and then click View Code. Find the existing declaration for the applicationObject variable, and modify it so that it refers to a Word.Application object. That is, modify the declaration so that it looks like the following code. (C# only)); } On the File menu, click Save All. Exit Word 2007 if it is running. On the Build menu, click Build Solution. In Solution Explorer, right-click InsertCompanyAddInSetup, and then click Build. Right-click InsertCompanyAddInSetup, and then click Install. The InsertCompanyAddIn Setup Wizard appears. Click Next on each of the pages, and then click Close on the last screen. Start Word. The My Tab tab appears to the right of the other tabs. Click My Tab, and then click Insert Company Name. Word inserts the specified company name into the document at the cursor location. Exit Word. In Visual Studio, in Solution Explorer, right-click InsertCompanyAddInSetup, and then click Uninstall.. In the New Project dialog box, select Visual Basic or Visual C#. In the Project Types pane, expand the Office node, and select 2007 Add-ins. In the Templates pane, select Word Add-in. Name the new add-in InsertCompanyAddIn1, and then click OK to create the new add-in. Visual Studio creates a new solution containing two projects—the add-in itself, and a Setup project. (The Setup project enables you to install the add-in on other users' computers, and it makes it easier for you to install and uninstall the add-in at design time.) Note that although the new add-in implements the IExtensibility2 interface, you do not see all the procedures required by this interface. Instead, Visual Studio 2005 Tools for Office Second Edition creates a simple class named ThisAddIn, and provides the procedures you are likely to need. You can add code to the ThisAddIn_Startup method or to the ThisAddin_Shutdown method, as appropriate. For this example, you do not need code in either method. You also do not need to modify code or set references to create the add-in—all the connection work has been done for you. To add a Ribbon extensibility item On the Project menu, click Add New Item. In the Add New Item dialog box, select Ribbon Support. Click Add to accept the default name (Ribbon1.vb or Ribbon1.cs). The template adds an XML file named Ribbon1.xml, and a new class to your project. The XML file contains a very simple customized UI. The new Ribbon1 file contains a commented-out extension of the ThisAddIn class, and a new class named Ribbon1. In Solution Explorer, double-click Ribbon1.xml to open it in the XML editor. Modify the existing XML, so that it looks like the following markup. <customUI xmlns="" onLoad="onLoad"> <ribbon> <tabs> <tab id="CustomTab" label="My Tools Tab"> <group id="SampleGroup" label="Sample Group"> <button id="Button" label="Insert Company Name" size="large" onAction="InsertCompanyName" /> </group> </tab> </tabs> </ribbon> </customUI> Save the XML file and close the XML editor. It is easiest to use the XML file if it is treated as a resource within the project's resource file. To create the XML resource On the Project menu, click InsertCompanyAddIn1 Properties. Click the Resources tab. From Solution Explorer, drag Ribbon1.xml onto the Resources design surface. This action creates a new file-based resource that contains the XML content. From now on, the Ribbon1.xml file is automatically stored as an application resource, and you can retrieve this content by using Visual Basic or Visual C# language features. Close the Resources window. When prompted, click Yes to save the resources. To modify the Ribbon code and complete the add-in In Solution Explorer, right-click Ribbon1.vb or Ribbon1.cs, and then click View Code. In the Code Editor, select the partial class named ThisAddIn, and uncomment the partial class. The RequestService procedure enables the Visual Studio 2005 Tools for Office Second Edition runtime to determine which class should handle callbacks for the add-in's Ribbon customization. If this procedure is passed a GUID corresponding to the IRibbonExtensibility interface, it returns its IRibbonUI instance, if it has one. If not, it passes control to the RequestService method of its base class. In the Ribbon1 class, modify the GetCustomUI procedure so that it returns the XML from the Ribbon1 resource, rather than calling the add-in's GetResourceText procedure. Return My.Resources.Ribbon1 return Properties.Resources.Ribbon1;); } To test the add-in On the File menu, click Save All. Press F5 to run the project, which also starts Word 2007. Click the My Tools Tab tab, and then click Large Button. The code inserts the company name at the cursor location in the document. Exit Word 2007. You can build the Setup project and install the add-in just as you did in the previous example. In this case, Visual Studio 2005 Tools for Office Second Edition makes it easier to run (and debug) add-ins. Press F5, and the project runs as you might expect. You can get the same behavior with the shared add-in template—you just need to set the project properties that indicate which application you want to run when you press F5, and select the correct Office application. You might find it instructive to debug the add-in, and add a breakpoint to the code. Working with Existing Command-Bar Add-Ins When you create COM add-ins, you usually need a way for users to interact with the add-in. In earlier versions of Office, you accomplished this by adding a menu item or toolbar button to the application by using the command bars object model. In the 2007 release of Office, custom applications continue to work in the Fluent UI without modification in most cases. However, changes you make with the command bars object model, or with any other technology that modifies the menus or toolbars, such as WordBasic or XLM, appear on a separate Add-Ins tab. This helps users locate the controls they need to work with and the add-ins they used previously. Figure 5. A custom toolbar button added to the Add-Ins tab in Excel 2007 .gif) To make changes to the items in the Fluent UI, you can use the techniques and code already described. For existing add-ins that change the menu structure, the commands appear on the Add-Ins tab. For information about how to update existing add-ins, see the technical article Migrating a Shared Add-in to a Visual Studio 2005 Tools for the Office System SE Add-in. Dynamically Updating the Fluent UI Callbacks that return properties of a control (such as the gallery control's getItemCount callback) normally get called only as the Fluent UI initializes, unless you explicitly force the control to re-initialize. You can force this to happen by storing a reference to the Ribbon in your code, and then calling methods of the Ribbon that invalidate an individual control or the entire Ribbon. To do this, you must add the onLoad attribute, specifying a callback procedure, in the <customUI> element. The onLoad callback is called once, when the Ribbon extensibility markup file is successfully loaded. The callback procedure receives an IRibbonUI object as a parameter—your code can cache this reference for later use. The IRibbonUI class provides methods that enable you to invalidate a single control or the entire Ribbon. To cache the IRibbonUI object so you can update your controls at run time, you might add code like this: . Table 4. Methods of the IRibbonUI interface The <customUI> element's loadImage attribute enables you to specify a callback that can load all images. After you set up this callback procedure, Office calls the callback procedure and passes the string from the image attribute for each control that loads images. You do not need to implement the getImage callback multiple times, such as one time for each control that requires images. For example, a customization might include markup like the following. <customUI xmlns="" loadImage="GetImage"> <!-- Later in the markup --> <button id="myButton" image="mypic.jpg" /> To supply the button's image, Office calls the GetImage function. It passes the parameter "mypic.jpg" and expects an IPictureDisp object in return. By using this technique, you can write a single callback procedure that returns all the images your customization needs, without having to write each individual control's getImage callback. Note that the loadImage callback is not called again when you call the Ribbon's Invalidate method or InvalidateControl method. For the controls that need to change images dynamically at run time, use the getImage callback. For example, you could use the code from the following example to provide your customization's images. The getImage callback method must return a stdole.IPictureDisp type, so you usually need to convert your images to this type. To perform these conversions, you can use the following PictureConverter class, which inherits from the AxHost class. Class internal class PictureConverter : AxHost { private PictureConverter() : base(String.Empty) { } static public stdole.IPictureDisp ImageToPictureDisp(Image image) { return (stdole.IPictureDisp)GetIPictureDispFromPicture(image); } static public stdole.IPictureDisp IconToPictureDisp(Icon icon) { return ImageToPictureDisp(icon.ToBitmap()); } static public Image PictureDispToImage(stdole.IPictureDisp picture) { return GetPictureFromIPicture(picture); } } Then, your callback procedure might look something like this, assuming that you had added an icon to your project resources named MyIcon.); } Conclusion Customizing the UI in previous versions of Office meant creating COM add-ins or DLL files for each application that shared the add-in. By contrast, the Ribbon feature uses text-based, declarative XML markup that simplifies creating and customizing the Ribbon. With a few lines of XML, you can create just the right interface for the user. Because the XML markup is contained in a single file, modifying the interface as requirements change is much simpler. You can also improve user productivity by putting the commands where users can find them more easily. The Ribbon adds consistency across applications, which reduces the time users spend learning each application.
https://docs.microsoft.com/en-us/previous-versions/office/developer/office-2007/aa338202(v=office.12)
CC-MAIN-2019-09
refinedweb
7,881
54.22
Chris Downie and Sam Landfried If you’ve ever played with Core Image’s filter API, you might have been wondering “What would it take to make a filter and launch my own Snapchat!”. There are ways to build out and chain Core Image Filters to make custom ones. However, this is a bit expensive compared to writing your own. When I first went on this journey, I found many issues with API documentation being only in Objective-C and for Desktop. Moving this to both iOS and Swift proved to be quite the undertaking. Let’s jump into the deep end and take a look at the Core Image Kernel file. For this post, we are creating a CI Color Kernel that applies a haze filter in a file called HazeRemove.cikernel. kernel vec4 Haz); } So whats going on here? We’ll break it down on each line. However, it’s important to note this a pixel-for-pixel change. We run this code on a single pixel at a time and be returning a modified pixel. For the syntax, the Core Image Kernel Language sits on top of the OpenGL Shading Language so it’ll have different rules than from Swift of Objective-C. kernel vec4 HazeRemovalKernel( The first line we specify this is a kernel routine, so the system knows to hand this off to the CIKernel class to execute. We specify a return type of vec4 as Core Image requires us to return this type in order to change the input pixel for your output pixel properly. sampler src, __color color, float distance, float slope) In our function HazeRemovalKernel we are passing in a CISampler object that we treat as the source pixel. __color is a color that gets matched to the CIContext’s color space helping us keep the color looking as expected if the user has True Tone or Night Swift turned on. Also for our filter, we pass in a slope and distance as floats. These are just ways to affect the parameters of the filter for a typical haze removal algorithm. vec4 t; float d; Next, we define a few variables we’ll use and modify in our routine. The first is our modified pixel; we make this a vec4. In OpenGL, a vec4 is a vector type that has 4 components of single precision floating-point numbers. So in our case, it is holding RGBA values. Next, we define a float that is used to hold our calculated value for our haze removal algorithm. d = destCoord().y * slope + distance; To figure out the amount we want to distort we use a simple algorithm that adds the slope to the distance. To get a slope that considers the full image, we take the slope value that is passed in and multiplies is by destCoord().y. destCoord returns the position of the pixel in the current working space, and it is a good base to use to create a slope. t = unpremultiply(sample(src, samplerCoord(src))); Next thing we need to do is account for the fact there may be some transparency applied to the image. So before we do the color correction, we want to remove the alpha to get its pure color. To do this, we use a method called unpremultiply. This takes in a vec4 color so to get this we use a method called sample which returns a vec4 containing the color of a given pixel. To help sample do its job we pass in our src variable that’s of type sampler. Also, a vec2 containing that pixel coordinate. We get the vec2 by calling samplerCoord(src) that method uses the sampler variable and find its coordinates for us. All of that done and we now have two set variables. d is our distortion and t is the pure color values of the pixel we are trying the change. t = (t - d*color) / (1.0-d); Now let us create that haze! The haze is a pretty simple calculation on our end. t and color are both vect4 types, so they easily subtract from each other. return premultiply(t); Once we have our new haze removed pixel, we need to reapply that transparency if needed and return the results. We can do this by using premultiply and just returning the vect4 it generates. Great we have our CI Kernel File but to use it we’ll need to wrap it into a CI Filter, so it is accessible to call from our app. Now a word of warning we are playing with a C level API and because of this while we are writing this is Swift knowledge of C, and Objective-C interoperability is needed. import Foundation import CoreImage class HazeRemoveFilter: CIFilter { @objc dynamic var inputImage: CIImage? @objc dynamic var inputColor: CIColor = CIColor.white @objc dynamic var inputDistance: NSNumber = 0.2 @objc dynamic var inputSlope: NSNumber = 0 First, we’ll set up the filter by importing the essentials like CoreImage and creating a new class that inherits from CIFilter. We will then define our variables we’ll be passing into our Filter and give all but inputImage a default value. override var attributes: [String : Any] { return [ kCIAttributeFilterDisplayName: "Remove Haze", "inputImage": [kCIAttributeIdentity: 0, kCIAttributeClass: "CIImage", kCIAttributeDisplayName: "Image", kCIAttributeType: kCIAttributeTypeImage], "inputDistance": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Distance Factor", kCIAttributeDefault: 0.2, kCIAttributeMin: 0, kCIAttributeMax: 1, kCIAttributeSliderMin: 0, kCIAttributeSliderMax: 0.7, kCIAttributeType: kCIAttributeTypeScalar], "inputSlope": [kCIAttributeIdentity: 0, kCIAttributeClass: "NSNumber", kCIAttributeDisplayName: "Slope Factor", kCIAttributeDefault: 0.2, kCIAttributeSliderMin: -0.01, kCIAttributeSliderMax: 0.01, kCIAttributeType: kCIAttributeTypeScalar], kCIInputColorKey: [ kCIAttributeDefault: CIColor.white ] ] } Next part is a bit tricky. Because we are defining some custom inputs (being distance and slope) we need to override CIFilters attributes so it knows about them. With us overriding attributes we will also have to define some that CIFilter already had, this would be the display name, image, and color. I won’t go into all the details, the main thing to know is all we are doing is setting up a map so the C level API knows how to interpret the Objective-C objects and if any min max info, defaults, and more we want it to adhere too. There are a lot available checkout Apple’s documentation for Filter Attribute Keys in CIFilter. private lazy var hazeRemovalKernel: CIColorKernel? = { guard let path = Bundle.main.path(forResource: "HazeRemove", ofType: "cikernel"), let code = try? String(contentsOfFile: path) else { fatalError("Failed to load HazeRemove.cikernel from bundle") } let kernel = CIColorKernel(source: code) return kernel }() Now lets load in that filter! However, let us be lazy about it. This way we don’t load in the file until we know we need to use it for the first time. Again we made a CI Color Kernel, so we make sure our filter is of the same type. To load in a CI Color Kernel, you’ll pass in its source code as a string to CIColorKernel, so we simply load our file with bundle and check to make sure it has loaded in as a string. In a production application we might not want a fatal error, but for our purpose here it’ll work just fine. override var outputImage: CIImage? { get { if let inputImage = self.inputImage { return hazeRemovalKernel?.apply(extent: inputImage.extent, arguments: [ inputImage as Any, inputColor, inputDistance, inputSlope ]) } else { return nil } } } Finally getting to business. To actually filter the image we will override a computed method called outputImage. Here we can take our hazeRemovalKernel and call the CIColorKernel method apply with our input image and our arguments and get back our new filtered output. To make our new shiny filter available to Core Image clients, we need to create a vendor that implements the CIFilterConstructor protocol. import CoreImage class CustomFiltersVendor: NSObject, CIFilterConstructor { We’ll set up our filter with the awesome name of CusomFilterVendor As this is an Objective-C protocol we’ll have to inherit NSObject. New to Swift interoperability? We teach it in our Advanced iOS Bootcamp! public static let HazeRemoveFilterName = "HazeRemoveFilter" I’m not a big fan of stringly typing names. So let us define a public static variable with our filter name, so we don’t misspell anything by accident. static func registerFilters() { let classAttributes = [kCIAttributeFilterCategories: ["CustomFilters"]] HazeRemoveFilter.registerName(HazeRemoveFilterName, constructor: CustomFiltersVendor(), classAttributes: classAttributes) } Next, we’ll register our filter in a pretty straightforward way. If you have more filters you made throw them in here by calling registerName on their own filter object. This is the method telling Core Image if this filter gets called what vendor is responsible for it. func filter(withName name: String) -> CIFilter? { switch name { case CustomFiltersVendor.HazeRemoveFilterName: return HazeRemoveFilter() default: return nil } } Finally, if Core Image tells our vendor one of its filters has been called it’ll call its filter method with the filter name to figure out what filter should get returned. Here we’re assuming you are going to love writing your filters so much you’ll want to start our your own Snapchat. For this, we set up a switch so you can easily keep adding more. For using the custom filter, I like to extend CIImage that way we already have access to the root image, and it can be as simple as calling a method on any CIImage processed by our filter. enum Filter { case none case gloom(intensity: Double, radius: Double) case sepia(intensity: Double) case blur(intensity: Double) case removeHaze } First I like to define an enumerator of our filters we plan on using here we can pass in parameters like the slope and distance, but in my implementation, I was happy with the defaults we defined earlier. func filtered(_ filter: Filter) throws -> CIImage { let parameters: [String: AnyObject] let filterName: String let shouldCrop: Bool // Configure the CIFilter() inputs based on the chosen filter switch filter { case .none: return self case .removeHaze: parameters = [ kCIInputImageKey: self ] filterName = CustomFiltersVendor.HazeRemoveFilterName shouldCrop = false } Here we set up a filtered function that takes that Enum type we defined and find the corresponding filter via a switch statement. One we call ours we set up the parameters we want to pass in because we are using defaults we pass in the ImageKey of self. Moreover, make sure to set our filterName to the one we defined in our CustomFiltersVendor. // Actually create and apply the filter guard let filter = CIFilter(name: filterName, withInputParameters: parameters), let output = filter.outputImage else { throw ImageProcessor.Error.filterConfiguration(name: filterName, params: parameters) } // Crop back to the extent if necessary if shouldCrop { let croppedImage = output.cropped(to: extent) return croppedImage } else { return output } Once we have our filterName and parameters set we call CIFilter, and it takes care of the rest for us. Assuming nothing went wrong and we didn’t throw an error we get the output by calling the outputImage on our new filter object. Some filters might edit the output image outside of the original bounds so we define a shouldCrop property so if we had one of those filters we could crop the image to its original size. Extending the image is not something our filters does but look into CIGaussianBlur for an example of one that would. After all of that, the filter is complete! You could call our new filter from any CIImage as simple as just running let newImage = image.filtered(.removeHaze). I’ve hope you have enjoyed going down this tunnel of custom filters implemented in Swift for iOS. If you want to learn more about writing shaders and making more complex filters, check out OpenGL Shading Language published by Pearson Education. Apple’s documentation is also has other kinds of shaders you can create outside of CI Color
https://www.bignerdranch.com/blog/creating-custom-filters-using-core-image-kernel-language/
CC-MAIN-2019-22
refinedweb
1,941
54.32
Select a language to translate this page! @Nathan, @ScubaDog2011 - OCR:- few days back on another WP blog post by Michael Stroh, I commented on OCR library missing for phone developers and that I am trying to develop an app which requires offline OCR capability. Unless you have low level C/C++ support, you can't have high performance OCR in WP. Bing Vision has implemented it. Bing translator is consuming it. But Microsoft doesn't provide offline OCR in WP SDK for third-party developers yet and no support otherwise in Silverlight. - ISharing on 1st generation WP devices:- internet sharing is blocked by AT&T on 1st generation AT&T unlocked devices which being used even outside the United States with other operators. I contacted Microsoft and HTC for my 7 Surround and they asked me to contact AT&T. Microsoft support implied; "even if the phone is factory unlocked and being used with other carrier, its branded with AT&T and AT&T has control to enable the features on phone." I further contacted AT&T support and they ensure me that in future all 1st gen WP devices will be pushed with an update to enable these features which were not there at the time of release and later came with Mango. Moreover, except one LG device, all WP devices have tethering enabled WLAN hardware. Unfortunately, no ETAs from AT&T on this one! - Wireless document printing:- Last year there was an app called Robocopy on windows phone. But since they never release the update for Mango, the application is forgotten and buried down the ground. If you dig into it, you will find they were providing some awesome features at that time. There must be other apps capable of pair and connect with printer wirelessly (bluetooth and wifi) without hopping through the PC. Would be great if documents in Office hub get this feature in next WP update. - Internet Explorer:- Well gltiches. - Pasting into dialer: pasting into native dialer is certainly required. Encouraging the developers is not the point at all. Microsoft DOES NOT let the third party to dial the number "within the app". You app can ONLY delegate the task to native phone dialer (read more on msdn about Microsoft.Phone.Task namespace). Also, the dialing task refrains the user to send the numbers with security code (with * and # etc). So third-party app can never give the first-class experience that native app can. Copy paste the number in phone dialer shouldn't be dropped in the next update of WP and letter to number translation, using the international phone dialer scheme (1-800-Microsoft = 1-800-642767638), would be an extra treat! @Nathan, allow me to address your wish list. 1. Support for multicore devices is coming with WP8. I get SO tired, though, of spec-whores. Specs mean nothing. Performance is king. Anyone chasing after specs clearly is NOT paying attention to the performance of the device. To this day, my original Focus OUTPERFORMS my wife's iPhone 4 in every way except the camera. It also outperforms every Android device I've been able to put it up against, and I expect my Lumia 900 will do even better. Multicores are essentially a waste if you really research it---better that they concentrate on leveraging the GPUs and continue to optimize the OS. 2. IE10 is coming with WP8. I hate all other browsers, by the way, on my desktop, so why would I pine for them on my smartphone? Yikes. 3. Wireless document printing. Haven't heard for certain, but since WP8 is closer to Windows 8, it's likely that this capability will be coming. 4. That's a repeat of 3. 5. Pasting into dialer. There are already apps that let you do that. Install one and pin it to your Start screen. People need to quit complaining about a function not being in a "native app". Acknowledge the great developers that exist out there and use there products. ENCOURAGE DEVELOPERS. 6. I can't speak to the C++ support, but I do know there are OCR scanner apps for WP7. 7. NFC, USB, HDMI, etc. Most of this appears to also be coming with WP8---remember, it will share more in common with your desktop than with your current phone. AT&T didn't "block" internet sharing. I have it with the Lumia 900. It's just not free. We can debate THAT issue elsewhere, but the fact is that it's available on most of the devices that have the physical capability. 8. Other OEMs. It's not Microsoft "forgetting" other OEMs. It's other OEMs thumbing their noses at Microsoft, plain and simple. And you can't blame stupid advertising that OEMs or carriers do on Microsoft. I can point you to far too many web or print ads by carriers/OEMs that are just plain wrong. Attack them. 9. Updates. Read my earlier post. The fact is that Microsoft never actually made a "promise". It was implied. And Microsoft was derelict in dispelling the assumption immediately. The fact is that carriers can decide to NOT update ANY devices. If they DO update a device whatever update they are deploying (and it doesn't have to be the latest) it MUST contain any updates between it and the previous one they deployed. It's ugly. It's stupid. But it's the facts. @tsrblke, yeah, I just saw that today. Speaking of quality control! Sheesh! People making purchasing decisions based on these things! Fair enough, @Rodney. Let me address each of your points. 1. Updates aren't any more or less fluid than they are for the other platforms, if we're honest about this. The BIG issue was, of course, that Microsoft finally came clean that they have absolutely NO control over whether OEMs and carriers EVER update devices. Really, this is also true of the other platforms BUT apparently Apple and, to a much lesser extent, Google, have successfully leveraged more INFLUENCE over OEMs/carriers to get theirs through at least more predictably. Android is STILL all over the flipping map, though. As for WP, carriers CAN choose to update zero devices if they wish--but if they DO deploy an update it must be accumulative of any updates that were released between the previous time they deployed an update and the latest one they choose to deploy. Example: AT&T has not deployed the two interim patches since Mango, but they apparently will be deploying the 7.5 Refresh, which WILL include those two interim patches. 2. Hardware. I don't believe this is a Microsoft issue at all, frankly. I believe this is 100% an OEM issue. My Samsung Focus works just fine with 40GB of memory. In fact, the ONLY issue ANY Focus owner has had with the additional memory was because of the card itself, not the capability of the OS. And, if memory servers, the Fujitsu device has 32GB built in. As for the cloud, I think this is much less an issue with the OS than it is the SkyDrive itself. Microsoft has made terrific improvements in it, but Apple has so far eaten their lunch in the seamless aspect. The problem with cloud use right now is the same for ALL ecosystems: availability of cheap, high-speed wireless. I live in an area where 3G is very limited and LTE is still in the planning stages. Until users can access LTE EVERYWHERE the cloud will only be truly viable for metropolitan areas. 3. Skype. I agree with your issue, but think it would be a mistake to leave it out. It's a mistake, though, for it NOT to be integrated in WP8. Tango (the app) actually works better and it saw every one of my contacts who had Tango installed automatically---I didn't have to add people like I do with Skype. 4. Quality control. For the most part, I agree. But part of the issue is the hype that goes on. The Lumia 900 camera was oversold. Even so, the camera is actually better than the default settings lead you to believe. The problem is that MOST users are much too lazy to actually LEARN about photography and expect the default settings to be the most excellent experience. I'm betting every real photographer just rolls his/her eyes hearing that, too. Personally, I've been able to educate myself on the topic of settings and get some much better photos from the Lumia. The camera STILL could have been (should have been) a bit better, though. The iPhone IS the bar, after all. 5. Marketing. This has always been the most dismal aspect of Microsoft, worst of all with Windows Phone---and it is just as weak with Windows 8 and Windows Phone 8. Nokia, for all its other challenges, was the best thing to happen to Microsoft in WP7 marketing. It's tough to come from a huge deficit, awareness-wise, to improve it as much as they have, acknowledging that a lot more needs to be done, though. @ Everyone, & Nathan Above are pretty much the things that WP users have been saying since the release of Mango. We loved the feature set that Mango brought us, and it's been great having devices that can at least compete, on a basic level, with A&A. Nathan, you said it! I think you just summed up the lessons learned in 2012, and you just reinforce pretty much what everybody supporting WP has been saying all year long. I agree with you. We all know that sooner, or later, MS will unveil plans for future updates, and features. As we get closer to finding out what has been engineered we hope that we can get a few final words in before it's to late. We know that development takes time, and that the WP team is not going back to the drawing board, at this stage, because of anything we post. I guess this is just one last plea for features, and procedures, before work on upcoming updates is complete. If "WP8" addresses all of this stuff then great. But, if the majority of these request aren't fulfilled then you guys can pretty much see the tone of the Blog for 2013. The issue I'm beginning to have, or what's worrying me is that these things being asked for are either old, standard, features now, or are practices that should be already followed. Their seriously is no room, at this point, to miss a single thing here in the next version. I hope that "WP8" takes us from playing catch up to Innovating once again. WP needs to not only come in line with the others, but it's time WP really crossed the line in terms of functionality, procedure, and marketing. "Metro's to the Maxx, so we got what takes"......... Cheerleaders! Agree with almost everything what Rodney said. There is this news about Ex-Microsoftie, head of entertainment division who claimed that Microsoft shouldn't developed the Zune software to merely compete Apple. I second his opinion that Microsoft shouldn't follow the Apple's trend. Microsoft has its own trends and capabilities which they should endorse rather undermine them and do whatever the Apple is doing *blindly* Wish-list: 1: support for Multicores and enhanced memory 64-128gigs. Dont wait for iOS or Andriod. 2: support NDK so the real browsers like FF can kick in! IE9 is good but can't render the RIA properly (esp with javascript popups) while retaining the look and feel with its desktop counterpart. Release IE10 for wp as soon as you can. Implement roam-able favorites via IE10 mobile, desktop, metro and Bing bar (to sync with other browsers) using SkyDrive (waste of space). Bring "Find on page" back 3: Document printing over wireless - Wifi and bluetooth. 4: support printing over wifi and bluetooth. Make a decent app to view and edit XPS and PDF documents and print them wirelessly. Dont *silently murder* XPS! many printers out there have support for XPS. No development for XPS after 2009... 90% of the times MS murder its products (Zune, WMA, much more and now XPS too!) 5: copy past in dialer. iOS was the first smartphone platform of world which didnt had the feature to paste the phone number in phone dialer. Microsoft second it in WP... rather 100% dettp copy! iOS doesnt have the support for Wireless printing over Bluetooth and Wifi, windows phone second it again. 6: C/C++ support for developers. I need OCR in windows phone and i cant use cpp library neither can i use bing vision. 7: Support for FM-modulator, NFC, USB-drive support, HDMI in/out.. to make the gadget *modren* and to the OS ready for all kinds of gadget hardware. Let the nokia and other manufacturers decide which hardware is present in low-price or high-end devices. But DO NOT let the carriers to mess with basic support. AT&T blocked mango features like Internet Sharing and USSD even if you have unlocked device and using with other network. Quality Control? 8: Dont forget other OEMs in favor of Nokia! For example, go to and see how much information they are offering for andriod compared to wp. if you scroll down the wp page its say: <quote>Mango Is Coming! Learn about the upcoming version of Windows Phone, otherwise known as Windows Phone 7.1 “Mango”. <unquote> Still coming huh! So dont murder the relationship with other OEMs. 'Keep them in loop' 9: Dont delay the updates. Killing the promise (1 minor and 1 major update for WP per year) would kill the whole ecosystem. and finally Dont wait for Apple to release a feature first and see how it plays. Trust YOUR abilities and release whatever it takes to make wp robust, top of the line and feature-full like windows and xbox OSes. Give people reason to buy windows phone who already own iphone or andriod or who have choice to buy one of three OS device. My dual core slick n slim andriod with extra peripherals has the same battery life as my single core – less memory – lesser hardware – wp. Then why choose WP? because of Metro? or Xbox Live (which without real-time multiplayer has no real advantage over ios and andriod games)? or because some guy hoping and plaguing the other guy that Microsoft shall make it better and explaning MS is better than Apple and Google!! << if that is true atleast act like that! PS fire your marketing heads and decision makers (along with steve balmer and steven sinofsky) who are stalling the great features to go public and sailing ms to the hell door -- [f-word]'ing waste of talent! PPS I hope anyone from MS still remember that they have an orphaned uservoice channel for wp suggested features. Not a single reply from MS employees anywhere on uservoice in months. @ Tsrblke Uh ohhhh! I spoke to soon... Lets hurry and change the subject! Did you guys here? Photosynth for WP just hit the marketplace! Next post please.. Lol @Scuba Sadly the 32gig Lumia turned out to be a typo! Please vote for the utorrent app on windows phone: utorrentideas.uservoice.com/.../2357784-add-support-for-windows-phone-7-5-mango- Also for the textfreeapp: pinger.zendesk.com/.../20320071-please-create-a-textfree-windows-phone-app No Buckeye! You have to realize your faults before you can improve. Today is a glorious day for WP! The war is what our focus is on, not the battle. @Rodney --Thanks for the pep talk. I have no probably bing a qaulity role player on the WP Team. As for Verizon, I have HTC Surround on ATT and have had two other phones (Samsung/Windows Mobile and Motorola flip phone) before then. I'm not sure if it is a regionally thing or just where my travels take me but I haven't had half the problems other ATT users have had with converage. I've always wondered if it just not the iPhone versus the network. @James M -- I've been content with the ATT store by me. Even at the beginning, their sales guys were carrying HTC Surrounds... they actually convniced to go with the Surround instead of the Focus back in the day. Guy walked my wife throught the basics of the Lumina like a decent pro. @MSFT -- One more happy WP user (should say two? since I do all my wife's tech support); My wife is quickly learning how to pin tiles, download apps, set up her own gmail accounts... All stuff I had to do for her back in her Droid days or it just never got done with Droid. And she already noted how much better the voice to text is... @ Rodney - Are you on something boy? LOL! @ Scuba, and Whoever Loves WP! Let's face it guys, this year was better than last, but the season is over. We lost, and we're not going to the playoffs! The things that held the team back: 1. Updates: What updates? Why have we not been getting incremental updates to add functionality thought the year? And, why are the updates that are being released being block? This is not going to cut it! Try harder next season! 2. Hardware: Not enough memory for 2012 usage, and WP software isn't advanced enough (yet) to take full advantage of cloud storage,,, mainly because we rarely get updates that add new features! Try harder next season guys! 3. Shooting holes in our own foot: Skype? If it doesn't work just leave it out! It's beter to staye quiet cand lok smart Thhan to open yYour mout and Look knot smart as, well,, See my point?.. Next season? Please don't intentionally piss of the players by not giving them enough training,, just to turn around and well train the rookies! Catch my drift? Maybe next year guys. 4. Quality Control: I don't know? IMO it seems like the 900 is "hindered". The camera talks the talk, but walk the walk? Software issues? Some guys have been complaining about battery issues, and the reception issue! Why? This device should have been perfect, even if it had to be released a few months latter. But, good job on the update, which just shows how much att cares about the thousands of other WP devices they sell. Next season try harder! 5. Marketing: "You are our weakest link, so you better get your s&#t together or you're of the team! Permanently! Actually, the best thing to happen to WP this year was the much better than last year, but still not anywhere near being "right", mom and pop shop budget marketing. Maybe the franchise spent millions, but was it in the right place? Try again! Like Miyagi says to the karate kid.. Again-Again-Again-Again... That's because practice makes perfect! Now,, we can do it, we just need more practice. The best advice I can give to the team is to listen to each other, and play by the rules. We can't change the game until we learn to play it first. But, we need to learn fast because next season will be here before you know it. All us "players" can do is sit back and see how the coaches revised the playbook (WP8)..... Positive feedback or tough love,, whatever works! But, we got to pull our heads out of our asses, and face the facts that we're just not good enough yet. But, I wont stand for loosing! I'm no looser, and it just isn't going to happen on my watch!... Hit The Showers! The 710 is, yes. I work with someone who has the 710 and, aside from having no front camera, everything else works fine. The 610 was the first of the "third-world devices". Now, on the OTHER end of the spectrum, what the heck is the deal with Germany getting a 32GB version of the Lumia 900!!!!?????? I am SO PO'd right now, I can't stand it. I maxed out my Lumia 900 day one and it angers me that Nokia suddenly listened to customers and produced a version that wasn't anemic in the memory department. Ugh!!!!!! but, aren't those devices capable of running these apps already? @ Micheal H, Scuba.. I guess the best advice, or hope, I can give anyone who is disappointed with the limitations of 256/800mhz devices is that supposedly in future updates more functionality will be added making apps like Skype usable. But, I'm not sure if this is even factual yet. So, when buying a device just know what you're getting into... Question for Micheal H.. Was the 710 available in your area, and what was the price difference?? If any.. :-» Ditto. I'm assuming he was complaining that a number of games & apps won't run on the Lumia 610. What seems a mystery to me is that ANYONE thought every single app would be able to run on a low-end device. And, did I misread his post, or was he calling the Lumia 610 a "hero phone"? Um, if any Windows Phone devices could be called "hero phones" it would be the Titan II, the Focus S and the Lumia 900. @ Micheal H. Are you using a Lumia 610? What exactly is frustrating you? Are some games not working for you? And last, What????? why do keep reject my game zombies night out for nokia lumia 610 is becourse you can not get your own game to run on a 800mhz processor with realtime light and shadows 35 fully rigid and animated monsters and zombies , and it is all first person shooter why are you so unfair,, ermit i am better than you 200 million developers download if you have a apphub account and put it on your nokia 610 and wacth a full blown 3D FPS,, the most impressive game on windows nokia lumia 610 and remember you will never run as good as i do on a small phone ,, and a processor 800mhz in managed code,, link to the game that we are missing on the NEW HERO WINDOWS PHONE NOKIA LUMIA 610 800MHZ PROCESSOR 256MB OF RAM wmpoweruser.com/a-list-of-apps-which-will-not-install-on-the-nokia-lumia-610 You got smoked there ,, it that why you keep rejecting the game ,, it is becourse it delever some feuturs that no xbox live can do it is becourse better action gameplay, or better quality , better graphics and running so smoot , that even some of your 2d games can not follow this can you please answhere this from my reject report What part do you find offencive ,, the text is this part " the hobbyist game makers proudly present special agent solo operation global take ove easter egg " well you are dam right it is a global takeover ,, you can not even get your own games to run with all those inhouse made games ,, pehaps you shood have let the real developers made these games , instend those ninja developers you have inside microsoft Michael @KR I'd be all on board with you on that, EXCEPT, tango is really meant for "emerging" (read: Third world) markets by many/all accounts. I can't pretend to understand the market differences between here (first world) where my microwave likely has more than 256mb of ram (joking! I think, I hope!) and cars have complex computer systems built into the dash that make my first computer look like a cheap toy and the third world markets where ever dollar counts. Heck even my pithy comparison is likely more wrong that it is right. I have to think that MS weighed everything is is much more familiar with the on the ground realities of those markets. @Bill and James All I can say is "heh." Seriously, "Heh" is all I got. I'll repeat the story at least some of you have read from me. When my wife went to AT&T with a Focus S in hand (Thanks Windows Phone Night out crew!) and asked to swap the SIM from the iPhone to the WP7 (they use different SIMs, plus we needed 3G+ or whatever turned on) the sales guy told her "Don't do that, you'll hate it." I politely told him I didn't ask his advice, just his service. And pulled out my Mango updated Focus (Gen 1) and said "Why wouldn't you like this, flipping tiles, fancy animations." He was floored, didn't even know it did most of that. Why? Because and I quote he "had one [a Focus AT&T gave him], but it just sat in his car off" he likely never even upgraded it to Mango. FWIW, in other interactions with AT&T I complained about his rank stupidity (and quite frankly rudeness) that it wasn't fitting of a "Premiere Parnter" to Windows Phone. Unrelatedly, (I'm sure) they've gotten better. When we went to get the Focus S case fixed/returned that customer service guy say "Have you seen the Lumias?" and pulled one right out of his pocket and said "I love this thing." So there is hope. @ James... I guess that was you... Remember? "The only way to get a dual core WP is to glue two together" lol. That was hilarious! @Bill94 Yeah I got that from Verizon too! I went in to buy my friend a small 100 dollar entry droid phone. I was looking at the Trophy and the sales rep said "I wouldn't suggest that phone, it is a small niche and probably won't make it, I suggest getting an android phone." I took out my Samsung Focus I had at the time and showed him that I had one, and was interested in the ecosystem/OS. His response? "Oh, I'm sorry to see that." I was very angry. My reaction was close to this: Really? Excuse you? Insulting the customer? How professional. Please, tell me more about how a terrible business man such as yourself knows about android. I was very frustrated and went back to AT&T instead of switching to Verizon. @Rodney E. Jones I am known for jokes now? @ bill94.... Good! Glad you guys didn't listen to that B$ from Verizon. But, if you're still with Verizon you might want to wait and see what they have to offer... You will be able to two up your wife because for one your WP8 device will be marginally better, and second, with Verizon you will probably get your updates. Lol! I am officially having phone envy. My wife traded her Verizon/Droid 2 for a black ATT/Lumina 900. She had been drooling over my Surround for a year now. Two things learned from the process... 1. Verizon store arrogant and quite rude when I asked to see a HTC Trophy.. I knew my wife wanted a WP for Mother's Day. Commet was "Why do you want that?" My initial response was to pull out my Surround and say "She likes my phone." Pushed Droid, "Well our network is better." and then ignore me. 2. Lumina 900 seems to be rocking here in Boston... My wife's co-worker picked up the Cyan a few weeks ago. The salesperson told my wife and me that he alone sells about 60 - 75 phones on a very good week... He is averaging 30 - 35 of those 60 sales as lumina phones since the release. End of story, my wife ends up with new Pandora braclet and WP... I just have to wait for WP8 and the rumor Nokia Pureview to one up her later. @KR - EXACTLY!! When the Lumia 610 was announced, its price didn't seem to me, to be SIGNIFICANTLY lower than the already affordable 710. And I had an HTC Hero Android phone, talk about a mobile device that makes you hate a whole ecosystem... @Djmike Totally agree with you.if the Lumia 710 sells for $250 off contact and still has the 512 and 1.4GHz processor I really think we just don't have to flood the market because it wouldn't create legacy and standards.HTC learned that with Android. I still just get angry when I read about these 256MB devices... There is NO WAY anyone can convince me that in 2012, the price difference between 256MB and 512MB of RAM is enough to justify gimping a whole series of devices just so they can sell for, what - $50 less than the 512MB variety?? I call full-on Shenanigans on this. It is NOT worth the fragmentation and subsequent confusion to the public. It completely unravels the ecosystem and "same experience" that WP has been building for the last two years. And like I pointed out the last time I went on this rant, if the Lumia 900 can come out with a launch price of $99 on contract (and immediately, half of that through 3rd parties) there are plenty of OTHER specs that can be dumbed down to drop the price, without taking a machete to the list of supported apps. I hate these pathetic devices, and refuse to call them "entry level" or "developing" phones, they're just plain wrong, in every way. There are just certain high performance apps that wouldn't work on those devices especially games.its like trying to play FIFA12 on a Pentium 2,it just can't handle it. @KR @Rodney, I suspect that's right. People report that Skype was working fine on the 256 phones before they pulled it (and WP central sideloaded it and still isn't having problems.) I wonder if this was just over cautiousness. Also remember that the 256 phones aren't really ready until Tango IIRC, and just like our apps needed to be updated to Mango, I'd imagine apps will need to be updated to full tango complience, after which they'll work fine. @ KR I think I read somewhere that this is a temporary limitation. Future updates my bring more functionality to 256 devices. Hopefully! So apparently it's not just Skype that can't work on 256MB devices,angry birds,PES and Tango wouldn't work on them.i wonder where we are heading to.not all apps can be coded to work on such low memory its just like trying to install windows 7 on a 256MB PC or Pentium 2.and these apps are big ones JAT,, If the next Xbox has serious Skype integration could this make it popular with the enterprise?? Microsoft seems to have the most complete ecosystem, and if it's even more tight within itself I don't really see Apple being as popular for very long. I can't wait to see how this pans out. @Rodney My suggestions come from my foucs group of 1, my wife. The semi-target market of "frustrated iphone user who wants something different." Oh BTW, while we were returning the focus S case to AT&T, the lady next to us was buying a Lumia (900 it looked like). In any case she seemed excited. The guy helping us showed us his Lumia since I was interested in them (such a purrrrrtttttyyyy phone, but I'm holding out for WP8 announcements.) In any case, the guy helping Lumia lady couldn't get the contacts to transfer properly from her feature phone to the lumia (it's not that hard, but I'm convinced that AT&T people just don't know what they're doing 50% of the time, yes it's a lot of phones to handle, but it sounded like he failed to check and make sure everything was copied to the SIM from the feature phone before running the transfer.) In any case, AT&T's standard response to this stuff (this is going somewhere I promise!) is to just dump everything again doubling most of your contacts (how do I know this? They did this to my wife with her iPhone. Honestly I forgot how we got the iPhone contacts to the WP8, I think we exported them to outlook then to Gmail, and she used Gmail contacts...anyway back on story.) Obviously this is stupid, and AT&T guy knew as such so he produced a slightly less stupid idea of manually entering the missing contacts. I say "obviously this is stupid" which actually isn't true. In this case it might have been easier to do the double dump, and point out the customer the robust Address managment at live.com (or hotmail.com for us oldies.) which IIRC includes a "duplicate finder/merger/deleter" app. I thought about interjecting, but I was up to my eyeballs in something else (and didn't want to confuse the poor guy.) TL;DR, make sure your sales people know the web side of things so they can suggest that stuff to the users in strange cases (like complex address book managment) @Rodney - LOL! No new sightings this week, my job had me over in Spokane, where I was pretty much working odd hours and not hanging with the public at all... But next week I'm back to my normal routine, so I'll let you know as soon as I see some more WP in Action! @ Micheal... Thanks! @ T Win. .... Keep representing! @ DJ Mike.. Did you see any this week?? @ Skuba..... How's the lessons going? Can you get underwater pictures? @ Kenny..... Change it back! @ James M. No jokes this week? @ Tsrblke.... keep up the great suggestions! @ Buckeye.. Or was it you that made me laugh last week?lol @ KC "Lemon" Your boy "Mazhar Mohommed" That guy is the other talkative one. Love me some Mazhar! Lol... @ Ben PC guy.. Quit bragging already! Lol @ at&t......... I'm not speaking, DROP! F%$K, WAIT, DROP, DAMNIT! WAIT,, Ok as I was saying, DROP! S%&T!... UHHH!, Ok, I'm not speeking to you right now, because you make it to damn difficult! Lol.... @ Nokia...... Unlike some partners, above, you are doing a tremendous job. If you guys pay me out of my contract I promise I will go Lumia for life! No joke! And, everyone else,,, Support the troops, and have a great Memorial Day!! ;O) @Michael Thanks for the post –and Major cool points for posting the Flo-Rida video debuting the White Lumia 900. The Windows Phone was not the only eye candy in this video, but it did capture some awesome photos during the video shoot. The Carl Zeiss 8 megapixel performed flawlessly during the video – to note this is the 3rd music video I’ve seen the Windows Phone in, so great job to the Windows Phone marketing team on this. We hope to see more exposure like this in the future with films and various media spots to come, thanks again Michael. - Stay Powered by Windows
http://blogs.windows.com/windows_phone/b/windowsphone/archive/2012/05/25/the-wrap-flying-games-photo-tips-and-flo-rida.aspx
CC-MAIN-2013-48
refinedweb
5,891
73.07
Introduction:-. WCF client makes a request to WCF service object.. WCF service object is instantiated.. WCF service instance serves the request and sends the response to the WCF client.Following is the pictorial representation of how WCF request and response work. Following are different ways by which you would like to create WCF instances:-. You would like to create new WCF service instance on every WCF client method call.. Only one WCF service instance should be created for every WCF client session.. Only one global WCF service instance should be created for all WCF clients.To meet the above scenarios WCF has provided 3 ways by which you can control WCF service instances:-. Per Call. Per session. Single instance.. WCF service serves the request and sends response and the WCF instance is destroyed and given to garbage collector for clean up.. 'InstanceContextMode' value in the 'ServiceBehavior' attribute as shown below. This attribute we need to specify on the 'Service' class. In the below code snippet we have specified 'intCounter' as a class level variable as shown below and the class counter is incremented by one when method 'Increment' is called. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Percall)] public class Service : IService { private int intCounter; public int Increment() { intCounter++ return intCounter; } } At the client we have consumed the WCF client and we have called 'Increment' method twice. ServiceReference1.ServiceClient obj = new ServiceReference1.ServiceClient(); MessageBox.Show(obj.Increment().ToString()); MessageBox.Show(obj.Increment().ToString()); Even though we have called the 'Increment' method twice we get value '1'... Client creates the proxy of WCF service and makes method calls.. One WCF service instance is created which serves the method response.. Client makes one more method call in the same session.. The same WCF service instance serves the method call.. When client finishes his activity the WCF instance is destroyed and served to garbage collector for clean up. To configure service as per session we need to configure 'ServiceBehavior' attribute with 'PerSession' value in the 'InstanceContextMode' object. [ServiceBehavior(InstanceContextMode = InstanceContextMode.PerSession)] public class Service : IService { private int intCounter; public int Increment() { intCounter++ return intCounter; }} At the client side when we run the below client code. You should see the value as '2' 'Single' instance mode. Below is a simple pictorial notation of how single instance mode will operate:-. WCF client 1 requests a method call on WCF service.. WCF service instance is created and the request is served. WCF service instance is not destroyed the service instance is persisted to server other requests.. Now let's say some other WCF client i.e. client 2 requests a method call.. 'InstanceContextMode' as 'Single'. [ServiceBehavior(InstanceContextMode = InstanceContextMode.Single)] public class Service : IService { } If you call the WCF from different client you will see the counter keep incrementing. The counter has become a global variable. . You want a stateless services. Your service hold intensive resources like connection object and huge memory objects.. Scalability is a prime requirement. You would like to have scale out architecture.. Your WCF functions are called in a single threaded model. . You want to maintain states between WCF calls.. You want ok with a Scale up architecture.. Light resource references . You want share global data through your WCF service.. Scalability is not a concern. MSDN link for WCF instances Do not miss this post which covers end to end about WCF sessions Great blog by Rick rain on WCF instancing You can download source code for this tutorial from bottom of article. Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/kb/2071-3-ways-to-do-wcf-instance-management-per.aspx
CC-MAIN-2018-30
refinedweb
591
58.58
Interested in learning React Native? Let’s build your first React Native app, a simple mobile app displaying a list of countries, fetched from a REST API with a network request. This React Native tutorial is aimed at introducing React Native, giving you the basis of what you need to know before building a real React Native application. After that, we proceed to helping you build your first real React Native app. By the end of this article you will build a React Native app that can run on both iOS and Android devices. React Native is a cross platform development library built on top of React by Facebook, for mobile development platforms. React Native was developed in 2013 as a hackthon project inside Facebook and was later released for public use in 2015. It gained huge popularity in the developer community and multiple tech companies adopted it as a mobile development solution because React Native apps share a single codebase for both iOS and Android and could hardly be distinguished from truly native apps. According to the React Native website: In 2018, React Native had the 2nd highest number of contributors for any repository in GitHub. Today, React Native is supported by contributions from individuals and companies around the world including Expo, and Microsoft. Before we go ahead and build our first React Native app, I’m going to show you the pros and cons of React Native and and more details on what it actually is. What is React Native? - React Native is a hybrid mobile development library. - React Native apps are written in JSX and Javascript and compiled into native code. - React Native apps contain 85-90% shared Javascript and JSX code What is React Native not? - React Native is not a webview - React Native is not React - React Native is not PWA - React Native as of this writing supports web development using React Native for Web Why should you adopt/learn React Native? - Targets multiple platforms (iOS, Android, Web, TVOS) with the same codebase and effort - Has a large and growing community that is there to provide adequate support - Has native support meaning that you can customize the native code to suit your use-case/business logic - Requires knowledge of Javascript. Javascript is a language in high popular demand and learning it will pay off immensely - Has a feature which I personally refer to as the sweet spot: Fast Refresh (Hot Reloading) React Native Drawbacks? React Native has some drawbacks too, but the developers of the library are consistently trying to improve them as the community grows: - While the codebase is mostly shared among various platform, knowledge of native development is sometimes required in developing more advanced React Native projects - Despite the fact that most React Native apps look the same in appearance to native apps React Native seems to lack the smooth navigation achieved by native apps. - React Native developers agree that React Native style of error reporting is not the best out there but they cope with it over time. Build Your First React Native App Let’s build a React Native app to display a simple list of countries. The app will contain only one screen, and we are going to keep its functionality and styling to a minimum, since the purpose of this tutorial is to help you set up your React Native developer environment and dip your toes into the React Native programming language. In this React Native tutorial we are going to use Expo in order to build your first React Native application. Expo is a powerful tool for those how are beginners in the React Native world, since it lets you run and preview React Native apps on your devices easily. 1. Install Expo Follow the official documentation on how to install Expo. Once you’ve installed it, come back to this tutorial and follow the next steps in order to build your first React Native app. 2. Create a New React Native App expo init firstapp Select the ‘blank‘ project Select ‘Y‘ to work with yarn. Yarn v1.19.2 found. Use Yarn to install dependencies? (Y/n) Once you click Yes, Expo will work its magic and create all the necessary files for you. You can take a look at the directory structure to get an idea of what is going on in the project. 3. Run Your First React Native App Run the following commands to start your newly created React Native app: cd firstapp yarn start At this point, if you set up Expo properly at the previous steps, the new React Native project should have loaded successfully and you should be able to see the app as in the following screenshot: There you have it, the very first React Native application that you’ve build. By default it says ‘Open up App.js to start working on your app‘ and I agree that it’s not the best welcome message Expo could offer but we’re going to go ahead and do as they say. Let’s open App.js file, which looks like this:', }, }); Now let me give a concise summary of what’s going on before we move on. - The styles variable contains various style dicts of the components - The function App is a React Native Functional Component, the default one that renders what we currently see on our screen and above are import statements that import components to be used and composed to create our parent component App. 4. Add List of Countries Let’s move on and rewrite this dummy screen with our own UI. As we mentioned before, we are going to display a list of countries. For this, we need to implement the following: import React from 'react'; import { StyleSheet, Text, FlatList } from 'react-native'; export default function App() { const countriesData = [{"name":"Afghanistan"},{"name":"Åland Islands"},{"name":"Albania"},{"name":"Algeria"}] return ( <FlatList data={countriesData} contentContainerStyle={styles.container} keyExtractor={item => item.name} renderItem={({item})=> <Text style={styles.text}>{item.name}</Text>} /> ); } const styles = StyleSheet.create({ container: { paddingTop: 30, }, text: { fontSize: 20, margin: 10 }, }); As you can see, we have updated our App.js and added a few things: - A Flatlist to display the list of countries - A dummy dataset to display to be displayed on the list - We updated the style object to contain the style for our text Run your app if you haven’t started it already, and you should be seeing this: List of countries displayed with dummy data We now have something to work with. But the data is static and we would like a longer dynamic list, that can change and we need those changes to be reflected in the UI. So we need the UI to be “reactive” to the changes in the data model. This is the core concept of React, and therefore React Native. So we need to introduce the State concept. A React Native component holds data in its state, and whenever the state changes, the UI is re-rendered to reflect those changes. Let’s add a state variable, named countriesData which will store the dynamic list of countries displayed on the screen. const [countriesData, setCountriesData] = useState([]) The useState is called a “hook” in React Native. According to official React documentation on hooks A Hook is a special function that lets you “hook into” React features We just declared a state for our app countriesData with default value as an empty array [] and a function setCountriesData to update the value of countriesData. For example, calling setCountriesData([1,2,3,]) will update the value of countriesData to [1,2,3,]. Another important hook useEffect is going to be applied in the following code snippet. Simply put, any code written inside the useEffect runs when the component is mounted. import React, {useState, useEffect} from 'react'; import { StyleSheet, Text, FlatList } from 'react-native'; export default function App() { const [countriesData, setCountriesData] = useState([]) function fetchCountriesData() { fetch('') .then((response) => response.json()) .then((json) => setCountriesData(json)) .catch((error) => console.error(error)) } useEffect(()=> { fetchCountriesData(); }) return ( <FlatList data={countriesData} contentContainerStyle={styles.container} keyExtractor={item => item.name} renderItem={({item})=> <Text style={styles.text}>{item.name}</Text>} /> ); } const styles = StyleSheet.create({ container: { paddingTop: 30, }, text: { fontSize: 20, margin: 10 }, }); Please don’t be scared of what’s going on. We are using the fetch API to retrieve countries data from an API endpoint and display a list of African countries. The fetch API is how you make network requests in React Native. As you can notice, we’ve used a free API endpoint, exposed on the restcountries.eu website. This returns a JSON object, parsed in the then() clause of the fetch method. Once parsed successfully, we update the countriesData state variable with the new list of country, newly retrieved. As a result of updating the state object, the UI also gets re-rendered and we can see the countries on the screen: List of countries wih live data 5. Styling Your First React Native App Let’s now focus on making the design of the app slightly better, since we already have the core functionality in place. We are going to focus on styling the app and our focus is on the styles dictionary. import React, {useState, useEffect} from 'react'; import { StyleSheet, Text, FlatList, Pressable, Alert } from 'react-native'; import { StatusBar } from 'expo-status-bar'; export default function App() { const [countriesData, setCountriesData] = useState([]) function fetchCountriesData() { fetch(';capital') .then((response) => response.json()) .then((json) => setCountriesData(json)) .catch((error) => console.error(error)) } useEffect(()=> { fetchCountriesData(); }) return ( <> <StatusBar style='light'/> <FlatList data={countriesData} contentContainerStyle={styles.container} keyExtractor={item => item.name} renderItem={({item})=> <Text onPress={() => {Alert.alert(`The Capital of ${item.name} is ${item.capital}`)}} style={styles.text}>{item.name}</Text>} /> </> ); } const styles = StyleSheet.create({ container: { paddingTop: 30, backgroundColor: '#483D8B' }, text: { fontSize: 18, margin: 5, color: '#fff' }, }); As you can see, we’ve changed the color of the background to purple, by providing the backgroundColor attribute with ‘#483D8B’ hex code. While the syntax is very similar to CSS, it is slightly different. But the core concepts are the same, so if you already know CSS, learning how to style React Native apps will be extremely easy. Especially if you are already familiar with flexbox layout. Conclusion We saw what are the biggest sell points for using React Native in your mobile development process, and how easy it is to create apps for both iOS and Android. We’ve set up Expo, which is an amazing tool for beginners who are new to the React Native world. We then leveraged Expo to create our first React Native project. After that, we learned about functional components, hooks and state. We’ve used the fetch API to retrieve data via a network request, and we styled the visual components by modifying the stylesheet. Congratulations! You were able to build a React Native app. Now it’s time to learn more advanced concepts, in order to add more complex functionalities and develop fully functional mobile apps, that you can publish to the App Store and Google Play Store. Check out this list of the best React Native resources to learn more about React Native and dive into the next level. Next Steps Now that you have learned about best React Native development tools, | Podcasts | Newsletters | App templates If you need a base to start your next React Native app, you can save months of development by leveraging one of our React Native templates.
https://www.instamobile.io/react-native-tutorials/build-react-native-app/
CC-MAIN-2021-10
refinedweb
1,905
50.97
. If customization is needed, the usage follows the example: my $obj = My::Class->new( @new_args ); $obj->doit(); However, most of the time, your users will not be interested in the neat OO design underneath and some default object will be good enough. So a nice interface would be to use give_my_self was called. The default object is always the same (that is, a singleton). The default object is not saved into a package variable or something like that. (Actually it resides in closures that make it accessible only to the code which needs it.) So it can't pollute your namespace and hopefully will keep us out of trouble with hard-to-track bugs. give_my_self was called). The first argument is shifted from the argument list. In scalar context, it returns the computed invocant. In list context, it returns the computed invocant and the the rest of the argument list. The usage forms above are just handy ways to make current @_.
http://search.cpan.org/~ferreira/Class-Lego-0.004/lib/Class/Lego/Myself.pod
CC-MAIN-2015-06
refinedweb
162
65.52
Q.2) In ASP.NET in form page the object which contains the user name is ______ ? A. Page.User.Identity (your answer) B. Page.User.IsInRole C. Page.User.Name D. None of the Above Q.3) Find the term: The .NET framework which provides automatic memory management using a technique called ______________ ? A. B. C. D. Serialization Garbage Collection (your answer) Assemblies Overriding Q.4) Which of the following denote ways to manage state in an ASP.Net Application? A. Session objects B. Application objects C. ViewState (your answer) D. All the Above (correct answer) Q.5) What is the base class from which all Web forms inherit? A. B. C. D. Master Page Page Class (your answer) Session Class None of the Above Q.6) WSDL stands for _________________ ? A. Web Server Description Language B. Web Server Descriptor Language C. Web Services Description Language (your answer) D. Web Services Descriptor Language Q.7) Which of the following must be done in order to connect data from some data resource to Repeater control? A. B. C. D. Set the DataSource property Call the DataBind method Both A) and B) (your answer) None of the Above Page 2 of 6 Q.8) Which of the following is FALSE? A. ASP.NET applications run without a Web Server B. ASP+ and ASP.NET refer to the same thing C. ASP.NET is a major upgrade over ASP D. None of the Above (your answer) Q.9) Which of the following transfer execution directly to another page? A. B. C. D. Server.Transfer (your answer) Response.Redirect Both A) and B) None of the Above Q.10) If one has two different web form controls in a application and if one wanted to know whether the values in the above two different web form control match what control must be used? A. DataList B. GridView C. CompareValidator (your answer) D. Listview Q.11) Which of the following is used to send email message from my ASP.NET page? A. B. C. D. System.Web.Mail.MailMessage System.Web.Mail.SmtpMail Both A) and B) (your answer) None of the Above Q.12) In my .NET Framework I have threads. Which of the following denote the possible priority level for the threads? A. Normal (your answer) B. AboveNormal C. Highest D. All the Above (correct answer) Q.13) In .NET the operation of reading metadata and using its contents is known as ______? A. B. C. D. Reflection (your answer) Enumeration Binding Serialization Q.14) In ASP.NET the < authorization > section contain which of the following elements? A. < deny > B. < allow > C. Both A) and B) (your answer) D. None of the Above Page 3 of 6 Q.15) The type of code found in Code-Behind class is ________ ? A. B. C. D. Server-side code (your answer) Client-side code Both A) and B) None of the above Q.16) Common type system is built into which of the following: A. CLR (your answer) B. RCT C. RCW D. GAC Q.17) The actual work process of ASP.NET is taken care by _____________? A. B. C. D. Q.18) Which of the following allow writing formatted output? A. Response.Write() B. Response.Output.Write() (your answer) C. Both A) and B) D. None of the Above Q.19) Which of the following denote the property in every validation control? A. B. C. D. ControlToValidate property Text property Both A) and B) (your answer) None of the Above Q.20) How many classes can a single .NET DLL contain? A. One B. Two C. None D. Many (your answer) Q.21) Suppose one wants to modify a SOAP message in a SOAP extension then how this can be achieved. Choose the correct option from below: A. B. C. D. One must override the method ReceiveMessage (correct answer) One must override the method InitializeMethod Both A) and B) One must override the method ProcessMessage (your answer) Page 4 of 6 Q.22) Which of the following can be used to add alternating color scheme in a Repeater control? A. AlternatingItemTemplate (your answer) B. DataSource C. ColorValidator D. None of the Above Q.23) Suppose a .NET programmer wants to convert an object into a stream of bytes then the process is called ______________ ? A. B. C. D. Serialization (your answer) Threading RCW AppDomain Q.24) The technique that allow code to make function calls to .NET applications on other processes and on other machines is A. .NET Threading (correct answer) B. .NET Remoting (your answer) C. .NET RMT D. None of the above Q.25) The namespace within the Microsoft .NET framework which provides the functionality to implement transaction processing is .................... A. B. C. D. System.EnterpriseServices (your answer) System.Security System.Diagnostics System.Data Q.26) Which of the following method is used to obtain details about information types of assembly? A. GetTypes B. GetType C. Both A) and B) (your answer) D. None of the Above Q.27) Which of the following is TRUE about Windows Authentication in ASP.NET? A. B. C. D. Automatically determines role membership (your answer) Role membership determined only by user programming ASP.NET does not support Windows Authentication None of the Above Q.28) What tags one need to add within the asp:datagrid tags to bind columns manually? A. Set AutoGenerateColumns Property to false on the datagrid tag (your answer) B. Set AutoGenerateColumns Property to true on the datagrid tag Page 5 of 6 C. It is not possible to do the operation Set AutomaunalColumns Property to true on the D. datagrid tag Q.29) Which method do you invoke on the DataAdapter control to load your generated dataset with data? A. B. C. D. Load ( ) Fill( ) (your answer) DataList DataBind Q.30) In ASP.NET the sessions can be dumped by using A. Session.Dump B. Session.Abandon (your answer) C. Session.Exit D. None of the Above Q.31) ASP.NET is a _________________________ ? A. B. C. D. Server Side Scripting Technology (your answer) Client Side Scripting Technology Programming Language Database Programming Language same as SQL. Q.32) What is ASP+ ? A. ASP+ is the same as ASP.NET. (your answer) B. ASP+ is the Next version of ASP.NET (your answer) C. ASP+ is just an early name used by Microsoft when they developed ASP.NET. (missed) D. ASP+ is a programming Language Specially developed for ASP.NET E. ASP+ is the new Web Server by Microsoft after IIS. Q.33) ASP stands for ____________ ? A. B. C. D. Active Side Pages Active Script Pages Active Server Page (your answer) Active Script Program Q.34) ASP.NET provides increased performance by ____________________? A. supporting active variables. B. running CLR. (your answer) C. running compiled code. (correct answer) D. using IIS Server Q.35) What is the extension of ASP.NET web pages files A. .ashx B. .aspx (your answer)
https://www.scribd.com/document/70234435/aspnet-1
CC-MAIN-2019-39
refinedweb
1,160
70.5
checktype 1.1.4 Intuitive and minimalistic type checking for Python objects Getting Started The first snippet below checks that an object is a list of tuples, each tuple with an int and a string. The second snippet shows how to decorate a function activate_checktype() # by default, checktype is deactivated o = [(1, 'hello'), (2, 'world') checktype(o, '[(int, str)..]') @check('str, {str:int} -> [int..]') def myfunction(a1, a2): return [1,2,3] myfunction("say", {"hello":1}) Introduction Python is strongly, dynamically typed. This is fine, but at times when objects get too complicated, it can be a good thing to check for types. Checktype allows simple checking of Python object formats. It has a very intuitive type system that mimics the way you define your own Python objects. It can be particularily helpful when refactoring programs. Its performance has not been optimized and it is intended as a development-time type checking utility (disabled by default, and should probably be activated in tests only). Installation You can install checktype with pip: pip install checktype Usage examples: from checktype import checktype, activate_checktype, check # 'activates' checktype. You need to explicitly call this, # else it will do nothing (by default, to save cpu time). # It is common to specify it in tests activate_checktype() # checktype only provides a single function, that takes two arguments. # the first one is the python object you want to test; # the second one is an 'object specification' (spec), that mimics the way # objects are represented in Python. This spec is a string representation of # a python object. For example, to check that 12 is an int or 'hello' is a str: checktype(12, 'int') checktype('hello', 'str') # A list of exactly 3 floats is specified as [float,float,float] checktype([1.0,2.0,3.0], '[float,float,float]') # To match a variable-length list of ints, use [int..] checktype([1,2,3], '[int..]') # To only check that it is a list (but not its content), use [] checktype([1, "deux"], '[]') # And so on for tuples, checktype((1,2,3), '(int,int,int)') checktype((1,2,3), '(int..)') checktype((1, "deux"), '()') # dictionnaries, checktype({11:2, 12: 3}, '{int:int}') checktype({11:2, 12: 3}, '{}') # and sets. checktype({11, 2}, '{int}') # Use the ? wildcard if you don't want to check for a specific part checktype({11:2, 12: "a", 13:(3,4)}, '{int:?}') # Further examples checktype({11: (2,3), 12: (4,"5")}, '{ int: (int,?)}') checktype([(2, "asdf"),(-12, "asfwe"),(1,"")], "[(int,str)..]") checktype([(1, 'hello', 2.0)], "[(int, str, float)]") # Decorator examples @check("str.. -> int") def fn_1(a1, a2): return 1 fn_1("say", "hello") @check("str, {str:int} -> [int..]") def fn_3(a1, a2): return [1,2,3] fn_3("say", {"hello":1}) - Author: Renaud Richardet - Keywords: type checking - License: Apache License (2.0) - Categories - Development Status :: 5 - Production/Stable - Environment :: Console - Intended Audience :: Developers - License :: OSI Approved :: Apache Software License - Operating System :: OS Independent - Programming Language :: Python :: 2.6 - Programming Language :: Python :: 2.7 - Programming Language :: Python :: 3 - Programming Language :: Python :: 3.2 - Programming Language :: Python :: 3.3 - Programming Language :: Python :: 3.4 - Topic :: Software Development :: Testing - Package Index Owner: renaudr - DOAP record: checktype-1.1.4.xml
https://pypi.python.org/pypi/checktype/
CC-MAIN-2017-43
refinedweb
527
57.27
I have a class fib __iter__ class fib(object): def __init__(self): self.prev = 0 self.curr = 1 def __iter__(self): return self def __next__(self): value = self.curr self.curr += self.prev self.prev = value return value from collections import Iterable print(isinstance(fib, Iterable)) False True You're supplying a class to isinstance not an instance. It's False because isinstance will go ahead and check if type(fib) has an __iter__ method defined: # type(fib) is type, its default metaclass, doesn't define __iter__ type(fib).__iter__ # AttributeError Supply an instance to it and print yields True: isinstance(fib(), Iterable) # True Alternatively, feed fib to issubclass for a similar check that takes a class as a first arg. issubclass(fib, Iterable) # True Two extra things to point out: objectexplicitly is unnecessary in Python 3(good to use if you're developing code that runs on both Py2 and Py3, though) fib -> Fib.
https://codedump.io/share/h9d7iRhYCWz4/1/checking-if-a-class-is-iterable
CC-MAIN-2017-09
refinedweb
155
52.29
cliar 1.1.6 Cliar lets you create powerful commandline interfaces from regular Python classes. Using type hints, you can add validation and on-the-fly parsing. Create CLIs from Python classes. Make them powerful with type hints. Cliar is a Python tool that helps you create commandline interfaces: from cliar import CLI class Git(CLI): '''Git clone created with Cliar''' def clone(self, repo, dir='.'): '''Clone a git repo from REPO to DIR.''' print('Cloning from %s to %s' % (repo, dir)) if __name__ == '__main__': Git().parse() Run the script: $ python git.py clone -d baz Cloning from to baz Requirements Cliar runs with Python 3.5+ on Windows, Linux, and Mac. There are no external dependencies. Install Install Cliar from PyPI with pip: $ pip install cliar You can install Cliar on CentOS 6 with yum from Gleb Goncharov’s public repo: $ yum install -y python-cliar Hello World from cliar import CLI class Hello(CLI): def hello(self, name='world'): print('Hello ' + name + '!') if __name__ == '__main__': Hello().parse() python hello.py hello --name Bob Hello Bob! Limitations Cliar is designed to help you create CLIs quickly. For the sake of simplicity, some features are unavailable: - You can’t add help text for individual arguments. You can add help text for individual commands with docstrings though. - You can’t have 3rd-level commands. Contribute - Author: Konstantin Molchanov - License: MIT - Categories - Package Index Owner: moigagoo - DOAP record: cliar-1.1.6.xml
https://pypi.python.org/pypi/cliar/
CC-MAIN-2017-43
refinedweb
241
68.97
Routing is what matches a url (such as /posts/123) to a controller and action (such as Posts.view(123)). Ferris can automatically generate routes for your actions but also provides the flexibility for you to specify your own routes. It’s useful to think of the route in three components: - The route name is a unique, canonical name for the action. This is used for inter-app references to other routes. For example posts-view. - The route function refers to the controller and action. For example Posts.view(). - The route url is how the function can be called from the outside world. For example /posts/view/123. A route is automatically generated using using four parts determined from the route function: These are called the route parts and are used to build both the route name and the route url from the route function. For the route name, it follows the convention [prefix:]handler:action with handler being underscored. For the url, it follows the convention [/prefix]/handler/action[/param_1, etc.] with handler being underscored. The following table demonstrates various mappings: The methods named list, view, add, edit, and delete are always treated as actions and are implicitly routed (even when prefixed). This means you don’t have to use the @route decorator to expose these actions and there’s no way to unexpose these. These methods have preset url mappings as follows, but can be prefixed: Actions other than the CRUD actions need to be explicitly routed using @route or @route_with. Take the following methods for example: def list(self): return 'list' @route def test(self): return 'test' def run(self): return 'run' The methods list and test will be accessible via HTTP, but the method run is only accessible from within your code. To set a custom url or name for an action, use @route_with A prefix is just a simple string that is placed before the action name, route name and url. It’s useful for grouping actions. You might use the ‘admin’ prefix to group together actions for an administrator and the ‘api’ prefix to group together actions that return machine-readable data instead of html. Prefixes must be explicitly listed in the prefixes property in the Meta configuration for a Controller, for example: class Posts(Controller): class Meta: prefixes = ('json', 'admin') @route def json_stats(self): pass @route def xml_stats(self): pass json_stats will have the url /json/posts/stats but xml_stats will be at /posts/xml_stats because there isn’t a prefix setup for ‘xml’. There is a standard way to generate URLs to actions across the application: - Controller.uri(route_name = None, prefix = <sentinel>, controller = <sentinel>, action = <sentinel>, _pass_all = False, _full = False, *args, **kwargs)¶ Generate in-application URIs (or URLs). Examples:uri('foxes:run') # -> /foxes/run uri(prefix=False, controller='foxes', action='run') # -> /foxes/run # when currently at /foxes/run uri(action='hide') # -> /foxes/hide Attempting to generate a URL to an action that doesn’t exist will result in an exception. You can check for the existence of an action before attempting to generate a URL to it: You can see if you’re on a particular action. While this may seem like a superfluous feature, it’s very useful in templates: Your application’s route configuration is located in app/routes.py. You can configure custom routes such as the application root and additional redirects. Plugins can also be enabled using this configuration file. By default, Ferris shows a helpful landing page when you pull up /. However, in your complete application you will want this to go to one of your handlers. The easiest way to do this is to remove this: # Default root route routing.default_root() Adds the default Ferris root route Replace it with something like this: # Default root route routing.redirect('/', to='/posts') Adds a redirect route with the given url templates. Beyond redirects you can also create completely custom routes. This is very useful for when you want to expose a ordinary webapp2.RequestHandler or similar: routing.add(routing.Route('/special', SpecialHandler)) Adds a webapp2.Route class to the router The default routes.py automatically routes all of the controllers in the app using auto_route: # Routes all App handlers routing.auto_route() Automatically routes all controllers in main app or the given plugin You can remove this and route manually using route_controller: from app.controllers.posts import Posts routing.route_controller(Posts) Adds all of the routes for the given controller
http://ferris-framework.appspot.com/docs21/users_guide/routing.html
CC-MAIN-2017-13
refinedweb
741
55.13
Accessing Nested Objects in JavaScript Dinesh Pandiyan Feb 10 '18 Updated on Apr 07, 2018 ・3 min read t: 'jack@dev.com',: 'jack@dev.com' } Typy library that I've written. In addition to safely accessing nested objects, it does many more awesome things. 🎉 It is available as an npm package - Design Patterns in Java I thought it would be a fun to write a series of blog posts looking at differen... or github.com/tc39/proposal-optional-..., in future... I have been looking forward to this a lot; checking the site on a near-weekly basis to see if it has progressed a stage It'll be great to see this operator soon in ES. I like the way how ES is progressing forward. It's a GOOD thing that you get this error from JS! It tells you that something in your program and/or your data is wrong. By coding like this, you may circumvent the error message, but the root cause still exists. Use Typescript instead. It will tell you exactly when it is safe to navigate nested structures and when it is not. In the latter case, you should HANDLE the error, not ignore it. I agree TypeScript is safe and provides great many flexibilities in handling unexpected code. But the alternate without a typescript (preference differs) would be to catch all these in a try catch block throughout the code, which will look really messy in a huge codebase. Sometimes, missing data in nested structures might be intentional too, mostly because JS is weakly typed. I think handling all those errors is a little too much effort and rather we should focusing on coding for the problem and let utils/libs handle the language shortcomings. I use extract method for my project. Purpose can be different. These codes from my localization project on Github. github.com/aligoren/local.js/blob/... Usage: This is great and easily readable. Maybe we should benchmark all the ways to access nested objects and spread the word so the community will know which one to use and when. Take a look at i18n library, works in this way. or get from Lodash. Lodash is all too awesome and there's nothing you can't do in Lodash. I'm a big fan of it. But sometimes, in a few light-weight front-end codebases, I find Lodash to be heavy and prefer to write the util on my own, especially if I'll be needing only one or two methods from Lodash. You can install any lodash method in isolation for that case. If you're bundling your assets, you can install lodash and load just the parts you need. Lodash get all the things 🙌🙌🙌 Instead of reinventing wheel, I highly suggest looking at lenses randycoulman.com/blog/2016/07/12/t... I am a big fan of Lodash and have heard a great deal about Ramda too. But most of the time I find myself working on a small project that doesn't need 99% of the utils in these libraries, especially on the front-end. In those cases, I prefer to either write the util on my own or use a micro library that works for my project. But anyway thanks for letting me know about lenses. This looks pretty interesting and I'm going to take a closer look at how it works internally. import _get from "lodash/get"; What about this? Ah, default value doesn't make sense here, so github.com/developit/dlv How about something actually tiny? This is amazing. Concise and clean. Do you want to be able to support arrays in string path? I can create a PR. But the code won't be as small though. Or you could use lodash _.get(array[pos].property, defaultValue) and get a way cleaner code. Hey! Don't forget lodash.get! If you find loadash too heavy just import the get! I think is one of the most common ways of accessing nested objects until se get an Elvis operator like kotlin Too many times have I had >120 character variables of just trying to get nested objects. Very ugly. I am ashamed of myself. We've all been there. Cheers!
https://dev.to/flexdinesh/accessing-nested-objects-in-javascript--9m4
CC-MAIN-2019-18
refinedweb
709
74.69
1 /*2 * JORAM: Java(TM) Open Reliable Asynchronous Messaging3 * Copyright (C) 2005 -.shared.admin;24 25 import java.util.Hashtable ;26 27 /**28 * A <code>Monitor_GetStatRep</code> instance replies to a get stat,29 * monitoring request.30 */31 public class Monitor_GetStatRep extends Monitor_Reply {32 private static final long serialVersionUID = 5241964631247563162L;33 34 /** Table holding the statistic. */35 private Hashtable stats;36 37 /**38 * Constructs a <code>Monitor_GetStatRep</code> instance.39 */40 public Monitor_GetStatRep(Hashtable stats) {41 this.stats = stats;42 }43 44 /** Returns the stats table. */45 public Hashtable getStats() {46 return stats;47 }48 }49 Java API By Example, From Geeks To Geeks. | Our Blog | Conditions of Use | About Us_ |
http://kickjava.com/src/org/objectweb/joram/shared/admin/Monitor_GetStatRep.java.htm
CC-MAIN-2016-50
refinedweb
111
52.56
A few years ago, I wrote an introductory React tutorial based on a workshop I taught. Since that point in history, I've taught hundreds of new web developers React, and the library has evolved significantly. I thought it was time to come back to the fundamentals and discuss learning React from absolute zero in the era of Hooks. Some pre-requisites for the tutorial in this blog post: HTML, CSS, and JavaScript fundamentals. React is a JavaScript library which was written by Facebook in 2013. It speeds up and simplifies the frontend development process. It has many key features that aid in the development of user interfaces, such as JSX, components, and the virtual DOM. It's almost inescapable in the current era of frontend development. In this tutorial, we'll learn about the React fundamentals, use Create React App to scaffold a project, build out an app with React state and props, and then deploy it to AWS Amplify. Components You may have learned very early on in your programming journey to "separate concerns" or put your HTML, CSS, and JS in separate files. React flips this on its head. We will instead break our webpages into chunks called components and write all of their display and logic code all in one. This will increase the modularity of our user interfaces, and we can compose components in infinite combinations and reuse them over and over again. In many web pages, you will have similar user interface components over and over again -- think, for example, of Facebook's like button. It's on posts, videos, and pictures. If you were using standard HTML, each one of those buttons would need to be written separately, given a class to add styling to them, and then JavaScript code would need to be written to implement their behaviors. If you needed to update these buttons, code would likely need to be changed in many places. React's component-based architecture allows us to instead reuse that button over and over again and only update code in one place if needed. Let's see how a Facebook status may be broken down into components: We can also have subcomponents which are components within a parent component. For example, the three buttons at the bottom of the status could be broken into their own components. There are a bunch of ways you could break down these components and subcomponents depending on your application's needs. Installation && Setup First, install Node.js. If you haven't encountered Node.js, it is a runtime that allows you to write JavaScript outside the browser. In this case, we'll be using it to make development on our React application as easy as possible. Once you have Node installed, open up your command line and run: npx create-react-app color-switcher. Heads up, this command may take a few minutes to run. npxis a tool that comes with Node that allows you to run commands without installing them first. - We are using it to run create-react-appwhich does what the name implies! It scaffolds a React application for us and sets up Babel and Webpack, two super important tools we'll come back to later in the tutorial. - Finally color-switcheris the name of our application, you will need to re-run the npx create-react-app your-app-namecommand for each app you build. Once your app is created cd into the directory that create-react-app created for us. cd color-switcher Create React App Generated Files Open up the directory in your text editor of choice, and check out the files that were created. There are a bunch! But don't be intimidated, let's do a quick run-through of the files create-react-app generated. The ones highlighted are the important ones for us: - node_modules/ - the Node modules we are using for our project, essentially other people's code that's going to make our life easier. - public/ - favicon.ico - the icon that shows up when you favorite a site - index.html - the file our JavaScript attaches to - logo.png files - different icons for our app - manifest.json - allows us to make our app into a progressive web app, we won't make our app into one today. - robots.txt - declares the rules for bots on our site - src/ - App.css - Where our App component's styling will go - App.js - Where our App component will be written - App.test.js - A file where you can write automated tests for your App component - index.css - A file for global styles for your application - index.js - Configuration for your React application - logo.svg - a React logo - serviceWorker.js - code to configure - setupTests.js - configuration for automated testing - .gitignore - files you want to keep local and hide from git - package.json - holds project metadata - package-lock.json - auto-generated file to track dependencies There are a bunch of files created, but we only need to worry about a very few of them. The index.js File Let's break down what's in the index.js first: import React from 'react' - import the React library. We need this in every file where we use JSX syntax. import ReactDOM from 'react-dom' - ReactDOM allows us to use React in the browser import './index.css' - apply the global styles import App from './App' - import the App component Now for the important code! We are going to take our <App> component and attach it to an element with the id #root. You can find that element in the public/index.html file. This allows our React code to actually render on the page. React utilizes the virtual DOM, which is a virtual representation of the DOM that you would normally interact within Vanilla JavaScript or JQuery. This reactDOM.render renders this virtual DOM to the actual DOM. Behind the scenes, React does a lot of work to efficiently edit and re-render the DOM when something on the interface needs to change. ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById('root') ); The <React.StrictMode> component is a tool that will give you extra warnings about issues that may exist in your code. Again, we'll just ignore the service worker code, it goes above and beyond what we need to do. You don't need to change anything in the index.js file, I just wanted to run through it since it is so key to making our application work. A React Hello World Now for the fun part, writing the code! Open up your App.js file. This will be our top-level, or root, component for our application. Inside that file we already have some code written. We are again importing React (which we need to do in every file that we use React in), the React logo, and the CSS file specific to this App component. We also have a function, App that returns a bunch of what looks like HTML -- this is actually JSX. Finally, we are exporting the component so we can import it into other files, in this case, our index.js that was generated for us. Let's go ahead and remove the logo import and change the JSX code so that it only returns <h1>Hello, World</h1> import React from 'react' - import logo from './logo.svg' import './App.css' function App () { return ( + <h1>Hello world!</h1> ) } export default App JSX is an extension of JavaScript that allows you to write what looks like HTML directly in your JavaScript code. You can't natively use JSX in the browser, but we will use a library called Babel to transpile (or convert) our JSX into regular JavaScript so that the browser can understand it. JSX is actually optional in React, but you'll see it used in the vast majority of cases. Okay, now you've written your first React code, but how do you see the output? Go back to your CLI and run npm run start. A webpage should pop up that displays your React app. It will hot reload, so every time you change your code and save those changes, your application will show those changes automatically. In order to exit out of the server, you can press ctrl + c. It may be helpful to have two terminal windows or tabs open while you're developing React apps because you can't write additional commands in the session where the server is running. React Color Switcher First, we're going to build a color picker application -- the background of the page will change color based on a button the user selects. The first step is to build out the static user interface. First, we'll add an enclosing div which will be the top-level element of our React application. Then, we'll add another div inside of that one that will allow our content to be centered on the page. We'll also add a header to title our page and three buttons. We are also going to add some className attributes to our elements. In JavaScript, a class is for creating classes in object-oriented programming, so, React can't use the word class to add class names for styling groups of elements. So, it uses className instead. We will add the following classNames to our elements: import React from 'react' import './App.css' function App () { return ( <div className='react-root'> <div className='centered'> <h1>Color Picker</h1> <button className='red'>red</button> <button className='blue'>blue</button> <button className='yellow'>yellow</button> </div> </div> ) } export default App Since this tutorial is focused on React, we'll just copy some CSS code into your App.css. Remove what's in there and replace it with: html, body, #root, .react-root { height: 100%; width: 100%; background-color: white; color: black; display: flex; justify-content: center; align-items: center; } .centered { text-align: center; } button { padding: 10px; margin: 5px; border: 2px solid white; color: white; font-size: 20px; } .red { background-color: red; color: white; } .blue { background-color: blue; color: white; } .yellow { background-color: yellow; color: black; } Now, your app should look like this: Now we need to actually make it do something! Any variables we want to have changed while our application is running need to be stored in state. This will cause React to automatically update our component's appearance each time a state variable updates. React State In order to utilize state, we will import the useState hook from React. Hooks are new to React -- they were introduced near the end of 2018. React looks very different from when I learned it five years ago. ES6 wasn't fully implemented yet, so we wrote components using objects and the React.createClass function. Then there was the era of JavaScript classes, and most recently, React has implemented Hooks, which allow us to write components using just functions. This makes React's syntax simpler and less verbose. According to the React docs, "Hooks are functions that allow us to 'hook into' React features." In our App.js component, we will update our first line of code. + import React, { useState } from 'react' import './App.css' The useState hook takes one argument: what the initial value of state will be. It then returns two values in an array. The first is the value of the state variable, the second is a function that will allow us to update state. We will use array destructuring to set both of the items returned to their own variables. import React, { useState } from 'react' import './App.css' function App () { + const [color, setColor] = useState('') return ( <div className='react-root'> <div className='centered'> <h1>Color Picker</h1> <button className='red'>red</button> <button className='blue'>blue</button> <button className='yellow'>yellow</button> </div> </div> ) } export default App If you console log each item, you'll see color is an empty string because we provided useState the argument ''. If you changed that empty string to 'blue' then color will then store the value blue! setColor is a function, which we will use to update the color variable. Now, we need to add an event listener so that when a user clicks on our buttons, the color stored in state updates. First, we will display the current value of color on the interface. We can do this by writing the color variable in curly braces, this tells React that any code inside the curlies is JavaScript code. In general, we will use {} wh We will also add an onClick attribute to our first button, after that onClick we will add a function that will run when the event fires. This is how we write event listeners in React. For now, we will just console.log('clicked'). import React, { useState } from 'react' import './App.css' function App () { const [color, setColor] = useState('') return ( <div className='react-root'> <div className='centered'> <h1>Color Picker</h1> + {color} + <button className='red' onClick={() => console.log('clicked')}> red </button> <button className='blue'>blue</button> <button className='yellow'>yellow</button> </div> </div> ) } export default App Now we'll change the event listener function to instead change the color state variable. We can do so by using the setColor function that useState gave us. <button className='red' onClick={() => setColor('red')}> red </button> Now, you can see that when you click on the button the word "red" displays on the page! Now let's make both of the other buttons work as well. <button className='blue' onClick={() => setColor('blue')}>blue</button> <button className='yellow' onClick={() => setColor('yellow')}>yellow</button> The last thing that we need to do is actually change the color of the page instead of just displaying the color's name on the page. In our CSS file, we already have three classes for our colors -- yellow, red, and blue. What we need to do is add those classes onto our react-root element so that it changes color to match our color variable. We need to make our className take JavaScript code instead of just a string, and then we will use string interpolation to add our color class to the element. <div className={`react-root ${color}`}> Our final code should look like this: import React, { useState } from 'react' import './App.css' function App () { const [color, setColor] = useState('') return ( <div className={`react-root ${color}`}> <div className='centered'> <h1>Color Picker</h1> <button className='red' onClick={() => setColor('red')}>red</button> <button className='blue' onClick={() => setColor('blue')}>blue</button> <button className='yellow' onClick={() => setColor('yellow')}>yellow</button> </div> </div> ) } export default App React Props Now we've used some of React's most important features: JSX and state. There are two more that I want to show you: components and props. Right now we are actually using a component: App. But, we want to make our components small and reusable. Right now, our buttons follow a pattern. Each displays text, has a className, and has an onClick event. We will make a second ColorChangeButton component so that we can reuse as much code as possible, and if we want to update the buttons in the future we can do so more easily. The first step is to create another file in your src/ folder called ColorChangeButton.js. Now, we will create a second React component in this file. // ColorChangeButton.js import React from 'react' function ColorChangeButton () { return ( <button>Hi!</button> ) } export default ColorChangeButton We'll now go back to our App.js and import our ColorChangeButton: // App.js import React, { useState } from 'react' import './App.css' + import ColorChangeButton from './ColorChangeButton' In our JSX code, we will create three instances of our ColorChangeButton. // App.js return ( <div className={`react-root ${color}`}> <div className='centered'> <h1>Color Picker</h1> + <ColorChangeButton /> + <ColorChangeButton /> + <ColorChangeButton /> <button className='red' onClick={() => setColor('red')}>red</button> <button className='blue' onClick={() => setColor('blue')}>blue</button> <button className='yellow' onClick={() => setColor('yellow')}>yellow</button> </div> </div> ) Boom! Now you should have three more buttons that show up on the page that all say Hi!. This is how we create and include a second component in React. But, right now our components are pretty boring. They all say the same thing. We want these to eventually replace the three color-changing buttons we have written, so we need to allow our button to be a different color and to have different text. React uses unidirectional data flow, which means we can only pass data from a parent component to a child component. We will use props to pass data from one component to another. // App.js return ( <div className={`react-root ${color}`}> <div className='centered'> <h1>Color Picker</h1> + <ColorChangeButton color='red' /> + <ColorChangeButton color='blue' /> + <ColorChangeButton color='yellow' /> <button className='red' onClick={() => setColor('red')}>red</button> <button className='blue' onClick={() => setColor('blue')}>blue</button> <button className='yellow' onClick={() => setColor('yellow')}>yellow</button> </div> </div> ) In our parent component, App, we can use what looks like an HTML attribute to send props. In this case, color is the name of our prop and then the value comes after the equals sign, 'red' for the first component, 'blue' for the second, and 'yellow' for the third. Now, we need to use those props in our child component. Switch over to ColorChangeButton.js. First, we will make our function take the parameter props. // ColorChangeButton.js function ColorChangeButton (props) { ... } Then, you can console.log props before the return to see what's there: { color: 'red' } { color: 'blue' } { color: 'yellow' } It's an object! React combines each prop we send from the parent component into an object with each key and value in the child. So, to access our color in our child component, we would do props.color. Let's make our button display our color as its text and also add the color as a class to the button so that the correct color displays. // ColorChangeButton.js import React from 'react' function ColorChangeButton (props) { return ( + <button className={props.color}>{props.color}</button> ) } export default ColorChangeButton Now our buttons look the way they are supposed to! The last thing that we need to do is make the click event work. In our App.js, we wrote this code to change the current color: <button className='red' onClick={() => setColor('red')}>red</button> The one issue we have is that setColor is defined in our App component, so we don't have access to it ColorChangeButton. Good news though: we have a way to pass data from a parent component to a child component that we learned in the past step: props! Let's pass the setColor function down as a prop to our ColorChangeButton component. I'm also going to delete our three original buttons since we no longer need them. // App.js return ( <div className={`react-root ${color}`}> <div className='centered'> <h1>Color Picker</h1> + <ColorChangeButton color='red' setColor={setColor} /> + <ColorChangeButton color='blue' setColor={setColor} /> + <ColorChangeButton color='yellow' setColor={setColor} /> </div> </div> ) Now, if you go back to the ColorChangeButton and console.log what the props are, you'll see that you have a second item in the object, for example: { color: "red" setColor: ƒ () } Let's use that setColor function: function ColorChangeButton(props) { return ( + <button className={props.color} onClick={() => props.setColor(props.color)}> {props.color} </button> ) } export default ColorChangeButton Now each button should work as expected! This pattern of passing the state change function down from parent to child components is called inverse data flow. It allows us to circumvent the unidirectional data flow nature of React. Deployment Amazing, now our application is complete. One small problem though: our application is only accessible locally, meaning that we can't send the localhost URL to friends for them to see the application. We need to deploy our application so that anybody on the web can see it. We will use AWS Amplify to do so with just a few clicks. First, we need to push this tutorial code to GitHub by: - creating a new repository by clicking the plus button on the top right of the page. - choose a repository name and click create repository - Then, copy the commands from …or push an existing repository from the command lineand run them in your terminal. - Run git add . && git commit -m "tutorial complete" && git pushin your terminal to send your latest changes. Then to get it deployed:. For the first 12 months of your AWS account existing, Amplify has a free tier that will most likely cover your hosting. After that, here is more information about pricing! It may take a few minutes for your app to build, but once it does you will get a URL that anyone can visit! You can visit mine at this url. Next Steps This tutorial took you through the basics of React data flow, components, and project setup. Here are some awesome resources for learning more: - React: Getting Started - The Complete Tutorial for 2020 - The Beginner's Guide to React - Tutorial: Intro to React In addition, I did a live stream with the content from this tutorial if you'd prefer to view it that way. If you extend what you built, please share it with me on twitter! Posted on by: Ali Spittel Passionate about education, Python, JavaScript, and code art. Discussion Nice post Ali, I haven't used AWS in years but thinking of trying it again. I love React Hooks, it has made React so much easier! Great Article for quick onboarding to React and React Hooks. Thanks alot . Perfect introduction for a beginner like me!
https://practicaldev-herokuapp-com.global.ssl.fastly.net/aspittel/a-complete-beginner-s-guide-to-react-hooks-edition-1bi0
CC-MAIN-2020-40
refinedweb
3,585
55.64
Hi I want to add a generating custom command that will query one of our DBs. So I have followed the tutorials and created a class that inherits from GeneratingCommand and implemented the generate method. Problem is that Splunk waits for all the results to return and the query might be slow (4-5 seconds). So following some of the docs it looks like timeline_events_preview is what I need but I still don't get the live update of the events view (Similar to using the builtin search command). GeneratingCommand generate timeline_events_preview search I can't post the original code (for copyright reasons) but I can't make it work even with the next simple example: @Configuration(streaming=True) class MyGeneratingCommand(GeneratingCommand): def generate(self): for i in range(10 ** 6): yield {'_time': time.time(), '_raw': 'test {}'.format(i), 'events_no': i} I added a limits.conf file to $SPLUNK_HOME/etc/apps/myapp/local with: limits.conf $SPLUNK_HOME/etc/apps/myapp/local [search] timeline_events_preview = true When I use the custom command Splunk waits for all 1 million results to return before showing some of them in the events view. So my problem was that I used the SCPv1 instead of using SCPv2 that supports the chunked. This property of the SCPv2 should be documented more because I didn't find any explicit and clear description of the differences between v1 and v2. chunked So you actually solved the problem? I'm trying the same thing using SCPv2 and it still waits for all 1M results before showing them in preview. Same configuration settings and CSC.
https://community.splunk.com/t5/Splunk-Search/Preview-generating-custom-command-result/m-p/398206/highlight/true
CC-MAIN-2021-21
refinedweb
264
62.48