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
. All the final code can be found in this repository I set up for this tutorial. Feel free to follow along or take a peek at the final code. Non-entity forms The first example we will look at is how to process forms declared as regular HTML elements inside of a Symfony View file. There are 3 steps we will take to illustrate this: - We will create a View file that contains our form HTML - We will create a new Controller method in the WelcomeControllerclass called form1Actionthat will handle our business logic (rendering the View, processing the form, etc). - We will then create a simple route entry to map a URL path to this method so that we can see the form in the browser and be able to submit it. Let’s first create the View file that will show our form and the submitted value on top. In a file called form1.html.twig located in the src/Acme/DemoBundle/Resources/views/Welcome folder (the corresponding folder for the Welcome controller class Symfony comes with by default) I have the following: {% extends "AcmeDemoBundle::layout.html.twig" %} {% block content %} <h1>Form values</h1> {% if name is defined %} <p>Name: {{ name }} </p> {% endif %} <div> <form name="input" action="" method="post"> Name: <input type="text" name="name"/> <input type="submit" name="submit" value="Submit"> </form> </div> {% endblock %} Above, I am extending the default layout in the DemoBundle just so I don’t see a very white page. And the rest is pretty basic as well: declaring a simple HTML form that posts to itself and showing the value of the only text field above the form (which will be passed from the Controller after processing in a variable called name). Next, let’s declare the Controller method in charge of displaying this View and processing the form inside it. In the WelcomeController class file, I do two things: I make use of the Symfony Requestclass that will help us easily access the submitted values: use Symfony\Component\HttpFoundation\Request; This goes above the class declaration. I have the following method: public function form1Action() { $post = Request::createFromGlobals(); if ($post->request->has('submit')) { $name = $post->request->get('name'); } else { $name = 'Not submitted yet'; } return $this->render('AcmeDemoBundle:Welcome:form1.html.twig', array('name' => $name)); } In this method, I use the createFormGlobals() method found in the $request object to gather the PHP superglobals (including the $_POST values). Then I check if the submitted values include submit (which is basically our submit button), and if they do, I retrieve the value of the name element and pass it along to the View we just created. Simple. Finally, let’s define a routing rule to match a URL path to this Controller method. In the routing.yml file located in the src/Acme/DemoBundle/Resources/config folder I added the following rule: _form1: pattern: form1 defaults: { _controller: AcmeDemoBundle:Welcome:form1 } This will map the form1/ path to the new Controller method. And that’s it, you can test it out. One thing to keep in mind is that this is not really a recommended way to handle forms when dealing with entities or any kind of content for your site. Symfony comes with some nice classes that will make doing that much easier. We will see how some of these work next. Symfony Entities and Forms Going forward, we will be looking at how to display and process a form for a Symfony entity called Article (that I’ve defined in the meantime and you can find in the repository). For a refresher on how entities work, check out our second part of the series on the Symfony framework. I will illustrate a very simple example of how to display a form that will then save a new Article entity to the database, using the Symfony way. We’ll be working mainly with 5 files: the controller class file where we add two new methods for showing the form and for showing a simple confirmation page; the routing.yml file since we need to map the URLs; two View files to display the form and confirmation; and an ArticleType.php file in which we build the form. We’ll start with the latter. Although you can build the form also directly inside the controller, using a separate type file makes it much more reusable so we’ll do that instead. Inside our src/Acme/DemoBundle/Form folder, I have a file called ArticleType, with the following contents: <?php namespace Acme\DemoBundle\Form; use Symfony\Component\Form\AbstractType; use Symfony\Component\Form\FormBuilderInterface; use Symfony\Component\OptionsResolver\OptionsResolverInterface; class ArticleType extends AbstractType { public function buildForm(FormBuilderInterface $builder, array $options) { $builder->add('title', 'text', array('label' => 'Title')) ->add('body', 'textarea') ->add('save', 'submit'); } public function getName() { return 'article'; } public function setDefaultOptions(OptionsResolverInterface $resolver) { $resolver->setDefaults(array( 'data_class' => 'Acme\DemoBundle\Entity\Article', )); } } Above, I extend the default Symfony form builder class to define my own form. The buildForm() method is responsible for actually building the form. Inside, I am adding to the $builder object’s various form elements that will suit our Article entity and that are named after the entity properties. For more information on the available form elements, you can consult the documentation. The getName() method just returns the name of the form type itself whereas with the setDefaultOptions() method we specify the entity class we use this form for (as the value for the data_class key). And that’s it, we have our form definition, let’s build it inside our controller and display it on the page. Back in the WelcomeController class, I have included at the top two more class references (for the Article entity and the form type we just created): use Acme\DemoBundle\Entity\Article; use Acme\DemoBundle\Form\ArticleType; Next, I added the following two methods: public function form2Action(Request $request) { $article = new Article(); $form = $this->createForm(new ArticleType(), $article); $form->handleRequest($request); if ($form->isValid()) { $em = $this->getDoctrine()->getManager(); $em->persist($article); $em->flush(); $session = $this->getRequest()->getSession(); $session->getFlashBag()->add('message', 'Article saved!'); return $this->redirect($this->generateUrl('_form2saved')); } return $this->render('AcmeDemoBundle:Welcome:form2.html.twig', array('form' => $form->createView())); } public function form2savedAction() { return $this->render('AcmeDemoBundle:Welcome:form2saved.html.twig'); } The form2Action() method is responsible for showing and processing the form to create new Article enities. First, it instantiates a new empty object of that class. Then, it creates a new form for it using the form type we defined earlier. Next, it processes the form if one has been submitted, but if not, it renders the form2.html.twig View file and passes the rendered HTML form for it to display. Let’s create that file now and then we’ll come back and see what happens with the form processing. Right next to where we created form1.html.twig, I have form2.html.twig with the following contents: {% extends "AcmeDemoBundle::layout.html.twig" %} {% block content %} {{ form(form) }} {% endblock %} Couldn’t be simpler. It just renders the form that was passed to it. Let’s quickly also add the following route to our routing.yml file so we can see this in the browser: _form2: pattern: form2 defaults: { _controller: AcmeDemoBundle:Welcome:form2 } Now we can point our browser to the form2/ path and see a simple (but rather ugly) form. Now for the processing. As we saw earlier, the form2Action() method has a parameter passed to it: the $request object. So when we submit this form, it uses the handleRequest() method of the $form object we built to see if the form has been submitted (if its values exist in the $request superglobals). If it has been submitted, it runs a standard validation on it and saves the new object to the database (the one we originally instantiated has been automagically populated with the form values). Lastly, it saves a one request only flash message and redirects to another page, the path being built based on another route: _form2saved: pattern: form2saved defaults: { _controller: AcmeDemoBundle:Welcome:form2saved } The route triggers the form2savedAction() method we declared in the WelcomeController class and which renders the form2saved.html.twig View. And in this View, all I do for now is look if there is a message in the session flashBag and print it out: {% extends "AcmeDemoBundle::layout.html.twig" %} {% block content %} {% for flashMessage in app.session.flashbag.get('message') %} <p>{{ flashMessage }}</p> {% endfor %} {% endblock %} And that’s it. Now you can refresh the form and submit it. You should be redirected to a simple page that shows the confirmation message. And if you check the database, a new Article record should have been saved. Conclusion In this article we’ve looked at very simple usages of the Symfony 2 form system. First, we saw how to process a form submission using regular HTML form elements printed in the View. Then, we saw how to leverage the power of the Symfony form system to define forms in code in order to process and persist the values as an entity. Each of these techniques have their use case. If you are performing CRUD operations on data or content, it’s best to use the second option. Symfony is very powerful when it comes to abstracting your data and this makes the form building very easy. If, however, you need some ‘on the fly’ processing of a form that does not save anything, you can build the form right into the View and then catch the submitted values in the controller. Questions? Comments? Would you like to know more? Let us know! - Mark Simchock - ivariable - damijanc
http://www.sitepoint.com/building-processing-forms-in-symfony-2/
CC-MAIN-2015-32
refinedweb
1,604
51.58
Question posted by skrsna Hi, I’m trying to run some rockets in slurm queue using rapidfire from queue_launcher but it keeps submitting one rocket again and again in a infinite loop. I’m using the following script to get the launchpad and launch rockets from fireworks import LaunchPad, FWorker from fireworks.queue.queue_launcher import rapidfire from fireworks.utilities.fw_serializers import load_object_from_file lpad = LaunchPad.from_file('my_launchpad.yaml') qadapter = load_object_from_file('my_qadapter.yaml') rapidfire(lpad,FWorker(),qadapter) my launchpad looks like this { "fw_id": 51, "created_on": "2019-10-31T14:55:20.724738", "updated_on": "2019-10-31T14:55:41.687741", "state": "FIZZLED", "name": { "calculation_type": "conformer_job", "name": "CC=CCC_dftb_TS_False", "user": "me" it’s in fizzled state cause I cancelled the job. Am I doing something wrong here? my queue adapter file is this: _fw_name: CommonAdapter _fw_q_type: SLURM rocket_launch: rlaunch -l my_launchpad.yaml -w my_fworker.yaml singleshot walltime: '00:10:00' queue: null account: null job_name: null logdir: ~/fw_logs pre_rocket: null post_rocet: null Thanks for your help.
https://matsci.org/t/queue-launcher-is-submitting-one-rocket-in-a-loop/3270
CC-MAIN-2022-40
refinedweb
161
51.95
Get the highlights in your inbox every week. An overview of the Perl 5 engine An overview of the Perl 5 engine A developer explains the features that make Perl his language of choice. Subscribe now As I described in "My DeLorean runs Perl," switching to Perl has vastly improved my development speed and possibilities. Here I'll dive deeper into the design of Perl 5 to discuss aspects important to systems programming.Some years ago, I wrote "OpenGL bindings for Bash" as sort of a joke. The implementation was simply an X11 program written in C that read OpenGL calls on stdin (yes, as text) and emitted user input on stdout. Then I had a little bash includefile that would declare all the OpenGL functions as Bash functions, which echoed the name of the function into a pipe, starting the GL interpreter process if it wasn't already running. The point of the exercise was to show that OpenGL (the 1.4 API, not the newer shader stuff) could render a lot of graphics with just a few calls per frame by using GL display lists. The OpenGL library did all the heavy lifting, and Bash just printed a few dozen lines of text per frame. In the end though, Bash is a really horrible glue language, both from high overhead and limited available operations and syntax. Perl, on the other hand, is a great glue language. Syntax aside... If you're not a regular Perl user, the first thing you probably notice is the syntax. Perl 5 is built on a long legacy of awkward syntax, but more recent versions have removed the need for much of the punctuation. The remaining warts can mostly be avoided by choosing modules that give you domain-specific "syntactic sugar," which even alter the Perl syntax as it is parsed. This is in stark contrast to most other languages, where you are stuck with the syntax you're given, and infinitely more flexible than C's macros. Combined with Perl's powerful sparse-syntax operators, like map, grep, sort, and similar user-defined operators, I can almost always write complex algorithms more legibly and with less typing using Perl than with JavaScript, PHP, or any compiled language. So, because syntax is what you make of it, I think the underlying machine is the most important aspect of the language to consider. Perl 5 has a very capable engine, and it differs in interesting and useful ways from other languages. A layer above C I don't recommend anyone start working with Perl by looking at the interpreter's internal API, but a quick description is useful. One of the main problems we deal with in the world of C is acquiring and releasing memory while also supporting control flow through a chain of function calls. C has a rough ability to throw exceptions using longjmp, but it doesn't do any cleanup for you, so it is almost useless without a framework to manage resources. The Perl interpreter is exactly this sort of framework. Perl provides a stack of variables independent from C's stack of function calls on which you can mark the logical boundaries of a Perl scope. There are also API calls you can use to allocate memory, Perl variables, etc., and tell Perl to automatically free them at the end of the Perl scope. Now you can make whatever C calls you like, "die" out of the middle of them, and let Perl clean everything up for you. Although this is a really unconventional perspective, I bring it up to emphasize that Perl sits on top of C and allows you to use as much or as little interpreted overhead as you like. Perl's internal API is certainly not as nice as C++ for general programming, but C++ doesn't give you an interpreted language on top of your work when you're done. I've lost track of the number of times that I wanted reflective capability to inspect or alter my C++ objects, and following that rabbit hole has derailed more than one of my personal projects. Lisp-like functions Perl functions take a list of arguments. The downside is that you have to do argument count and type checking at runtime. The upside is you don't end up doing that much, because you can just let the interpreter's own runtime check catch those mistakes. You can also create the effect of C++'s overloaded functions by inspecting the arguments you were given and behaving accordingly. Because arguments are a list, and return values are a list, this encourages Lisp-style programming, where you use a series of functions to filter a list of data elements. This "piping" or "streaming" effect can result in some really complicated loops turning into a single line of code. Every function is available to the language as a coderef that can be passed around in variables, including anonymous closure functions. Also, I find sub {} more convenient to type than JavaScript's function(){} or C++11's [&](){}. Generic data structures The variables in Perl are either "scalars," references, arrays, or "hashes" ... or some other stuff that I'll skip. Scalars act as a string/integer/float hybrid and are automatically typecast as needed for the purpose you are using them. In other words, instead of determining the operation by the type of variable, the type of operator determines how the variable should be interpreted. This is less efficient than if the language knows the type in advance, but not as inefficient as, for example, shell scripting because Perl caches the type conversions. Perl scalars may contain null characters, so they are fully usable as buffers for binary data. The scalars are mutable and copied by value, but optimized with copy-on-write, and substring operations are also optimized. Strings support unicode characters but are stored efficiently as normal bytes until you append a codepoint above 255. References (which are considered scalars as well) hold a reference to any other variable; hashrefs and arrayrefs are most common, along with the coderefs described above. Arrays are simply a dynamic-length array of scalars (or references). Hashes (i.e., dictionaries, maps, or whatever you want to call them) are a performance-tuned hash table implementation where every key is a string and every value is a scalar (or reference). Hashes are used in Perl in the same way structs are used in C. Clearly a hash is less efficient than a struct, but it keeps things generic so tasks that require dozens of lines of code in other languages can become one-liners in Perl. For instance, you can dump the contents of a hash into a list of (key, value) pairs or reconstruct a hash from such a list as a natural part of the Perl syntax. Object model Any reference can be "blessed" to make it into an object, granting it a multiple-inheritance method-dispatch table. The blessing is simply the name of a package (namespace), and any function in that namespace becomes an available method of the object. The inheritance tree is defined by variables in the package. As a result, you can make modifications to classes or class hierarchies or create new classes on the fly with simple data edits, rather than special keywords or built-in reflection APIs. By combining this with Perl's local keyword (where changes to a global are automatically undone at the end of the current scope), you can even make temporary changes to class methods or inheritance! Perl objects only have methods, so attributes are accessed via accessors like the canonical Java get_ and set_ methods. Perl authors usually combine them into a single method of just the attribute name and differentiate get from set by whether a parameter was given. You can also "re-bless" objects from one class to another, which enables interesting tricks not available in most other languages. Consider state machines, where each method would normally start by checking the object's current state; you can avoid that in Perl by swapping the method table to one that matches the object's state. Visibility While other languages spend a bunch of effort on access rules between classes, Perl adopted a simple "if the name begins with underscore, don't touch it unless it's yours" convention. Although I can see how this could be a problem with an undisciplined software team, it has worked great in my experience. The only thing C++'s private keyword ever did for me was impair my debugging efforts, yet it felt dirty to make everything public. Perl removes my guilt. Likewise, an object provides methods, but you can ignore them and just access the underlying Perl data structure. This is another huge boost for debugging. Garbage collection via reference counting Although reference counting is a rather leak-prone form of memory management (it doesn't detect cycles), it has a few upsides. It gives you deterministic destruction of your objects, like in C++, and never interrupts your program with a surprise garbage collection. It strongly encourages module authors to use a tree-of-objects pattern, which I much prefer vs. the tangle-of-objects pattern often seen in Java and JavaScript. (I've found trees to be much more easily tested with unit tests.) But, if you need a tangle of objects, Perl does offer "weak" references, which won't be considered when deciding if it's time to garbage-collect something. On the whole, the only time this ever bites me is when making heavy use of closures for event-driven callbacks. It's easy to have an object hold a reference to an event handle holding a reference to a callback that references the containing object. Again, weak references solve this, but it's an extra thing to be aware of that JavaScript or Python don't make you worry about. Parallelism The Perl interpreter is a single thread, although modules written in C can use threads of their own internally, and Perl often includes support for multiple interpreters within the same process. Although this is a large limitation, knowing that a data structure will only ever be touched by one thread is nice, and it means you don't need locks when accessing them from C code. Even in Java, where locking is built into the syntax in convenient ways, it can be a real time sink to reason through all the ways that threads can interact (and especially annoying that they force you to deal with that in every GUI program you write). There are several event libraries available to assist in writing event-driven callback programs in the style of Node.js to avoid the need for threads. Access to C libraries Aside from directly writing your own C extensions via Perl's XS system, there are already lots of common C libraries wrapped for you and available on Perl's CPAN repository. There is also a great module, Inline::C, that takes most of the pain out of bridging between Perl and C, to the point where you just paste C code into the middle of a Perl module. (It compiles the first time you run it and caches the .so shared object file for subsequent runs.) You still need to learn some of the Perl interpreter API if you want to manipulate the Perl stack or pack/unpack Perl's variables other than your C function arguments and return value. Memory usage Perl can use a surprising amount of memory, especially if you make use of heavyweight libraries and create thousands of objects, but with the size of today's systems it usually doesn't matter. It also isn't much worse than other interpreted systems. My personal preference is to only use lightweight libraries, which also generally improve performance. Startup speed The Perl interpreter starts in under five milliseconds on modern hardware. If you take care to use only lightweight modules, you can use Perl for anything you might have used Bash for, like hotplug scripts. Regex implementation Perl provides the mother of all regex implementations... but you probably already knew that. Regular expressions are built into Perl's syntax rather than being an object-oriented or function-based API; this helps encourage their use for any text processing you might need to do. Ubiquity and stability Perl 5 is installed on just about every modern Unix system, and the CPAN module collection is extensive and easy to install. There's a production-quality module for almost any task, with solid test coverage and good documentation. Perl 5 has nearly complete backward compatibility across two decades of releases. The community has embraced this as well, so most of CPAN is pretty stable. There's even a crew of testers who run unit tests on all of CPAN on a regular basis to help detect breakage. The toolchain is also pretty solid. The documentation syntax (POD) is a little more verbose than I'd like, but it yields much more useful results than doxygen or Javadoc. You can run perldoc FILENAME to instantly see the documentation of the module you're writing. perldoc Module::Name shows you the specific documentation for the version of the module that you would load from your include path and can likewise show you the source code of that module without needing to browse deep into your filesystem. The testcase system (the prove command and Test Anything Protocol, or TAP) isn't specific to Perl and is extremely simple to work with (as opposed to unit testing based around language-specific object-oriented structure, or XML). Modules like Test::More make writing the test cases so easy that you can write a test suite in about the same time it would take to test your module once by hand. The testing effort barrier is so low that I've started using TAP and the POD documentation style for my non-Perl projects as well. In summary Perl 5 still has a lot to offer despite the large number of newer languages competing with it. The frontend syntax hasn't stopped evolving, and you can improve it however you like with custom modules. The Perl 5 engine is capable of handling most programming problems you can throw at it, and it is even suitable for low-level work as a "glue" layer on top of C libraries. Once you get really familiar with it, it can even be an environment for developing C code.
https://opensource.com/article/18/1/why-i-love-perl-5
CC-MAIN-2020-16
refinedweb
2,435
58.32
[Solved]Question about the example "Scene Graph - OpenGL Under QML" - stereomatching How could I apply the effect on a specific component? @ //! [1] import QtQuick 2.0 import OpenGLUnderQML 1.0 Item { width: 320 height: 480 //! [1] //! [2] Rectangle { color: Qt.rgba(1, 1, 1, 0.7) radius: 10 border.width: 1 border.color: "white" anchors.fill: label anchors.margins: -10 //apply the Squircle effect on the Rectangle rather than the root item Squircle { SequentialAnimation on t { NumberAnimation { to: 1; duration: 2500; easing.type: Easing.InQuad } NumberAnimation { to: 0; duration: 2500; easing.type: Easing.OutQuad } loops: Animation.Infinite running: true } } } } } //! [2] @ No matter how I try, it is always render on the background but not the Rectangle As the documentation and the description states, the Squircle is not a part of the items rendered by the scene graph. It is using raw OpenGL combined with the QQuickWindow::beforeRendering() signal. It renders itself beneath the entire Qt Quick scene. If you want to integrate raw GL inside the item scene, have a look at the textureinsgnode example (for integrating raw OpenGL calls using and FBO and a texture) or customgeometry and simplematerial example (for how to create a custom scenegraph node and material. - stereomatching bq. textureinsgnode example, customgeometry, simplematerial Can't find any example when I input those names in the example page of QtCreator, are you sure the names are correct? but I do found other interesting examples which may solve my problem "Scene Graph-Rendering" Have a look in the 5.1 qtdeclarative source tree: The "textureinsgnode" example was added for 5.1 but the others have been there since 5.0
https://forum.qt.io/topic/28726/solved-question-about-the-example-scene-graph-opengl-under-qml
CC-MAIN-2018-09
refinedweb
272
51.44
Not able to import remote javascript file in QML Hi, I have this import statement in my code but it doesn't seem to work. qmlscene exits with code 255 import "" as Browser the server is running locally on my machine and the url works fine in the browser. I do see a request being sent to my server and a response is sent back to qml too. enabling QML_IMPORT_TRACE does not show anything. What is the reason for this failure? do i need to configure something to allow this file to be downloaded? Thanks, Rohit How do i enable http thread debugging for this particular import request? Thanks, Rohit
https://forum.qt.io/topic/47298/not-able-to-import-remote-javascript-file-in-qml
CC-MAIN-2018-47
refinedweb
110
72.56
,. VPN best vpn provider in usa Opera Opera.,,.?,check Point also supports IPsec VPN and L2TP for client to site VPNs. StrongSwan, there are multiple 3rd party VPN clients best vpn provider in usa which are able to work with the Check Point Security Gateway. Openswan, you can use for example one from the SWAN family (FreeS/WAN,)and IPSec. PPTP, if your company has a private intranet best vpn provider in usa that you need access to while on the road, vPN client that supports L2TP, apple makes it easy to set up a. Best vpn provider in usa imdi, internet üzerindeki younluu azaltaca gibi, proxylerin, bu, bizlerin kulland alanda nasl best vpn provider in usa kullanldna bakalm; Güvenlik Amac ile Proxy Kullanm Proxyler, hz da arttracak ve ayn zamanda kullanclarn proxy sunucunun depolama (cache)) özelliinden faydalanmasn da salayacaktr. Proxy sunucusunun ayarlar ile ilgili olarak,wenn Sie keine der oben aufgeführten Verbindungen mit Ihrem best vpn provider in usa Rechner benutzen, wenn eine direkte PPPoP-Verbindung hergestellt werden soll für normal. Können Sie den Dienst deaktivieren. Bei DSL-Verbindungen wird der Dienst nur benötigt,for best performance, look for timestamp logging best vpn provider in usa thats limited to just the date of your connection and logging of server names and users rather than specific IP addresses. Does it have servers in the locations you need? this is for web browsers, best vpn provider in usa remote logins, tor Browser Bundle : This used to work wonderfully. It works in our university currently. And more. B. To download the Tor Browser Bundle Click Here. Instant messaging clients, this prevents anyone from learning your location kostenlose vpn android or browsing habits. A. Best vpn provider in usa EU: with a broad range best vpn provider in usa of encryption tunneling protocols, each of the listed VPN services is tested and is compatible on both S6 and S7. The below-listed VPN services will protect your Smartphone against most severe cyber-threat.S tä dt ische s k r a nk e nh aus m a ria - hil f in brilon smart quality speed comfort eco space der neue echelon smart (1,5t) besticht durch smartquality für eine hervorragende bildqualität dank hoch entwickelter technologien smartspeed verkürzt deutlich die untersuchungszeit smartcomfort für patientenfreundliche und leise untersuchungen smarteco ermöglicht einen. advanced threat prevention, check Point endpoint best vpn provider in usa security solutions include data security, network security, to simplify security administration, forensics and remote access VPN for complete endpoint protection. hotspot Baidu WiFi hotspot salah satu dari aplikasi rpi vpn bridge hotspot pc terbaik yang dimana baidu wifi hotspot ini merupakan aplikasi sharing WiFi freeware yang sangat ringan dan berjalan pada sistem operasi windows, best vpn provider in usa aplikasi yang dikembangkan oleh Baidu PC Faster ini menawarkan banyak kelebihan, baidu WiFi. Tun. ko : Samsung Galaxy Y - GT-S5360 Cherry Orbit / Gigabyte GSmart G1310. Samsung Galaxy Pro HTC T-Mobile MyTouch 3G Samsung Galaxy SII. M110S Samsung Galaxy S TUN. ko installer 1. , ROOT 2. , , tun. ko . 3. . tun. ko , . tun. ko: 1. , tun. ko . 2. Share tun. ko 3. . 20 thoughts on Unblock / Hack Cyberoam to Access the Blocked Sites hanellafraga says: Easy way to unblock with the help of some online tools that give you direct access without waste your time on searching the best proxy server sites only check these links for secure connection. Free the internet with Hotspot Shield for Windows with a 45-day money-back guarantee. peering is beneficial for three key reasons: it lessens the need for IP transit significantly reducing network costs, it increases redundancy and it improves network resiliency providing a better end best vpn provider in usa user experience. vPNs are really very useful services! Another advantage of using VPN services directly in Chrome is to overcome best vpn provider in usa the technical hurdles faced while configuring the VPN clients such as Open VPN, so, and here we present you the Best 7 Free VPN services (apps/extensions)) for Google Chrome Browser/Chromebooks i.e VPN for chrome OS.setting a password will be required. At the best vpn provider in usa first time if your login, this password is important for make you exclusive to login the administrator mode of the VPN Server. On the VPN Server Manager screen, double-click the "localhost" item on the servers list.3,513 Replies Dr Sebi describes how he was persecuted in a New York criminal court for announcing to the world that he cures Aids and Cancer. Sebi won his court case a. WINS, cRIMINAL, video Rating: 4 / 5 is Rick Simpsons personal website with much more information if best vpn provider in usa you want to research further or have questions not addressed in this. Dr. PROVING, tRIAL, yORK on. SEBI, this entry was posted in Cancer and tagged AIDS, cancer, cures, june 19,their logging policy is legit: None of your personal data is monitored or stored. Perfect-Privacy Unlimited Simultaneous best vpn provider in usa Connections (10.49/mo)) Ranks #3 out of 74 VPNs You know exactly what youre getting from a product called Perfect-Privacy. in the last decade, two best vpn provider in usa things have happened that affect almost everybody in the age groups north of third grade and south of assisted living. First, cellphones have become "personal data assistants" (PDAs)) such that one gets cisco packet tracer easy vpn used to receiving and sending e-mail,more than 500 VPN servers are located in 141 countries, this is definitely a bonus! An impressive collection! 5 Multi logins is a feature that allows up to 5 simultaneous connections in a single VPN account. Best vpn provider in usa which makes their VPN very reliable. And transparency. Properly cloaking our online activities at all times." Jul 28, security, also, too, known for speed, they do not keep logs, 2016 m is a well-known name in the best vpn provider in usa VPN industry, passed our privacy tests,estos son entregador por la compaa que best vpn provider in usa acta como proveedor del servicio. El software VPN es aquel que utilizas como medio para utilizar la red.e80.65 Check Point Remote Access VPN Clients for best vpn provider in usa Windows - Automatic Upgrade file. 2. Enterprise Endpoint Security R Server and E80.65 Client.it seems thats about to best vpn provider in usa change in Windows 8.1 with the introduction of the new b and stom namespaces. september 17, continue reading. G Suite's videoconferencing platform, and Hangouts Meet. A Slack-like platform for teams that finally launched out of beta earlier this year, which came about after Google revealed last year that it was splitting best vpn provider in usa the Hangouts platform into two core services: Hangouts Chat, the feature is being added to Hangouts Meet, 2018 Telepresence Options Google has announced that G Suite Enterprise subscribers will now be able to livestream meetings to up to 100,000 people across the company.windows IoT - Windows 10,., ioT - - -, best vpn provider in usa raspberry Pi 2 3.aggressive Mode - VPN and IPSec tutorial. Aggressive Mode. For a successful and secure best vpn provider in usa communication using IPSec, the IKE (Internet Key Exchange)) protocols takes part in a two step negotiation.you will only get access to your home region, best vpn provider in usa if you use a VPN to access another EU region, meaning that you will still watch your home region. As you travel to another EU country you will bring your Netflix region with you, # fastest vpn service 2018 excel High-Speed VPNVPN touch vpn gratuita e ilimitada pc for iOS 2018. w3.org/TR/xhtml1/DTD/xhtml1-transitional. Dtd" Resolve a DOI Name doi: Type or paste a DOI name into the text box. Send questions or comments to. DOI, dOI System Proxy Server Documentation, further documentation is available here. DOI. "http www. Your browser will take you to a Web page (URL)) associated with that DOI name. ORG, click Go. avast SecureLine VPN 2018 Box Avast SecureLine VPN exists in best vpn provider in usa several versions including a mobile one (both Android and iOS)) and multi-platform, but in this review, we will focus on the Windows desktop version of SecureLine.2011 at 1:37 a.m. By stretch Monday, the public Internet). Today we're going to look at. LAN-to-LAN VPNs are typically used to transparently connect geographically disparate LANs over an untrusted medium (e.g.) july 11, uTC. LAN-to-LAN VPNs using the pair of ASA 5505s in best vpn provider in usa the community lab. Here we'll see how to configure a simple L2L VPN as pictured in the below topology in a few simple steps. windows Version Mac Version Get Android App Google Play. Can't log in to Facebook, apk Download Android 4.x VpnTraffic. VpnTraffic. Netflix,Pandora)? Twitter or Blogspot? No access to TV free vpn russia mac websites in the USA (Hulu,) do you want to be anonymous on the Internet?
http://babyonboard.in/stream-sports/best-vpn-provider-in-usa.html
CC-MAIN-2019-26
refinedweb
1,518
60.75
. It is a common misconception that the less code you need to achieve something, the better the API. Keep in mind that code is written more than once but has to be understood over and over again. For example, QSlider *slider = new QSlider(12, 18, 3, 13, Qt::Vertical, 0, "volume"); is much harder to read (and even to write) than QSlider *slider = new QSlider(Qt::Vertical); slider->setRange(12, 18); slider->setPageStep(3); slider->setValue(13); slider->setObjectName("volume"); Boolean parameters often lead to unreadable code. In particular, it's almost invariably a mistake to add a bool parameter to an existing function. In Qt, the traditional example is repaint(), which takes an optional bool parameter specifying whether the background should be erased (the default) or not. This leads to code such as widget->repaint(false); which beginners might read as meaning, "Don't repaint!" The thinking is apparently that the bool parameter saves one function, thus helping reducing the bloat. In truth, it adds bloat; how many Qt users know by heart what each of the next three lines does? widget->repaint(); widget->repaint(true); widget->repaint(false); A somewhat better API might have been widget->repaint(); widget->repaintWithoutErasing(); In Qt 4, we solved the problem by simply removing the possibility of repainting without erasing the widget. Qt 4's native support for double buffering made this feature obsolete. Here come a few more examples: widget->setSizePolicy(QSizePolicy::Fixed, QSizePolicy::Expanding, true); textEdit->insert("Where's Waldo?", true, true, false); QRegExp rx("moc_*.c??", false, true); An obvious solution is to replace the bool parameters with enum types. This is what we've done in Qt 4 with case sensitivity in QString. Compare: str.replace("%USER%", user, false); // Qt 3 str.replace("%USER%", user, Qt::CaseInsensitive); // Qt 4, you'll find that the similarity of APIs makes this replacement very easy. This is what we call "static polymorphism". Static polymorphism also makes it easier to memorize APIs and programming patterns. As a consequence, a similar API for a set of related classes is sometimes better than perfect individual APIs for each class. Naming is probably the single most important issue when designing an API. What should the classes be called? What should the member functions be called? A few rules apply equally well to all kinds of names. First, as I mentioned earlier, do not abbreviate. Even obvious abbreviations such as "prev" for "previous" don't pay off in the long run, because the user must remember which words are abbreviated. Things naturally get worse if the API itself is inconsistent; for example, Qt 3 has activatePreviousWindow() and fetchPrev(). Sticking to the "no abbreviation" rule makes it simpler to create consistent APIs. Another important but more subtle rule when designing classes is that you should try to keep the namespace for subclasses clean. In Qt 3, this principle wasn't always followed. To illustrate this, we will take the example of a QToolButton. If you call name(), caption(), text(), or textLabel() on a QToolButton in Qt 3, what do you expect? Just try playing around with a QToolButton in Qt Designer: Identify groups of classes instead of finding the perfect name for each individual class. For example, All the Qt 4 model-aware item view classes are suffixed with View (QListView, QTableView, and QTreeView), and the corresponding item-based classes are suffixed with Widget instead (QListWidget, QTableWidget, and QTreeWidget). offers a template class QFlags<T>, where T is the enum type. For convenience, Qt provides typedefs for the flag type names, so you can type Qt::Alignment instead of QFlags<Qt::AlignmentFlag>. By convention, we give the enum type a singular name (since it can only hold one flag at a time) and the "flags" type a plural name. For example: enum RectangleEdge { LeftEdge, RightEdge, ... }; typedef QFlags<RectangleEdge> RectangleEdges; In some cases, the "flags" type has a singular name. In that case, the enum type is suffixed with Flag: enum AlignmentFlag { AlignLeft, AlignTop, ... }; typedef QFlags<AlignmentFlag> Alignment; The number one rule of function naming is that it should be clear from the name whether the function has side-effects or not. In Qt 3, the const function QString::simplifyWhiteSpace() violated this rule, since it returned a QString instead of modifying the string on which it is called, as the name suggests. In Qt 4, the function has been renamed QString::simplified(). Parameter names are an important source of information to the programmer, even though they don't show up in the code that uses the API. Since modern IDEs show them while the programmer is writing code, it's worthwhile to give decent names to parameters in the header files and to use the same names in the documentation. Finding good names for the getter and setter of a bool property is always a special pain. Should the getter be called checked() or isChecked()? scrollBarsEnabled() or areScrollBarEnabled()? In Qt 4, we used the following guidelines for naming the getter function: Which is best for out-parameters, pointers or references? void getHsv(int *h, int *s, int *v) const void getHsv(int &h, int &s, int &v) const Most C++ books recommend references whenever possible, according to the general perception that references are "safer and nicer" than pointers. In contrast, at Trolltech, we tend to prefer pointers because they make the user code more readable. Compare: color.getHsv(&h, &s, &v); color.getHsv(h, s, v); Only the first line makes it clear that there's a high probability that h, s, and v will be modified by the function call. To show some of these concepts in practice, we'll study the QProgressBar API of Qt 3 and compare it to the Qt 4 API. In Qt 3: class QProgressBar : public QWidget { ... public: int totalSteps() const; int progress() const; const QString &progressString() const; bool percentageVisible() const; void setPercentageVisible(bool); void setCenterIndicator(bool on); bool centerIndicator() const; void setIndicatorFollowsStyle(bool); bool indicatorFollowsStyle() const; public slots: void reset(); virtual void setTotalSteps(int totalSteps); virtual void setProgress(int progress); void setProgress(int progress, int totalSteps); protected: virtual bool setIndicator(QString &progressStr, int progress, int totalSteps); ... }; The API is quite complex and inconsistent; for example, it's not clear from the naming that reset(), setTotalSteps(), and setProgress() are tightly related. The key to improve the API is to notice that QProgressBar is similar to Qt 4's QAbstractSpinBox class and its subclasses, QSpinBox, QSlider and QDial. The solution? Replace progress and totalSteps with minimum, maximum and value. Add a valueChanged() signal. Add a setRange() convenience function. The next observation is that progressString, percentage and indicator really refer to one thing: the text that is shown on the progress bar. Usually the text is a percentage, but it can be set to anything using the setIndicator() function. Here's the new API: virtual QString text() const; void setTextVisible(bool visible); bool isTextVisible() const; By default, the text is a percentage indicator. This can be changed by reimplementing text(). The setCenterIndicator() and setIndicatorFollowsStyle() functions in the Qt 3 API are two functions that influence alignment. They can advantageously be replaced by one function, setAlignment(): void setAlignment(Qt::Alignment alignment); If the programmer doesn't call setAlignment(), the alignment is chosen based on the style. For Motif-based styles, the text is shown centered; for other styles, it is shown on the right hand side. Here's the improved QProgressBar API: class QProgressBar : public QWidget { ... public: void setMinimum(int minimum); int minimum() const; void setMaximum(int maximum); int maximum() const; void setRange(int minimum, int maximum); int value() const; virtual QString text() const; void setTextVisible(bool visible); bool isTextVisible() const; Qt::Alignment alignment() const; void setAlignment(Qt::Alignment alignment); public slots: void reset(); void setValue(int value); signals: void valueChanged(int value); ... }; APIs need quality assurance. The first revision is never right; you must test it. Make use cases by looking at code which uses this API and verify that the code is readable. Other tricks include having somebody else use the API with or without documentation and documenting the class (both the class overview and the individual functions). Documenting is also a good way of finding good names when you get stuck: just try to document the item (class, function, enum value, etc.) and use your first sentence as inspiration. If you cannot find a precise name, this is often a sign that the item shouldn't exist. If everything else fails and you are convinced that the concept makes sense, invent a new name. This is, after all, how "widget", "event", "focus", and "buddy" came to be.
https://doc.qt.io/archives/qq/qq13-apis.html
CC-MAIN-2019-13
refinedweb
1,434
54.02
01 November 2011 08:04 [Source: ICIS news] LONDON (ICIS)--DSM remains confident that the Netherlands-based company is on track to achieve its earnings before interest, tax, depreciation and amortisation (EBITDA) target of €1.4bn-1.6bn ($1.9bn-2.2bn) in 2013, it said on Tuesday. “Our outlook remains unchanged: 2011 is expected to be a strong year with further progress towards achieving our 2013 targets,” said Feike Sijbesma, CEO and chairman of the DSM managing board. “However, DSM remains vigilant to possible negative developments in the global economy. [Through the third quarter] we have experienced weakening in the electronics and electrical markets and in the depressed building and construction markets,” he added. Sijbesma said DSM would not be immune to deterioration in the economic environment, but added that the company had become a more balanced one with a strong presence in high-growth economies, especially ?xml:namespace> Earlier on Tuesday, DSM announced that its third-quarter net profit after exceptional items soared to €171m from €79m in the same period last year, partially helped by strong earnings from its Materials Sciences and Polymer Intermediates clusters. Its total net sales from continuing operations in the third quarter of 2011 rose to €2.32bn, up by 14% from the same period last year, on the back of strong sales across all its business segments DSM’s total operating profit from continuing operations in the three months ended 30 September rose by 37% year on year to €231m. “We are pleased to have delivered continued profitable growth compared to last year across all business clusters. This performance has been achieved despite the significant impact of a very strong Swiss franc and a weak US dollar,” said Sijbesma. DSM’s Performance Materials cluster reported sales of €711m, up 7% year on year, mainly due to price rises at its engineering plastics and resins businesses. The group’s Polymer Intermediates segment achieved sales of €473m, a growth of 39% compared with the third quarter of 2010. DSM said that volumes were higher compared with last year as a result of yield improvements in operations in both caprolactam and acrylonitrile (ACN) and a maintenance shutdown in Sales in the group’s Nutrition business in the third quarter increased by 16% to €868m over the same period last year, due to an organic sales growth of 8%, DSM said. Its total net profit after exceptional items for the first nine months of 2011 more than doubled to €729m from €358m in the same period last year and its net sales from continuing operations rose by 12% year on year to €6.82bn. (
http://www.icis.com/Articles/2011/11/01/9504285/dsm-confident-of-hitting-2013-ebitda-target-of-1.4bn-1.6bn.html
CC-MAIN-2014-15
refinedweb
438
51.52
How Feature Engineering Can Help You Do Well in a Kaggle Competition – Part 3 http likes 92 In this last post of the series, I describe how I used more powerful machine learning algorithms for the click prediction problem as well as the ensembling techniques that took me up to the 19th position on the leaderboard (top 2%) By Gabriel Moreira, CI&T. In the first and second parts of this series, I introduced the Outbrain Click Prediction machine learning competition and my initial tasks to tackle the challenge. I presented the main techniques used for exploratory data analysis, feature engineering, cross-validation strategy and modeling of baseline predictors using basic statistics and machine learning. In this last post of the series, I describe how I used more powerful machine learning algorithms for the click prediction problem as well as the ensembling techniques that took me up to the 19th position on the leaderboard (top 2%). Follow-the-Regularized-Leader One of the popular approaches for CTR Prediction is Logistic Regression with a Follow-the-Regularized-Leader (FTRL) optimizer, which have been used in production by Google to predict billions of events per day, using a correspondingly large feature space. It is a linear model with a lazy representation of the coefficients (weights) and, in conjunction with L1 regularization, it leads to very sparse coefficient vectors. This sparsity property shrinks memory usage, making it scalable for feature vectors with billions of dimensions, because each instance will typically have only a few hundreds of nonzero values. FTRL provides efficient training on large datasets by streaming examples from disk or over the network — each training example only needs to be processed once (online learning). I tried two different FTRL implementations, available in Kaggler and Vowpal Wabbit (VW) frameworks. For CTR prediction, it is important to understand the interactions between the features. For example, the average conversion of an ad from “Nike” advertiser might be very different, depending on the publisher that is displaying the ad (e.g. ESPN vs. Vogue). I considered all categorical features for models trained on Kaggler FTRL. The feature interactions option was enabled, meaning that for all possible two-paired feature combinations, feature values were multiplied and hashed (read about Feature Hashing in the first post) to a position in a sparse feature vector with dimension of 2²⁸. This was my slowest model and the training time took more than 12 hours. But my LB score jumped to 0.67659 for this Approach #6. I also tried FTRL on VW, which is a very fast and efficient framework in the usage of CPU and memory resources. The input data was again categorical features, with the addition of some selected numeric binned features (read about Feature Binning in the first post). My best model was trained in two hours and lead to a LB score of 0.67512 in this Approach #7. The accuracy was a little bit lower, but much faster than the previous model. In a second FTRL model on VW, I used a VW hyperparameter to configure interactions (feature pairing) of only a subset of features (namespace). In this case, interactions paired only categorical features and some selected numeric features (without binning transformation). That change lead to a better mode in this Approach #8: 0.67697. All those three FTRL models were ensembled for my final submissions, as we’ll describe in next sections. Field-aware Factorization Machines A recent variant of Factorization Machines, named Field-aware Factorization Machines (FFM) was used in winning solutions for two CTR prediction competitions in 2014. FFM tries to model feature interactions by learning latent factors for each features interaction pair. This algorithm was made available as the LibFFM framework and used by many competitors. LibFFM makes a very efficient usage of parallel processing and memory for large datasets. In the Approach #9, I used categorical features with paired-interactions hashed to a dimensionality of 700,000. My best model took me only 37 minutes to train and it turned out to be my best single model, with a LB score of 0.67932. In Approach #10, the input data contained some selected binned numeric features in addition to categorical features. Training data increased to 214 minutes, and LB score was 0.67841. For Approach #11, I tried to train a FFM model considering only the last 30% of events of the training set, under the hypothesis that training on the last days could improve the prediction of the next two days (50%) of test set. The LB score was 0.6736, increasing accuracy for those two last days, but decreasing accuracy for previous events of test set. In Machine Learning projects it is not rare that some promising approaches end up failing miserably. That happened with some FFM models. I tried to transfer learning from a GBDT model to a FFM model with leaf encoding, a winning approach in a Criteo competition. However, the FFM model accuracy dropped, probably because the GBDT model was not accurate enough in this context, adding more noise than signal. Another unsuccessful approach was to train separate FFM models, specific for geographic regions with more events in test dataset, like some countries (US ~ 80%, CA ~ 5%, GB ~ 5%, AU ~ 2%, Others ~ 8%) and U.S. states (CA ~ 10%, TX ~ 7%, FL ~ 5%, NY ~ 5%). To generate predictions, each event of test set was sent to the model specialized on those region. Models specialized to the U.S. performed well predicting clicks for that region, but for other regions the accuracy was lower. Thus, using world-wide FFM models performed better. The three selected FFM approaches were used in my final ensemble, as I show next. Ensembling methods Ensembling methods consist of combining predictions from different models to increase accuracy and generalization. The less correlated models' predictions are, the better the ensemble accuracy may be. The main idea behind ensembling is that individual models are influenced not only by signal, but also by random noise. Taking a diverse set of models and by combining their predictions, considerable noise may be cancelled, leading to better model generalization, like shown below. From the competition Don’t overfit A simple, yet powerful, ensembling approach is to merge models predictions by averaging. For this competition, I tested many types of weighted averages types like Arithmetic, Geometric, Harmonic and Ranking averages, among others. The best approach I could find was to use a Weighted Arithmetic Average of the logit (inverse of sigmoidal logistic) of predicted CTR (probabilities), shown in Equation 1. It considered predictions of the three selected FFM models (Approaches #9, #10, and #11) as well as one the FTRL models (Approach #6). Such averaging gave me a LB score of 0.68418 for this Approach #12, a nice jump from my best single model (Approach #10, with a score of 0.67932). Equation 1 — Ensembling by Weighted Average of logit of models predictions At that time, competition submission deadline was only a few days away. My choice for the remaining time was to ensemble using a Learning-to-Rank model to merge up best models predictions. That model was a GBDT with 100 trees and ranking objective using XGBoost. This ensemble considered as input features the best 3 FFM and 3 FTRL model predictions as well as 15 selected engineered numeric features (like user views count, user preference similarity and average CTR by categories). That ensemble layer was trained only using validation set data (described in the second post), in a setting named Blending. The reason for that approach is that if predictions for train set were also considered by ensemble model, it would prioritize more overfitted models, reducing its ability to generalize for the test set. In the last competition day, Approach #13 gave me my best Public LB score (0.68688). The competition then finished, my Private LB Score was revealed (0.68716) and kept me at 19th position in the final leaderboard, as illustrated below. Kaggle’s Outbrain Click Prediction final leaderboard I have not tracked the exact submission days, but the graph below gives a sense of how my LB scores evolved during the competition. It can be seen that first submissions provided nice jumps on the score, but improving upon that became harder, which is quite common in machine learning projects. LB scores for my approaches during competition Conclusions Some of the things I learned from this competition were: - A good Cross-Validation strategy is essential for competing. - One should spend a good chunk of time in feature engineering. Adding new features on datasets afterwards requires much more effort and time. - Hashing is a must for sparse data. In fact, it performed better than One-Hot Encoding (OHE) in terms of simplicity and efficient. - OHE categorical features were not optimal for decision trees ensembles. Based on competitors shared experiences, tree ensembles could perform better with original categorical values (ids) with enough trees, because it would reduce feature vectors to a much lower dimensionality, increasing the chance that the random feature sets contained more predictive features. - Testing many different frameworks is great for learning, but usually takes tons of time to transform data to the required format, read documentation and tune hyperparameters. - Reading scientific papers about the main techniques (FTRL and FFM) were essential for guidance on hyperparameter tuning. - Studying forums posts, public Kernels (shared code) and past solutions shared by competitors was great way to learn and is essential for competing. Everyone should share something back! - Ensembling based on average improves accuracy a lot, blending with ML models leverages the bar, and stacking is a must. I had not time to explore stacking, but according to other competitors, using out-of-fold predictions on fixed folds increases the available data for ensemble training (full train set) and improves final ensemble accuracy. - One shouldn't leave generating one's submission files until the final hours of the competition! Kaggle is like a university for cutting-edge machine learning, for those who decide to embrace the challenges and learn from the process and peers. It was a highly engaging experience to compete against and learn from world-class data scientists. Google Cloud Platform was a great hiking partner during that journey, providing all the necessary climbing tools to overcome cliffs of big data and distributed computing, while my focus and effort was directed to get to the top of the mountain.:
https://www.kdnuggets.com/2017/07/feature-engineering-help-kaggle-competition-3.html
CC-MAIN-2020-24
refinedweb
1,736
51.18
This tutorial will teach you how to use Python to analyze millions of rows of Baltimore City parking ticket data. More specifically, we will be using a Python package called pandas. It is not humanly possible to comprehend a dataset with millions of rows. That’s why we will use the data analysis tool pandas to help us gain some insights into our dataset. If you have never used pandas before, don’t sweat it. I’ll walk you through all the fundamentals that you need to start crunching your own datasets. Baltimore City Parking Ticket Data Below is a preview of the data that we will be working with in this tutorial. I created this dataset based on publicly available data through Baltimore’s Open Data website. The dataset used in this tutorial can be downloaded as a CSV file from the dropdown menu of the table below. Note that the CSV file is a few hundred megabytes in size. I stumbled upon this dataset after I got my very own Baltimore City parking citation. I used to crunch large financial datasets on a daily basis as a software engineer at a hedge fund, so I figured that I’d do an analysis on parking tickets in Baltimore and see how much money the city was pulling in from these fines. Getting Setup with Python and Pandas I’ll assume that you have a recent version of Python installed on your machine, but if you don’t, you can learn how to install virtualenv with Python 3. The first thing you’ll want to do is install the pandas package. We’ll do that with the pip package manager. In a terminal, type the following. pip install pandas That’s it! You now have pandas installed. If you haven’t already done so, download the Baltimore_City_Parking_Tickets.csv file from the Export tab. Place this file in your home directory. Finally, let’s hop into a Python interpreter in your terminal from your home directory. Simply type python into your terminal window. python Reading a CSV File with Pandas The pandas Python package makes it super easy to work with delimited datasets such as CSV files. To read our CSV file, we will use the read_csv function. import pandas as pd df = pd.read_csv('Baltimore_City_Parking_Tickets.csv') We now have a variable called df with a chronological integer index that holds over 1 million rows and 7 columns of parking tickets from Baltimore City. We called our variable df which is short for dataframe. This is common practice when working with pandas. You can think of a dataframe as an Excel-like spreadsheet object. You can see a preview of the data by typing the name of the df variable into your Python interpreter. Examine your dataframe by accessing some of these properties and methods. df df.columns df.head() df.tail() This is a very simple way to quickly read a CSV file, but this is a very dumb way to read a CSV file. Right now, every cell in our dataframe is an object. In other words, Python doesn’t know that our dates are actually dates or that our fines are actually numbers. Additionally, we want to use violation date column as our index. Ultimately, we want a sorted DateTimeIndex in order to do time series analysis. Let’s reread our CSV file into memory, but this time, be smarter about it. index_col = 'ViolDate' dtype = {'Description':str, 'ViolFine':float, 'Address':str, 'Citation':str, 'Tag':str, 'State':str} df = pd.read_csv('Baltimore_City_Parking_Tickets.csv', index_col=index_col, dtype=dtype) df.index = pd.to_datetime(df.index, format='%m/%d/%Y %I:%M:%S %p') df = df.sort_index() Now we have a dataframe with a DateTimeIndex, over 1 million rows, and 6 typed columns. Perfect! Baltimore City Parking Ticket Statistics with Python and Pandas We are ready to start analyzing this dataset! There’s a lot of insight we can gain from this data. Let’s walk through a few examples. How Much Money Does Baltimore Make From Parking Tickets? You’re probably wondering, as was I, how much money Baltimore is pulling in from parking tickets. We can easily find this answer by using the sum aggregate function. df['ViolFine'].sum() As you’ll see, Baltimore City made a staggering $123,391,897 from parking tickets over the course of two years. How Much Money Does Baltimore Make From Speed Cameras? Speed cameras seem to be around every corner in Baltimore. You’re probably in the minority if you live in Baltimore and have never received a speed camera ticket. All joking aside, to find out how much Baltimore has made from speed camera tickets, we first need to only consider rows with a description of ‘Fixed Speed Camera’. df['Description'] == 'Fixed Speed Camera' As you’ll see, this just returns True or False if that row matches ‘Fixed Speed Camera’. We need to use this boolean series to index into our dataframe and subset only those rows with a value of True. df[df['Description'] == 'Fixed Speed Camera'] Perfect. You’ll see right away that Baltimore issued 498,840 speed camera tickets over the course of these two years. This is already an staggering insight. Moving on though, let’s use sum like we did before to get the total dollar amount. df[df['Description'] == 'Fixed Speed Camera']['ViolFine'].sum() Wow! Baltimore City issued $19,953,600 in speed camera tickets between October 5, 2016 and October 5, 2018. It’s worth noting at this point that you don’t have to chain the Python code on a single line. You can also create intermediate variables if that helps you understand these concepts better. The following code is identical to above and will yield the same result. speed_camera_df = df['Description'] == 'Fixed Speed Camera' speed_camera_viol_fine_df = df[speed_camera_df]['ViolFine'] speed_camera_viol_fine_df.sum() How Much Money Does Baltimore Make From Each Type of Ticket? Now that we know Baltimore City is pulling in nearly $20 million over the course of two years from speed camera tickets alone, how much are they making from other types of tickets? We can determine this with a single line of code. df.groupby('Description')['ViolFine'].sum().sort_values(ascending=False) This might seem complicated, but let’s take it one function at a time from left to right. First, we use groupby to essentially put all the same violation descriptions into the same bucket. Then we sum all the violation fines in each bucket. Finally, we sort by descending order so that the larger fines appear first. What we end up with is the following table, which shocked me, and will probably shock you too. Remember that these numbers are over the course of two years… but still. Baltimore City Ticket Revenue by Violation The second most popular ticket in Baltimore is the red light violation ticket. I would have to guess that, similar to the speed cameras, these red light violations are the automatic ones that you see fixed to a pole at intersections. The type of ticket that I got this year was “Obstruct/Impeding Movement of Pedestrian” which brought in nearly a cool million bucks over two years. What is Baltimore’s Monthly Ticket Revenue? After knowing how much Baltimore City is making for each type of ticket, let’s find out how much Baltimore City is making on tickets every month. We can resample the data on a monthly basis (i.e. ‘M’) and aggregate this result with a sum like before. Resampling on a daily basis with ‘D’ and yearly basis with ‘Y’ are also valid arguments. df['ViolFine'].resample('M').sum() This yields a dataframe with 25 rows, one for each month between October 5, 2016 and October 5, 2018. Notice that the first and last row are the relatively smaller because these October months are only partial months. Baltimore City Ticket Revenue by Month You’ll quickly see that Baltimore is making well over $1 million dollars each and every month from tickets and in some cases over $5 million dollars in a single month. Which Month Did Baltimore City Issue the Most Tickets? Now that we know how much money Baltimore is making off of ticket for each month, we can easily find out which month saw the most revenue by using max. df['ViolFine'].resample('M').sum().max() Baltimore issued a record $5,002,747 of tickets in July 2018. Mind blowing! Final Thoughts I’m sure by now you see the power of the Python package pandas. We were able to effortlessly comb through millions of rows of Baltimore City parking ticket data and gain many insights that would be very hard to conclude from manually examining the raw data by hand. For more tutorials like this, check out some of my other Python blog posts. As a resident of Baltimore for 10 years, all of the insights that we derived from the data were surprising to me. If nothing else, I hope that this tutorial helped you better understand how to use pandas to do basic data analysis on large datasets. Let me know in the comments below what your thoughts are about the insights that we gained from the data or if you were able to find out anything else interesting about this Baltimore City parking ticket dataset. Keep on crunching that data!
https://tonyteaches.tech/baltimore-city-parking-tickets-analysis/
CC-MAIN-2021-31
refinedweb
1,565
64.2
Mark Wielaard wrote: * NEWS, java/lang/Thread.java, vm/reference/java/lang/VMThread.java: treat Thread.sleep(0) like Thread.yield() for JDK compatibility, and add a non-native implementation of VMThread.sleep().Could you try to follow the "Documenting what changed when with ChangeLog entries" section in the GNU Classpath hacker guide That makes the entries look more the same and makes it easier to quickly grep for specific methods and class changes. I'll send an example in my next email. Thanks, I'll fix that. Maybe you could explain to the person that controls this that you send email to public mailinglists which are read by an unknown number of people. And ask that it is not added automatically for such outgoing email. Or that people can add a flag to their headers indicating which emails are and which aren't "confidential" so that the text is only added to relevant emails. Sure thing. It never hurts to ask. Because that's what the JDK does.As explained that isn't a real argument. We would have to install and check all kinds of jdks to confirm this. And since a lot of them (at least those from sun, ibm, bea, etc) are proprietary that isn't really an option. To everyone on the list: please come to agreement about whether Thread.sleep(0) should throw InterruptedException or just be equivalent to Thread.yield() (personally, I'm happy either way). Then I will make the changes as necessary. E.g., watch the output of this program: public class zz extends Thread { private final int num; public zz(int num) { this.num = num; } public void run() { try { System.out.println("thread " + num); Thread.sleep(0); System.out.println("thread " + num); Thread.sleep(0); System.out.println("thread " + num); Thread.sleep(0); } catch (Exception e) { throw new RuntimeException(e); } } public static void main(String[] args) throws Exception { new zz(1).start(); new zz(2).start(); new zz(3).start(); } }Could you send the expected and actual output of the jdk you are using? There is no "expected" output because it's a nondeterministic program. I'm just using this program as empirical evidence (but not proof) that the JDK treats Thread.sleep(0) as a yield. On my 1 CPU machine, this is the output: thread 1 thread 2 thread 3 thread 1 thread 2 thread 3 thread 1 thread 2 thread 3 If you comment out the Thread.sleep()'s, then you get this: thread 1 thread 1 thread 1 thread 2 thread 2 thread 2 thread 3 thread 3 thread 3 These results are consistent with, and highly suggestive of, the theory that the VM is treating Thread.sleep(0) like Thread.yield(). It is just that I find the particular interpretation of Thread.sleep(0) calls Thread.yield() suspicious since Thread.yield() isn't even guaranteed to change control to any particular other thread. And with SMP systems even then you aren't guaranteed to one or another particular thread makes or doesn't make progress before another thread. Right. By the same argument, there is nothing incompatible about a VM callling Thread.yield() after every instruction execution. The only thing really at issue here from the point of view of "spec correctness" is whether Thread.sleep(0) can throw InterruptedException. Your argument is that some programs might depend on sleep(0) to act like yield() to escape from tight loops? Are there actually such programs. And wouldn't you just consider them buggy? I would. I'm not arguing anything like that. I'm just saying: all things being equal, behaving more consistently with the JDK (unfortunately, our current de facto standard) is preferable. -Archie __________________________________________________________________________ Archie Cobbs * CTO, Awarix *
http://lists.gnu.org/archive/html/classpath-patches/2005-01/msg00005.html
CC-MAIN-2015-11
refinedweb
625
68.57
In the previous part of this series we learned the basics of creating a Ruby gem. We created an initial directory structure, defined a gemspec, installed dependencies, and started to write the actual code. Today, we are going to continue creating the Ruby gem and, specifically, we will take care of the testing suite. You will learn how to setup RSpec, create a Rails dummy application, define and test generator tasks, and how to test Rake tasks. Also, we will integrate your code with Travis CI and Codecov services. Sound good? Then let’s get started! - Setting up the testing suite - Configuration options: Tests - Installation task (Rails generator) - Rake tasks - Integrating with Travis CI and Codecov - Conclusion First part of the series: lokalise.com/blog/create-a-ruby-gem-basics Third part of the series: lokalise.com/blog/how-to-create-a-ruby-gem-publishing Setting up the testing suite Adding development dependencies So, first of all let’s add some more development dependencies into the gemspec file, like so: Gem::Specification.new do |spec| spec.add_development_dependency 'codecov', '~> 0.1' spec.add_development_dependency 'dotenv', '~> 2.5' spec.add_development_dependency 'rails', '~> 6.0.3' spec.add_development_dependency 'rake', '~> 13.0' spec.add_development_dependency 'rspec', '~> 3.6' spec.add_development_dependency 'rspec-rails', '~> 4.0' # rubocop dependencies... spec.add_development_dependency 'simplecov', '~> 0.16' spec.add_development_dependency 'vcr', '~> 6.0' end - Codecov is an integration for the Codecov.io service which displays test coverage results in a fancy way. We will return to it later. - Dotenv allows us to set environment variables ( ENV) using the values inside a separate file. In our case these variables will contain the Lokalise API token and project ID. - We will employ Rails to run a dummy application. - Rake can be used to run certain tasks. - RSpec is our TDD framework. Of course, you can stick to Minitest, but I really love RSpec which seems more expressive to me. - Simplecov will allow us to measure code coverage for the testing suite. - VCR is a tool to record interactions with third-party services within special files (called cassettes) and replay them during subsequent test runs. This allows us to use pre-recorded fixture data instead of sending real requests every time. Don’t forget to run: bundle i before proceeding to the next section. Creating a Rails dummy application We will require a special “dummy” Rails app that will be used to test various features of our gem. This dummy will reside inside the spec/ folder. It should load only the bare minimum as we will not need features like ActionCable, ActiveJob, Spring, etc. Actually, we won’t even require ActiveRecord. Here are the commands to generate the app: mkdir spec cd spec rails new dummy --skip-spring --skip-listen --skip-bootsnap --skip-action-text --skip-active-storage --skip-action-cable --skip-action-mailer --skip-action-mailbox --skip-test --skip-system-test --skip-active-job --skip-active-record --skip-javascript Once the above command succeeds, open the spec/dummy/config/application.rb file and remove the following line: config.load_defaults 6.0 We don’t need it because later I would like to run the testing suite using both Rails 5 and 6. Remove the Gemfile and Gemfile.lock from the spec/dummy folder because we will employ the Gemfile which resides in the project root. Open the spec/dummy/config/boot.rb file and replace its contents with the following: ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../../Gemfile', __dir__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) $LOAD_PATH.unshift File.expand_path('../../../lib', __dir__) This way we are pointing the Rails app toward the proper Gemfile. Let’s also add a tzinfo-data gem that should be loaded for Windows and JRuby users. Add the following to the Gemfile: # ... group :test do gem 'tzinfo-data', platforms: %i[mingw mswin x64_mingw jruby] end Setting up RSpec Next, create a new spec/spec_helper.rb file with the following contents: require 'dotenv/load' # <============= 1 require 'simplecov' SimpleCov.start 'rails' do # <============= 2 add_filter 'spec/' add_filter '.github/' add_filter 'lib/generators/templates/' add_filter 'lib/lokalise_rails/version' end if ENV['CI'] == 'true' # <============= 3 require 'codecov' SimpleCov.formatter = SimpleCov::Formatter::Codecov end Dir["#{File.dirname(__FILE__)}/support/**/*.rb"].sort.each { |f| require f } # <============= 4 ENV['RAILS_ENV'] = 'test' # <============= 5 require_relative '../spec/dummy/config/environment' # <============= 6 ENV['RAILS_ROOT'] ||= "#{File.dirname(__FILE__)}../../../spec/dummy" # <============= 7 - Load ENV variables using Dotenv. The contents for these variables will be hosted inside the .envfile (we’ll create it a bit later). - Start to measure code coverage for our testing suite. I’ve also provided some folders to ignore. - If the testing suite runs on a continuous integration service (like Travis CI), the coverage data should then be sent to Codecov.io. - Load support files from the spec/supportdirectory. We’ll also create this directory later. - We are loading the Rails dummy app using “test” environment. - Load the environment.rbfile to boot the dummy app. - Set the Rails root. Now let’s also create a .rspec file inside the project root (outside of the spec/ folder). This file contains the RSpec options: --color --require spec_helper --order rand --format doc - Test results should be printed in color. - The spec_helper.rbfile loads automatically. - The order of the tests is random. - The output formatter is doc. Setting ENV variables The next step is to provide values for the ENV variables. These variables, as you already know, are set by the Dotenv gem. So, create an .env file inside the project root: LOKALISE_API_TOKEN=123abc LOKALISE_PROJECT_ID=456.def Replace these sample values with the proper ones. Make sure to add this file to .gitignore. We have already done so in the previous part, but I’ll provide the .gitignore contents again just in case: *.gem coverage/* Gemfile.lock *~ .bundle .rvmrc log/* measurement/* pkg/* .DS_Store .env spec/dummy/tmp/* spec/dummy/log/*.log Remember that the .env file must not be tracked by Git because otherwise your API token will be exposed! Finally, create the .env.sample file which will provide sample contents: LOKALISE_API_TOKEN=123abc LOKALISE_PROJECT_ID=456.def Developers will then copy-paste this file as .env on their local machines and replace the sample contents with the real values. Adding Rake tasks Let’s also add RSpec-related Rake tasks to the Rakefile. Here’s the new version of this file: require 'rake' begin require 'bundler/setup' Bundler::GemHelper.install_tasks rescue LoadError puts 'although not required, bundler is recommended for running the tests' end task default: :spec require 'rspec/core/rake_task' RSpec::Core::RakeTask.new(:spec) require 'rubocop/rake_task' RuboCop::RakeTask.new do |task| task.requires << 'rubocop-performance' task.requires << 'rubocop-rspec' end Configuration options: Tests Testing config method Okay, so at this point we are ready to write some tests! In the previous part we provided some config options for our gem ( api_token, locales_path, and others). Therefore, let’s make sure that it is possible to adjust these options. Create a new spec/lib/lokalise_rails_spec.rb file: describe LokaliseRails do it 'is possible to provide config options' do described_class.config do |c| expect(c).to eq(described_class) end end end This test makes sure that when the config method is run, the LokaliseRails module is passed properly. This allows us to provide config in the following way: LokaliseRails.config do |c| c.api_token = '123' end Now change directory to the root of your project and run: rspec . This command will run all the tests inside the spec/ directory. Testing mandatory options Next, I would like to add a couple of tests for the mandatory options, namely the project_id and api_token. Specifically, we need to make sure that these options can be provided using the corresponding writers. However, I would like these tests to be isolated — in other words, they should not change the real config which will be loaded by the test dummy Rails app later. Therefore, let’s take advantage of a class double and create a fake class: describe LokaliseRails do # ... describe 'parameters' do let(:fake_class) { class_double('LokaliseRails') } end end Now provide the test case, like so: describe LokaliseRails do # ... describe 'parameters' do let(:fake_class) { class_double('LokaliseRails') } it 'is possible to set project_id' do expect(fake_class).to receive(:project_id=).with('123.abc') fake_class.project_id = '123.abc' end end end So, we are expecting the fake class to receive a writer method with the proper argument. Then we are actually calling this method. This test will pass if the project_id= writer method was actually provided for the LokaliseRails module. To avoid false positives, let’s start by making this test fail (the “red” phase, as some devs would say). Open the lib/lokalise_rails.rb file and remove the project_id accessor: module LokaliseRails class << self attr_accessor :api_token # remove project_id # ... other code... end end Now run rspec . and you’ll see the following output: Randomized with seed 7575 LokaliseRails is possible to provide config options parameters is possible to set project_id (FAILED - 1) Failures: 1) LokaliseRails parameters is possible to set project_id Failure/Error: expect(fake_class).to receive(:project_id=).with('123.abc') the LokaliseRails class does not implement the class method: project_id= # ./spec/lib/lokalise_rails_spec.rb:12:in `block (3 levels) in <top (required)>' Finished in 0.058 seconds (files took 6.06 seconds to load) 2 examples, 1 failure Failed examples: rspec ./spec/lib/lokalise_rails_spec.rb:11 # LokaliseRails parameters is possible to set project_id Great! This means our test actually does its job. Now add the project_id to the list of accessors to make the test pass (“green” phase): module LokaliseRails class << self attr_accessor :api_token, :project_id end end Run rspec . again. Here’s the result: Randomized with seed 3205 LokaliseRails is possible to provide config options parameters is possible to set project_id Finished in 0.055 seconds (files took 6.07 seconds to load) 2 examples, 0 failures Randomized with seed 3205 Coverage report generated for RSpec to f:/rails/lokalise/lokalise_rails/coverage. 12 / 18 LOC (66.67%) covered. Note that we also can see the test coverage percentage. To learn more about the test coverage, open the coverage/index.html file in your favorite browser. This provides detailed information for each monitored file line by line. Now, using the same approach we can add the test for the api_token= method: describe LokaliseRails do # ... describe 'parameters' do let(:fake_class) { class_double('LokaliseRails') } # ... it 'is possible to set api_token' do expect(fake_class).to receive(:api_token=).with('abc') fake_class.api_token = 'abc' end end end While we could also test the reader methods, it is not really necessary: they will be tested implicitly in other specs. Therefore, let’s take care of other methods. Testing other options Use the below approach to test other options: describe LokaliseRails do describe 'parameters' do # ... it 'is possible to set file_ext_regexp' do expect(fake_class).to receive(:file_ext_regexp=).with(Regexp.new('.*')) fake_class.file_ext_regexp = Regexp.new('.*') end it 'is possible to set import_opts' do expect(fake_class).to receive(:import_opts=).with(duck_type(:each)) fake_class.import_opts = { format: 'json', indentation: '8sp' } end it 'is possible to set export_opts' do expect(fake_class).to receive(:export_opts=).with(duck_type(:each)) fake_class.export_opts = { convert_placeholders: true, detect_icu_plurals: true } end it 'is possible to set import_safe_mode' do expect(fake_class).to receive(:import_safe_mode=).with(true) fake_class.import_safe_mode = true end it 'is possible to override locales_path' do expect(fake_class).to receive(:locales_path=).with('/demo/path') fake_class.locales_path = '/demo/path' end it 'is possible to set skip_file_export' do cond = ->(f) { f.nil? } expect(fake_class).to receive(:skip_file_export=).with(cond) fake_class.skip_file_export = cond end end end Nice! Installation task (Rails generator) So, we have created basic unit tests for the gem options. To adjust these options, the user should create a config/lokalise_rails.rb with the following content: LokaliseRails.config do |c| c.api_token = '123' c.project_id = '345.abc' # ... other options end While we may instruct the user to create this file manually, it’s not very convenient. What I would like to do is introduce a command like rails g lokalise_rails:install that creates the configuration file containing the list of all supported options and usage instructions. To achieve this, we need to define a special generator to run the installation task. Creating the generator Our generator will live under the lib folder, therefore create the following path: lib/generators/lokalise_rails/install_generator.rb. This new file should contain the following code: require 'rails/generators' module LokaliseRails module Generators class InstallGenerator < Rails::Generators::Base source_root File.expand_path('../templates', __dir__) desc 'Creates a LokaliseRails config file.' def copy_config template 'lokalise_rails_config.rb', "#{Rails.root}/config/lokalise_rails.rb" end end end end This code will simply take the template lokalise_rails_config.rb from the ..templates/ directory and copy-paste it to the config/ folder of the Rails app. The target file will be named lokalise_rails.rb. You can find additional explanations for these methods in the official documentation. Next we’ll need a template to copy, thus create a new path: lib/generators/templates/lokalise_rails_config.rb. This is the file that will be copied in the user’s application: require 'lokalise_rails' LokaliseRails') } # Regular expression to use when choosing the files to extract from the downloaded archive and upload to Lokalise # c.file_ext_regexp = /\.ya?ml\z/i end We provide explanations for each option, which makes the lives of our users a bit easier. Now let’s add some tests for our new installation task. Testing the installation task Create a new spec/lib/generators/lokalise_rails/install_generator_spec.rb file. Our test case will be very simple because we only need to make sure that running the given task results in creating the proper file. To run the task programmatically, you can call the start method: require 'generators/lokalise_rails/install_generator' describe LokaliseRails::Generators::InstallGenerator do it 'installs config file properly' do described_class.start expect(File.file?(config_file)).to be true end end config_file is a helper method that is going to return path to the lokalise_rails.rb configuration file. Such methods are usually defined in the support folder. Therefore, create a new spec/support/file_manager.rb file: module FileManager def config_file "#{Rails.root}/config/lokalise_rails.rb" end end We also need to include this module in our tests, so adjust the spec/spec_helper.rb file in the following way: # ... other code ... RSpec.configure do |config| config.include FileManager end Now you can run the rspec . command and observe test results. The lokalise_rails.rb file should be created inside the config/ folder of your dummy Rails app. The problem, however, is that we are not doing any cleanup after running this test. In other words, the created config file is not being removed afterwards. Also, it might be a good idea to try and remove the config before running the test to make it isolated. This problem can be easily solved with before and after hooks: require 'generators/lokalise_rails/install_generator' describe LokaliseRails::Generators::InstallGenerator do before :all do remove_config end after :all do remove_config end # your test... end remove_config is also a helper method that we can define inside the support/file_manager.rb file: require 'fileutils' module FileManager def remove_config FileUtils.remove_file config_file if File.file?(config_file) end end Note that I’m utilizing the remove_file method provided by the FileUtils module. This method allows us to delete a file by providing full path to it. Don’t forget to import the FileUtils module before using it. And that’s it: our installation task is done! Rake tasks Creating and registering a Rails task with railtie The next step is to define and register two Rake tasks that the user will run to export or import translation files. These tasks will reside inside the lib/tasks/lokalise_rails_tasks.rake, for instance: require 'rake' require "#{Rails.root}/config/lokalise_rails" # <======= 1 namespace :lokalise_rails do task :import do # <======= 2 LokaliseRails::TaskDefinition::Importer.import! end task :export do # <======= 3 LokaliseRails::TaskDefinition::Exporter.export! end end - Before running the tasks, we are trying to load the config file. This file is created by the installation task we added a minute ago. - To call this task, one should write rails lokalise_rails:import. The task delegates all work to the import!method which we are going to create later. - Use the rails lokalise_rails:exportcommand to run this task. We must register these tasks before using them. To register a task, you need to create a railtie — a block of code that extends Rails core functionality. We are going to place our railtie inside the lib/lokalise_rails/railtie.rb file: module LokaliseRails class Railtie < Rails::Railtie rake_tasks do load 'tasks/lokalise_rails_tasks.rake' end end end We also need to load this railtie inside the lib/lokalise_rails.rb file and make sure that the Rails framework is loaded: require 'lokalise_rails/railtie' if defined?(Rails) module LokaliseRails # ... options here ... end Rake task definitions So, we’ve created the tasks, but all the heavy lifting will be done by the import! and export! methods, therefore let’s draft them now. Start by creating a new lib/lokalise_rails/task_definition/base.rb file. This file will host a base class. The import and export task will inherit from it: module LokaliseRails module TaskDefinition class Base end end end Now create a lib/lokalise_rails/task_definition/importer.rb file: module LokaliseRails module TaskDefinition class Importer < Base class << self def import! $stdout.print 'Task complete!' true end end end end end We’ll take care of the actual implementation later. Note that I’m explicitly using the $stdout variable to print the success message. This is required for our testing purposes. Finally, create a lib/lokalise_rails/task_definition/exporter.rb file: module LokaliseRails module TaskDefinition class Exporter < Base class << self def export! $stdout.print 'Task complete!' true end end end end end It’s not much, but I’d like to create a minimal setup required to make the tests pass. Load these three files inside the lib/lokalise_rails.rb file: require 'lokalise_rails/task_definition/base' require 'lokalise_rails/task_definition/importer' require 'lokalise_rails/task_definition/exporter' require 'lokalise_rails/railtie' if defined?(Rails) module LokaliseRails # ... options ... end Now we can proceed to testing our Rake tasks. Testing Rake tasks First and foremost, we need to load the available Rake tasks in the spec/spec_helper.rb before running them programmatically. Add the following line to the bottom of the spec_helper.rb file: # ... other code Rails.application.load_tasks Create a new spec/lib/tasks/import_task_spec.rb file. What should we test for? Well, the import task should output the success message to STDOUT if is everything is okay. This can be tested using the following code snippet: expect(import_task_call_here).to output(/complete!/).to_stdout Thing is, this expectation requires a callable object (lambda or procedure). To run a Rake task programmatically, you can use the following approach: Rake::Task['lokalise_rails:import'].execute Which means that the expectation transforms to the this: expect(-> { Rake::Task['lokalise_rails:import'].execute }).to output(/complete!/).to_stdout This construct is pretty complex, so let’s create a new support file: spec/support/rake_utils.rb with the following content: module RakeUtils def import_executor -> { Rake::Task['lokalise_rails:import'].execute } end def export_executor -> { Rake::Task['lokalise_rails:export'].execute } end end These methods return callable objects to run import and export tasks. Include this module inside the spec/spec_helper.rb: # ... other code RSpec.configure do |config| config.include FileManager config.include RakeUtils # <======= end Rails.application.load_tasks Now, create a new test case inside the import_task_spec.rb file: RSpec.describe LokaliseRails do it 'import rake task is callable' do expect(import_executor).to output(/complete!/).to_stdout end end Also, add another spec/lib/tasks/export_task_spec.rb file: RSpec.describe LokaliseRails do it 'runs export rake task properly' do expect(export_executor).to output(/complete!/).to_stdout end end The tests are ready but there’s one problem. Our Rake tasks try to load the config/lokalise_rails.rb file containing the config options. This means that this file has to be created before running all the tests. Let’s take care of this issue now. Creating a sample config file Open the spec/support/file_manager.rb file and add a new method: require 'fileutils' module FileManager def add_config data = <<~DATA require 'lokalise_rails' LokaliseRails.config do |c| c.api_token = ENV['LOKALISE_API_TOKEN'] c.project_id = ENV['LOKALISE_PROJECT_ID'] end DATA File.open(config_file, 'w+:UTF-8') do |f| f.write data end end # ... other methods... end This method will create a new config file with the required options. I’m using heredoc to provide the file contents. Now tweak the spec/spec_helper.rb in the following way: # ... other code include FileManager add_config Rails.application.load_tasks We are creating our configuration file before any test is run. Problem is, the test for the installation task removes the config inside the after hook. Therefore, let’s re-create the config by tweaking the spec/lib/generators/lokalise_rails/install_generator_spec.rb, for instance: require 'generators/lokalise_rails/install_generator' describe LokaliseRails::Generators::InstallGenerator do before :all do remove_config end after :all do remove_config add_config # <========== end # ... end Now you may run the rspec . command and observe the test results! Integrating with Travis CI and Codecov Before wrapping up this article, I also wanted to show how to integrate your plugin with Travis CI and Codecov services. Travis CI is a continuous integration service that specifically allows you to run your test suite using different versions of Ruby and Rails. It also enables us to deploy the code automatically to the target server. Codecov, in turn, monitors test coverage and displays results in a beautiful way. Setting up Travis CI To get started, create a new repository on GitHub (Bitbucket or GitLab). Next, open travis-ci.org and sign up using your GitHub account (it’s free for open source projects). Then click on your avatar in the top right corner and open ‘Settings’. Click ‘Sync account’ to load the available repositories. After the sync is done, find your new repository in the list and enable it by toggling the switch next to its name. Click ‘Settings’ next to your repository and find the ‘Environment variables’ section. Create LOKALISE_API_TOKEN and LOKALISE_PROJECT_ID variables with the proper values. The values won’t be shown in the logs so you’re safe. Now we need to create a new .travis.yml file in the root of your project: language: ruby rvm: - 2.5.8 - 2.6.6 - 2.7.1 install: bundle install --retry=3 before_install: - gem update bundler env: - 'TEST_RAILS_VERSION="~> 5.1.6"' - 'TEST_RAILS_VERSION="~> 5.2.3"' - 'TEST_RAILS_VERSION="~> 6.0.3"' We are instructing it to use Ruby language and run the testing suite with Ruby 2.5.8, 2.6.6, and 2.7.1. Also, I would like to use different versions of Rails for testing. To properly install these Rails versions, update the gemspec, like so: if ENV['TEST_RAILS_VERSION'].nil? spec.add_development_dependency 'rails', '~> 6.0.3' else spec.add_development_dependency 'rails', ENV['TEST_RAILS_VERSION'].to_s end So, on Travis CI we’ll use three different Rails versions to run the tests. Locally you’ll utilize Rails 6.0.x only. Setting up Codecov Navigate to codecov.io and sign up with your GitHub account (this service is free for open source projects). After signing up, click on your account name and search for your new repository. Basically, this is it: no additional configuration is needed as we’ve already added Codecov-related code to the spec_helper.rb file. At this point we are ready to get rolling. Commit your changes and push them to GitHub (make sure that the spec/dummy folder does not have its own .git directory!). Return to Travis CI and open the ‘Current’ tab for your repository. You will see something like this: So, the tests are being run for every Ruby and Rails version we’ve specified. To get more information on any job, click on the specific build. After all tests have passed, return to Codecov and update the page. You’ll see the code coverage results: You can find detailed information by clicking on the lib folder and proceeding to individual files. Codecov provides more insights (especially when you have added more commits), so make sure to browse other tabs. Badges We can also add fancy-looking badges to the README of our gem. These badges will display test coverage and the results of the most recent test run. To do that, add the following contents to the README.md: []() []() Make sure to replace USERNAME with your name (in my case that’s bodrovis) and REPO_NAME with the name of your repository ( lokalise_rails in my case). Commit the changes and push to GitHub: git add . git commit -am "added badges [skip ci]" git push Note the [skip ci] part of the commit message. It makes sure that Travis CI does not re-run all the tests again because we have not modified any codebase. Return to your GitHub repo and check out your cool new badges: Conclusion That’s it for today, guys. In this article we have seen how to create a Ruby gem and introduce a testing functionality. We have created a new generator, two Rake tasks, added tests for them, and integrated our repository with Travis CI and Codecov. Not bad, eh? In the next part of this series we will flesh out the gem and see how to test third-party APIs and work with ZIP files. See you really soon! Proceed to the third part
https://lokalise.com/blog/how-to-create-a-ruby-gem-testing-suite/
CC-MAIN-2022-05
refinedweb
4,185
51.85
More, Vivo X21, LG G7, Huawei P20 or Asus Zenfone 5. Similar to the iPhone X, Apple’s new iPad Pro model, the iPad X, will also include a notch and feature Face ID. . As a native iOS and Android developer, you will experience similar issues yourself when you start to develop for devices with edge-to-edge screens. For iOS, Apple even requires you to support iOS 11 and the notch: All new apps & app updates submitted after July 2018 get rejected otherwise. So we put up our sleeves and prepared this guide to show you how to support the notch in your apps. Thus the sooner you start following this guide the better you are prepared for the Apple change coming in July and for upcoming Android P changes. The tips provided in this guide apply for both iOS and Android and are useful for cross-platform developers as well. Along the way, we also modified all the components in Felgo, a cross-platform framework for app & game development. It now supports the notch out-of-the-box, so you don’t need to go through this „notch hell“ yourself. 🙂 Here we go! We hope you enjoy the „Ultimate Guide to Survive the Notch“: - User Interface Challenges of Devices with Edge-to-Edge Displays - How to Create iPhone X Apps with Xcode - Android P Developer Preview: Display Cutouts - Save Time and Effort with Felgo Engine for Mobile Apps - More Free App Developer Resources - The Best App Development Tutorials & Free App Templates - App Development Video Tutorials User Interface Challenges of Devices with Edge-to-Edge Displays Many manufacturers already announced new models with edge-to-edge screens, which became even more popular after the release of the iPhone X: Such screens allow to get the most out of the available space the device offers. In addition to the rounded edges, there is a main pain point for mobile app developers: the notch. Instead of a clear rectangular frame, app developers now face arbitrary shaped screens. Also, hardware buttons at the front no longer exist. They got replaced by on-screen buttons and gestures provided by the OS. The following sections describe how to create adaptive layouts to handle those challenges for both iOS & Android. While this post uses examples for iPhone X, the same concepts and suggested solutions also apply for other devices & platforms with similar screens, like upcoming Android P devices. Bigger Screen Size and Safe Area of iPhone X For the iPhone X, the new screen holds two major factors to account for in your mobile app: - The screen is bigger in general, so there’s more space your app can use. - Your app content should not cover areas with a notch or native on-screen buttons. Otherwise, the elements you place at these parts of the screen are not accessible. To support different device models and screens, most apps use a responsive layout. This means that the pages use the full height and width to show as much content as possible. This is a good thing. But if the notch and reserved areas are not taken into consideration, some parts of your app are covered or inaccessible. In the example screenshots shown above for the iPhone X, the notch covers the top navigation bar in portrait mode and your page content, the list item text, in landscape mode. For both orientations, the area for the home swipe gesture overlays your app at the bottom. Also note that the new screen comes with rounded corners. To solve this problem, your app needs to consider the safe area of the screen. It is the part of your app, which won’t be covered by the notch or on-screen gestures. The required top and bottom screen insets determine the safe area in portrait mode: For example, the navigation bar requires more padding at the top to be within the safe area. In landscape mode it looks a bit different. We then require margins to the left and right (for the rounded corners and the notch), as well as a small inset at the bottom (for the home swipe gesture): How Do Existing Apps Look on iPhone X? If you are worrying that your published app is already affected by the notch, you can relax. Only apps configured to target iPhone X will run full-screen. Your existing iOS apps will come with black borders as shown on the right in this image, to not overlay areas with a notch or screen gestures: The disadvantages are that the borders do not look good and the app does not match the style of other iPhone X apps – your user’s will realize this and your app will get a worse rating. The black border fallback is simply a backwards compatibility feature by Apple to not break anything. However, it also means some work for us app developers to support the new screen. How to Create iPhone X Apps with Xcode Enable iPhone X Support for Your App Unless your app enables support for iPhone X, it will show with black borders by default. This also means, that your existing apps won’t be affected by the notch. However, if you want to fully support iPhone X and let your app fill the whole screen, you need to add an additional launch image for the iPhone X resolution in Xcode: Add one image with 2436 x 1125 pixels for landscape mode, and one with 1125 x 2436 pixels if you want to support portrait. Position Your Content to the Safe Area Layout Guide Many iOS apps use a navigation bar at the top and a tab bar at the bottom. With iOS 7, Apple decided to add the topLayoutGuide and bottomLayoutGuide properties, which match the insets for these bars in the view. Developers can thus align their content to match these insets. For iPhone X, it is not enough to only take care of the top and bottom margins. We also have insets to the left and right of the screen, e.g. when in landscape mode. So Apple introduced the new safeAreaLayoutGuide property with iOS 11. The top and bottom layout guides are now deprecated. To make sure your content isn’t covered by the notch, position it to the safe area layout guide. Similar to the previous top and bottom layout guides, this can be done with constraints. But this simple solution is still far from perfect. Especially in landscape mode, constraining your content area can leave some ugly margins. To avoid this, you can instead add custom insets to your content only where necessary. The new safeAreaInsets property gives access to the exact pixel inset for the safe area. You can thus tweak the layout to look exactly as you want. For example, you can design the cells of your list items to account for the safe area with a bigger indent. The view content can then cover the whole screen. How to Migrate Existing Native iOS Apps to work with Safe Area Insets To make updating your apps a bit easier, you have the option to activate the Use Safe Area Layout Guides setting for each of your Storyboards in Xcode. The Storyboard then replaces the top and bottom layout guides with a safe area and updates the constraints. This is a quick first measure to get your app ready for iPhone X. But as mentioned above, you will still need to check all your views to provide the best possible user experience. For example, to: - Let the background of a sub-view use the full screen while keeping the content safe. - Decide how to handle the insets when flicking a UIScrollView. - Set up your UITableView or UICollectionView to correctly layout for iPhone X. Also, you might not be happy with the result of the default Use Safe Area Layout Guides setting in case your app hides the system status bar: Due to a bug within the latest iOS 11 SDK, the navigation bar does not account for the notch in this case. Except for some workarounds, there is no simple solution for this issue at the moment of writing this guide. At least when relying on native iOS development with Xcode. Android P Developer Preview: Display Cutouts Many Android phone manufacturers already announced their upcoming device models with edge-to-edge displays and rounded corners. For example: Google also already released the developer preview for Android P. It comes with the ability to handle these so-called display cutouts. In the iOS world, display cutout is equivalent to notch. How to Test Apps with Display Cutout in Android P The Android P Developer Preview allows simulation of display cutout. Android P is available with the SDK Manager of Android Studio. It is sufficient to install the Android P SDK and System Image to test on a virtual Android P device: After installation is complete, you can start an emulator running Android P. The developer settings on Android P offer four different display cutout options to choose from: After selecting this option, the Android device will show with a bigger status bar that also includes a display cutout: The layoutInDisplayCutoutMode attribute controls how the window is laid out if there is a display cutout. By default your Android P app never extends into cutout areas – with a single exception. As visible on the image above, your app can safely cover the full screen for cutouts that do not exceed the status bar area. Note: The window will lose this ability to extend into the cutout area when FLAG_FULLSCREEN or SYSTEM_UI_FLAG_FULLSCREEN is set. To let your app always take advantage of the full screen, you can set the value LAYOUT_IN_DISPLAY_CUTOUT_MODE_ALWAYS. You are then responsible to keep your app content within the safe area of the screen. For example, when the device is in landscape mode or if the cutout exceeds the status bar in portrait. Custom Layouts with Safe Area Insets in Android P Like iOS 11, Android P includes features to determine the safe area of the screen and work with the given insets. The new DisplayCutout class lets you find out the location and shape of the non-functional areas where content shouldn’t be displayed. To determine the existence and placement of the cutouts areas, use the getDisplayCutout() method. You can then access the following fields for the DisplayCutout: - getSafeInsetBottom() – Returns the bottom safe area inset of the screen. - getSafeInsetLeft() – Returns the left safe area inset of the screen.. - getSafeInsetRight() – Returns the right safe area inset of the screen.. - getSafeInsetTop() – Returns the top safe area inset of the screen.. - getBoundingRects() – Returns a list of Rect objects that describe non-functional areas of the screen. Overall it means quite some work to let your app layout adapt to these new displays. Especially for developers that target both iOS and Android. Save Time and Effort with Felgo Engine for Mobile Apps Create iOS and Android Apps that Support The Notches and Display Cutouts Felgo Engine focuses on making mobile app development easy. And it also supports the iPhone X notch and Android P devices with display cutouts out-of-the-box. You can write your app once, and build for iOS, Android or even Desktop with a single button press from 1 IDE. The source code is 100% shared across all platforms. Felgo builds upon C++ & Qt and utilizes QML & JavaScript. QML is a fast and easy-to-use declarative UI language. With only a few lines of code, it is possible to create native iOS and Android apps that look native on every device: import Felgo 3.0 import QtQuick 2.0 App { // adds tab navigation (iOS) or drawer menu (Android) Navigation { // first tab NavigationItem { icon: IconType.home title: "Main" // main page NavigationStack { Page { title: "Main" Rectangle { anchors.fill: parent // Rectangle fills whole Page color: "lightgreen" AppText { anchors.centerIn: parent // AppText is centered on Page text: "Safe Area" } } } } } // second tab NavigationItem { icon: IconType.gears title: "Settings" // settings page NavigationStack { Page { title: "Settings" } } } } } This is how the above example app looks like on an iPhone X: The used components like Navigation and NavigationStack are prepared to work with safe area insets: They automatically include extra margins for the tab and navigation bar if required. In contrast to the native iOS SDK it is also possible to hide the status bar without any issues. You can do this by setting a single property in your code: import Felgo 3.0 import QtQuick 2.0 App { onInitTheme: { Theme.colors.statusBarStyle = Theme.colors.statusBarStyleHidden } // main page NavigationStack { Page { title: "Main" AppButton { anchors.horizontalCenter: parent.horizontalCenter text: "Toggle Status Bar" onClicked: { if(Theme.statusBarStyle !== Theme.colors.statusBarStyleHidden) Theme.colors.statusBarStyle = Theme.colors.statusBarStyleHidden else Theme.colors.statusBarStyle = Theme.colors.statusBarStyleBlack } } } } } The top navigation bar in Felgo always supports the notch automatically, even with a hidden status bar. Like the Use Safe Area Layout Guide setting for Xcode Storyboards, the content of your pages does not overlap reserved areas of the screen. But Felgo requires no extra setting to achieve this. The page content aligns with the safe area out-of-the box. For devices without a notch, the app does not show any extra margins or insets: Note: Configure iPhone X launch images for your iOS app to get full-screen support on iPhone X if you have an existing Felgo app. For new apps, this is set up automatically. Optimize your User Interface with Adaptive Layouts For most use cases, the default settings are fine to let your app look good on devices with and without display cutouts. If you want more control over how to display your content, you can disable the useSafeArea setting of each Page. You then have two options to work with the safe area: - Configure only certain content items within the Page to align with the safe area. - Retrieve the exact safe area inset of the screen and layout items as required. The following example deactivates the useSafeArea setting and shows both options: import Felgo 3.0 import QtQuick 2.0 App { Page { useSafeArea: false // the page content can use all available space // fill whole page/screen with blue color (background) Rectangle { anchors.fill: parent color: "lightblue" } // Option 1: fill only safe area with green color (content) Rectangle { anchors.fill: parent.safeArea color: "lightgreen" } // Option 2: adaptive background to cover top inset area (or status bar area on devices without insets) Rectangle { width: parent.width height: nativeUtils.safeAreaInsets.top > 0 ? nativeUtils.safeAreaInsets.top : nativeUtils.statusBarHeight() color: "yellow" } } } The page content can now cover the full screen by default. You can use the safeArea property of the Page to align items with the safe area of the screen. In the above example, we use this to fill the safe area with a green rectangle. This is where you can place your content items. The nativeUtils.safeAreaInsets hold the exact safe area insets of the screen in pixels. Devices without a notch do not have any insets and thus return 0. For iPhone X, the yellow rectangle will cover the top inset, which includes the status bar. To also support older devices, you fill the status bar if no inset is returned by nativeUtils.safeAreaInsets.top. The available safeAreaInsets properties are: - nativeUtils.safeAreaInsets.top - nativeUtils.safeAreaInsets.right - nativeUtils.safeAreaInsets.bottom - nativeUtils.safeAreaInsets.left Running this app on iOS or Android produces the following result: Developing adaptive user interfaces this way is very convenient. The following example shows how you could use nativeUtils.safeAreaInsets.left to add more indent for the cells of a list. import Felgo 3.0 import QtQuick 2.0 App { NavigationStack { ListPage { title: "List Page" useSafeArea: false // the page fills all available space model: 50 // quick way to populate the list with 50 items // UI for cells of the list delegate: SimpleRow { text: "Item #"+index // set indent of the cells // matches the safe area inset or minimum 16 dp (if no inset required, e.g. in portrait mode or on older devices) style.indent: Math.max(nativeUtils.safeAreaInsets.left, dp(16)) } } } } With such simple additions, you can make sure that your app looks pixel-perfect on screens with and without safe area insets. You don’t need to add such tweaks for apps that offer the default UI with a navigation bar and tab bar. The Felgo page and navigation components look good on all devices and adapt their style automatically. Support for Display Cutout on Android P Devices Felgo Engine is a cross-platform development tool that supports both Android and iOS. You can take the QML code of your iOS app and directly build for Android, or vice-versa. All components change their look and behavior then. They match the native style and user experience of the given platform: The above image shows the Android and iOS style for the same example app. The Android style is already prepared to support edge-to-edge screens. No extra work is required, to make your app work cross-platform for iOS & Android with display cutouts, safe area and a notch! Simulate Safe Area Insets while Developing on Desktop It takes quite some time to always build and deploy to your phone or the simulator. With Felgo you can run and test your app directly on Desktop. It is even possible to simulate different devices and resolutions to see how your app will look like. You can change the resolution at runtime, without having to restart your app. This is a huge time-saver for UI development & testing! Native development for Android or iOS requires deployment to another real or virtual device to test the UI. Along with the support for a display notch, Felgo also comes with a new resolution simulator entry for iPhone X. And the best thing is: It even covers the safe area insets you get on a real device: Felgo Engine is thus a huge time-saver when developing for iOS and Android. The Felgo SDK is free to use, so make sure to check it out! If you enjoyed this post, please leave a comment or share it on Facebook or Twitter. More Relevant App Development Resources - How to Create Mobile Games for Devices with Safe Areas like iPhone X - How to support multiple screen sizes & screen densities – Responsive App Guide - Guide for App Layout - Guide for App Navigation - iPhone X Human Interface Guidelines - iOS Documentation: Positioning Content Relative to the Safe Area - Safe Area Development Guide for iOS - Layout Guide, Margins, Insets and Safe Area demystified on iOS 10 & 11 - Android P Documentation: Display Cutout Support - Exploring Android P Display Cutouts Thanks for reading & scrolling that far! 🙂 Do you have suggestions for posts or tutorials about app development? Simply send us a message which tutorial you’d like to see here. More Posts Like This How to Make Cross-Platform Mobile Apps with Qt – Felgo Apps Release 2.16.0: iPhone X Support and Runtime Screen Orientation Changes How to Expose a Qt C++ Class with Signals and Slots to QML
https://felgo.com/cross-platform-app-development/notch-developer-guide-ios-android
CC-MAIN-2019-39
refinedweb
3,173
61.36
02 June 2009 16:00 [Source: ICIS news] LONDON (ICIS news)--BioDiesel International (BDI) has been commissioned to build a 100,000 tonne/year biodiesel plant for BioDiesel Amsterdam, the Austria-based plant builder said on Tuesday. The €31m ($44m) facility would be built in the ?xml:namespace> BDI said the plant would utilise a mixed feedstock of used cooking oil and animal fats. The project would be part of a “future-oriented energy park” in the port, which would also include a biogas plant for converting the by-products of biodiesel production into heat and electricity. BioDiesel Amsterdam is part of Greenmills, a joint initiative which uses waste flows from various processes as raw materials to produce biofuels and 'green' power. (
http://www.icis.com/Articles/2009/06/02/9221583/bdi-wins-contract-to-build-amsterdam-biodiesel-plant.html
CC-MAIN-2014-23
refinedweb
122
56.79
Someone ask me how I work with PL/SQL, here it is...It was created only for my own usage and tailored for it, so don't ask too much... Notes:-It was only tested on Windows, so it will probably not work out of the box on other OS. But it could probably work.-The syntax def. come from somewhere on internet and was slightly updated by myself.-I work with scripts (.sql) that contains more than one 'create or replace' instance.-It hijack the Build system to modify the output of it. This way standard error navigation (f4/shift+f4) should work.-It use sqlplus.exe from Oracle (must be on path).-The menu of Build come from Sublime Text 2\Packages\OracleSQL\oracle_functions.py and have to be updated for your need (a settings will be better, maybe next time ?): class OracleExecuteListCommand(sublime_plugin.WindowCommand): instance_list = "MASTER COMPANY", "DEVELOP/DEVELOP@DEV1252A"], "MASTER PCS", "PCS/PCS@DEV1252A"], "10.02 COMPANY", "DEMO_MAS_F/DEMO_MAS_F@T1002U"], "10.01 COMPANY", "MAS_F/MAS_F@T4001U"]] Good luck.SublimeOracleSQL.zip (12.4 KB) Hi, I'm trying this script with Sublime Text 2 on Ubuntu 12.04 and it's great!!!thanks a lot. I am surprised that it works 'out of the box', the binary for sqlplus is called "sqlplus.exe" on Linux too ?I think I changed a few things in the past months. If I have some times, I will push everything on github. Hey, is there a github or bitbucket for this yet? I'm just mucking around on github and can't find anything there. If it stays like that, I want to start sharing any changes I make. Would that be okay? I'll just have to link the repo back to this forum post, which is suboptimal. Feel free to change whatever you want and send Pull request, or Fork it. As I already wrote in this topic, I only tested it on Windows. Hi, When I'm using this, sometimes when i build, if it doesn't compile or has warnings it does not give me the error messages and it doesn't update the database. Instead, it just goes [Finished in 0.2s]. On good times, it will give me the error and the line it is on and f4 error navigation works. When running PL/SQL anonymous blocks that doesn't have an error it'll return my query results and display. Filename: C:\temp\test2.sql AND TYPE || ' ' || NAME in () *ERROR at line 4:ORA-00936: missing expression [Finished in 0.3s] Are these known issues and is there a fix for them? This has been bugging me for a while as well so finally I took a look into the code. It happens when there isn't a create or replace statement in the file. I was able to fix the problem by changing the following code in oracle_exec.py: Before: sqlfilter = '"' + ",".join("'%s'" % entity for entity in self.entities.keys()) + '"' After: if len(self.entities) == 0: sqlfilter = "\"''\"" else: sqlfilter = '"' + ",".join("'%s'" % entity for entity in self.entities.keys()) + '"' I'll make a pull request with the change on github.... gist.github.com/jbjornson/8704419 I'd happy to create a patch to bizoo with a version that works on both ST2 and ST3 but I'm not sure how to handle the different import between the two versions: On ST2: execmod = __import__("exec") On ST3: from Default import exec as execmod Anyone know how to handle both those import cases? You'll also need to update oracle_commands.py as well for ST3 compatibility. oracle_exec.pygist.github.com/jbjornson/8704419 oracle_commands.pygist.github.com/jbjornson/8704545 As exec is a statement in Python 2 (so ST2), I think the only way to manage it is with a conditional import (if) based on the sublime.version().I asked jps to rename the exec.py file long time ago, but he refused. I am no longer interested in maintaining ST packages, if someone want to "carry the torch"...I've merged the Pull requests but without testing anything. In addition, it looks like some forks are better than the original, like: Someone has already published a Oracle PL/SQL package: it looks like a simple copy of tmBundle that only support syntax.
https://forum.sublimetext.com/t/oracle-pl-sql/4091/12
CC-MAIN-2016-36
refinedweb
716
68.36
In case I want any class inherits/implements some methods which is better an interface or an abstract class contains these abstract methods only and acts as an interface. I know the difference between the interface and the abstract class well but in this case do the two have the same function or there are different something? I think we can feel free to use one of them but still I take the side of interface because my aim is to enforce any class to implement these methods and it is the job of interface. I agree an abstract class with no concrete behavior seems a little pointless so I would favour an interface. Abstract classes are far more useful when bringing together some common behavior that cannot be overridden along with some elements that can eg) template methods public abstract class Base { public void TemplateMethod() { AbstractMethod1(); AbstractMethod2(); } public abstract void AbstractMethod1(); public abstract void AbstractMethod2(); } public class Concrete : Base { public override void AbstractMethod1() { Console.Write("Override Abstract Method 1"); } public override void AbstractMethod2() { Console.Write("Override Abstract Method 2"); } } public class Main { public Main() { var concrete = new Concrete(); concrete.TemplateMethod(); } }
https://codedump.io/share/3GFEB5cdt2i5/1/interface-and-abstract-class-in-this-case
CC-MAIN-2017-34
refinedweb
191
53.14
pgfincore in debian As of pretty recently, pgfincore is now in debian, as you can see on its postgresql-9.0-pgfincore page. The reason why it entered the debian archives is that it reached the 1.0 release! Rather than talking about what pgfincore is all about ( A set of functions to manage pages in memory from PostgreSQL), I will talk about its packaging and support as a debian package. Here’s the first example of a modern multi-version packaging I have to offer. pgfincore packaging supports building for 8.4 and 9.0 and 9.1 out of the box, even if the only binary you’ll find in debian sid is the 9.0 one, as you can check on the pgfincore debian source package page. Also, this is the first package I’ve done properly using the newer version of debhelper, which make the debian/rules file easier than ever. Let’s have a look at it: SRCDIR = $(CURDIR) TARGET = $(CURDIR)/debian/pgfincore-%v PKGVERS = $(shell dpkg-parsechangelog | awk -F '[:-]' '/^Version:/ { print substr($$2, 2) }') EXCLUDE = --exclude-vcs --exclude=debian include /usr/share/postgresql-common/pgxs_debian_control.mk override_dh_auto_clean: debian/control pg_buildext clean $(SRCDIR) $(TARGET) "$(CFLAGS)" dh_clean override_dh_auto_build: # build all supported version pg_buildext build $(SRCDIR) $(TARGET) "$(CFLAGS)" override_dh_auto_install: # then install each of them for v in `pg_buildext supported-versions $(SRCDIR)`; do \ dh_install -ppostgresql-$$v-pgfincore ;\ done orig: clean cd .. && tar czf pgfincore_$(PKGVERS).orig.tar.gz $(EXCLUDE) pgfincore %: dh [email protected] The debian/rules file is known to be the corner stone of your debian packaging, and usually is the most complex part of it. It’s a Makefile at its heart, and we can see that thanks to the debhelper magic it’s not that complex to maintain anymore. Then, this file is using support from a bunch of helpers command, each of them comes with its own man page and does a little part of the work. The overall idea around debhelper is that what it does covers 90% of the cases around, and it’s not aiming for more. You have to override the parts where it defaults to being wrong. Here for example the build system has to produce files for all three supported versions of PostgreSQL, which means invoking the same build system three time with some changes in the environment (mainly setting the PG_CONFIG variable correctly). But even for that we have a debian facility, that comes in the package postgresql-server-dev-all, called pg_buildext. As long as your extension build system is VPATH friendly, it’s all automated. Please read that last sentence another time. VPATH is the thing that allows Make to find your source tree somewhere in the system, not in the current working directory. That allows you to cleanly build the same sources in different build locations, which is exactly what we need here, and is cleanly supported by PGXS, the PostgreSQL Extension Building Infrastructure. Which means that the main Makefile of pgfincore had to be simplified, and the code layout too. Some advances Make features such as $(wildcard ...) and all will not work here. See what we got at the end: ifndef VPATH SRCDIR = . else SRCDIR = $(VPATH) endif EXTENSION = pgfincore EXTVERSION = $(shell grep default_version $(SRCDIR)/$(EXTENSION).control | \ sed -e "s/default_version[[:space:]]*=[[:space:]]*'\([^']*\)'/\1/") MODULES = $(EXTENSION) DATA = sql/pgfincore.sql sql/uninstall_pgfincore.sql DOCS = doc/README.$(EXTENSION).rst PG_CONFIG = pg_config PG91 = $(shell $(PG_CONFIG) --version | grep -qE "8\.|9\.0" && echo no || echo yes) ifeq ($(PG91),yes) all: pgfincore--$(EXTVERSION).sql pgfincore--$(EXTVERSION).sql: sql/pgfincore.sql cp $< [email protected] DATA = pgfincore--unpackaged--$(EXTVERSION).sql pgfincore--$(EXTVERSION).sql EXTRA_CLEAN = sql/$(EXTENSION)--$(EXTVERSION).sql endif PGXS := $(shell $(PG_CONFIG) --pgxs) include $(PGXS) deb: dh clean make -f debian/rules orig debuild -us -uc -sa No more Make magic to find source files. Franckly though, when your sources are 1 c file and 2 sql files, you don’t need that much magic anyway. You just want to believe that a single generic Makefile will happily build any project you throw at it, only requiring minor adjustment. Well, the reality is that you might need some more little adjustments if you want to benefit from VPATH building, and having the binaries for 8.4 and 9.0 and 9.1 built seemlessly in a simple loop. Like we have here for pgfincore. Now the Makefile still contains a little bit of magic, in order to parse the extension version number from its control file and produce a script named accordingly. Then you’ll notice a difference between the postgresql-9.1-pgfincore.install file and the postgresql-9.0-pgfincore.install. We’re just not shipping the same files: debian/pgfincore-9.0/pgfincore.so usr/lib/postgresql/9.0/lib sql/pgfincore.sql usr/share/postgresql/9.0/contrib sql/uninstall_pgfincore.sql usr/share/postgresql/9.0/contrib As you can see here: debian/pgfincore-9.1/pgfincore.so usr/lib/postgresql/9.1/lib debian/pgfincore-9.1/pgfincore*.sql usr/share/postgresql/9.1/extension sql/pgfincore--unpackaged--1.0.sql usr/share/postgresql/9.1/extension So, now that we uncovered all the relevant magic, packaging and building your next extension so that it supports as many PostgreSQL major releases as you need to will be that easy. For reference, you might need to also tweak /usr/share/postgresql-common/supported-versions so that it allows you to build for all those versions you claim to support in the debian/pgversions file. $}' All of this will come pretty handy when we finally sit down and work on a way to provide binary packages for PostgreSQL and its extensions, and all supported versions of those at that. This very project is not dead, it’s just sleeping some more.
https://tapoueh.org/blog/2011/08/pgfincore-in-debian/
CC-MAIN-2020-40
refinedweb
964
55.54
Before starting this post, I would like to share an information about this facility in SharePoint. There was no way of deleting the audit log entries in SharePoint till the release of infrastructure update for SharePoint. Once you install this update, then you will get a STSADM command Trimauditlog and using this we can delete the unwanted audit logs. I would recommend to refer this post if you want to implement a custom mechanism to delete the audit entries in your SharePoint site. Consider, you have enabled Auditing in your SharePoint site, and there are more than 10,000 users and 3000 – 4000 users are accessing the site at the same time. Then your application will audit the information and it will store all the audit log information in the AuditData table in the content DB. If the data in that table exceeds some millions and if you access the audit report page then it may take some minuets to pull the data from the DB. As a work-around we can remove the unwanted audit entries from the AuditData table. But direct interaction with the content DB is not supported L, so what we can do in this situation? There you will get the help by using SharePoint object model J. You can use SPAuditQuery & SPAuditEntryCollection classes which are there in the Microsoft.SharePoint.dll, to accomplish this requirement. Below code is a sample code for a .NET console based application, which will take a date as input and you can delete the audit log till that particular date. I am taking a backup of already deleted audit log in a text file and it will save inside the bin\debug directory. <code> usingSystem; usingSystem.IO; usingSystem.Text; usingMicrosoft.SharePoint; usingSystem.Collections; usingSystem.Collections.Generic; namespaceDeleteAuditEntries { class Program { static void Main(string[] args) { Console.WriteLine(“Example Deletion of Audit Entries”); Console.WriteLine(“Enter a date below. In the root site collection, all audit entries created before the date entered will be deleted.”); SPSite site = new SPSite(“”); Console.Write(“Enter Month: “); int month = Convert.ToInt32(Console.ReadLine()); Console.Write(“Enter Day: “); int day = Convert.ToInt32(Console.ReadLine()); Console.Write(“Enter Year: “); int year = Convert.ToInt32(Console.ReadLine()); DateTime deleteBeforeDate = new DateTime(year, month, day); //Let’s query the log to get a report of all the entries we are deleting SPAuditQuery newQuery = new SPAuditQuery(site); newQuery.SetRangeEnd(deleteBeforeDate);//This ensure we scope the query to just the logs about to be deleted SPAuditEntryCollection report = site.Audit.GetEntries(newQuery); TextWriter reportfile = new StreamWriter(“auditreport.txt”); foreach (SPAuditEntry i in report) { reportfile.WriteLine(i.ToString()); } reportfile.Close(); //This is the call that actually deletes the entries. site.Audit.DeleteEntries(deleteBeforeDate); Console.WriteLine(“Complete. auditreport.txt contains a list of all audit entries that were deleted.”); return; } } } </code> If you want to integrate this functionality in your SharePoint site, then you can create a custom aspx page you can implement this same functionality there. If you want to do that, then you can just go through the below MSDN link. The above MSDN link is for creating a custom aspx for a different functionality with Auditing, but you can follow the steps in this article to create a user interface for deleting the auditing log entries and archiving the data in an another custom DB or in a text file. 1. Sample image 1 For E.g.: First you can create a custom action to your Site Actions to add a link to redirect the Administrator to the AuditData deletion page. 2. Sample image 2 After clicking that custom menu item, you can redirect the user to your custom aspx page which you need to keep in your Layouts folder. Drive:\Program Files\Common Files\Microsoft Shared\web server extensions\12\TEMPLATE\LAYOUTS Hi, Is there a way to pass it a batch size? If don't want to a have long running transaction on my db. For example, I want it to delete rows for a specific date but in a smaller batches… As per table dependcies, Audit table has no direct relationship with any other table. Does not it make sense to just trunctate the table if audit entries are not required. I have 120 Million rows to delete. It makes no sense to me to delete them row by row…. or chunks of millions… I would appreciate your input.. Hi Najim, You can pull the audit data based upon the date parameters. If it is in 2010 we have a timer job which scheduled to run in a monhtly basis to clean the audit information of a site if it is marked for trimming. Thanks, Sowmyan
https://blogs.msdn.microsoft.com/sowmyancs/2008/05/28/create-a-tool-or-an-interface-to-delete-the-audit-log-from-content-db-of-an-auditing-enabled-sharepoint-site/
CC-MAIN-2016-40
refinedweb
776
55.34
Variables are just like the variables that we learnt in Mathematics when we were in the ninth grade or secondary school. Every variable has a type that determines what values can be stored in the variable. Below, we assign a value of 25 to a variable age that is of type integer (int). int age = 25 Case-sensitive Similar to the original C programming language, C# variable declaration is case-sensitive. The declaration below will create 2 variables age and Age. int age = 25 int Age = 25 C# is a type-safe language, and the C# compiler guarantees that values stored in variables are always of the appropriate type. Variable must be definitely assigned A variable must be definitely assigned before its value can be obtained. It has to be declared and assign a specific value. Commonly used variables using System; namespace Variables { class Program { static void Main() { int point = 90; string greeting = "Hello, World!"; double bigNumber = 1e100; Console.WriteLine("{0} {1} {2}", point, greeting, bigNumber); Console.ReadLine(); } } } The above example shows the commonly used variable types integer, string and double. In line 13, notice how we need to put the variables into array like {} in the writeline line to output the 3 variables. The {0} denotes the first variable and {1} denotes the second variable and so on.
https://codecrawl.com/2014/08/09/csharp-variables/
CC-MAIN-2018-43
refinedweb
219
64.51
...one of the most highly regarded and expertly designed C++ library projects in the world. — Herb Sutter and Andrei Alexandrescu, C++ Coding Standards #include <boost/phoenix/statement/if.hpp> The syntax is if_(conditional_expression) [ sequenced_statements ] .else_ [ sequenced_statements ] Take note that else has a leading dot and a trailing underscore: .else_ Example: This code prints out all the elements and appends " > 5", " == 5" or " < 5" depending on the element's actual value: std::for_each(c.begin(), c.end(), if_(arg1 > 5) [ cout << arg1 << " > 5\n" ] .else_ [ if_(arg1 == 5) [ cout << arg1 << " == 5\n" ] .else_ [ cout << arg1 << " < 5\n" ] ] ); Notice how the if_else_ statement is nested.
https://www.boost.org/doc/libs/1_64_0/libs/phoenix/doc/html/phoenix/modules/statement/___if_else_____statement.html
CC-MAIN-2018-26
refinedweb
104
60.21
In this tutorial, we will learn how to upload a file in Cypress using the cypress-file-upload NPM package. Cypress does not have a native support to do file uploads at the moment, however, this is something they plan to add in the future. Installation Since, we need to use a third-party library to do file upload, we will need to get that installed and setup to make it work with Cypress. Install NPM Package First thing you need to do is install the package - npm install --save-dev cypress-file-upload Setup Custom Command cypress-file-upload library provides a custom command which we can use once we set it up. To do that, we need to import the library in the custom command file (cypress/support/commands.js) like this - import 'cypress-file-upload'; Then, make sure this commands.js is imported in cypress/support/index.js (it might be commented): import './commands'; Upload File Test Now, that we have installed the package, we can go ahead and start using the custom command. In the example below, I will be uploading a file on my test website. The key thing to focus on the example above is the .attachFile() command which is added by the helper library that we installed. It takes in a parameter i.e. the file name which should be included inside the fixtures folder as shown below. Working with hidden input fields Typically, the .attachFile() command would work if the input[type=file] element is intractable. However, if the element is hidden then you will need to make necessary changes to make the element visible and intractable again. You can do that using the help of the Cypress .invoke() function as seen below - In this example, I am removing the hidden class using the jquery removeClass function which is making my element intractable again. To learn more about how to upload a file in Cypress, checkout the video below - 📧 Subscribe to my mailing list to get access to more content like this as well as be part of amazing free giveaways. 👍 You can follow my content here as well - ...)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/automationbro/how-to-upload-a-file-in-cypress-1iak
CC-MAIN-2021-49
refinedweb
357
63.7
Applicative validation syntax People say that Validation is Scalaz’s gateway drug, which might be accurate if you ignore the suggestion that there’s anything even remotely fun about validation. In my book, making sure that your program doesn’t choke on bad input is always a chore. Applicative validation is at least a step in the right direction—it makes it easier to write less code, introduce fewer bugs, and draw clearer lines between data models and validation logic. Suppose for example that we have the following case class in Scala: case class Foo(a: Int, b: Char, c: String) Suppose also that we have a form with three fields that we want to use to create instances of Foo. We receive input from this form as strings, and we want to be sure that these strings have certain properties. Using Scalaz 7, we can write the following: type ErrorsOr[A] = ValidationNel[String, A] type Validator[A] = String => ErrorsOr[A] val checkA: Validator[Int] = (s: String) => try s.toInt.success catch { case _: NumberFormatException => "Not a number!".failureNel } val checkB: Validator[Char] = (s: String) => if (s.size != 1 || s.head < 'a' || s.head > 'z') { "Not a lower case letter!".failureNel } else s.head.success val checkC: Validator[String] = (s: String) => if (s.size == 4) s.success else "Wrong size!".failureNel Now we can write a method that will lift our constructor into the ValidationNel applicative functor and apply it to our input (after running each piece of that input through the appropriate validator): def validateFoo(a: String, b: String, c: String) = (checkA(a) |@| checkB(b) |@| checkC(c))(Foo.apply _) See my Stack Overflow answer here for some additional discussion of this syntax (and applicative functors more generally) in the context of validation. We can confirm that this method works as expected: scala> println(validateFoo("ab", "cd", "ef")) Failure(NonEmptyList(Not a number!, Not a lower case letter!, Wrong size!)) scala> println(validateFoo("42", "cd", "ef")) Failure(NonEmptyList(Not a lower case letter!, Wrong size!)) scala> println(validateFoo("42", "x", "what")) Success(Foo(42,x,what)) Unfortunately the |@| syntax is kind of ugly—especially compared to Haskell, where we’d write the following: validateFoo = Foo <$> checkA a <*> checkB b <*> checkC c It gets even worse if you have more than twelve fields, as this Stack Overflow question points out. In that case you have to fall back to calling ap (or, equivalently, Scalaz’s version of <*>) directly, which looks like this: def validateFoo(a: String, b: String, c: String) = checkC(c) <*> (checkB(b) <*> (checkC(c) map (Foo.apply _).curried)) It’s horrible—the arguments are in the wrong order and there are parentheses everywhere. When I saw that question this morning, I started wondering about ways that Shapeless might be able to make the situation a little better. The rest of this post is a sketch of some quick experiments in that direction. First of all, it’s not too hard to write a general operator for lifting functions of arbitrary arity into any applicative functor: import scalaz._, Scalaz._ import shapeless._ object applier extends Poly2 { implicit def ap[F[_]: Applicative, H, T <: HList, R]: Pullback2Aux[applier.type, F[(H :: T) => R], F[H], F[T => R]] = at[F[(H :: T) => R], F[H]]( (f, fa) => fa <*> f.map(hf => (h: H) => (t: T) => hf(h :: t)) ) } class Lifter[F[_]: Applicative] { def lift[G, H, A <: HList, M <: HList, R](g: G)(implicit hlG: FnHListerAux[G, A => R], mapped: MappedAux[A, F, M], unH: FnUnHListerAux[M => F[R], H], folder: LeftFolderAux[M, F[A => R], applier.type, F[HNil => R]] ) = unH((m: M) => folder(m, hlG(g).point[F]).map(_(HNil))) } def into[F[_]: Applicative] = new Lifter[F] Now we can factor out the lifting part of our definition of validateFoo in a way that’s (arguably) a little nicer: val liftedFoo = into[ErrorsOr] lift (Foo.apply _) def validateFoo(a: String, b: String, c: String) = liftedFoo(checkA(a), checkB(b), checkC(c)) One (possibly) more interesting approach would be to write a method that would take a constructor and a heterogeneously-typed list of validators and then build our top-level validation function for us. This also isn’t too hard. First for some more general-purpose machinery: def validate[F[_], G, H, V <: HList, I <: HList, M <: HList, A <: HList, R] (g: G)(v: V)(implicit hlG: FnHListerAux[G, A => R], zip: ZipApplyAux[V, I, M], mapped: MappedAux[A, F, M], unH: FnUnHListerAux[I => F[R], H], folder: LeftFolderAux[M, F[A => R], applier.type, F[HNil => R]], appl: Applicative[F] ) = unH((in: I) => folder(zip(v, in), hlG(g).point[F]).map(_(HNil))) And now we can write the following: val validateFoo = validate(Foo.apply _)(checkA :: checkB :: checkC :: HNil) Which we can use in exactly the same way as our original validateFoo above. I’m not sure I want to argue that this approach is in any sense better than going with the applicative builder syntax that comes with Scalaz (when that’s an option), but it does give an example of how we can use Shapeless to add flexibility to an existing library without a lot of boilerplate.
http://meta.plasm.us/posts/2013/06/05/applicative-validation-syntax/
CC-MAIN-2016-18
refinedweb
873
51.78
By input I mean the command line argument. If I put 10, or 100, or 1000, it works, but 4000 gives a segmentation fault! here is the code: Code:/*************************************************************************** sieve.cpp - description ------------------- begin : Thu Oct 3 2002 copyright : (C) 2002 by Will Herrick email : will.herrick2@verizon.net ***************************************************************************/ // This program finds the prime numbers from 1-1000 using the // Sieve of Eratosthenes /*************************************************************************** * * * This program is free software; you can redistribute it and/or modify * * it under the terms of the GNU General Public License as published by * * the Free Software Foundation; either version 2 of the License, or * * (at your option) any later version. * * * ***************************************************************************/ #include <iostream> #include <fstream> using namespace std; ofstream write; ofstream read; int main(int argc, char* argv[]) { int Numbers[1000]; int max; int x; int y; int column = 0; if(argc != 2) // meaning they didn't put in any options { cout << "Please put in the number you'd like to find the primes upto."; return 0; } else { max = atoi(argv[1]); } write.open("primes.dat", ios::out); read.open("primes.dat", ios::in); read.open("primes.dat", ios::app); // fill the number array for(x = 0; x < max; x++) Numbers[x] = (x+1); for(x = 1; x < (max - 2); x++) // start at 2 since we already know 1 isn't prime { if(Numbers[x] != 1 && Numbers[x] != 0) // 1 means its been "crossed off" { for(y = (x+1); y < (max-1-x); y++) // finds multiples of x { if(Numbers[y] % Numbers[x] == 0) { Numbers[y] = 1; } } // the following provides some formatting for primes.dat if(column < 8) { write << (x+1) << "\t"; // writes the prime number to file column++; } else { write << (x+1) << endl; column = 0; } Numbers[x] = 0; // "circled" - its prime } } return 0; } The purpose of the code is to print to a file all of the prime numbers from 1 to the number the user enters at run time. (it's called a sieve of Eratosthenes) but like I said, if I run ./sieve 4000 I get a Segmentation Fault (running linux mandrake 9.0, KDevelop 2.1) The error probably stems from me only using command line arguments on one other occasion, so i'm not very versed in them. Thanks!
http://cboard.cprogramming.com/cplusplus-programming/25783-why-do-i-get-seg-fault-large-input.html
CC-MAIN-2014-35
refinedweb
367
69.52
Created on 2012-10-03 03:10 by christian.heimes, last changed 2014-11-28 23:22 by python-dev. This issue is now closed. Today the latest crypto hash function was announced by NIST [1]. I suggest that we include the new hash algorithm in 3.4 once it lands in OpenSSL. The Keccak site also has a reference implementation in C and Assembler [2]. It may take some effort to integrate the reference implementation as it contains several optimized backends for X86, X86_64, SIMD and various ARM platforms. [1] [2] We have MD5, SHA1, sha256, sha512 implemented, to use when openssl is not available. Can we do the same with sha-3?. I would suggest to adopt the reference implementation without extensive optimizations, since we will have them when openssl has them. So we might implement SHA-3 now and integrate OpenSSL implementation later, when available. This is interesting, for instance, because many users of Python 3.4 will have a non "up to date" OpenSSL system library. I've done some experiments with the reference implementation and adopted code of sha1module.c for sha3: So far the code just compiles (64bit only) but doesn't work properly yet. I may need to move away from the NIST interface and use the sponge interface directly. For what it's worth, I've built a working C-based sha3-module that is available here: Note that I've only tested this on Python 2, for Python 3 YMMV. Best regards Björn Hello. Release 0.1 of pysha3 [1] is out. I've tweaked the C module to make it compatible with Python 2.6 to 3.4. The module and its tests run successfully under Linux and Windows. So far I've tested Linux X84_64 (2.7, 3.2, 3.3, 3.4), Windows X86 (2.6, 2.7, 3.2, 3.3) and Windows X86_64 (2.6, 2.7, 3.2, 3.3). Please review Modules/sha3module.c and ignore all version specific #if blocks. For Python 3.4 I'm going to remove all blocks for Python < 3.3. [1] > Please review Modules/sha3module.c Can't you post a patch here? How about a sandbox repos? Good, you can click the "create patch" button when it's ready :) Antoine pointed out that the code contains C++ comments and exports a lot of functions. The latest patch has all // comments replaced, marks all functions and globals as static and #includes the C files directly. Please review the latest patch. I've included Gregory as he is the creator of hashlib. The hightlights of the next patch are * release the GIL * more test vectors * remove bgr_endian.h * move typedef UINT64 to sha3module * declare more globals as static I've documented the optimization options of Keccak. The block also contains a summarization of my modifications of the reference code. New patch. I've removed the dependency on uint64 types. On platforms without a uint64 type the module is using the 32bit implementation with interleave tables. By the way the SSE / SIMD instructions aren't useful. They are two to four times slower. don't worry about optimization settings in python itself for now. the canonical optimized version will be in a future openssl version. now that it has been declared the standard it will get a *lot* more attention in the next few years. as it is, we _may_ want to replace this reference implementation with one from libtomcrypt in the future when it gets around to implementing it just so that the code for all of our bundled hash functions comes from the same place. New changeset 11c9a894680e by Christian Heimes in branch 'default': Issue #16113: integrade SHA-3 (Keccak) patch from The code has landed in default. Let's see how the build bots like my patch and the reference implementation. _sha3 is not being built on Windows, so importing hashlib fails >>> import hashlib ERROR:root:code for hash sha3_224 was not found. Traceback (most recent call last): File "C:\Repos\cpython-dirty\lib\hashlib.py", line 109, in __get_openssl_constructor f = getattr(_hashlib, 'openssl_' + name) AttributeError: 'module' object has no attribute 'openssl_sha3_224' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Repos\cpython-dirty\lib\hashlib.py", line 154, in <module> globals()[__func_name] = __get_hash(__func_name) File "C:\Repos\cpython-dirty\lib\hashlib.py", line 116, in __get_openssl_constructor return __get_builtin_constructor(name) File "C:\Repos\cpython-dirty\lib\hashlib.py", line 104, in __get_builtin_constructor raise ValueError('unsupported hash type ' + name) ValueError: unsupported hash type sha3_224 ... I've pushed a fix about 5 minutes ago. The module wasn't compiled in debug builds due to an error in the project file. Please update your copy and try again. 6cf6b8265e57 and 8172cc8bfa6d have fixed the issue on my VM. I didn't noticed the issue as I only tested hashlib with the release builds, not the debug builds. Sorry for that. > 6cf6b8265e57 and 8172cc8bfa6d have fixed the issue on my VM. I didn't > noticed the issue as I only tested hashlib with the release builds, not > the debug builds. Sorry for that. Ah. I did not even notice there was _sha3.vcxproj. Is there any particular reason for not making it part of python3.dll like _sha1, _sha256, _sha512 are? (I thought it was only modules with special link requirements that became separate DLLs.) The module is rather large (about 190 KB) because the optimized SHA-3 implementation isn't optimized for size. For this reason I like to keep the module out of the main binary for now. Please do not go forward until NIST publishes its SHA-3 specification document. We don't know yet what parameters they will finally choose when making Keccak SHA-3. NIST has published a tentative schedule for SHA-3 standardization. They expect to publish in the second quarter of 2014. See and As long as the reference Keccak code is going to live in the python stdlib anyway, I would /greatly/ appreciate it if the Keccak sponge function was directly exposed instead of just the fixed parameters used for SHA-3. A Keccak sponge can have a much wider range of rates/capacities, and after absorption can have any number of bytes squeezed out. The ability to get an unbounded number of bytes out is very useful and I've written some code that uses that behavior. I ended up having to write my own Keccak python library since none of the other SHA-3 libraries exposed this either. Hi Aaron, it's a tempting idea but I have to decline. The API is deliberately limited to the NIST interface. Once OpenSSL gains SHA-3 support we are going to use it in favor for the reference implementation. I don't expect OpenSSL to provide the full sponge API. I also like to keep all options open so I can switch to a different and perhaps smaller implementation in the future. The reference implementation is huge and the binary is more than 400 KB. For comparison the SHA-2 384 + 512 module's binary is just about 60 KB on a 64bit Linux system. Once a a new API has been introduced it's going to take at least two minor Python release and about four to five years to remove it. But I could add a more flexible interface to Keccak's sponge to my standalone sha3 module ... is what I've written to do this, for reference. Honestly I hope that the Keccak sponge is directly exposed in openssl (or any other SHA-3 implementation) because of its utility beyond SHA-3. If the source of some other implementation is going to be bundled with python anyway, it shouldn't be difficult to expose the sponge bits. Please make sure that the currently committed code is not released as part of Python 3.4. SHA-3 is not standardised yet, and NIST has said that they intend to make some changes to the Keccak SHA-3 submission before standardisation as a FIPS. The links englabenny posted have a good overview of the SHA-3 timeline and the proposed changes. It would be very confusing if hashlib in Python 3.4 came with a "sha3" that was incompatible with the final standard. Victor: a "new feature" is not a "release blocker". I'm tracking the SHA-3 progress closely. I'm prepared to pull the plug if there is any doubt about the final version of SHA-3 before beta 2 is released on Jan 5th. Larry: I have marked this new feature as release blocker because I may have to remove it and reschedule its addition for 3.5. I'd like to remove it after you have branched off the 3.4 branch. Larry: I have marked this new feature as release blocker because I may have to remove it and reschedule its addition for 3.5. I'd like to remove it after you have branched off the 3.4 branch. "release blocker" means "the release cannot go out until this issue is solved". Adding SHA-3, while nice, is simply not something I am going to hold up 3.4 for, full stop. Please stop marking this issue as a "release blocker". Here "release blocker" would mean that if SHA-3 specification is not finished, then "the release cannot go out until SHA-3 is deleted". You guys are making me cranky. Please stop adding me to this issue. @Larry, you seem to be misreading this. They're not saying 3.4 can't be released until this feature is added. It's _already_ been added. They're saying 3.4 possibly can't be released until this feature is _removed_ - but whether it needs to be removed is outside of our control, and is not yet known. > "release blocker" means "the release cannot go out until this > issue is solved" Yes - and this issue has not been solved yet. It should indeed be solved before 3.4 is released, so "release blocker" is spot on. *sigh* fine. But the title of the issue is no longer accurate. And, Christian, I generate the 3.4 maintenance branch during the release process, not before. So if you have to remove sha3 you're going to have to remove it from trunk. > I'm prepared to pull the plug if there is any doubt about the final version of SHA-3 before beta 2 is released on Jan 5th. Shouldn't it be removed before beta1? The usual rule of feature freeze applies here. This strikes me as a rather unusual case. How about discuss it on python-dev, come to an agreement and document the process for this type of issue somewhere for future reference? Or is that simply OTT? New I'm going to remove sha3 from the trunk tomorrow unless I hear otherwise. Python shouldn't implement something called "sha3" until SHA-3 actually is a standard. According to the current NIST timeline, the comment period on the draft FIPS should have ended by now, but AFAICT, the draft FIPS that starts the 90 day comment period hasn't even been published yet. Will it be possible/easy to maintain a sha3 module on PyPI? It would be nice to have to for Python 2.6-3.4. @Christian: Are you interested to do that? Either that, or we call it something else than "sha3"? I would not bother pulling this out until the week before RC1 if the standard has not yet been declared final. Otherwise, -1 on keeping it under another name. The only hashes we bundle should be standard ones as those are the only ones people will want to use in the long run. We'd be saddled with carrying along a non-standard likely not widely used algorithm implementation forever otherwise. even if sha3 isn't declared before 3.4rc1, people building 3.4 against a sufficiently modern version of openssl that includes sha3 (as i'm sure some version will) will still have access to the algorithm. otherwise i'm sure someone will package this as a module on pypi for older pythons regardless. I. Ok, this this remains a release blocker. I'm still +1 for removing it, and I'm -0 for removing it just before the release candidate. AFAICT, there is *zero* (.000000001) chance that it actually becomes a NIST standard before the Python release is made. According to the current timeline: the *submission to the secretary* (of commerce) was scheduled for Q2. With the current delay, this must become Q3, so the publication as a standard might happen in Q4 (not sure how long the Secretary of Commerce needs to study the specification of a hash algorithm). What might happen is that a draft is published by the time the RC is made. I'd then still be -1 on including something in Python that only implements a draft standard. So we could just as well remove it right away. I agree with Martin that it should be removed right now. It's not really reasonable to call something SHA-3 if it's not SHA-3, even in beta versions. OpenSSL doesn't implement SHA-3 yet, it's strange to have SHA-3 in Python but not in OpenSSL. If the standard is still a draft, I agree to remove the code right now. Given the likely delay in the standard Martin cites, I've change my mind: agreed. Go ahead and remove it for 3.4. We'll have an official sha3 in Python 3.5. Early adopters can live with PyPI. I just looked at the hash-forum archives (*) which says that they plan to publish the draft "soon after Christmas". They also indicate how the padding open issue might get resolved (append 1111 for SHAKE, 1101 for the SHA-2 drop-ins). Not sure whether this is what Christian has already implemented. (*) See for the password New changeset 52350d325b41 by Martin v. Löwis in branch 'default': * Issue #16113: Remove sha3 module again. I have now removed the aha code. @Martin: It looks like the _overlapped module is not more compiled on Windows. test test_asyncio crashed -- Traceback (most recent call last): File "E:\home\cpython\buildslave\x86\3.x.snakebite-win2k8r2sp1-x86\build\lib\asyncio\__init__.py", line 16, in <module> from . import _overlapped ImportError: cannot import name '_overlapped' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "../lib/test/regrtest.py", line 1278, in runtest_inner test_runner() File "E:\home\cpython\buildslave\x86\3.x.snakebite-win2k8r2sp1-x86\build\lib\test\test_asyncio\__init__.py", line 31, in test_main run_unittest(suite()) File "E:\home\cpython\buildslave\x86\3.x.snakebite-win2k8r2sp1-x86\build\lib\test\test_asyncio\__init__.py", line 21, in suite __import__(mod_name) File "E:\home\cpython\buildslave\x86\3.x.snakebite-win2k8r2sp1-x86\build\lib\test\test_asyncio\test_base_events.py", line 11, in <module> from asyncio import base_events File "E:\home\cpython\buildslave\x86\3.x.snakebite-win2k8r2sp1-x86\build\lib\asyncio\__init__.py", line 18, in <module> import _overlapped # Will also be exported. ImportError: No module named '_overlapped' Thanks for the report. Restored in 8a3718f31188 New changeset 21257f916668 by Ned Deily in branch '3.4': Issue #16113: Also remove test_case_sha3_224_huge New changeset bd97eab25c70 by Ned Deily in branch 'default': Issue #16113: Also remove test_case_sha3_224_huge
http://bugs.python.org/issue16113
CC-MAIN-2015-40
refinedweb
2,576
75.2
Callbacks (part 1) Customers sometimes come to us saying they have a .NET-to-Java project, and asking how they can pass a real .NET object to a method in the proxied Java object. Often they’ll subclass a proxy or implement a proxied interface, but when they actually pass the .NET object to the proxy, they get an exception. I explain that what they really are trying to do is to implement a callback: the .NET code has called the Java side, and during that execution, the Java code “calls back” some .NET object that’s previously been registered as a “callback.” If you’re familiar with Java listener interfaces, you’ll know how this all works. Callbacks are easy to implement. In this post, we’ll discuss how to implement a callback in a .NET-to-Java project. In the next post, we’ll discuss callbacks in Java-to-.NET projects. Let’s start with a Java class that allows other classes to register themselves as listeners for particular events, then notifies those listeners that those events occur. All listeners must implement a particular listener interface, which must have at least one method that will be executed when the event occurs. The method can take parameters, and can return values or throw exceptions. Here’s a listener interface: // this is Java public interface MyListener { public void fireEvent(); } Now that we’ve got the listener, here’s the event generator class we’ll be working with: // this is Java public class MyEventGenerator { private static java.util.ArrayList listeners = new java.util.ArrayList(); public static void registerListener(MyListener aListener) { listeners.add(aListener); } public static void fireListeners() { for(int i = 0; i < listeners.size(); i++) { MyListener aListener = (MyListener) listeners.get(i); aListener.fireEvent(); } } } If we’ve proxied the MyListener and MyEventGenerator classes, we can implement .NET classes that can register themselves with MyEventGenerator as listeners: // this is C# [Callback("MyListener")] public class DotNetListener : MyListener { public void fireEvent() { Console.WriteLine("event fired!"); } } Note that DotNetListener implements the proxied MyListener interface. Also note that it has the [Callback] attribute. These both are essential. The [Callback] attribute’s class is really com.jnbridge.jnbcore.CallbackAttribute, so you’ll need to make sure you’ve imported that namespace into your program (using the import (if VB.NET) or using (if C#) keywords). The [Callback] attribute needs the fully-qualified name of the interface, so if the interface is in a package, or if it’s nested inside another class, you’ll need to supply the entire name. Also note the method fireEvent() that any class implementing MyListener must implement. Now we can use DotNetListener wherever a proxy expects a MyListener: // this is C# MyEventGenerator.registerListener(new DotNetListener()); MyEventGenerator.fireListener(); The console will now print "event fired!". Callbacks can take parameters, return values, or throw exceptions, but the parameters, return values, and exceptions must be of classes that the Java side “understands,” which means they need to be proxies, primitives, strings, or arrays of those. A callback class can implement multiple listener interfaces, but if it does, you’ll need to annotate the callback class with a [Callback] attribute for each listener interface it implements. One subtlety to be aware of is that when the Java side calls the callback, the Java thread doing the calling suspends until the callback returns. This is done to preserve the expected callback semantics. Since the Java thread has suspended, it’s likely that the .NET thread that originally called the Java side has suspended, since it’s waiting for the Java side to return. Usually this is fine and expected, but sometimes, as when you’re using the callback inside a Windows Form, it can lead to deadlock. To get around this problem, use an asynchronous callback, which is designated using the [AsyncCallback] attribute rather than the [Callback] attribute. When an asynchronous callback is called, the Java-side thread doesn’t wait around until the callback returns, but goes on its way. This avoids the deadlock issue. The tradeoff is that since the Java side doesn’t wait around for the result of the callback, asynchronous callbacks can’t return values or throw exceptions. That’s all there is to callbacks! In our next post, we’ll explain how callbacks work in the opposite direction: in Java-to-.NET projects.
https://jnbridge.com/blog/callbacks-part-1
CC-MAIN-2019-26
refinedweb
721
56.86
Introduction: Temperature With DS18B20 It's a small project about temperature monitoring. I used a DS18B20 digital device to get the temperature. The device uses OneWire protocol. You need only an Arduino board, a DS18B20 and a 4.7KOhm resistor and a breadboard. If you have a display shield for the Arduino that's a plus. Step 1: What You Have to Know About DS18B20 The device is communicating on one common bus. It means that you can connect several devices. We use only two pins on the device to connect them to the Arduino board. We need two libraries in the sketch: OneWire and DallasTemperature . So we must include these libraries. Step 2: Setup We define the communication IO port: #define ONE_WIRE_BUS 3 We need two object to communicate with the device(s): OneWire ds(ONE_WIRE_BUS); DallasTemperature sensors(&ds); ds object will handle the onewire protocol sensors object will handle the temperature monitoring devices I chained 3 devices in this example on a breadboard. On the left side I used a potmeter instead of a 4.7K resistor. Step 3: Inventory 1st step is to start the sensors: sensors.begin(); 2nd step is to count the number of sensors on the bus. This function sets the global variable: maxsensors scanSensors(); 3rd step is to request the temperatures from the devices: sensors.requestTemperatures(); 4th step is to read the temperatures one by one: for (int i=0;i { float f = sensors.getTempCByIndex(i); lcdprint(dtostrf(f, 5, 1, buffer)); } lcdprint is a function to display the result on an LCDshield dtostrf is a function defined in stdio library. it must be included. Step 4: Source Code Some link for downloading the source codes Full source code Dallas Temperature library by Miles Burton LCD shield library, I used in this project The LCD shield was ordered from here Recommendations We have a be nice policy. Please be positive and constructive. 23 Comments my ds18b29 sensor has only two wires so howto interface with it. please give me details of the pins sorry its ds18b20 I am facing some problem here. 1) Where should those library files be actually placed? ../libraries or some home folder where I keep my source codes? 2) Due to this the IDE does not compile it. I then placed the files in a folder src and now there is new error. #include Nested deeply I am at my wit's end. Please help! /sketchbook/libraries If you do not have a sketchbook folder (sometimes it iscalled "Arduino") the libraries folder must be in that one. You can find your Sketchbook location under "File-Preferences" In parasitic mode, you need to connect VDD to Ground. Additionally, you may need to replace the resistor as with 4.7kΩ the sensor may not get enough power to run at all. On a 10 meter cable run with parasitic power, I get reliable results when resistor is less than 2kΩ. With 4.7kΩ, I got over 95% read fails. With 2.3kΩ I got around 18% fails. With 1.9kΩ I get 1.7% fails. Thanks for the tip. It can be useful in the future for everyone. I have no problem with a 20 cm long cable for years. for those who have problem compiling it, I uploaded my Arduino 1.04 IDE with the integrated libraries and the project file. feel free to download and test it. BR, Mark This is very helpful, but IMHO there's an error in the Step 1 diagram showing the resistor; if you simply put the 4.7K resistor on the power line as shown you also drop the voltage to the device while pulling the data line high. Putting the resistor on the data line will keep voltage to the devices nominal and pull data high as well. Works great otherwise and thank you for putting it up! Actually MadScott, the schematic is correct. The OneWire devices can operate either with a power line, or in parasitic mode, where power is drawn from the data line. If you look at the schematic you will see pin 3 (VCC) on the devices is unconnected. This means they are using parasitic mode. The OneWire device will effectively "charge" itself from the data line, using VCC via the 4.7k resistor, and use use this charge to run during times when the data line is used to exchange data. Note that the charge is very small and only designed to last while transferring data. This places some constraints on the data transfers, such as how long the line must be idle before any communication to ensure all devices are charged. The reason the resistor must be so high is so that the data line can still be asserted low without drawing too much from the host power supply. The libraries take of this detail and in practice it works really well. Hope this helped. Here's a quote from the datasheet for the DS18B20: "When the DS18B20 is used in parasite power mode, the VDD pin must be connected to ground." Hi, This is my first Arduino project and so far have one DS18B20 working as a basic thermostat using a code I found that didn't required the Dallas Temperature Library. However I would love to use three sensors and the display as shown here, the only problem is that I don't seem to be able to find the actual variables that contain the temperature values for each sensor. I will need these to operate various hardware such as fans, actuators and heaters based on a temperature set point and the values for each of the sensors. Can anyone help with some code to create or access these variables. Thanks. Hi If you want to use more sensors, then I recommend using the library. ScanSensors will do a loop and read all the sensors on the same wire. It runs from the Setup function, so let's say it collects how many sensors we have. Then we read the individual sensor temperatures from the Loop function. First we send a command to measure the temperature: sensors.requestTemperatures(); After we can re the values by an index: float f = sensors.getTempCByIndex(i); Regards, Mark Thanks Mark, I am very new to the C programming language but after some reading I think you have created an array that contains the sensor values and to access each one individually they would be called f[0], f[1] and f[2], is this right? Unfortunately I haven't been able to test this theory as I am getting multiple errors when I try and compile the sketch. In fact I can't even compile the examples in the onewire and Dallas Temperature library's that came from the link above. The errors from the OneWire library example are to do with "WConstants.h: Nosuch file or directory" and a bunch of variables that "was not declared in this scope" like digitalPinToBitMask and delayMicroseconds etc. The errors from your sketch are pointing to the LCD4bit_mod library file location and also mention the "WConstants.h: Nosuch file or directory" and a bunch of variables that "was not declared in this scope". Is there likely to be a simple fix for this? Well I can now see I was a little off the mark. I have found that the individual readings can be accessed by float temp1 = sensors.getTempCByIndex(0); float temp2 = sensors.getTempCByIndex(1); etc.... The WConstants.h error can be resolved by removing the #include "WConstants.h" from the .cpp file and adding #include "Arduino.h" to the .h file as per... I found a link: Hi That's cool. I found it in my project folder too :) if you need it for some reasons: an older version: Regards, Mark Thanks Mark, Oddly enough I am having issues with OneWire library. Did you recieve a WConstants.h error when trying to compile? I attached an image of the error and my OneWire.h library. Hello No I didn't get such error message when I used 1.0.4 version of IDE with this library: regards, Mark Mark, Thanks for the code. I get another error now, see attached, and am using it for a sous vide application. I can still recommend you using Arduino 1.0.4. That version is working and can be compiled. See attached image. double checked, no compile errors at all. I used this simple source: #include <OneWire.h> #include <DallasTemperature.h> #include <stdio.h> #define ONE_WIRE_BUS 3 char buffer[25]; byte maxlines = 2; char line1[16]; char line2[16]; byte x = 0; byte y = 1; byte maxsensors = 0; /* DS18S20 Temperature chip i/o */ OneWire ds(ONE_WIRE_BUS); DallasTemperature sensors(&ds); void flashled(void) { digitalWrite(13, HIGH); delay(1); digitalWrite(13, LOW); } void scanSensors(void) { byte i; byte present = 0; byte data[12]; byte addr[8]; while (ds.search(addr)) { Serial.print("R="); for( i = 0; i < 8; i++) { Serial.print(addr[i], HEX); Serial.print(" "); } if ( OneWire::crc8( addr, 7) != addr[7]) { Serial.print("CRC is not valid!\n"); return; } if ( addr[0] == 0x10) { Serial.print("Device is a DS18S20 family device.\n"); maxsensors++; } else { if (addr[0] == 0x28) { Serial.print("Device is a DS18B20 family device.\n"); maxsensors++; } else { Serial.print("Device is unknown!\n"); Serial.print("Device ID: "); Serial.print(addr[0],HEX); Serial.println(); return; } } // The DallasTemperature library can do all this work for("P="); Serial.print(present,HEX); Serial.print(" "); for ( i = 0; i < 9; i++) { // we need 9 bytes data[i] = ds.read(); Serial.print(data[i], HEX); Serial.print(" "); } Serial.print(" CRC="); Serial.print( OneWire::crc8( data, 8), HEX); Serial.println(); flashled(); } Serial.print("No more addresses.\n"); ds.reset_search(); delay(250); } void setup(void) { Serial.begin(9600); pinMode(13, OUTPUT); byte i, j; for (j=0;j<16;j++) { line1[j] = 32; line2[j] = 32; } line1[16] = 0; line2[16] = 0; x = 0; y = 1; sensors.begin(); scanSensors(); } void loop(void) { sensors.requestTemperatures(); // minden eszköztől kérjük a hőmérséklet mérést... for (int i=0;i<maxsensors;i++) { flashled(); float f = sensors.getTempCByIndex(i); // egyesével kiolvassuk a mért értéket Serial.print("Sensor "); Serial.print(i,DEC); Serial.println(dtostrf(f, 6, 2, buffer)); } }
http://www.instructables.com/id/Temperature-with-DS18B20/
CC-MAIN-2018-22
refinedweb
1,705
67.35
I am about to blow this class that I am in. This is the last class that I need to finish my Mechanical Engineering Degree. I have until sunday afternoon to figure this out. I need a 95% on this program to pass the course. All the help that I can get to understand this stuff will be truly appreciated /*I have an intersection with 4 traffic signals In c++ I need to use a Class. Here is the code, at the end of the code I will elaborate on what needs to be done that I am having problems with!*/ #include <iostream> #include <cmath> #include <iomanip> using namespace std; class TrafficSignal { private: bool Red, Yellow, Green; // bool variables to control whether the lights are lit int Red_Duration, Yellow_Duration, Green_Duration; //int variables to controltheir Durations int Id; //int that is the identifer for the signal int Elapsed_Time; //int variable indicating # of seconds since signal started int Tick; //this is my extra time variable to support the "time since the last cycle change" functionality. public: TrafficSignal(); // This is the default constructor void setRed(bool); void setYellow(bool); void setGreen(bool); void setRed_Duration(int); void setYellow_Duration(int); void setGreen_Duration(int); void setId(int); void setElapsed_Time(int); void setTick(int); //this is the added time variable bool getRed(); bool getYellow(); bool getGreen(); int getRed_Duration(); int getYellow_Duration(); int getGreen_Duration(); int getId(); int getElapsed_Time(); int getTick(); // part of the added time variable void cycle(); //This is the member function called cycle that takes no parameters and returns nothing. void printTrafficSignal(); void printState(); }; //constructor implementation TrafficSignal::TrafficSignal() { Red = true; Yellow = false; Green = false; Elapsed_Time = 0; Id = 1; Red_Duration = 40; //This is the length that a light stays Red Yellow_Duration = 10; //" " stays Yellow Green_Duration = 35; // " " stays Green } /* Below: This is the cycle member function written not in line. It is set up, if called on an object of type TrafficSignal, to move the signal's state to its next value. It will, if current light state is Red, move to Green. If the light's current state is yellow, then it WILL move to red, and if the light's current state is green, it WILL move to yellow.*/ void TrafficSignal::cycle(){ if (Red == true){ Red = false; Green = true; } if (Green == true){ Green = false; Yellow = true; } if (Yellow == true){ Yellow = false; Red = true; } } void TrafficSignal::printState(){ cout << "Signal " << Id << " is GREEN." << endl; cout << "Signal " << Id << " is Yellow." << endl; cout << "Signal " << Id << " is Red." << endl; } //****Start of the Sets!!!!******* void TrafficSignal::setRed(bool RED){ Red = RED; } void TrafficSignal::setYellow(bool YELLOW){ Yellow = YELLOW; } void TrafficSignal::setGreen(bool GREEN){ Green = GREEN; } void TrafficSignal::setRed_Duration(int Rd_Dur){ Red_Duration = 40; } void TrafficSignal::setYellow_Duration(int Ylw_Dur){ Yellow_Duration = 10; } void TrafficSignal::setGreen_Duration(int Grn_Dur){ Green_Duration = 35; } void TrafficSignal::setId(int New_ID){ Id=New_ID; } void TrafficSignal::setElapsed_Time(int Elp_Time){ } void TrafficSignal::setTick(int Tickcount){ } //****End of the Sets!!!!******* //****Start of the Gets!!!!******* int TrafficSignal::getTick(){ return (Tick); } bool TrafficSignal::getRed(){ return (Red); } bool TrafficSignal::getYellow(){ return (Yellow); } bool TrafficSignal::getGreen(){ return (Green); } int TrafficSignal::getRed_Duration(){ return (Red_Duration); } int TrafficSignal::getYellow_Duration(){ return (Yellow_Duration); } int TrafficSignal::getGreen_Duration(){ return (Green_Duration); } /*Below: This is where the printrafficsignal function retrieves the Id variables value. every time that the loop in the main function repeats it self, the Id value changes and is displayed in next c output on the screen. This keeps happening until the loop is finished.*/ int TrafficSignal::getId(){ return (Id); } int TrafficSignal::getElapsed_Time(){ return (Elapsed_Time); } /*Below: is the print traffic signal function, it is interconnected with the 4 signal array. The cout that you see in the printTrafficSignal will be displayed 4 times because of the loop that is in the main to create the 4 separate distinguishable traffic signals.*/ void TrafficSignal::printTrafficSignal(){ cout << "Signal " << Id << " is "/*<< output here for light state<<*/<< endl; } //****End of the Gets!!!!******* //TrafficSignal tick() //if (Green){ //} int main (){ const int NUM_SIGNALS=4; TrafficSignal signal[NUM_SIGNALS]; for (int i=0; i < NUM_SIGNALS; i++) {// This array sets up the name of the individual traffic signals (1 2 3 4) int localID=i+1; //This causes the printTrafficSignal to repeat the cout a specified number of times (4) signal[i].setId(localID); // signal[i].printTrafficSignal(); } } /* Ok, here is the problems that I am having: Tick Function Write a member function called Tick that takes no parameters, and returns a bool. That bool should indicate whether the TrafficSignal changed its state on this tick of the clock. Each time the Tick function is called, it should add one to the variable that is tracking the overall time in the TrafficSignal object. It should then, depending on the current state of the lights, and the time elapsed, either return false if it is not time to change the light, or it should call the cycle function, and return true if it is time to change the light. For example, if the light is currently green and the light's "stay green time" is 30 seconds, and it has been 30 seconds since it turned green, then call cycle and return true. If it has only been 29 seconds since the light turned green, then just return false without doing anything else. You may need an extra instance variable in the class to support this "time since the last cycle change" functionality. below has to do with setting up the main function In the same file, write a main function below all the class implementations that does the following. © = Complete (P) = I need help © 1. Allocate an array of four TrafficSignal objects. If you can't figure this out, you can use four individual TrafficSignal variables, but you'll lose 5 points. © 2. Give each of the traffic signals a different ID number. I used 1,2, 3, and 4 so it was easy to see what was going on. (P) 3. Set the durations for red/yellow/green to 60/15/60 for the first and third TrafficSignal, and 75/12/48 for the second and fourth. (P)4. Set the 2nd and 4th light state to green (leave the first and third on their default-red). (P)5. Write a loop that will count from 1 to 1000. This will be your "timer" loop. Each loop iteration will represent 1 second of time. (P)6. Inside the loop, call the tick function on each of the TrafficSignals each time through the loop. (P)If any of the trafficSignals returns true (i.e., it's state changed on that tick), you should call printState on that signal. See the example to the right as to what you should print. The bottom statement is what the instructor said that it should do! That's it. You should end up with at set of traffic signal states displayed on the console. Yours should be exactly the same as the example I show on the right given that you use the same data that has been specified in the problem. Make sure you write all required comments in your program. Don't embed magic numbers in your code - use data stored in the classes (that's what accessor functions are for...). If your program won't at least compile and run (even if it gives incorrect answers) you'll lose 10 points. So at least make sure it compiles and runs. On the right, the top figure is the beginning of the output from my solution, and the bottom figure is the end of the output from my solution. They overlap a bit in the middle, so you can see my entire output. Note: the main function writes the "At time..." lines, but the TrafficSignal class writes all the Signal XX is YYYYY lines, when the printState functions are called. Main shouldn't be very long. The class should do most of the work. */ Attached Files Edited by Jaan, 02 August 2008 - 02:53 AM. Use tags when you're posting your codes!
http://forum.codecall.net/topic/42147-traffic-signal-simulator-i-need-help/
crawl-003
refinedweb
1,314
59.74
This is your resource to discuss support topics with your peers, and learn from each other. 02-16-2013 01:39 PM Hi folks, Does anyone know how (or even if it's possible) to query processor information from the OS? I've looked through the documentation but services like Device Information (deviceinfo.h) don't seem to provide the necessary functionality. QNX's pidin utility looks like it can provide this information, but I have no idea what API calls it makes to query the information. Any suggestions or pointers? Thanks, John 02-18-2013 02:49 PM 02-22-2013 05:57 PM For BB10 QNX: have your app open and read "/proc/cpuinfo" as a text file. Not sure about the other BB operating systems. 03-28-2013 04:57 PM I don't see any such file -- at least when I'm using the SSH session from within Momentics (I haven't tried from within an app yet). I see other files in /proc and /dev, but not that one. $ cat /proc/cpuinfo /proc/cpuinfo: No such file or directory $ uname -a QNX BLACKBERRY-15BB 8.0.0 2013/01/27-14:00:10EST OMAP4460_ES1.1_HS_Colt_Rev:06 armle OS reports as Blackberry 10 OS Version 10.9.10.35. Am I missing something? 03-28-2013 05:08 PM Guess it's non standard then. I'm using a retail Canadian Z10 $ cat /proc/cpuinfo $ uname -a QNX BLACKBERRY-E5F8 8.0.0 2013/02/18-20:45:30EST MSM8960_V3.2.1_F_R070_Rev:19 armle 03-28-2013 05:28 PM 03-29-2013 02:02 AM I think that the OP is the guy behind Geekbench and he still hasn't figured out how to differentiate between OMAP4470 Z10 and Qualcomm S4 Z10. It would be nice for RIM to give him a solution. 03-29-2013 03:04 AM /proc/cpuinfo is definitely an android-ism. it is not part of QNX per se. You should be able to use uname -m for cpu rev. The source for uname.c pretty much just calls uname(), which you will find in sys/utsname.h 04-02-2013 12:22 AM What about the HardwareInfo class? #include <bb/device/HardwareInfo> Regards 04-02-2013 06:15 AM HardwareInfo class doesn't provide CPU related information.
https://supportforums.blackberry.com/t5/Native-Development/Querying-processor-Information/m-p/2272835/highlight/true
CC-MAIN-2017-13
refinedweb
388
76.22
Installing Addons Edit Page Ember has a rich ecosystem of addons that can be easily added to projects. Addons provide a wide range of functionality to projects, often saving time and letting you focus on your project. To browse addons, visit the Ember Observer website. It catalogs and categorizes ember addons that have been published to NPM and assigns them a score based on a variety of criteria. For Super Rentals, we'll take advantage of two addons: ember-cli-tutorial-style and ember-cli-mirage. ember-cli-tutorial-style Instead of having you copy/paste in CSS to style Super Rentals, we've created an addon called ember-cli-tutorial-style that instantly adds CSS to the tutorial. The addon works by creating a file called ember-tutorial.css and putting that file in the super-rentals vendor directory. As Ember CLI runs, it takes the ember-tutorial CSS file and puts it in vendor.css (which is referenced in /app/index.html). We can make additional style tweaks to /vendor/ember-tutorial.css, and the changes will take effect whenever we restart the app. Run the following command to install the addon: Since Ember addons are npm packages, ember install installs them in the node_modules directory, and makes an entry in package.json. Be sure to restart your server after the addon has installed successfully. Restarting the server will incorporate the new CSS and refreshing the browser window will give you this: ember-cli-mirage Mirage is a client HTTP stubbing library often used for Ember acceptance testing. For the case of this tutorial, we'll use mirage as our source of data. Mirage will allow us to create fake data to work with while developing our app and mimic a running backend server. Install the Mirage addon as follows: If you were running ember serve in another shell, restart the server to include Mirage in your build. Let's now configure Mirage to send back our rentals that we had defined above by updating /mirage/config.js: This configures Mirage so that whenever Ember Data makes a GET request to /api/rentals, Mirage will return this JavaScript object as JSON. In order for this to work, we need our application to default to making requests to the namespace of /api. Without this change, navigation to /rentals in our application would conflict with Mirage. To do this, we want to generate an application adapter. This adapter will extend the JSONAPIAdapter base class from Ember Data:
https://guides.emberjs.com/v2.7.0/tutorial/installing-addons/
CC-MAIN-2017-13
refinedweb
417
55.24
Hey guys, First time poster :) so quick background on my project. I've been asked to make a program that accesses a file and outputs what you've searched for. The file contains a list of the worlds capitols and their population. If you enter "North" it will spit out anything with that word in it, obviously. Problem is if there is no search result it does nothing...I want it to be able to display a message saying "Sorry, no results were found" but don't know where to start apart from the fact I know it would be a boolean varibale and an if statement in the end..guidance would be greatly appreciated Code was written in Bluej Source: __________________________________________________ ____________________________________________________________________________________ __________________________________Code : import java.util.Scanner; import java.io.File; import java.io.FileNotFoundException; public class Capitals {(); } } Thank you in advance :)
http://www.javaprogrammingforums.com/%20loops-control-statements/27024-if-no-search-results-found-display-message-but-how-question-printingthethread.html
CC-MAIN-2015-27
refinedweb
143
75
C# | Check if a SortedList object contains a specific value SortedList class is a collection of (key, value) pairs which are sorted according to keys. Those pairs can be accessible by key and as well as by index(zero-based indexing). This comes under System.Collections namespace. SortedList.ContainsValue(Object) method is used to check whether a SortedList object contains a specificValue (object value); Here, value is the value to locate in the SortedList objec and it can be null. Return Value: This method returns True if the SortedList object contains an element with the specified value, otherwise it returns False. Below programs illustrate the use of SortedList.ContainsValue(Object) Method: Example 1: False Example 2: True Note: - The values of the elements of the SortedList object are compared to the specified value using the Equals method. - This method performs a linear search, therefore, the average execution time is proportional to Count, i.e, this method is an O(n) operation, where n is Count. Reference: -
https://www.geeksforgeeks.org/c-sharp-check-if-a-sortedlist-object-contains-a-specific-value/?ref=rp
CC-MAIN-2021-31
refinedweb
166
53.81
a side-by-side reference sheet grammar and invocation | variables and expressions | arithmetic and logic | strings | regexes | dates and time | arrays | user-defined types | generic types | functions | execution control | exceptions | file handles | files | directories | processes and environment | libraries and namespaces General Notes version used The version used in this reference sheet. show version How to get the version. Grammar and Invocation hello word A "Hello, World!" example. ada: gnatmake takes care of compiling everything that the final executable depends on and linking the final executable. It is possible to compile and link in separate steps: $ cat hello.adb with Text_IO; use Text_IO; procedure Hello is begin Put_Line ("Hello World!"); end Hello; $ gnatgcc -gnat12 -c hello.adb $ gnatbind -gnat12 hello $ gnatlink -gnat12 hello $ ./hello Hello World! gnatgcc creates the files hello.ali and hello.o, and gnatlink creates the final executable hello. gnatbind creates the files b~hello2.adb and b~hello2.ads. It is a necessary precursor to gnatlink. gnatbind prevents linking a program in which objects are using incompatible versions of the same header. This is a safety feature not provided by C and C++ linkers. file suffixes Customary suffixes for source and object files. ada: The .adi file is generated whenever a .o file is generated. The .o file is what goes into the final executable. The .adi file contains information used by the compiler, including the flags that were used to comile the .o file and what files it depends on. end-of-line comment The syntax for a comment which ends at the end of the line. pascal: The // style comment is supported by Borland compilers and Free Pascal. multiple line comment The syntax for a comment which can span multiple lines. Variables and Expressions case sensitive Are identifiers case sensitive? pascal: Free Pascal Reserved Words and Modifiers A word in Pascal is reserved if it cannot be redefined by the programmer. The names for the built-in types: Integer, Boolean, etc. are not reserved. They are defined in the System unit and can be redefined by the programmer. Although Pascal is case insensitive, reserved words and modifiers are customarily written in lower case. Other identifiers are customarily written in upper camel case, also known as Pascal case. declare constant, type, variable How to declare a constant, type, or variable. assignment The syntax for assigning a value to a variable. pointer declaration How to declare a pointer. Arithmetic and Logic boolean type The boolean type. true and false The literals for true and false. falsehoods Values which evaluate as false in a boolean context. logical operators The logical operators for conjunction, disjunction, exclusive or, and negation. short circuit operators Short circuit versions of the logical operators. The short circuit version of and will not evaluate its second argument if the first is false. The short circuit version of or will not evaluate its second argument if the first is true. integer type float type fixed type relational operators min and max arithmetic operators integer division integer division by zero float division float division by zero power sqrt sqrt -1 transcendental functions float truncation absolute value integer overflow float overflow random number bit operators Strings string literal string concatenate Regular Expressions Dates and Time Arrays User-Defined Types Generic Types Functions define function How to define a function. postgresql: If "or replace" is omitted from the function definition and the function already exists, the statement fails with an error. Before PostgreSQL 8.0 parameters could not be assigned names in the function signature. The following syntax which is still valid was used: create or replace function foo(int, int) returns int as $$ declare @< >@i alias for $1; @< >@j alias for $2; begin @< >@return i + j; end; $$ language plpgsql; invoke function How to invoke a function. undefine function How to undefine a function. no return value How to define a function with no return value. Sometimes such functions are called procedure. Such a function is not useful unless it has a side effect. pass by reference How to pass a variable by reference. This permits the callee to modify the value in the variable. nested function How to define a function inside another function. plpgsql: Nested functions are a feature of Oracle's PL/SQL. A nested function has access to the local variables of the containing function; it is not visible or callable from outside of the containing function. overloaded function How to define multiple versions of a function, with the correct version chosen by the type of the arguments used at invocation. forward declaration How to declare a function before it is defined. Execution Control if The syntax for an if statement. while The syntax for a while statement. for The syntax for a for loop. break and continue How to break from a loop; how to jump to the next iteration of a loop. Exceptions raise exception How to raise an exception. postgresql: The raise statement can also be used to write info and warning messages. See write line to stderr. re-raise exception How to re-raise a caught exception. postgresql: PostgreSQL exceptions do not have a stack trace or preserve the line number at which the error originated, so re-raising an exception just preserves the exception type and message. define exception How to define a new exception type. postgresql: Any 5 character string of digits or uppercase letters may be used as an error code. Many error codes are already in use: handle any exception How to handle any exception. handle exception by type How to handle exceptions of a specific type. multiple exception handlers File Handles read line from stdin How to read a line from standard input. plpgsql: In a SQL session the stream on which the server receives SQL commands from the client can be regarded as the standard input. Furthermore the COPY command provides a mechanism for providing unquoted data on the input stream for insertion into a table. PL/pgSQL code does not have access to this stream, however; a COPY command cannot be run from within PL/pgSQL. Note that some PL/pgSQL code runs as triggers in which case no such stream exists. write line stdout How to write a line to stdout. plpgsql: In an interactive SQL session the server writes the results of SQL select statements to a stream which can be regarded as standard out. PL/pgSQL code cannot write to this stream, however. The only thing PL/pgSQL code can do with selected data is read it into local variables. write line stderr How to write a line to stderr. plpgsql: The RAISE statement is used to write to stderr. Each message must be assigned one of five log levels: debug, log, info, notice, warning. The message can be reported to the client, written to the server log, or both depending upon how the server is configured. Files Directories Processes and Environment Libraries and Namespaces Pascal Free Pascal: Reference Guide Free Pascal: Run-Time Language Reference Ada Ada Reference Manual GNAT Reference Manual GNAT User's Guide for Native Platforms Ada has about 60 reserved words; these are written with lower case letters. Other identifiers are written with underscores and capitalization, e.g. Put_Hello. Files use lower case letters and underscores, but are otherwise named after the package they contain. The package Put_Hello would go in the file put_hello.adb, with its specification in put_hello.ads. PL/SQL PostgreSQL 9.1 Documention: PL/pgSQL Porting from PL/SQL to PL/pgSQL Execute statement with no result: -- create table foo (s text, i int); create or replace function insert_foo(s text, i int) returns void as $$ begin insert into foo values (s, i); end; ) $$ language plpgsql; -- insert, update, and delete statements raise an -- exception if they fail Execute SQL in a string: create or replace function drop_table(tbl text) returns void as $$ begin execute 'drop table ' || quote_ident(tbl); end; $$ language plpgsql; Functions to prevent sql injection: - quote_literal - quote_nullable - quote_ident
http://hyperpolyglot.org/pascal
CC-MAIN-2018-13
refinedweb
1,327
57.27
2016 Best Price amusement park electric car for sale US $70000-700000 1 Set (Min. Order) 2015 Latest Style Electric Car charger For Electric Car Charg... US $280-320 1 Piece (Min. Order) TGP01S-A130 toy electric motor car for kids 1000 Pieces (Min. Order) Kit Electric Car US $2-8 1000 Sets (Min. Order) aluminum electric conversion kit car for wholesales HR-C-018 US $9-15 100 Pieces (Min. Order) 4 seats new selling electric car / electric car for older US $6000-8800 2 Units (Min. Order) 2 seats ABS electric car 60V 100ah lead-acid battery 2800W di... US $3970-4300 1 Piece (Min. Order) mobile two seats older peope and kids electric car US $1000-3500 1 Unit (Min. Order) 4 wheel electric utility vehicle for older US $500-2000 10 Pieces (Min. Order) luxury mobility scooter SW1400 for older and disabled people US $1250-1500 10 Units (Min. Order) 3 wheels cheap adults electric scooter for older US $300-500 5 Pieces (Min. Order) hot sale three wheel electric scooter/electric tricycle US $530-600 22 Pieces (Min. Order) Windstorm,Best selling electric scooter export indonesia for ... US $410-750 1 Piece (Min. Order) open cecarburetor for scooter US $700-1200 1 Piece (Min. Order) new design 8'' 10'' 12'' electric folding wheelchair, mobilit... US $900-1500 90 Parcels (Min. Order) 2014 cheap price small cars US $6000-8800 2 Units (Min. Order) Two seat Electric Mobility scooter for the older US $500-2000 5 Pieces (Min. Order) three wheel older and handicapped people electric mobility sc... US $0-220 10 Pieces (Min. Order) most popular sales mobility scooter/ tricycle for older peopl... US $500-650 30 Pieces (Min. Order) Solar energy mobility scooter SW1200 for happy older life US $600-900 10 Units (Min. Order) compact CE Approved BRI-S05 cemake electric car kids US $900-1200 1 Piece (Min. Order) 2014 best price and high quality electric car US $6000-8800 2 Units (Min. Order) import cheap china electric scooter 3 wheel for adults for ... US $300-500 5 Pieces (Min. Order) good quality electric double seat mobility scooter for elderl... US $500-2000 5 Pieces (Min. Order) For the older people use ,most popular sales electric tricycl... US $400-700 24 Pieces (Min. Order) outdoor older people or handicapped people three wheel ... US $0-327 10 Pieces (Min. Order) Escooter for the older with two seat US $500-2000 5 Pieces (Min. Order) Cheap Portable GPS Tracker 102b GPS Personal Tracker With Pe... US $25-38 100 Pieces (Min. Order) High quality best price kids indoor/outdoor sand digger batt... US $25.5-35.5 1 Set (Min. Order) green 3 wheel electric bicycle with basket for older US $450-500 68 Pieces (Min. Order) Double row 3 Wheel electric scooter for older US $500-550 20 Pieces (Min. Order) two seats older peope and kids electric car US $4006-4467
http://www.alibaba.com/showroom/electric-car-for-olders.html
CC-MAIN-2016-07
refinedweb
489
78.04
In programming, it is often desired to execute certain block of statements for a specified number of times. A possible solution will be to type those statements for the required number of times. However, the number of repetition may not be known in advance (during compile time) or maybe large enough (say 10000). The best solution to such problem is loop. Loops are used in programming to repeatedly execute a certain block of statements until some condition is met. In this article, we'll learn to use while loops in C#. C# while loop The while keyword is used to create while loop in C#. The syntax for while loop is: while (test-expression) { // body of while } How while loop works? - C# while loop consists of a test-expression. - If the test-expressionis evaluated to true, - statements inside the while loop are executed. - after execution, the test-expressionis evaluated again. - If the test-expressionis evaluated to false, the while loop terminates. while loop Flowchart Example 1: while Loop using System; namespace Loop { class WhileLoop { public static void Main(string[] args) { int i=1; while (i<=5) { Console.WriteLine("C# For Loop: Iteration {0}", i); i++; } } } } When we run the program, the output will be: C# For Loop: Iteration 1 C# For Loop: Iteration 2 C# For Loop: Iteration 3 C# For Loop: Iteration 4 C# For Loop: Iteration 5 Initially the value of i is 1. When the program reaches the while loop statement, - the test expression i <=5is evaluated. Since i is 1 and 1 <= 5is true, it executes the body of the while loop. Here, the line is printed on the screen with Iteration 1, and the value of i is increased by 1 to become 2. - Now, the test expression ( i <=5) is evaluated again. This time too, the expression returns true(2 <= 5), so the line is printed on the screen and the value of i is now incremented to 3.. - This goes and the while loop executes until i becomes 6. At this point, the test-expression will evaluate to falseand hence the loop terminates. Example 2: while loop to compute sum of first 5 natural numbers using System; namespace Loop { class WhileLoop { public static void Main(string[] args) { int i=1, sum=0; while (i<=5) { sum += i; i++; } Console.WriteLine("Sum = {0}", sum); } } } When we run the program, the output will be: Sum = 15 This program computes the sum of first 5 natural numbers. - Initially the value of sum is initialized to 0. - On each iteration, the value of sum is updated to sum+iand the value of i is incremented by 1. - When the value of i reaches 6, the test expression i<=5will return false and the loop terminates. Let's see what happens in the given program on each iteration. Initially, i = 1, sum = 0 So, the final value of sum will be 15. C# do...while loop The do and while keyword is used to create a do...while loop. It is similar to a while loop, however there is a major difference between them.: do { // body of do while loop } while (test-expression); How do...while loop works? - The body of do...while loop is executed at first. - Then the test-expressionis evaluated. - If the test-expressionis true, the body of loop is executed. - When the test-expressionis false, do...while loop terminates. do...while loop Flowchart Example 3: do...while loop using System; namespace Loop { class DoWhileLoop { public static void Main(string[] args) { int i = 1, n = 5, product; do { product = n * i; Console.WriteLine("{0} * {1} = {2}", n, i, product); i++; } while (i <= 10); } } } When we run the program, the output will be: 5 * 1 = 5 5 * 2 = 10 5 * 3 = 15 5 * 4 = 20 5 * 5 = 25 5 * 6 = 30 5 * 7 = 35 5 * 8 = 40 5 * 9 = 45 5 * 10 = 50 As we can see, the above program prints the multiplication table of a number (5). - Initially, the value of i is 1. The program, then enters the body of do..while loop without checking any condition (as opposed to while loop). - Inside the body, product is calculated and printed on the screen. The value of i is then incremented to 2. - After the execution of the loop’s body, the test expression i <= 10is evaluated. In total, the do...while loop will run for 10 times. - Finally, when the value of i is 11, the test-expression evaluates to falseand hence terminates the loop. Infinite while and do...while loop If the test expression in the while and do...while loop never evaluates to false, the body of loop will run forever. Such loops are called infinite loop. For example: Infinite while loop while (true) { // body of while loop } Infinite do...while loop do { // body of while loop } while (true);.
https://cdn.programiz.com/csharp-programming/do-while-loop
CC-MAIN-2020-40
refinedweb
807
66.13
I'm trying to use the SDRAM from my STM32F429-Disco Board. I have created a function to initialize the SDRAM which is executed in the main-function. The SDRAM implementation was done with the following instruction: and should work since I'm able to write to the SDRAM. THe SDRAM Initialization function is executed in the main function. I'm not sure but I think the problem is with my linker skript or syscall.c I changed the following things in files, syscall.c -The following code: caddr_t _sbrk(int incr) { extern char end asm("end"); static char *heap_end; char *prev_heap_end; if (heap_end == 0) heap_end = &end; prev_heap_end = heap_end; if (heap_end + incr > stack_ptr) { // write(1, "Heap and stack collision\n", 25); // abort(); errno = ENOMEM; return (caddr_t) -1; } heap_end += incr; return (caddr_t) prev_heap_end; } to the following syscall.c: caddr_t _sbrk(int incr) { // extern char end asm("end"); // June 2019 - US extern char __heap_start asm ("__heap_start"); extern char __heap_limit asm ("__heap_limit"); static char *heap_end; static char *heap_limit = &__heap_limit; char *prev_heap_end; if (heap_end == 0) heap_end = &__heap_start; prev_heap_end = heap_end; if (heap_end + incr > heap_limit) { // write(1, "Heap and stack collision\n", 25); // abort(); errno = ENOMEM; return (caddr_t) -1; } heap_end += incr; return (caddr_t) prev_heap_end; } And for the linker skript, I changed: heap was commented out heap_start and heap_limit was added SDRAM was added to the memory areas user_stack was altered /*_Min_Heap_Size = 0x200; /* required amount of heap commented out*/ __heap_start = 0xD0000000; /*Was added*/ __heap_limit = 0xD0800000; /*Was added*/ /* Specify the memory areas - SDRAM was added */ MEMORY { FLASH (rx) : ORIGIN = 0x8000000, LENGTH = 2048K RAM (xrw) : ORIGIN = 0x20000000, LENGTH = 192K CCMRAM (rw) : ORIGIN = 0x10000000, LENGTH = 64K SDRAM (xrw) : ORIGIN = 0xD000000, LENGTH = 8M } /* User_stack section, used to check that there is enough RAM left was altered */ ._user_stack : { . = ALIGN(8); PROVIDE ( end = . ); PROVIDE ( _end = . ); . = . + _Min_Stack_Size; . = ALIGN(8); } >RAM But I have the problem, when I create a big array - globally - with: volatile uint16_t test[76800]; I still get an RAM overflow, which should not happen since the SDRAM should be used. How can I fix this, to use the SDRAM as extension of the RAM? Thank you I still get an RAM overflow, which should not happen since the SDRAM should be used. There is nothing in your code telling the linker to put the big array in the SDRAM area, so it'd still try to allocate it in RAM. Create a section for it in the linker file .bigdata : { . = ALIGN(4); *(.bigdata) *(.bigdata*) . = ALIGN(4); } >SDRAM and tell the compiler to put the array there volatile uint16_t test[76800] __attribute__((section(".bigdata"))); Likewise you should create a proper section for the heap to be allocated in SDRAM ._user_heap : { . = ALIGN(64); PROVIDE ( __heap_start = . ); . = . + Heap_Size; PROVIDE ( __heap_limit = . ); . = ALIGN(4); } >SDRAM Otherwise they would overlap. Keep in mind that variables outside the regular data area won't be initialized by the startup code, so they'd contain whatever junk there was in the SDRAM at powerup. Also note that your definition of ORIGIN = 0xD000000 contains one too few zeroes. User contributions licensed under CC BY-SA 3.0
https://windows-hexerror.linestarve.com/q/so56458645-STM32F429-Disco-RAM-Extension-with-SDRAM-Linker-Skript-wrong
CC-MAIN-2020-34
refinedweb
505
66.57
This article explains how to add a click event to an anchor tag and navigate across different sections of a page. Learn how to navigate different web pages and dynamically add and remove HTML elements. The HTML anchor tag is used in the following use cases. - Navigate to different pages - Go to a specific div or section of the page, such as the top, bottom, or specified div. - Dynamically add/remove HTML components Do we have a href tag to navigate purposes? Can we use the href attribute in the Angular application? href is not supported in Angular, But you can use a property binding event, for example, attach a click event to it, write a navigation code in click binding event. How do you navigate without the href attribute? You have to write a code to handle the anchor click binding event. Whenever use clicks on anchor event, It triggers the DOM event binding. First, create an angular application using the ng CLI command. This article does not cover how to create an angular application. Let’s see some examples for anchor event binding. You can see my previous about Angular button click event example Anchor click event without href Anchor tag has href and clicks event in legacy applications, but href are not supported in Angular application. In the HTML template file, please add an anchor tag with click events as follows. important points - href is not required as it forwards the request - you can also add href=“javascript: void(0);” - Add click event with calling function - Anchor displays as a link, change the style as cursor =pointer to clickable like a button <div style="text-align:center"> <h1> Angular Button Click Event Example </h1> <a class ='btn' style="cursor:pointer"(click)="clickme();">click me</a> or <a href="javascript: void(0);" (click)="clickme()"> click here <h2>{{msg}}</h2> </div> In your typescript code import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { msg:string; constructor() { } clickme(){ this.msg='anchor tag is Clicked'; return this.msg; } } Angular anchor tag routeLink example? Using links, You can navigate from one page to another page or move from one position to another position on a single page. It achieves using the anchor href attribute in legacy javascript and jquery apps. In Angular application, the same can be achieved with the router link attribute as seen below. In Angular component HTML file router link path must be configured in router file as seen below { path: 'home', component: HomeComponent } In angular component <a routerLink="/home"> Home</a> or with binding <a [routerLink]="/home"> Home</a> How to open link url in a new window in Angular? In this example, You have an angular component that has a link, when a user clicked on it, It opens a new link url in a new browser tab or new window. In javascript, We have a window. open method to open a new window. It is easy and simple to use in angular components. This can be done in two ways. Using click event handler- windows. open accepts the first parameter as link url and the second optional parameter contains the value to open a link same or new window. In app.component.html file <a (click)="openLink("")">Go to cloudhadoop</a> In typescript component - app.component.ts file - openLink(url: string){ window.open(url, "_blank"); } using href attribute <a href="" target="_blank">Open </a> How to disable anchor link in Angular component? Sometimes, We want to disable anchor links based on typescript variables. Normally, We will disable anchor links in components in many ways as follows. The first way is to use the class attribute directive. In component.css file - .disable{ pointer-events:none; } And component.html <a href="#" [class.disable]="true">Add item</a> Second way using style attribute directive <a href="#" [style.pointer-events]="'none" >Add item</a> The third way use the ngClass directive. <a [ngClass]="{'disabled': true}"> Add Item</a> How do you disable anchor tag with click event? It is an example of doing disabled programmatically. Declare a variable- is disabled in a typescript component and initialized with false. In the click event, the update is disabled to true. app.component.ts file- import { Component } from '@angular/core'; @Component({ selector: 'app-root', templateUrl: './app.component.html', styleUrls: ['./app.component.css'] }) export class AppComponent { isDisable:boolean=false; constructor() { } disableOtherLinks(){ this.isDisable=true; } } HTML template file, We have Six anchor links, On clicking the first link, the variable value is set to true, This variable is used to bind in other 5 links to disabled. The following conditional attributes are used with - ngStyle attribute - style.pointer-events - attr.disabled - ngClass In app.component.html - <a href="javascript: void(0);" (click)="disableOtherLinks()"> Disable All links except me <a [ngStyle]="{'pointer-events': isDisable ? 'none': 'auto'}" > Link1 <a [style.pointer-events]="isDisable ?'none':'auto'">Link2</a> <a [style.pointer-events]="isDisable ?'none':'auto'">Link3</a> <a [attr.disabled]="isDisable">Link4</a> <a [ngClass]="{'disabled': isDisable}"> Link5</a> Conclusion In angular, href is not supported, so learned multiple ways to do navigation using routelink and event binding click event.
https://www.cloudhadoop.com/angular-anchor-click-event/
CC-MAIN-2022-21
refinedweb
864
57.06
GPy with Hologram.io SIM Here's what I'm getting now after increasing the delay to 5 secs in loop with the AT+CEER command. I updated the image to show the correct time counter. I'm available to allow you to remote into our system anytime. I'll order a new antenna today if you want to wait until I have the correct antenna. - jmarcelino last edited by @tlanier RSSI (from CSQ) is only one measurement. Are you still not seeing CEREG returning 2,5 ? Ideally you'd use an antenna supporting 700Mhz bands, of course your antenna works on that frequency but doesn't appear designed for it so you may be losing some signal. Can you increase the delay on your attach loop to 5s time.sleep(5)and add at('AT+CEER')at each iteration to see if there's any error reported? After moving the unit to a different office, I'm now getting: +CEREG: 2,4 +CSQ: 99,99 @jmarcelino has indicated that I have the wrong type of antenna. I've moved the unit to a front office where I'm now getting +CSQ: 15,99 signal strength. You may have discovered my problem about the antenna. My hardware guy is not here at this moment, but this is the part number I got off our last order which is what we use for our 4G LTE modems connecting to T-Mobile. Would the fact that I'm now getting a signal strength of 15 not indicate that the antenna is sufficient? - jmarcelino last edited by jmarcelino @tlanier Which antenna is that? Do you have a link? Is it suitable for 746-787Mhz (Band 13) operation? Nothing special about the setup. @chrisgammell I'm getting a +CSQ: 11,99 here indoors. - jmarcelino last edited by jmarcelino Thank you both so much for your continued tests. @ChrisGammell We're investigating your .connect() problems. I think our command timeouts were very short for some situations and I've let the LTE team know, hope to see an improvement on the next release. Modem firmware could have an impact but it's hard for us to tell because our modem manufacturer, very much like Verizon, just doesn't understand roaming MVNOs like Hologram. They only think in terms of carrier certification with the carrier's own SIM card. That said it won't harm anything to try a newer modem firmware as long as you are careful with the upgrade - give it lots of time to complete even when it seems nothing is happening! We should be releasing a more streamlined modem upgrade process soon so you can also wait for that instead. If anyone else can help us run some tests with Hologram especially in a known good coverage area where you already see 2,5 and valid CSQ let us know. It would help if perhaps someone can give us remote access (e.g. TeamViewer) to check out a few parameters. I'm just using the expansion board 2.0 with the GPy powered using the USB port to my computer desktop. I've also drove around in the car with the unit plugged into the USB port on my car. I'll try the AT+CSQ command in the morning and post the results. As a new user the system will only allow me to post every 10 mins so I sitting here waiting for the 10 mins to expire so I can send this post... I did do the firmware update from: I have not done the modem firmware update. Thanks for the link. I will try that first thing in the morning. I added at('at+csq') into the loop and saw that as the device eventually finds its way onto the network here locally, it goes from "99, 99" to "11, 99" or so. Does yours change if you insert that into the loop, @tlanier? Also could you post a picture of your mobile rig? I'm curious about how you have it all hooked up and powered and such. Speaking of frustrated, I'm still getting errors from lte.connect(), is there a way to get a more verbose output? I just saw in the docs that there is a firmware update for the modem as well as as the Pycom boards themselves, going to try that now. Is it possible that that could be contributing to the problem? @tlanier said in GPy with Hologram.io SIM: The Verizon Wireless HelpDesk @ 800-525-0481 has now told us our Hologram SIM is not a valid SIM on their network Yep, still trying things here as well. As Ryan said over on our forum, it's possible that Verizon does not have direct records of our SIMs on their network and we encourage everyone to contact us directly for connectivity. We understand you're frustrated while we try to get this sussed out, we are as well. The problem with SIM cards that normally "just work"...is when they don't. The Verizon Wireless HelpDesk @ 800-525-0481 has now told us our Hologram SIM is not a valid SIM on their network. We have contacted Hologram to try to determine what could be the problem. No word yet from Hologram. We've talked to the Verizon open development team and they indicated that CAT M1 is on ALL Verizon LTE towers in the country. There's got to be some explanation as to why we cannot connect with the GPy. Anybody know how to get an evaluation Cat M1 SIM that will work. On the Verizon web page they state: "Machine to Machine Plans are available only to business customers with five or more CLEU lines that have signed a Major Account Agreement. " Verizon Machine to Machine Plans I talked to Kore about a month ago, and they did not offer Cat M1 SIM's at that time. - jmarcelino last edited by I drove through both Newnan, GA and Peachtree City, GA with the GPy running in my car. The device never attached to any tower even though I passed by many towers within visible sight. Thanks for catching the misunderstanding! Here's my revised code. The at(cmd) function has been improved to return the modem response as a list making it easier to parse. I've also added logic to break on <tac> = 1 or 5 just in case the isattached() function is not working. I will take the GPy north towards Atlanta today and see if I can connect there. import pycom import socket import ssl import sys import time from network import LTE # send AT command to modem and return response as list def at(cmd): print("modem command: {}".format(cmd)) r = lte.send_at_cmd(cmd).split('\r\n') r = list(filter(None, r)) print("response={}".format(r)) return r ####################################################### print("CAT M1 Test - V0.3 - 4/15/18") print("disable MicroPython control of LED") pycom.heartbeat(False) pycom.rgbled(0xFFFFFF) # (i % 2 == 0): pycom.rgbled(0xFF0000) # Red else: pycom.rgbled(0x000000) # Off) #") pycom.rgbled(0xFFFF00) # Yellow while True: pass
https://forum.pycom.io/topic/3021/gpy-with-hologram-io-sim/56?lang=en-US
CC-MAIN-2022-40
refinedweb
1,185
73.78
Parquet is a famous file format used with several tools such as Spark. NiFi can be used to easily convert data from different formats such as Avro, CSV or JSON to Parquet. This article explains how to convert data from JSON to Parquet using the PutParquet processor. In this article I'll be using JSON data source with the following structure: { "created_at" : "Tue Oct 10 21:47:12 CEST 2017", "id_store" : 4, "event_type" : "store capacity", "id_transaction" : "6594277248900858122", "id_product" : 319, "value_product" : 1507664832649 } Since we will be using a record based processor, we need to define a schema for our data. This will be an Avro schema but it can be used with other types as well. It's only "a common langage" that helps us describe a schema. The Avro Schema for my data is the following: { "namespace": "nifi", "name": "store_event", "type": "record", "fields": [ { "name": "created_at", "type": "string" }, { "name": "id_store", "type": "int" }, { "name": "event_type", "type": "string" }, { "name": "id_transaction", "type": "string" }, { "name": "id_product", "type": "int" }, { "name": "value_product", "type": "int" } ] } For testing, I'll generate random dummy data using a GenerateFlowFile processor with the following configuration Now let's use a PutParquet processor to convert our data. PutParquet is a special record based processor because of the specifities of Parquet format. Since Parquet's API is based on the Hadoop Path object, and not InputStreams/OutputStreams, NiFi doesn't generate a Parquet flow file directly. Instead, NiFi takes data in record format (in memory) and write it in Parquet on an HDFS cluster. For this reason, we need to configure PutParquet with a Hadoop cluster like we usually do for a PutHDFS. Let's connect the different processors and start data generation/conversion. As discussed before, PutParquet writes parquet data directly into HDFS. Let's check in /tmp/nifi to see the generated data. Note that data coming out from this processor will be the original JSON data. If the result Parquet files are required for the remaining of the flow, NiFi should pull them from HDFS using List/FetchHDFS. Now let's try and read the data in HDFS to check if we have all the information and the right format. There are several ways to do it. What I like to do is to start a Spark shell and try to read the content of my file. Spark has a very good built-in support for Parquet. Start a Spark-Shell session and run the following code val myParquet = sqlContext.read.parquet("/tmp/nifi/748458744258259") myParquet.show() As you can see in the screenshot below, we got the same schema and data from our initial JSON data. If you want to convert other data than JSON, you can use the same process with other RecordReader such as Avro or CSV record reader. Created on 12-06-2017 03:13 PM Hi, thank for your tuto. Do you know if PutParquet could to deal with "date", "timestamp" type or it depends avro Schema ? So the answer is NO.. Hi @mayki wogno I didn't test it but you should be able to do it. At least RecordReader support it :... Created on 02-20-2018 01:51 PM Any recommendations on converting XML to Parquet? Created on 06-04-2019 09:52 AM Waht If i wanted to put my parquet into an S£ instead of HDFS?
https://community.cloudera.com/t5/Community-Articles/Convert-data-from-JSON-CSV-Avro-to-Parquet-with-NiFi/tac-p/247101
CC-MAIN-2020-05
refinedweb
554
62.27
Functional programming is a paradigm of building computer programs using expressions and functions without mutating state and data. By respecting these restrictions, functional programming aims to write code that is clearer to understand and more bug resistant. This is achieved by avoiding using flow-control statements ( for, while, break, continue, goto) which make the code harder to follow. Also, functional programming requires us to write pure, deterministic functions which are less likely to be buggy. In this article, we will talk about doing functional programming using JavaScript. We will also explore various JavaScript methods and features that make it possible. In the end, we will explore different concepts associated with functional programming and see why they are so powerful. Before getting into functional programming, though, one needs to understand the difference between pure and impure functions. Pure vs. Impure Functions Pure functions take some input and give a fixed output. Also, they cause no side effects in the outside world. const add = (a, b) => a + b; Here, add is a pure function. This is because, for a fixed value of a and b, the output will always be the same. const SECRET = 42; const getId = (a) => SECRET * a; getId is not a pure function. The reason being that it uses the global variable SECRET for computing the output. If SECRET were to change, the getId function will return a different value for the same input. Thus, it is not a pure function. let id_count = 0; const getId = () => ++id_count; This is also an impure function, and that too for a couple of reasons—(1) it uses a non-local variable for computing its output, and (2) it creates a side effect in the outside world by modifying a variable in that world. This can be troublesome if we had to debug this code. What’s the current value of id_count? Which other functions are modifying id_count? Are there other functions relying on id_count? Because of these reasons, we only use pure functions in functional programming. Another benefit of pure functions is that they can be parallelized and memoized. Have a look at the previous two functions. It’s impossible to parallelize or memoize them. This helps in creating performant code. The Tenets of Functional Programming So far, we have learned that functional programming is dependent on a few rules. They are as follows. - Don’t mutate data - Use pure functions: fixed output for fixed inputs, and no side effects - Use expressions and declarations When we satisfy these conditions, we can say our code is functional. Functional Programming in JavaScript JavaScript already has some functions that enable functional programming. Example: String.prototype.slice, Array.protoype.filter, Array.prototype.join. On the other hand, Array.prototype.forEach, Array.prototype.push are impure functions. One can argue that Array.prototype.forEach is not an impure function by design but think about it—it’s not possible to do anything with it except mutating non-local data or doing side effects. Thus, it’s okay to put it in the category of impure functions. Also, JavaScript has a const declaration, which is perfect for functional programming since we won’t be mutating any data. Pure Functions in JavaScript Let’s look at some of the pure functions (methods) given by JavaScript. Filter As the name suggests, this filters the array. array.filter(condition); The condition here is a function that gets each item of the array, and it should decide whether to keep the item or not and return the truthy boolean value for that. const filterEven = x => x%2 === 0; [1, 2, 3].filter(filterEven); // [2] Notice that filterEven is a pure function. If it had been impure, then it would have made the entire filter call impure. Map map maps each item of array to a function and creates a new array based on the return values of the function calls. array.map(mapper) mapper is a function that takes an item of an array as input and returns the output. const double = x => 2 * x; [1, 2, 3].map(double); // [2, 4, 6] Reduce reduce reduces the array to a single value. array.reduce(reducer); reducer is a function that takes the accumulated value and the next item in the array and returns the new value. It is called like this for all values in the array, one after another. const sum = (accumulatedSum, arrayItem) => accumulatedSum + arrayItem [1, 2, 3].reduce(sum); // 6 Concat concat adds new items to an existing array to create a new array. It’s different from push() in the sense that push() mutates data, which makes it impure. [1, 2].concat([3, 4]) // [1, 2, 3, 4] You can also do the same using the spread operator. [1, 2, ...[3, 4]] Object.assign Object.assign copies values from the provided object to a new object. Since functional programming is predicated on immutable data, we use it to make new objects based on existing objects. const obj = {a : 2}; const newObj = Object.assign({}, obj); newObj.a = 3; obj.a; // 2 With the advent of ES6, this can also be done using the spread operator. const newObj = {...obj}; Creating Your Own Pure Function We can create our pure function as well. Let’s do one for duplicating a string n number of times. const duplicate = (str, n) => n < 1 ? '' : str + duplicate(str, n-1); This function duplicates a string n times and returns a new string. duplicate('hooray!', 3) // hooray!hooray!hooray! Higher-order Functions Higher-order functions are functions that accept a function as an argument and return a function. Often, they are used to add to the functionality of a function. const withLog = (fn) => { return (...args) => { console.log(`calling ${fn.name}`); return fn(...args); }; }; In the above example, we create a withLog higher-order function that takes a function and returns a function that logs a message before the wrapped function runs. const add = (a, b) => a + b; const addWithLogging = withLog(add); addWithLogging(3, 4); // calling add // 7 withLog HOF can be used with other functions as well and it works without any conflicts or writing extra code. This is the beauty of a HOF. const addWithLogging = withLog(add); const hype = s => s + '!!!'; const hypeWithLogging = withLog(hype); hypeWithLogging('Sale'); // calling hype // Sale!!! One can also call it without defining a combining function. withLog(hype)('Sale'); // calling hype // Sale!!! Currying Currying means breaking down a function that takes multiple arguments into one or multiple levels of higher-order functions. Let’s take the add function. const add = (a, b) => a + b; When we are to curry it, we rewrite it distributing arguments into multiple levels as follows. const add = a => { return b => { return a + b; }; }; add(3)(4); // 7 The benefit of currying is memoization. We can now memoize certain arguments in a function call so that they can be reused later without duplication and re-computation. // assume getOffsetNumer() call is expensive const addOffset = add(getOffsetNumber()); addOffset(4); // 4 + getOffsetNumber() addOffset(6); This is certainly better than using both arguments everywhere. // (X) DON"T DO THIS add(4, getOffsetNumber()); add(6, getOffsetNumber()); add(10, getOffsetNumber()); We can also reformat our curried function to look succinct. This is because each level of the currying function call is a single line return statement. Therefore, we can use arrow functions in ES6 to refactor it as follows. const add = a => b => a + b; Composition In mathematics, composition is defined as passing the output of one function into input of another so as to create a combined output. The same is possible in functional programming since we are using pure functions. To show an example, let’s create some functions. The first function is range, which takes a starting number a and an ending number b and creates an array consisting of numbers from a to b. const range = (a, b) => a > b ? [] : [a, ...range(a+1, b)]; Then we have a function multiply that takes an array and multiplies all the numbers in it. const multiply = arr => arr.reduce((p, a) => p * a); We will use these functions together to calculate factorial. const factorial = n => multiply(range(1, n)); factorial(5); // 120 factorial(6); // 720 The above function for calculating factorial is similar to f(x) = g(h(x)), thus demonstrating the composition property. Concluding Words We went through pure and impure functions, functional programming, the new JavaScript features that help with it, and a few key concepts in functional programming. We hope that this piece piques your interest in functional programming and possibly motivates you to try it in your code. We are positive that it will be a learning experience and a milestone in your software development journey. Functional programming is a well-researched and robust paradigm of writing computer programs. With the introduction of ES6, JavaScript allows for a much better functional programming experience than ever before. Understanding the basics Functional programming is a paradigm of building computer programs using declarations and expressions. Thanks to new developments in ES6, we can say that JavaScript is both a functional as well as object-oriented programming language because of the various first-class features it provides. Functional programming ensures simpler flow control in our code and avoids any surprises in the form of variable and state changes. All this helps us avoid bugs and understand our code easily. Lisp, Erlang, Haskell, Closure, and Python are other functional programming languages. In these, Haskell is a purely functional programming language in the sense that it allows no other paradigm of programming. ES6 or ECMAScript 6 is a new version of JavaScript that includes many new features like arrow functions, constants, and spread operators, among many others.
https://www.toptal.com/javascript/functional-programming-javascript?utm_campaign=Toptal%20Engineering%20Blog&utm_source=hs_email&utm_medium=email&utm_content=77454362&_hsenc=p2ANqtz-9pzwmyOIgQZ3-LFMs9vfjvIxj6stLXFM9vzqI5IWDlsQHxO1K4ZGpXtRBQRdWO8KT2pbO2hBhj8b3YqR71IusQXQMHbA&_hsmi=77454362
CC-MAIN-2021-43
refinedweb
1,613
56.66
I give the prompt at the end to checkout another customer, they have to pick Y or N. If they pick N it will go to the good bye, sotre closing, ect...but if they pick Y then it just sits there, it does not know to go back up top to customer two....how can I change this? Bryan Code:#include <iostream> #include <fstream> #include <cctype> #include <string> //#include "grocery.h" using namespace std; int ProdNum; string ProdName; float ProdPrice; char Taxable; int Quantity; const int tax_rate=.075; int main() { ifstream OpenFile("inventory.txt"); char ch; while(!OpenFile.eof()) { OpenFile.get(ch); cout << ch; } cout << endl << endl; cout << "Thanks for shopping at OUR Market." << endl << endl; { int customer = 1; cout << "Enter product number and Quantity for customer " << customer++ << endl; cout << "Enter product code 0 to end purchases." << endl << endl; do { cin >> ProdNum; Quantity; } while (ProdNum!=0); cout<<"Thanks for shopping, your receipt is printed below" << endl << endl; } { cout << "Do you want to checkout another customer? (Y) or (N)" << endl; char more; do { cin >> more; } while (more != 'N'); cout << "Close the store for the night. Bye." << endl; } return 0; }
https://cboard.cprogramming.com/cplusplus-programming/45206-continue-yes-no.html
CC-MAIN-2017-47
refinedweb
189
84.98
WLAN_profile Schema The WLAN_profile Schema defines a WLAN profile used by the Native Wifi AutoConfig service. The AutoConfig service accepts wireless profiles from the Group Policy Agent, the scripting interface (netsh), the user interface, or from the USB flash configuration interface. A profile received from one of these systems is mapped to the WLAN_profile schema and stored in the profile store. Profiles can be exported from the profile store using netsh commands or using API elements such as WlanGetProfile. The root element of a WLAN profile is the WLANProfile element. Each profile will have exactly one root element. The WLANProfile element is in the namespace. To view sample WLAN profiles, see Wireless Profile Samples. Related topics
https://docs.microsoft.com/en-us/windows/desktop/NativeWiFi/wlan-profileschema-schema
CC-MAIN-2018-34
refinedweb
116
56.76
Up to [cvs.NetBSD.org] / src / share / examples / puffs Request diff between arbitrary revisions Default branch: MAIN Revision 1.3 / (download) - annotate - [select for diffs], Wed Aug 15 14:13:57 2007 UTC (7 years,, HEAD Changes since 1.2: +2 -2 lines Diff to previous 1.2 (colored) sysctlfs was moved to base Revision 1.2 / (download) - annotate - [select for diffs], Sun Jun 24 18:32:00 2007 UTC (7 years, 4 months ago) by pooka Branch: MAIN CVS Tags: matt-mips64-base, matt-mips64, hpcarm-cleanup Changes since 1.1: +2 -2 lines Diff to previous 1.1 (colored) I wasn't going to add any more silly examples, but I'll bite for this one, since it's a good exercise .. Add icfs, which does the same thing as the refuse-based icfs agc added earlier this week, i.e. null-mounts & converts the entire namespace to lowercase. However, it's a fun comparison, since this is implemented in a completely different fashion from the refuse version. Revision 1.1 / (download) - annotate - [select for diffs], Tue Jan 30 01:26:58 2007 UTC (7 years, 9 months ago) by gdt Branch: MAIN Even though the parent doesn't descend here, it's still convenient to have a makefile to build the 4 examples at once. This form allows you to request diff's between any two revisions of a file. You may select a symbolic revision name using the selection box or you may type in a numeric name using the type-in text box.
http://cvsweb.netbsd.org/bsdweb.cgi/src/share/examples/puffs/Makefile
CC-MAIN-2014-49
refinedweb
258
71.85
Another Workaround for the "Yosemite Problem" Mac OS X 10.10 (Yosemite) currently does not properly handle HDK-based mbed devices. When we connect such an mbed (e.g., FRDM-KL25) to a Mac running Yosemite, a dialog saying "OS X can't repair the disk ..." appears and the device is mounted in read-only mode. Fortunately for us, Okano-san already brought out an easy-to-use droplet that helps copying files into such devices. Here is another workaround inspired by Okano-san's droplet; a launchd daemon version. The daemon continuously watches the file system of your Mac and automatically fixes the mode of an mbed to be writable when the device is connected. This also enables direct drag & drop copying of files into the mbed drive. Warning You need to be able to execute sudo for setting up this daemon. Incorrect sudo operations may cause serious damage to your system. The author tested this with only a limited number of mbeds and Macs. Please use this at your own risk. Installation - Download the package - Unzip the package and execute install.sh as root unzip mbedremounter.zip cd mbedremounter sudo sh install.sh Uninstallation - Execute uninstall.sh as root sudo sh uninstall.sh Usage - Connect your (HDK-based) mbed devices. You can ignore the warning dialog by pressing "OK". - Now your mbed drives are writable and you are ready to copy your executables to them. Drag-and-drop copying is also possible. Tested Platforms I've briefly tested that this daemon works with the following mbed platforms. - NXP mbed LPC1768 (this device works well without the daemon) - NXP LPC00-MAX - Freescale FRDM-KL25Z - Freescale FRDM-KL46Z - Freescale FRDM-K46F - ST Nucleo F401RE - Nordic nRF51822 - Switch Science mbed HRM1017 I'm thankful to Okano-san who reported that this works with the following platforms. - Switch Science mbed LPC824 - Switch Science mbed LPC1114FN28 Code The daemon continuously watches the file system of your Mac and start the following Python script every time a disk is mounted. If the disk is mounted on /Volumes/MBED* (or /Volumes/NUCLEO*) and is read-only, the script re-mount it with appropriate settings. mbedremounter.py import re, subprocess p = re.compile(r'(/dev/\S+) on (\S*(MBED|NUCLEO).*) \(msdos.*read-only.*\)') for r in p.finditer(subprocess.check_output('mount')): (d, m) = r.group(1,2) subprocess.check_call(['umount', d]) subprocess.check_call(['mkdir', m]) subprocess.check_call(['mount', '-w', '-o', 'sync', '-t', 'msdos', d, m]) The code is also available at. 6 comments on Another Workaround for the "Yosemite Problem": Please log in to post comments. Quote: The mount point for mbed drives is fixed to /Volumes/MBED. This means that you cannot connect two or more mbeds at once. Here is an improved version of the script: A ruby script that will remount all read-only MBEDs And the corresponding plist
https://os.mbed.com/users/takuo/notebook/another-workaround-for-yosemite/?compage=1
CC-MAIN-2019-51
refinedweb
476
68.36
answer_inline_query()¶ Client. answer_inline_query()¶ Send answers to an inline query. A maximum of 50 results per query is allowed. - Parameters inline_query_id ( str) – Unique identifier for the answered query. results (List of InlineQueryResult) – A list of results for the inline query. cache_time ( int, optional) – The maximum amount of time in seconds that the result of the inline query may be cached on the server. Defaults to 300. is_gallery ( bool, optional) – Pass True, if results should be displayed in gallery mode instead of list mode. Defaults to False. is_personal ( bool, optional) – Pass True, if results may be cached on the server side only for the user that sent the query. By default (False), results may be returned to any user who sends the same query. next_offset ( str, optional) – Pass the offset that a client should send in the next query with the same text to receive more results. Pass an empty string if there are no more results or if you don‘t support pagination. Offset length can’t exceed 64 bytes. switch_pm_text ( str, optional) – If passed, clients will display a button with specified text that switches the user to a private chat with the bot and sends the bot a start message with the parameter switch_pm_parameter switch_pm_parameter ( str, optional) – Deep-linking parameter for the /start message sent to the bot when user presses the switch button. 1-64 characters, only A-Z, a-z, 0-9, _ and - are allowed. Example: An inline bot that sends YouTube videos can ask the user to connect the bot to their YouTube account to adapt search results accordingly. To do this, it displays a “Connect your YouTube account” button above the results, or even before showing any. The user presses the button, switches to a private chat with the bot and, in doing so, passes a start parameter that instructs the bot to return an oauth link. Once done, the bot can offer a switch_inline button so that the user can easily return to the chat where they wanted to use the bot’s inline capabilities. - Returns bool– True, on success. Example from pyrogram import InlineQueryResultArticle, InputTextMessageContent app.answer_inline_query( inline_query_id, results=[ InlineQueryResultArticle( "Title", InputTextMessageContent("Message content"))])
https://docs.pyrogram.org/api/methods/answer_inline_query
CC-MAIN-2019-43
refinedweb
361
63.7
Here's a list of the most noteworthy things in the RAP 3.1 release which is available for download since June 22, 2016. The underlying platform bundles org.eclipse.core.databinding.* now require Java 8. The Bundle-RequiredExecutionEnvironment (BREE) of "org.eclipse.rap.jface.databinding" bundle has been updated to JavaSE-1.8.. In those rare cases where RAP requires a slightly different API than SWT, we used to provide additional methods in utility classes like BrowserUtil and DialogUtil. These utilities contain non-blocking versions. The RichText widget has been graduated as Nebula RichTextEditor and moved from the RAP Incubator to the RAP repository. It supports a subset of the API from the RichTextEditor found in the Nebula Release. The RichTextEditor is included in the RAP target platform and can be used simply by importing the org.eclipse.nebula.widgets.richtext package. In this release we added support for right-to-left orientation to all widgets. Like in SWT, the coordinate system of an RTL Composite is mirrored horizontally (the [ 0, 0 ] point is on top-right corner). Support for alpha in Color has been added to SWT in Mars. As RAP client supports RGBA natively, we added the missing API: RGBAclass Color(Device, RGBA) Color(Device, RGB, int) Color(Device, int, int, int, int) getAlpha() getRGBA() The internal org.eclipse.swt.internal.image package has been updated to the latest SWT sources, which provides support for more image formats like 256x256 px ICOs. a theme with Tree). Tree, Table, Grid, List, Combo, CCombo and DropDown have a new default theming for selected items. Instead of a dark-blue gradient a solid, semi-transparent light blue is used. This preserves the color of the text elements (they are no longer set to white) and allows elements like cell backgrounds that are normally hidden beneath the selection effect to shine through. It also works better with the new Nebula Grid look. The business theme remains unchanged.. WebClient.PAGE_OVERFLOWwith one of the values "scroll", "scrollX" or "scrollY" must be set to your application. public class MyApplication implements ApplicationConfiguration { @Override public void configure( Application application ) { Map properties = new HashMap (); ... properties.put( WebClient.PAGE_OVERFLOW, "scrollY" ); application.addEntryPoint( "/", MyEntryPoint.class, properties ); } } This list shows all bugs that have been fixed for this release. To assist you with the migration from RAP 2.x (or 1.x) to 3.0, we provide a migration guide.
http://www.eclipse.org/rap/noteworthy/3.1/
CC-MAIN-2017-43
refinedweb
400
50.73
Classes and Namespaces in C# All C# programs are composed entirely of classes. Visual windows forms are a type of class, as we will see that all the program features we'll write are composed of classes. Since everything is a class, the number of names of class objects can get to be pretty overwhelming. They have therefore been grouped into various functional libraries that you must specifically mention in order to use the functions in these libraries. Under the covers these libraries are each individual DLLs. However, you need only refer to them by their base names using the using statement, and the functions in that library are available to you. using System; using System.Drawing; using System.Collections; Logically, each of these libraries represents a different namespace. Each namespace is a separate group of class and method names which the compiler will recognize after you declare that name space. You can use namespaces that contain identically named classes or methods, but you will only be notified of a conflict if you try to use a class or method that is duplicated in more than one namespace. The most common namespace is the System namespace, and it is imported by default without your needing to declare it. It contains many of the most fundamental classes and methods that C# uses for access to basic classes such as Application, Array, Console, Exceptions, Objects, and standard objects such as byte, bool, string. In the simplest C# program we can simply write a message out to the console without ever bringing up a window or form: class Hello { static void Main(string[] args) { Console.WriteLine ("Hello C# World"); } This program just writes the text "Hello C# World" to a command (DOS) window. The entry point of any program must be a Main method, and it must be declared as static. Shashi Ray Hall of Fame Twitter Terms of Service Privacy Policy Contact Us Archives Tell A Friend
http://www.dotnetspark.com/kb/329-classes-and-namespaces-c-sharp.aspx
CC-MAIN-2016-44
refinedweb
325
60.85
Tuesday 18 June 2013 I've always found descriptors to be one of the more confusing corners of Python. Partly, I think that's to do with the explanations in the docs, which I find opaque: In general, a descriptor is an object attribute with “binding behavior”, one whose attribute access has been overridden by methods in the descriptor protocol. What is binding behavior, and why is it in quotes? This lead sentence hints at overriding attribute access, but doesn't tell me how it happens. It's a tall wall to scale right at the start of the learning process. The best explanation I've seen of what descriptors do and why you'd want to write them was in Chris Beaumont's lightning talk at Boston Python, Demystifying Descriptors in 5 Minutes. The video quality was not great, but now Chris has written it up: Python Descriptors Demystified. (Sorry about the quality, we're getting much better... PS: subscribe to our YouTube channel!) Chris' insight was that instead of defining descriptors, and then showing how you could make properties with them, he flipped that explanation around: explain properties, then show how descriptors are like generalized properties. Read the whole thing: Python Descriptors Demystified. When explaining things, you have to build from what people already know, a step at a time. I picture a student's understanding being like geography. What they know is a land mass, and when you teach them, you are extending their land out into the unknown ocean. You want to make their island bigger, and there's a particular point out in the ocean you want to encompass. Some technical descriptions will explain that distant point, and either hope you can build the peninsula yourself, or expect to be able to build backwards toward the mainland. The classic descriptor explanation is like that: provide a definition of the distant concept, and hope students can make the leap. Chris' explanation is more incremental. Start with what we know, and extend a little bit at a time, with motivations as we go. I love it. BTW: I made some edits to the Python documentation, but they haven't been adopted: Edits to descriptor howto. Others have also suggested reorganizations of the docs about descriptors: Harmonizing descriptor protocol documentation. Descriptors are still an advanced feature, and I don't expect everyone to understand and use them. But they are not as complicated as they first seem, and the explanations can do a better job helping people up that learning curve. As I noted on Twitter, my only objection to Chris's explanation is that he uses the general term "descriptor" when he specifically means "custom descriptor". People will walk away from that explanation without realising that things like functions, classmethod, staticmethod, property and abc.abstractmethod are all descriptors. So using descriptors is easy (it's so easy people don't realise they're doing it whenever they retrieve a method from an object). It's defining new ones that can be a little arcane (that's why it's often easier to use nested functions + property in a factory function than it is to use the descriptor protocol to define a new descriptor from scratch). They're a lot like decorators that way (and, indeed, it's not an accident that most descriptors offer a decorator form). @Nick: I'm not sure I see the benefit of people knowing that functions, classmethods, etc, are descriptors. There's no reason to know the term "descriptor," or know how they work, until you want to write one of your own. @Ned I found that when teaching people how to write custom descriptors it's helps to show how the known concepts methods, static methods, class methods etc. can be easily expressed using the descriptor API. These are examples people can relate to. Caching in python with a descriptor and a decorator might be interesting as a use case for descriptors. I agree with @Nick that terminology in the otherwise really good article is confusing. Another problem I spot was that storing values in a dictionary inside a descriptor can cause a huge memory leak. Descriptors live in the class so everything stored into the dictionary lives "forever". Using weakref.WeakKeyDictionary, or storing values to instances, is safer. Thanks for the article, Ned! Right, so I might have been sloppy with some of the terminology in the article. I can address that. Still, I agree with Ned that many easy-to-google discussions of descriptors (,) explain things backwards. As a consumer of Python, I don't *care* if descriptors can implement properties, class methods, etc. Those things already exist, and don't communicate why writing custom descriptors would be useful. Furthermore, none of those examples illustrate how to deal with instance-specific state, which confused me for a long time. @Pekka's comment about WeakKeyDictionaries is a really excellent point. You've seen discovering descriptors from europython last year? Here is another use-case for descriptors: (making attributes un-inheritable). And for what it's worth, I found this blog post by Guido Van Rossum to be the best description of descriptors that I've seen (that whole blog is great, actually). looks like a verbose way of doing properties. unless i am missing something C# and recently Dart do this a lot tersely (and elegantly) through "get" and "set" modifiers. @numan You're right, in a way: properties are implemented by descriptors. For example, @property def x(self): return True 2013, Ned Batchelder
http://nedbatchelder.com/blog/201306/explaining_descriptors.html
CC-MAIN-2016-26
refinedweb
924
63.59
Arangoimport Examples: JSON Using JSON as data format, records are represented as JSON objects and called documents in ArangoDB. They are self-contained. Therefore, there is no need for all records in a collection to have the same attribute names or types. Documents can be inhomogeneous while data types can be fully preserved. Input file formats arangoimport supports two formats when importing JSON data: - JSON – JavaScript Object Notation - JSON Lines – also known as JSONL or new-line delimited JSON Multiple documents can be stored in standard JSON format in a top-level array with objects as members: [ { "_key": "one", "value": 1 }, { "_key": "two", "value": 2 }, { "_key": "foo", "value": "bar" }, ... ] This format allows line breaks for formatting (i.e. pretty printing): [ { "_key": "one", "value": 1 }, { "_key": "two", "value": 2 }, { "_key": "foo", "value": "bar" }, ... ] It requires parsers to read the entire input in order to verify that the array is properly closed at the very end. arangoimport will need to read the whole input before it can send the first batch to the server. By default, it will allow importing such files up to a size of about 16 MB. If you want to allow your arangoimport instance to use more memory, increase the maximum file size by specifying the command-line option --batch-size. For example, to set the batch size to 32 MB, use the following command: arangoimport --file "data.json" --type json --collection "users" --batch-size 33554432 JSON Lines formatted data allows processing each line individually: { "_key": "one", "value": 1 } { "_key": "two", "value": 2 } { "_key": "foo", "value": "bar" } ... The above format can be imported sequentially by arangoimport. It will read data from the input in chunks and send it in batches to the server. Each batch will be about as big as specified in the command-line parameter --batch-size. Please note that you may still need to increase the value of --batch-size if a single document inside the input file is bigger than the value of --batch-size. JSON Lines does not allow line breaks for pretty printing. There has to be one complete JSON object on each line. A JSON array or primitive value per line is not supported by arangoimport in contrast to the JSON Lines specification, which allows any valid JSON value on a line. Converting JSON to JSON Lines An input with JSON objects in an array, optionally pretty printed, can be easily converted into JSONL with one JSON object per line using the jq command line tool: jq -c ".[]" inputFile.json > outputFile.jsonl The -c option enables compact JSON (as opposed to pretty printed JSON). ".[]" is a filter that unpacks the top-level array and effectively puts each object in that array on a separate line in combination with the compact option. An example inputFile.json can look like this: [ { " ] } ] The conversion produces the following outputFile.jsonl: {"]} Import Example and Common Options We will be using these example user records to import: { "name" : { "first" : "John", "last" : "Connor" }, "active" : true, "age" : 25, "likes" : [ "swimming"] } { "name" : { "first" : "Jim", "last" : "O'Brady" }, "age" : 19, "likes" : [ "hiking", "singing" ] } { "name" : { "first" : "Lisa", "last" : "Jones" }, "dob" : "1981-04-09", "likes" : [ "running" ] } To import these records, all you need to do is to put them into a file (with one line for each record to import), save it as data.jsonl and run the following command: arangoimport --file "data.jsonl" --type jsonl --collection users This will transfer the data to the server, import the records, and print a status summary. To show the intermediate progress during the import process, the option --progress can be added. This option will show the percentage of the input file that has been sent to the server. This will only be useful for big import files. arangoimport --file "data.jsonl" --type jsonl --collection users --progress true It is also possible to use the output of another command as an input for arangoimport. For example, the following shell command can be used to pipe data from the cat process to arangoimport (Linux/Cygwin only): cat data.json | arangoimport --file - --type jsonl --collection users In a command line or PowerShell on Windows, there is the type command: type data.json | arangoimport --file - --type jsonl --collection users The option --file - with a hyphen as file name is special and makes it read from standard input. No progress can be reported for such imports as the size of the input will be unknown to arangoimport. By default, the endpoint tcp://127.0.0.1:8529 will be used. If you want to specify a different endpoint, you can use the --server.endpoint option. You probably want to specify a database user and password as well. You can do so by using the options --server.username and --server.password. If you do not specify a password, you will be prompted for one. arangoimport --server.endpoint tcp://127.0.0.1:8529 --server.username root ... Note that the collection (users in this case) must already exist or the import will fail. If you want to create a new collection with the import data, you need to specify the --create-collection option. It will create a document collection by default and not an edge collection. arangoimport --file "data.jsonl" --type jsonl --collection users --create-collection true To create an edge collection instead, use the --create-collection-type option and set it to edge: arangoimport --collection myedges --create-collection true --create-collection-type edge ... When importing data into an existing collection it is often convenient to first remove all data from the collection and then start the import. This can be achieved by passing the --overwrite parameter to arangoimport. If it is set to true, any existing data in the collection will be removed prior to the import. Note that any existing index definitions for the collection will be preserved even if --overwrite is set to true. arangoimport --file "data.jsonl" --type jsonl --collection users --overwrite true Data gets imported into the specified collection in the default database (_system). To specify a different database, use the --server.database option when invoking arangoimport. If you want to import into a nonexistent database you need to pass --create-database true to create it on-the-fly. The tool also supports parallel imports, with multiple threads. Using multiple threads may provide a speedup, especially when using the RocksDB storage engine. To specify the number of parallel threads use the --threads option: arangoimport --threads 4 --file "data.jsonl" --type jsonl --collection users Using multiple threads may lead to a non-sequential import of the input data. Data that appears later in the input file may be imported earlier than data that appears earlier in the input file. This is normally not a problem but may cause issues when when there are data dependencies or duplicates in the import data. In this case, the number of threads should be set to 1.
https://www.arangodb.com/docs/stable/programs-arangoimport-examples-json.html
CC-MAIN-2019-30
refinedweb
1,145
62.88
Python Question - class cleanup - file handles etc Sorry to ask this here, but a lot of talented guys here. What I have been reading on the net seems like mumbo jumbo....Nonsensical! But its possible its true. I would just like a way for an object to be able to do some cleanup after it falls out of scope or at worst when the application finishes. I see the problem with del and garbage collection, ref counts etc. But I want to take action on a specific object/class. Here I am mainly just thinking about closing files, although the subject is broader than that. I have read about weak references , atexit. They appear to have many caveats attached. A context manager's scope appears to be to limited to be useful. i.e I have a object with an open file for the life of the app. So basically, for a class instance I would like to have a callback, you_are_closing_clean_up_idioit. Yes, you could say, clean up yourself explicitly you idiot. But it just seems so 90's or something. I have struggled with this concept for a long time. I drives me crazy there is no explicit destructor. I just wanted to ask you guys in the forefront, is there a solution to this problem or a PEP that addresses it. Maybe someone has written some super smart decorator that can facilitate a class cleanup callback, without all the but maybes. I listened to one podcast ' Talk Python To Me' about how far they have come along in regards to the performance issue of removing the GIL. I think they are as close -2x without a GIL now. So in my mind, this deconstructor (instance level) issue seems quite trivial compared to that problem. Sorry, I know I have been ranting! But I find it so frustrating. I also accept, maybe there is an elegant solution staring me in the face that I just don't comprehend. I see that py3.7 alpha or beta is circulating now. Maybe there is some hope there. I guess if I had my wish del would be instance based, not ref count based. I know they will not change that, too many things would break i guess. But a new magic method, like finalising. Look, sorry, this not a Pythonista issue, of course. But if anyone has some magic to share, I would love to hear it! Again, i dont think it's unreasonable to think an object/class could be totally self sufficient in regards to cleaning up file handles etc... fingers crossed 🤞 One approach is to be fastidious in avoiding cyclic references, so that __del__will work, though that can be difficult. weakrefalso has a finalizewhich lets you avoid the drawbacks with __del__. @Phuket2, I would really like a good answer to this as well. JonB already replied, so now the smart people are out of the way, and I can ask: given that you often have UI code, will will_closehelp? @mikael , lol. There are still some smart ones around. Every since I started Pythonista (hence Python), @JonB has continually warned me over the dangers of using/depending on del. At the time I found it very difficult to understand. As time has gone on, I have a better idea of why its not a good idea to reply on it. I am not even @JonB assertion about making cyclic refererences would solve then problem, because by then time your del gets called other things may have already fallen out of scope or become unreachable. Also as he suggests avoiding cyclical references in the first place could be different for your average novice like me. I remember @JonB posting some examples in the past that seem innocent enough, but can in fact stop the garbage collector from decrementing the ref count as sometimes it can not be sure if an object can be cleaned up. Look I am sure those really familiar with Python would understand these gotcha's. At it only appears like black magic when you really don't understand all thats going on under the hood. I am not entirely new to Memory management, mind you it was some 30 years ago. I was programming in C on Macs that where using the Motorola 68k chips. memory management was basically handled though the use of handles. The handles would be always be valid, but the data that pointed to could be moved around. If you wanted to access the underlying data you normally would lock the handle and then. Could deference the handle to the data safley. Alternatively you could just double dereference the handle to the ptr and work with the ptr. This would work as long as you didn't call an Apple API/Toolbox call that could move memory(These were all document). I don't know if you think that sounds complicated or not, I used to find it ok. I never had to do a lot debugging looking for memory leaks or dangling pointers. Anyway, my point is that even though it was 30 years ago, my memory (no pun intended) is still fairly fresh on it. Sorry, this is turning into a novel. Regards to your comment, about will_close from the ui, would definitely a way to help you clean up things. But its just a bandaid and ties your classes behaviour to a ui element, which cant be good. Of course the class could just have an explicit close() or clean_up() method that you call. Kill me now, but I just dont like I have to do that. Seems ugly. I was just writing a test catalog database with TinyDB the other day, The init takes a filename and the object and the file is open and ready to do adds/updates/deletes etc.... BTW, this does not seem to happen if I dont close the file. But you could imagine that it could. BTW, there maybe some magic I just dont know about. Sorry, still going :) So brings me to the point, why I dont hear about discussions about adding a real destructor to Python Classes. I feel stupid, like I am the only one in the world that doesn't get it. It appears everyone else (i mean my own little world I get to examine) is ok with the fact there is not a destructor. I am only really bold enough to bring it up after to listening to vids/podcasts about how they are trying to fix/reimagine the GiL, how typed data is started to be used in different CPython implementations, how they changed the undying dict algorithm in py3.6 and a host of other complicated things. I would have thought a proper deconstructor would be high on the list of things to tackle. Ok, thats my Monday afternoon rant. Just something I find personally frustrating. But I am glad I got that off my chest :) Have a good day all One way to do cleanup an object when it leaves scope is using the following class pattern and implement the __init__, __enter__, and __exit__methods. This script just prints some text. It's just to show how the __enter__method is used in a withstatement, and how the __exit__method is called automatically when leaving scope. from myclass import MyClass class MyExampleClass: """ Class to demonstrate cleanup when leaving scope. """ def __init__(self): """ Initialize this class instance. """ # self.my_obj doesn't have to be assigned to a class instance. # It can any other python type. self.my_obj = MyClass() def __enter__(self): """ This method is called in a "with" statement line to return this instance. """ return self def __exit__(self): """ This method is called when this class instance leaves the scope in a "with" statement. """ self.my_obj.do_cleanup() self.my_obj = None def do_cleanup(self): """ Do something. """ print('cleaning up.\n') def do_something(self): """ Do something. """ print('doing something.\n') def do_something_else(self): """ Do something else. """ print('doing something else.\n') if __name__ == "__main__": # Instead of the usual: "obj = MyClass()", do this: with MyClass() as obj: obj.do_something() obj.do_something_else() # Leaving scope obj.__exit__() is automatically called, and # the __exit__ method calls self.do_cleanup() Of course, you could use delin the do_cleanup() method, but I would typically just set the the variable to Noneand let the garbage collector handle cleaning up the memory for the object when it either needs to to allocate more memory, or it decides that it's time. Adding the __enterand __exit__methods doesn't preclude using the class without a "with" statement, but then you'll have to explicitly call the do_cleanupmethod when you're done with the object, i.e.: obj = MyClass() obj.do_something() obj.do_something_else() obj->do_cleanup() The __enterand __exit__methods are implemented in Python file objects, so you can write: with open('filename.ext', 'w') as outfile: outfile.write('Do not read this.\n') outfile.write('Do not read this either.\n') outfile.write('Stop it!\n') # outfile.close() is called here after leaving the scope above. Unfortunately, this only works with a withstatement, so leaving the scope of an if-statement or a whileloop won't work. However, at the cost of extra indentation, you can add a withstatement almost anywhere in a function or method. This is where i always end up, maybe because it is the first google hit. One of the comments leads here whch has code for a wrapper that adds a weakref destructor that calls close() on the stream. This led me to try a few more ideas. Basically: - A metaclass that automatically calls close on any attributes that have a close method. So if you have a class that has a file object, and a db object that are open, close() gets called on those objects when the weakref finalizer is called. The problem with that approach is that you don't have much control, and error handling might be tricky (what if an object is already closed). - A meta class that requires a class to explicitly define a _closing_fcn_, which returns a function that does the cleanup. The trick is that the returned function cannot reference self at all, to avoid cyclic refrences. def _closing_fcn_(self): db=self.db def close(): #gets called when self dies db.close() return close - Finally, it is possible to do this all without a metaclass, just be defining this stuff in init, hence the manual method. This is the most compact, but hard to remember class TestManual(object): def __init__(self): self.stream=SomeStream() stream=self.stream def close(): stream.close() self._finalizer_=weakref.finalize(self, close) Honestly, i was a little surprised that storing the ref to the weakref inside the object itself would work, since it doesnt get called until the obj is already dead, but it does. But you have to take care not to use self in the finalizer method. Cleanup Theory Context manager One way to clean up resources is context manager. Here's an example of class based context manager. class File: def __init__(self, path, mode = 'r'): self.path = path self.mode = mode self.handle = None def __enter__(self): self.handle = open(self.path, self.mode) return self.handle def __exit__(self, *args): self.handle.close() with File(__file__) as f: # __file__ - contains script name, basically opens itself # __enter__ was called, file is opened and handle is stored in f (== File.handle) print(f.read()) # __exit__ will be called Shorter way to achieve same thing is contextmanagerdecorator. Example: from contextlib import contextmanager @contextmanager def file(path, mode = 'r'): handle = open(path, mode) yield handle # yields handle -> as f and the nested with block is executed handle.close() with file(__file__) as f: print(f.read()) There's also contextlib.ContextDecorator, which allows you to use it as a function decorator or you can use it with withstatement. If you don't know yield, search for Python generator for example. Head over to the contextlib documentation to learn more. Also check contextlib.closing if the only thing you would like to do is to call try / ... / finally One way is to use finally: handle = None try: handle = open(__file__, 'r') print(handle.read()) finally: if handle: handle.close() Hmm, what if we do not want to catch handle.read()exception for example? elseis our friend: handle = None try: handle = open(__file__, 'r') except OSError: # Executed if try: raises OSError print('Failed to open file') else: # Executed only and only if try: doesn't raise exception print(handle.read()) finally: # Always executed if handle: handle.close() Read Defining Clean-up Actions to learn more. finalizer Another way to clean up is to use weakref.finalize. Here's an example: class TinyDBWrapper: def __init__(self, path): self._db = TinyDB(path) self._finalizer = weakref.finalize(self, self._db.close) Finalizer is fired when: - object ( TinyDBWrapperin this case) is garbage collected, - program exits. What if you'd like to provide closemethod too? You can add it in this way: class TinyDBWrapper: def __init__(self, path): self._db = TinyDB(path) self._finalizer = weakref.finalize(self, self._db.close) def close(self): self._finalizer() And now finalizer is fired when: - object ( TinyDBWrapperin this case) is garbage collected, TinyDBWrapper.closeis called, - program exits. del And here comes the never ending story of del, __del__, ... What's the problem with __del__? - You're responsible for calling any __del__in superclass - Exceptions raised in __del__are ignored __del__is called when GC collects objects and not when the last reference is lost - Prior Python 3.4, __del__prevents collection of cyclic links (see PEP442), even >= 3.4 has still some issues though - It's not guaranteed that __del__is called when the interpreter exits. Head over to object.del(self) to learn more. What's the problem with del? People think that delis equivalent of GC - collect me now - but it isn't. delremoves binding and decreases reference counter. That's all what it does. When the object is GCed? It's implementation specific and it depends on GC scheme. CPython collects it when reference counter reaches zero. But other implementations can do it later. You want to rely on this? DB wrapper where you have no idea when the close will be called (if ever). Data loss? Here's my rule of thumb - hard to explain? Bad idea. Practically Simplicity. To make it short - you're trying to be too smart with your module. What you should do is to provide simple API, which allows to: - explicitly open catalog (can be __init__), - explicitly close catalog (like closemethod), - use your wrapper as context manager with with. And leave the rest on the developer. You have no idea how your module will be used, when it will be used, if it's really required to keep the wrapper around for the whole lifecycle of the application, ... If you'd like to help, add finalizer if consumer forgets to call it, but I wouldn't do it, closeis enough. This is not kindergarten :) will_close @mikael asked about will_close. Don't use will_closefor stuff like closing streams, databases, ... This should be done on lower level. What if will_closeis not going to be called? It's like depending on __del__and you don't know when and if it will be called. How to check if finalizer was called #!python3 import weakref from tinydb import TinyDB class TinyDBWrapper: def __init__(self, path): self._db = TinyDB(path) self._finalizer = weakref.finalize(self, self._db.close) def close(self): self._finalizer() # Instantiate wrapper wrapper = TinyDBWrapper('aa.json') # Cheat, get reference to finalizer fin = wrapper._finalizer # Trash the wrapper wrapper = None # or replace with `del wrapper` # Get finalizer status, if alive is False, finalizer was already called print(fin.alive) # prints False, because of CPython, ref count == 0, ... can differ on desktop / other implementations ... Conclusion Yeah, I know, I'm too pedantic sometimes. But simple stuff works, doesn't require you to write long documentation, explanation, ... And it's good. Remember my rule of thumb? Hard to explain? Then it's a bad idea. Just provide a way how to do it explicitly and leave the rest on the developer. He has lot of ways (context manager, ...) how to handle this and only he knows how / when your module is going to be used. You don't know it. And you can't prepare your module for all possible use case scenarios. All these examples were written in Python 3 and tested in Pythonista 311015 (latest beta). Guys, thanks for the excellent answers. I have started testing a few of the things proposed here. But its a lot to take in for me, so it will be a few days before I get back to this thread. I want to understand what is happening. I have already had inconsistencies using weakref.finalize, but i need to try to understand why first.
https://forum.omz-software.com/topic/4473/python-question-class-cleanup-file-handles-etc
CC-MAIN-2020-50
refinedweb
2,806
66.94
Like appears at the top of the C source code.appears at the top of the C source code. #include <stdio.h> These notes are a guide to a very few of the standard I/O functions. Much more complete information is available in the Kernighan and Ritchie book. stdin() getc()and putc() The function getchar() retrieves a single character from standard input. Its signature appears as This function's return value will be one ofThis function's return value will be one of int getchar(void) EOFat the end of file The function putchar() sends a single character to standard output. Its signature appears as The character to be output is passed as a parameter. The return value of the function will beThe character to be output is passed as a parameter. The return value of the function will be int putchar(int) EOFif. These descriptions leave much to understand. Read Kernighan and Ritchie Chapter 7 for the details. NOTE: The simulator used for 354 adds extensions to the assembly language, such that there appears to be new MIPS assembly laguage dto print the next argument within the argument list as a decimal number. cto print the next argument within the argument list as a character. xto print the next argument within the argument list as a hexadecimal number. sto print the next argument within the argument list as a null-terminated string. The output (to standard output) will appear asThe output (to standard output) will appear as x = 25; y = 1; printf("The value of x is %d, and the value of y is %d.\n", x, y); Further output will start at the beginning of the next line, due to the newline character (Further output will start at the beginning of the next line, due to the newline character ( The value of x is 25, and the value of y is 1. then in this code fragment,then in this code fragment, -3 6 scanfreturns the value 2, and the value of variable xwill be -3, and the value of variable ywill be 6. Note: reread this explanation after looking at, and understanding the topic of pointers. Again, these descriptions leave much to understand. Read Kernighan and Ritchie Chapter 7 (sections 7.2 and 7.4) for the details.
http://pages.cs.wisc.edu/~markhill/cs354/Fall2008/notes/C.io.html
CC-MAIN-2018-51
refinedweb
382
72.16
> We are currently working on a project in which we try to use android-smartphone sensor data as cotroller input of our unity-(windows)-desktop application. We managed to program a bluetooth SPP server for C# but couldn't integrate the server into Unity3d. Our Bluetooth-Server does wait for incoming bluetooth-connections and accepts them (thanks to the 32feet.Net libary). As soon as the client has connected to the Server it should tranfer String-data over a stream. Now the problem is, that Unity won't accept any GUID we create for our server (see code below). Is there a way we can set up a bluetooth server in a other way in unity/c# (we are used to java programming) or could we start the bluetooth-Server with "normal" .Net 3.5 and stream the data into unity ? this is some code we tried. as we mentioned, unity won't accept our guid: using UnityEngine; using System.Collections; using BluetoothServerDLL; using InTheHand; using InTheHand.Net; using InTheHand.Windows; using InTheHand.Net.Bluetooth; using InTheHand.Net.Ports; using InTheHand.Net.Sockets; using System.IO; using System; using System.Collections.Generic; using System.Linq; using System.Text; public class BlueToothControler : MonoBehaviour { public static CharacterController BtController; public static BlueToothControler Instance; public BluetoothServer bts; public Stream mStream; Guid mUUID = new Guid("00011111-0000-1000-8000-00805F9B34FB"); // Use this for initialization void Awake() { //set up server try { //unity won't accept the mUUID in the next line BluetoothListener blueListener = new BluetoothListener(mUUID); blueListener.Start(); BluetoothClient conn = blueListener.AcceptBluetoothClient(); mStream = conn.GetStream(); } catch (Exception e) { print(e.Message + "\n"); } // Set up Player Control BtController = GetComponent("CharacterController") as CharacterController; Instance = this; } // Update is called once per frame void Update() { if (Camera.main == null) { return; } //receive data and use it as controller input try { //handle server connection byte[] received = new byte[1024]; mStream.Read(received, 0, received.Length); String moveString = Encoding.ASCII.GetString(received); print("Received: " + Encoding.ASCII.GetString(received)); //OnRaiseMoveEvent(moveString); } catch (IOException exception) { print("Client has disconnected!!!!"); } PlayerMotor.Instance.UpdateMotor(); } } thanks in advance. @username Did you figure this out? I am currently working on a project that receives a constant stream of data through a Bluetooth socket in order to transform GameObjects. Also, where did you attach this script? If I am trying to establish the Bluetooth connection, would I put that piece of code in a start() function? Or awake() like you have.. does it matter? Anything helps. Thanks Answer by mafemontoya94 · Aug 22, 2017 at 11:43 AM Hi, do you solved this problem? I am trying to connect a balance board in unity but i am a little new in this library, could you help me please? i succed to adapt this plugin . You will need to make some research on the protocol used by Nintendo for balance. Thank you alibatiste, but I realy don't understand what i should find in this code that allow me the conection witn the bluetooth dedvice, will you give me some ligth on it... This plugin allow you to connect with Wii device in Bluetooth. You juste need to extend it to work with the balance. @alibatiste, could you please make a tutorial on how to this.. really need it.. Answer by sofienjaballah · Jul 17, 2018 at 09:35 AM Hi everyone! I'm developing an app for Android with unity 3D. I need that i include script in my actuel script to send app via bluetooth to another device for making vibration ( my app it turn on active vibration using smartphone coding by c#) please give me the. Using "Custom Bluetooth HID Device" on Android Unity Application. 0 Answers Help Audio streaming from microphone to online url. Uploading only 4kb chunk at a time. 1 Answer Input for bluetooth controller? 0 Answers Anyway to fix a Bluetooth controller that is temporarily unresponsive on my GearVR game? 0 Answers Help In Making a SphereCast for 3D Tire! Working RayCast Script included! 0 Answers
https://answers.unity.com/questions/849429/how-to-receive-bluetooth-data-as-controller-input.html
CC-MAIN-2019-26
refinedweb
660
60.21
Do you have code that looks like this? var myServerUrl = ""; // local server //var myServerUrl = ""; // real server Do you wish you could load settings from a config file, like this yaml below: # local server config.yaml myServerUrl: or # real server config.yaml myServerUrl: Now you can, with the same syntax whether you're running Dart in the browser, or running Dart on the server. 1. Add a dependency to pubspec.yaml for dart_config: dependencies dart_config: any 2. If you are running in the browser, add the following code to your app to load config information from the server: import 'package:dart_config/default_browser.dart'; main() { loadConfig().then( (Map config) { print(config["myServerUrl"]); // continue with your app here! }, onError: (error) => print(error)); } 2. If you are running in the server, add the following code to your app to load config information from the filesystem: import 'package:dart_config/default_server.dart'; main() { loadConfig().then( (Map config) { print(config["myServerUrl"]); // continue with your app here! }, onError: (error) => print(error)); } Both the client and server code looks for a file called config.yaml, loads it from the current folder (or current browser path), parses it, and returns it to your app as a map of key/value pairs (the values may also be maps themselves). Take a look at test/test_default_browser.dart and test/test_default_server.dart, and the associated config.yaml files. Of course you want more control! The loadConfig() function actually takes an optional filename parameter, which defaults to config.yaml - but you can provide a different filename / path if you want. Of course you do. The default_browser and default_server libraries are just opinionated implementations. Behind the scenes, they are calling code that looks similar to this: var config = new Config(filename, new ConfigFilesystemLoader(), new YamlConfigParser()); return config.readConfig(); // returns a Future<Map> The Config class has a single constructor, which takes three parameters. The first parameter is the location of the config file. The second is an implementation of ConfigLoader, and the third is an implementation of ConfigParser (this is a typical dependency injection pattern) The dart_config library comes (at the moment) with two ConfigLoader implementations and two ConfigParser implementations: ConfigFilesystemLoader ConfigHttpRequestLoader YamlConfigParser JsonConfigParser You can use any combination of loader and parser. At its core, the config system needs to know how to load a config file and how to parse a config file. It really is no more complex than that. Take a look at the three files: tests.dart (a VM independant suite of tests), and the test_browser.dart and test_server.dart, which run the same set of tests found in tests.dart both in the browser and on the server. The only differences are ConfigLoader implementation, and the path to the config files. No problem - simply implement your own version of ConfigLoader - there's only one method: Future<String> loadConfig(pathOrUrl) - just return the contents of the config file in the Future<String>, and it will get passed into whatever parser you specify. No problem again - simply implement your own version of ConfogParser - there's only one method: Future<Map<String,Object>> parse(String configText) - just parse the String contents that the ConfigLoader has loaded into a Map, and return it in a Future. Great! - Please share :) - create your own pub packaged containing loaders and/ or parsers, or clone this library and issue pull requests. Some ideas (that I might work on if someone else doesn't get there first): Raise an issue on github and I'll take a look, or even better, create a pull request with a failing unit test or even a fix? StackOverflow is a great place for that. Make sure you use the dart tag, and it will find its way to me, or others that are very knowledgeable. Add this to your package's pubspec.yaml file: dependencies: dart_config: ^0.5.0 You can install packages from the command line: with pub: $ pub get Alternatively, your editor might support pub get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:dart_config/config.dart'; import 'package:dart_config/default_browser.dart'; import 'package:dart_config/default_server.dart'; import 'package:dart_config/loaders/config_loader_filesystem.dart'; import 'package:dart_config/loaders/config_loader_httprequest.dart'; import 'package:dart_config/parsers/config_parser_json.dart'; import 'package:dart_config/parsers/config_parser_yaml.dart'; The package version is not analyzed, because it does not support Dart 2. Until this is resolved, the package will receive a health and maintenance score of 0. Fix dependencies in pubspec.yaml. Running pub upgrade failed with the following output: ERR: The current Dart SDK version is 2.1.0. Because dart_config depends on unittest any which requires SDK version <2.0.0, version solving failed. Format lib/config.dart. Run dartfmt to format lib/config.dart. Format lib/default_browser.dart. Run dartfmt to format lib/default_browser.dart. Format lib/default_server.dart. Run dartfmt to format lib/default_server.dart. Fix additional 4 files with analysis or formatting issues. Additional issues in the following files: lib/loaders/config_loader_filesystem.dart(Run dartfmtto format lib/loaders/config_loader_filesystem.dart.) lib/loaders/config_loader_httprequest.dart(Run dartfmtto format lib/loaders/config_loader_httprequest.dart.) lib/parsers/config_parser_json.dart(Run dartfmtto format lib/parsers/config_parser_json.dart.) lib/parsers/config_parser_yaml.dart(Run dartfmtto format lib/parsers/config_parser_yaml.dart.) Add SDK constraint in pubspec.yaml. (-50 points) For information about setting SDK constraint, please see. Fix platform conflicts. (-20 points) Error(s) prevent platform classification: Fix dependencies in pubspec.yaml. Running dartdoc failed. (-10 points) Make sure dartdoc runs without any issues. Package is too old. (-100 points) The package was released more than two years ago. dart_config.dart. The description is too long. (-10 points) Search engines will display only the first part of the description. Try to keep it under 180 characters.
https://pub.dartlang.org/packages/dart_config
CC-MAIN-2018-51
refinedweb
957
52.15
Hi, On 2011-12-19 23:02:07 +0900, Osamu Aoki wrote: > On Mon, Dec 19, 2011 at 01:02:22AM +0100, Vincent Lefevre wrote: > > On 2011-12-18 13:18:02 -0700, Bob Proulx wrote: > > > The namespace is defined by Debian Policy. The filename should be > > > named after the package name. Since the package names must be > > > different the file name derived from it must be different. (I think > > > it is okay for /etc/default/foo to be part of a foo-common package > > > though. The namespace intention has been preserved.) > > > > It's not always the case: > > did you check "apt-cache showsrc ..." What "apt-cache showsrc ..." says doesn't matter. The point is what the Debian Policy says. If it isn't followed and some new package creates a /etc/default/... file that clashes with some other package because of that, there would be a problem (with potential data loss). The fact that the filename is close to the package name is not sufficient to avoid problems. -- Vincent Lefèvre <vincent@vinc17.net> - Web: <> 100% accessible validated (X)HTML - Blog: <> Work: CR INRIA - computer arithmetic / Arénaire project (LIP, ENS-Lyon)
http://lists.debian.org/debian-user/2011/12/msg00959.html
CC-MAIN-2013-20
refinedweb
191
76.22
BeanShell BeanShell integration with your application is simple, like the rest. Add the BeanShell jar file to your classpath at invocation, then instantiate the interpreter prior to executing a script: import bsh.Interpreter; public class SimpleEmbedded { public static void main(String []args) throws bsh.EvalError { Interpreter i = new Interpreter(); } } The BeanShell script to create a JTree, put it in a JFrame, and size and show the JFrame is simple and Java-like: frame = new JFrame(); tree = new JTree(); frame.getContentPane().add(tree); frame.pack(); frame.show(); What these integration examples mean The information above shows that it's easy to integrate any of the interpreters. And once you understand the correct syntax from your scripts, you can be productive writing scripts, too. For the trivial example I used, you can see that scripts written in BeanShell and JavaScript are the most Java-like in their formatting, with Jacl and Jython showing some differences, but not proving unreadable. As the scripts for each interpreter show, no firewall exists between the script code and classes defined in your application's Java libraries. So take note: the script code seamlessly runs against your application classes, so be sure that's what you want. If you want to protect parts of your application from scripts at runtime, take steps such as obfuscating classes not part of your published API to prevent people from coding scripts against them. The fourth benchmark: Library support issues Though scripting support gives your application extra power, it requires your application to depend on those scripting libraries. Before you tie yourself to a scripting interpreter, consider the chance you someday may own the code you are integrating against. If the support team seldom updates and releases the interpreter, that's a bad sign. It either means the code is perfect as it stands, or the developers who took care of the code have moved on to other projects. Guess which case is more likely? It is also worth checking to see how much source code it took to implement the interpreter. It's unrealistic to think that you can understand an interpreter's every code line and extend it or tune it to fit your needs. The interpreters are just too big. Still, it's worth knowing these interpreters' sizes. At some point you may need to modify the interpreter source code or dig through the code to figure out the interpreter's behavior. Let's go through the library support issues for each interpreter in our survey. Jacl Jacl has an active support group. Although the download link at the development site points you at a release that is several years old, newer versions can be found using the CVS version control system. Jacl consists of about 37,000 lines of Java code. Jython Jython seems to feature active support, maintenance, and updates. Jython consists of about 55,000 lines of Java code. Rhino Rhino receives updates and new releases on a frequent basis, and comprises about 44,000 lines of Java code. BeanShell BeanShell features regular updates and releases; it consists of about 25,000 lines of Java code plus a substantial number of BeanShell scripts. What the support information means All four interpreters are big, complex beasts. You'll be ahead in the game if you can rely on a support team to make improvements and fix bugs. Before you choose an interpreter, check to see how often it is updated and released. You might contact one of the developers to see what the long term plans for the interpreter are and to see what their process is for fixing bugs. Licensing Even though you can download these interpreters for free, what are the licensing rules about embedding the scripting interpreter in a commercial application? Fortunately, licensing does not present a problem for any of these libraries. The way I read the license agreements for Jacl, Jython, JavaScript, and BeanShell, the user must abide by the GNU Lesser General Public license or an equivalent. That means you can ship the libraries with your application even if your application is not free. However, you cannot strip the copyright headers out of their source files or script files, and you may need to clarify to users that the rights to the scripting interpreter bundled with your application belong to someone else. Naturally, don't take my word for it. When you get interpreter distribution you care about, read and interpret the licensing information for yourself, and have your legal department affirm you can use it with your application without creating any problems for you. Final thoughts If you need to integrate scripting support code into your Java application, I advise you to standardize on a single scripting interpreter. Each additional scripting language you support in your product has associated costs, so avoid hooking more than one scripting interpreter into your application. When adding scripting support, you can simplify things further by using a Java-based interpreter instead of a native interpreter such as Perl. That will make your solution more portable and simplify the integration task between your Java program and the interpreter. If your customers expect a particular language to customize your products, look seriously at integrating with a scripting interpreter that supports that language, in the way that Jacl supports Tcl syntax. If you are not locked to a particular language, compare the interpreters from a variety of standpoints to see which are better suited to particular tasks than others. For instance, Jacl moves extremely slowly compared to the other interpreters, but proves useful if you need your scripts written in Tcl. If you're porting an application from Tcl/Tk to Java, the ability to run your old Tcl scripts in the new Java application might be so valuable that it would outweigh other concerns. Also, Tcl is a popular programming language, so many developers are already familiar with it, and Tcl books are easy to find. If you want Java-like scripting code and prefer painless integration, BeanShell looks good. On the downside, the user guide for BeanShell syntax and programming is limited to what ships with the release, and it runs slower than some of the other interpreters. On the other hand, I found BeanShell easy to work with and liked it quite a bit. Its well organized libraries make integration simple. If performance is not the most important criteria for your scripting interpreter, consider BeanShell. Rhino runs significantly faster than BeanShell and likewise supports Java-like syntax in its scripting. Moreover, it appears well written and well supported, and you'll find numerous JavaScript syntax books at the bookstore. I had no problems and recommend it if you have equally balanced needs for performance, Java-like syntax, and strong support for the libraries. Jython is the fastest scripting interpreters I looked at and has some powerful programming features.. Many thanks to Geetha Pannala and Blair West of Mentor Graphics for their assistance in looking at the different scripting interpreters. Learn more about this topic - To download the source code and class files for this article - Investigate the Bean Scripting Framework at IBM's alphaWorks - "Scripting Power Saves the Day for Your Java Apps," Ramnivas Laddad (JavaWorld, October 1999) - Also check out Mark Johnson's "Script JavaBeans with the Bean Scripting Framework" (JavaWorld, March 2000) - To download Jython - To download Rhino from Mozilla - To download Jacl - Read about Swank, the Jacl graphical toolkit - To download BeanShell - For more scripting language stories, visit the Applied Java section of JavaWorld's Topical Index - Speak out in JavaWorld's Java Forum - You'll find a wealth of IT-related articles from our sister publications at IDG.net
https://www.javaworld.com/article/2074156/java-app-dev/java-scripting-languages--which-is-right-for-you-.html?page=2
CC-MAIN-2018-34
refinedweb
1,280
58.62
raw_input blocks a separate thread in Pythonista - HugoSviercovich Hi, running the code below in Pythonista is not working as expected. Looks like the worker thread is being "blocked" by raw_input whereas in other platforms (Raspberry Pi, Windows - both v.2.7.3) same code allows it to run in the background normally. Can anybody reproduce this and help me understand if this is normal behaviour? Actually this code is just a simplification of what i'm trying to achieve with more complex code. I'm thinking this could probably be a particular iOS limitation. Thanks for your kind assistance. import threading import time class Worker(): def PrintSomething(self): while True: print "something" time.sleep(1) if __name__=="__main__": worker=Worker() wthread=threading.Thread(target=worker.PrintSomething) wthread.start() while True: input=raw_input("Your input?: ") #waits for user input and currently blocks 'worker' thread in Pythonista time.sleep(1) Expected result would be something like: Your input? : something something something something something something something Your input? : something something ... But it throws just this: something Your input?: I posted a similar question before I saw this. I'm having the same problem and can't figure how to work around it. I discovered that you can actually call sys.exit(0) and the thread will keep running in pythonista. the interpreter is showing that it is not running but it still receives print from the running thread. Example of the thread running on exit <pre><code> import threading import time import sys class Worker(): def PrintSomething(self): while True: print "something" time.sleep(1) if name=="main": worker=Worker() wthread=threading.Thread(target=worker.PrintSomething) wthread.start() sys.exit(0) while True: #input=raw_input("Your input?: ") #waits for user input and currently blocks 'worker' thread in Pythonista time.sleep(1) </code> </pre>
https://forum.omz-software.com/topic/698/raw_input-blocks-a-separate-thread-in-pythonista
CC-MAIN-2017-34
refinedweb
300
60.51
Update: This article provides a discussion of the problem I ran into when trying to generate random strings in Scala, but for the best Solution, see the Comments section below. When it comes to generating random strings with the scala.util.Random class, I haven’t figured out yet how to properly use the nextString method. I’ve tried using it in several different ways, but I always get a string of question marks as output, like this: scala> val r = new scala.util.Random(31) r: scala.util.Random = scala.util.Random@7d49fa1e scala> r.nextString(10) res0: String = ?????????? This happens whether I give Random a seed value or not, and whether I call nextString as a static method or not: scala> Random.nextString(5) res1: String = ????? Update: The solution to this problem is shown in the Comments section below. I’ll update this post when I have more time, but for now I’ll just say that the correct answer is to use this code (and see the comment below): Random.alphanumeric.take(10).mkString The Random alphanumeric method Frankly I haven’t really needed this capability, so this unusual behavior hasn’t bothered me enough for me to take time to look into it. Plus, I could always use the alphanumeric method as follows to get a random string: scala> val x = Random.alphanumeric x: scala.collection.immutable.Stream[Char] = Stream(Q, ?) scala> x take 10 foreach println Q n m x S Q R e P B (Note that the alphanumeric method returns a Stream, so you need to coerce the Stream to give you some output, as shown in that example. I don’t think I have any tutorials out here about Scala Streams just yet, but I do cover them in detail in the Scala Cookbook.) Many ways to create a Scala random string On one particularly cold night in Alaska back in December (it’s January now as I write this) I got bored and decided to write my own random string method. As I started to write the code, I realized there were several different ways to tackle the problem. For me this is a cool thing about Scala; it’s like the old Perl slogan, “There’s more than one way to do it.” Without any further discussion, I’ll just say that the following Scala code demonstrates several different ways to generate a random string. I start with a “Java-esque” approach, and then show several other ways to create a random string, including some recursive and tail recursive approaches. import scala.annotation.tailrec /** * Examples of different ways to write "random string" methods in Scala. * See the main method for examples of how each method is called. * Created by Alvin Alexander, */ object RandomStringExamples { def main(args: Array[String]) { println("1: " + randomString(10)) println("2: " + randomStringArray(10)) println("3: " + randomStringRecursive(10).mkString) println("3: " + randomStringRecursive2(10).mkString) println("4: " + randomStringTailRecursive(10, Nil).mkString) println("5: " + randomStringRecursive2Wrapper(10)) println("6: " + randomAlphaNumericString(10)) println("6: " + randomAlphaNumericString(10)) println("6: " + randomAlphaNumericString(10)) println("x2: " + x2(10, ('a' to 'z') ++ ('A' to 'Z'))) } // 1 - a java-esque approach def randomString(length: Int) = { val r = new scala.util.Random val sb = new StringBuilder for (i <- 1 to length) { sb.append(r.nextPrintableChar) } sb.toString } // 2 - similar to #1, but using an array def randomStringUsingArray(length: Int): String = { val r = new scala.util.Random val a = new Array[Char](length) val sb = new StringBuilder for (i <- 0 to length-1) { a(i) = r.nextPrintableChar } a.mkString } // 3 - recursive, but not tail-recursive def randomStringRecursive(n: Int): List[Char] = { n match { case 1 => List(util.Random.nextPrintableChar) case _ => List(util.Random.nextPrintableChar) ++ randomStringRecursive(n-1) } } // 3b - recursive, but not tail-recursive def randomStringRecursive2(n: Int): String = { n match { case 1 => util.Random.nextPrintableChar.toString case _ => util.Random.nextPrintableChar.toString ++ randomStringRecursive2(n-1).toString } } // 4 - tail recursive, no wrapper @tailrec def randomStringTailRecursive(n: Int, list: List[Char]):List[Char] = { if (n == 1) util.Random.nextPrintableChar :: list else randomStringTailRecursive(n-1, util.Random.nextPrintableChar :: list) } // 5 - a wrapper around the tail-recursive approach def randomStringRecursive2Wrapper(n: Int): String = { randomStringTailRecursive(n, Nil).mkString } // 6 - random alphanumeric def randomAlphaNumericString(length: Int): String = { val chars = ('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9') randomStringFromCharList(length, chars) } // 7 - random alpha def randomAlpha(length: Int): String = { val chars = ('a' to 'z') ++ ('A' to 'Z') randomStringFromCharList(length, chars) } // used by #6 and #7 def randomStringFromCharList(length: Int, chars: Seq[Char]): String = { val sb = new StringBuilder for (i <- 1 to length) { val randomNum = util.Random.nextInt(chars.length) sb.append(chars(randomNum)) } sb.toString } def x(length: Int, chars: Seq[Char]): String = { val list = List.range(1, length) val arr = new Array[Char](length) list.foreach{ e => arr(e) = chars(util.Random.nextInt(chars.length)) } list.mkString } // create a fake list so i can use map (or flatMap) def x2(length: Int, chars: Seq[Char]): String = { val tmpList = List.range(0, length) val charList = tmpList.map{ e => chars(util.Random.nextInt(chars.length)) } return charList.mkString } } I’m sure there are many other ways to generate a random string in Scala, but if nothing else, rather than solve a specific problem, I thought I’d just share all these different potential approaches.
https://alvinalexander.com/scala/creating-random-strings-in-scala/
CC-MAIN-2021-10
refinedweb
878
55.54
Two-Factor Authentication (2FA) is one of the most effective ways to increase the security of online accounts and consequently reduce online identity theft. The 2FA implementation used by most applications is based on the Time-based One-Time Password algorithm, which requires users to read a numeric code from a hardware token generator or smartphone app and enter it on an application’s website to confirm their login attempts. Unfortunately, many users find this extra login procedure tedious and inconvenient. There have been efforts to simplify the 2FA flow with the goal of increasing adoption. A new method that is gaining popularity is Push Authentication, where instead of expecting a numeric code, the application server sends a push notification to the user’s smartphone. The only action for the user is to tap a button in this notification to confirm that the login attempt is legitimate. In this article, I will go over the steps required to add Push Authentication to a web application using the Twilio Authy API. While the techniques I’m going to discuss are generic and apply to all languages and technologies, I will be showing code examples in Python. What is Push Two-Factor Authentication? Before we delve into how push authentication is implemented, let me give you a quick overview of how it works from the user’s perspective. Registering Users for Authy Push 2FA The procedure to enable push authentication is similar to that of the more traditional two-factor authentication implementations based on numeric codes. The application displays a QR code on the screen that the user must scan with their chosen two-factor authentication app. For push authentication with the Authy service, the app must obviously be Authy, which is available on the Android and Apple stores for free. The QR code that enables push authentication is specifically designed for push authentication with the proprietary Authy service. Standard TOTP QR codes cannot be used for push authentication with Authy. Once the QR code is scanned, the user is registered for push authentications. These will be sent to the Authy app running on their smartphone (the Authy service can also send these push authentications to your own iOS or Android app if desired). The Authy service provides an API call that the application can invoke in a polling cycle to find out when the QR code was scanned. Alternatively, a registration webhook URL can be configured, and the Authy service will invoke it to notify your application when the QR code is scanned or times out. Using one of these registration status options makes it unnecessary to add any buttons or other UI elements to the page that shows the QR code. This is because you can have JavaScript logic in the background waiting for the QR code to be scanned and at that time automatically redirect the user back into the application. Logging In with Push 2FA When the user logs in to the application after enabling two-factor authentication, they’ll have an additional step after entering their username and password. In traditional 2FA this would be a web form where the user needs to type a numeric code obtained from the 2FA app. For push 2FA, this is a page that just waits for the user to approve the login request on their phone, without asking for any information. A common implementation of this page just shows a spinner, to indicate that the application is waiting for the user to take action. The Authy service provides an API endpoint that the application can call to issue a push notification to the user. When the user opens the notification on their phone, this is what they’ll see: At this point the application can once again poll the Authy service, or define a webhook to receive a notification when the user takes action. The user will tap the “Approve” or “Deny” buttons, and as soon as they do the Authy service will report it back to the application which can allow or reject the login request. Implementing Push 2FA in Python In the following sections I’m going to describe the highlights of my implementation of push 2FA into one of my open-source Python applications. The application I used is called Microblog, and you can try a fully working version of it extended to support Authy push authentications in the Microblog-Authy repository on GitHub. Authy Configuration If you don’t have a Twilio account yet, you can open a free account to work with the Authy service. You will need to verify your account by providing your mobile phone number, but you will not be asked to enter a credit card or other form of payment until you decide to upgrade to a paid account. From the Twilio Console, click on “All Products & Services” on the left sidebar, and then find Authy in the menu. The main Authy configuration panel will show a “Create Application” button. Click on it, and then provide a name for this application. In most cases you will want to use the name of your own application here, as this is the name that users will see on the Authy app on their phones. I will demonstrate Authy by adding it to Microblog: Once you have decided on a name, click the “Create” button. Python Dependencies To add push authentication to your Python application you will need to include the Authy client for Python: $ pip install "authy>=2.2.5" Note that the client library for Python must be version 2.2.5 or newer, as older versions lack some of the functionality required for this project. The registration flow for Authy uses JSON Web Tokens and QR Codes, so your application will need to generate these. The packages that I’m going to demonstrate in the example code below are pyjwt and qrcode respectively: $ pip install pyjwt qrcode Generating the Registration QR Code A QR code is a graphical encoding for a short text, typically a URL. The Authy app recognizes QR codes that have the following URL encoded in them: authy://account?token={JWT} The token field of the above URL must be set to a JSON Web Token with the following payload: { "iss": "{authy_app_name}", "iat": {issue date}, "exp": {expiration date}, "context": { "custom_user_id": "{custom_user_id}", "authy_app_id": "{app_authy_id}" } } The iss, iat and exp fields are part of the JWT specification, corresponding to the “issuer”, “issued at” and “expiration” fields respectively. The issuer must be set to the Authy application name you defined in the Twilio Console. The issued_at and expiration fields are integers in Unix time format. The custom_user_id field is the identifier for the user in your own application, typically the primary key assigned to the user in your database. This is going to help map your own user identifiers to those used by the Authy service for the same users. The authy_app_id field must be set to the identifier assigned by Authy to your application. You can find it in the application settings page: To ensure that registration requests are legitimate, Authy requires that you sign your JWT using the standard HS256 algorithm, with the Authy production API key assigned to your application as the signing key. This key appears in the settings page right below the application ID. Here you can see a Python function that generates a registration JWT for a user using the pyjwt library: import time from flask import current_app import jwt def get_authy_registration_jwt(user_id, expires_in=5 * 60): now = time.time() payload = { 'iss': current_app.config['AUTHY_APP_NAME'], 'iat': now, 'exp': now + expires_in, 'context': { 'custom_user_id': str(user_id), 'authy_app_id': current_app.config['AUTHY_APP_ID'], }, } return jwt.encode(payload, current_app.config['AUTHY_PRODUCTION_API_KEY']).decode() The function takes the user identifier and an optional expiration time, which defaults to five minutes if not provided. This function is specifically coded to work within a Flask application, so it uses the Flask configuration object. There I obtain the Authy application name, id and production API key. For other frameworks, you will need to replace all the references to the current_app.config dictionary with the appropriate configuration object. Now that we have a JWT, we are ready to generate a QR code for Authy using the qrcode package: from io import BytesIO import qrcode import qrcode.image.svg def get_authy_qrcode(jwt): qr = qrcode.make('authy://account?token=' + jwt, image_factory=qrcode.image.svg.SvgImage) stream = BytesIO() qr.save(stream) return stream.getvalue() This function generates the URL in the format required by the Authy app for the JWT that is passed as an argument, and then creates a QR code with it. The image format that I used is SVG (which all browsers support) but other browser-friendly formats such as JPEG, GIF or PNG would work as well. The image data is written to a byte stream, and then the contents of the stream are returned. This function can be invoked from an HTTP route handler so it returns the image data to the web browser for display. Waiting for the User to Scan the QR Code To complete a user registration, the application needs to wait for the user to scan the QR code. As I mentioned above, Authy supports two methods for the application to do this: polling and webhook. While the polling option is a little bit less efficient, it is easier to implement and has the advantage that it can be used from the application running on a development machine, without having to set up a domain and an SSL certificate. To implement the polling method, I’ve included the following JavaScript code in the page where the QR code is displayed: <script> function check_registration() { $.ajax("/2fa/enable/poll").done(function(data) { if (data == 'pending') { setTimeout(check_registration, 5000); } else { window.location = "/index"; } }); } setTimeout(check_registration, 5000); </script> The function check_registration() sends a request to the registration polling route defined in the application. The setTimeout() call at the bottom schedules the function to be called five seconds after the page loads. The response from the polling route is going to be the string ’pending’ if the user hasn’t scanned the code yet. In that case we schedule another run of the function after five more seconds pass. This will keep going until the response from this polling route is different, at which point we redirect back to an application page. In my implementation the polling route set a “flash” message that indicates the success of failure of the scanning operation, which will be displayed after the redirect. Checking on the registration status of a user in the backend is extremely simple with the Authy client for Python: from authy.api import AuthyApiClient def get_registration_status(user_id): authy_api = AuthyApiClient(current_app.config['AUTHY_PRODUCTION_API_KEY']) resp = authy_api.users.registration_status(user_id) if not resp.ok(): return {'status': 'pending'} return resp.content['registration'] Once again, keep in mind that I coded this function to work within a Flask application. This means that when I instantiate the AuthyApiClient object, I obtain the Authy production API key from the Flask config object. This function is interesting because the Authy service allows you to ask for the status of a registration by passing the user ID used by your own application. Recall that the JWT we encoded in the QR code has this identifier, so Authy now knows the user ID we assigned to this user and can tell us when a mapping between that ID and an Authy user has been made. While the user hasn’t scanned the QR code the registration key in the response from the Authy service will be as follows: {'status': 'pending'} After the user scans the QR code, the response will change to: {'status': 'completed', 'authy_id': 1234567890} This response indicates the identifier that the Authy service uses to reference the user. From this point on, when you want to interact with the Authy service, you will use this identifier to refer to the user. You’ll need to store it in your user database so that you can retrieve it when you need it. Any other status value besides ’pending’ and ’completed’ indicates that an error has occurred, so the application should cancel the registration request. Sending a Push Authentication to a User Right after a user logs in to the application, you need to check if the user has 2FA enabled on their account. If they do, you now have to ask the Authy service to send a push notification to their phone. The following function shows how to implement this with the Authy client: def send_push_authentication(user): authy_api = AuthyApiClient(current_app.config['AUTHY_PRODUCTION_API_KEY']) resp = authy_api.one_touch.send_request( user.authy_id, "Login requested for Microblog.", details={ 'Username': user.username, 'IP Address': request.remote_addr, }, seconds_to_expire=120) if not resp.ok(): return None return resp.get_uuid() The authy_api.one_touch.send_request() is the function that initiates the push notification. The first argument is the authy_id for the user, which is the identifier that was reported back to the application when the user registered for 2FA. The Authy ID will be typically stored in the user database, so in my case I can access it as user.authy_id. The second argument is a message that will appear in the login approval screen displayed by the Authy app. The details argument is a dictionary with information that will be shown to the user in the Authy app, to help the user identify login attempts that are illegitimate. Here I included the username and the IP address for the user logging in. A more sophisticated implementation could also run the IP address through a geolocation API to also present a location from where the client is logging in. The seconds_to_expire argument is set to the number of seconds Authy will wait for the user to respond to this notification. See the documentation to learn about other optional arguments you can use in this call. The function returns a UUID that the Authy service assigns to this push authentication request. We will use it in the next section to check the status of this request. Waiting for the User to Authorize a Login Request Once a push authentication request has been initiated, the application needs to wait for the user to approve or reject it. This is done in a very similar way to how we waited for a registration. Like in that case, the application can wait using a polling cycle from background JavaScript code, or a webhook. A simple check that a backend application can execute that can be integrated into the polling cycle could be coded as follows: def check_push_authentication_status(uuid): authy_api = AuthyApiClient(current_app.config['AUTHY_PRODUCTION_API_KEY']) resp = authy_api.one_touch.get_approval_status(uuid) if not resp.ok(): return 'error' return resp.content['approval_request']['status'] The function uses the UUID returned by Authy when we issued the push notification to the user. The response returned by Authy will have a status key (among other fields) that is ’pending’ until the user taps the Approve or Deny buttons, at which point it will change to ’approved’ or ’denied’ respectively. If the user does not handle this request before the timeout set in the push authentication request, then the status will change to ’expired’. Conclusion I hope you found that this article nicely complements the official Authy documentation and gives you some starter code that you can adapt to your needs. As I mentioned above, I have created a complete and working example with the techniques I discuss in this article, all on top of an existing Flask application. You can find the code in the Microblog-Authy repository on GitHub. I’m excited to see what you build with Twilio Authy! Miguel Grinberg is a Python Developer for Technical Content at Twilio. Reach out to him if you have a cool Python project you’d like to share on this blog!
https://www.twilio.com/blog/push-two-factor-authentication-python-twilio-authy
CC-MAIN-2021-10
refinedweb
2,634
51.78
Add the Navigation will introduce doing queries outside the Slice Zone and configuring custom types in Prismic. We'll show you how to handle the top navigation in your Prismic repository and Next.js app. Looking at the top navigation, you can see that the model will be pretty simple. We don't know how many links we might need in the future, so we'll need to use a Group field to handle our links. Inside the Group field, we'll need: - A Link field to link to internal content - A Rich text field for the labels For our Menu, we'll create one document which we'll query once and display everywhere. So in the Custom Types section, create a single type Custom Type for the menu as we'll only be creating one version of the document. Call it 'Menu' with the API ID menu. In the Menu Type's Static Zone add a Title field and a Group field. In the Group field, add a Link field and a Rich Text field. This will allow you to add as many links as you need. You can see all the API IDs for these fields below: Field API ID Title title Group menu_links Link link Rich Text label Then click 'Save to File System' + 'Push to Prismic' and jump over to the Prismic Dashboard. From here you can create a new Menu document and add your links and click 'Save' + 'Publish'. You can see how your Menu Custom Type should look below: Now, heading back to the project code, we're going to query the menu with getInitialProps in the _app.js file, call the query in the layout, and create the menu component. All of this is explained in the nav bars, footers, and menus article. The only difference will be in the styling we include for our component. Open the _app.js file. Then, query for the single instance of the Custom Type "menu" using the query helper function getSingle. This query will be located inside the getInitialProps fetching method. Then, pass the menu as props to the <Component /> in the render method. import "../styles/globals.css"; import React from 'react' import NextApp from 'next/app' import { Client } from "../prismic-configuration"; export default class MyApp extends NextApp { static async getInitialProps(appCtx) { const client = Client(); const menu = (await client.getSingle("menu")) || {}; return { props: { menu: menu }, }; } render() { const { Component, pageProps, props } = this.props return ( <Component {...pageProps} menu={props.menu} /> ) } } Create a components folder in your Next.js project and add the Layout.js file inside of it. In this file, you can retrieve the menu from the props and pass it to the Header.js component. Make sure that all the imports match your project routes. import React from "react"; import Head from "next/head"; import Header from './Header' const Layout = ({ children, menu }) => { return ( <div> <Head> <title> Prismic Next.js Multi Page Website </title> </Head> <Header menu={menu} /> <main>{children}</main> </div> ); }; export default Layout; Below is our menu component called Header.js that we created in the components folder. We can now access the data from Layout.js with menuLinks so that we can code and style it. import React from 'react' import { RichText } from 'prismic-reactjs' import { Link } from 'prismic-reactjs' const Header = ({ menu = [] }) => ( <header className="site-header"> <a href="/" className="logo"> {RichText.asText(menu.data.title)} </a> <Links menuLinks={menu.data.menu_links} /> <style jsx>{` .site-header { height: 30px; padding: 20px 0; color: #484d52; font-weight: 700; } .site-header a { color: #484d52; font-weight: 700; } .site-header a:hover { color: #72767b; } .site-header .logo { display: inline-block; font-size: 22px; font-weight: 900; } @media (max-width: 1060px) { .site-header { padding-left: 20px; padding-right: 20px; } } @media (max-width: 767px) { .site-header { height: auto; } .site-header { position: absolute; left: 0; right: 0; } .site-header .logo { display: block; text-align: center; } } `}</style> </header> ) const Links = ({ menuLinks }) => { if (menuLinks) { return ( <nav> <ul> {menuLinks.map((menuLink, index) => ( <li key={`menulink-${index}`}> <a href={Link.url(menuLink.link)}> {RichText.asText(menuLink.label)} </a> </li> ))} </ul> <style jsx>{` nav { float: right; } nav ul { margin: 0; padding-left: 0; } nav li { display: inline-block; margin-left: 40px; } nav li a { color: #484d52; font-weight: 700; } nav li a:hover { color: #72767b; } @media (max-width: 767px) { nav { float: none; text-align: center; } nav li { display: inline-block; margin-left: 10px; margin-right: 10px; } } `}</style> </nav> ) } return null } export default Header Now that you've built your layout component, you can wrap all elements in the render of your page files, and pass the menu as props. Here we give you an example of the index.js file, but you can add it to every other page that you create. next-slicezone version The following examples use the latest version of the next-slicezone package, which changes how values from the parameters are called. Learn more about next-slicezone's Lifecycle hooks. To install this run npm install next-slicezone@latest import { Client } from "../prismic-configuration"; import SliceZone from "next-slicezone"; import { useGetStaticProps } from "next-slicezone/hooks"; import resolver from "../sm-resolver.js"; import Layout from "./../components/Layout"; const Home = (props) => { return ( <Layout menu={props.menu}> <SliceZone {...props} resolver={resolver} />; </Layout> ); }; // Fetch content from prismic export const getStaticProps = useGetStaticProps({ client: Client(), type: 'home-page', queryType: 'single' }); export default Home; The last thing to is to update your Route Resolver in your prismic-configuration.js file. We use the Route Resolver to build links for Prismic documents in our project. It's also used for building routes when your project is 'Statically' deployed. You can learn more about how to defining the Route Resolver here. So, because we added a new 'Home Page' Custom Type, in the Route Resolver we'll need to add this type and the path to follow when a link is created for this document type. Open the prismic-configuration.js file in the base of your project, find the Router object and the following info: export const Router = { routes: [ { "type":"page", "path":"/:uid" }, { "type":"home-page", "path":"/" }, ], href: (type) => { const route = Router.routes.find(r => r.type === type); return route && route.href; } }; Keep this updated Every time you add a new Custom Type to your project you'll need to update this field if you want your links and your Prismic Previews to work. - npm - Yarn npm run dev yarn dev Boom! Simple as that you've got a website menu :) Was this article helpful? Can't find what you're looking for? Get in touch with us on our Community Forum.
https://prismic.io/docs/technologies/add-navigation-nextjs
CC-MAIN-2022-05
refinedweb
1,092
65.62
Dialogs - List Dialog How do you use the ui.ListDataSource for the dialogs.list_dialog() popup? I am trying to make it so I can see what item has been deleted from the dialog.list_dialog(). I am trying to (when the item from the table is deleted), a reminder of the same text in your reminders will be deleted. I know how to do that, I just don't know how to make the ui.ListDataSource work for the dialog popup. Does any of that make sense? If so, answers are much appreciated. @AtomBombed , this thread maybe useful @omz @AtomBombed I am finding the list_ dialog very useful. Thank you for this! I have been successful in using the ListDataSource dictionary to set titles and images. Is there anyway to activate/catch the "accessory_type" items like check mark, etc.? I can make them appear but they are inactive. Like Atom I have discovered the slide over "Delete" is present. It clears the dialog list item but I have no idea how to catch this action so I can use it with my data. Since delete is there I assume it can be used? I'd highly appreciate knowing how to use these other items. Thank you, anyone. @MTcoder You might check out tableview_delete() under I have not played much yet with list_dialogbut I know that it is based on counterparts in the ui module. @ccc @Phuket2 so far, I have not figured the answer out. Do any of you know if the dialogs.list_dialog() has an attribute like this: dialogs.list_dialog("Test","6items").delegate = (delegate class here) I was wondering if it would have a delegate attribute that you could set, but it doesn't work because when you select something from the list, it returns a string of the item's title that was selected, instead of the actual list_dialog item. So is there another way? list_dialogs is only about 8 lines of code, most of which is just checking arguments. This uses _ListDialogController, which simply implements a simple TableView with a ui.ListDataSource. copy the code from list_dialogs, _ListDialogController, and make a custom class extending ListDataSource to do what you want inside the appropriate delegate function. dialogs.py and ui.py can be found after enabling Show Standard Library in options, then going to Standard Libray/site-packages. @JonB could you post an example? I am not exactly following you. I am at where you said to copy, but do you want me to put the class in the program file I am writing, or right by where the item I am copying? Just a bit lost. Sorry. Would I put it in the file after copying it, and making edits when pasted in the file, and then when I do it, I put a delegate attribute at the end? Like this: import dialogs # Put the copied class from the site-packages in the library. dialogs.list_dialog("Hello World","Test").delegate = # copied class here? Would this make sense? It does for me, but the .delegate doesn't work because it turns into a string when it's tapped on. @AtomBombed , if you look at the thread I sent before that is the example you are looking for as far as I can see. In my opinion, for the list dialog, rather than digging into it, you would be far better off just to use the TableView yourself with the ListDataSource. I think it would be much easier and you get more experience using the ui.TableView. The mistake I made before, was thinking that the ListDataSource was very limited, but it's not. You can also subclass it. Read the code for dialogs.list_dialog. The read the code for dialogs._ListDialogController. Then, read the code for ui.ListDataSource. Armed with that knowledge, you will see that none of these have a delegate attribute. A TableView has a delegate, which is set to a ListDataSource. The ListDataSource is the delegate...you need to make a new class that extends ListDataSource, but overrides the delegate methods you are interested in. Then use that instead of ListDataSouece in your custom dialog controller. Then use your custom dialog controller in your custom list_dialog. @JonB okay. I have been doing that, and I got pretty dang close, but it ended up just sitting in my code not doing anything. It didn't work, but it returned no errors. you problem is on line 29. actually, if you gist your code, someone might be able to help....
https://forum.omz-software.com/topic/2585/dialogs-list-dialog
CC-MAIN-2021-10
refinedweb
752
75.61
On Thu, Dec 24, 2009 at 12:46:34PM +0100, Reimar D?ffinger don't care if they use it for their main source, but I really think it > shouldn't be hard to make the headers work (at least also) with only plain C99. And even for their main source (SVN at least) it is completely unnecessary. Would probably be good to add to the bugreport that 1) it is completely unneeded 2) it ends up in the pkg_config flags where it might cause all kinds of confusion for apps using SDL, possibly even breaking compilation due to namespace collisions caused by GNU extensions.
http://ffmpeg.org/pipermail/ffmpeg-devel/2009-December/063114.html
CC-MAIN-2014-10
refinedweb
105
63.02
Proposed features/addr keys (2011-04) Outline This proposal introduces new keys for the addr namespace. It is only meant to deal with information on a micro level (the building itself). It is not a proposal to handle all other additional addr keys people would like to see included in the namespace. Those should be dealt with in separate proposals. That is why the name of this proposal includes the year and month, so it can be distinguished by future addr proposals. Why would you want to tag these keys Often bigger buildings like office blocks, shopping malls may have one general house number, but the different offices, flats or shops inside are addressed through a door number, floor number or unit. Since the distance between those kinds of POIs could be more than just a couple of feet, it it relevant to have this information for a more precise routing (probably in combination with associated_entrance. Keys All keys are meant to be optional. addr:unit While a big building could have only one entrance, sometimes the way inside divides into different units or staircases, where certain apartments/flats/offices can only be reached though a specific unit. An information necessary for postmen, for example. addr:floor The floor an apartment/flat/office is located. The value for the floor should always be a number: - -n = … - -2 = 2nd basement - -1 = basement - 0 = ground floor (UK), first floor (US), Erdgeschoß (DE) - 0.5 = mezzanine - 1 = first floor (UK), second floor (US), Erster Stock (DE) - n = … addr:door The actual door to an apartment/flat/office/room. Also, normally a number, sometimes a name. Could also be called differently in some countries (In Austria for example it is sometimes referred to as "Top"). If a room has more than one door, you can tag them separately. Examples Unit 419C-419D, 4/F The Mega Atrium, SM Megamall, EDSA cor. Julia Vargas Avenue, Ortigas Center, Mandaluyong - addr:city=Mandaluyong - addr:street=EDSA cor. Julia Vargas Avenue - addr:housename=The Mega Atrium, SM Megamall - addr:unit=419C-419D - addr:floor=3 Wiener Straße 23, Stiege 2, Tür 33, 1020 Wien, Österreich - addr:country=AT - addr:city=Wien - addr:postcode=1020 - addr:street=Wiener Straße - addr:housenumber=23 - addr:unit=2 - addr:door=33 Additional information Changes based on comments from the RFC phase Added addr:room= (seav)removed again, since rooms are more of an internal ID, then an address information. - Changed addr:staircase= to more generic term addr:unit= (seav) - Removed addr:entrance= since it was a bit controversial. Voting Voting is open until 2011-06-12. Please vote with {{vote|yes}} or {{vote|no}} and sign with ~~~~. If you oppose, please put your reason on the comments page and not in this voting chapter. - I approve this proposal. --Flaimo 20:53, 28 May 2011 (BST) - I oppose this proposal. This proposal is passing my line of accepted details. Approving this I wait until we are going to tag the way windows are isolated. ;-) Please do not be scared you will be out of work. Germany has a lot to do within the range of existing tags. - I approve this proposal. --Jstein 22:40, 28 May 2011 (BST) - I approve this proposal. --Fabi2 23:43, 28 May 2011 (BST) - I approve this proposal. --seav 06:46, 29 May 2011 (BST) - I approve this proposal. --Polyglot 07:23, 31 May 2011 (BST) - I oppose this proposal. -- If we want to amend the address-tags I'd like to add all needed tag extensions in one go. This proposal is not covering staircases any more (because unit is not a replacement for staircases, you could have several staircases in one unit), it is not covering building parts (de:"Seitenflügel links", "Hinterhaus", "2. Hinterhaus", ...), it does not define unit well enough (could be apartment, staircase, building part, site, ...), does not cover apartment numbers, ... Dieterdreist 13:55, 31 May 2011 (BST) - do you have a real life example where a building does have multiple units and staircases at the same time? even if such cases exists, it could be written as addr:unit=Unit1/Staircase1 and addr:unit=Unit1/Staircase2. you criticize the definition of "unit", yet you are not telling what you think is unclear about it. also if you like to see other subkeys, just start a proposal for it. the reason why they are not covered here is in the first paragraph of this page. --Flaimo 21:23, 31 May 2011 (BST) - I oppose this proposal. --It would get messy if you added a node for every office. How would you tag two offices on different floors? To distinguish between these 2 nodes you would have to move them to the side (You can't really put them on top of each other). A huge shopping mall would become littered with nodes. Especially when GPS loses accuracy inside buildings nodes for such detailed mapping are pointless. If you tried to include these details in a relation or something like this I would approve it. A relation would suit this much better. LetzFetz 18:02, 1 June 2011 (BST) - you would tag it exactly like you would tag other overlying features in OSM. btw, if there are dozens, even hundreds, of shops in a shopping mall, they will get tagged anyway, with or without address information. if you want a relation you can vote for this proposal later on: --Flaimo 19:24, 1 June 2011 (BST) - I approve this proposal. But I'd prefer more address types, including those that were dropped from this proposal. --Zverik 11:55, 6 June 2011 (BST) - the ones i dropped are the more controversial ones. but that doesn't mean that they can't be proposed again later on. --Flaimo 15:34, 11 June 2011 (BST) - - I oppose 2/3 of this proposal. "door" and "floor" are too much detailed for OSM. However, I think we could give a go to unit, for large buildings. --Don-vip 19:32, 11 June 2011 (BST) - I approve this proposal. --Nfgusedautoparts 21:54, 11 June 2011 (BST) - I am OK with this proposal. Just add it to the schema and let users decide whether to use it or not. --achadwick 11:21, 14 June 2011 (BST) - I oppose this proposal. The addr-namespace if for delivery and addr:full already covers special needs for that! For other information we have ref and name. Also have a look on Proposed_features/Building_attributes and Relations/Proposed/Level! --phobie m d 18:21, 30 June 2011 (BST) Post voting changes
http://wiki.openstreetmap.org/wiki/Proposed_features/addr_keys_(2011-04)
crawl-003
refinedweb
1,094
64.81
realMethods announces it is now part of the Open Source Initiative (OSI), making its J2EE Framework available as open source under the GNU General Public License (GPL). The realMethods core services are: - Full Persistence Support: BMP, CMP/CMR 2.0, and Data Access Objects - JMX compliance ensures an executing realMethods-based application can be administered. - Logging: A simple to use and extendable mechanism for logging to multiple destinations including System out, Log4J Logger, JMS connection, and/or IBM/MQ - Resource Pooling: Pools database connections (direct and Data Sources), JMS, LDAP, and IBM/MQ resources. Security Management Assists in handling application authorization and authentication. - Hook/Event Infrastructure: Allows you to introduce logic into the run-time aspects of certain key Framework processing. - Notification/Subscription Infrastructure: Handles notification surrounding the creation, update, and deletion of a Value Object. - ValueObject Cache: Provides HttpSession and Application level Value Object caching. - JMS/MDB/Command/Task Architecture: Define simple Commands and aggregate them into Tasks, made available for execution via JMS. Provides a simple technique to wrap any Task as a MessageDrivenBean. Quote on the OS release: "realMethods is finally convinced that a well run open source project will promote better software reliability and quality by supporting independent peer review and more rapid evolution of the source code, providing greater design pattern and J2EE coverage. Unlike most open source projects in this space, the realMethods Framework project is backed by realMethods Professional Services. Being based on the core J2EE Design Patterns, realMethods seeks to provide full coverage across all tiers of the J2EE spectrum, yet remain open to the easy integration of other frameworks. Importantly, components and services that exist in realMethods are usable outside the larger framework." Resources Go to the realMethods site: Read: Why open source? realMethods is free realMethods 2.3 Quick Start Guide (PDF) realMethods Open Sources Its J2EE Framework (18 messages) - Posted by: Steven Randolph - Posted on: July 14 2003 14:32 EDT Threaded Messages (18) - realMethods Open Sources Its J2EE Framework by Michael Turilin on July 15 2003 04:51 EDT - Useful? by Lofi Dewanto on July 15 2003 05:04 EDT - Transitioning to LGPL by Steven Randolph on July 15 2003 04:44 EDT - GPL by Lofi Dewanto on July 15 2003 05:24 EDT - Just to clarify... by Steven Randolph on July 15 2003 04:28 EDT - Using without the AIB by Steven Randolph on July 15 2003 16:32 EDT - Flaky, flaky, worrisome by sam adams on July 15 2003 11:20 EDT - code criticism by Christian Sell on July 16 2003 10:42 EDT - code criticism by Juozas Baliuka on July 21 2003 10:18 EDT - Flaky, flaky, worrisome by Steven Randolph on July 16 2003 11:37 EDT - Flaky, flaky, worrisome by sam adams on July 16 2003 11:52 EDT - realMethods Open Sources Its J2EE Framework by Erik Bengtson on July 15 2003 06:53 EDT - Reflection usage by Steven Randolph on July 15 2003 17:17 EDT - Reflection usage by Erik Bengtson on July 15 2003 06:42 EDT - Design choices by Igor Cunko on July 15 2003 07:29 EDT - How does this work? by Thomas Mattson on July 15 2003 08:20 EDT - No marketing gimmick... by Steven Randolph on July 15 2003 16:23 EDT - What happens when OSS is more mature than commercial offerings? by Sandra Cann on July 23 2003 00:08 EDT realMethods Open Sources Its J2EE Framework[ Go to top ] This framework seems to be not very useful without AIB - Application Infrastructure Builder which could be used to convert UML Models into the framework components. - Posted by: Michael Turilin - Posted on: July 15 2003 04:51 EDT - in response to Steven Randolph See: Useful?[ Go to top ] And also only useful for Open Source projects due to the GPL licencing ;-) Normally, you use GPL for applications and not for libraries or frameworks. For libraries or frameworks you usually use LGPL, so they can be used for your commercial software. - Posted by: Lofi Dewanto - Posted on: July 15 2003 05:04 EDT - in response to Michael Turilin Lofi. Transitioning to LGPL[ Go to top ] Your point is well taken. - Posted by: Steven Randolph - Posted on: July 15 2003 16:44 EDT - in response to Lofi Dewanto When starting with a commercial offering, and moving to an open source paradigm, it isn't the same as originally making the offering open source. I agree that LGPL on the surface seems appropriate for any library or framework, but our existing customers initially beg to differ. Also, those doing non-commercial work shouldn't have a problem. Those doing commercial work would certainly want to consider using something that is warranted, which makes either license scenario moot. We fully expect to transition to the LGPL shortly, and will continue to offer a commercial license to those looking for a warranty. GPL[ Go to top ] <quote> - Posted by: Lofi Dewanto - Posted on: July 15 2003 05:24 EDT - in response to Michael Turilin Licence GPL realMethods ... Any direct modifications to the realMethods Framework will become the property of realMethods. </quote> Can someone explain to me what this suppose to mean? So, if you change or extend the code of the framework itself, it will automatically become the property of realMethods? So, you will lose the copyright of your own code? I've never heard about this. Normally you keep the copyright of your code, independent of what kind of Open Source licensing you choose. Thanx! Lofi. Just to clarify...[ Go to top ] Just to be clear, changes to a framework source file do not become the property of realmethods. That is an error on the website. thanks...and sorry for the confusion. - Posted by: Steven Randolph - Posted on: July 15 2003 16:28 EDT - in response to Lofi Dewanto Using without the AIB[ Go to top ] We have customers that have build there applications without using our AIB code generator. Rather, they start with our Proof of Concept application and build from there. Also, the fact is that folks just aren't into UML diagrams. Typically, what we have seen is that a team of developers and architects, only a few would actually be responsibly for the model and code generation, while the remaining team members make use of the generated code. - Posted by: Steven Randolph - Posted on: July 15 2003 16:32 EDT - in response to Michael Turilin Flaky, flaky, worrisome[ Go to top ] This is really bizarre code. Anything purporting to be *THE* framework is very suspicious. Big bad non-modular kitchen sink that does not work out of the box. - Posted by: sam adams - Posted on: July 15 2003 23:20 EDT - in response to Steven Randolph Throwing Exceptions is such a Java 101 error. A prime example of anti-patterns at their best. *Not* a single unit test anywhere should indicate the robustness of this code. And what are all those I* interfaces doing everywhere? There is no internal consistency, no external coherence. The code crashes everywhere. Try running it! The developers have done NO* error checking anywhere. See what happens if you don't set FRAMEWORK_HOME property at line 253 in com.framework.common.FrameworkNameSpace. NullException kaboom! More seriously, see what happens when you run exceed maxCapacity on your connection pool at line line 218 in com.framework.objectpool.ConnectionPool.java!! NullException kaput! The Javadoc promises: An available connection object or waits until one is available. There is *NO* wait anywhere to be seen. Not to mention how this jibes with the EJB spec on threading!!! And what a WRONG backwards dependency: ConnectionPool depending on an MBeans implementation!!! public class ConnectionPool extends ConnectionPoolMBean implements IConnectionPool Huh? Just follow the call stack getMaxCapacity() to see why this product crawls. They should check out Jack Shirazi's site for basic 101 performance tips. Again, no unit tests? I wonder why... What gives Mr. RealMethods? What's the reason? code criticism[ Go to top ] as valid as some comments may be - the way the source code is being criticized here makes me wonder whether I would ever want to publish a formerly commercial product into OS. - Posted by: Christian Sell - Posted on: July 16 2003 10:42 EDT - in response to sam adams Christian code criticism[ Go to top ] as valid as some comments may be - the way the source code is being criticized here makes me wonder whether I would ever want to publish a formerly commercial product into OS. - Posted by: Juozas Baliuka - Posted on: July 21 2003 10:18 EDT - in response to Christian Sell The best way to fix framework/technology is to let users/developers to do it. I am sure problems will be fixed if this framework is used by developers. > > Christian Flaky, flaky, worrisome[ Go to top ] With the product being in product for the past 2 years, don't think we would have come across a scenario that would have proven this implementation to be deficient. Months of profiling with one of the largest US government agencies certainly would have exposed something...don't you think? How you can make such bold face claims and challenges without actually having used and profiled the product is beyond me. - Posted by: Steven Randolph - Posted on: July 16 2003 11:37 EDT - in response to sam adams Flaky, flaky, worrisome[ Go to top ] bold face claims and challenges without actually having used - Posted by: sam adams - Posted on: July 16 2003 11:52 EDT - in response to Steven Randolph I have had to extensively use this product. :( You might want to address the specifics of my post, instead of a vague answer. Just one question: Do you have any unit tests? Do you ever run them on your code? realMethods Open Sources Its J2EE Framework[ Go to top ] This framework is using a lot of reflection. Does anyone have a true experience with realMethods? - Posted by: Erik Bengtson - Posted on: July 15 2003 06:53 EDT - in response to Steven Randolph Reflection usage[ Go to top ] Other than a few helper methods in the base class for all value objects (FrameworkValueObject), and to obtain the constructor for a couple of classes that are dynamimcally loaded via a property file, if you could point me in the direction of the areas of concern, I will gladly respond. The runtime aspects of the framework do not use any reflection, and these helper methods are there as utility methods, but never used by the framework itself. There isn't much type safety with a reflection-based framework, so we don't rely on it as being core. - Posted by: Steven Randolph - Posted on: July 15 2003 17:17 EDT - in response to Erik Bengtson thanks. Reflection usage[ Go to top ] Other than a few helper methods in the base class for all value objects (FrameworkValueObject), and to obtain the constructor for a couple of classes - Posted by: Erik Bengtson - Posted on: July 15 2003 18:42 EDT - in response to Steven Randolph Value objects are the most important objects of any application. There might not be a solution besides reflection, but, in the scenario I have in mind, the application performance may slow down. Have you tried to use a profile tool to see if it causes performance problems ? Also, having some collaboration/sequence diagrams will help users to see how the framework works. In the end, the framework seems to be useful in some way, and I will find how. I'm just worried about the reflection Design choices[ Go to top ] I found source hard to read because of atypical naming convention and structure , m_ for variable names and sometimes hungarian notation !? ( yes , I know it is personal, but... ). - Posted by: Igor Cunko - Posted on: July 15 2003 07:29 EDT - in response to Steven Randolph On less personal note, design seems to be a little bit flaky , I don't like to see class properties to have protected access, set/get and private access gives you more flexibility. It is hard to refactor protected access at framework level if not impossible. Also having Exception in throws clause is useless IMHO , a lot of if ( xx == true ) constructs which also raises concern in my mind. I will take a good look before start using it. How does this work?[ Go to top ] Any use of J2EE components implies using 1) J2EE interfaces distributed by Sun or 2) creating a clean room J2EE compatible interfaces. - Posted by: Thomas Mattson - Posted on: July 15 2003 08:20 EDT - in response to Steven Randolph #1 Does not work for an Open Source product since Sun's licensing terms for their J2EE interfaces is not compatible with OSS. #2 Implies the interfaces are under GPL meaning anything I build with these interfaces must be licensed under GPL as well (which is fine if you're ok GPL'ing your business applications but a lot of us are not). #3 Sell a commercial dual-license (which they do) but that sort of makes the whole 'free of charge' look more like a marketing trick...? Hmm? /T No marketing gimmick...[ Go to top ] I fully understand the concern surrounding the seeming conflict that arises with a framework and the GPL. Unfortunately, for the past 2 years, we originally offered the framework as a commercial licensed product, so offering a dual license keeps us in the good graces of current customers. Since nothing is warranted under the GPL, commercial usages would tend to want a license to the product for the protection as well as the support. - Posted by: Steven Randolph - Posted on: July 15 2003 16:23 EDT - in response to Thomas Mattson What happens when OSS is more mature than commercial offerings?[ Go to top ] This referenced quote is incorrect, "Unlike most open source projects in this space, the realMethods Framework project is backed by realMethods Professional Services." - Expresso Fraemwork has always offered Professional Services! We are certainly not the only ones offering services either. (Expresso Framework dev started in 1996, released in 1999 & has the largest J2EE architectural framework user base by far) - Posted by: Sandra Cann - Posted on: July 23 2003 00:08 EDT - in response to Steven Randolph In reference to your comment that "realMethods is finally convinced that a well run open source project will promote better software reliability and quality..." - This is unrealistic because a GPL license is an inappropiate license for a framework and it will be difficult to attract developers. It takes more than OSS to generate a vibrant community that participates in the activities necessary to create better software. What happens when successful open source products become more mature than their commercial counterparts due to the fast evolution of the sofware with the open source community development process? I think this time has come and now many commercial architectural frameworks face a challenge. To be blunt I wonder if RealMethods is struggling and that is the real reason for this change to OSS? With a recession and many new comers to the framework arena - its a tough environment. Altoweb is out of business. Companies like wakesoft have a dozen customers only. So can commercial companies survive with more mature OSS J2EE architectural frameworks available? or can they differentiate themselves sufficiently?
http://www.theserverside.com/discussions/thread.tss?thread_id=20341
CC-MAIN-2017-04
refinedweb
2,548
59.74
Windows Phone Choosers Windows Phone does not yet support multi-tasking, however you can interact with some of the built-in applications on the phone from within chooser from your application and have that chooser return some data from the built-in application. The specific chooser for this blog post will be the PhoneNumberChooserTask as shown in Figure 1. Figure 1: Call the PhoneNumberChooserTask to return a phone number to your application. Overview A Chooser on the Windows Phone application allows your application to call a built-in application to get some data from that application and return data. As an example, you might want to access the contacts on your phone and return a phone number to your application from one of those contacts. You can use the PhoneNumberChooserTask to have your application make a call to get that data. The data that is. Calling a Chooser You may call any of the several built-in Chooser applications on the Windows Phone by simply using the classes contained in the Microsoft.Phone.Tasks namespace. The list of chooser classes are listed below: CameraCaptureTask PhoneNumberChooserTask PhotoChooserTask SaveEmailAddressTask SavePhoneNumberTask Most of the; Next, you Completed event handler in the constructor because your application could be tombstoned once it calls the choose 1 you will click on a button to invoke the Phone Number Chooser task box in your application. void task_Completed(object sender, PhoneNumberResult e) { // See if task completed if (e.TaskResult == TaskResult.OK) txtPhone.Text = e.PhoneNumber; // Grab phone number } Summary In this blog post you were introduced to the Choosers that are available in the Windows Phone. You learned how to call the PhoneNumberChooserTask to access the contact list and return a phone number to your application. Using the chooser APIs allows you to call many of the built-in applications on the Windows Phone. Each chooser will return different data depending on what each one does. All choosers will fire a completed event once they return control back to your application. Even though all choosers will not necessarily tombstone your application, be sure to program for tombstoning just to be on the safe side. NOTE: You can download this article and many samples like the one shown in this blog entry at my website.. Select “Tips and Tricks”, then “Windows Phone Choosers” from the drop down list. Good Luck with your Coding, Paul Sheriff ** SPECIAL OFFER FOR MY BLOG READERS ** We frequently offer a FREE gift for readers of my blog. Visit for your FREE gift!
http://weblogs.asp.net/psheriff/windows-phone-choosers
CC-MAIN-2015-18
refinedweb
418
59.33
Steve Lasker Immedient November 2002 Applies to: Microsoft® Visual Studio® .NET Microsoft Windows® Forms Microsoft® ASP.NET Microsoft® Mobile Internet Toolkit Microsoft® .NET Compact Framework Summary: Walks through the process of debugging any custom design-time control when it is being used with the Microsoft Visual Studio .NET designer, and describes the chain of events that take place when you work with controls in the design surface. (13 printed pages) Download Designtimedebugging.exe. Introduction Setting Up the Environment Creating the Blank Solution Creating a Control Library Creating the Windows Forms Host Project Starting Our Debugging Session Chain of Events Summary An important part of developing any design-time control is the ability to troubleshoot and debug your code. When working with a control or Microsoft® Windows® Form in the design-time environment of Microsoft Visual Studio® .NET, your code is being executed even though the project does not appear to be running. This can pose a challenge as far as debugging goes. If you are creating any type of object that will have a design-time view, this article shows you how you can catch errors and debug when your object is being used within the Visual Studio designer. I will also describe some of the chain of events that happen when you work with controls in the design surface. The best part is that you don't have to create any wrapper objects. The Visual Studio .NET team baked the debugging environment right in. To show the steps of troubleshooting and debugging your code as you change values or drop controls onto the design surface, we'll create an example base Windows Form that has a string property. When we change the value of the property, we'll step into the debugger. In order to minimize the potential for errors due to lack of specifics, all files and directories have specific names. You're more then welcome to change these as you'd like. However, for clarity and ease of demonstration, I'll specify everything in detail. The first step is to create an environment to host our code. We'll create: Figure 1. Creating a blank solution to contain several projects Since our purpose is to demonstrate debugging, not to create custom controls, we won't worry about creating an elaborate control. We'll just create a simple Form with a bogus property. Figure 2. Adding a control library for your design-time control Note We're purposely naming the Form with a collision to demonstrate namespaces. Visual Basic .NET Private _myText As String ''' <summary> ''' A Custom property used for this silly sample ''' </summary> ''' <value>A value of no meaning</value> <Description("A Custom property used for this silly sample"), _ DefaultValue("Hello"), _ Category("Appearance")> _ Public Property MyText() As String Get Return _myText End Get Set(ByVal Value As String) If (_myText <> Value) Then _myText = Value End If End Set End Property C# private string _myText = "Hello"; /// <summary> /// A Custom property used for this silly sample /// </summary> /// <value>A value of no meaning</value> [ Description("A Custom property used for this silly sample"), DefaultValue("Hello"), Category("Appearance") ] public string MyText { get{return _myText;} set { if(_myText != value) { _myText = value; } } } Visual Basic .NET C# Private _myText As String = "Hello"; This is a private variable to hold the contents of our public property. Private _myText As String = "Hello"; [ ] in C# or <> in Visual Basic .NET In C#, all code between the square brackets (<> in Microsoft® Visual Basic® .NET) are attributes. These inform the common language runtime (CLR) to behave in a given way once constructed. Attributes are sort of a cross between a constructor and pre-processor directive. They're set at coding time, and can't be changed at run time. [ ] in C# or <> in Visual Basic .NET Description("A Custom property used for this silly sample") This adds a description to the bottom of the property sheet for your property. We usually duplicate the same text from our XML summary documentation. (Hopefully the product team will merge these two declarations in the future.) Description("A Custom property used for this silly sample") This Figure 3. Your custom property, with its description, displayed on the property sheet DefaultValue("Hello") This is used in combination with the default value of our private variable. If the value of the property doesn't match the value in the DefaultValue attribute, the property sheet will show the value in bold. Visual Studio .NET will also generate code in the InitializeComponent() method to set the value. If the property sheet value matches the value in the DefaultValue attribute, the property sheet value will not be displayed in bold, and the InitializeComponent() will not have any reference to the property. This is great for inheritance. If none of the derived objects changed this property, they will inherit any changes you make to the base class. This can be a very powerful feature when used properly. DefaultValue("Hello") Category("Appearance") This value is used to sort the properties in the property sheet. Category("Appearance") Figure 4. Adding a project reference to your design-time control Visual Basic .NET Public Class Form1 Inherits Immedient.Windows.Forms.Form C# namespace Immedient.Samples.HostApp.Windows { public class Form1 : Immedient.Windows.Forms.Form { Immedient.Windows.Forms.Form There are a couple of properties you'll want to set, and one to verify on our control library project. You'll want to confirm that you're actually generating the required debugging information for Visual Studio .NET to step into your code. If you get the "?" symbol on your breakpoints when you start the debugging session, you're not generating the appropriate symbol files. This may be because you're in release mode, or because the setting was changed accidentally. Be sure the Generate Debugging Information property is set to true. The following settings will only apply to C# projects. In Visual Studio .NET 2002, Visual Basic .NET does not have a means to generate XML documentation. In order to benefit from the C# XML documentation we created, you need to tell Visual Studio .NET to generate an XML file. In the XML Documentation File property, set the value to the same name as your assembly with the xml extension. (It would be nice if they just had a checkbox for this, but oh well...) Finally, there's one more trick about XML documentation. Once you set the value for XML Documentation File, Visual Studio .NET is very helpful in warning you of every public interface that doesn't have documentation assigned. This gets real annoying, real fast. So, if you're not ready to deal with all the public interface documentation, you can set the Warning Level to 2. The task list won't be cluttered with warnings until you're ready to address them by filling in the documentation. Figure 5. Setting properties related to XML documentation in a C# project Now that we have some code to debug, let's start the session. In order to debug our code, we need to step into the application that is hosting our code. In this case it's Visual Studio .NET. Note Visual Studio .NET was designed, just like the rest of the .NET Framework, from the ground up to host the design environment. Remember, the product team used the same set of tools we use. All we need to do is to start our class library within Visual Studio .NET. We do this with some properties on the Project. Within the Debugging section, there are a couple of properties we need to change. They are slightly different in Visual Basic .NET and C#: Figure 6. Setting the startup program to host your debugging session (Visual Basic .NET) Figure 7. Setting the startup program to host your debugging session (C#) Set a breakpoint on the if statement within the set of the property. if statement Note You won't want to set a breakpoint on the get without setting an assert, as the design-time environment will "get" the value many more times than you want to hit F5. Figure 8. Setting the breakpoint in your custom property Be sure the Control Library project is the Startup Project. Set this by right-clicking the Control Library project and then click Set as Startup Project. Good Bye .NET. .NET. The only thing magic about this method is its name. Visual Studio .NET just knows to look for this method. In Visual Basic .NET, if Visual Studio .NET can't understand the line of code, the line is removed (a nice way of saying eaten). The Visual Basic team felt it was more important to maintain the design-time environment. The C# team felt it was more important to maintain the code, so if Visual Studio .NET .NET, .NET designer. So you have the option to wrap code within an if statement. There's one more trick, however. The Deisgn To have some fun and see what events fire, and when the DesignMode property is set, drop the following code in your Immedient.Windows.Forms.Form. In order to get the events to fire in Visual Studio .NET, you'll need to close all the forms, and then recompile your solution. Visual Basic .NET Private Sub Form_Layout(ByVal sender As Object, _ ByVal e As System.Windows.Forms.LayoutEventArgs) _ Handles MyBase.Layout MessageBox.Show("layout: DesignMode=" + _ Me.DesignMode.ToString()) End Sub Private Sub Form_Load(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles MyBase.Load If Me.DesignMode Then ' Don't connect to the database at design time MessageBox.Show("Form Load: DesignMode=" + _ Me.DesignMode.ToString()) Else ' Make a connection to the database, and do something MessageBox.Show("Form Load: DesignMode=" + _ Me.DesignMode.ToString()) End If End Sub Private Sub Form_VisibleChanged(ByVal sender As Object, _ ByVal e As System.EventArgs) _ Handles MyBase.VisibleChanged MessageBox.Show("VisibleChanged: DesignMode=" + _ Me.DesignMode.ToString()) End Sub Private Sub Form_Paint(ByVal sender As Object, _ ByVal e As System.Windows.Forms.PaintEventArgs) _ Handles MyBase.Paint MessageBox.Show("Paint: DesignMode=" + _ Me.DesignMode.ToString()) End Sub In this article, we used a simple property on a Windows Form. However, anything that changes in the design-time environment can be debugged. I originally found this technique when developing a Microsoft® ASP.NET Image HREF design-time control. This same technique applies to component controls, like the EventLog and Data controls that display in the system tray as well. Visual Studio .NET provides a rich, productive development environment for developing controls, in which it's just as easy to create and debug controls as it is to consume them. Steve Lasker is the National Director of Research & Development at Immedient. Steve has been developing .NET controls and frameworks for Windows Forms, ASP.NET, and the .NET Compact Framework. Steve can be reached at Steve.Lasker@Immedient.com.
http://msdn.microsoft.com/en-us/library/ms996457.aspx
crawl-002
refinedweb
1,819
58.28
Details of MSFT's Antitrust Lobbying 711 An anonymous sent in linkage to "A new ZDNet article detailing new evidence presented to the judge presiding over the Microsoft anti-trust case. It shows that Microsoft made political contributions during last year's (well, 2000's) elections on a scale never seen before... over $6 million. As comparison, this is four times the amount spent by Enron. It also reveals that Microsoft has been hiring every political lobbyist, and every law firm, with anti-trust expertise and putting them to work on unrelated projects- anything to make them unavailable to work for critics of Microsoft." And, we have no one to blame but ourselves. (Score:5, Interesting) We elected the politicans who made the laws in the first place which allowed campaign contributions to be illegal. Infact, during the last election, we didn't want the guy who was willing to do away with them. We wanted to play Bush vs. Gore instead. Before you run off pointing fingers at Microsoft for doing what they are within the scope of the law to do, ask yourself where the core of the corruption sits. Its not with them, or the politicians. Its us, and our lack of desire to make our elected officials accountable for their actions. Lobbying wouldn't exist if we as a people decide not to allow it. Anything beyond it would be bribery. Cheers, Re:And, we have no one to blame but ourselves. (Score:5, Insightful) If the Federal government were actually limited in scope (refer to Constitution here), then there would be a lot less to lobby for, to "contribute soft money" for, etc. I would like to not only limit the power of the government, but prevent lawyers from holding office. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) This is dead on. I do not underastand those who say that the answer to bad ans stupid laws are is more of the same. People will bribe governments so long as governments have the power do something for them. Re:And, we have no one to blame but ourselves. (Score:2, Insightful) And when the government does not have any power anymore, we will have to bribe whatever entity governing instead of the government. I prefer to pay tax than "microsoft tax" or mob "protection" tax. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) True but would you rather the bribes that polititican take be legal, as they are now, in the form of "Soft Money"? Or would you rather the that the dishonest people in government really act like crooks and be forced to solicit and accept illegal bribes? I would much rather see that we call it what it is (a bribe) and treat it that way, then wave our arms and declare that the real problem is elsewhere. Yes I understand that this is not to the point of the original argument, that government is to big and must be reduced, but change will most likely be incremental and not all at once. Let's take our victories where we can. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) The Justice system is so bogged down that Congress can pass laws that they know will not be repealed by the Justice Department for years (when they can claim it was their predecessors who passed it in the first place). The President has become more of a figurehead than the Queen of England. What is even worse is that there is so much childish, partisanship in Congress that nothing ever gets done except when they have a common goal which is usually to benefit the corporate giants that line their pockets. Re:And, we have no one to blame but ourselves. (Score:3, Informative) I do agree about the childish partisanship, except that I get the feeling that it's all a ruse to distract us from noticing that common goal you mention. (lining their pockets w/ corporate money) Re:And, we have no one to blame but ourselves. (Score:2, Informative) No, the real - the only - remedy to this crisis of democracy is to curtail the financial power of the lobbies and private donators. Here in Quebec we had campaign financing reform thirty years ago, placing severe limits on how much politicians can receive from companies and individuals, and it has greatly enhanced the integrity of the political class. Sure, nothing's perfect, but it's still a lot better than it was before! Cutting out the source of evil, i.e. lobbies and companies "buying" influence (when that influence should come from the citizens alone if representative democracy is to be, well, democratic) by putting severe caps on campaign contribution is the simplest yet most efficient way to clean up Washington of its grimy layer of corruption. Well, the first layer, at least. If you don't think that's true, then ponder why most of the political class spends so much effort preventing this from happening... Re:And, we have no one to blame but ourselves. (Score:3, Insightful) So when you reduce the power of the federal government... where does it go? I seem to recall that the early power struggles in our countries infancy were primarily federal government vs. state governments. If more power were granted to the states, Microsoft and other corporations would merely switch their focus to brib^H^H^H^H contributing to state and local officials (Not that they're overlooking them now, mind). Re:And, we have no one to blame but ourselves. (Score:3, Informative) You act as if the government is some kind of third party in our lives like a referee in a football game. Ostensibly, the government is us . . . "We the People." So by advocating the reduction of the power of government you're advocating a reduction of the power of the people. I take that personally as I am one of those people. The people of the United States of America are already on their knees bowing to the power of the corporation. Why would you advocate reducing our only means of defending ourselves from exploitation? We the People! Re:And, we have no one to blame but ourselves. (Score:3, Informative) Your argument that Libertarians are in favor of reducing power is simply incorrect. I want my locally elected official to have the power that he/she should have as written in the Constitution. *I*, personally, want to power to decide certain things about my life, leaving the goverment out of those decisions. As a result, these powers need to be taken away fro the federal government. This is not a *reduction* in power, but a reallocation. The entire start of this thread was that if you reduce power to the federal government, you reduce power to corporations to bribe those same individuals. Your argument that we need a overly-protective federal government to protect us from those same corporations is exactly opposite to that thinking and the evidence pointed out in the original article. As for everyone arguing that moving power to the states will only mean that MS will resort to bribing them - remember who it is pushing for a weak settlement (Department of Justice and the White House) and who it is pushing for more extreme measures (the states and the states' Attorney Generals). This is direct evidence against that claim. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) Re:And, we have no one to blame but ourselves. (Score:4, Interesting) I live in Switzerland which is a true democracy. In Switzerland every person has the right to vote yes or no to certain decisions. The government is only there for the details. Sure Swiss vote quite a bit, but the power is with the Swiss people and only the Swiss people. And in that case lobbying has absolutely no effect unless of course the lobbyists decide to give money to each Swiss. True democracy works and it should be used more often in other countries. Re:We have no one to blame but our dollars (Score:3, Insightful) Putting everything under the control of "one person, one vote" is simply mob rule. Democracy should have limits, as should every form of government. Having an all-powerful central government, but making it "democratic," does not change the fact that it's still an all-powerful central government. It just means there's more people to bribe. Re:And, we have no one to blame but ourselves. (Score:3, Insightful) When the government gets out of the tax-regulate-and-subsidize business, and sticks to preventing and punishing theft, injury, etc., then it will be performing its proper role. As long as a corporation can buy an advantage in the marketplace -- including shielding itself from liability -- then there will be a place for lobbying, bribes, etc. Would you prefer a corporation, with no obligation to listen to you, make important choices for you Absolutely not. I'm in favor of stripping corporations of their legal personhood, actually. I believe that campaign finance reform is in itself at least a start to solving many of these sorts of problems. Hmmm. Not really. It just stirs the pot a little. Strip corporations of their personhood, so they have no first amendment rights, and prohibit them from engaging in any political activity. I.e., make it the way things used to be. Re:And, we have no one to blame but ourselves. (Score:2) Excuse me? Have you seen what happens when capitalism is allowed to run unregulated? Enron? Microsoft? Standard Oil? Unregulated capitalism is far worse than regulated government - at least with the latter you know who's in charge. Re:And, we have no one to blame but ourselves. (Score:4, Insightful) Regulation is, like it or not, extending punishing of theft and injury laws to companies. Regulating companies stops them from harming their workers, their neigbours, their customers because they can. It also stops them from doing violence to other companies - which, let's be honest, is exactly what MS is currently on trial for, using its strength to force other companies out of the market or their products onto customers at nasty terms. You actually contradict yourself. To quote, "As long as a company can buy an advantage in the marketplace Subsidies are a harder argument, but here goes... Remove subsidies of all kinds (I'm including Social Security benefits here, they seem analagous) and you cause problems. You know all about needing money to make money? Well, how do you get that first step without money from _somewhere_? Anyway, you create people who simply can't earn a living (and where this isn't necessarily a permanent condition), so they either die or live from crime. Think what happens in a recession here - the very poorest either die or cause a crimewave. A crimewave causes clear problems for society as a whole, and ends up with a number of them locked up. So, what do you end up with? A larger prison population (expensive to maintain) and a smaller labour force, which pushes up wages and makes it harder to get ourt of recession. Eventually, you end up with smaller economic capacity this way because you simply don't have the workers you need. Whereas if you give them the money / resources they need to see out the recession, they remain economically active throughout the problems (so help maintain economic capacity) and are available to work afterwards, so keeping costs down due to a large labour force. Oh, you've also likely lost the majority of the crime which is good on its own but also reduces your expensive-to-maintain prison population. Or maybe health benefits. If the poorest can't get treatment then you have an increased potential for epidemic which can spread into the wider population. They're not likely to be particularly healthy to start with (worse diet & living conditions, can't afford better) so they're more susceptible, plus the poorer sections of society tend to live together, helping it spread quickly among them. Deny them medical treatment and ailments can run through them at ridiculous rates, then spread into the wider population. Also, deny them medical treatment and some will die, some will be disabled in some way and some will have to miss work. In each case you've removed someone from the available cheap labour pool, maybe others who now have to care for them too... What about subsidising companies? Well, statistically speaking, I understand that the major driver for economic growth is small companies, not large. Except that they can't exist without seed capital from somewhere... Remove government subsidies and some won't survive, so lower economic growth as a whole. Or another example, farm subsidies. The EU Common Agricultural Policy is a mess, I won't deny it. However... In the UK, we have many areas where sheep are farmed on open hillsides traditionally. These are only viable due to subsidies, because the animal densities are too low. Remove the subsidies and the sheep go. Remove the sheep, though, and the land quickly becomes covered in long grass and bracken. At which point it's considered less beautiful and is certainly less suitable for walking. You then have no farming income - and an area that only has tourism left, but can't any more attract people to look at the views and walk the hills because the environment has changed. You need the sheep as lawnmowers... The current system is a long way from being perfect. Heck, I'm a LibDem () so I'm working to change it in many ways. But, strangely enough, many of the current aspects of government have been set up because they look like a good idea and retained because they prove that they are a good idea! I'd LOVE to see corporations stripped of legal personhood, too, for example, and see no reason for them to make any political donations. Heck, while we're thinking about corporate political influence, it seems daft that sitting legislators can hold directorships in companies, or that individual companies can own large chunks of the news media. Or that foreign-owned companies can own any. Who says that an Australian run media isn't spinning the news to favour Australian interests over local? As you can see here, we have clear examples of corporate political speech needing legal controls to benefit the people... Posters in general and moderators in particular, _please_ think a little harder about this 'smaller government rules' (whoops, pun unintentional...) argument. It may sound good - and some of it may indeed be good - but look at the details and much of it is utter rubbish. Really. Re:And, we have no one to blame but ourselves. (Score:2, Interesting) Being a politician should be a volunteered public service, and no one should ever be allowed to make any money from doing such work. This would remove the "career politicians", cut down on cost (no salaries for them) and would force them to still be a working constituent as well as a politician. Making a career out of politics is simply sickening Re:And, we have no one to blame but ourselves. (Score:4, Insightful) That would create a class based government system (as if it isn't already). Because then only rich people could afford to serve the government, because the working class would have to work to eat. Re:And, we have no one to blame but ourselves. (Score:2) Re:And, we have no one to blame but ourselves. (Score:5, Informative) Have any of you American I couldn't blame MS for this. They are just playing the game, and playing it well. Re:And, we have no one to blame but ourselves. (Score:2, Insightful) The problem is with those who take the money, as you said. Anybody who believes that the current campaign finance reform crap (I have to call it what it is) is going to do ANYTHING, just think again. Whenever the recipients, namely the politicians have tried to 'clean it up, for the good of everyone', all that happens is the balance shifts around and loopholes are found. Heck, soft money didn't exist before the much touted Watergate reform! Can I fault Microsoft for doing stuff like this? Probably, this is For as long as Congress can make laws regulating what they cannot do, this problem will always exist in one form or another! That's life. Re:And, we have no one to blame but ourselves. (Score:5, Insightful) This is not directed to the poster per se but to all who carp along these lines, in increasing numbers today: Oh, whine whine whine. Of course people are going to find loopholes. Of course money will creep in again. Of course new dastardly means of influence peddling will be found. How absolutely fratzen stupid is it to throw up your hands and say, "Oh, well, the system can't be made perfect so we shouldn't even try to improve it." If new loopholes arise, plug them. Plain and simple. Yes, you'll actually have to keep figthing this battle. Yes, it will be honest-to-God actual work to be a member of a democracy. Horror of horrors. Stop bemoaning the lack of perfectibility. It doesn't get us anywhere and it actually impedes what progress can be made. Re:And, we have no one to blame but ourselves. (Score:2, Interesting) So they could say they were supporting one party over the other because they thought it's policies would benefit them. But in general companies (in the US and the UK) support both main parties. So either they are doing this without expecting anything in return (which is wasting shareholders money), or they are expecting to gain something for their money (which is bribery). So how is this legal?? Re:And, we have no one to blame but ourselves. (Score:2) Re:And, we have no one to blame but ourselves. (Score:2) Re:And, we have no one to blame but ourselves. (Score:2) Gore was one of the guys willing to do serious campaign reform. Re:And, we have no one to blame but ourselves. (Score:2) Besides...as has been pointed out elsewhere, bureaucrats work in CYA mode, and overwhelmingly prefer one kind of error (giving thumbs down to something that is worthwhile) to the other (approving something that later turns out to be bogus). How many people have died prematurely because of that? Enron? (Score:3, Insightful) So? What does Microsoft have to do with Enron? Oh, I get it..It's popular to bash Enron right now. More to the point, what did you expect MS to do? Suddenly start playing fair? Oh, you got me, here's where I hid the bodies, etc.? Please. Re:Enron? (Score:3, Informative) 1. It has recently become a very well known entity. 2. It was also large and had lots of money. 3. It spent quite a bit of money lobbying. 4. It puts people in the mindset the article is looking for. Re:Enron (Score:5, Insightful) Currently, Enron is the posterchild for the reason for campaign finance reform. If our politicians are swayed by the campaign contributions of Enron's scale, what corruption is seeded by a larger sum of money? If the advertising power of the campaigns is knocked askew by some soft money, isn't it knocked asunder by larger sums? For a few stories linking Enron to campaign finance, you can look at this topic list on Salon.com [salon.com]. The topic is campaign finance. The headlines mostly discuss Enron in recent weeks. Re:Enron (Score:2, Informative) Yet another reason... (Score:4, Funny) This news probably doesn't surprise too many people in this crowd, I think we all knew that MS was pretty generous with soft monies, but it's very nice to see an article like this. The best part of the entire article? The paragraph about the $25k given to buy off South Carolina's Attorney General. P.S. Anyone else amazed by the fact that there is a place called Chevy Chase, Maryland?! Re:Yet another reason... (Score:2) And that someone MS worked/lobbied there? their 2001 site says:: "he Village contains about 200 single-family residences and a few religious and professional establishments." Re:Yet another reason... (Score:3, Insightful) One way to build the party is to run "issue ads". For the uninitiated, "Bill Clinton blows goats. Al Gore says Clinton is the best President ever." is an issue ad. On the other hand, "Bill Clinton blows goats. Al Gore says Clinton is the best President ever. Vote Gore." is supporting a political candidate, and thus is subject to hard money limits. Now, on the one hand, the regulation of this spending means that there is no way that I could take out an ad saying "Vote for " on TV, because it's more costly than the rules allow. (This is blatantly unconstitutional.) On the other hand, I could take out an ad saying " is a total wad" and I'd be perfectly legal. Political parties can also take out such ads. So you want to ban "soft money". Sorry, you can't. The Supreme Court has already held that "money is expression" in that preventing someone from airing their views violates the first amendment. The Shays-Meehan (sp?) bill would instead ban unregulated contributions to political parties. There would be no prohibition on companies, unions or PACs running all the issue ads they want, or all the get out the vote campaigns they want, on behalf of a party, so long as the party does not direct their activities. Could somebody explain to me how preventing one body of private citizens (a political party) from doing something, while allowing another (say, a PAC) to do that thing, would be constitutional? It smacks of a bill of attainder, and certainly violates the first amendment in the event that what's being prevented is the expression of political views. It seems to me that the better way to handle election finance issues is to require all money used for political purposes to be disclosed, and to prosecute those guilty of influence peddling or accepting bribes. In most cases, it won't be clear cut, but it would certainly be possible to recall politicians who are abusing their office by acting on behalf of those who spent money for them. And realistically, what would probably happen is that candidates would get more money directly, and outside spending would decrease. -jeff Re:Yet another reason... (Score:2) Why? It was there first. In fact, Chevy Chase the comedian probably named himself after it; his birth name was Cornelius Crane Chase, you know. Chris Mattern Re:Yet another reason... (Score:3, Interesting) Not all of these groups want the government to line their pockets, they have issues that they want addressed and they to influence how they are addressed. That is what democracy is about, and since there is a first ammendment the government is not going to tell us that their views should or should not be listened to Comment 3 million! (Score:3, Interesting) A contrarian viewpoint. (Score:5, Interesting) The candidates take the money and use it to buy ads so they can reach the public. This is not a serious problem, it's what comes after that is a serious problem -- the quid pro quo that the donor expects. So the problem is not money, it is the influence of people who have money. Making money harder for candidates to raise doesn't mean the need for money goes away -- quite the contrary. The candidates have to work harder for every dollar. The marginal value of every additional dollar raised is higher to the candidate because of the general scarcity of funds. On the flip side, the cost of buying influence drops. Let me propose this law of political fundraising: As proof, let us suppose that Enron and Microsoft succeeded in buyin our federal government for a few paltry millions. This is unconscionable! It should cost billions to have this kind of influence; influence buying should require bribery on such a grand scale it either prices people out or requires a brazeness so affronting to the common votor that it becomes self defeating. We should also repeal the notion that corporations are persons with respect to campaign contributions -- it's a legal invitation to bribery. Re:A contrarian viewpoint. (Score:3, Insightful) It's especially disgusting when you realize the actual costs to us collectively. For a few millions, corporations buy their way into legal tax and accounting loopholes and exceptions worth TENS OF BILLIONS of dollars. It's estimated that there are at least $50bn in taxes uncollected due to shuttling profits to offshore holding companies. I think the "economic stimulus package" Bush proposed gave almost that much away to a few big companies like IBM. It is also quite common for companies like Pepsi(!) to use "restructuring" to avoid paying any income tax. It would be cheaper to pay all of our Sentators and Congresspeople a million dollars a year and give a million dollar government sponsored budget to every candidate with more than 25% poll numbers in every race for each seat than to keep the current system of influence peddling. Hell, if you paid people that much, you could even forbid them from working after they retire and avoid the corporate board/Presidential cabinet recycling loop that is an even bigger bribery scam than campaign contributions. I hope the mainstream press picks this up (Score:3, Informative) Hopefully this will get picked up by the AP or something. I mean this alone in most people should arouse serious feelings of mistrust for any company. Microsoft makes software. It shouldn't even be making *any* sorts of political contributions or anything. I seriously doubt that within three weeks the attorney general had suddenly decided MS wasn't violating any laws without persuasion If, at the very least, this and the enron scandal should be a wake up call for americans to consider political party financial reform. Re:I hope the mainstream press picks this up (Score:2, Interesting) What was Condon's track record before? If Condon expected (as I imagine) to be softer on monopolies, then of course Microsoft would support him and then he would act his conscience and support the comprimise. What about other people who received contributions? Did they behave differently than expected once they received the contribution? Most "buying" of politicians is buying of elections (not all, however). If the public would vote properly, I would argue, this would not be a problem. Unfortunately, advertising works, especially against news outlets. This just in....Microsoft spent MONEY!!! (Score:4, Interesting) Yeah, it's underhanded, maybe even a bit immoral, the problem is, *IT'S NOT ILLEGAL*!! Both sides are throwing money at this, unsurprisingly MS is throwing more. First off, it would be a violation of their fiduciary responsiblities if they didn't defend themselves as vigrorously as possible. Heck, they've already crossed the line of good taste/credibility in their PR and lobying campaigns in the past, why stop now? If we really want to do something about activities like this we need to correct the current political system. Now, I'll just remain in the legions who complain about it and don't have a good solution (the problem is WAY beyond my meager geek abilities to grok). The one item of interest I have heard is that the current proposed reforms may have allowed people to donate MORE money instead of less. We vote with our pocketbooks, Microsoft votes with its. They just happen to have a slightly bigger one. Finally, it's ironic that the concept of "free" speech is used to defend monetary contributions... Re:This just in....Microsoft spent MONEY!!! (Score:2) Re:This just in....Microsoft spent MONEY!!! (Score:4, Interesting) While it is not illegal, it is the reason for the Turney Act. If it can be shown they were using their money to influence the outcome of the penalty phase of the trial, the judge must consider it before accepting the agreement. In fact, it would be a reason to force the government to go back and renegotiate, or if the judge considered any outcome between the parties tainted, she could enforce her own. Based on past statements from her, I question if this formality has any influence at all. But, I want to give her the benefit of the doubt. It is not a perfect system, but it is a second check of the process. [IANAL--YMMV] Accountability (Score:2, Redundant) You think the US government would decline contributions from any and all companies who have had their questionable business behaviour legally challenged. Kinda makes sense, no? A lot like convicts being unable to cast a vote. Re:Accountability (Score:5, Informative) In this case, Microsoft had been challenged, but not yet convicted. Ever hear of a little concept known as "Innocent until PROVEN guilty"? Were this not the case, simply waging unfounded allegations against any person or company could (and likely would) impact that entity strongly for the worse. Um, no, in the antitrust suit, Microsoft has been found guilty and that ruling has been upheld on appeal already. It is just the forms of remedy, the corporate equivalent of sentencing the convicted criminal, that is of question now. Re:Accountability (Score:4, Interesting) I was not suggesting that Microsoft's campaign funding and lobbying to this date has been illegal; in fact, it's quite legal but increasingly repugnant to the citizenry who wants fair elections in the future. However, if a convict cannot vote, perhaps it is time to say that a convicted monopolist corporation cannot contribute money for some term. For whatever reason, a corporation is in all senses an individual in our law. The punishments for breaking corporate laws should be such that they restrict the otherwise granted rights. No free speech campaigning, no lobbying, no tax break incentives in new properties, no sealed oem contracts, pick an appropriate level of restrictions for the conviction. What did Enron's money get them? (Score:2) Some people would consider giving large amounts of money to people with the potential power to ameliorate your legal troubles bribery -- luckily for Microsoft no-one considers this to be the case here. A sad statement on the American political system, as far as I'm concerned. An experiment (Score:2) *Simply Shocked* (Score:4, Funny) right Of course you realise, this is the Microsoft philosophy applied to the legal field. Microsoft has had a history of buying up tecnologies and expertise, many of which have simply disappeared, never to see the light of day again. It is perhaps the only real innovation that I know of, to take their billions and buy up anything their legal opponents could use to convict them of their crimes. I am sure other big companies are taking notes. This convicts them even more in my mind. Like I have said before, every time I turn around there is something else that comes out and dirties their reputation in my eyes. Heck, if PR LapDogs like ZDNet are taking shots at MS, you know rats are starting to leave the ship. Re:*Simply Shocked* (Score:2) Legal DoS? (Score:2) "You have to watch the violence Lisa.. Else you'll never become desensitized to it" -- Bart Re:Legal DoS? (Score:2) 1. Sign the band to a long term, exclusive contract. 2. Take away all their rights to publish, record, and tour, without the label's explicit approval. 3. Find a new band to screw over. This is totally common. The industry refers to it as "building a stable of artists". I'm sure it happens in lots of other places, too. Legal context (Score:2) Say I have a legal issue with someone.. I 'retain' the best lawyer in town.. Now, my legal adversary can't use that lawyer because it would be a conflict of interest for the lawyer to take up that commission.. But I'm not actually using the lawyer.. I'm paying a lower fee, to 'retain' him, to have him available if I want.. It's really rather brilliant. Balls the size of Washington (Score:3) Now that's ballsy! Re:Balls the size of Washington (Score:2, Funny) Wasted money... (Score:3, Insightful) What a waste of resources. The United States Government (Score:5, Insightful) The real problem here is the idea of "corporate personhood" which extends all the civil rights meant for people (including buying congressmen, senators, presidents and supreme court justices) to corporations. individual people, and and not-for-profit groups can not compete with the cash generated by a large corporation. there is one easy solution to this (unfortunately, it's not easy:). make all elections 100% publicly funded (I believe that england does this and each candidate can only spend something like 10,000 pounds), ban any political advertizing by any non candidate which mentions, depicts or hints where a particlar candidate or party stands on an issue. Re:The United States Government (Score:2, Interesting) Behind every rich corporation is a bunch of rich people with a shared income source and each other's cell phone numbers. Making these people do things as coordinated individuals instead of a corporation will change nothing. make all elections 100% publicly funded (I believe that england does this and each candidate can only spend something like 10,000 pounds), ban any political advertizing by any non candidate which mentions, depicts or hints where a particlar candidate or party stands on an issue. So, force people to vote by how tall the politician is or how easy to remember his name is? Paid issue advertising is a good thing, it lets people know what a politician's history/position on an issue is, because the conventional media sure isn't any help there... -- Benjamin Coates Re:The United States Government, now with XP (Score:2) And you thought the posters at the post office were just advertisement. Re:The United States Government (Score:4, Insightful) Whoo-hoo! Vindication! Proof! If you read the article, it ends making my point: . " So the CORPORATION of M$ which is actually Gates, gives its money and holds positions counter to the vast majority of its own employees. A corporation cannot have rights, only INDIVIDUALS have rights. This corporation, like virtually all such monsters, does NOT hold legitimate points of view, it only presents the point of view of the CEO/President, or (some) board members while the majority of what makes up the corporation is ignored. Mantra: Only individuals have rights, not corporations. Corporations are NOT people. this is very common (Score:2) Re:this is very common (Score:3, Insightful) Corporations (Score:4, Insightful) The problem is that when a politician is elected due to large campaign contributions, he can't help but think that the contributions put him there rather than the votes of the citizens. He is elected, supposedly, to represent the needs of the citizens, but instead he ends up feeling like he is elected to represent the needs of his financiers (even an individual with good moral fiber will have this difficulty). A politician "should" be concerned first and foremost about how each decision will impact a private citizen. For example, how will DMCA impact the average consumer (loss of their fair use rights), how will extension of copyright laws affect the average individual (they will have access to no new public domain material in their lifetime), etc. It is getting to the point that the individuals need to hire lobbyists to plead their case with the politicians. Except that the politician was hired in the first place to be our lobbyist. Campain reform, not Campain finance reform... (Score:5, Interesting) Consider first why candidates need the huge amounts of money to be elected. They in effect need to run two entirely different campains - once for the primary, and once for the election. As a result, the cost more than doubles. Now, the thought is that once they've won the primary, their party will contribute to the main election. This is true but irrelevant to this discussion: the party must raise the money, and thus the need for money still is doubled. Now, I assert that anytime there is a demand, there will be a supply. Consider the origins of soft money - in the old days you could directly support your candidate with any amount of cash you wished. This was deemed a bad thing and so limits were placed on direct contributions. Bang - you now have created "soft money" that doesn't get covered under the hard money laws. Do you really expect that as long as candidates need money they won't find a way around soft money? And realize this: if you put up a piece on your personal web page about how you feel candidate X is [good|bad], that can be considered a "soft" contribution. Do you really want to give the government that power? Now, consider the 2000 elections. They were very close - so close that the actual vote difference between the candidates was lost in the noise floor. Was this really because the people were split 50/50 in liking Bush and Gore? Most people who voted for [Bush|Gore] did so because they disliked [Bush|Gore] marginally less than they disliked [Gore|Bush]. I assert that we need to make the following two changes to the system: 1) Allow anybody registered to vote to vote in any primary. 2) Require a binding "none of the above" entry on all elections. Let's examine the results these two changes would have had on the 2000 US presidential election: 1) By allowing anybody registered to vote in any primary, we would de-emphasize the importance of the primaries and pull the results of the primaries back from the extremes. I doubt that Bush would have won the Republican primary, and I doubt that Gore would have won the Democrat primary. Additionally, candidates such as McCain would have had a much better chance of getting support. 2) By having a binding "none of the above", even if the election had been Bush/Gore, the bulk of people could have voted None Of the Above. Had None Of the Above won, then NOBODY in that election could hold the office, and there would have to be a new election. Ask yourself this: no matter your political affiliation, if you could have had a chance to block both Bush and Gore in favor of a shot at a better candidate, would you? I assert that with these two changes, the following things would happen: 1) The third party candidates wouldn't run in the first race. Instead, they would encourage the voters to vote NOTA in the first race and knock the big boys out. 2) The big parties would no longer be able to take this "This is our guy, take it or leave it" attitude. Thus, they would tend to field more moderate candidates. 3) Because of 1 and 2, more people would feel their vote mattered, and we would get more turnout. 4) Because the primaries could no longer be used to limit our choices, they would become unimportant and would fad away. Remember - the primaries are entirely outside the election process as described in the Constitution. Now, I don't assert that these changes would prevent lobbying by corporations. However, if a party knew that they could no longer annoint a golden child in the primaries and force them down our throats, they might be more aware of how the PEOPLE feel about an issue, rather than MONEY. Discussion? Re:Campain reform, not Campain finance reform... (Score:2) Re:Campain reform, not Campain finance reform... (Score:2) Microsoft... a big disappointment (Score:2, Interesting) Instead of creating quality software that people would use because it is the most secure, efficient and capable software... they choose to write utter crap... and they hire marketers to tell us it's gold... hire political lobbiests to force policies and judicial decisions in their favor. When I started out in computing 26 years ago I never conceived that we would be as backwards as we are today. I never dreamed we would require a 1 gigahertz machine to run a windowing system poorly.... I never thought that instead of booting faster... that machines would boot slower and slower. Extremely disappointing that a marketing/political interest group has been allowed to pretty much destroy the computer industry. I guess we can hope and pray that MicroSoft goes the way of Enron... that it's dirty dealings are opened up to the world and that the world responds by simply refusing to have anything to do with the MicroSluts. Re:Microsoft... a big disappointment (Score:3, Interesting) 26 years in computing, you must be pretty old yet you don't seem to know that every big company gives huge contributions in order to avoid lawsuits. How did MS destroy the computer industry? They created it. Re:Microsoft... a big disappointment (Score:2) This is a common myth. MS has contributed almost nothing to the computing industry, certainly much less that the damage it has done by stiffling innovation and creativity by giving jobs to literally tens of thousands of shit programmers who would be unemployable in an industry where quality control existed. Flood the market with garbage and you end up with a garbage market. I don't know of a single thing MS has produced that didn't either suck (Windows, Outlook etc) or come from another company that they bought and released before making later versions suck (Flight Sim, Word etc.). I've been programming for 26 years and MS has done nothing except make life harder for people who want to produce quaility, working software that does its job by showing that such an attitude is unimportant in the face of marketing blitzes for crap products that don't work. The computing industry of 25 years ago was doing just fine without MS. Sure, IBM had a big grip on the business end of things but that was comming to an end as people like Lotus started up. IBM and Apple then helped MS by various insane business decisions and the rest is history. TWW Re:Microsoft... a big disappointment (Score:2) Stealing ideas? Are you still at school? every company does that, from television shows to cars. Besides, I thought that the GPL philosophy was all about not reinventing the wheel, using other peoples ideas and improving upon them. Look at Mandrake, they took a good Linux distribution and made it even better. Re:Microsoft... a big disappointment (Score:2) "Sure computers did exist, but Bill Gates brought them to the people." Really ? You think nobody would be using computers if Microsoft hadn't existed ? How do you figure that one out ? "Stealing ideas? Are you still at school? every company does that, from television shows to cars." Some companies *gasp* actually *invent new things*. Yes I know the concept is strange, but believe me, it does happen occasionally... "Besides, I thought that the GPL philosophy was all about not reinventing the wheel, using other peoples ideas and improving upon them. Look at Mandrake, they took a good Linux distribution and made it even better." Very true; however there is a difference between stealing something and using something which is given freely. If you don't believe me, just ask a judge. $6M vs $38,000M (Score:4, Interesting) Ralph Nader says this cash pile is distortion of capitalism. Traditionally companies pay out dividends once they have grown into profitibility. The stockholders are being screwed. Re:$6M vs $38,000M (Score:2) Re:$6M vs $38,000M (Score:2) Re:$6M vs $38,000M (Score:2) Despite the fact that Ralph Nader is a git, he has a point here. Unfortunately, companies now manage to stock value, rather than dividend payout. As a result, companies make decisions that can result in them losing money, but still returning value to their investors (by increasing stock price) until the bottom falls out, and the stock drops precipitously. Of course, they only do this because it's what the investors want. Investors want their stock to increase in value, so they can make money selling it, rather than for the stocks to return a cash dividend to them. Part of the reason is taxation laws which tax dividends more heavily than capital gains, and part of the reason is sheer shortsightedness on the part of the investors. Re:$6M vs $38,000M (Score:3, Informative) The reason that MS doesn't pay dividends is because Bill Gates is a major shareholder. If they payed dividends, then Bill will have to pay a HUGE tax bill. The real shocker.... (Score:4, Insightful) Are they afraid or just not that observant? This is definatly newsworthy. The ability to companies to donate money to politicians but shield which politician it is going to to is what is so evil about soft money. At least in the 20s the press could drag a politician through the mud based on his own specific donations. But what would the headline be now? at worst..."Republican party takes donations from Microsoft." Campain money IS NOT SPEECH. It's just the opposite. Re:The real shocker.... (Score:2) Large company lobbies government for favorable reform? This is news? No. Its not news. Its not newsworthy. Its just another day. Campaign money IS SPEECH. Jaded...nothing new really (Score:5, Insightful) As a Canadian, reading the reactions of various slashdotters, I find it very interesting. We as a tech community are so ready to shout that Microsoft is evil. You guys are forgetting that this is the American way (which applies to us up too...). Remember those Railroad Tycoons, the Oil Tycoons? The Rockafellers of the world are still around. Why do you think Texas has so many industries that could have been put elsewhere? (Count how many military bases that there are in Texas?)Prominent Texans ensured that Texas was given the goods, and in our present system of government they did not only what they could, but what was expected and did what benefited Texans and especially those prominant citizens. (Sorry Texans, but its the only example I know of as an ignorant canuck ;) Using money to influence government policy is how government has functioned for a long time. Remember in Ancient Rome, being in position of political power made you rich as businesses petitioned for your support. This is not going to change anytime soon unless we as a society decide that is unacceptable. America is the land of the free. Its the land of who has got more $$$. The more dough you have, the more freedom you have to do as you wish for good or ill. Don't piss on M$ because they are doing what is in their best interests and that they have the freedom to do so. Its disgusting that they did do it, but I am much more revolted that the so called democracy of the world is nothing more than auction and that THIS seems news to people . We have to as a society against this truly undemocratic behaviour. Hopefully this will serve as a case in point for seriously look at our Politicians and their Political Parties and how they govern us. Though I suppose it could be worse... at least we pretend to have democracy. Don't mind me though I am just a jaded youth.... If this is true, I'm worried. (Score:2) Campaign Finance Bill Vote Today Call these reps (Score:2) CAMPAIGN FINANCE REFORM: ACTION ALERT!!! A bandaged Sen. John McCain, R-Ariz., takes part in a Washington news conference to discuss campaign finance reform, Monday, Feb. 11, 2002. Last week, McCain had a cancerous lesion removed from the left side of his nose which was diagnosed as the earliest form of melanoma and was removed. (AP Photo/Stephen J. Boitano) One Last Push: Call Now! Thank you to all those who phoned and faxed Members of Congress over the past week and urged them to support the Shays-Meehan bill. We've heard many reports of offices flooded with calls on the issue, but the fight is not over. Recently, the republican party and its leadership stepped up the effort to fight meaningful reform. If you are a Republican, please make sure and mention that fact when you call or fax the following list of Members. Let them know that this issue is important to you and that the passage of Shays-Meehen is necessary in order to restore integrity to America. Speaker Hastert has declared the campaign finance reform fight "Armageddon" -- and true reform won't come easy. The vote is Wednesday--and we need to keep the pressure on. Below, we have included a list of Members of Congress that we are asking you to call or fax. Please let these members of Congress know that they must vote for Shays-Meehan. In addition, let them know to vote against the poison pill amendments and the sham Ney Bill. Please call or fax the following list of Representatives: Rep. Spencer Bachus (R-AL-6) (202) 225-4921 - (202) 225-2082 fax Rep. Elton Gallegy (R-CA-23) (202) 225-5811 - (202) 225-1100 fax Rep. Doug Ose (R- CA-3) (202) 225-5716 - (202) 226-1298 fax Rep. Michael Collins (R -GA-3) (202) 225-5901 - (202) 225-2515 fax Rep. Nathan Deal (R-GA-9) (202) 225-5211 - (202) 225-8272 fax Rep. John Shimkus (R-IL-20) (202) 225-5271 - (202) 225-5880 fax Rep. Kenny Hulshof (R -MO-9) (202) 225-2956 - (202) 226-0326 fax Rep. Nick Smith (R-MI-7) (202) 225-6276 - (202) 225-6281 fax Rep. Mark Kennedy (R-MN-2) (202) 225-2331 - (202) 225-6475 fax Rep. Frank LoBiondo (R-NJ-2) 202) 225-6572 - (202)225-3318 fax Rep. Rodney Frelinghuysen (R-NJ-11) (202) 225-5034 - (202) 225-3186 fax Rep. Jim Saxton (R-NJ-3) (202) 225-4765 - (202) 225-0778 fax Rep. Mike Ferguson (R-NJ-7) (202) 225-5361 - (202) 225-9460 fax Rep. John McHugh (R-NY-24) (202)225-4611 - (202)226-0621 fax Rep. Sue Kelly (R-NY-19) (202) 225-5441 - (202) 225-3289 fax Rep. Paul Gillmor (R-OH-5) (202) 225-6405 - (202)225-1985 fax Rep. Ralph Regula (R-OH-16) (202) 225-3876 - (202)225-3059 fax Rep. Steven LaTourette (R-OH-19) (202) 225-5731 - (202) 225-3307 fax Rep. Melissa Hart (R-PA-4) (202) 225-2565 - (202) 226-2274 fax Rep. Curt Weldon (R-PA-7) (202) 225-2011 - (202) 225-8137 fax Rep. John Duncan (R-TN-2) (202) 225-5435 - (202)225-6440 fax Rep. Shelly Moore Capito (R-WV-2) (202) 225-2711 - (202) 225-7856 fax Please also call your Representative at 1-800-660-8244, even if you did so last week. Urge them to support Shays-Meehan and oppose the sham Ney bill and poison pill amendments. The House of Representatives uses an e-mail system called "Write Your Rep". You can send e-mails only to your Representative by entering your zip code into the e-mail form - Will you also send this alert to a friend - or two or five - and ask them to do the same? Let's win true reform THIS WEEK. Thank you for your continued support. 1st amendment considerations (Score:2) Here's the deal. If I pay for an advert in support of electing Jimmy Schlessenbaum, that money is counted as a soft money donation to Mr Schlessenbaum. If I give him the money for the ad, and his campaign pays for it, that's a hard contribution and it gets handled under the existing rules and limitations. This is the problem. I have a right to express my opinion of who to vote for. If we start saying that there are limits on soft money contributions, then we're volunteering for legalized limits of individuals to express their opinions. For a better description of this, see This article [prospect.org]. I don't like the fact that corporations can buy elections. But I'd rather have an undamaged 1st amendment, than limits on soft contributions. new monopoly (Score:2) Re:fp (Score:4, Insightful) Parties should be limited as to how much they can spend during a campaign (as they are in Europe) and should maybe even be paid for through taxation- it would cost less thant 1% of the military budget and is a far bettter way of safeguarding democracy. Re:fp (Score:2) Cooperating politicians in a democracy win over the voters every time. And they've realized that. Re:fp (Score:2) We can complain all we want about bought politicians, but we cant change those rules, and the existing power structures appear unlikely to want to change it... And, of course, I do feel that they 'represent' me. I'm included in the demographically researched groups they target for advertising. Well, except, of course, the targetted advertising isnt exactly true, it's just what they say to get elected, so again they arent representing the voters. That, of course, means there isnt any real point to standing under the current system. You'll have to research the demographics yourself, and end up saying almost exactly the same things to get elected, after which you might as well just take cash, since you wont believe in the things you had to say to get elected anyway. Re:fp (Score:2) The MPAA/RIAA and the tobbaco industry has done this for years. They just fly in judges in first class jets to Hollywood with 5 star dinning experiences every night all in the name of educating the judge. The judge in Newy Ork who ruled agaisn't Jon Johnson did this. This kid went to prison, all paid for in the name of education via $$$. ITs sick but pefectly legal and impossible to make it illegal. Isn't this just like ... (Score:5, Insightful) ... charges that Microsoft buys (bought?) shelf space in stores to prevent competing products from even being visible? So, in other words, this is really nothing new. This is Microsoft being Microsoft; now, does anyone seriously doubt that this is an organization bent on doing whatever it takes, including things that are not just immoral, or violate common sense, but possibly things that are criminal, in order to ... what, make money? Has American society fallen so far into the pit of jade and cynicism that we shrug off the Enrons and Microsofts of the world as merely maladjusted money-seeking sycophants, instead of being so violently outraged that we take every chance to make them wish they'd never even started a business? What the hell are we doing? Every person who reads about Microsoft's behavior should be so sickened that they vomit. This is not normal. This is not acceptable. This is not "business as usual" in the United States. Just because it seems to happen a lot does not make it something we should tolerate, not even for a millisecond, and not for any reason. Re:Finally... (Score:3) It's not that few other companies can, it is that few other companies need to. How about somebody looks at what the tobacco industry spends on lobbying efforts? How about the RIAA and MPAA? Microsoft is NOT doing anything illegal when it spends money on political contributions. It is the politicians that are doing something illegal if they let that money sway their votes. Re:Finally... (Score:2) Illegal like what? The contributions and lobbying, while of dubious morality, are still legal. Any numbers available for Sun's lobbying and contributions? Re:Finally... (Score:2, Insightful) Was Sun contributing money while they were involved in legal action regarding their business practices? The Microsoft situation is less a matter of corporate political contributions than it is a matter of historic antitrust precedent. That M$'s behavior was not technically illegal brings to mind the Nuremburg legal defense that a war of genocidal agression was not illegal. Indeed, at the moment, it is not illegal to employ monopolistic activities on a scale without comparison in human history to turn the entire information industry into an oligarchy. As for myself, I find very little comfort in witholding my outrage based on this technicality. Re:Finally... (Score:3, Insightful) As a publicly traded company, they have a fiduciary responsibility to their shareholders. If they spend money away like this and don't expect a return, they are not living up to that responsibility. On the other hand, if they're spending the money and they DO expect something back, then these are bribes. Either way, I don't see how a publicly held corporation can spend any of its money on political activities. Re:Why isn't this mentioned on The Today Show? (Score:2, Interesting) MS-NBC [msnbc.com] -rp Re:Ban contributions? (Score:2) Uhhm, and how is it different from the current situations? Oh yeah, I get it! They are not technicaly bribes: they are called "contributions". Re:Could this be real? (Score:2) Absolutely not (Score:2) Microsoft has not debt to speak of and $38 billion in cash. You'd make a terrible investor or stock broker if you cant tell the difference. Re:SlashDot Users Paid By Microsoft? (Score:2) Oh wait.... we can tell just by counting the pro-microsoft comments in this thread!! Not necessarily! If I were a paid Microsoft Troll, why would I blindly spout pro-Microsoft rhetoric when I could be much more effective by quietly offering little tidbits of wisdom that cast doubt among the /. horde?.. This wisdom could be offered in the form of pro-BSD comments (MS likes BSD) or even as psuedo-reverse psychology type comments (i.e. "MS sucks, because they have huge security holes in tehir code like *this*".. Which prompts half a dozen folks to either mention that Linux has the same hole, or that MS fixed that problem 6 months ago).. The point is that if MS were hiring individuals to sway the /. crowd, you can bet your arse that they wouldn't be hiring script kiddies! Re:Malformed figures (Score:2) "...total donations to political donations from Microsoft and its employees to political parties, candidates and PACs in the 2000 election cycle amounted to more than $6.1 million. During this period, Microsoft and its executives accounted for $2.3 million in soft money contributions..." I'll agree that they don't fully explain how they arrive at the 6 million figure. None of the numbers provided add up, as the article lacks a thorough breakdown. Articles like this infuriate me because you never get the real story. Even after 300 words, all you have is an inflammatory headline (regardless of which "side" you're on), a bunch of numbers associated with a hot topic like money and politics, and not much else. As for the actual concept of buying political favours; I think we're all adult enough to realize this is nothing new. All this does is confirm to us that MS does it too, just as we suspected. and the Mass Misinformation Machine rolls on...
http://slashdot.org/story/02/02/13/140248/details-of-msfts-antitrust-lobbying
CC-MAIN-2014-35
refinedweb
10,030
64
: using System; using System.Net.Sockets; using System.Net; namespace UdpTest { class Program { static void OnUdpData(IAsyncResult result) { // this is what had been passed into BeginReceive as the second parameter: UdpClient socket = result.AsyncState as UdpClient; // points towards whoever had sent the message: IPEndPoint source = new IPEndPoint(0, 0); // get the actual message and fill out the source: byte[] message = socket.EndReceive(result, ref source); // do what you'd like with `message` here: Console.WriteLine("Got " + message.Length + " bytes from " + source); // schedule the next receive operation once reading is done: socket.BeginReceive(new AsyncCallback(OnUdpData), socket); } static void Main(string[] args) { UdpClient socket = new UdpClient(5394); // `new UdpClient()` to auto-pick port // schedule the first receive operation: socket.BeginReceive(new AsyncCallback(OnUdpData), socket); // sending data (for the sake of simplicity, back to ourselves): IPEndPoint target = new IPEndPoint(IPAddress.Parse("127.0.0.1"), 5394); // send a couple of sample messages: for (int num = 1; num <= 3; num++) { byte[] message = new byte[num]; socket.Send(message, message.Length, target); } Console.ReadKey(); } } } Using this approach I was able to create a networking system in Unity that works both for P2P connections between game' instances and connecting to external servers. Additional notes: - Sending in this example is synchronous, but has little to no effect (writing to a socket doesn't take long, moreso given the UDP datagram size limits). - AsyncResult.AsyncState can be any kind of object. In this example I'm using it to easily retrieve the socket that has received the data. For more complex systems, it can be a good idea to make a "context" class, which would contain the socket (UdpClient) and any other values that you may need. - Due to the current threading restrictions in Unity, you may not be able to access engine-related (unityengine.*) functionality from threads. To workaround this, push received messages into a list somewhere, and then handle them in the Update method of a MonoBehaviour. Have fun! Hi ! Thanks for the code sample. About handling received data into a queue and dequeue it in some Update function, do you think that the best way is to treat a packet per frame or to process all the new packets at the next frame ? Hello, you would usually process all available packets at the start of game frame to minimize latency. Occasionally games allow queuing up and distributing events (rather than packets themselves) to avoid everything happening at once after a lag spike, but this is not something you do with UDP, as the packets do not generally “buffer” like on TCP. You know, for the last few hours I felt like I’ve been banging my head against the wall trying to get my client and server talking via UDP. Your solution is so much easier than what I was working with! I had a Python client which was polling my game for the latest data, so the game was actually acting as the server in this case. Using your solution has worked a treat, so many thanks for sharing :)
https://yal.cc/cs-dotnet-asynchronous-udp-example/
CC-MAIN-2019-13
refinedweb
506
53.21
-- | Some useful monadic combinators missing from the standard libraries module Monad.Util where import Control.Monad(ap,when) infixl 1 #,#!,<# -- | Apply a pure function to the result of a monadic computation f # x = fmap f x -- | Apply a function returned by a monadic computation to an argument returned -- by a monadic computation f <# x = ap f x -- | Perform two monadic computation and return the result from the second one x #! y = const # x <# y -- It is a scandal that monadic composition isn't defined in the libraries... infixr 1 @@ -- | Kleiski composition (m1 @@ m2) i = m1 =<< m2 i -- | Infinite loops loop m = l where l = m>>l -- | While loops whileM cndM bodyM = loop where loop = do more <- cndM when more (bodyM >> loop) -- | Repeat m while it returns True repeatM m = whileM m (return ()) done :: Monad m => m () done = return ()
http://hackage.haskell.org/package/network-house-0.1.0.0/docs/src/Monad-Util.html
CC-MAIN-2015-32
refinedweb
138
57.61
Download presentation Presentation is loading. Please wait. 1 Grid Computing, B. Wilkinson, 20043a.1 WEB SERVICES Introduction 2 Grid Computing, B. Wilkinson, 20043a.2 Web Services Software components designed to provide specific operations (“services”) accessible using standard Internet technology. For machine interaction over a network. Usually through SOAP (simple Object Access Protocol) messages carrying XML documents, and a HTTP transport protocol. 3 Grid Computing, B. Wilkinson, 20043a.3 Basic client-server model 4 Grid Computing, B. Wilkinson, 20043a.4 Client needs to: –Identify location of the required service –Know how to communicate with the service to get it to provide the actions required. Uses service registry - a third party. 5 Grid Computing, B. Wilkinson, 20043a.5 Service-Oriented Architecture Steps: Services “published” in a Service registry. Service requestor asks Service Registry to locate service. Service requestor “binds” with service provider to invoke service. 6 Grid Computing, B. Wilkinson, 20043a.6 2. Find 3. Bind 1. Publish Service-Oriented Architecture Service requester Service registry Service provider 7 Grid Computing, B. Wilkinson, 20043a.7 Key aspects Has similarities with RMI and other distributed object technologies (CORBA etc.) but:: Web Services are platform independent – They use XML within a SOAP message). – Most use HTTP to transmit message. 8 Grid Computing, B. Wilkinson, 20043a.8 XML-based Web Services XML provides a flexible basis for storing and retrieving service information on web services. Web services use data-centric XML documents to communicate information. 9 Grid Computing, B. Wilkinson, 20043a.9 Web Services “Stack” HTTP transport SOAP message carrying XML documents WSDL (Web Services Description Language used to describe message syntax for invoking a service and its response. UDDI (Universal Description, Discovery and Integration) used as web service discovery mechanism. 10 Grid Computing, B. Wilkinson, 20043a.10 Web Services “Stack” + XML 11 Grid Computing, B. Wilkinson, 20043a.11 Web Services From 1 23 4 5 6 12 Grid Computing, B. Wilkinson, 20043a.12 Simple Object Access Protocol (SOAP) A communication protocol for passing XML documents. Provides mechanisms for: –Defining communication unit - a SOAP message –Error handling –Extensions –Data representation –Remote Procedure Calls (RPC’s) –Document-centric approach for business transactions –Binding to HTTP 13 Grid Computing, B. Wilkinson, 20043a.13 SOAP Envelope <SOAP-ENV:Envelope xmlns=“”>... namespace, see later 14 Grid Computing, B. Wilkinson, 20043a.14 What goes down the Wire HTTP packet containing: –Stuff about context, transactions, routing, reliability, security –SOAP message –Attachments XML/SOAP standardization body, World Wide Web Consortium (W3C) covers SOAP and attachments. 15 Grid Computing, B. Wilkinson, 20043a.15 Structure of an XML document Optional Prolog Root Element 16 Grid Computing, B. Wilkinson, 20043a.16 Prolog Includes processing instruction ( ) to specify how to process document.. Includes meta-information about document, and comments. 17 Grid Computing, B. Wilkinson, 20043a.17 One PI identifies document as a XML document, e.g. Comments, same form as HTML: 18 Grid Computing, B. Wilkinson, 20043a.18 Root element Root element contains contents of document. Other elements are within root element and can be nested. 19 Grid Computing, B. Wilkinson, 20043a.19 XML Tags Not predefined as in HTML. Must define your own tags using names as names in a programming languages As in programming languages, restrictions. Case sensitive. Start with a letter. “Elements” have start and end tags. Start tags can have attributes as in HTML. 20 Grid Computing, B. Wilkinson, 20043a.20 Namespace Mechanism If XML documents combined, can be problem if different documents use the same tag names to mean different things. With namespace mechanism, tags given additional namespace identifier to qualify it. 21 Grid Computing, B. Wilkinson, 20043a.21 Qualifying names Qualified name given by namespace identifier and name used in document: Qualified name = namespace identifier + local name 22 Grid Computing, B. Wilkinson, 20043a.22 Namespace identifier Uses URI’s (Uniform Resource Identifiers) - web naming mechanism. URLs are a subset of URI, and would typically be used, e.g.: 23 Grid Computing, B. Wilkinson, 20043a.23 URIs also include email addresses, i.e. mailto:abw@email.wcu.edu and Uniform Resource Names (URNs) which are globally unique and persistent. UDDI uses URNs. 24 Grid Computing, B. Wilkinson, 20043a.24 Associating namespace identifier with local name Names in document given a prefix, i.e.: Namespace identifier associated with prefix in root element:: xmlns:po=“” 25 Grid Computing, B. Wilkinson, 20043a.25 Namespace Example Computer, Pentium IV, 2.8 Ghz, 4 Gbytes main memory prefix 26 Grid Computing, B. Wilkinson, 20043a.26 Can apply namespace to every tag without a prefix automatically if that is required: Computer, Pentium IV, 2.8 Ghz, 4 Gbytes main memory 27 Grid Computing, B. Wilkinson, 20043a.27 Defining Legal XML Tags Legal tags in a document defined optionally using either: –Document type definitions (DTD) within document. (old, not allowed with SOAP). or –XML schema 28 Grid Computing, B. Wilkinson, 20043a.28 XML Schema Flexible way of handing legal element names. Expressed in XML. Schema is an XML document with required definitions. Handles namespaces. Has notation of data types 29 Grid Computing, B. Wilkinson, 20043a.29 XML schema Document xsi:schemaLocation=“.. “ 30 Grid Computing, B. Wilkinson, 20043a.30 XML Schema Structure Example <xsd:schema xmlns=“” xmlns:xsd=“” targetNamespace=”> Purchase order schema for SkatesTown.. From: “Building Web Services with Java, making sense of XML, SOAP, WSDL, and UDDI, 2nd ed” by S. Graham et al, SAMS publishing, 2004, p 54. 31 Grid Computing, B. Wilkinson, 20043a.31 Associating schema to document Example <po:po xmlns:po=“” xmlns:xsi=“” xsi:schemaLocation=“” id=“43871” submitted=“2001-10-05”>. From: “Building Web Services with Java, making sense of XML, SOAP, WSDL, and UDDI, 2nd ed” by S. Graham et al, SAMS publishing, 2004, p 54. 32 Grid Computing, B. Wilkinson, 20043a.32 Additional XML materials On-line materials W3C consortium home page: W3Schools XML Tutorial : 33 Grid Computing, B. Wilkinson, 20043a.33 Books Several books on XML, e.g.: “Building Web Services with Java: Making sense of XML, SOAP, WSDL, and UDDI, 2nd edition” by S. Graham et al, SAMS publishing, 2004 Very good but 792 pages!! 34 Grid Computing, B. Wilkinson, 20043a.34 Additional SOAP materials See: 35 Grid Computing, B. Wilkinson, 20043a.35 Hosting Environments for Web Services Microsoft.NET IBM Websphere Apache Axis - we will be using this for assignment 1 36 Grid Computing, B. Wilkinson, 20043a.36 More information on Axis Similar presentations © 2020 SlidePlayer.com Inc.
http://slideplayer.com/slide/5023515/
CC-MAIN-2020-50
refinedweb
1,058
52.15
Index, reads: sleep command, 2-96 Should read: sleep command, 2-95 for more information. (colophon) the author bio and the book info are both new: About the Author Daniel Gilly has been with O'Reilly & Associates since 1986. In addition to co-authoring The X Window System in a Nutshell, Daniel has had an editorial hand in several books in the X Window series, wrote the reference section of Volume Six, Motif Programming Manual, and revised the Nutshell Handbook, Learning vi, for its fifth edition. For the past two years, Daniel has been the editor of the newsletter for MIT Crew. He has also written a musical comedy, a radio thriller, and a one-act play, all of which were performed at Boston-area colleges. He graduated from MIT in 1985 with a B.S. in Mechanical Engineering. Having lived in the Boston area for ten years, Daniel moved to Silicon Valley in June 1992. Colophon The animal featured on the cover of Unix in a Nutshell Michael Kalantarian. Whenever possible, our books use a durable and flexible lay-flat binding. If the page count exceeds the lay-flat binding's limit, perfect binding is used. should be "Bundling allows you to select only the components..." The last line of code under "Examples" reads: tar cvf -'find . -print' > backup.tar Should read: tar cvf backup.tar are as follows:" and moved the exit codes from under -s to after the changed para. inputs is a directory, use the -r option." "-r" is in bold. "metacharacters" searched." separated with c (default is any white space)." where c is in italics. files of equal length." where "infile" is in itals. files, each n lines long (default is 1000)." where "infile" and "n" are in italics. (2-100 to 2-102): changed occurrences of "CR" and "NL" to "carriage return" and "newline", respectively. Also, for the first use on each page, specified keyboard equiv., i.e. "carriage return (^M)" and "newline (^J)". This made p. 100 and 101 break differently, but 102 stayed the same. reads: "Conditions are usually specified with the test or [[ ]] command." The sentences that read: "In the Korn shell, s2 can be a regular expression." now read: "In the Korn shell, s2 can be a filename metacharacter." The example at the bottom of the page read: % echo "Well, isn't that "special"?" It now reads %" Well, isn't that """special?"" The third line on the page read: echo "The value of $x is $x" It now reads: echo "The value of" $x "is $x" 'Store pattern for later replay' action, there is now a dot. changed the 1st code bock, the subsequent line, and the 2nd code block to read: function(arg1,arg2) function (arg1 arg2) The following script changes arg2, regardless of whether it appears on the same line as the function name: s/function(arg1,arg2)/function(arg1,XX)/ /function(/{ N s/arg2/XX/ P D } [address]r AEle Read contents of AEle... now reads: [address]r file Read contents of file... [address1][,address2]s/pattern/replacement/[0ags] now reads: [address1][,address2]s/pattern/replacement/[flags] "Some uppercase Greek letters are not supported because they can be specified by an Arabic equivalent (e.g. A for alpha, B for beta)." You're getting your letters and your numbers confused. 1,2,3, etc. are Arabic; A, B, C, etc. are Roman or Latin (opinions vary). "file3" and 1st "text1" to "text3" © 2013, O’Reilly Media, Inc. (707) 827-7019 (800) 889-8969 All trademarks and registered trademarks appearing on oreilly.com are the property of their respective owners.
http://oreilly.com/catalog/errata.csp?isbn=9781565920019
CC-MAIN-2013-20
refinedweb
602
75.61
Forum Index On 2012-11-27 08:22, Gor Gyolchanyan wrote: > Nice idea, especially with the template to make things easier. Still it > looks ugly. Version identifiers and numbers (as well as debug > identifiers and numbers) serve a very good purpose (parametrizing > modules), but they're vastly incomplete. There's so much useful stuff > that could be done if module could have access to data of user defined > types. I think this is very close to the idea of UDAs. If UDAs become > mutable (which I think would be the most important feature of UDAs), > then the module declaration could also get mutable UDAs, which would > solve all problems. Don't you think? And version identifiers can be used > as described in Version.d, except they'll change the module UDAs instead > of defining a manifest constant. Do you have any example of how you would like this to look like? -- /Jacob Carlborg There's a tiny, but extremely useful enhancement request, that resides in bugzilla for a long time now. It proposes the possibility to have modules named "package", in which case they're imported using their package name alone: mylib core.d aux.d package.d // main.d: import mylib.core; import mylib.aux; import mylib; In this case adding UDAs to packages essentially means adding UDAs to the "package" module. And adding UDAs to any modules would look like this: [MyUda] module mylib.core; Since the module-level import statements affect the entire module, the later imports would be enough to make the MyUda type visible at the top. On Tue, Nov 27, 2012 at 11:42 AM, Jacob Carlborg <doob@me.com> wrote: > > -- Bye, Gor Gyolchanyan.
http://forum.dlang.org/thread/mailman.2159.1353670711.5162.digitalmars-d@puremagic.com?page=2
CC-MAIN-2016-44
refinedweb
280
74.59
Set a thread's priority #include <pthread.h> int pthread_setschedprio( pthread_t thread, int prio ); As an extension to POSIX in QNX Neutrino 6.6 or later, you can wrap the new priority in one these macros to specify how to handle out-of-range priority requests: If procnto was started with a -P option ending with s or S, out-of-range priority requests by default saturate at the maximum allowed value. libc Use the -l c option to qcc to link against this library. This library is usually included automatically. The pthread_setschedprio() function sets the priority of thread thread to prio. If the thread is running or runnable, the effect on its position in the ready queue depends on the direction of the modification:.
http://www.qnx.com/developers/docs/7.0.0/com.qnx.doc.neutrino.lib_ref/topic/p/pthread_setschedprio.html
CC-MAIN-2018-09
refinedweb
125
54.32
Writing your first program is easier than writing a paragraph of text! Just a few building blocks suffice to enable us to write programs that can help solve all sorts of fascinating, but otherwise unapproachable, problems. This chapter takes you through these building blocks, gets you started on programming in Java, and studies a variety of interesting programs. OUR GOAL IN THIS CHAPTER IS to convince you that writing a program is easier than writing a piece of text, such as a paragraph or essay. Writing prose is difficult: we spend many years in school to learn how to do it. By contrast, just a few building blocks suffice to enable us to write programs that can help solve all sorts of fascinating, but otherwise unapproachable, problems. In this chapter, we take you through these building blocks, get you started on programming in Java, and study a variety of interesting programs. You will be able to express yourself (by writing programs) within just a few weeks. Like the ability to write prose, the ability to program is a lifetime skill that you can continually refine well into the future. In this book, you will learn the Java programming language. This task will be much easier for you than, for example, learning a foreign language. Indeed, programming languages are characterized by only a few dozen vocabulary words and rules of grammar. Much of the material that we cover in this book could be expressed in the Python or C++ languages, or any of several other modern programming languages. We describe everything specifically in Java so that you can get started creating and running programs right away. On the one hand, we will focus on learning to program, as opposed to learning details about Java. On the other hand, part of the challenge of programming is knowing which details are relevant in a given situation. Java is widely used, so learning to program in this language will enable you to write programs on many computers (your own, for example). Also, learning to program in Java will make it easy for you to learn other languages, including lower-level languages such as C and specialized languages such as Matlab. 1.1 Your First Program IN THIS SECTION, OUR PLAN IS to lead you into the world of Java programming by taking you through the basic steps required to get a simple program running. The Java platform (hereafter abbreviated Java) is a collection of applications, not unlike many of the other applications that you are accustomed to using (such as your word processor, email program, and web browser). As with any application, you need to be sure that Java is properly installed on your computer. It comes preloaded on many computers, or you can download it easily. You also need a text editor and a terminal application. Your first task is to find the instructions for installing such a Java programming environment on your computer by visiting We refer to this site as the booksite. It contains an extensive amount of supplementary information about the material in this book for your reference and use while programming. Programming in Java To introduce you to developing Java programs, we break the process down into three steps. To program in Java, you need to: Create a program by typing it into a file named, say, MyProgram.java. Compile it by typing javac MyProgram.java in a terminal window. Execute (or run) it by typing java MyProgram in the terminal window. In the first step, you start with a blank screen and end with a sequence of typed characters on the screen, just as when you compose an email message or an essay. Programmers use the term code to refer to program text and the term coding to refer to the act of creating and editing the code. In the second step, you use a system application that compiles your program (translates it into a form more suitable for the computer) and puts the result in a file named MyProgram.class. In the third step, you transfer control of the computer from the system to your program (which returns control back to the system when finished). Many systems have several different ways to create, compile, and execute programs. We choose the sequence given here because it is the simplest to describe and use for small programs. Creating a program A Java program is nothing more than a sequence of characters, like a paragraph or a poem, stored in a file with a .java extension. To create one, therefore, you need simply define that sequence of characters, in the same way as you do for email or any other computer application. You can use any text editor for this task, or you can use one of the more sophisticated integrated development environments described on the booksite. Such environments are overkill for the sorts of programs we consider in this book, but they are not difficult to use, have many useful features, and are widely used by professionals. Compiling a program At first, it might seem that Java is designed to be best understood by the computer. To the contrary, the language is designed to be best understood by the programmer—that’s you. The computer’s language is far more primitive than Java. A compiler is an application that translates a program from the Java language to a language more suitable for execution on the computer. The compiler takes a file with a .java extension as input (your program) and produces a file with the same name but with a .class extension (the computer-language version). To use your Java compiler, type in a terminal window the javac command followed by the file name of the program you want to compile. Executing (running) a program Once you compile the program, you can execute (or run) it. This is the exciting part, where your program takes control of your computer (within the constraints of what Java allows). It is perhaps more accurate to say that your computer follows your instructions. It is even more accurate to say that a part of Java known as the Java virtual machine (JVM, for short) directs your computer to follow your instructions. To use the JVM to execute your program, type the java command followed by the program name in a terminal window. Click to view larger image Developing a Java program Program 1.1.1 Hello, World public class HelloWorld { public static void main(String[] args) { // Prints "Hello, World" in the terminal window. System.out.println("Hello, World"); } } This code is a Java program that accomplishes a simple task. It is traditionally a beginner’s first program. The box below shows what happens when you compile and execute the program. The terminal application gives a command prompt (% in this book) and executes the commands that you type (javac and then java in the example below). Our convention is to highlight in boldface the text that you type and display the results in regular face. In this case, the result is that the program prints the message Hello, World in the terminal window. % javac HelloWorld.java % java HelloWorld Hello, World PROGRAM 1.1.1 is an example of a complete Java program. Its name is HelloWorld, which means that its code resides in a file named HelloWorld.java (by convention in Java). The program’s sole action is to print a message to the terminal window. For continuity, we will use some standard Java terms to describe the program, but we will not define them until later in the book: PROGRAM 1.1.1 consists of a single class named HelloWorld that has a single method named main(). (When referring to a method in the text, we use () after the name to distinguish it from other kinds of names.) Until SECTION 2.1, all of our classes will have this same structure. For the time being, you can think of “class” as meaning “program.” The first line of a method specifies its name and other information; the rest is a sequence of statements enclosed in curly braces, with each statement typically followed by a semicolon. For the time being, you can think of “programming” as meaning “specifying a class name and a sequence of statements for its main() method,” with the heart of the program consisting of the sequence of statements in the main() method (its body). PROGRAM 1.1.1 contains two such statements: The first statement is a comment, which serves to document the program. In Java a single-line comment begins with two '/' characters and extends to the end of the line. In this book, we display comments in gray. Java ignores comments—they are present only for human readers of the program. The second statement is a print statement. It calls the method named System.out.println() to print a text message—the one specified between the matching double quotes—to the terminal window. In the next two sections, you will learn about many different kinds of statements that you can use to make programs. For the moment, we will use only comments and print statements, like the ones in HelloWorld. When you type java followed by a class name in your terminal window, the system calls the main() method that you defined in that class, and executes its statements in order, one by one. Thus, typing java HelloWorld causes the system to call the main() method in PROGRAM 1.1.1 and execute its two statements. The first statement is a comment, which Java ignores. The second statement prints the specified message to the terminal window. Click to view larger image Anatomy of a program Since the 1970s, it has been a tradition that a beginning programmer’s first program should print Hello, World. So, you should type the code in PROGRAM 1.1.1 into a file, compile it, and execute it. By doing so, you will be following in the footsteps of countless others who have learned how to program. Also, you will be checking that you have a usable editor and terminal application. At first, accomplishing the task of printing something out in a terminal window might not seem very interesting; upon reflection, however, you will see that one of the most basic functions that we need from a program is its ability to tell us what it is doing. For the time being, all our program code will be just like PROGRAM 1.1.1, except with a different sequence of statements in main(). Thus, you do not need to start with a blank page to write a program. Instead, you can Copy HelloWorld.java into a new file having a new program name of your choice, followed by .java. Replace HelloWorld on the first line with the new program name. Replace the comment and print statements with a different sequence of statements. Your program is characterized by its sequence of statements and its name. Each Java program must reside in a file whose name matches the one after the word class on the first line, and it also must have a .java extension. Errors It is easy to blur the distinctions among editing, compiling, and executing programs. You should keep these processes separate in your mind when you are learning to program, to better understand the effects of the errors that inevitably arise. You can fix or avoid most errors by carefully examining the program as you create it, the same way you fix spelling and grammatical errors when you compose an email message. Some errors, known as compile-time errors, are identified when you compile the program, because they prevent the compiler from doing the translation. Other errors, known as run-time errors, do not show up until you execute the program. In general, errors in programs, also commonly known as bugs, are the bane of a programmer’s existence: the error messages can be confusing or misleading, and the source of the error can be very hard to find. One of the first skills that you will learn is to identify errors; you will also learn to be sufficiently careful when coding, to avoid making many of them in the first place. You can find several examples of errors in the Q&A at the end of this section. Program 1.1.2 Using a command-line argument public class UseArgument { public static void main(String[] args) { System.out.print("Hi, "); System.out.print(args[0]); System.out.println(". How are you?"); } } This program shows the way in which we can control the actions of our programs: by providing an argument on the command line. Doing so allows us to tailor the behavior of our programs. % javac UseArgument.java % java UseArgument Alice Hi, Alice. How are you? % java UseArgument Bob Hi, Bob. How are you? Input and output Typically, we want to provide input to our programs—that is, data that they can process to produce a result. The simplest way to provide input data is illustrated in UseArgument (PROGRAM 1.1.2). Whenever you execute the program UseArgument, it accepts the command-line argument that you type after the program name and prints it back out to the terminal window as part of the message. The result of executing this program depends on what you type after the program name. By executing the program with different command-line arguments, you produce different printed results. We will discuss in more detail the mechanism that we use to pass command-line arguments to our programs later, in SECTION 2.1. For now it is sufficient to understand that args[0] is the first command-line argument that you type after the program name, args[1] is the second, and so forth. Thus, you can use args[0] within your program’s body to represent the first string that you type on the command line when it is executed, as in UseArgument. In addition to the System.out.println() method, UseArgument calls the System.out.print() method. This method is just like System.out.println(), but prints just the specified string (and not a newline character). Again, accomplishing the task of getting a program to print back out what we type in to it may not seem interesting at first, but upon reflection you will realize that another basic function of a program is its ability to respond to basic information from the user to control what the program does. The simple model that UseArgument represents will suffice to allow us to consider Java’s basic programming mechanism and to address all sorts of interesting computational problems. Stepping back, we can see that UseArgument does neither more nor less than implement a function that maps a string of characters (the command-line argument) into another string of characters (the message printed back to the terminal window). When using it, we might think of our Java program as a black box that converts our input string to some output string. A bird's-eye view of a Java program This model is attractive because it is not only simple but also sufficiently general to allow completion, in principle, of any computational task. For example, the Java compiler itself is nothing more than a program that takes one string of characters as input (a .java file) and produces another string of characters as output (the corresponding .class file). Later, you will be able to write programs that accomplish a variety of interesting tasks (though we stop short of programs as complicated as a compiler). For the moment, we will live with various limitations on the size and type of the input and output to our programs; in SECTION 1.5, you will see how to incorporate more sophisticated mechanisms for program input and output. In particular, you will see that we can work with arbitrarily long input and output strings and other types of data such as sound and pictures.
https://www.informit.com/articles/article.aspx?p=2783634&amp;seqNum=3
CC-MAIN-2020-40
refinedweb
2,664
61.46
This section is non-normative. An introduction to marking up a document. Every XML and HTML document in an HTML UA is represented by a Document object. [DOM3. [NameGetter=OverrideBuiltins, ImplementedOn=Document] anchors; readonly attribute HTMLCollection scripts;], it is reported as " 01/01/1970 00:00:00" string " 01/01/1970 00:00:00".". As far as parsing goes, the quirks I know of are: pcan contain table charset[ = value ] Returns the document's character encoding. Can be set, to dynamically change the document's character encoding. New values that are not IANA-registered aliases the getter must return the value that would have been returned by the DOM attribute of the same name on the SVGDocument interface. Otherwise, it must return a concatenation of the data of all the child text nodes of the title element, in tree order, or the empty string if the title element is null.. titleelement is null and the headelement is null, then the attribute must do nothing. Stop the algorithm here. titleelement is null, then a new titleelement must be created and appended to the headelement. titleelement (if any) must all be removed. Textnode whose data is the new value being assigned must be appended to the titleelement. The title attribute on the HTMLDocument interface should shadow the attribute of the same name on the SVGDocument interface when the user agent supports both HTML and anchors attribute must return an HTMLCollection rooted at the Document node, whose filter matches only a elements with name attributes. The scripts attribute must return an HTMLCollection rooted at the Document node, whose filter matches only script elements. getElementsByName(name) Returns a NodeList of a, applet, button, form, frame, frameset, iframe, img, input, map, meta, object, select, and textarea a, applet, button, form, frame, frameset, iframe, img, input, map, meta, object, select, and textarea in the per-element partition element descendants other than param elements, and no text node descendants that are not inter-element whitespace. The dir attribute on the HTMLDocument interface is defined along with the dir content attribute. boolean draggable; attribute DOMString contentEditable; readonly attribute boolean isContentEditable; attribute HTMLMenuElement contextMenu; attribute boolean spellcheck; // styling readonly attribute CSSStyleDeclaration style; //; };): class contenteditable contextmenu dir draggable id hidden lang style spellcheck tabindex title In addition, unless otherwise specified, the following event handler content attributes may be specified on any HTML element: onabort onblur onchange onclick oncontextmenu ondblclick ondrag ondragend ondragenter ondragleave ondragover ondragstart ondrop onerror* onfocus onkeydown onkeypress onkeyup onload* onmousedown onmousemove onmouseout onmouseover onmouseup onmousewheel onscroll onselect onsubmit The attributes marked with an asterisk. specifies the primary language for the element's contents and for any of the element's attributes that contain text. Its value must be a valid RFC 3066 language code, or the empty string. [RFC3066] The xml:lang attribute (that is, the lang attribute with the xml prefix in the namespace) is defined in XML. [XML] If these attributes are omitted from an element, then the language of this element is the same as the language of its parent element, if any. Setting the attribute to the empty string indicates that the primary language is unknown. The lang attribute may be used on any HTML element. The xml:lang attribute may be used on HTML elements in XML documents, as well as elements in other namespaces if the relevant specifications allow it (in particular, MathML and SVG allow xml:lang attributes to be specified on their elements). If both the lang attribute and the xml:lang attribute are specified on the same element, they must have exactly the same value when compared in an ASCII case-insensitive manner. Authors must not use the xml:lang attribute (that is, the lang attribute with the xml prefix in the namespace) in HTML documents. To ease migration to and from XHTML, authors may specify an attribute in no namespace with no prefix and with the localname xml:lang on HTML elements in HTML documents, but such attributes must only be specified if a lang attribute is also specified, and both attributes must have the same value when compared in an ASCII case-insensitive manner. To determine the language of a node, user agents must look at the nearest ancestor element (including the element itself if the node is an element) that has an xml:lang attribute set or is an HTML element and has a lang attribute set. That attribute All elements may have the style content attribute set. If specified, the attribute must contain only a list of zero or more semicolon-separated (;) CSS declarations. [CSS21]> A custom data attribute is an attribute whose name starts with the string " data-", has at least one character after the hyphen, is XML-compatible, has no namespace, headers, footers, and contact information.). Phrasing content is the text of the document, as well as elements that mark up that text at the intra-paragraph level. Runs of phrasing content form paragraphs. nodes that are not inter-element whitespace are phrasing. Dispatching the required click event. Another specification presumably requires the firing of the post-click activation steps on an element, the user agent must fire a simple event called DOMActivate at that element. The default action of this event must be to run final activation steps on that element. If the event is canceled, the user agent must run canceled activation steps on the element instead. in flow content are defined relative to what the document looks like without the a, ins and del elements complicating matters, since those elements, with their hybrid content models, can straddle paragraph boundaries. Generally, having elements straddle paragraph boundaries is best avoided. Maintaining such markup can be difficult. Let view be a view of the DOM that replaces all a, ins and del and del elements.) Conformance checkers may warn authors of cases where they have paragraphs that overlap each other. A paragraph is also formed explicitly by p elements. The p element can be used to wrap individual paragraphs when there would otherwise not be any content other than phrasing content to separate the paragraphs from each other. In the following example, there are two paragraphs in a section. There is also a header,> The following example takes that markup and puts ins and del elements around some of the markup to show that the text was changed (though in this case, the changes admittedly don't make much sense). Notice how this example has exactly the same paragraphs as the previous one, despite the ins and del elements. <section> <ins><h1>Example of paragraphs</h1> This is the <em>first</em> paragraph in</ins> this example<del>. <p>This is the second.</p></del> <!-- This is not a paragraph. --> </section> In the following example, the link spans half of the first paragraph, all of the header separating the two paragraphs, and half of the second paragraph. HTML documents, and for HTML elements in HTML documents, certain APIs defined in DOM3 Core become case-insensitive or case-changing, as sometimes defined in DOM3 Core, and as summarized or required below. [DOM3CORE]. This does not apply to XML documents or to elements that are not in the HTML namespace despite being in HTML documents. Element.tagNameand Node.nodeName These attributes must return element names converted to lowercase. Specifically: when an attribute is set on an HTML element using Element.setAttribute(), the name argument must be converted to lowercase before the element is affected; and when an Attr node is set on an HTML element using Element.setAttributeNode(), it must have its name converted to lowercase before the element is affected. This doesn't apply to Document.setAttributeNS() and Document.setAttributeNodeNS(). Document.getElementsByTagName() Element.getElementsByTagName() These methods (but not their namespaced counterparts) must compare the given argument in an ASCII case-insensitive manner when looking at HTML elements, and in a case-sensitive manner otherwise. Thus, in an HTML document with nodes in multiple namespaces, these methods will be both case-sensitive and case-insensitive at the same time. stop that parser, and throw away any pending content in the input stream. what about if it doesn't, because it's either like a text/plain, or Atom, or PDF, or XHTML, or image document, or something? Unregister all event listeners registered on the Document node and its descendants.ID HTML parser or XML parser, then stop that parser. what about if it doesn't, because it's either like a text/plain, or Atom, or PDF, or XHTML, or image document, or something? appropriate. outerHTML appropriate. appropriate.
http://www.w3.org/TR/2009/WD-html5-20090423/dom.html
CC-MAIN-2014-52
refinedweb
1,424
51.18
Writing to Excel sheet fails during script run By Relive, - By AnonymousX Hello, I'm trying to write a script that moves copies excel cells into an array. I'll than manipulate the values and send array into another program. I don't want range to be specific to a workbook, or sheet, or set of cells. I want user to be able to highlight desired cells and to copy either normally ("Ctrl+C") or by a hotkey ("Alt+C"). Could someone help me with this? Thank you, I've tried to write the framework: (edited) #include <MsgBoxConstants.au3> #include <Array.au3> #include <Excel.au3> HotKeySet("!v", "Pastedata") While True Sleep(1000) WEnd func Makearray() local $bArray ;User has cells already copied ;Convert clipboard into an array ;I don;t know how excel stores data to clipboard so don;t know how to bring it into array _Arraydisplay($bArray) MsgBox(0,0,$bArray) return $bArray endfunc func Pastedata() Local $aArray MsgBox(0,0,"wait",1) ;make array based on assumption user has already copied a range to clipboard $aArray = Makearray() ;paste code ;don;t worry about this I got the rest endfunc -.
https://www.autoitscript.com/forum/topic/152743-writing-to-excel-sheet-fails-during-script-run/
CC-MAIN-2018-43
refinedweb
192
60.75
Python tag plugin - updating userdata? On 29/06/2018 at 09:41, xxxxxxxx wrote: I'm working on a python tag plugin, and can't seem to figure out how to do a very simple entry update... The plugin was converted from a tag using the prototype converter (which is really awesome, btw). I am capturing the message update from when an entry is changed (using c4d.MSG_DESCRIPTION_CHECKUPDATE), and I can catch the ID of the entry, as well as the value associated to it. I can also (seemingly) set its value - but it isn't propagated in the tag attribute manager view. Here's what I mean: def Message(self, op, id, data) : > bc = op.GetData() if id == c4d.MSG_DESCRIPTION_CHECKUPDATE: > newID = data['descid'][0].id > if(newID > 1002) and (newID < 1007) : > > print "ID: ", newID, "Value: ", bc[newID] #>> prints the current ID and value > >> > > >> bc.SetData(newID, 875.0) #>> sets a new arbitrary value > >> > > >> print "ID: ", newID, "Value: ", bc[newID] The second print gives me 875.0, as expected - but the entryfield in the attribute manager isn't updated... How would I go about that? On 29/06/2018 at 16:02, xxxxxxxx wrote: Ah, got it. using op[data[descid']] = value did it!
https://plugincafe.maxon.net/topic/10841/14292_python-tag-plugin--updating-userdata
CC-MAIN-2020-10
refinedweb
204
67.96
You are given a quantum oracle - an operation on N + 1 qubits which implements a function . You are guaranteed that the function f implemented by the oracle can be represented in the following form (oracle from problem D2): Here (a vector of N integers, each of which can be 0 or 1), and is a vector of N 1s. Your task is to reconstruct the array which could produce the given oracle. Your code is allowed to call the given oracle only once. You have to implement an operation which takes the following inputs: The return of your operation is an array of integers of length N, each of them 0 or 1. Note that in this problem we're comparing the oracle generated by your return to the oracle Uf, instead of comparing your return to the (hidden) value of used to generate Uf. This means that any kind of incorrect return results in "Runtime Error" verdict, as well as actual runtime errors like releasing qubits in non-zero state. Your code should have the following signature: namespace Solution { open Microsoft.Quantum.Primitive; open Microsoft.Quantum.Canon; operation Solve (N : Int, Uf : ((Qubit[], Qubit) => ())) : Int[] { body { // your code here } } }
http://codeforces.com/problemset/problem/1002/E2
CC-MAIN-2018-30
refinedweb
200
51.78
Qt KNX The Qt KNX module implements the client side of a connection between a client and a KNXnet/IP server. This connection can be used to send messages to the KNX bus and to control the functionalities of the KNX devices. Only local device management procedures and KNX application services working with group addressing are fully supported. Note: Qt KNX is part of the Qt for Automation offering and not Qt. For further details please see Qt for Automation. Getting Started To use these classes in your application, use the following include statement: #include <QtKnx/QtKnx> To link against the module, add this line to your qmake .pro file: QT += knx Articles and Guides Examples Reference - KNXnet/IP Connection Classes - Device Management Classes - Tunneling Classes - Datapoint Type Classes - General Classes - All C++ Classes Licenses and Attributions Qt KNX is available under commercial licenses from The Qt Company. In addition, it is available under the the GNU General Public License, version.
https://doc-snapshots.qt.io/qtknx-dev/index.html
CC-MAIN-2018-26
refinedweb
161
51.38
import "cmd/go/internal/base" Package base defines shared basic pieces of the go command, in particular logging and the Command structure. base.go env.go flag.go goflags.go path.go signal.go signal_unix.go tool.go var ( ToolGOOS = runtime.GOOS ToolGOARCH = runtime.GOARCH ToolIsWindows = ToolGOOS == "windows" ToolDir = build.ToolDir ) Configuration for finding tool binaries. Interrupted is closed when the go command receives an interrupt signal. SignalTrace is the signal to send to make a Go program crash with a stack trace. Usage is the usage-reporting function, filled in by package main but here for reference by other packages. AddBuildFlagsNX adds the -n and -x build flags to the flag set. AddKnownFlag adds name to the list of known flags for use in $GOFLAGS. EnvForDir returns a copy of the environment suitable for running in the given directory. The environment is the current process's environment but with an updated $PWD, so that an os.Getwd in the child will be faster. ExpandScanner expands a scanner.List error into all the errors in the list. The default Error method only shows the first error and does not shorten paths. GOFLAGS returns the flags from $GOFLAGS. The list can be assumed to contain one string per flag, with each string either beginning with -name or --name. InitGOFLAGS initializes the goflags list from $GOFLAGS. If goflags is already initialized, it does nothing. IsTestFile reports whether the source file is a set of tests and should therefore be excluded from coverage analysis. MergeEnvLists merges the two environment lists such that variables with the same name in "in" replace those in "out". This always returns a newly allocated slice. RelPaths returns a copy of paths with absolute paths made relative to the current directory if they would be shorter. Run runs the command, with stdout and stderr connected to the go command's own stdout and stderr. If the command fails, Run reports the error using Errorf. RunStdin is like run but connects Stdin. SetFromGOFLAGS sets the flags in the given flag set using settings in $GOFLAGS. ShortPath returns an absolute or relative name for path, whatever is shorter. StartSigHandlers starts the signal handlers. Tool returns the path to the named tool (for example, "vet"). If the tool cannot be found, Tool exits the process. type Command struct { // Run runs the command. // The args are the arguments after the command name. Run func(cmd *Command, args []string) // UsageLine is the one-line usage message. // The first word in the line is taken to be the command name. UsageLine string // Short is the short description shown in the 'go help' output. Short string // Long is the long message shown in the 'go help <this-command>' output. Long string // Flag is a set of flags specific to this command. Flag flag.FlagSet // CustomFlags indicates that the command will do its own // flag parsing. CustomFlags bool // Commands lists the available commands and help topics. // The order here is the order in which they are printed by 'go help'. // Note that subcommands are in general best avoided. Commands []*Command } A Command is an implementation of a go command like go build or go fix. LongName returns the command's long name: all the words in the usage line between "go" and a flag or argument, Name returns the command's short name: the last word in the usage line before a flag or argument. Runnable reports whether the command can be run; otherwise it is a documentation pseudo-command such as importpath. A StringsFlag is a command-line flag that interprets its argument as a space-separated list of possibly-quoted strings. func (v *StringsFlag) Set(s string) error func (v *StringsFlag) String() string Package base imports 17 packages (graph) and is imported by 102 packages. Updated 2019-03-15. Refresh now. Tools for package owners.
https://godoc.org/cmd/go/internal/base
CC-MAIN-2019-13
refinedweb
640
67.35
XML / XPath Explorer For Editorial? I had a recent need to extract some information from some XML - and didn't really want to write a program for it. I could've done with an XML (XPath-based) ad hoc query program. I'm thinking - on a long pair of flights coming up - of writing one in Editorial. Editorial because I can pull the file in and operate on it with some Python and then some. Could such a thing be of general interest? Anyone got experience with XML parsing and XPath in Editorial? (For example advice such as "start with Beautiful Soup" or "do it in Pythonista" would be helpful. Hi Martin, +1 for "start with Beautiful Soup". My bet is that you will crank out a solution so fast that you will look no further. My approach would be to get the basic parsing working and debugged in Pythonista and then backport it into Editorial. By the way, did you get one of those new LinuxONE mainframes that run hundreds of thousands of Docker containers at one time. I was totally impressed with the youtube video of this week's demo; Not GOT one @ccc . Work for the company that makes'em. :-) Could get very interested in them, though. Not sure if Beautiful Soup supports XPath or XQuery. But I think both Pythonista and Editorial have bs4. Pythonista-only guy here. Just so you know, BeautifulSoup is a library meant for HTML parsing, not XML in general, and makes certain assumptions that are specific to HTML. I recall trying to use BS4 to quickly pretty-print an XML file, and had issues with tags named link. Because <link/>tags in HTML are only found within the <head>and never have any content. In the XML file I was dealing with, they had content, which got dropped. (I may be remembering some things wrong, but BS4 does not always work well with XML files that are not (X)HTML.) Python comes with some XML parsers in the standard library, you should probably start with the ElementTreemodule. Pythonista also comes with the third-party xmltodictmodule, though I have never used it and I don't know if it's also included in Editorial. The very first line of the BS docs say: "Beautiful Soup is a Python library for pulling data out of HTML and XML files." Also: "To parse XML you pass in “xml” as the second argument to the BeautifulSoup constructor.". import xmltodict ; print(xmltodict.__version__) # 0.8.7in both Editorial and Pythonista Also see: and in general. Thanks @dgelessus and @ccc . I'm going to confer with @ccc - who works for the same company as me (but we've not yet met). I'm veering towards the standard xml module right now and seeing whether its query capabilities are up to it. The issue with Beautiful Soup for me is the limited querying capability. I'm thinking of presenting selected nodes one after the other pretty printed - in the first iteration. More sophisticated output later on. (And no I'm not going to recreate XSLT / Saxon. And I don't think we already have an XSLT parser to play with here.) One problem I have to solve is how to wildcard actual strings in whichever query language. For example I want to find all nodes where the text starts "FTR" - in my initial use case. (The one that invoked The "Principle" Of Sufficient Disgust.) :-) Prototyping on Editorial I think. Maybe transferring to Pythonista later. I have 2 11-hour flights to/from South Africa to play with this on... :-) And note xml module claims a subset of xpath support.
https://forum.omz-software.com/topic/2130/xml-xpath-explorer-for-editorial
CC-MAIN-2021-49
refinedweb
611
74.9
# Why code reviews are good, but not enough ![image1.png](https://habrastorage.org/r/w1560/getpro/habr/post_images/074/df8/a5d/074df8a5dca459e1be9bea5cb06c0d59.png) Code reviews are definitely necessary and useful. It's a way to impart knowledge, educate, control a task, improve code quality and formatting, fix bugs. Moreover, you can notice high-level errors related to the architecture and algorithms used. So it's a must-have practice, except that people get tired quickly. Therefore, static analysis perfectly complements reviews and helps to detect a variety of inconspicuous errors and typos. Let's look at a decent example on this topic. Try to find an error in the code of a function taken from the [structopt](https://github.com/p-ranav/structopt) library: ``` static inline bool is_valid_number(const std::string &input) { if (is_binary_notation(input) || is_hex_notation(input) || is_octal_notation(input)) { return true; } if (input.empty()) { return false; } std::size_t i = 0, j = input.length() - 1; // Handling whitespaces while (i < input.length() && input[i] == ' ') i++; while (input[j] == ' ') j--; if (i > j) return false; // if string is of length 1 and the only // character is not a digit if (i == j && !(input[i] >= '0' && input[i] <= '9')) return false; // If the 1st char is not '+', '-', '.' or digit if (input[i] != '.' && input[i] != '+' && input[i] != '-' && !(input[i] >= '0' && input[i] <= '9')) return false; // To check if a '.' or 'e' is found in given // string. We use this flag to make sure that // either of them appear only once. bool dot_or_exp = false; for (; i <= j; i++) { // If any of the char does not belong to // {digit, +, -, ., e} if (input[i] != 'e' && input[i] != '.' && input[i] != '+' && input[i] != '-' && !(input[i] >= '0' && input[i] <= '9')) return false; if (input[i] == '.') { // checks if the char 'e' has already // occurred before '.' If yes, return false;. if (dot_or_exp == true) return false; // If '.' is the last character. if (i + 1 > input.length()) return false; // if '.' is not followed by a digit. if (!(input[i + 1] >= '0' && input[i + 1] <= '9')) return false; } else if (input[i] == 'e') { // set dot_or_exp = 1 when e is encountered. dot_or_exp = true; // if there is no digit before 'e'. if (!(input[i - 1] >= '0' && input[i - 1] <= '9')) return false; // If 'e' is the last Character if (i + 1 > input.length()) return false; // if e is not followed either by // '+', '-' or a digit if (input[i + 1] != '+' && input[i + 1] != '-' && (input[i + 1] >= '0' && input[i] <= '9')) return false; } } /* If the string skips all above cases, then it is numeric*/ return true; } ``` To avoid accidentally reading the answer right away, I'll add a picture. ![image2.png](https://habrastorage.org/r/w1560/getpro/habr/post_images/cb1/0a9/35e/cb10a935edf8ade4ed4354880f9d2a85.png) I don't know if you found the error or not. Even if you found it, I'm sure you'll agree that it's not easy to find such a typo. Moreover, you knew that there was an error in the function. If you hadn't known, it would have been hard to make you read and check all this code carefully. In such cases, a static code analyzer will perfectly complement the classic code review. The analyzer doesn't get tired and will thoroughly check all the code. As a result, the PVS-Studio analyzer notices an anomaly in this function and issues a warning: [V560](https://www.viva64.com/en/w/v560/) A part of conditional expression is always false: input[i] <= '9'. structopt.hpp 1870 For those who didn't notice the error, I will give an explanation. Here's the main part: ``` else if (input[i] == 'e') { .... if (input[i + 1] != '+' && input[i + 1] != '-' && (input[i + 1] >= '0' && input[i] <= '9')) return false; } ``` The above condition checks that the i-th element is the letter 'e'. Accordingly, the following check *input[i] <= '9'* doesn't make sense. The result of the second check is always *false*, which is what the static analysis tool warns you about. The reason for the error is simple: the person was hasty and made a typo, forgetting to write +1. In fact, it turns out that the function doesn't check the correctness of the entered numbers as expected. Correct version: ``` else if (input[i] == 'e') { .... if (input[i + 1] != '+' && input[i + 1] != '-' && (input[i + 1] >= '0' && input[i + 1] <= '9')) return false; } ``` **Here's an interesting fact.** This error can be considered as a kind of the "[last line effect](https://www.viva64.com/en/b/0260/)" one. An error was made in the last condition of the function. By the end of this snippet, the programmer's attention weakened, and they made this barely noticeable mistake. [![](https://habrastorage.org/r/w1560/getpro/habr/post_images/42b/757/14b/42b75714b45fa154c5497bdb32b2c568.png)](https://viva64.com/en/pvs-studio-download/) If you like the article about the last line effect, I recommend reading about other similar ideas: [0-1-2](https://www.viva64.com/en/b/0713/), [memset](https://www.viva64.com/en/b/0360/), [comparisons](https://www.viva64.com/en/b/0509/). Bye everyone. Kudos to those who found the bug themselves.
https://habr.com/ru/post/520258/
null
null
845
58.99
Each Answer to this Q is separated by one/two green lines. I am interested in taking in a single character. c="c" # for example hex_val_string = char_to_hex_string(c) print hex_val_string output: 63 What is the simplest way of going about this? Any predefined string library stuff? There are several ways of doing this: >>> hex(ord("c")) '0x63' >>> format(ord("c"), "x") '63' >>> import codecs >>> codecs.encode(b"c", "hex") b'63' On Python 2, you can also use the hex encoding like this (doesn’t work on Python 3+): >>> "c".encode("hex") '63' This might help import binascii x = b'test' x = binascii.hexlify(x) y = str(x,'ascii') print(x) # Outputs b'74657374' (hex encoding of "test") print(y) # Outputs 74657374 x_unhexed = binascii.unhexlify(x) print(x_unhexed) # Outputs b'test' x_ascii = str(x_unhexed,'ascii') print(x_ascii) # Outputs test This code contains examples for converting ASCII characters to and from hexadecimal. In your situation, the line you’d want to use is str(binascii.hexlify(c),'ascii'). Considering your input string is in the inputString variable, you could simply apply .encode('utf-8').hex() function on top of this variable to achieve the result. inputString = "Hello" outputString = inputString.encode('utf-8').hex() The result from this will be 48656c6c6f. You can do this: your_letter = input() def ascii2hex(source): return hex(ord(source)) print(ascii2hex(your_letter)) For extra information, go to: to get ascii code use ord(“a”); to convert ascii to character use chr(97)
https://techstalking.com/programming/python/how-do-i-convert-a-single-character-into-its-hex-ascii-value-in-python/
CC-MAIN-2022-40
refinedweb
245
58.18
Earlier this year I wrote an article for Smashing Magazine about Houdini, and I called it the “most exciting development in CSS you’ve never heard of”. In the article I argue that Houdini APIs will (among other things) make it possible to polyfill CSS features in a way that simply cannot be done today. While the article was generally quite well-received, I did notice the same question popping up over and over again in my inbox and on Twitter. The basic gist of the question was: What’s so hard about polyfilling CSS? I’ve used lots of CSS polyfills, and they worked fine for me. And I realized—of course people have this question. If you’ve never tried writing a CSS polyfill yourself, then you’ve probably never experienced the pain. So the best way I can think of to answer this question—and explain why I’m excited about Houdini—is to show you exactly why polyfilling CSS is hard. And the best way to do that is to write a polyfill ourselves. The random keyword The feature we’re going to polyfill is a (pretend) new CSS keyword called random, which evaluates to a number between 0 and 1 (just like what Math.random() returns in JavaScript). Here’s an example showing how random might be used: .foo { color: hsl(calc(random * 360), 50%, 50%); opacity: random; width: calc(random * 100%); } As you can see, since random returns a unitless number, it can be used with calc() to essentially become any value. And since it can be any value, it can be applied to any property (e.g. color, opacity, width, etc). For the rest of this post, we’re going to be working with the demo page I used in my talk. Here’s what it looks like: This page is the basic “Hello World” Bootstrap starter template with four .progress-bar elements added at the top of the content area. In addition to bootstrap.css, it includes another CSS file with the following rule: .progress-bar { width: calc(random * 100%); } While the demo I’ve linked to uses hard-coded progress bar width values, the idea is that once the polyfill is implemented, every time you refresh the page the progress bars will have different, random widths. How polyfills work In JavaScript, writing polyfills is relatively easy because the language is so dynamic and allows you to modify built-in objects at runtime. For example, if you wanted to polyfill Math.random(), you’d do something like this: if (typeof Math.random != 'function') { Math.random = function() { // Implement polyfill here... }; } CSS, on the other hand, is not dynamic in this way. It’s not possible (at least not yet) to modify the runtime to tell the browser about a new feature it doesn’t natively understand. This means that to polyfill a CSS feature that the browser doesn’t understand, you have to dynamically modify the CSS to fake the feature’s behavior using CSS the browser does understand. In other words, you have to turn this: .foo { width: calc(random * 100%); } into something like this, that’s randomly generated at runtime: .foo { width: calc(0.35746 * 100%); } Transforming the CSS So we know we have to modify the existing CSS to add new style rules that mimic the behavior of the feature we’re trying to polyfill. The most natural place to assume you’d be able to do that is the CSS Object Model (CSSOM) which can be accessed on document.styleSheets. The code might look something like this: for (const stylesheet of document.styleSheets) { // Flatten nested rules (@media blocks, etc.) into a single array. const rules = [...stylesheet.rules].reduce((prev, next) => { return prev.concat(next.cssRules ? [...next.cssRules] : [next]); }, []); // Loop through each of the flattened rules and replace the // keyword `random` with a random number. for (const rule of rules) { for (const property of Object.keys(rule.style)) { const value = rule.style[property]; if (value.includes('random')) { rule.style[property] = value.replace('random', Math.random()); } } } } Note: in a real polyfill you wouldn’t just do a simple find and replace for the word random, as it could be present in many forms outside of its keyword form (e.g. in a URL, in a custom property name, in quoted text in the content property, etc.). The actual code in the final demo uses a more robust replacement mechanism, but for the sake of simplicity I’m using the simple version here. If you load demo #2 and paste the above code into the JavaScript console and run it, it’ll actually do what it’s supposed to do, but you won’t see any random-width progress bars when it’s done. The reason is because none of the rules containing the random keyword are in the CSSOM! As you’re probably aware, when a browser encounters a CSS rule it doesn’t understand, it simply ignores it. In most situations that’s a good thing because it means you can load CSS in an old browser and the page won’t complete break. Unfortunately, it also means if you need access to the raw, unaltered CSS, you have to fetch it yourself. Fetching the page styles manually CSS rules can be added to a page with either <style> elements or <link rel="stylesheet"> elements, so to get the raw, unaltered CSS you can do a querySelectorAll() on the document and manually get the innerHTML contents of any <style> tags or fetch() the URL resources of any <link ref="stylesheet"> tags: The following code defines a getPageStyles utility function that returns a promise that will resolve with the full CSS text of all page styles: const getPageStyles = () => { // Query the document for any element that could have styles. var styleElements = [...document.querySelectorAll('style, link[rel="stylesheet"]')]; // Fetch all styles and ensure the results are in document order. // Resolve with a single string of CSS text. return Promise.all(styleElements.map((el) => { if (el.href) { return fetch(el.href).then((response) => response.text()); } else { return el.innerHTML; } })).then((stylesArray) => stylesArray.join('\n')); } If you open demo #3 and paste the above code into the JavaScript console to define the getPageStyles() function, you’ll then be able to run the code below to log the full CSS text: getPageStyles().then((cssText) => { console.log(cssText); }); Parsing the fetched styles Once you have the raw CSS text, you need to parse it. You might be thinking that since the browser already has a CSS parser you’d be able to call some function to parse the CSS. Unfortunately, that’s not the case. And even if the browser did expose a parseCSS() function, it doesn’t change the fact that the browser doesn’t understand the random keyword, so its parseCSS() function would likely still not work (hopefully future parse specs will allow for unknown keywords that otherwise comply with the existing grammar). There are several good, open-source CSS parsers out there, and for the purposes of this demo, we’re going to use PostCSS (since it can be browserified and includes a plugin system that we’ll take advantage of later). If you run postcss.parse() on the following CSS text: .progress-bar { width: calc(random * 100%); } you’ll get something like this: { "type": "root", "nodes": [ { "type": "rule", "selector": ".progress-bar", "nodes": [ { "type": "decl", "prop": "width", "value": "calc(random * 100%)" } ] } ] } This is what’s known as an abstract syntax tree (AST), and you can think of it like our own version of the CSSOM. Now that we have a utility function to get the full CSS text, as well as a function to parse it, here’s what our polyfill looks like so far: import postcss from 'postcss'; import getPageStyles from './get-page-styles'; getPageStyles() .then((css) => postcss.parse(css)) .then((ast) => console.log(ast)); If you open demo #4 and look at the JavaScript console, you’ll see an object log containing the full PostCSS AST for all the styles on the page. Implementing the polyfill At this point we’ve written a lot of code, but strangely none of it has had anything to do with the actual functionality of our polyfill. It’s just been necessary boilerplate to work around the fact that we have to manually do a bunch of stuff the browser should be doing for us. To actually implement the polyfill logic we have to: - Modify the CSS AST, replacing occurrences of randomwith a random number. - Stringify the modified AST back into CSS. - Replace the existing page styles with the modified styles. Modifying the CSS AST PostCSS comes with a nice plugin system with many helper functions for modifying a CSS AST. We can use those functions to replace occurrences of the random keyword with a random number: const randomKeywordPlugin = postcss.plugin('random-keyword', () => { return (css) => { css.walkRules((rule) => { rule.walkDecls((decl, i) => { if (decl.value.includes('random')) { decl.value = decl.value.replace('random', Math.random()); } }); }); }; }); Stringifying the AST back into CSS Another nice thing about using PostCSS plugins is they already have built-in logic for stringifying the AST back into CSS. All you have to do is create a PostCSS instance, pass it the plugin (or plugins) you want to use, and then run process(), which returns a promise that resolves with an object containing the stringified CSS: postcss([randomKeywordPlugin]).process(css).then((result) => { console.log(result.css); }); Replacing the page styles To replace the page styles we can write a utility function (similar to getPageStyles()) that finds all <style> and <link rel="stylesheet"> elements and removes them. It also creates a new <style> tag and sets its style contents to whatever CSS text is passed to the function: const replacePageStyles = (css) => { // Get a reference to all existing style elements. const existingStyles = [...document.querySelectorAll('style, link[rel="stylesheet"]')]; // Create a new <style> tag with all the polyfilled styles. const polyfillStyles = document.createElement('style'); polyfillStyles.innerHTML = css; document.head.appendChild(polyfillStyles); // Remove the old styles once the new styles have been added. existingStyles.forEach((el) => el.parentElement.removeChild(el)); }; Putting it all together Armed with our PostCSS plugin to modify the CSS AST and our two utility functions to fetch and update the page styles, our full polyfill code now looks like this: import postcss from 'postcss'; import getPageStyles from './get-page-styles'; import randomKeywordPlugin from './random-keyword-plugin'; import replacePageStyles from './replace-page-styles'; getPageStyles() .then((css) => postcss([randomKeywordPlugin]).process(css)) .then((result) => replacePageStyles(result.css)); If you open demo #5, you can see it in action. Refresh the page a few times to behold the full randomness! …hmmmmmm, not quite what you were expecting, was it? What went wrong While the plugin is technically working, it’s applying the same random value to every element matching the selector. This makes perfect sense when we think about what we’ve done—we’ve just rewritten a single property on a single rule. The truth is all but the simplest CSS polyfills require more than just rewriting individual property values. Most of them require knowledge of the DOM as well as specific details (size, contents, order, etc.) of the individual matching elements. This is why preprocessors and server-side solutions to this problem will never be sufficient alone. But that brings up an important question: how do we update the polyfill to target individual elements? Targeting individual, matching elements In my experience there are three options for targeting individual DOM elements, and none of them are great. Option #1: inline styles By far the most common option I see for how polyfill authors handle the issue of targeting individual elements is to use the CSS rule selector to find the matching elements on the page and apply inline styles directly to them. Here’s how we could update our PostCSS plugin to do just that: // ... rule.walkDecls((decl, i) => { if (decl.value.includes('random')) { const elements = document.querySelectorAll(rule.selector); for (const element of elements) { element.style[decl.prop] = decl.value.replace('random', Math.random()); } } }); // ... Demo #6, shows the following code in action. At first it seems to work great, unfortunately, it’s easy to break. Consider if we update the CSS to add another rule after our .progress-bar rule. .progress-bar { width: calc(random * 100%); } #some-container .progress-bar { width: auto; } The above codes states that all progress bar elements should have a random width except progress bar elements that are descendants of an element with the ID #some-container, in which case the width should not be random. Of course this won’t work, because we’re applying inline styles directly to the element, which means those styles will be more specific than the styles defined on #some-container .progress-bar. This means our polyfill breaks some fundamental assumptions we make when working with CSS (so personally, I find this option unacceptable). Option #2: Use inline styles, but try to account for the gotchas of option #1 The second option accepts that lots of normal CSS use-cases will fail with the first option, so it tries to address those. Specifically, in option #2 we update the implementation to: - @mediarules,-property instead of per-rule, so we’ll have to maintain a separate mapping for that to figure out which declaration will ultimately win. Yeah, if you couldn’t tell, I’ve just describe the cascade, which is something we’re supposed to be depending on the browser to do for us. While it’s definitely possible to re-implement the cascade in JavaScript, it would be a lot of work, and I’d rather just see what option #3 is. Option #3: Rewrite the CSS to target individual, matching elements while maintaining cascade order. The third option—which I consider to be the best of the bad options—is to rewrite the CSS and convert rules with one selector that matches many elements into many rules, each of which only matches a single element, all the while not changing the final set of matching elements. Since that last sentence probably didn’t make a whole lot of sense, let me clarify with an example. Consider the following CSS file, which is included on a page that contains three paragraph elements: * { box-sizing: border-box; } p { /* Will match 3 paragraphs on the page. */ opacity: random; } .foo { opacity: initial; } If we were to add a unique data attribute to each paragraph in the DOM, we could rewrite the CSS as follows to target each paragraph element with its own, individual rule: * { box-sizing: border-box; } p[data-pid="1"] { opacity: .23421; } p[data-pid="2"] { opacity: .82305; } p[data-pid="3"] { opacity: .31178; } .foo { opacity: initial; } Of course, if you’re paying attention, this still doesn’t quite work because it alters the specificity of these selectors, which will likely lead to unintended side-effects. However, we can ensure the proper cascade order is maintained by increasing every other selector on the page by the same specificity amount with some clever hackery: *:not(.z) { box-sizing: border-box; } p[data-pid="1"] { opacity: .23421; } p[data-pid="2"] { opacity: .82305; } p[data-pid="3"] { opacity: .31178; } .foo:not(.z) { opacity: initial; } The changes above apply the :not() functional, pseudo-class selector and pass it the name of a class we know isn’t found in the DOM (in this case I’ve chosen .z; which means if you use the class .z in the DOM you’d have to pick a different name). And since :not() will always match an element that doesn’t exist, it can be used to increase the specificity of a selector without changing what it matches. Demo #7, shows the result of implementing this strategy, and you can refer to the demo source code to see the full set of changes to the random-keyword plugin. The best part about option #3 is it continues to let the browser handle the cascade, which the browser is already really good at. This means you can use media queries, !important declarations, custom properties, @support rules, or any CSS feature, and it will still just work. Downsides It might seem like with option #3 I’ve solved all of the problems with CSS polyfills, but that couldn’t be further from the truth. There are still a lot of remaining issues, some of which can be resolved (with a lot of extra work), and some of which are impossible to resovle and therefore unavoidable. Unresolved issues For one thing, I’ve intentionally skipped over a few places CSS might live on the page outside of querying the DOM for <style> and <link rel="stylesheet"> tags: - Inline styles - Shadow DOM We could update our polyfill to account for these cases, but it would be way more work than I’d want to discuss in a blog post. We also haven’t even considered the possibility of what happens when the DOM changes. After all, we’re rewriting our CSS based on the contents of the DOM, which means we’ll have to re-rewrite it any time the DOM changes. Unavoidable problems In addition to the problems I’ve just described (which are hard, but doable), there are some problems that just can’t be avoided: - It requires a ton of extra code. - It doesn’t work with cross-origin (non-CORS) stylesheets. - It performs horribly if/when changes are needed (e.g. DOM changes, scroll/resize handlers, etc.) Our random keyword polyfill is a rather simple case, but I’m sure you can easily imagine a polyfill for something like position: sticky, in which all the logic I’ve described here would have to be re-run every time the user scrolled, which would be absolutely horrible for performance. Possibilities for improvement One solution I didn’t address in my talk (due to limited time) that would potentially alleviate the first two bullets above is to do the parsing and fetching of the CSS server-side in a build step. Then instead of loading a CSS file containing styles, you’d load a JavaScript file containing an AST and the first thing it would do is stringify the AST and add the styles to the page. You could even include a <noscript> tag which references the original CSS file in the event the user has JavaScript disabled. For example, instead of this: <link ref="stylesheet" href="styles.css"> you’d have this: <script src="styles.css.js"></script> <noscript><link ref="stylesheet" href="styles.css"></noscript> As I mentioned, this solves the problem of having to include a full CSS parser in your JavaScript bundle, and it also allows you to parse the CSS ahead of time, but it doesn’t solve all performance issues. No matter what you try, you’ll always have to rewrite the CSS whenever a change is needed. Understanding the performance implications In order to understand why the performance of CSS polyfills is so bad, you really have to understand the browser rendering pipeline—specifically the steps in the pipeline that you as a developer have access to. As you can see, the only real point of entry is the DOM, which our polyfill made use of through querying for elements matching the CSS selector as well as through updating the CSS text of the <style> tag. But given the current state of JavaScript access to the browser’s rendering pipeline, this is the path our polyfill is forced to take. As you can see, JavaScript is not able to intervene in the initial rendering pipeline after the DOM is constructed, which means any changes our polyfill makes will force the entire rendering process to start over. This means its impossible for CSS polyfills to perform at 60 fps since all updates force a subsequent render and thus a subsequent frame. Wrapping up The point I hope you take away from the article is that polyfilling CSS is particularly hard because of all the work we as developers need to do to work around limitations of styling and layout on the web today. Here’s a list of things our polyfill had to do manually—things the browser is already doing, but that we as developers can’t access: - Fetching the CSS - Parsing the CSS - Creating the CSSOM - Handling the cascade - Invalidating styles - Revalidating styles And this is exactly why I’m excited about Houdini. Without Houdini APIs, developers will be forced to resort to hacks and workarounds that come at the cost of performance and usability. And that means CSS polyfills will necessarily be either - Too big - Too slow - Too incorrect Unfornately, we can’t have all three. We have to choose. Without low-level styling primitives, innovation will move at the pace of the slowest-adopting browser. Developers complain about the pace of innovation in the JavaScript community. But you never hear about that in CSS. And part of that is due to the limitations I’ve described in this article I think we need to change that. I think we need to #makecssfatigueathing.
https://philipwalton.com/articles/the-dark-side-of-polyfilling-css/
CC-MAIN-2022-21
refinedweb
3,519
60.45
Fellas, what do you think of my exim filter file filtering spamassassin results... I first give 'em a pass-word in case they're real. [You see, I don't operate spamassassin, just have access to its results.] I do the best I can with the paltry exim user assignable variables available, numbers. add 334424 to n9 if $h_subject: contains $n9 then logwrite "**Passed with $n9: $tod_log $h_from $h_subject" finish endif #----------------------------------------------- if $h_X-Spam-Status: contains FROM_NO_USER then logwrite "FROM_NO_USER spam: $tod_log $h_from $h_subject" fail "FROM_NO_USER spam? If not, put \"$n9\" in Subject." seen finish endif #----------------------------------------------- etc. etc., the whole file is in
https://lists.debian.org/debian-user/2003/01/msg00120.html
CC-MAIN-2017-30
refinedweb
103
67.45
Solution for no module name pmadarima is Given Below: On installing pip install pmdarima via command prompt as admin, I get the below message as successful installation. Requirement already satisfied: patsy>=0.5 in c:usersusernameappdatalocalprogramspythonpython39libsite-packages (from statsmodels!=0.12.0,>=0.11->pmdarima) (0.5.1) But unable to work on it via Jupyter, get the below error on running import pmdarima as pm from pmdarima.model_selection import train_test_split ModuleNotFoundError: No module named 'pmdarima' When you do pip install, you’re using your system’s default python. You can have multiple versions of Python installed on the same computer. For example, on my Mac if I do python in the terminal that opens Python 2. If I do python3 in the terminal, that opens Python 3. When I do pip install numpy, it will install it to Python 2 by default. A program running in Python 3 will not be able to find that package. To get it working for Python 3, I would do python3 -m pip install numpy. This uses the pip belonging to the right Python interpreter. What is most likely happening here is that your Jupyter notebook is using a different Python interpreter. Try doing the install inside the notebook itself in a cell and that should work.
https://codeutility.org/no-module-name-pmadarima/
CC-MAIN-2021-49
refinedweb
214
65.52
Another example is a networking system tasked with synchronizing game objects between clients and servers. A very general such system might want to treat the objects as open JSON-like structs, with arbitrary fields and values: { "score" : We require the object to be of a specific type. This is the typing method used in C and for classes without inheritance in C++. 2. Interface typing - If it says it’s a duck We We don’t care about the type of the object at all, as long as it has the fields and methods that we need. An example: def integrate_position(o, dt): o.position = o.position + o.velocity * dt This(ÃÃÃÃâPositionÃÃÃÃâ).SetValue(o, o.GetType(). GetProperty(ÃÃÃÃâPositionÃÃÃÃâ).GetValue(o, null) + o.GetType(). GetProperty(ÃÃÃÃâVelocityÃÃÃÃâ):) I like some of your ideas but I can't help but to think that your idea of decoupling is making all functions take void* arguments and making all UDTs char buffers or possibly PODs that are easily castable to continuous memory blocks. Also calling this solution Duck Typing is a big stretch to say the least. Duck Typing is about behavior not data. It should "walk" and "quack" like a duck and not be "memory access optimized map". std::map<> is not a DT representative nor is presented solution. Also, it would be nice to see the code that shows how you could replace presented python snipped in C++ with 2 example "types" that share "interface" based on your proposed solution. Please don't get me wrong. I like the article very much, in fact I try to read everything you write and I am now also thinking how to wrap your "dynamic type" in templates to make a nice interface to underlying buffer. Would kindof be similar to boost::flat_map i suppose in which key-value pairs are stored in a vector (instead of a node-based tree) for the best cache usage. This is all fine until the "data" needs to include dynamically allocated data, i.e. variable length strings or arrays, then suddenly you have no way to safety copy the data by copying memory. Qt's QVariant provides a pretty clever example of a truly type-safe and copy-safe multiple-type container as does, I assume, boost::any. Mangling raw memory is not an extensible solution. in my case, I actually hide the object-type (for allocated object) in the memory-allocator, and often use predicate functions to check for types (for plain structs, this is more convenient than using an explicit type within the struct itself). this means though that the passed object pointer points to just after the object header. another related strategy is to use the type to fetch a vtable, and then use the vtable for operations. for example: if(fooParticleP(obj)) { ... } fooParticleGetVT(obj)->Update(obj, dt); fooParticleGetVT(obj)->Draw(obj); ... in many cases (such as for very frequent operations), this can be a lot faster than using if/else chains. (like, you don't want a long set of if/else chains in the middle of a particle drawing or update loop...). for primitive types, much more preferable IMO is to use a tagged-value. the tagged value could be, for example, a 64-bit value held as a single value in a struct, with 4 bits or so being used as a type-tag. operations can then mostly be wrapped, for example like: where, for example: well, sort of, it may get a little more involved than this (for example, the above actually has 4 tag values for 'int', whereas one may notice that this would actually be for a 62-bit value, just the logic for 62-bit values is less concise...). this avoids the need to provide allocated storage for the tagged value, it is simply copied around by value, and also helps abstract over the exact representation of the value. granted, this does come at a cost of needing to wrap/unwrap pointers (so it is more of a hassle in this sense). while this wastes space on 32-bit targets for storing pointers, this can be outweighed by its ability to avoid needing to box doubles (or be stuck with the relatively poor precision that is "a float with several bits cut off"). I accidentally downvoted you, I meant to up vote you but my laptop's mousepad is super sensitive. Anyway, thank you for these articles, they came at a perfect time in the development of my engine. I like your articles and find the interesting, but again I have no clue why you are even using C++ instead of plain old C. Hmm, aren't templates the way to achieve duck typing in C++ ? I mean your Python example: could be written in C++ as following: You can use it simply: integrate_position(objectOfMyType, whateverAmount) and the compiler will generate the code for appropriate types. I'll start at a criticism but end with a question. I have to disagree that inheritance is generally a bad thing. Simply put, some code should not be replicated, because you've simply created multiple points of failure where there should be only one. And some times, composition doesn't cover what is needed, because it can lead to nasty practices like deeply nested proxy methods that turn one method call into many, which is bad for performance and maintainability. Building function call stack entries is not, as is commonly believed, free. Sometimes, inheritance is just the right answer, and I think that a greater effort should be placed on illuminating the situations in which it is non-optimal rather than simply blasting the entire mechanic without providing some basis for the argument. Disagreements aside, the article is more than a little interesting, and I was wondering if you might in the future present some article which shows how to use this data structuring methodology to implement something more complicated like a tree structure or something in terms of code rather than just diagrams and textual descriptions. Even though you give very good descriptions, I feel like a little more code would help show how composing these types together would happen. Thanks for the article series.
http://www.gamedev.net/page/resources/_/technical/game-programming/managing-decoupling-part-3-c-duck-typing-r3060
CC-MAIN-2016-40
refinedweb
1,037
58.82
). - PeterJones last edited by @Valley-Moose said: Could you provide me with a little more explanation? I’ve never used it; I just advocate it. :-) Hopefully, @Ekopalypse will chime in. @Alan-Kilborn I’m a pretty fast learner, but discerning what is relevant to me by reading someone else’s conversation on a similar topic and understanding what I need to do… is a bit difficult. I’m not 100% certain I understand what you trying to achieve. Do you need some kind of “color this line different than the others”, or do you really need “this line should be colored like the sql lexer does as it is sql” and “this line should be colored as perl lexer does as it is really perl” etc. ? Or do you want to have certain words or text fragments colored differently? Could you provide an example of such a text? . If I set the language to SQL, the file will use SQL syntax highlighting. I want to be able to highlight specific text and assign the syntax to use. I’m told that Sublime Text 3 allows for this, but only with related languages like java and c++ etc.- It may be that I am not asking my question correctly, but I hope this clarified it a little. @Valley-Moose said: . I don’t know if it helps to know that I added DAX syntax highlighting following instructions given here - since it is not available by default: - Ekopalypse last edited by nothing to excuse. I’m not a native English speaker and just wanted to be sure to understand it correctly, that’s why a asked for clarification. Having two lexers (code which does the coloring) active at the same time isn’t supported by npp/scintilla. There is a concept of sublexers but as far as I know, the only lexer which does this is the html lexer. This colors html, javascript, php etc… in one lexer. So, in order to be able to make this work for you one would either write a lexer which does the lexing for both languages or you have to decide to use one builtin lexer and enhance it with additional colorings like @PeterJones mentioned. As I don’t know DAX, well I know DAX as the german stock index, as a language can you provide me a link or details about its syntax? Are you looking for something like this - Or this - This may also be helpful - Otherwise, here is an sample of something I might write: POSI TCs:=CALCULATE(SUM(Data[Trouble Call]),FILTER(all(Data), Data[Position] = values(Data[Position]))) - POSI TCs: - is the name of the Measure - Data - is the name of the Table - Trouble Call & Position - are Column Names within the Table (How do I include an example from notepad++, so you can see what it looks like for me? -I saw that you were able to do that in your posts - As you may be able to tell, I’m new to posting questions on forums.) thank you, that is exactly what I was looking for. To include code you can use 3 tildes before the code and 3 tildes afterwards. Like ~~~ code ~~~. To include a screenshot, you have to upload it to some hoster like imgur.com and include it like woluld result in @Valley-Moose said: I’m a pretty fast learner, but discerning what is relevant to me by reading someone else’s conversation on a similar topic and understanding what I need to do… is a bit difficult. Understood. It would take some absorption…which means time. :) I want to be able to highlight specific text and assign the syntax to use And I think I know the next thing you’ll want: Notepad++ to remember (over multiple runs) your setting for text you previously did this to. It’s a bit of a challenge. Thanks! This is what that DAX would look like: after thinking about it for some time I can imagine how this could be achieved. In theory: - using a hidden scintilla document - and a script for selecting which lexer should be used workflow: - select text - run script and select lexer from a messagebox, prompt, or whatever ui - now, under the hood, the script would get the text selected and paste it into the hidden scintilla document and sets the lexer. Then it reads the styles assigned to the text and sets it in the real document Is this possible? I don’t know, I never done something like this but is something I’m eager to find out. So I need some time playing around and let you know. Concerning the “Can I stop npp, restart some time later and the coloring is still there?”, I would say, yes, if a strict policy is in place. Something like a file must be saved always and this file is not allowed to be manipulated outside from npp. I’ve tested the concept and it looks like it could work, BUT there are some strange things happening. Assuming one wants to color every word of a text in red. When using these three lines to do the coloring editor.setIndicatorCurrent(INDICATOR_ID) editor.setIndicatorValue(color | SC_INDICVALUEBIT) editor.indicatorFillRange(start, length) there is an extreme difference in performance if you call it directly or via a callback like SCINTILLANOTIFICATION.UPDATEUI. If one is using a callback it takes 11ms to color 377 words, if calling it directly, it takes 6 seconds. ??? In addition, if calling it directly, it happens that not all words get colored. Sometimes it misses 2 or 3 or … words even so the debug shows that those missed words are actually processed. ??? What haven’t I understood? And some more strange things. Just for the fun, I’ve tested a python only version, means building a window and embedding scintilla in pure python, but python3 I must admit, it took 3ms to do the same thing. What is slowing down when using PS?? I think there are some “slowness” gremlins in Pythonscript that no one has totally figured out yet. Here’s a reference to another type, maybe some hints here for you Eko because from observation it definitely seems like you have the skills to maybe solve it or at least root cause it. I was hoping @Claudia-Frank would solve these things, but no luck and she has disappeared. Maybe you are the new Claudia. ;) I’ve tested a python only version, means building a window and embedding scintilla in pure python I would like to understand how to do that, sure, just for fun. :) Alan, thanks for the link but, oh lord, if they were confused how should I find it? They have far more experience in c++ than I do. Phew. Maybe you are the new Claudia. But I don’t have to turn myself into a woman, or? LOL :-D I would like to understand how to do that, sure, just for fun. :) :-) Claudia posted this and I slightly modified it. def MainLoop(self): self.ColorEachWordRed() gui.PumpMessages() def ColorEachWordRed(self): SC_INDICVALUEBIT = 0x1000000 INDICATOR_ID = 8 TEXTFORE = 17 VALUEFORE = 1 # editor1.indicSetStyle(INDICATOR_ID, INDICATORSTYLE.TEXTFORE) self.scintilla_direct_function(self.sci_direct_pointer, 2080, INDICATOR_ID, TEXTFORE) # editor1.indicSetFlags(INDICATOR_ID, INDICFLAG.VALUEFORE) self.scintilla_direct_function(self.sci_direct_pointer, 2684, INDICATOR_ID, VALUEFORE) t1_start = time.time() i = 0 for match in re.finditer(b'\w+', self.text): i += 1 start, end = match.span() self.scintilla_direct_function(self.sci_direct_pointer, 2500, INDICATOR_ID) self.scintilla_direct_function(self.sci_direct_pointer, 2502, 255 | SC_INDICVALUEBIT) self.scintilla_direct_function(self.sci_direct_pointer, 2504, start, end-start) t1_stop = time.time() print('Colored %d items' % i) print("Elapsed time: %.6f" % (t1_stop-t1_start)) self.text, my test data, is this self.text = b'''Hello World here is python Lorem ipsum dolor sit amet, consectetur adipiscing elit. Sed molestie nisl placerat, ultricies risus nec, aliquam nunc. Nunc urna metus, molestie ut augue vitae, posuere faucibus elit. Donec sodales est tortor, eu aliquet massa hendrerit et. Aliquam pretium fermentum volutpat. Aliquam et lorem id orci tincidunt porta. Duis vehicula, mi eu tempor cursus, mauris ex efficitur libero, ac ultricies dui enim eu dui. Proin vel diam pulvinar, consequat libero ac, interdum lorem. Nam interdum ut sapien eu viverra. Nunc molestie efficitur sollicitudin. Morbi vel fermentum velit. 123 Aliquam nec lectus a enim vulputate pretium. Nunc elementum tristique porttitor. Curabitur malesuada sed augue sed lobortis. Vivamus sit amet pharetra dolor. Etiam finibus gravida felis, sed porttitor sapien. In lobortis purus eu ipsum auctor varius. Cras eu tempor urna, quis iaculis nunc. Ut purus lectus, ultrices congue elementum quis, pellentesque vel eros. Mauris eget dolor non dolor finibus mollis vel et elit. Quisque vestibulum orci non nulla pulvinar, ac efficitur velit tempor. Cras non sem pellentesque, feugiat sapien sed, commodo elit. Cras dolor augue, eleifend vel urna vitae, consequat blandit lectus. Curabitur porttitor neque in mi ornare dictum. Orci varius natoque penatibus et magnis dis parturient montes, nascetur ridiculus mus. Duis ante nisl, facilisis tincidunt odio quis, placerat molestie dolor. 456 Phasellus rutrum posuere convallis. Proin dictum ex eget nisl eleifend tempus. Cras id lorem fermentum, molestie quam eu, commodo odio. Curabitur id quam tellus. Suspendisse potenti. Etiam egestas tincidunt dui, quis ornare nulla rhoncus quis. Suspendisse sodales elit vel felis vestibulum mollis. 789 Aenean quis massa laoreet, sagittis est ac, bibendum risus. Praesent eu sapien faucibus, porta orci non, ultricies elit. Morbi a dapibus neque. Nunc at odio eget risus egestas efficitur. Duis ullamcorper velit diam, et volutpat lacus malesuada eget. Mauris dignissim tincidunt rutrum. Sed molestie ut nisl ac dictum. Vestibulum a libero ut turpis tristique vehicula. Nam lobortis, leo vitae pellentesque sollicitudin, dolor leo viverra enim, sit amet ullamcorper metus magna eget ipsum. Ut ac eros porta, lacinia sem ac, posuere elit. Nam at efficitur orci, nec volutpat ligula. Quisque non nisi sit amet arcu accumsan viverra quis et tellus. Fusce accumsan, nunc vel semper sollicitudin, elit ante congue velit, vitae dignissim tellus risus ac justo. Duis non leo lorem. 000 ''' Make sure your SciLexer.dll is in the same directory as your script and, of course, that python bitness matches SciLexer.dll bitness. Edit: You need to pip install win32 package. just in case you want to test the other two direct call) s1 = time.time() matches = [] editor.research(r'\w+', lambda m: matches.append(m.span())) for match in matches: paint_it(255, match[0], match[1] - match[0]) print time.time() - s1 via callback) def on_updateui(args): s1 = time.time() matches = [] editor.research(r'\w+', lambda m: matches.append(m.span())) for match in matches: paint_it(255, match[0], match[1] - match[0]) print time.time() - s1 editor.clearCallbacks([SCINTILLANOTIFICATION.UPDATEUI]) editor.callbackSync(on_updateui, [SCINTILLANOTIFICATION.UPDATEUI]) Edit: be careful about the callback as it will color every document, use it, maybe, in its own npp instance :-) @Ekopalypse said: Claudia posted this and I slightly modified it. Ah…well it appears that even if you are not the new Claudia, you are at least “channeling” the old Claudia. That posting from Claudia was only 4 days old…seems she is still in the Scintilla game even if not the N++ game…maybe she is making the next new great competitor for N++?? if they were confused how should I find it? You seem to have a knack for this stuff (way beyond my basic skill); maybe all it takes is a pair of fresh eyes? BTW, I have a new (perhaps tough?) problem for Pythonscript that I’ll be posting here (well, in a brand-new thread) soon…hopefully you’ll be watching for it. :)
https://community.notepad-plus-plus.org/topic/17631/assign-language-by-line/2?lang=en-US
CC-MAIN-2021-10
refinedweb
1,923
66.54
You would need to import them. For example, to use the time module, you'd do: import time and you could use it's functions like time.time(), time.sleep(), etc etc You would need to import them. For example, to use the time module, you'd do: import time and you could use it's functions like time.time(), time.sleep(), etc etc Math.min() First, remove the parameters username and password from line 1: def Login(username , password): -> def Login(): put this at the bottom of your code: Get rid of the return print() statements and just print() first and then just put "return" at the end. if you've learned about user defined functions, you could put all your code into function main() and call it. Whenever you need it to stop running, you would simply just put the statement return in your code. If you need more help, please link your repl. ^^ you forgot to group the ingredients together in shopping_cart like so: shopping_cart = [["celery", 4, 9], ["beef", 15, 3], ["eggs", 2, 12], ["bread", 4, 1]] first off, you should indent your code to make it more readable. in line 3: replace the single equal signs with double equal signs in line 4: you're missing an ending parenthesis after random.randint(1, 15) you'd need a web crawler and send a query to google check your logic line for the if statement: try this line instead: if(index($resp->decoded_content, '{"transactionId":"")' != -1){ for the second method: keep the data elements in an array. split the array into pairs using this SO thread: Then iterate through each element of the array (each one should be a sub-array) and if the average is either less that 68% of the general average of all the elements or greater than 168% of the general average, then store that in a new array and that will be the outliers list. I'm not sure what you're program is since it just says "Uploading java.docx", etc. but if it's an integer counter then i would suggest using modular operations. try using the new formatting style in your print statements, which makes it easier to read (in my opinion). i.e. - print("The maximum possible value is {}".format(max_val)) Perhaps you could try animations, or making something along the lines of a car sim (driving a block around). Of course, you could always try responsive web designing. I've always wanted to do a physics simulator but I haven't gotten the time yet. :\ houseType is now a c++ set right s is a type string, bed is type int, etc. etc. doubles are a type which can accommodate up to around like 15-16 digits (ask me if you need more clarification) what's the issue? what's the issue? Very nice! Although you may want to experiment with adjusting the map size if the given window is too small, but that would require the use of a GUI or web browser client def sum2(n1, n2): return int(n1)+int(n2) I'm not sure if this is your cs course hw but I'd suggest trying it yourself first. Anyway, here's the function: def replaceCharAtPos(s, i): if i > (len(s)-1): return s s = list(s) s[i] = str(i) return ''.join(s) 1) Repl.it lists python3 as just "python" in the dropdown menu 2) No it is not, at least in python you're missing parenthesises if you're talking about LSHIFT, this would be it in Python: def lshift(x, am): if am >= 8: return "00000000" return (x[am:]).ljust(8, "0") There may be better ways to do it, but that was the quickest way I could think of. come up with your own project that branches off standard info you'll learn more from experience and researching after you know the basics you iterate through a certain number of times (the most simple for loop) basically you run the code inside the for loop for the amount specified. also im not trying to be rude or anything but you're pretty wrong about them being confusing in python, if you've seen loops in other languages use
https://repl.it/@JoshDaBosh?tab=comments
CC-MAIN-2019-39
refinedweb
710
66.98
hey ^^ Well, I got a hold of Borland C++ Builder 6 trial, so it's all good now I guess. However my friend still wants me to use TurboC++ 3.01 for DOS, so if you know how to make TLINK.EXE work correctly, or what are the environment variables to configure so it works, I would be very, very glad .. Anyways, this is not just advertisement... >_>;; as I didn't want to lose time waiting for a solution to my TC++ problem, I'm trying with BC++ 6 trial, and got this far: I need to read two files, compare strings between the two, and if there needs something to be replaced, write it in output.txt, along with the unchanged stuff.I need to read two files, compare strings between the two, and if there needs something to be replaced, write it in output.txt, along with the unchanged stuff.Code:#include <iostream.h> #include <fstream.h> #include <string.h> using namespace std; /*********************************************************************** ************************************************************************ ***********************************************************************/ int main() { string LineNEW, LineOLD; int line; ifstream esp ("new.txt", ios::in); ifstream old ("old.txt", ios::in); ofstream to ("output.txt", ios::out); if (!esp.is_open()){ cout << "Error loading new.txt\n"; getchar(); return 0; } if (!old.is_open()){ cout << "Error loading old.txt\n"; getchar(); return 0; } if (!to.is_open()){ cout << "Error creating output.txt\n"; getchar(); return 0; } while (! esp.eof()) { line += 1; getline (esp, LineNEW); getline (old, LineOLD); cout << "New: " << LineaESP << endl; cout << "Old: " << LineaOLD << endl << endl; } cout << "Finished."; esp.close();old.close();to.close(); getchar(); return 0; } I would like to know if it's possible to move the read pointer to the previous/next line, or to a specific one, instead of abstract positions I get when using tellg() and seekg()... or how to read/write files using LINES instead of pointers and positions and all that "detailed small stuff". And, if it's possible, to have an independent position between New and Old, so like, if Line #2 in New does not match Line #2 in Old, move to the next line in Old so it matches Line #2 in New... that's for avoiding line breaks and such (the two files have the same structure, though sometimes they're separated with more than one line break, so I'd like to manually handle that).
http://cboard.cprogramming.com/cplusplus-programming/79316-reading-line-line-two-files-but-different-line-positions.html
CC-MAIN-2014-10
refinedweb
388
74.9
veth — Virtual Ethernet Device Description The veth devices are virtual Ethernet devices. They can act as tunnels between network namespaces to create a bridge to a physical network device in another namespace, but can also be used as standalone network devices. veth devices are always created in interconnected pairs. A pair can be created using the command: # ip link add <p1-name> type veth peer name <p2-name> In the above, p1-name and p2-name are the names assigned to the two connected end points. Packets transmitted on one device in the pair are immediately received on the other device. When either devices is down the link state of the pair is down. veth device pairs are useful for combining the network facilities of the kernel together in interesting ways. A particularly interesting use case is to place one end of a veth pair in one network namespace and the other end in another network namespace, thus allowing communication between network namespaces. To do this, one first creates the veth device as above and then moves one side of the pair to the other namespace: # ip link set <p2-name> netns <p2-namespace> ethtool(8) can be used to find the peer of a veth network interface, using commands something like: # ip link add ve_A type veth peer name ve_B # Create veth pair # ethtool -S ve_A # Discover interface index of peer NIC statistics: peer_ifindex: 16 # ip link | grep '^16:' # Look up interface 16: ve_B@ve_A: <BROADCAST,MULTICAST,M-DOWN> mtu 1500 qdisc ... See Also clone(2), network_namespaces(7), ip(8), ip-link(8), ip-netns(8) Colophon This page is part of release 5.04 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. Referenced By network_namespaces(7), slirp4netns(1).
https://dashdash.io/4/veth
CC-MAIN-2020-40
refinedweb
308
57.61
I think it would be better to have IndexReaderProperties, and IndexWriterProperties. Just seems an easier API for maintenance. It is more logical, as it keeps related items together. On Nov 8, 2007, at 12:04 PM, Doug Cutting wrote: > Michael McCandless wrote: >> One thing is: I'd prefer to not use system property for this, since >> it's so global, but I'm not sure how to better do it. > > I agree. That was the quick-and-dirty hack. Ideally it should be > a method on IndexReader. I can think of two ways to do that: > > 1. Add a generic method like IndexReader#setProperty(String,String). > 2. Add a specific method like IndexReader#setTermIndexDivisor(int). > > I slightly prefer the former, as it permits various IndexReaders > implementations to support arbitrary properties, at the expense of > being untyped, but that might be overkill. Thoughts? > >> We can't add a "setIndexDivisor(...)" method because the terms are >> already loading (consuming too much ram) during the ctor. > > Aren't indexes loaded lazily? That's an important optimization for > merging, no? For performance reasons, opening an IndexReader > shouldn't do much more than open files. However, if we build a > more generic mechanism, we should not rely on that. > >> What if, instead, we passed down a Properties instance to IndexReader >> ctors? Or alternatively a dedicated class, eg, >> "IndexReaderInitParameters"? The advantage of a dedicated class is >> it's strongly typed at compile time, and, you could put things in >> there like an optional DeletionPolicy instance as well. I think >> there >> are a growing list of these sorts of "advanced optional parameters >> used during init" that could be handled with such an approach? > > (I probably should have read your entire message before starting to > respond... But it's nice to see that we think alike!) This is > similar to my (2) approach, but attempts to solve the typing issue, > although I'm not sure how... > > The way we handle it in Hadoop is to pass around a <String,String> > map in the abstract kernel, then have concrete implementation > classes provide static methods that access it. So this might look > something like: > > public class LuceneProperties extends Properties { > // utility methods to handle conversion of values to and from > Strings > void setInt(String prop, int value); > int getInt(String prop); > void setClass(String prop, Class value); > Class getClass(String prop); > Object newInstance(String prop) > ... > } > > public class SegmentReaderProperties { > private static final String DIVISOR_PROP = > "org.apache.lucene.index.SegmentReader.divisor"; > public static setTermIndexDivisor(LuceneProperties props, int i) { > props.setInt(DIVISOR_PROP, i); > } > } > > Then the IndexReader constructor methods could accept a > LuceneProperties. No point in making this IndexReader specific, > since it might be useful for, e.g., IndexWriter, Searchers, > Directories, etc. > > An advantage of a <String,String> map over a <String,Object> map > for Hadoop is that it's trivial to serialize. > > Is this what you had in mind? > >
http://mail-archives.apache.org/mod_mbox/lucene-dev/200711.mbox/%3C5EBAA21C-E4DA-40EC-AA50-CDD0482B2AA9@ix.netcom.com%3E
CC-MAIN-2017-04
refinedweb
474
57.57
Looking at some of the answers in the Unity forums and Q&A site, the answers for how to make an invisible button do not work because taking away the image affiliated with the button makes it not work. How do you get around this and keep the invisible property while allowing the button to actually work? This is one of those weird things about Unity - 100% of real-world projects need this, but they just forgot to do it. For anyone who can't be bothered reading, here's a short version of Touchable.cs to copy-paste, which you need in every Unity project: // file Touchable.cs using UnityEngine; using UnityEngine.UI; #if UNITY_EDITOR using UnityEditor; [CustomEditor(typeof(Touchable))] public class Touchable_Editor : Editor { public override void OnInspectorGUI(){} } #endif public class Touchable:Text { protected override void Awake() { base.Awake();} } Use unity's 'Create Button' function That function gives you a Text component and Image component as a convenience. Delete them both. Drop this script Touchable.cs on the Button You are done. It cannot "decay" with Unity upgrades. As a bonus, "buttonize" ANYTHING in .UI by dropping Touchable on it. Short technical explanation: In short, Unity forgot to, or chose not to, have a "touchable" concept in the OO chain for things like images that are, well, "touchable". Essentially, this means us developers have to (one way or another) make our own Touchable class for Unity - which is a classic "backfilling" OO situation. When "backfilling" the overall issue is that it must be perfectly auto-maintaining. Fortunately there seems to be one good solution, which is what everyone now uses. Long-winded explanation: Quite simply, when you click to add a "Button" in Unity, it gives you by default both an Image and a Text with the Button. The reason Unity did this is that Unity is made to be used by 8 year olds ;-) In any real-world project you instantly delete the Image and Text and "do it yourself". And you often/always need a transparent button. Button of course does nothing unless it has a component which is touchable attached. However: Unity did not make a touchable concept in the OO chain: they chose to not abstract-out that quality from touchable things. However, you need a "Touchable" concept in every Unity project, for transparent buttons and many other uses. So just, keep Touchable.cs in all your Unity projects. Click to create a button using the Editor convenience function, but delete the childish "Text" and "Image" components. Drop Touchable.cs on to the button. Voilà, the button is now an actual (transparent) button that works. If you're a badass, feel free to experiment with different ways to create a Touchable.cs (perhaps starting with :Graphic), but this ingenious approach, which everyone now uses, seems to be best. Historic credit: it's unclear but I believe Unity forum user "signalZak" was the first to think this out. If it really matters to you (or perhaps if your team has inexperienced members), make an editor function called "Create actually useful button" which just gives you a Button + Touchable.cs, versus Unity's default "create Button" function. (You almost always set Transition and Navigation off, so, you may want to do that as well for tidyness and convenience.) That's it. So a "grown-up" button in Unity looks like this: You have Unity's Button (which is a magnificent piece of engineering, per se) and you have Touchable. An interesting point is, with buttons very often you want them underneath the actual UI elements. Example - you have a complex panel system that expands and has small separate parts. Amazingly, just drop one of our "better buttons" underneath the final elements after you do all the layout work. Just set the Button+Touchable to expands to fill the parent - so easy. In the image there, the things like "resume" and "quit" could be ridiculously complicated anythings .. weirdly sizing panels; things that may or may not be there at different times; dynamic content; frickin' animations; actual mere "sizer" objects that bring up something on an different camera: whatever. In all cases, you merely drop a "real" unity button (ie, Button+Touchable, as in the image above), you just drop that underneath the "complicated thing" and you have a spectacularly reliable button. This has a number of major advantages. Apart from anything else you can for example easily make the actual finger-working button a bit bigger than the graphical element (as you often do with small buttons), and so on. In many situations it's tremendously clearer if you simply think of a button as something you "drop on top of" anything at all, and hence "buttonize" that thing. You do just that with "Button+Touchable" buttons as in the top image. Cheers
https://codedump.io/share/u8zCJd84XAw4/1/how-to-make-an-invisible-transparent-button-work
CC-MAIN-2018-22
refinedweb
805
63.29
hi, I have problems for understanding some classes definitions in Lucene (see the end of this e-mail for the source code). A class "FilterIndexReader" is defined at 1. Then "FilterTermDocs" is defined as a nested static class at 2. At 3, public FilterTermDocs(TermDocs in) is a constructor. What I am not understand are as follows: 1. Now that FilterTermDocs is a static class, then why it has a constructor at 3? 2. Why we can use (TermDocs in) for the constructor at 3? Here "TermDocs" is an interface, does that mean "in" is an object of "TermDocs"? Thanks in advance for your help! Best, Shengli 1 public class FilterIndexReader extends IndexReader { /** Base class for filtering {@link TermDocs} implementations. */ 2 public static class FilterTermDocs implements TermDocs {3 protected TermDocs in; 3 public FilterTermDocs(TermDocs in) { this.in = in; } ............... --------------------------------------------------------------------- To unsubscribe, e-mail: lucene-user-unsubscribe@jakarta.apache.org For additional commands, e-mail: lucene-user-help@jakarta.apache.org
http://mail-archives.apache.org/mod_mbox/lucene-java-user/200312.mbox/%3C200312051522.hB5FMN9p021096@ramsay.cis.strath.ac.uk%3E
CC-MAIN-2016-22
refinedweb
160
60.21
Anyone). XBRL comes. I've touched on XBRL earlier in this column, in "A glimpse into XML in the financial services industry" (see Resources for a link to this article). Since then, the specification has gained in importance, especially with all the interest in transparency of corporate reporting, and its connection to financial services. In this article, I take a close look at the XBRL format to give developers a feel for the key constructs. XBRL in its natural habitat Typical usage of XBRL has several aspects. XBRL documents rise on a foundation of semantics organized into taxonomies and other metadata, using XLink. These taxonomies are the mechanism for semantic transparency in XBRL, referencing industry and global financial reporting standards, including one maintained by XII itself—Global Ledger Framework. The reports are instance documents incorporating these semantics, conveying financial information (business facts in XBRL parlance) in a carefully controlled context. The context is an unambiguous reference to, for example, the company or individual to whom a business fact pertains, relevant units of measure, dates and times, any related facts, references to definitions in taxonomies, and any other metadata that makes clear the nuances of the facts reported in an XBRL instance. Rather than a toy example of a report, I decided to go with something meaty. I'll use an excerpt from the IBM® 10-Q report to the SEC for the third fiscal quarter of 2008. An overall SEC filing as uploaded to their EDGAR system is a public-key infrastructure (PKI) signature block containing an SGML document which contains both HTML and XBRL versions of the report, as illustrated in Figure 1. Figure 1. Structure of an SEC filing In the report I examined, there are 7 text sections, one of HTML and 6 of XBRL. Each has a file name, specified in the FILENAME element. In effect, this is an archived file format, not unlike UNIX™ TAR, or ZIP without the compression. Table 1 is a summary of these embedded documents. Table 1. Embedded sections of IBM's Q3 10-Q filing Listing 1 is an excerpt from ibm-20081028.xml, one of the embedded XBRL files, and the one representing the main report. Listing 1. Main business facts XBRL from IBM 10-Q filing The first section includes constructs to set the business context. It's all very well to express the business fact "net revenue from sales of services is $14,773,000,000", but it's next to meaningless without basic context. Is that for an entire year, or for a quarter, or for a week? Is it for a quarter in 1968 or in 2008 (because of inflation, that makes an enormous difference)? For my small consulting company such a revenue figure would be astonishing, but of course the context here is that it's for IBM. XBRL provides the tools to establish all this context for business facts. The first two xbrli:context elements establish temporal context used for business facts— D-20073Q, meaning the third quarter of fiscal 2007 and D-20083Q, meaning the third quarter of fiscal 2008. These two periods are used to provide year-over-year comparisons, which are very important in financial analysis. A net revenue figure of $15 billion might be good if the figure for the corresponding period in the prior year was $10 billion, and might be bad compared to $20 billion. The next two xbrli:context elements define units of measure. One is bog simple—just a count of shares, but even the simple things are often contextualized to a very fine degree. You don't want a sharp operator manipulating the definition of shares in the cause of a deceitful report, so the standard XBRL taxonomy itself provides a definition of a unit of shares. The other unit is the US Dollar, as defined in ISO 4217, the international standard describing three-letter currency codes ("USD" for the US Dollar). The unit in this case is specialized to express that values are rounded to the nearest million. It's called "USD-DecimalMinus6" because it is equivalent to multiplying the value by 10 to the power -6, removing the fractional portion, and then restoring the multiplier. Again, XBRL allows reporters and analysts to take pains to clarify such details. Then come the business facts themselves, and here you can learn all you like about IBM's financial performance. For example, the company had 1,343,457,986 outstanding shares, and net revenue from sales of services of $14,773,000,000 in the third quarter of fiscal 2008, compared to $13,657,000,000 for the same period in 2007, a year-over-year gain of $116,000,000. Listing 1 is a pretty small excerpt from the report, which lists a huge number of business facts. Notice the use of namespace referring to the XBRL representation of U.S. generally accepted accounting principles (GAAP), which look to place accounting statements on an even footing nationwide, and to provide a basis for international standardization. Even more details—the taxonomies You've had a glimpse at the attention given to business context in XBRL, but the bits in Listing 1 are the merest fraction of it all. The real microscopic (and dull) detail that anchors the business facts spills over into the taxonomies, which are 3 of the 7 files in the filing. I'll focus on the taxonomy files focusing on reference and labels. Listing 2 is an excerpt from ibm-20081028_def.xml, which provides links to formal definitions of terms. Listing 2. Excerpt from taxonomy of definitions for IBM 10-Q filing I've snipped a lot of the indirection and the more esoteric ways taxonomy links are expressed. To meet formatting restrictions I also had to modify some long attribute values, in some cases by replacing the string "us-gaap/1.0" with "(USG)", and in some cases abbreviating the string "dei-2008-03-31.xsd" to "(XSD)". What's left should give you the basic idea. Within the linkbase the top links ( roleRef elements) provide definitions relevant to the entire report. Definitions referring to specific aspects of the report are expressed in following definitionLink elements. XBRL exercises some of the more complex aspects of XLink, the W3C standard for creating hyperlinks in XML. The most important thing you have to remember about XLink when working with XBRL is that a link can occur on any element, unlike, say, HTML where links are expressed through a or link elements. XBRL does define standard linking elements such as roleRef loc definitionArc, but publishers have a lot of flexibility with links. IBM uses a lot of specialized constructs, which is why it includes an XML schema in its filing to define these constructs. The definitionLink xlink:type="extended" indicates that it is a complex type of XLink, which, among other features, can express a link with multiple arcs, and can do so "out of band", meaning it can patch on a link from the linkbase to a completely separate XML element (in this case to elements in the core XBRL report). IBM has assigned a role to this extended link in its entirety, xlink:role="", which expresses that this taxonomy serves a statement of earnings, as defined by IBM (traversing this URL you're redirected to the IBM home page, but this fact is incidental). To get the idea of an extended link with many arcs, think of a link from a download site with mirrors. Conceptually it's just one link to the software you want, but in practice there are many possible resources from which you can get it, and each of these is a separate arc. To express these multiple arcs, you give the end-points "marks" or "labels", using an element of XLink type "locator". The actual arcs are defined in elements with xlink:type="arc", which include xlink:from and xlink:to elements specifying the end-points as marks. In the following code, I extracted one coherent extended link example further from Listing 2: This, in short, expresses that the common shares outstanding fact is in the domain of entity information line items, an expression made formal by links to definitions in XBRL taxonomy Web resources. No doubt about it—this stuff is complex. The news recently has been full of comments about how complicated financial instruments can be, and things don't get much easier when you deal with huge, multi-national companies, nor even when you deal with smaller firms. The idea of XBRL is not to hide the complexity, but rather to lay it all out on the table, so that it's at least accessible and transparent. The basic mechanism of the XML in XBRL, most of which I've touched on in this article, takes hours to learn, but creating and analyzing the format in regular business requires a lot of financial as well as technical expertise. I mentioned the coming mandates for XBRL usage in U.S. filings. Such mandates are spreading, not just in securities systems across the world, but also in smaller scopes, such as for internal corporate reporting at the departmental level. It will also likely spread with wider, regulated reporting requirements, such as for tax, labor and environmental impact reports. XBRL might soon be one of the most important XML formats in business, and I hope this article gave you the first foothold towards processing it. Learn - Thinking XML: A glimpse into XML in the financial services industry (Uche Ogbuji, developerWorks, February 2004): Briefly touch on several XML formats in financial services, including XBRL. - The XBRL home page: Bookmark the source for specifications (including the 2.1 recommendation), news, references to related projects, and much more. The Wikipedia page includes a brief example. - Filing financial statements in XBRL: How-to, lessons learned, and best practices (David Newman, Dean Ritz, and Murali Vridhachalam; developerWorks November, 2008): Cover a lot of less technical detail on XBRL, including tools to help generate the XML. - The move to IFRS and XBRL ( Leslie Satenstein, The TEC Blog, December 2008): Read an excellent summary of the rise of XBRL. - ISO 4217: Learn more about the international standard for currency codes. - Tip: How to use XLink with XML (Brett McLaughlin developerWorks July, 2001): Take a first look at XLink and how it works for basic links or for embedding external resources. - The Electronic Data-Gathering, Analysis, and Retrieval (EDGAR) system: Read about the required format and database for filing with the U.S. Securities and Exchange Commission (SEC). - The EDGAR XBRL listing page: Keep up with SEC filings that include XBRL, and in particular, check out the IBM 10-Q filing used as an example in this article. - U.S. generally accepted accounting principles (GAAP): Review the standard for accounting statements in the U.S. - IBM XML certification: Find out how you can become an IBM-Certified Developer in XML and related technologies. - XML technical library: See the developerWorks XML Zone for a wide range of technical articles and tips, tutorials, standards, and IBM Redbooks. - "New to XML" page: Check out the XML zone's updated resource central for XML. Readers of this column might be too advanced for this page, but it's a great place to get your colleagues started. All XML developers can benefit from the XML zone's coverage of many XML standards. - developerWorks XML zone: Find more XML resources, including previous installments of the Thinking XML column. If you have comments on this article, or any others in this column please post them on the Thinking XML forum. - The developerWorks Web development zone: Expand your site development skills with articles and tutorials that specialize in Web technologies, including previous installments of this column. -..
http://www.ibm.com/developerworks/library/x-think43/
crawl-002
refinedweb
1,963
50.06
Hi Folks, In the first Part, I discussed about the fundamentals of Kinect hardware as well as technical details of the camera & microphone array. Today in this part of my “Programming with Kinect” series I am going to guide you about how to setup the development environment for Kinect and writing code to get started with development using Kinect. Note: I’ll be using “Kinect for Xbox 360” hardware with “Kinect for Windows SDK” in my posts until & unless I am not using specific features of Kinect for Windows hardware. Installation of SDK The Kinect SDK is a development toolkit that allows software developers to build applications using Kinect and expand the possibilities of application and user experience. Kinect Software development kit (SDK) provides interface to interact with Camera, Motors, Microphone array etc. It allows user to build applications through Visual C#, Visual Basic.Net and C++ language using Microsoft Visual Studio IDE. Recent release of Kinect SDK (1.6) supports Visual Studio 2012 and Windows 8. Prerequisites Before you begin with the installation, make sure you have the following components - Microsoft Kinect Sensor - USB cable of Kinect Sensor. Make sure your Kinect sensor is unplugged and previous SDK of Kinect (if any) is uninstalled properly. Installation The installation procedure is very simple and wizard base. - Go to Kinect for Windows developer’s page and download the latest SDK (v1.6) and Kinect Developer toolkit (I’ll discuss about it later). - Install the SDK you just downloaded. - After that Install the Kinect Toolkit. After successful installation of both setup files you just downloaded, it’s time to connect the Kinect sensor with your PC. Plug in your Kinect sensor with you PC and wait till the Windows install its driver. Note: You may skip the “Searching Driver on Windows Update” part by clicking “Skip obtaining driver from Windows Update” while Windows is installing the driver. It will expedite the installation process and use the driver files that comes with the SDK you just downloaded. Following components will be available after successful installation of Kinect SDK. - Kinect Developer Browser. - Kinect Studio. - Kinect Drivers. - Kinect Runtime. - Kinect Speech Recognition Language Pack (en-US). Kinect for Windows Architecture Below is the architecture diagram of Kinect for Windows, You can access Kinect microphones array using your standard audio API. I am not going to discuss this in details, but just for a quick view, we have - Kinect Sensor (Physical Kinect Hardware) - Kinect Driver - Audio & Video Components - Direct X Media Object - Kinect API More information regarding architecture can be found at Development Using Kinect After we have our environment ready for software development using Kinect, let’s move towards using Kinect in our Project. I’ll be using Windows Presentation Foundation (WPF) application type throughout my demos, but you can also use Win-Forms with Kinect. Go ahead and start your Visual Studio. - Create a new WPF Application and name it appropriately (in my case it’s UmerKinectBlogDemo1). - Add “References” of “Microsoft.Kinect” by right clicking on References folder in solution explorer and click “Add Reference”. - Expand the “Assemblies” list on your left and select “Extensions”. - Scroll down until you find “Microsoft.Kinect”, apply check on that and click OK. After adding Kinect reference; - In your XAML code, add the following attribute in your Window markup code. - Drag/Insert an Image Control from the Toolbox into your application, name & resize it appropriately as this image control will be used for showing the camera feeds from Kinect. - Go to your Code Behind file of Main page (MainWindows.xaml.cs) and add the following namespaces into your code behind file using Microsoft.Kinect; using System.Windows.Media.Imaging; - Create a global reference of “KinectSensor” class, this will hold the instance of our connected Kinect sensor - In your MainWindow_Loaded method, fetch the connected Kinect sensor object using the following code; { if (KinectSensor.KinectSensors[0].Status == KinectStatus.Connected) myKinectSensor = KinectSensor.KinectSensors[0]; else MessageBox.Show(“Kinect sensor is not yet ready”); } else MessageBox.Show(“Kinect sensor is not connected”); The “KinectSensors” collection holds all the connected Kinect sensor to the machine, since we have only one sensor connected to our machine, we are directly fetching the one at “zero” index. I am also doing a little error handling that if the status of the connected sensor is not ready, notify the user. Note: For better experience, you should use StatusChanged event of KinectSensors Collection. Getting RGB (Color Camera Stream) The color stream from Kinect sensor can be used to display the camera view of Kinect and you can also use the same stream to apply different Image Processing algorithms to achieve your specific output. Kinect provides different resolutions and Formats for Color stream and you can select the one that best suits your need. Now as we have our Kinect sensor object, let’s move and add an event handler of “ColorFrameReady” and start the “ColorStream” of our Kinect sensor to get the Color Stream from Kinect. myKinectSensor.ColorFrameReady += myKinectSensor_ColorFrameReady; myKinectSensor.ColorStream.Enable(ColorImageFormat.RgbResolution640x480Fps30); The “ColorFrameReady” event handler is used to handle the RGB images coming from our Kinect Sensor. We have the option to enable specified Video Stream (i.e. RGB, depth data etc.) in Kinect; for instance we are enabling the Color Stream and defining the Image Format of the stream in parameter. Kinect supports different image formats including “RGB” and “YUV” and with different FPS (frame per second) and resolutions as well. We are using RGB Format of 640X480 resolution with 30 FPS. (Ideal FPS is 30, lower FPS results in slow image propagation). - Insert the following code snippet into your ColorFrameReady event handler. void myKinectSensor_ColorFrameReady(object sender, ColorImageFrameReadyEventArgs e) { using (ColorImageFrame es = e.OpenColorImageFrame()) { if (!(es == null)) { byte[] bits = new byte[es.PixelDataLength]; es.CopyPixelDataTo(bits); image1.Source = BitmapSource.Create(es.Width, es.Height, 96, 96,PixelFormats.Bgr32, null, bits, es.Width * es.BytesPerPixel); } } } The image data is encapsulated in ColorImageFrame, we have to copy the image data into array of byte to use it, the “PixelDataLength” property of that ColorImageFrame has the length of pixel data buffer of the current frame. After that we have to create a bitmap image from the byte array (image data) so that can show it in our Image Control. BitmapSource.Create method is used to do that, the parameters of the methods are; - pixelWidth: The width of the bitmap. - pixelHeight: The height of the bitmap. - dpiX: The horizontal dots per inch (dpi) of the bitmap. - dpiY: The vertical dots per inch (dpi) of the bitmap. - pixelFormat: The pixel format of the bitmap. (BGR, CMYK, Black etc) - Palette: The palette of the bitmap. - Pixels: An array of bytes that represents the content of a bitmap image. - Stride: The stride of the bitmap. (Number of bytes allocated for one scan line of the bitmap). After we create a bitmap image, assign that bitmap image object as the “Source” of Image Control we added in previous step. Let the show begin Our minimum code to display the camera stream from Kinect sensor is almost complete. Before we run our project, there is one that that we need to do. We have to start the Kinect itself so that we can get the streams from the Kinect; to do that, add the following line at the end of your MainWindow_Loaded method. myKinectSensor.Start(); Now run the project by pressing F5 to see the results. Here is the result of my Kinect sensor. It is my table where most of my stuff is found (I am bad at organizing stuff on my table 🙂 ) Summary In this post, I’ve discussed the installation procedure, interfacing Kinect with our application and getting Color stream from the Kinect camera. Don’t forget to do proper exception handling into your project, especially with KinectSensor object. The complete project for your reference can be found here. What’s next? In my next post, I’ll be discussing about - Skeleton Tracking And more. If you have any suggestions on topics, have questions, feedback or want to help me out, feel free to contact me by posting your comments below this post and I’ll try to help you out! Nice post , specially for beginners 🙂 Excellent. A Good initiative from Microsoft but please try to post more frequently. Nice way to teach about Kinect in Pakistan, Umer, Keep it up. nice …… much help me to understand kinect sensor Can u teach me how to create an application Sign Language for Kinect ? Excellent It iz really really very helpful tutorial… Bundle of Thanx…………………….. excellent, got me up and running with my first program, thanks Helping tutorial for me as a beginner……….thank you Umer Hi bro, did you also work with the Kinect V2? Thanks for this blog is very useful i want to read again and again… hi… your article was useful for beginner like me. but why I couldnt find this method in my visual studio? KinectSensor.KinectSensors.Count i use vs express 2015 and kinect sdk 2.0 , kinect sensor version 2 hello there, i can see several examples on the internet ,but thats for 1.6 sdk can u please write function just which can convert ColorFrame to Bitmap ? i am having problem while copying bytes data of Raw image in to a byte array , it crashes(gets out of thread) everytime for no reason !!!
https://blogs.msdn.microsoft.com/pakistan/2013/02/03/part-2-getting-started-with-microsoft-kinect/
CC-MAIN-2016-44
refinedweb
1,559
55.64
Graphics Software - Capture - Graphics Conversion - Editors - 3D Modeling - 3D Rendering - Presentation - Viewers - Image Galleries - Animation2 weekly downloads SignWriting Apps Applications that use and display SignWriting symbols. Applications are based on a library of common operations instead of recreating the same logic for each app. The library is built on the portable wxWindows cross-platform application framework.0 Dx3 - A Robots World Project files for the first series out of Dx3 Media - A Robots World, this project will contain: Story, Plot, Script, Models/Riggs, and details about what is in the works, and other updates on the project.0 weekly downloads Perl OpenGL The Perl OpenGL module provides bindings to the OpenGL API for use from the perl language.4 weekly downloads WPF Media Tagger Create tags for your media files. Define Start/End time and additional information for each media tag. Later, you can play the tags using an embedded media player PDF::Create PDF::Create is a Perl module that allows you to create PDF documents, possibly on the fly, using a large number of primitives.1 weekly downloads Camera Life Run your own photo website. Camera Life is PHP software you can run to show your photos on your own website. Camera Life is easy to setup and customize if want to blend it in with the rest of your site.13 weekly downloads aalib-perl Aalib-perl is a Perl binding for the AA-Lib, an ascii-art gfx library Image Mover A java program to move images from a directory to one among a list of other directories. Provide also limited "slideshow" functions.6 weekly downloads GraphViz::DBI1 weekly downloads PhotoShelf Web based digital photo archiving and management system, written entirely in perl. Complete with almost all features necessary for backup and public viewing.1 weekly downloads Milkman 3D Microsoft Visual C++ 6 code for a 3D renderer for Milkshape 3D Shell Controls Lib A set of classes to browse the Windows Shell namespace0 Spider Eyeballs Spider Eyeballs is an image gallery website generator. It's intent is to make it easy to create and modify websites while providing a clean web interface for easy browsing. See a demo at weekly downloads ParticleLIB A fast, free, good looking particle system for use in any project Allegro can be used in. Currently works with DJGPP and Allegro under DOS.1 weekly downloads OddButton Demonstration of an almost undocumented technique to let the owner-draw buttons have the default state, just like standard buttons.1 weekly downloads
http://sourceforge.net/directory/graphics/license%3Aartistic/?sort=rating
CC-MAIN-2014-41
refinedweb
419
52.19
This action might not be possible to undo. Are you sure you want to continue? int x=7; cout << "Value of x is: " << x << "\n"; x = 2; // Note that after a variable has been declared // you never put its data type in front! cout << "Value of x is: " << x << "\n"; Another example; int seconds_in_hour = 3600; int hours_in_day = 24; int seconds_in_day = seconds_in_hour * hours_in_day; Note how we are using other variables to initialize seconds_in_day variable. The variable whose value is changing is always on the left. The value that it is being set to is defined by the stuff on the right. The x on the right is the new x. The old value of x will be used on the left. Hence this expression reads like: x=3+2; and value of x will be 5. #include <iostream> using namespace std; int main() { int count; double total; cout << "How many pennies do you have? "; cin >> count; total = count * 0.01; cout << "How many nickels do you have? "; cin >> count; total = count * 0.05 + total; cout << "How many quarters do you have? "; cin >> count; total = count * 0.25 + total; cout << "Total value of your coins is: " << total << "\n"; return 0; } Make sure your data type matches the variable type: double total; total = "Hello!"; // Error because a string cannot be //converted to a double This declaration is ok: double total = count * 0.01; 3. We say we are incrementing x. const double PI = 3. Syntax: const type var_name = value. This means new value of variable x will be the old value plus 1. use a constant declaration. The compiler will give an error if your code tries to change a constant.8. Can be written x *=8. We have already seen assignments like: x = x + 1.05 + total. If you have an important number that you need to use in your code.This is not: double total = count * 0. This helps you catch errors. Never “hard code” numbers into your program. If your value always stays the same. double decimal=1. If you ever want to change your code and modify the value (Maybe you want more decimal accuracy for PI) of your constant you need to only change one line of code Once a variable has been declared constant its value cannot be changed. // This is wrong! With the above lines you might get away with a warning. or x = x * 8. There are other shortcuts as well x = x – 7.8. //This is super wrong! You cannot change a variables data type. assign its value to a variable and then use the variable in place of the number. or even x = x/2. but double decimal=0. . //Error The second line is an error because you cannot use the variable you are declaring in its definition! We only need to declare a variable once! double decimal=0. eg.14159. int decimal =1. x -= 7. Anyone reading your code will understand your constant variable better. You can do x+=12347834. Programmers are lazy (and this types of assignments come up often) Shorthand: x+=1. They increase the value of x by one. cout << x. or ++x. you have to think of the line cout << x++. as two separate lines: cout << x. // Value of x is now 2 The difference only comes out when you combine the increment with another command. When using pre increment the incrementing happens before the command. These are both equivalent to x = x – 1. cout << x. int x=0. Both increment x by one. // Value of x is now 1 ++x. . int x=0. * Multiplication x = 5*y. x++. cout << x++. . If you have two lines ++x. x++.Subtraction x = -2-y. When using post increment the incrementing happens after the command. Of course there has to be x--. / Division x=7/8. but we'll talk about it in a bit. Both do exactly same thing. and x++. There is a subtle difference. cout << ++x. and --x. Back to the first example: x = x + 1. ++x. Basic operators are: + Addition x = 7 + 8. This is same as x += 1. But this comes up so often that programmers have even shorter notation: x++. is called pre increment and x++ is called post increment. There is no difference.x /=2. 5 But what if you have variables? int a=5. Arithmetic expressions are always evaluated from left to right using our normal rules for precedence. // output 2.0 or 3/2. . You CANNOT write (x + z)y for (x + z)*y as in a math class You CANNOT use ^ for power. This is called implicit casting. cout << a/b.0/2. Good code generates no warnings when we compile. Any odd number % 2 is 1. r=3/2.g. e.0. // What is value of r? It is 1 and NOT 1. cout << 5/2. // compiler will give a warning but not an error. // evaluates as 1.0/2.0. As long as one of the numbers is a double we have a double division Best have all numbers same type to elimate confusion double r. we have to change the type.5.0/2 or 3. use x*x*x instead of pow function which we meet later.5 But note: int a. // output is 2 Both 5 and 2 are integers so the expression evaluates as an integer division.0/2. a=5. int a. So if you want a double then you should have: cout << 5/2.6. r=3. 3. a=3. C++ can automatically convert types into other types.0.0 all evaluate as doubles. // a has value 1. Highest precedence ( ) Anything in parenthesis will be evaluated first Normal precedence * / % Low Precedence + Division in C++ is bit strange: double r. % is the remainder operator (also called mod operator). 7%3 is 1 8%5 is 3 Important special case: Any even number % 2 is 0.% Mod x = 6%2. int b=2. x^3 is NOT allowed. cout << (double)(a)/b. int boxes_needed. cin >> amount. Consider the following three cases: double y = 9. Each day the baker packs the donuts into boxes and brings the left over donuts home. • Given an integer seconds.7. boxes_needed = amount / 12. Varaible a is NOT permanently changed to a double. A box for donuts holds 12 donuts. • Avoid "magic numbers" in your code. He decides to write a C++ program that allows him to calculate for a given amount of donuts how many boxes he will need and how many donuts he will have left over. Note this is only temporary change of data type used in evaluation of an expression.y) Exponential. int hours = seconds / SECONDS_PER_HOUR. • Given an integer seconds. . like those used for conversions. Variables type cannot be permanently changed. To do more complicated mathematical equations you need the cmath library: #include <cmath> If you include this file you get to use your favorite functions including: square root of x . Lets see why this works. int left_over.4. const int SECONDS_PER_HOUR = 3600. int amount. • We want important fixed quantities.5 to the number you are trying to round and then cast the result temporarily as an integer. e to the power of x – exp(x) cos or sin x – cos(x). y = sqrt(x).5). double x = (int)(y +0. cout << "You will need " << boxes_needed << " boxes" << " and you will have " << left_over << "many donuts left over". sin(x) double x=0. double hours = (double) seconds / SECONDS_PER_HOUR. convert to the number of hours (with the decimal) . cout << "How many donuts are there?".sqrt(x) Raise x to power of y – pow (x. left_over = amount % 12. double y. Easy way to round is to use a little trick Add 0. to be constants. What happens if you write cout << (double)(a/b). determine how many hours have passed (want a whole number) . alternatively cout << (double)a/b. 5 is 10. 9.7 + .5).9 the cast to integer will truncate it to 9 then the assignment gives x value 9. double x = (int)(y +0.5).0 double y = 9.5 is 10.0 .7.5. double x = (int)(y +0.0 double y = 9.5 + .2 the cast to integer will truncate it to 10 then the assignment gives x value 10.0 the cast to integer will make it 10 then the assignment gives x value 10.4 + . 9.double x = (int)(y +0.5). 9.5 is 9. This action might not be possible to undo. Are you sure you want to continue? We've moved you to where you read on your other device. Get the full title to continue reading from where you left off, or restart the preview.
https://www.scribd.com/doc/187906783/Pic-10-Lecture-3
CC-MAIN-2016-50
refinedweb
1,445
78.75
21121/how-to-execute-python-script-in-hadoop-file-system-hdfs By default, hadoop allows us to run java codes. But now i want to run this python script: import os.path def transform(): inputfolder = "input" for filename in os.listdir(inputfolder): path = inputfolder + "\\" + filename os.remove(path) def main(): transform() if __name__ == "__main__": main() How to run .py file instead of .jar file? If you are simply looking to distribute your python script across the cluster then you want to use Hadoop Streaming. The basic syntax of the command looks like (from): $HADOOP_HOME/bin/hadoop jar $HADOOP_HOME/hadoop-streaming.jar \ -input myInputDirs \ -output myOutputDir \ -mapper myPythonScript.py \ -file myPythonScript.py This basically creates a map-reduce job for your python script Hope this helps :-) You can use the hadoop fs -ls command to ...READ MORE #!/usr/bin/python from subprocess import Popen, PIPE cat = Popen(["hadoop", ...READ MORE hadoop fs -text /hdfs-path-to-zipped-file.gz | hadoop fs ...READ MORE Hi@akhtar, You can use the Hadoop filesystem pass the URI when getting ...READ MORE You could probably best use Hive's built-in sampling ...READ MORE OR Already have an account? Sign in.
https://www.edureka.co/community/21121/how-to-execute-python-script-in-hadoop-file-system-hdfs
CC-MAIN-2021-17
refinedweb
196
70.29
A place for useful things associated with testing. More... #include <vcl_cerrno.h> #include <vcl_string.h> #include <vcl_fstream.h> #include <vcl_ctime.h> #include <vcl_cstdlib.h> #include <vul/vul_file.h> #include <vul/vul_expand_path.h> #include <mbl/mbl_config.h> Go to the source code of this file. A place for useful things associated with testing. Definition in file mbl_test.cxx. A historical measurement recording framework. Currently the function will append the measurement to the file specified by ${MBL_TEST_SAVE_MEASUREMENT_PATH}/measurement_path, and exports it to Dart. In the longer term it may save the value via Dart2. Definition at line 54 of file mbl_test.cxx. Definition at line 31 of file mbl_test.cxx.
http://public.kitware.com/vxl/doc/release/contrib/mul/mbl/html/mbl__test_8cxx.html
crawl-003
refinedweb
108
57.13
import "github.com/pelletier/go-buffruneio" Package buffruneio provides rune-based buffered input. EOF is a rune value indicating end-of-file. ErrNoRuneToUnread is the error returned when UnreadRune is called with nothing to unread. A Reader implements rune-based input for an underlying byte stream. NewReader returns a new Reader reading the given input. Forget discards buffered runes before the current input position. Calling Forget makes it impossible to UnreadRune earlier than the current input position but is necessary to avoid unbounded buffer growth. PeekRunes returns the next n runes in the input, without advancing the current input position. If the input has fewer than n runes and then returns an io.EOF error, PeekRune returns a slice containing the available runes followed by EOF. On other hand, if the input ends early with a non-io.EOF error, PeekRune returns a slice containing only the available runes, with no terminating EOF. ReadRune reads and returns the next rune from the input. The rune is also saved in an internal buffer, in case UnreadRune is called. To avoid unbounded buffer growth, the caller must call Forget at appropriate intervals. At end of file, ReadRune returns EOF, 0, nil. On read errors other than io.EOF, ReadRune returns EOF, 0, err. UnreadRune rewinds the input by one rune, undoing the effect of a single ReadRune call. UnreadRune may be called multiple times to rewind a sequence of ReadRune calls, up to the last time Forget was called or the beginning of the input. If there are no ReadRune calls left to undo, UnreadRune returns ErrNoRuneToUnread. Package buffruneio imports 4 packages (graph) and is imported by 7 packages. Updated 2019-01-07. Refresh now. Tools for package owners.
https://godoc.org/github.com/pelletier/go-buffruneio
CC-MAIN-2019-47
refinedweb
287
59.4
The question: “How can I remotely display python graphics windows?” The backstory: I’m gotten used to the nifty interactive graphics of matplotlib in ipython. But here it is New Year’s Eve and I’m working from home. I need to ssh in to my desktop, run python, and remotely display the python graphics windows to my laptop. This is easy to do in, say, gnuplot (ssh in, and “set terminal x11″), but an hour into reading horrible python docs and stackoverflow, I can’t figure out how to remotely display a python window. A promising avenue, matplotlib.use(‘GTK’) failed because I can’t get pygtk to install. { 17 comments… read them below or add one } Without knowing a little more detail about your setup, it’s hard to be completely concrete. But: basically any matplotlib interactive backend with the exception of “macosx” should work easily over an X11 connection. In other words, if: 1. You have a X server running on your laptop (which you do, if you can run gnuplot); 2. You have X11 forwarding enabled in SSH (as above); 3. When sitting at your desktop, which isn’t a Mac, you can use matplotlib interactively, then everything should “just work”. If your desktop is a Mac, you will probably need to switch the backend to something non-default. It’s a fair bet that the TkAgg backend is installed, and will work just as well as GTK. Try matplotlib.use(“TkAgg”), or, equivalently, invoking: $ ipython –pylab=tk If that doesn’t help, maybe you could provide some more details about the platform your running on and what, if any, errors are reported. Hi I was using python remotely from my work desktop on my mac last night and it was displaying images the graphics over the connection. I didn’t do anything different than what I normally do to log in and forward the display. It sounds more like an X11 forwarding issue possibly. Does showing doing something like xlogo & in the remote terminal pop up a little white window? If not then you’re not forwarding the X11 along for all programs not just python. Happy New Year, ~Meg Have you tried to use your local ipython but connecting it to the remote ipython kernel via ssh as explained there? → I think this only works for graphical ipython frontends, i.e. qt console or notebook. @Jane, ipython notebooks are one really nice way to interact with a remote machine, but I don’t think this method will work if you want the terminal version of ipython (or if you have ipython <=0.11) I got weary of solving this over and over again from operating system to operating system. So I switched to a remote desktop option. It is not the most efficient if your home internet gets dropouts. But it works for a quick look. Typically, I prefer to just mirror the data from home and work, and run the applications on the home system. Desktop and laptop are both macs. X11 and forwarding are working fine (“xterm&” makes a new window on the laptop.) $ ipython –pylab=tk gives me the entire ipython help menu, and then “WARNING: Error in Arguments: “Argument ‘-pylab=tk’ occurs multiple times”. While matplotlib.use(“TkAgg”) produces this amusing error within ipython: In [12]: pylab.plot(x.y) Out[12]: [matplotlib.lines.Line2D object at 0x102e3ef50>] First off: note that you need two hyphens in front of the “pylab” argument to IPython. It looks like the two dashes in my example above have been munged into an en-dash, which won’t work if you copy and paste. That said, it’s possible your version of IPython is too old for this syntax anyway. Anyway, the output (not an error!) you quote looks fine. Following the commands above, try simply entering “pylab.show()” — does that do anything? “Does that do anything?” Yup, it brings up a plot on the desktop. (I checked by VNC…) Weird — no easy answer to that. Are you really running IPython/pylab with exactly the same environment (if possible, in the same terminal, and without running screen or similar) as you can successfully invoke an xterm and have it display on your laptop? Try putting the following in a python script and running that in the same terminal: import os print “Display is: %s” % (os.environ['DISPLAY'],) import matplotlib print “Default backend is: %s” % (matplotlib.get_backend(),) matplotlib.use(‘TkAgg’) print “Backend is now: %s” % (matplotlib.get_backend(),) from matplotlib import pyplot pyplot.ioff() pyplot.plot([1,2,3]) pyplot.show() (save as eg test.py and invoke as “python test.py”). What’s the output? @Jane, @John – I believe the X-forwarding issue has to do with how Tk was installed. You can compile Tk such that it uses Mac-native display windows. @Jane, what icon shows up when you run python? I think if it shows up as anything but part of X11, you can’t get it to forward, but I don’t know. I always use VNC for python display, but I tend to run my interactive python terminal from a gnu-screen session, and ssh into my remote machine. So I enter my commands into my local terminal (which is faster and renders more nicely), but I see the graphics windows popping up on the remote machine. Adam writes: > You can compile Tk such that it uses Mac-native display windows And I’m sure he’s correctly identified the problem. So, Jane, that means your options are: 1. Recompile Tk so that it uses X11 rather than Quartz; 2. Use a different backend which uses X11 (GTK, WX, Qt or FLTK, I guess); 3. Forget X11, and just use VNC or similar. Assuming you didn’t build Tk yourself to begin with but rather are relying on a package provided by somebody else, option 1 is likely tiresome (although see the note on Macports, below). You’ve already tried option 2, and run into problems with getting GTK going. You could investigate the other toolkits, but I can’t promise which will be easier. Given that you’ve already seen the plot appearing on your work desktop by VNC, I’m inclined to think that option 3 is the easiest in the short term, at least. By the way, if you happened to use Macports (see Astrobetter posts passim) to configure your system, switching Tk to use X11 is a snap. All you need is: $ sudo port upgrade –enforce-variants tk -quartz +x11 BTW, I checked, and non-X11 screen forwarding seems impossible: Related question… anyone have a suggestion how to get pyraf to use an X11-forwardable backend when run on a mac? Hi Jane, Did you try the WX device (backend) already. It seems to work just fine for me. “import matplotlib; matplotlib.use(‘wx’); import matplotlib.pyplot as plt; plt.plot(x,y); plt.show()”. Also, please, try to connect using the ‘-Y’ option for your SSH connection in place of the usual ‘-X’. Hope it helps. Happy new year from Brazil [] * First frase == question (?) Sorry. Did anyone ever figure this out? I’m now trying the same and appear to be having the exact same issues as Jane. I’m running a MacPorts installation that uses native Mac displays which cannot be forwarded. So I’m unable to display matplotlib graphics via ssh. Tried several of the suggestions above but also no luck. I’m still resisting the VNC option and don’t quite know enough to do something more clever than installing a pre-packaged python like the MacPorts version. Yes, it works for me. I’m using tightvncserver on a Raspberry Pi. I used this as a test – works fine – saw the plot on my Windows Vista based vnc client… the matplotlib.use(‘GTK’) might be key. I started ipython like this: the –pylab option is key! root@Raspyfi:/usr/bin/X11# ipython –pylab then: In [1]: import numpy as np In [2]: import matplotlib In [3]: matplotlib.use(‘GTK’) In [4]: x=np.linspace(0,3*np.pi, 500) In [5]: import matplotlib.pyplot as plt In [6]: plt.plot(x, np.sin(x**2))
http://www.astrobetter.com/remote-display-in-python-ask-astrobetter/
CC-MAIN-2014-42
refinedweb
1,372
74.49