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
I am trying to replace a character in multiple files in multiple subdirectories (over 700 files in 50 or so subfolders). This files works if I remove the path and place the file in the specific folder; however, when I try and use the os.walk function to go through all subdirectories, I get the following error: [Error 2] The system cannot find the file specified import os path = "C:\Drawings" for root, dirs, files in os.walk( path ): # parse through file list in the current directory for filename in files: #os.listdir( path ): if filename.find("~"):# > 0: # if a space is found newfilename = filename.replace("~","_") # convert spaces to _'s os.rename(filename,newfilename) # rename the file As has been mentioned, you need to give the rename function full paths for it to work correctly: import os path = r"C:\Drawings" for root, dirs, files in os.walk( path ): # parse through file list in the current directory for filename in files: if "~" in filename: source_filename = os.path.join(root, filename) target_filename = os.path.join(root, filename.replace("~","_")) # convert spaces to _'s os.rename(source_filename, target_filename) # rename the file It is also best to add an r before your path string to stop Python trying to escape what comes after the backslash.
https://codedump.io/share/E6JhHCjviiF2/1/using-oswalk-in-python
CC-MAIN-2017-26
refinedweb
215
63.9
Extension objects are used to extend the functionality of style sheets. Extension objects are maintained by the XsltArgumentList class. The following are advantages to using an extension object rather than embedded script: Provides better encapsulation and reuse of classes. Allows style sheets to be smaller and more maintainable. XSLT extension objects are added to the XsltArgumentList object using the AddExtensionObject method. A qualified name and namespace URI are associated with the extension object at that time. The FullTrust permission set is required to call the AddExtensionObject method. For more information, see Code Access Security and Named Permission Sets. The data types returned from extension objects are one of the four basic XPath data types of number, string, Boolean, and node set. Any method that is defined with the params keyword, which allows an unspecified number of parameters to be passed, is not currently supported by the XslCompiledTransform class. XSLT style sheets that utilize any method defined with the params keyword will not work correctly. For details, see params (C# Reference). Create an XsltArgumentList object and add the extension object using AddExtensionObject method. Call the extension object from the style sheet. Pass the XsltArgumentList object to the Transform method.
http://msdn.microsoft.com/en-us/library/tf741884.aspx
crawl-002
refinedweb
198
58.08
setaudproc(2) setaudproc(2) NAME setaudproc - controls process level auditing for the current process and its decendents SYNOPSIS #include <<<<sys/audit.h>>>> int setaudproc(int aflag); DESCRIPTION setaudproc() controls process level auditing for the current process and its decendents. It accomplishes this by setting or clearing the u_audproc flag in the u area of the calling process. When this flag is set, the system audits the process; when it is cleared, the process is not audited. This call is restricted to super-users. One of the following aflags must be used: AUD_PROC Audit the calling process and its decendents. AUD_CLEAR Do not audit the calling process and its decendents. The u_audproc flag is inherited by the descendents of a process. consequently, the effect of a call to setaudproc() is not limited to the current process, but propagates to all its decendents as well. For example, if setaudproc() is called with the AUD_PROC flag, all subsequent audited system calls in the current process and its descendents are audited until setaudproc() is called with the AUD_CLEAR flag. Further, setaudproc() performs its action regardless of whether the user executing the process has been selected to be audited or not. For example, if setaudproc() is called with the AUD_PROC (or the AUD_CLEAR) flag, all subsequent audited system calls will be audited (or not audited), regardless of whether the user executing the process has been selected for auditing or not. Due to these features, setaudproc() should not be used in most self- auditing applications. audswitch() should be used (see audswitch(2)) when the objective is to suspend auditing within a process without affecting its decendents or overriding the user selection aspect of the auditing system. RETURN VALUE Upon successful completion, setaudproc() returns 0; otherwise, it returns -1 and sets errno to indicate the error. AUTHOR setaudproc() was developed by HP. Hewlett-Packard Company - 1 - HP-UX Release 11i: November 2000 setaudproc(2) setaudproc(2) SEE ALSO getaudproc(2), audswitch(2), audusr(1M), audevent(1M), audit(5). Hewlett-Packard Company - 2 - HP-UX Release 11i: November 2000
http://modman.unixdev.net/?sektion=2&page=setaudproc&manpath=HP-UX-11.11
CC-MAIN-2017-17
refinedweb
341
53.31
I would like to stream video to rtsp from opencv in python. There are a lot of threads in here that mentioned about it like these links but the problem is, when the code run to if not out.isOpened() : print("Writer failed") exit() print('Writer opened') This would cause “Writer failed” error. So I think I might miss some installation somewhere? There is not many information on this so if anyone could give some guide, it would be very helpful. FYI: Here is my code run on Jetson Nano that cause the error above import cv2 import os import numpy as np cap = cv2.VideoCapture(RTSP_URL, cv2.CAP_FFMPEG) width = int(cap.get(cv2.CAP_PROP_FRAME_WIDTH)) height = int(cap.get(cv2.CAP_PROP_FRAME_HEIGHT)) fps = int(cap.get(cv2.CAP_PROP_FPS)) gst_out = "appsrc ! videoconvert ! x264enc noise-reduction=10000 tune=zerolatency byte-stream=true threads=4 " \ " ! h264parse ! mpegtsmux ! rtpmp2tpay ! udpsink host=127.0.0.1 port=5000" out = cv2.VideoWriter(gst_out,cv2.CAP_GSTREAMER,0, float(fps), (int(width), int(height)), True) print('Writer opened') if not cap.isOpened(): print('Cannot open RTSP stream') exit(-1) while True: _, frame = cap.read() out.write(frame) if cv2.waitKey(1) == 27: break cap.release() cv2.destroyAllWindows() """
https://forums.developer.nvidia.com/t/rtsp-stream-with-opencv-missing-installation/194869/8
CC-MAIN-2022-33
refinedweb
199
70.39
Text field keyboard I have tried the code below to change the keyboard type, but no luck. What is the right way to do this? import ui v = ui.View() tf = ui.TextField() tf.keyboard_type = DECIMAL=True v.add_subview(tf) v.present() Try something like tf.keyboard_type = ui.KEYBOARD_DECIMAL_PAD. The available keyboard types are documented here: Still not working. I guess I am not understanding the syntax structure to change the key board. With both methods above it runs without error, but no change in keyboard... Are you running this on an iPhone or an iPad? Certain types of keyboard are only available on the iPhone... iPhone 6+ For example I have done this and it works for text alignment: label1.alignment = ALIGN_CENTER = TRUE even though it is not the best way to do it. So I figure that tf.keyboard_type = DECIMAL = True would work but it doesn't. Then your solution of tf.keyboard_type = ui.KEYBOARD_DECIMAL_PAD looked promising but didn't work either. I am on an iPhone 6+ and started a new script with the code up top to be sure I wasn't doing anything to keep the keyboard from changing. I am hoping to see an example of the keyboard changing at all. It seems it wont respond to any requests. Could you show your entire code? I just tried the following minimal example on an iPhone 6, and it worked just fine: import ui tf = ui.TextField() tf.keyboard_type = ui.KEYBOARD_DECIMAL_PAD tf.present() Your text alignment code basically just works "by accident". The alignment constants are integers, and centered happens to be defined as 1, which is equivalent to Trueunder some circumstances, but this isn't the right way to do it. What you're doing is basically to create a new local variable ( ALIGN_CENTER) and assign Trueas both the value of this (unused) variable and the label's alignmentattribute. As I said, it happens to work in this particular case, but it wouldn't work with any other alignment than centered. I entered your latest code in a new script on my 6+ (running iOS 8.1.3). See screen shot: Mar 03%2C 8 30 38 AM.png Here is the keyboard: Mar 03%2C 8 31 05 AM.png P.S. thanks for the label alignment clarification.... Hmmm, okay, I'm sorry then. This might be something I fixed in 1.6 (beta); from the screenshot, it looks like you're running 1.5... Wait a minute..... I cleared Pythonista from the iOS multitasking menu (double click home button) and re-ran the script and it works now.... (yes I am running the latest non beta version) This happened with the label border clipping issue too. When I cleared the app from multitasking and reopened it my label corner radius clipped properly. I hope this discussion was worth your time for debugging the next version. I really do appreciate your support as I learn Python. ( by the way, how would you recommend in an example I center align label text in contrast to my bad example? ) import ui w,h = ui.get_screen_size() tf = ui.TextField() tf.frame = (0, 50, w, 25) tf.keyboard_type = ui.KEYBOARD_DECIMAL_PAD lbl = ui.Label() lbl.frame = (0, 100, w, 25) lbl.border_width = 1 lbl.bg_color = 'white' lbl.alignment = ui.ALIGN_CENTER lbl.text = 'Center aligned label' v = ui.View() v.add_subview(tf) v.add_subview(lbl) v.present() v.wait_modal() print(tf.text) Thank you! Much appreciated. I am an electrical engineer trying to make it in a programming world :)
https://forum.omz-software.com/topic/1615/text-field-keyboard
CC-MAIN-2021-17
refinedweb
590
69.18
A method contains one or more statements. In well-written Java code, each method performs only one task. Each method has a name, and it is this name that is used to call the method. In general, you can give a method whatever name you please. However, remember that main( ) is reserved for the method that begins execution of your program. Also, don’t use Java’s keywords for method names. In the following example we demonstrate how to define methods inside class, although we already have, but a new thing how we can return values from methods as: class MethodTest { String MethodTest() // String is a return type of the Method MethodTest { return "It's great"; } } public class MethodExample { public static void main(String[] args) { MethodTest obj1 = new MethodTest(); String s = obj1.MethodTest(); System.out.println("Returned Value : " + s); } }
http://www.loopandbreak.com/methods/
CC-MAIN-2019-43
refinedweb
139
63.39
Need it to work in Ideone HOMEWORK 5 STRUCTURES. Use 1.5 as the overtime pay factor. -------------------------------------------------------------------------- Clock# Wage Hours OT Gross -------------------------------------------------------------------------- 098401 10.60 51.0 11.0 598.90 526488 9.75 42.5 2.5 426.56 765349 10.50 37.0 0.0 388.50 034645 12.25 45.0 5.0 581.88 127615 8.35 0.0 0.0 0.00 You should implement this program using the following structure to store the information for each employee. /* This is the structure you will need, feel free to modify as needed */ struct employee { long int id_number; float wage; float hours; float overtime; float gross; }; In your main function, define an array of structures, and feel free to initialize the clock and wage values in your array declaration. Use the following information to initialize your data. 98401 10.60 526488 9.75 765349 10.50 34645 12.25 127615 8.35 Create an array of structures with 5 elements, each being of type struct employee. Initialize the array with the data provided and reference the elements of the array with the appropriate subscripts. Like the previous homework, use multiple functions in your answer and continue to use constants as needed. The only array you need is the array of structures, you don't need to create a separate array for clock, wage, hours, ot, and gross. You can either pass the entire array of structures to each function, or pass values that work on one array element (and its associated structure members) at a time ... either will work. Assignment 5 Templates Here are some templates you could use for this week's assignment. There are many ways to do it, below are just some ideas you are welcome to use for your design. The template below provides a basic set up that you can modify and includes a sample function to print the array of structures ... which could prove useful as you add new functions and debug your code. It should compile and run in whatever compiler you use (including IDEOne). One thing you'll notice if you decide to do it this way, is that you can just pass a single array of structures to any function, and you will have access to any combination of the members inside that structure. Additionally, because it is an Array of Structures, you will also have the added bonus of being able to access any array element as well. Remember that in homework 4 (functions) you had to pass one or more arrays as needed to your functions, which can be quite a pain if you had lots of different attribute information about each employee (for example, if in the future I added their name, hire date, salary grade, ...). Review the template below and feel free to access it at: /**************************************************************************** ** ** HOMEWORK: #5 Structures ** ** Name: [Enter your Name] ** ** Class: C Programming ** ** Date: [enter the date] ** ** Description: This program prompts the user for the number of hours ** worked for each employee. It then calculates gross pay ** including overtime and displays the results in table. Functions ** and structures are used. ** /****************************************************************************/ /*Define and Includes */ #include <stdio.h> /* Define Constants */ #define NUM_EMPL 5 #define OVERTIME_RATE 1.5f #define STD_WORK_WEEK 40f /* Define a global structure to pass employee data between functions */ /* Note that the structure type is global, but you don't want a variable */ /* of that type to be global. Best to declare a variable of that type */ /* in a function like main or another function and pass as needed. */ struct employee { long id_number; float wage; float hours; float overtime; float gross; }; /* define prototypes here for each function except main */ void Output_results_screen (struct employee [ ], int size); /************************************************************************* ** Function: Output_results_screen ** ** Purpose: Outputs to screen in a table format the following ** information about an employee: Clock, Wage, ** Hours, Overtime, and Gross Pay. ** ** Parameters: employeeData - an array of structures containing ** employee information ** size - number of employees to process ** ** Returns: Nothing (void) ** *************************************************************************/ void Output_results_screen ( struct employee employeeData[], int size ) { int i; /* loop index */ /* printf information about each employee */ for (i = 0; i < size ; ++i) { printf(" %06li %5.2f %4.1f %4.1f %8.2f \n", employeeData[i].id_number, employeeData[i].wage, employeeData[i].hours, employeeData[i].overtime, employeeData[i].gross); } /* for */ } /* Output_results_screen */ int main () { /* Variable Declaration and initialization */ struct employee employeeData[NUM_EMPL] = { { 98401, 10.60 }, { 526488, 9.75 }, { 765349, 10.50 }, { 34645, 12.25 }, { 127615, 8.35 } }; /* Call various functions needed to reading, calculating, and printing as needed */ /* Function call to output results to the screen in table format. */ Output_results_screen (employeeData, NUM_EMPL); return(0); /* success */ } /* main */ I always found that creating a function to display the data first is a good initial step. Then you can call it any time to check that your variables are initializing and updating correctly. Don't feel you have to create all your functions right way. Develop and test the ones you need one at a time. This Divide and Conquer approach will serve you well and you won't be worried about initially debugging lots of errors. Another way to do this is to pass member values of specific elements into the array of structures from a function like main to other functions that will return a value in the result. For example, passing hours for an employee to a function and returning back the overtime hours, and having this call in a loop that will process each employee. If you do it this way, you have to pass the right information about the employee as needed by each function, i.e., expect each function to have multiple parameters (for example, to figure out gross pay, you'll need to pass at least wage, hours, and overtime). /* In your main function, this is how you could call your needed */ /* functions using this method. You'll need to define the */ /* employeeData, which I declared and intialized in the other example. */ int main () { for (i = 0; i < SIZE; ++i) { /* call functions to process each employee, one at a time */ employeeData [ i ].hours = Get_Hour ( employeeData[i].clock ); employeeData [ i ].overtime = Calc_Overtime ( employeeData[i].hours ); employeeData [ i ].gross = Calc_Gross ( employeeData[i].wage, employeeData[i].hours, employeeData[i].overtime, employeeData[i].gross ): } /* for */ } /* main */ Whatever way you do it, don't use global variables ... I don't want all your functions looking like: void foo ( ) with no parameters passed or used. There are benefits and drawbacks to each approach. Good luck with these templates, or feel free to create your own from scratch.
https://www.studypool.com/discuss/249871/need-it-to-work-in-ideone
CC-MAIN-2016-50
refinedweb
1,077
64.2
Subject: Re: [Boost-bugs] [Boost C++ Libraries] #1541: [parameter] Patch for missing includes From: Boost C++ Libraries (noreply_at_[hidden]) Date: 2010-06-14 11:37:04 #1541: [parameter] Patch for missing includes ----------------------------------------------------------+----------------- Reporter: Richard Webb <richard.webb@â¦> | Owner: danielw Type: Patches | Status: reopened Milestone: Boost 1.36.0 | Component: parameter Version: Boost Development Trunk | Severity: Problem Resolution: | Keywords: ----------------------------------------------------------+----------------- Changes (by Jens Seidel <jensseidel@â¦>): * cc: jensseidel@⦠(added) * status: closed => reopened * resolution: fixed => Comment: Your guess is wrong. The file parameter/aux_/default.hpp is still unpatched and misses a #include <boost/detail/workaround.hpp> but uses BOOST_WORKAROUND. Also one or two other files are unpatched. Is it really so hard for you to apply a one line patch or to check whether it is still required? -- Ticket URL: <> Boost C++ Libraries <> Boost provides free peer-reviewed portable C++ source libraries. This archive was generated by hypermail 2.1.7 : 2017-02-16 18:50:03 UTC
https://lists.boost.org/boost-bugs/2010/06/12827.php
CC-MAIN-2020-10
refinedweb
158
50.73
Working with asfunction in AS2 Class Files Flash Player has supported a limited subset of the HTML specification since version 6 — just set a text field’s htmlText property to an HTML-formatted string and you’re good to go. Fortunately, <a> (anchor) tags are among the supported few, which means you can even put working hyperlinks inside your text. Not only that, but Flash includes a special protocol, asfunction, that allows you to trigger functions from those hyperlinks, in case you prefer to do that instead of visiting URLs. ActionScript 3.0 uses a different approach, but if you’re coding in AS1 or 2, just replace with asfunction:someFunction,someParam, as described elsewhere on this blog. If you’re coding in timeline keyframes, it’s all pretty straightforward. But asfunction can seemingly break when used in custom class files. Here’s what’s going on and how to fix it. A bit of backstory When a text field responds to an asfunction trigger, it looks for the specified function inside the movie clip that contains the text field in question (that is, the container object of that text field, or its parent). Again, if you’re coding on the timeline, everything tends to fall into place. Imagine the following ActionScript 2.0 in a keyframe of the main timeline: function linkHandler(param:String):Void { // do something neat with the hyperlink } myTextField.htmlText = "<a href='asfunction:linkHandler,param'>click me</a>"; When a user clicks the words “click me” in this text field, asfunction looks for a function named linkHandler() in the movie clip (aka the timeline) that contains this text field. And of course, there it is, in the very same keyframe. In some custom class situations, the above concept still works without a hitch. If your class extends MovieClip, for example, then the class itself becomes the “timeline” that contains both the text field and asfunction’s function. class CustomClass extends MovieClip { private var tf:TextField; public function CustomClass() { tf = this.createTextField("tf", 0, 0, 0, 100, 22); tf.html = true; tf.htmlText = "<a href='asfunction:linkHandler,clicked'>click me</a>"; } private function linkHandler(param:String):Void { trace(param); } } In the preceding code, an arbitrarily named property, tf, is declared and — inside the constructor function — set to an instance of the TextField class by way of the MovieClip.createTextField() method. This method succeeds here when invoked on the global this property because the class extends MovieClip (i.e., it is a movie clip). In the following line, tf’s TextField.html property is set to true, which allows it to accept HTML input, then its htmlText property is set to the same HTML-formatted string as before. Note that asfunction still points to a custom linkHandler() function, this time passing in the parameter “clicked” (a string). The private linkHandler() method (which could be public too, either way) hears asfunction’s call when the hyperlink is clicked. All is still well — the Output panel traces the word “clicked” because param’s value is that word. Note: To test the above class, you’ll have to save the preceding code as a simple text file named CustomClass.as and put it into the same folder as a new FLA. Inside that FLA, draw a quick rectangle and convert it to a movie clip symbol. Right-click / Command-click the symbol in the Library and choose Linkage from the context menu. Check “Export for ActionScript” and type the name of the class ( CustomClass) into the Class field. So what’s the problem? The problem is, your class might not extend MovieClip (or extend anything!) at all. Which would be fine. There’s no reason to extend MovieClip, or any class, unless the class you’re writing actually is an example of the class you’re extending. In the following code — almost identical — asfunction is no longer able to find its linkHandler() function: class CustomClass { private var tf:TextField; public function CustomClass(target:MovieClip) { tf = target.createTextField("tf", 0, 0, 0, 100, 22); tf.html = true; tf.htmlText = "<a href='asfunction:linkHandler,clicked'>click me</a>"; } private function linkHandler(param:String):Void { trace(param); } } What’s the difference? This time, the class doesn’t extend anything. It’s instantiated in the main timeline … new CustomClass(this); … and fed a MovieClip instance — here, the global this property — as a parameter. The only reason for the parameter is so that the target reference inside the constructor function can be used in the very next line as the MovieClip instance required for the createTextField() method. The difference may be subtle, but when this class is instantiated, the text field becomes an immediate child of the main timeline. The problem is, the class itself — which contains the linkHandler() method — is also a child of the main timeline, which means asfunction is looking in the wrong place for linkHandler(). As always, asfunction is looking in the movie clip that contains the text field. Here, the movie clip is the main timeline, but the desired function is inside an object (this CustomClass instance) inside the main timeline. So close, but yet so far, eh? So what’s a solution? The easiest way to fix the disconnect is to re-route the function, which can be done with a single line. Here’s a quick look at the constructor function only: public function CustomClass(target:MovieClip) { tf = target.createTextField("tf", 0, 0, 0, 100, 22); tf.html = true; tf.htmlText = "<a href='asfunction:linkHandler,clicked'>click me</a>"; tf._parent.linkHandler = this.linkHandler; } The workaround here takes advantage of the fact that the MovieClip class is dynamic, which means it can have properties and methods added to it at runtime. In this case, a reference is made to the movie clip that contains the text field — tf._parent (the TextField._parent property of tf) — and then a new function is declared in that movie clip and set to the function defined inside the class. Because the constructor function accepts a target parameter, you could also use the following in this scenario, which means the exact same thing: target.linkHandler = this.linkHandler; It’s interesting to note that linkHandler(), as defined in the class, is private, yet the twin function, dynamically set to a different MovieClip instance, is able to invoke this private method without any issues. That’s just the broken way it works in AS2. It shouldn’t do that, but hey, you’re a developer. That makes you like a stage hand. You keep the magician’s secrets. Is there a better solution? There is a better solution — though “better” is subjective, and you really only need the alternate approach if the scope of your function needs to reside inside the class. Under the current setup, if you replace trace(param); with trace(this);, you’ll see _level0 in the Output panel. Why? Because the dynamically added function exists in the main timeline, so the this reference thinks that’s where it is. (It only happens like this because the parent of the text field happens to be the main timeline. The point, however, is that this refers to an object that isn’t the CustomClass instance.) To re-route not only the function, but its scope, use the Delegate class as follows: import mx.utils.Delegate; class CustomClass { private var tf:TextField; public function CustomClass(target:MovieClip) { tf = target.createTextField("tf", 0, 0, 0, 100, 22); tf.html = true; tf.htmlText = "<a href='asfunction:linkHandler,clicked'>click me</a>"; tf._parent.linkHandler = Delegate.create(this, linkHandler); } private function linkHandler(param:String):Void { trace(param); } }
http://www.quip.net/blog/2008/flash/actionscript-20/working-with-asfunction-in-as2-class-files
CC-MAIN-2016-07
refinedweb
1,269
64.51
What is serverless? Before the deep(er) dive into the details it's worth to give a try to clarify the main subject. Serverless is still a hot topic today and as always, there is no one, ultimate definition for it. For starters there are two close areas - one was firstly used in 2012 and originally was described as Backend as a Service (BaaS), which means applications that significantly or fully incorporate third-party, cloud-hosted applications and services, to manage server-side logic and state. As an example, a mobile or a single-page application perfectly describes the basics of the concept, where a client application implements the business logic and connects to and uses resources via third-party services - such as databases, authentication services...etc. While Infrastructure as a Service (IaaS) gives us a virtualization layer to create virtual machines, install operating systems, support applications and data...etc. then in case of Platform as a Service (PaaS) the provider offers more of the application stack than IaaS providers, by adding operating systems, middleware (such as databases) and other runtimes into the cloud environment. FaaS Nowadays serverless has got a more up-to-date definition: Function as a Service (FaaS) - which implies that the server-side logic is organized into functions which are also developed by the application developers and which is triggered by e.g. events or HTTP requests, they are ephemeral and run in stateless compute containers. Google Cloud Functions, Microsoft Azure Functions and AWS Lambdas are the implementations from the cloud vendors of the "Big Three". When using FaaS we don't need to care about the image or the hardware, we can focus on building the application logic turned into functions, directly into the cloud-hosted environment. FaaS is about running backend code without managing your own server systems or your own long-lived server applications. The provider cares about everything and technically there is no limitation for the programming language, the environment or the framework - fundamentally anything can be run in a serverless-way (in case of AWS, a Lambda function can also execute another process that is bundled with its deployment artifact, so we can actually use any language that can compile down to a Unix process). As all the work is done by the provider, serverless solutions are literally stateless - which means the state of a FaaS application must be persisted externally, outside of the instance. Startup latency or "cold start" is also an interesting topic around serverless. It means initially there is no container started to host our functions and it takes some time to build up the first ones to be able to process the first requests. The latency depends on many variables: the programming language, the number of libraries used, the amount of code written, the configuration of the environment...etc. The opposite way is a warm start, when an already existing instance is used to respond. This "problem" has been stuck in the heads of the developers and there have been many attempts to turn cold starts to warm starts or to make the provider to keep the instances - the truth is that it cannot be managed by this way. Startup latency and cold start is a "behavior" that comes with serverless, and some may turn away from this architecture and don't even consider using it, but there are other solutions that can give us an acceptable operation. Advantages, disadvantages Serverless is described as an outsourcing solution as many uses the very same infrastructure therefore the operational costs are reduced. Pay what you need - it can be the biggest benefit as we only have to pay for the computing what we need and what we use. It also helps when there is inconsistent or non-deterministic traffic, when a regular environment would need auto-scaling which cannot be applied for peaks. Upscaled components would cost much more because in general these servers never deliver their maximum capable computing output. So, on demand computing also ends up in a "greener" computing. It is also clear if there are less components to be supported then it ends up in less work. A serverless solution performs upscaling with a "cold start" without any resource planning, allocation or provisioning which is done when all the current containers are already in the middle of processing. Downscaling is also done for unused containers which are retired after a few minutes of unuse. Serverless can also be a problem as an outsourcing solution when it comes to the control of some parts of our system. Vendors can define strong constraints over these areas which affect the whole system. Moreover, each vendor also provide their own solutions so a vendor-switch can end up changing operational tools, the code and also the architecture. There is no in-server state as mentioned before, execution duration is limited, there is startup latency ("cold start"), and debugging of production code more or less cannot be done(debugging can be done with the Amazon.Lambda.TestTool-2.1) and even if there are a lot of operations solved by the vendor (hosting, scaling, provisioning...etc.) there are steps we need to deal with like monitoring or security. AWS Lambda AWS Lambda is Amazon's serverless implementation. From vendor point of view, it supports many programming languages: Java, Go, PowerShell, Node.js, C#, Python, and Ruby code (). And there is also a Runtime API provided, to use any additional programming languages. AWS Lambda history, main milestones Nov 13, 2014 - Preview release Jul 9, 2015 - AWS Lambda now supports invoking Lambda functions with REST-compatible clients Dec 3, 2016 - AWS Lambda support for the .NET runtime Jan 15, 2018 - Runtime support for .NET 2.0 Jul 9, 2018 - Support for .NET Core 2.1.0 runtime in AWS Lambda Nov 29, 2018 - Custom Runtimes Initially when a Lambda is invoked, the provider creates a Linux-hosted "container" () for the function. The details are completely hidden from us: no provisioning, no allocating, no configuring of a server or an instance. In the background AWS Lambda is using Firecracker microVMs (), developed by AWS, which uses Linux Kernel-based Virtual Machines (KVM) to create microVMs with fast startup time, low memory overhead, and with a virtual machine memory barrier which enables workloads from various customers to run on the same machine, without any trade-offs to security or efficiency. See details in the following link about steps: Learning Lambda Part 8 Basic AWS Lambda types Technically we differentiate two basic patterns: the synchronous (RequestResponse - like an HTTP call) and the asynchronous invocation (event like action that occurs when e.g. inserting new records into a database). A Web API is a good example for the synchronous invocation where an API Gateway is configured to receive and forward the HTTP requests to the Lambda functions based on some routing and mapping. It returns the responses back to the caller at the end of the invocation. A common use-case for asynchronous invocation is file processing - a file upload from a mobile application, when the picture file is directly uploaded to an S3 bucket and it triggers an event for a Lambda function which resizes the image and save it to another S3 bucket. There are some basic settings available for a Lambda function. The amount of memory allocated to it can be set from 128 MB to 3 GB and the timeout can be specified from 1 sec to 15 minutes. Beside the computing needs, it also serves another purpose: pricing. As the charges are calculated on-demand, more memory consumed, longer processing times needed result more costs. Based on the memory boundary there are a lot of free seconds available in the free tier and for the rest the price is specified per 100ms. () E.g. Memory: 512 MB, Free tier per month: 800000 sec, Price per 100ms: $0.000000834 For AWS Lambda concurrent requests are limited to 1000 as a maximum under one account and region. When it is reached Lambda starts throttling the requests. Due to this limitation it is highly recommended not to share the account between production and non-production systems - otherwise e.g. a less-controlled load testing in the test environment can end up in production problems on the other side (throttling is treated as an error for synchronous calls).. The runtime package store feature (which is a cache of the NuGet packages installed on the target deployment platform) contains the packages pre-jitted which results smaller packages and also improves the cold startup time. We can make all ASP.NET Core and EF Core packages available by adding the Microsoft.AspNetCore.All dependency, but it does not include them in the deployoment package - they are available in Lambda. When a container is ready, the .NET Core "runtime" is launched. ASP.NET Core Razor Pages are now precompiled at publish time. This means when our serverless Razor Pages are first rendered, Lambda compute time isn’t spent compiling the Razor Pages from cshtml to machine instructions. Development There is an extension called AWS Toolkit for Visual Studio which is the easiest way to develop, debug and deploy AWS applications. When creating a new project from the blueprint it creates a regular-like ASP.NET Core project. There are several blueprints we can choose from - for ASP.NET Core Razor Pages we need the "ASP.NET Core Web App" blueprint: The Program.cs is renamed to LocalEntryPoint.cs: public class Program { public static void Main(string[] args) { BuildWebHost(args).Run(); } public static IWebHost BuildWebHost(string[] args) => WebHost.CreateDefaultBuilder(args) .UseStartup<Startup>() .Build(); } And in parallel there is an entry point created for the Lambda - LambdaEntryPoint.cs (this is actually the entry point from the API Gateway): /// <summary> /// This class extends from APIGatewayProxyFunction which contains the method /// FunctionHandlerAsync which is the actual Lambda function entry point. /// The Lambda handler field should be set to /// /// AutSoft.AspNetCoreServerless::AutSoft.AspNetCoreServerless.LambdaEntryPoint::FunctionHandlerAsync /// </summary> public class LambdaEntryPoint : // When using an ELB's Application Load Balancer as the event source change // the base class to Amazon.Lambda.AspNetCoreServer.ApplicationLoadBalancerFunction>(); } } Deployment is also easy from Visual Studio: right-click on the solution and select Publish to AWS Lambda - after selecting the account profile and region, we have to specify a CloudFormation stack name and an Amazon S3 bucket - it is used to upload the package and create the stack. The settings are saved to a config file, so we can do the deployment anytime from now by the dotnet publish command. The output parameter of the deployment (which is a CloudFormation stack creation/update) is the endpoint of the API Gateway that can be accessed by now: https://[unique_identifier].execute-api.eu-central-1.amazonaws.com/Prod The stack looks like the following - beside the permissions and some infrastructure-related items it consists two main parts: - AWS:ApiGateway:RestApi - AWS:Lambda:Function Basically, that's it! Only a few clicks were needed to have a working Web-application deployed, in a serverless way. Naturally it is a very basic setup, but implementing business logic, accessing other AWS services (such as DynamoDb, S3, Elasticsearch, SQS/SNS...etc.), adding logging (into CloudWatch), implementing authentication (with Cognito)...etc. is developed in the very same way as we would do for a non-serverless solution. Conclusion There is no silver bullet. Serverless is not the magic carpet that takes us to the place where all our problems are solved. As on-premise solutions versus cloud-based ones have their own purpose, we should not expect everything from serverless against regular, VM- and cloud-based solutions. Despite this it is important to understand the specialties, the advantages and disadvantages of this kind of architectures and keep them in our minds. If we do so, we can apply them in the right business situation. Sources Related articles
https://blog.autsoft.hu/serverless-aws-lambda-asp-net-core-razor-pages/
CC-MAIN-2019-30
refinedweb
1,976
51.48
2014-07-29), John-David Dalton (JDD) Introduction JN: (Welcome and host details) Introductions. Agenda: tc39/agendas/blob/master/2014/07.md JN: Agenda approval? Approved. JN: Minutes from June 2014 approval? Approved. 4.1 Review Latest Draft (Allen Wirfs-Brock) rwaldron/tc39-notes/blob/master/es6/2014-07/rev26-summary.pdf AWB: Slide 1 - "Task" => "Job" - Generator oject return method/for-of/in loops use return method on generatorsGetMethod, now treats null and indefined equiv as meaning no method available - Eliminated the ability of Proxy handlers to extend the set of property descriptor attributes thet expose vis [[GetOwnProperty]] - Added invariant checks for Proxy [[OwnPropertyNames]] internal method - Added an informative generator function based definiton for ordinary object [[Enumerate]] - Another round of updates to 9.2.13 FunctionDeclarationInstantiation to fix various scoping bugs. - Eliminated duplicate property name restrictions ob object literals and class definitions - Revisited @@unscopabe support in Object Environment Records RW: Clarification about #3 MM: Prevent the ability to lie about decriptor values; prevent leak "time of check to time of use" (ToCToU) vulnerability (re: #5) WH: Informative implementation may cause readers to incorrectly assume that anything that doesn't conform to to that informative implementation is wrong. In particular, worried about users assuming that implementation behaviors that the informative implementation doesn't do can't happen. (discussion re: normative vs informative prose in spec) WH: "Note" sections? AWB: Sections marked "Note" are informative, making them normative would be redundant WH: Too many "Note" sections appear to be normative rephrasings of other normative text, which we labelled as informative only because we're afraid of redundancy. Then when we have one which describes something that behaves quite differently from the normative text, it can be misleading. Slide 2 - For-of now throws if iterable value is null or undefined (also reverted comprehension to throwing for that case) Date.prototype.toStringnow uses NaN as its time value when applied to an object without a [[DateValue]] - Function poison pill caller and arguments properties are now configurable General concern about whether you could take the sloppy-mode and add it to a strict-mode function via reflective APIs. Turns out that the sloppy mode behavior is implemented in all current engines as a magic value property, so this will not be possible (phew!). awaitis a FutureReservedWord when parsing and the syntactic grammar goal symbol is Module - Better integration of Object.prototype.toLocaleStringand String.prototype.toLocaleStringwith ECMA-402 - Added nameproperty for bound functions in Function.prototype.bind. Fixed bugs in generating length property in Function.prototype.bind - Tweaked Script GlobalDeclarationInstantiations to deal with error situations that could arise from misusing proxies for the global object. - Changed handling of NaN from a sort comparefn to match web reality (ecmascript#2978) MM: (re: #6) What is the bound name? AWB: "bound ..." (per previous resolution—find and link) AWB: (re: #8, sort behavior when comparison function returns NaN) the change adds: "If v is NaN, then return +0. " WH: Note that that bug contains other examples where sort would still be inconsistent. WH: The issue here is that +∞ - +∞ is NaN, which means that using a-b as a sort function allows you to compare +∞ with -∞, but +∞ is not equal to itself. WH: I wrote this wording in ES3 and I'm fine with this change. It will fix the behavior of sorting arrays containing ±∞ but not NaN's. With NaN's you'll still get an inconsistent sort order (because the ordering relation is not transitive) and hence implementation-defined behavior. MM: Worried that implementation-defined behavior could do bad things such as violate memory safety. Should state that it doesn't. MM: (filing bug to make language more specific to avoid memory safety violations) AWB: There was never a concern about violating memory safety because we don't define memory safety WH: I tried to formalize it in ES3 but it was too much trouble. I wanted to state that the sort always produces a permutation, but that doesn't apply to sorting oddball input objects containing things such as holes with prototype properties showing through, read-only properties, getters/setters, proxies, .... Can't write "sort doesn't violate memory safety" without formalizing what memory safety is. MM: Will write concrete suggestion for handling and submit as part of bug Slide 3 - Updated Symbol conversions: aSym == "not a symbol"produces false. var s = Symbol(); s == Object(s)produces true. "foo" + aSymbolor aSymbol + "foo"throws TypeError. - Symbol @@toPrimitivereturns the wrapped symbol value. ToNumber(aSymbol)throws. - Spread now works on strings var codeUnits = [..."this is a string"] yield *now works with strings: function * getchars(str) {yield * str} - Annex B support for function declarations in IfStatementClauses - Annex B (and 13.12) support for legacy labelled FunctionDeclarations - Updated Annex C (strict mode summary) WRT ES6 changes and extensions EA: (re: #2) Removed the Object check? BE: Andreas didn't want values on the right of a destructuring (number, etc) EA: Definitely want to spread strings BE: Agreed, we should revisit. (Added: tc39/agendas/commit/370e3029d01659620e0ca03bf370eb5beefca45e ) Re: #4, the resolution: rwaldron/tc39-notes/blob/master/es6/2014-06/jun-6.md#block-scoping-issues BE: (function f() { console.log(g); L: function g() {}; })(); DH: The grammar: inside a LabelledStatement, can't start with "function" BE/AWB: Clarification of Statement and Declaration DH: Suggest: we can deal with this post-ES6. It's a useless thing that happens to parse and not worth our immediate attention. AWB: We need to decide if this is a function declaration, does it hoist? DH: But won't affect the web, existing can't be relied on. The existing work has been done, but no additional work WH: Treat this the same as function declarations inside of statements: ie. if (true) function f() {}. Do we allow while (true) function f() {} ? YK/BE: Let's take this offline. WH: Let's keep it as it is in ES5 AWB: Whoever maintains web specs...? BE: Not all browsers do the same: (results of above code) - SpiderMonkey ReferenceError - V8 function g() {} - JSC function g() {} - Chakra function g() {} AWB: Spec is up to date, without the modules work. 4.6 Unscopables (Erik Arvidsson) rwaldron/tc39-notes/blob/master/es6/2014-07/es6-unscopables.pdf Object instead of Array Array.prototype[Symbol.unscopables] = { ... }; (with null prototype) Walk The [[Prototype]] Chain For - HasBinding - GetBindingValue But nor for: - SetMutableBinding AWB: essentially replicating the prototype lookup algorithm in two additional places. Realized a third. EA: ... Setter Issue SetMutableBinding ignores @@unscopables so we can get a mismatch: with (object) { x = 1; assert(x === 1); // can fail } YK: Needs to be written? AWB: More that wasn't considered. Proxy issues in bug (above) EA: The problems arise when your prototype has getter or setter or proxy. The result of HasBinding can return true for a property further down the prototype chain, but then Set got invoked using a setter that was black listed in HasBinding. AWB: Proposal is, do what we've done and leave setting as is. Only apply unscopable at the local level, don't walk the prototype chain Any binding resolution operation, on a with env record: - looks up unscopables, doesn't matter where in the prototype - checks the nameagainst unscopables (has, not hasOwn) - if found continue up to the next level Only applies to "with environments" STH: Should unscopables affect things in the prototype chain WH: Does it apply to both reads and writes? AWB: Yes STH: Looks only at the object with unscopables as own property? AWB: No, it's on the prototype, to not own STH: Should this apply to all spec algorithms? YK: Everyone agrees? STH: AWB's proposal says no AWB: Only object environment records for with STH: it should apply to SetMutableBinding? AWB: Yes. EA: The reason for not doing [[Get]] was because you might have instance properties on the object YK: Can link the unscopables EA: Agreed. And don't do hasOwn STH: can break existing programs that use instance properties BT/AWB: Discussion about compatibility. EA: What about Globals & unscopables? The global object is an ObjectEnvironment too. Do we plan on adding unscopables? Generally, no. YK: Are we sure there is no case to use unscopables on the global object RW: Could we specify no unscopables on global now and relax it later? EA: for ES7 AWB: If this only applies to with environments, then that's not part of the global object MM: Unless you do: with(global object) {...} Confirm. AWB: Is this a function of with or the environment? Conclusion/Resolution - @@unscopables only works inside of withobject environment records, not global object environment records. - Revert to the previous algorithm: - looks up unscopables, doesn't matter where in the prototype - checks the nameagainst unscopables (HasProperty, not HasOwnProperty) - if found continue up to the next scope level 4.8 Consider if Object.assign should silently ignore null/undefined sources (Sebastian Markbage) (Request slides) SM: Object.assign({}, undefined); This throws, but propose that it shouldn't. SM/AWB: Object.keys was relaxed Object.assign(undefined, {}); This should still throw DH: undefined and null are probably treated the same by == Do we want to treat null and undefined the same? Probably not. DD: The mental model should be for-of + default arguments, not for-in MM: use case for tolerating the null is in JSON data. JSON has no way to represent undefined, except for null JH: or omission SM: Covered existing libraries to use Object.assign, feedback almost always included the undefined case. JM: Did you distinguish null and undefined? SM: No YK: We should distinguish or we have two nulls Conclusion/Resolution - do not throw on undefined - will throw on null Short discussion about making generator.return() throw a special exception. DH: Want to bring up Andy Wingo's preference (discussed on es-discuss) for modeling return() as an exception rather than a return. General opposition Conclusion/resolution - keep as is: return() method produces a return control flow, not an exception AWB: In the process of for-of, if a throw occurred, does that turn into a throw to the iterator? NO: Yield * AWB: Does an internal throw When a generator.throw() is called and the generator has a yield* the spec currently calls throw in the yield* expression DH: Call return() on the outer generator, delegates calling return() to the delegated yield * BE: function* g() { yield* h(); console.log(42); } function* h(bound) { try { for (let i of range(bound)) { yield i; } } finally { console.log("h returned"); } } let it = g(); it.next(); // returns {value: 0, done: false} it.throw(); // AWB: If it.return() we would send a return to the h instance. Confirm. AWB: if it.throw() do we send a return to the h instance? MM: we would do a throw? AWB: we wouldn't. Think of the yield* as a for-of. h() doesn't know what its client is. The problem the resumption from the yield is throw, back in the yield*, what to call on h() DH: Propagate, that's the point of yield*, it should behave as if the inner generator is inline and anything it does propagates. AWB: My mental model of yield* is that it expands to a for-of { ... yield ... } MM: You should not think of it that way. DH: You should not base your mental model off of an expansion; you should base it off of what yield* is meant to be used for. The desugaring into for-of is not at all straightforward. AWB: the desugaring in the algorithms in the spec is not actually that complex... DH: the way to think about this is to directly inline the body of h into the body of g, not as a generator equivalent. This is the generator analogue of beta-equivalence. AWB: why don't you do that for any function then? DH: well, if we had TCP, we would have beta-equivalence. YK: (Saw that one coming...) DH: the important refactoring property to have is that you can extract out some generator logic into a helper function and then call it with yield*. Ben Newman was talking about a similar/related thing. It is very important that the throw to the outer generator get delegated as a throw through the inner generator. MM: What is the model that the user has: who is the throw complaining to? AWB: And who has control? Is the generator calling out and getting something back or into another generator. DH: for-of and yield* diff roles: for-of is a consumer and generator stops there. yield* is consuming and producing by composition. JH: Two models: consuming and emitting. yield* is a stream fusion, STH: yield* compensates for the shallowness of yield DH: It allows composition of generators JS: You could expand these to for-of YK: Those that work in C# find this to be a natural way to think of this, but others may not JS: My concerns are speed DD: Think about how you could desugar and see where it falls down YK: disagreement DH: Fall over in more cases MM: Would it be plausible to have the throw propagate to the inner generator as well? DH: check out PEP-380. The desugaring is mind-bogglingly complex, but the refactoring principle is very straightforward. Refactoring should not introduce corner cases where it behaves differently. MM: consensus that yield* delegates throw? JS: no objection Conclusion/Resolution yield*delegates return()and throw() - for-of propagates abrupt completion outward, calls the iterator's return() AWB: Another question... when we do the return, that may return a value and currently throwing that value away. There is no way to override the normal loop termination. DH: If we do a throw that causes us to call return() on a generator, and that returns a value, the value is dropped on the floor, which is consistent. AWB: If the return call on the iterator is an abrupt return (normally means an exception)... MM: The call to return itself completes abruptly? AWB: Yes MM: it's "finally-like", that supersedes AWB: In one sense, a dropped exception BE: Let's have a smaller group with the champions look at the final specific details. 4.11 Consider adding "attribute event handlers" to ANNEX B (Allen Wirfs-Brock) AWB: Add to Annex B the semantics of defining an attribute handler so that the HTML spec can get out of the business of spec'ing a distinct form of ES function. MM: An internal function for other specs? AWB: If you're implementing a browser, you'd follow this specification. YK: Isn't this just with? DD: No, there is more there (see kangax.github.io/domlint/#5 for details) EA: Why can't this be in the HTML living spec? AWB: That's the problem, Hixie is using internal APIs, in some cases incorrectly. MM: Is this for ES6? BE: Not important enough for ES6 AWB: not a lot of work. No support for ES6 DD: I don't think we should push for ES6 RW: Last meeting pushed back 6 months, this isn't that valuable. Conclusion/Resolution - Scheduled for ES7 Annex B 4.9 Arguments/caller poisoning on new syntactic forms - Arrows, Generators (Brian Terlson) BT: All function-like things agree on having arguments object DH: What's wrong with having the poison properties? BT: The motivation for having those properties may not apply to those new syntactic forms. MM: Keep them and they are there and configurable, or mandate w/o caller and arguments properties EA: Too much weight on edge cases MM: Born without extra properties would be fine AWB: Do we even need poison pills? BT: Can we get rid of it? AWB: Can't add properties called "caller" and "arguments" to strict mode functions MM: New forms, the properties are absent. AWB: Are these properties implemented as own properties or inherited? MM: And we agreed that Function.prototype remains a function Conclusion/Resolution - Get rid of all poisoned caller and arguments, except for the poisoned caller and arguments on Function.prototype - All functions born of non-legacy function syntactic forms do not have caller and arguments properties 4.10 Signaling stability of existing features (Domenic Denicola and Yehuda Katz) YK: Problem: ES6 signaling is too fuzzy. ES6 is a monolithic thing. Three stages: - Seeking the happy-path semantics - Find the happy-path semantics - Finalize edge cases, done. Need to AWB: What are we doing that sends the wrong message? YK: eg. when we said were pushing for a 6 month extension, people assume this means all features are unstable RW: (relaying additional experience re: above) DD: Proposed stages: Locked Stable Almost Stable Stabilizing (need to fill in descriptions from proposal document) AWB: The problem is that some things that are "locked" become "unstable" JM: It's possible to be "unstable" until spec is published STH: And publication isn't even the end either. WH: Any time someone proposes something like this, I want to ask if this would've correctly predicted the results had we done it some time ago. For example, had we done this, say, in January then comprehensions would have been in the Locked stage, but then we took them out. WH: Math functions are listed in the Locked stage in your proposal but at the same time we have important discussions at this meeting about their precision. ?: Math function precision could be a different feature. WH: That's weasel wording — when you want to change some aspect of a feature, you just move the goalposts to make that aspect a separate feature. DD: "we're" not good a the PR of specification churn MM: Not sure what this proposal is really addressing. The community has a way exxagerated sense of instability, and over-reacts to any change. So what? JM: Won't implement modules at FB because of churn. AWB: Does this change the model for ES7? DD/YK: No. AWB: So this is for the next 5 months of ES6? MM: Not enough community feedback because the feedback is limited to only those that are willing to accept churn? YK: Yes DH: Priorities: getting feedback for ES6 is low, because it's too late in the game. Focus feedback priority on ES7. Despite the inclusion of more practitioners in the TC, there are still broad misunderstandings about TC39 and ES6. DD: The perception is that ES6 is the new ES4, except that we all know this isn't true. AWB: Two things... concerns about how you're defining these stages. Who is going to do this work? I don't want to say 5 months from now that the spec is "unstable" in its entirety. Mixed discussion about implementor opinion of feature. AWB: We don't want uninformed feedback that we have to filter DH: It's really bad to not talk to the community, because people think the worst. YK: A vast majority of ES6 is stable MM: How we should be messaging as individuals. TC39 should not be spending time PL: This is all too hard to quantify and assess because change will happen. DH: Stability chart is Conclusion/Resolution - Individual evangelism, feedback and outreach Postpone Realm API to ES7 MM: Can we? DH: I'm ok with this, but don't want to be in a situation where we're permanently postponed while waiting for a security review. Let's reach out to other security reviewers. DD: I can implement a draft implementation in node for the purpose of review. AWB: The modules spec depends on realms DH: Only the ability specify the Realm in user code needs to be removed. MM: let's pull Realm from ES6, if there are issues we can address them. AWB: The Realm API cleaned up how you go about eval'ing things. DH: This clean ups can stay as-is, now ready for the reflection to come in ES7 AWB: Not going to have anyway for user code to eval in Loader. DH: w/o Realm no ability to virtualize eval. Doesn't effect utility of Loader. The specification is detailed and complete, should continue moving forward. MM: And any issues that are encountered can be addressed. DH/YK: Agreement that test implementation in node is ideal (vs. browser) Discussion re security issues created by implementations in browsers. MM: The security implications and risks are greater for Realm because this is the sandbox api. DH: Agree. Conclusion/Resolution - Realm postponed to ES7 Revisit Object.assign() JDD: The issue currently: if we allow undefined then null is the only value not allowed. I don't see anything distinguishing. It's strange that null is singled out like this. When null is used correctly, it makes sense here. DD: Then the argument is that it should also throw JDD: No, it shouldn't throw. YK: Should throw on numbers, booleans, etc. JDD: Should affect Object.keys as well YK: Doesn't have to JDD: There shouldn't be special casing for null and undefined DD: undefined triggers the default parameter, null doesn't. YK: The mental model is: undefined is missing, null is not AWB: Mentions the relaxation of rules for Object.keys YK: We should enforce the difference between null and undefined SB: (details about a study in FB code re: how null and undefined are being used) DH: We need to decide whether there is a useful programming model for these cases: null and undefined JDD: I think the boolean, number, string values are a side effect because they are just treated as empty. Propose to treat both null and undefined the same way. JM: Sounds like a better argument against boolean, number, string. AWB: (example of a number object to be extended) SB: The differnce is target vs. source, null and undefined throw for target. Mixed Discussion DH: To avoid rehashing, guiding principle: nullrepresents the no-object object, just like NaN represents the no-number number undefinedrepresents the no-value value Conclusion/Resolution - Overriding previous resolution: Object.assigndoes not throw on nullor undefined - Adhere to the guiding principle stated above Test262 Update (Brian Terlson) BT: CLA is now online, fully electronic. Lots of contributions, specifically awesome help from Sam Mikes. - Improvements to the test harness - Repeat contributors - Converting ES5 to ES6 - Converting Promise test inbound - Massive refactoring commit Discussion about Promise testing JN: Work with István to write a press release for this? BT: Yes. DD: Node runner? BT: MS has been using a node runner internally, I've pulled out the useful pieces and pushed to github: bterlson/Test262-harness Conclusion/Resolution - announcement effort
https://esdiscuss.org/notes/2014-07-29
CC-MAIN-2019-18
refinedweb
3,762
54.93
To. /** @defgroup group1 The First Group * This is the first group * @{ */ /** @brief class C1 in group 1 */ class C1 {}; /** @brief class C2 in group 1 */ class C2 {}; /** function in group 1 */ group@endlink. */ class C5 {}; /** @ingroup group1 group2 group3 group4 * namespace N1 is in four groups * @sa @link group1 The first group@endlink,. * @{ */ /** another function in group 1 */ void func2() {} /** yet another function in group 1 */ void func3() {} /** @} */ // end of group1 A member group is defined by a //@{ ... //@} /*@{*/ ... /*@}*/. /** A class. Details */ class Test { public: //@{ /** Same documentation for both members. Details */ void func1InGroup1(); void func2InGroup1(); //@} /** Function without group. Details. */ void ungroupedFunction(); void func1InGroup2();). Go to the next section or return to the index.
https://www.star.bnl.gov/public/comp/sofi/doxygen/grouping.html
CC-MAIN-2018-26
refinedweb
112
80.92
The Python programming community is well-known for their advocacy of unit testing and functional testing. Not only do these practices help assure that components and applications are written right the first time, but that they stay working through months and years of further tweaks and improvements. This article is the second in a three-part series on modern Python testing frameworks. The first article in this series introduced zope.testing, py.test, and nose, and began to describe how they can change the way that Python projects write and maintain their tests. This second article details the differences in how the three frameworks are invoked, in how they examine a project to discover tests, and how they select which of those tests then get run. Finally, the third article will look at all of the reporting features that have been developed to let testing support more and more powerful techniques. The dark ages of Python testing Python project testing was once a very ad-hoc and personal affair. A developer might start by writing each batch of tests as a separate Python script. Later, he might write a script with a name like test_all.py or tests.py that imported and ran all of his tests together. But, however well he automated the process, his approach was unavoidably idiosyncratic: every developer who joined the project had to discover where the test scripts lived and how to invoke them. If a particular Python developer found himself working on, say, a dozen different projects, then he might have a dozen different testing commands to remember. Danger was incurred by the fact that the test_all.py script, or whatever a particular project called it, probably also did a manual import of all of the other tests. If this central list of tests became out of date, usually because a developer added a new test suite which he ran by hand and forgot to add to the central script, then entire files full of of tests could be omitted from the last test suite runs that were performed before a Python package was put into production. A final drawback to this testing anarchy is that it required every test file to contain the boilerplate code necessary to run as a separate command. If you look through much Python documentation, or even inside of some Python projects today, you will see dozens of testing examples like this: # test_old.py - The old way of doing things import unittest class TruthTest(unittest.TestCase): def testTrue(self): assert True == 1 def testFalse(self): assert False == 0 if __name__ == '__main__': unittest.main() The first article in this series has already addressed why TestCase class-based testing is often not necessary in the modern world. But now, turn your attention to those last two lines of code: what are they there to accomplish? The answer is that they detect when this test_old.py script has been run stand-alone from the command line, in which case they run a unittest convenience function that will search through the module for tests and run them. This is what lets this file of tests be run separately from the project-wide test script. Many of the drawbacks to copying identical code like this into dozens, or hundreds, of different test modules should be quite obvious. One drawback that might be less obvious is the lack of standardization that this encourages. If the test_main() function is not quite clever enough to detect the tests of some particular module, then that module will probably be extended with additional behaviors that do not match how the other test suites operate. Each module can therefore wind up with subtly different conventions for how test classes are named, how they operate, and how they are run. The space age of Python testing Thanks to the arrival of major Python testing frameworks, all of the problems outlined above have been solved and, as we will see, they have been solved in roughly the same way by each of the frameworks. To begin with, all three test frameworks provide some standard way of running tests from your operating system command line. This eliminates the need for every Python project to keep a global testing script somewhere in their code base. The zope.testing package, as one would expect, has the most idiosyncratic mechanism for running tests: since Zope developers tend to set up their projects using buildout, they tend to install their testing script through a zc.recipe.testrunner recipe in the buildout.cfg file. But the result is quite consistent across different projects: in every Zope project that I have ever come across, the development buildout creates a ./bin/test script which can be counted on to invoke the project's tests. The py.test and nose projects made a more interesting decision. They each offer a command-line tool that completely removes the need for each project to have its own testing command: # Run "py.test" on the project # in the current directory... $ py.test # Run "nose" on the project # in the current directory... $ nosetests The py.test and nosetests tools even have a few command-line options that they share in common, like the -v option that makes them print the name of each test as it is executed. The day might soon arrive when a Python programmer, simply by being familiar with these two tools, will be able to run the tests of most publicly available Python packages. But, there is one last level of standardization possible! Most Python projects these days include a top-level setup.py file with their source code that supports commands like: # Common commands supported by setup.py files $ python setup.py build $ python setup.py install Many Python projects these days use the setuptools package to support extra setup.py commands beyond those available through standard Python, including a test command that runs all of a project's tests: # If a project's setup.py uses "setuptools" # then it will provide a "test" command too $ python setup.py test \ This would be the pinnacle of standardization: if projects all supported setup.py test consistently, then developers would be presented with a uniform interface for running the testing suites of all Python packages. Happily, nose supports setup.py by providing an entry point that invokes the same test-running routines as are used by the nosetests command: # A setup.py file that uses "nose" for testing from setuptools import setup setup( # ... # package metadata # ... setup_requires = ['nose'], test_suite = 'nose.collector', ) Of course, most developers will probably keep using nosetests even when their project provides a setup.py entry point, because nosetests provides more powerful command-line options. But for a new developer who just wants to check whether a package is even working on his platform before he tries to track down a bug or add a new feature, a test_suite entry point is a wonderful convenience. Automatic Python module discovery A key feature of zope.testing, py.test, and nose is that they all search a project's source code tree in an attempt to find all of its tests without having to have them centrally listed. But the rules by which they discover tests are somewhat different, and might be worth reviewing before making a choice between the frameworks. The first step that a testing framework takes is to select which directories it will search for files that might contain tests. Note that all three frameworks start in the base directory of your entire project; if you are testing a package called example, then they all start looking for tests in the parent directory that contains example. The three frameworks make somewhat different choices, however, about which directories they search: - The zope.testingtool descends recursively into all directories that are Python packages, meaning that they contain an __init__.pyfile (which is what signals to Python that they can be imported with the importstatement). This means that data and code in non-package directories is safe from being inspected, but, on the other hand, this means that every test you write will be one that a programmer could theoretically reach with the importstatement if he wanted to. Some programmers will find this uncomfortable, and wish that they could place tests somewhere that made them invisible to normal users of their package. - The py.testcommand descends into every directory and sub-directory in your project, whether a directory looks like a Python package or not. Beware that it appears to have a bug when two adjacent directories share tests of the same name. If, for example, an adjacent dir1/test.pyand dir2/test.pyfile each have a test called test_example, then py.testwill run the first test twice and ignore the second test entirely! If you are writing tests for py.testand hiding them beneath non-package directories, be careful that you keep their names unique. - The nosetest runner implements a middle way between the other two tools: it descends into every Python package, but is only willing to examine directories, if they have the word testin their name. This means that if you want to write “Keep Out” across a directory, so that nosewill not try delving into it to find tests, you can just be careful not to include the word testin its name. Unlike py.test, noseoperates correctly even if adjacent directories contain tests with the same name (but it is still helpful to keep test names distinct, so that you can tell which is which when looking at test results with the -voption). Once they have selected which directories to search, the three testing tools have remarkably similar behavior: they all look for Python modules (that is, files ending with .py) matching some specific pattern. The zope.testing tool by default uses the regular expression "tests", which will only find files named tests.py and ignore all others. You can either use a command-line option or your buildout.cfg to specify an alternative regular expression: # Snippet of a buildout.cfg file that searches for tests # in any Python module starting with "test" or "ftest". [test] recipe = zc.recipe.testrunner eggs = my_package defaults = ['--tests-pattern', 'f?test'] The py.test tools is more rigid, and always looks for Python modules whose names either start with `test_ or end with _test. The nosetests command is more flexible, and uses a regular expression (which, for the curious, is “((?:^|[\b_\.-])[Tt]est)”) that selects any modules that either start with the word test or Test, or have that word following a word boundary. You can specify a different regular expression either at the command line with the -m option, or by setting the option in your project's .noserc file. Which approach is best? While some developers always prefer flexibility and, really, it would be a terrible hassle if the zope.testing tool's interests could not be broadened out to more modules than just ones with a tests.py filename, I actually prefer py.test in this case. All projects that use py.test will necessarily share a common convention for how their tests are named, making them easier to read and maintain for other programmers. When either of the other frameworks is used instead, then reading or creating test files will take two steps: first, you have to go look at what this particular project uses as the regular expression, and only then can you start usefully inspecting its code. And if you are working on several projects at once, then you might find yourself having to keep up with several different test-file naming conventions simultaneously. Including docfiles and doctests in a test suite The obtrusive three-chevron Python prompt, >>>, has wound up being a wonderfully obvious signal, in a longer document, that the writing is illustrating what should happen at the Python prompt. This can occur in stand-alone text files that are acting as documentation, as we saw in the first article in this series: Doctest for truth and falsehood ------------------------------- The truth values in Python, named "True" and "False", are equivalent to the Boolean numbers one and zero. >>> True == 1 True >>> False == 0 True Such illustrations can also occur right inside of source code, in the docstring of a module, class, or function: def count_vowels(s): """Count the number of vowels in a string. >>> count_vowels('aardvark') 3 >>> count_vowels('THX') 0 """ return len( c for c in s if c in 'aeiou') When these tests occur in a text file, as in the first example, then the file is called a docfile. When they occur inside of docstrings inside of Python source code, like in the second example, they are called doctests. Since docfiles and doctests are very common ways to write documentation that itself serves as a test (and that will also signal when it has gone out of date and become incorrect), they are directly supported by both py.test and nose. (Users of zope.testing will have to manually create Python test cases for each file by using the DocTestSuite class from the standard doctest module.) As with its rules for finding test modules, the py.test framework has fixed procedures for supporting doctests that do not seem to be configurable, choosing standardization across projects rather than flexibility within particular ones. - If you activate its -p doctestplugin, then it will look for doctests both in the documentation strings of all of your Python modules (even the ones without the word testin their names), and also in any text files whose names both start with test_and end with the .txtextension. - If you activate its -p restdocplugin, then not only do any doctests in your .txtfiles get tested, but py.testwill insist that every .txtfile in your project be a valid Restructured Text file, and will complain if any of them cause parsing errors. The plugin can also, through further command line options, be asked to check any URLs that you specify in your documentation, and to go ahead and generate HTML versions of each of your .txtdocumentation files. A very similar set of features are supported by nose, but, as you are probably guessing, it provides a bit more flexibility. - Choosing --doctest-testsis the least intrusive option, and simply asks noseto watch out for doctests in the docstrings of the test modules that it is already examining. - The --with-doctestoption is more aggressive, and asks noseto look through all of your normal modules, the ones that it does not think are tests, but that contain normal code and find and run any doctests that occur inside of their docstrings. - Finally, --doctest-extensionlets you specify a filename extension of your own choice (most developers I know would choose .txtor .rstor perhaps .doctest). This asks noseto read through all text files in your project with the given extension, running and verifying any doctests that it finds. Although py.test and nose have a quite similar feature set here, I actually prefer the approach of nose. I like using the non-standard .rst extension for all of my Restructured Text files, so that I can teach my text editor to recognize them and give them special syntax highlighting. The nose framework and executable modules There is one caveat that should be made about the nose framework: it will, by default, avoid Python modules that are marked as executable. (You can mark a file as an executable command on Linux® with something like a chmod +x command.) The nose framework ignores such files because modules that are designed to be run straight from the command line might perform actions that make them unsafe to import. You can make commands safe to import, however, by protecting the actual actions they perform with an if statement that checks whether the module is being run or simply imported: #!/usr/bin/env python # Sample Python command if __name__ == '__main__': print "This has been run from the command line!" If you take this precaution in every one of your commands, and therefore know them to be safe to import, then you can give nose the --exe command-line option and it will examine such modules anyway. I actually prefer the behavior of py.test in this case: by ignoring whether Python modules are executable, it winds up with rules that are simpler than those of nose, and that force good practices (like protecting command logic with an if statement). But if you want to experiment with using a test framework against a legacy application perhaps containing dozens of executable modules of whose code quality you are unsure, then nose does seem like the safer tool. Conclusion The article has now covered all of the details about how these three Python testing frameworks examine your code base and select which modules they think contain tests. By providing automated discovery based on uniform conventions, the choice of any of the three major testing frameworks will both help you write more consistent test suites that can be detected and examined by machine. But what do the web frameworks do next? What do they look for inside of those modules? That is the topic of the third article in this series!est.
http://www.ibm.com/developerworks/aix/library/au-pythontesting2/index.html
CC-MAIN-2014-35
refinedweb
2,864
60.35
react-images alternatives and similar libraries Based on the "Photo / Image" category react-image-galleryResponsive image gallery, carousel, image slider react component. react-photo-galleryResponsive React Photo Gallery. react-image-lightboxReact lightbox component. react-svg-pan-zoomA React component that adds pan and zoom features to SVG. react-imgix3.2 8.8 react-images VS react-imgixAdd fast, responsive images as an image, picture, or background! react-particle-imagedemo react-compare-imagedemo react-intense1.0 4.8 react-images VS react-intenseA React component for viewing large images up close. react-lightgalleryReact wrapper for lightgallery.js Do you think we are missing an alternative of react-images or a related project? README React Images A mobile-friendly, highly customizable, carousel component for displaying media in ReactJS. Browser support Should work in every major browser... maybe even IE10 and IE11? Getting Started Start by installing react-images npm install react-images or yarn add react-images If you were using 0.x versions: library was significantly rewritten for 1.x version and contains several breaking changes. The best way to upgrade is to read the docs and follow the examples. Please note that the default footer parses HTML automatically (such as <b>I'm bold!</b>) but it does not implement any form of XSS or sanitisation. You should do that yourself before passing it into the caption field of react-images. Using the Carousel Import the carousel from react-images at the top of a component and then use it in the render function. import React from 'react'; import Carousel from 'react-images'; const images = [{ source: 'path/to/image-1.jpg' }, { source: 'path/to/image-2.jpg' }]; class Component extends React.Component { render() { return <Carousel views={images} />; } } Using the Modal Import the modal and optionally the modal gateway from react-images at the top of a component and then use it in the render function. The ModalGateway will insert the modal just before the end of your <body /> tag. import React from 'react'; import Carousel, { Modal, ModalGateway } from 'react-images'; const images = [{ source: 'path/to/image-1.jpg' }, { source: 'path/to/image-2.jpg' }]; class Component extends React.Component { state = { modalIsOpen: false }; toggleModal = () => { this.setState(state => ({ modalIsOpen: !state.modalIsOpen })); }; render() { const { modalIsOpen } = this.state; return ( <ModalGateway> {modalIsOpen ? ( <Modal onClose={this.toggleModal}> <Carousel views={images} /> </Modal> ) : null} </ModalGateway> ); } } Advanced Image Lists The simplest way to define a list of images for the carousel looks like: const images = [{ source: 'path/to/image-1.jpg' }, { source: 'path/to/image-2.jpg' }]; However, react-images supports several other properties on each image object than just source. For example: const image = { caption: "An image caption as a string, React Node, or a rendered HTML string", alt: "A plain string to serve as the image's alt tag", source: { download: "A URL to serve a perfect quality image download from", fullscreen: "A URL to load a very high quality image from", regular: "A URL to load a high quality image from", thumbnail: "A URL to load a low quality image from" }; } All these fields are optional except source. Additionally, if using an object of URLs (rather than a plain string URL) as your source, you must specify the regular quality URL.
https://react.libhunt.com/react-images-alternatives
CC-MAIN-2020-24
refinedweb
535
50.12
In this tutorial, you’ll create a Telegram bot to interact with the ESP32-CAM to request a new photo. You can request a new photo using your Telegram account from anywhere. You just need to have access to the internet in your smartphone. Note: this project is compatible with any ESP32 Camera Board with the OV2640 camera. You just need to make sure you use the right pinout for the board you’re using. Project Overview Here’s an overview of the project you’ll build: - You’ll create a Telegram bot for your ESP32-CAM; - You can start a conversation with the ESP32-CAM bot; - When you send the message /photo to the ESP32-CAM bot, the ESP32-CAM board receives the message, takes a new photo and responds with that photo; - You can send the message /flash to toggle the ESP32-CAM’s LED flash; - You can send the /start message to receive a welcome message with the commands to control the board; - The ESP32-CAM will only respond to messages coming from your Telegram account ID. This is a simple project, but shows how you can use Telegram in your IoT and Home Automation projects. The idea is to apply the concepts learned in your own projects. We also have a dedicated project for the ESP32-CAM with Telegram that covers more advanced features: Take Photos, Control Outputs, Request Sensor Readings and Motion Notifications. Introducing Telegram Telegram Messenger is a cloud-based instant messaging and voice over IP service. You can easily install it in your smartphone (Android and iPhone) or computer (PC, Mac and Linux). It-CAM will interact with the Telegram bot to receive and handle the messages, and send responses. In this tutorial, you’ll learn how to use Telegram to send messages to your bot to request a new photo taken with the ESP32-CAM. You can receive the photo wherever you are (you just need Telegram<< Note: the bot token is a very long string. To make sure you get it right, you can go to the Telegram Web Interface and copy your bot token from Sketch > Include Library > Manage Libraries. - Install the library. We’re using ArduinoJson library version 6.5.12. Code Copy the following code the Arduino IDE. To make this sketch work for you, you need to insert your network credentials (SSID and password), the Telegram Bot token and your Telegram user ID. Additionally, check the pin assignment for the camera board that you’re using. /* <WiFiClientSecure.h> #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" #include "esp_camera.h" #include <UniversalTelegramBot.h> #include <ArduinoJson.h> const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; // Initialize Telegram BOT String String CHAT_ID = "XXXXXXXXXX"; bool sendPhoto = false; WiFiClientSecure clientTCP; UniversalTelegramBot bot(BOTtoken, clientTCP); #define FLASH_LED_PIN 4 bool flashState = LOW; //Checks for new messages every 1 second. int botRequestDelay = 1000; unsigned long lastTimeBotRan; / } void handleNewMessages(int numNewMessages) { Serial.print("Handle New Messages: "); Serial.println(numNewMessages); for (int i = 0; i < numNewMessages; i++) { String chat_id = String(bot.messages[i].chat_id); if (chat_id != CHAT_ID){ bot.sendMessage(chat_id, "Unauthorized user", ""); continue; } // Print the received message String text = bot.messages[i].text; Serial.println(text); String from_name = bot.messages[i].from_name; if (text == "/start") { String welcome = "Welcome , " + from_name + "\n"; welcome += "Use the following commands to interact with the ESP32-CAM \n"; welcome += "/photo : takes a new photo\n"; welcome += "/flash : toggles flash LED \n"; bot.sendMessage(CHAT_ID, welcome, ""); } if (text == "/flash") { flashState = !flashState; digitalWrite(FLASH_LED_PIN, flashState); Serial.println("Change flash LED state"); } if (text == "/photo") { sendPhoto = true; Serial.println("New photo request"); } } } String sendPhotoTelegram() { const char* myDomain = "api.telegram.org"; String getAll = ""; String getBody = ""; camera_fb_t * fb = NULL; fb = esp_camera_fb_get(); if(!fb) { Serial.println("Camera capture failed"); delay(1000); ESP.restart(); return "Camera capture failed"; } Serial.println("Connect to " + String(myDomain)); if (clientTCP.connect(myDomain, 443)) { Serial.println("Connection successful"); String head = "--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"chat_id\"; \r\n\r\n" + CHAT_ID + "\r\n--RandomNerdTutorials\r\nContent-Disposition: form-data; name=\"photo\"; filename=\"esp32-cam.jpg\"\r\nContent-Type: image/jpeg\r\n\r\n"; String tail = "\r\n--RandomNerdTutorials--\r\n"; uint16_t imageLen = fb->len; uint16_t extraLen = head.length() + tail.length(); uint16_t totalLen = imageLen + extraLen;); uint8_t *fbBuf = fb->buf; size_t fbLen = fb->len; for (size_t n=0;n<fbLen;n=n+1024) { if (n+1024<fbLen) { clientTCP.write(fbBuf, 1024); fbBuf += 1024; } else if (fbLen%1024>0) { size_t remainder = fbLen%1024; clientTCP.write(fbBuf, remainder); } } clientTCP.print(tail); esp_camera_fb_return(fb); int waitTime = 10000; // timeout 10 seconds long startTimer = millis(); boolean state = false; while ((startTimer + waitTime) > millis()){ Serial.print("."); delay(100); while (clientTCP.available()) { char c = clientTCP.read(); if (state==true) getBody += String(c); if (c == '\n') { if (getAll.length()==0) state=true; getAll = ""; } else if (c != '\r') getAll += String(c); startTimer = millis(); } if (getBody.length()>0) break; } clientTCP.stop(); Serial.println(getBody); } else { getBody="Connected to api.telegram.org failed."; Serial.println("Connected to api.telegram.org failed."); } return getBody; } void setup(){ WRITE_PERI_REG(RTC_CNTL_BROWN_OUT_REG, 0); // Init Serial Monitor Serial.begin(115200); // Set LED Flash as output pinMode(FLASH_LED_PIN, OUTPUT); digitalWrite(FLASH_LED_PIN, flashState); // Config and init the camera configInitCamera(); // Connect to Wi-Fi WiFi.mode(WIFI_STA); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } Serial.println(); Serial.print("ESP32-CAM IP Address: "); Serial.println(WiFi.localIP()); } void loop() { if (sendPhoto) { Serial.println("Preparing photo"); sendPhotoTelegram(); sendPhoto = false; }(); } } How the Code Works This section explains how the code works. Continue reading to learn how the code works or skip to the Demonstration section. Importing Libraries Start by importing the required libraries. #include <Arduino.h> #include <WiFi.h> #include <WiFiClientSecure.h> #include "soc/soc.h" #include "soc/rtc_cntl_reg.h" #include "esp_camera.h" #include <UniversalTelegramBot.h> #include <ArduinoJson.h> Network Credentials Insert your network credentials in the following variables. const char* ssid = "REPLACE_WITH_YOUR_SSID"; const char* password = "REPLACE_WITH_YOUR_PASSWORD"; Telegram User ID Insert your chat ID. The one you’ve got from the IDBot. String CHAT_ID = "XXXXXXXXXX"; Telegram Bot Token Insert your Telegram Bot token you’ve got from Botfather on the BOTtoken variable. String BOTtoken = "XXXXXXXXXX:XXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXXX"; The sendPhoto boolean variable indicates whether it is time to send a new photo to your telegram account. By default, it is set to false. bool sendPhoto = false; Create a new WiFi client with WiFiClientSecure. WiFiClientSecure clientTCP; Create a bot with the token and client defined earlier. UniversalTelegramBot bot(BOTtoken, clientTCP); Create a variable to hold the flash LED pin (FLASH_LED_PIN). In the ESP32-CAM AI Thinker, the flash is connected to GPIO 4. By default, set it to LOW. define FLASH_LED_PIN 4 bool flashState = LOW; The botRequestDelay and lasTimeBotRan variables; ESP32-CAM Initialization The following lines assign the ESP32-CAM AI-Thinker pins. If you’re using a different ESP32 camera model, don’t forget to change the pinout (read ESP32-CAM Camera Boards: Pin and GPIOs Assignment Guide). / The configInitCamera() function initializes the ESP32 camera. } handleNewMessages() The handleNewMessages() function handles what happens when new messages arrive. void handleNewMessages(int numNewMessages) { Serial.print("Handle New Messages: "); Serial.println(numNewMessages); It checks the available messages: for (int i = 0; i < numNewMessages; i++) { Get the chat ID for a particular message and store it in the chat_id variable. The chat ID identifies. This is useful if you happen to forget what are the commands to control your board. if (text == "/start") { String welcome = "Welcome , " + from_name + "\n"; welcome += "Use the following commands to interact with the ESP32-CAM \n"; welcome += "/photo : takes a new photo\n"; welcome += "/flash : toggles flash LED \n"; bot.sendMessage(CHAT_ID, welcome, ""); } Sending a message to the bot is very simple. You just need to use the sendMessage() method on the bot object and pass as arguments the recipient’s chat ID, the message, and the parse mode. bool sendMessage(String chat_id, String text, String parse_mode = ""); In our example, we’ll send the message to the ID stored on the CHAT_ID variable (that corresponds to your personal chat id) and send the message saved on the welcome variable. bot.sendMessage(CHAT_ID, welcome, ""); If it receives the /flash message, invert the flashState variable and update the flash led state. If it was previously LOW, set it to HIGH. If it was previously HIGH, set it to LOW. if (text == "/flash") { flashState = !flashState; digitalWrite(FLASH_LED_PIN, flashState); Serial.println("Change flash LED state"); } Finally, if it receives the /photo message, set the sendPhoto variable to true. Then, in the loop(), check the value of the sendPhoto variable and proceed accordingly. if (text == "/photo") { sendPhoto = true; Serial.println("New photo request"); } sendPhotoTelegram() The sendPhotoTelegram() function takes a photo with the ESP32-CAM. camera_fb_t * fb = NULL; fb = esp_camera_fb_get(); if(!fb) { Serial.println("Camera capture failed"); delay(1000); ESP.restart(); return "Camera capture failed"; } Then, it makes an HTTP POST request to send the photo to your telegram bot.); setup() In the setup(), initialize the Serial Monitor. Serial.begin(115200); Set the flash LED as an output and set it to its initial state. pinMode(FLASH_LED_PIN, OUTPUT); digitalWrite(FLASH_LED_PIN, flashState); Call the configInitCamera() function to configure and initialize the camera. configInitCamera(); Connect your ESP32-CAM to your local network. WiFi.mode(WIFI_STA); Serial.println(); Serial.print("Connecting to "); Serial.println(ssid); WiFi.begin(ssid, password); while (WiFi.status() != WL_CONNECTED) { Serial.print("."); delay(500); } loop() In the loop(), check the state of the sendPhoto variable. If it is true, call the sendPhotoTelegram() function to take and send a photo to your telegram account. if (sendPhoto) { Serial.println("Preparing photo"); sendPhotoTelegram(); When it’s done, set the sendPhoto variable to false. sendPhoto = false; In the loop(), you also check for new messages every second.-CAM board. Don’t forget to go to Tools > Board and select the board you’re using. Go to Tools > Port and select the COM port your board is connected to. After uploading the code, press the ESP32-CAM on-board; - /flash inverts the state of the LED flash; - /photo takes a new photo and sends it to your Telegram account. At the same time, on the Serial Monitor, you should see that the ESP32-CAM is receiving the messages. If you try to interact with your bot from another account, you’ll get the “Unauthorized user” message. Wrapping Up In this tutorial you’ve learned how to send a photo from the ESP32-CAM to your Telegram account. As long as you have access to the internet in your smartphone, you can request a new photo no matter where you are. This is great to monitor your ESP32-CAM from anywhere in the world. We have other tutorials using Telegram that you might be interested in: - ESP32-CAM with Telegram: Take Photos, Control Outputs, Request Sensor Readings and Motion Notifications - Telegram: ESP32 Motion Detection with Notifications - Telegram: Control ESP32/ESP8266 Outputs - Telegram: Request ESP32/ESP8266 Sensor Readings Learn more about the ESP32-CAM with our resources: Thanks for reading. 42 thoughts on “Telegram: ESP32-CAM Take and Send Photo (Arduino IDE)” Hi Sara, very interesting article about the ESP32 and the OV2640 (and alike) camera ! Do you intend to publish some articles about the Sipeed Maixduino AI processor Kit having also an ESP32 with a OV2640 camera on board and beeing also programmed with the Arduini IDE ? I believe that many your follower folks would like you, Sara or Ruis having published on this modern topic on AI and alike ! thanks a lot, Bruno Hi Bruno. Thanks for the suggestion. I have that board, but I didn’t have the time to look at it yet. Regards, Sara Very good tutorial. Working right out of the box, like they say. Thank you, great for survey from distance. Really impressed. I have been struggling for ages with another (well-known) IoT platform via a Raspberry as a gateway, but could never make it stable. This took me an hour tops, including reading the techo bits, and its up and running with no problems. Except I am having a problem with this. I was getting an image, but then I realised it is minimum resolution, and the file size is only about 5K even though it is set for UXGA. What I found is that this piece of code is keeping it in a low res mode, although I see the point in that for timelapse: s->set_framesize(s, FRAMESIZE_CIF); // UXGA|SXGA|XGA|SVGA|VGA|CIF|QVGA|HQVGA|QQVGA And so I changed the framesize to _SVGA, and also changed the camera config to set it to SVGA mode even if psram is found. I now get a larger file size generated (as confirmed by a println statement showing me fbLen). However it now seems to time out before the image is uploaded to Telegraph. In the… while ((startTimer + waitTime) > millis()) … loop the “.” is printed continuously until the timeout occurs. I have tried lengthening waitTime but it still times out. I am running the ESP-CAM with Arduino rev 1.8.13. This must be a newer version CAM, as it has a micro-USB connector and signal converter incorporated. It works perfectly with the Camera Web Server example, and I can change resolutions up to the max. Thanks, Derek Hi, has this issue been solved? I think it would be great to send a photo with a better resolution but is it possible? Hi Chong – no resolution. Been a while since I was playing with it, but I did not get anywhere. It seems to time out from the Telegraph end of things with larger file sizes. I have just come back to this project and about to try other options, probably having to email the photo as an attachment. I have been told that smtp2go.com will do this from an app. Also my private email provider (a paid service) has recently introduced an app specific password system which would get over my reluctance to embed my master email passwords into a device. Good luck, Derek Thank you Derek😁 One more thing that just came to me from memory. Even on mundane text only messages, there would sometimes be long delays (like10 or more minutes) before the reply would come back. So most likely it is just each package being sent not getting an acknowledgement before the ESP32 times out. Hi, i just tested SVGA and for me it is working (esp32-Cam AI Thinker) ” s->set_framesize(s, FRAMESIZE_SVGA); ” but no response for SXGA or XGA Hi. Change the uint16_t variables to uint32_t. Regards, Sara Thanks Sara. That sorts out the Telegraph timeout side of things, and images are being received reliably and in good time. However there is a deeper issue, which looks to be in the esp_camera library. It does not seem to like transferring larger amounts of image data from the camera. It works okup to SXGA (quality=8) as long as frame_size is still set yo UXGA. At that I get an image that seems like 1280×1024 (although it is chunky on lines, so not sure if it really is. Also file size is only around 75kB. In UXGA I get an image 1280×960 and around 65kB file size. Sara and Rui, Many thanks for your esp 32 projects, i am trying esp 32 with telegram app taking photo and sending via telegram app, during the uploading i am facing this error message Error COMPILING FOR BOARD ESP 32 WROVER Module. pls help to fix this problem. S.Yogaraja TN- INDIA Great guide! Thanks a lot! Your tutorials are very helpful (aspecialy about the TTGO T-Call board)! Hi there, I receive a error message when compiling: #include “soc/soc.h” No such file or directory #include “soc/rtc_cntl_reg.h” No such file or directory Which library is this a part of? Regards, Leon Sorted – I had the wrong board selected…😒 I have the same problem still without solving. Hello, I am still not receiving photos on the Telegram bot. Program seems to work (start/flash), but pictures do not come true. I have tried changing the uint16 to 32 and used all different resolutions. Any ideas? ESP32-AI thinker board. Thx Hi Sara: There is a bug in the code. Please modify it. I am truly grateful to you for what you have done. while ((startTimer + waitTime) > millis()) { Serial.print("."); delay(100); while (clientTCP.available()) { char c = clientTCP.read(); if (state==true) getBody += String(c); //Correct if (c == '\n') { if (getAll.length()==0) state=true; getAll = ""; } else if (c != '\r') getAll += String(c); // if (state==true) getBody += String(c); //Incorrect startTimer = millis(); } if (getBody.length()>0) break; } Hi. Thanks for telling me that. We’ve updated this and other codes. Regards, Sara If this line of code was on an incorrect line, what was the fault that it generated ? My esp32-cam worked good i think from the start in September 2020. Hi, I am from Iran and Telegram has been filtered in Iran and I could not do this project because the Iranian Internet is filtered for Telegram. You can help Hi. I’m sorry, but I don’t know how I can help you. Regards, Sara thanks a lot Do you know what code I should add if I want to connect to Telegram using a proxy? Or how can I connect to Telegram with an external host? Thanks You can perhaps look for Telegram alternatives, but there you must find out how to implement the bots talking to ESP32-Cam. thanks a lot I want to connect the ESP32 cam board to Wi-Fi inside the Arduino environment using a VPN or proxy. In this case, what library can I use and what will the codes look like? You could try this. I have used this VPN service, so cannot advise further. ESP 3.1 doesn’t works. Use 3.0 Greetings to authors, Sara and Rui! You are doing greatest work for hobbyist embedded programmers teaching. I did some experimental work to port this ESP32-CAM, trying to get connected with telegram bot on GSM network, by stand alone SIM800L module, the same, as on TTGO T-Call The sketch is almost the same compared with original version, beside of connection to Internet. All WiFi oriented initialization and and commands are removed and were written beneath lines: #include <TinyGsmClient.h> #define SerialMon Serial #define SerialAT Serial1 // Your GPRS credentials (leave empty, if not needed) const char apn[] = “xxxxxxxxxxxxxx”; // APN use const char gprsUser[] = “xxxxxxx”; // GPRS User const char gprsPass[] = “xxxxxxx”; // GPRS Password // SIM card PIN (leave empty, if not defined) const char simPIN[] = “****”; // Configure TinyGSM library #define TINY_GSM_MODEM_SIM800 // Modem is SIM800 #define TINY_GSM_RX_BUFFER 1024 // Set RX buffer to 1Kb #define TINY_GSM_USE_GPRS true #define USE_SSL #define DUMP_AT_COMMANDS // Add a reception delay – may be needed for a fast processor at a slow baud rate #define TINY_GSM_YIELD() { delay(2); } #define TINY_GSM_DEBUG SerialMon // SIM800L to ESP32-CAM pins #define MODEM_RST 2 #define MODEM_TX 14 #define MODEM_RX 15 // TinyGSM Client for Internet connection #ifdef USE_SSL TinyGsmClientSecure client(modem); const int port = 443; #else TinyGsmClientSecure client(modem); const int port = 80; #endif The following is the dump of terminal: 10:15:23.890 -> AT 10:15:24.195 -> AT 10:15:24.229 -> 10:15:24.229 -> OK 10:15:24.229 -> ATE0 10:15:24.263 -> 10:15:24.263 -> OK 10:15:24.263 -> AT+CMEE=2 10:15:24.263 -> 10:15:24.304 -> OK 10:15:24.304 -> AT+GMM 10:15:24.304 -> 10:15:24.304 -> SIMCOM_SIM800L 10:15:24.338 -> 10:15:24.338 -> OK 10:15:24.338 -> [11525] ### Modem: SIMCOM SIM800L 10:15:24.372 -> [11525] ### Modem: SIMCOM SIM800L 10:15:24.372 -> AT+CLTS=1 10:15:24.372 -> 10:15:24.372 -> OK 10:15:24.372 -> AT+CBATCHK=1 10:15:24.406 -> 10:15:24.406 -> OK 10:15:24.406 -> AT+CPIN? 10:15:24.440 -> 10:15:24.440 -> +CME ERROR: CFUN state is 0 or 4 10:15:25.457 -> AT+CPIN? 10:15:25.491 -> 10:15:25.491 -> RDY 10:15:25.491 -> 10:15:25.491 -> +CFUN: 1 10:15:25.525 -> 10:15:25.525 -> +CPIN: READY 10:15:25.559 -> 10:15:25.559 -> +CPIN: READY 10:15:25.593 -> 10:15:25.593 -> OK 10:15:35.600 -> 10:15:35.600 -> AT+CPIN? 10:15:35.634 -> 10:15:35.634 -> Call Ready 10:15:35.634 -> 10:15:35.634 -> SMS Ready 10:15:35.669 -> 10:15:35.669 -> *PSUTTZ: 2021,3,11,6,15,31,”+16″,0 10:15:35.702 -> [22863] ### Network time and time zone updated. 10:15:35.702 -> 10:15:35.702 -> DST: 0 10:15:35.702 -> [22875] ### Daylight savings time state updated. 10:15:35.702 -> 10:15:35.702 -> +CPIN: READY 10:15:35.736 -> 10:15:35.736 -> OK 10:15:35.736 -> AT+CPIN=”8722″ 10:15:35.770 -> 10:15:35.770 -> +CME ERROR: operation not allowed 10:15:35.804 -> Connecting to APN: internet.beeline.am 10:15:35.804 -> AT+CIPSHUT 10:15:35.838 -> 10:15:35.838 -> SHUT OK 10:15:35.875 -> AT+CGATT=0 10:15:36.590 -> 10:15:36.590 -> OK 10:15:36.590 -> AT+SAPBR=3,1,”Contype”,”GPRS” 10:15:36.624 -> 10:15:36.658 -> OK 10:15:36.658 -> AT+SAPBR=3,1,”APN”,”internet.beeline.am” 10:15:36.692 -> 10:15:36.692 -> OK 10:15:36.726 -> AT+SAPBR=3,1,”USER”,”internet” 10:15:36.760 -> 10:15:36.760 -> OK 10:15:36.760 -> AT+SAPBR=3,1,”PWD”,”internet” 10:15:36.794 -> 10:15:36.828 -> OK 10:15:36.828 -> AT+CGDCONT=1,”IP”,”internet.beeline.am” 10:15:36.862 -> 10:15:36.862 -> OK 10:15:36.896 -> AT+CGACT=1,1 10:15:39.377 -> 10:15:39.377 -> *PSUTTZ: 2021,3,11,6,15,37,”+16″,0 10:15:39.411 -> [26576] ### Network time and time zone updated. 10:15:39.411 -> 10:15:39.411 -> DST: 0 10:15:39.411 -> [26590] ### Daylight savings time state updated. 10:15:45.529 -> 10:15:45.529 -> *PSUTTZ: 2021,3,11,6,15,43,”+16″,0 10:15:45.563 -> [32746] ### Network time and time zone updated. 10:15:45.563 -> 10:15:45.563 -> DST: 0 10:15:45.597 -> [32758] ### Daylight savings time state updated. 10:15:45.631 -> 10:15:45.631 -> *PSUTTZ: 2021,3,11,6,15,43,”+16″,0 10:15:45.665 -> [32850] ### Network time and time zone updated. 10:15:45.665 -> 10:15:45.699 -> DST: 0 10:15:45.699 -> [32862] ### Daylight savings time state updated. 10:15:45.699 -> 10:15:45.699 -> +CIEV: 10,”28301″,”Beeline AM”,”Beeline AM”, 0, 0 10:15:45.835 -> 10:15:45.835 -> OK 10:15:45.835 -> AT+SAPBR=1,1 10:15:46.073 -> 10:15:46.073 -> OK 10:15:46.107 -> AT+SAPBR=2,1 10:15:46.107 -> 10:15:46.107 -> +SAPBR: 1,1,”10.111.24.84″ 10:15:46.175 -> 10:15:46.175 -> OK 10:15:46.175 -> AT+CGATT=1 10:15:46.209 -> 10:15:46.209 -> OK 10:15:46.209 -> AT+CIPMUX=1 10:15:46.243 -> 10:15:46.243 -> OK 10:15:46.243 -> AT+CIPQSEND=1 10:15:46.277 -> 10:15:46.277 -> OK 10:15:46.277 -> AT+CIPRXGET=1 10:15:46.311 -> 10:15:46.311 -> OK 10:15:46.311 -> AT+CSTT=”internet.beeline.am”,”internet”,”internet” 10:15:46.379 -> 10:15:46.379 -> OK 10:15:46.413 -> AT+CIICR 10:15:46.413 -> 10:15:46.413 -> OK 10:15:46.447 -> AT+CIFSR;E0 10:15:46.447 -> 10:15:46.447 -> 10.111.24.84 10:15:46.481 -> 10:15:46.481 -> OK 10:15:46.515 -> AT+CDNSCFG=”8.8.8.8″,”8.8.4.4″ 10:15:46.549 -> 10:15:46.549 -> OK 10:15:46.549 -> Waiting for network…AT+CREG? 10:15:46.583 -> 10:15:46.583 -> +CREG: 0,1 10:15:46.583 -> 10:15:46.583 -> OK 10:15:46.617 -> success 10:15:46.617 -> AT+CREG? 10:15:46.617 -> 10:15:46.617 -> +CREG: 0,1 10:15:46.651 -> 10:15:46.651 -> OK 10:15:46.651 -> Network connected 10:15:46.651 -> AT+CIFSR;E0 10:15:46.685 -> 10:15:46.685 -> 10.111.24.84 10:15:46.719 -> 10:15:46.719 -> OK 10:15:46.719 -> Local IP:10.111.24.84 10:15:46.719 -> AT+CSQ 10:15:46.719 -> 10:15:46.719 -> +CSQ: 28,0 10:15:46.753 -> 10:15:46.753 -> OK 10:15:46.753 -> Signal quality:28 10:15:47.400 -> Camera init Ok 10:15:47.434 -> AT+CIPRXGET=4,0 10:15:47.468 -> 10:15:47.468 -> +CIPRXGET: 4,0,0 10:15:47.502 -> 10:15:47.502 -> OK 10:15:47.502 -> AT+CIPSTATUS=0 10:15:47.536 -> 10:15:47.536 -> +CIPSTATUS: 0,,””,””,””,”INITIAL” 10:15:47.604 -> 10:15:47.604 -> OK 10:15:47.638 -> AT+CIPCLOSE=0,1 10:15:47.638 -> 10:15:47.638 -> +CME ERROR: operation not allowed 10:15:47.707 -> AT+CIPSSL=1 10:15:47.707 -> 10:15:47.707 -> OK 10:15:47.707 -> AT+CIPSTART=0,”TCP”,”api.telegram.org”,443 10:15:47.780 -> 10:15:47.780 -> OK 10:15:48.969 -> 10:15:48.969 -> 0, CLOSE OK 10:15:49.003 -> AT+CIPRXGET=4,0 10:15:49.003 -> 10:15:49.003 -> +CIPRXGET: 4,0,0 10:15:49.038 -> 10:15:49.038 -> OK 10:15:49.038 -> AT+CIPSTATUS=0 10:15:49.076 -> 10:15:49.076 -> +CIPSTATUS: 0,0,”TCP”,”149.154.167.220″,”443″,”CLOSED” 10:15:49.212 -> 10:15:49.212 -> 10:15:49.212 -> OK 10:15:49.212 -> See what bot updates 0 10:15:50.230 -> AT+CIPRXGET=4,0 10:15:50.230 -> 10:15:50.230 -> +CIPRXGET: 4,0,0 10:15:50.264 -> 10:15:50.264 -> OK 10:15:50.297 -> AT+CIPSTATUS=0 10:15:50.297 -> 10:15:50.297 -> +CIPSTATUS: 0,0,”TCP”,”149.154.167.220″,”443″,”CLOSED” Upon hitting /start on telegram bot nothing useful happens, just bot standard invitation appears. What could be the problem? Of course, also this is implemented: UniversalTelegramBot bot(BOTtoken, client); By the way, I did a try to get worked the original code with WiFi, but again none of performance. The photo by email sending sketch has been worked, thus it’s absolutely could be stated that my board is ok. Hi, I have tried out the code on one unit of ESP32_CAM, it work well. I can received picture on Telegram. When I setup another ESP32-CAM and switched on two ESP32-CAM at the same time. I have problem, only one ESP32-CAM is working, the second one is not responding to telegram command /photo. Can we run multiple ESP32-CAMs with the same TelegramBot account ? When I switched off the ESP32-CAMs. Restart only one unit of ESP32-CAM again, it is not working anymore. It did not response to Telegram command /start, photo or /flash. I couldn’t find anything that has gone wrong with the two units of ESP32-CAMs that fail to response to Telegram commands now. Please help. Hi. I haven’t tried that. So, I’m not sure if it is possible or if it is something wrong with your setup. But, maybe a good solution is to use two bots and put both bots in the same group with the recipient of the messages. We have this tutorial about telegram groups: Regards, Sara The two units of ESP32-CAMs not able to accept TelegramBot commands /start, /flash and /photo. Serial monitor show WiFi is OK. 01:20:59.717 -> x⸮x⸮x⸮x⸮⸮xxxx⸮x⸮⸮⸮⸮⸮⸮⸮⸮x⸮⸮⸮⸮⸮x⸮xx⸮xets Jun 8 2016 00:22:57 01:20:59.717 -> 01:20:59.717 -> rst:0x1 (POWERON_RESET),boot:0x12 (SPI_FAST_FLASH_BOOT) 01:20:59.717 -> configsip: 0, SPIWP:0xee 01:20:59.717 -> clk_drv:0x00,q_drv:0x00,d_drv:0x00,cs0_drv:0x00,hd_drv:0x00,wp_drv:0x00 01:20:59.717 -> mode:DIO, clock div:1 01:20:59.717 -> load:0x3fff0018,len:4 01:20:59.717 -> load:0x3fff001c,len:1216 01:20:59.717 -> ho 0 tail 12 room 4 01:20:59.717 -> load:0x40078000,len:10944 01:20:59.717 -> load:0x40080400,len:6388 01:20:59.815 -> entry 0x400806b4 01:21:01.677 -> 01:21:01.677 -> Connecting to ShiHan 01:21:01.677 -> . 01:21:02.136 -> ESP32-CAM IP Address: 192.168.86.26 I program the CAM with Video Streaming Web Server. No issue. It is working fine. Successfully programmed the ESP Cam, works with the Webserver example. Says it connected successfully and then no further interaction (tried /start, /flash, /photo inside the bot). Bot Token an my ID are fine. Used the TeleframBot Library as ZIP as described. Maybe: The ArduinoJSON in the latest version (6 upwards) causes a lot of debug errors indicating that that’s version 5 code, so I changed back to the latest version 5 of ArduinoJSON and it compiles without error. Stretch goal: Can I ommit the CHAT_ID if I want anybody to access the cam? Any hints? Hi Martin. Yes, you can omit the chat id. Make sure that you are interacting with the right bot in your Telegram account. Regards, Sara Hello Sara, I found the reason why it did not work (found it in the echo bot example): I had to add the middle line with the setCACert WiFi.begin(WIFI_SSID, WIFI_PASSWORD); clientTCP.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org while (WiFi.status() != WL_CONNECTED) Now this part works. Got a new one now: After requesting a photo an error message is displayed in the monitor: {“ok”:false,”error_code”:400,”description”:”Bad Request: group chat was upgraded to a supergroup chat”,”parameters”:{“migrate_to_chat_id”:-1001395804118} Thank you very much! And I answer it myself: When you change your group (e.g. add admin users) the ID changes sp just update the Group ID in the code and it will be fine! Error when i compile : Line 245: client.setCACert(TELEGRAM_CERTIFICATE_ROOT); // Add root certificate for api.telegram.org But it’s “clientTCP.” , maybe you can update the code 😉 Hi. That was a mistake during an update. It is fixed now. Thanks for telling me. Regards, Sara Hello Rui and Sara! Finally I got worked this project on GSM connection, having used SIM800C module. If you are interested in publishing my version of code, based on your original project, I’m ready to give the source code. Hi. That’s great! Thanks! Please send a message to Rui via our support form: Regards, Sara
https://randomnerdtutorials.com/telegram-esp32-cam-photo-arduino/
CC-MAIN-2021-25
refinedweb
5,198
69.79
Created on 2017-02-23 20:05 by dhimmel, last changed 2019-12-07 14:14 by methane. This issue is now closed. The. For discussion on how to implement this, see + + + Implementation now moved to The discussion is scattered between different tracker issues and pull requests. Let continue it in one place. I don't think we should add too much options for controlling any little detail. json.tools is just small utility purposed mainly for debugging. If you need to control more details, it is not hard to write simple Python script. For example, for "compact" output: $ python3 -c "import sys, json; json.dump(json.load(sys.stdin), sys.stdout, separators=(',', ':'))" To recap the discussion from: there are three potential mutually exclusive command line options that have been suggested. There are as follows. ```python import json obj = [1, 2] print('--indent=4') print(json.dumps(obj, indent=4)) print('--no-indent') print(json.dumps(obj, indent=None)) print('--compact') print(json.dumps(obj, separators=(',', ':'))) ``` which produces the following output: ``` --indent=4 [ 1, 2 ] --no-indent [1, 2] --compact [1,2] ``` Currently, has implemented --indent and --no-indent. One suggestion was to replace --no-indent with --compact, but that would prevent json.tool from outputting YAML < 1.2 compatible JSON. Therefore, the main question is whether to add --compact or not? There is a clear use case for --compact. However, it requires a bit more "logic" as there is no `compact` argument in json.dump. Therefore @serhiy.storchaka suggests not adding --compact to keep json.tool lightweight. I disagree that json.tool is "mainly for debugging". I encounter lot's of applications were JSON needs to be reformatted, so I see json.tool as a cross-platform command line utility. However, I am more concerned that the JSON API may change, especially with respect to the compact encoding (see). Therefore, it seems prudent to let the API evolve and later revisit whether a --compact argument makes sense. The danger of adding --compact now would be if json.dump adopts an argument for --compact that is not compact. Then aligning the json.tool and json.dump terminology could require backwards incompatible changes. I'm not particularly interested in this feature. Adding two or three options looks excessive. Python is a programming language and it is easy to write a simple script for your needs. Much easier than implement the general command line interface that supports all options of programming API. Easier, but if we do it in the tool, then it is done for everyone and they don't *each* have to spend that "less time" writing their own script. And --indent and --compact are both useful for debugging/hand testing, since it allows you to generate the input your code is expecting, and input your code might not be expecting. On the other hand, I'm not contributing much these days, so I'm not in a good position to be suggesting additions to the support burden :(. @ser.. Probably the best thing we could do here is to mirror the options available in similar tools, such as jq: The relevant options here would be: --indent --tab --compact-output --sort-keys The default indent in jq is 2, which I tend to prefer these days, but maybe 4 is still appropriate given PEP 8: $ echo '[{}, {"a": "b"}, 2, 3, 4]' | jq [ {}, { "a": "b" }, 2, 3, 4 ] This is how jq interprets --compact-output: $ echo '[{}, {"a": "b"}, 2, 3, 4]' | jq --compact-output [{},{"a":"b"},2,3,4] I do not think that it's worth having the command-line tool cater to people that want to indent in other ways (e.g. using a string that isn't all spaces or a single tab). @bob.ippolito thanks for pointing to jq as a reference implementation. I updated the pull request () to implement all of the relevant options. Currently, the PR supports the following mutually exclusive arguments: --indent --no-indent --tab --compact These additions took 16 new lines of code in tool.py and 41 new lines of tests. However, I am happy to refactor the tests to be less repetitive if we choose to go forward with these changes. @serhiy.storchaka I took a maximalist approach with respect to adding indentation options to GH #345. Although I know not all of the options may get merged, I thought we might as well work backwards. However, the more I think about it, I do think every option above is a unique and valuable addition. I think that even with the changes, json.tool remains a lightweight wrapper json.load + json.dump. I'm OK to options in current pull request. And I think this bike-shedding discussion is not so important to pay our time and energy. Does anyone have strong opinion? If no, I'll merge the PR. I don't think this PR should be merged. It adds too much options. I think that if one needs more control than the current json.tools command line interface gives, he should use the Python interface. Don't forget, that Python is a programming language. So what do we do about this? Two possibilities: 1. We merge PR 9765 and close PRs 345 and 201, as 9765 seems more straighforward and was already approved. 9765 should be resubmitted to be merged since the base repo does not exist anymore, I could do that. 2. We consider that this is out of scope for Python, and since jq is widely used, it does not make a lot of sense to include it. We should then close all PRs to keep our pull requests clean I suggest going with 2 Since opening this issue, I've encountered several additional instances where indentation control would have been nice. I don't agree that jq is a sufficient substitute: 1. jq is generally not pre-installed on systems. For projects where users are guaranteed to have Python installed (but may be on any operating system), it is most straightforward to be able to just use a python command and not have to explain how to install jq on 3 different OSes. 2. jq does a lot more than prettifying JSON. The simple use case of reformatting JSON (to/from a file or stdin/stdout) can be challenging. 3. json.tool describes itself as a "simple command line interface to ... pretty-print JSON objects". Indentation is an essential aspect of pretty printing. Why even have this CLI if we're unwilling to add essential basic functionality that is already well supported by the underlying json.dump API? Python excels at APIs that match user needs. It seems like we're a small change away from making json.tool flexible enough to satisfy real-world needs. So I'm in favor of merging PR 9765 or PR 345. I'm happy to do the work on either to get them mergeable based on whatever specification we can agree on here. [Ser). New changeset 03257949bc02a4afdf2ea1eb07a73f8128129579 by Inada Naoki (Daniel Himmelstein) in branch 'master': bpo-29636: Add --(no-)indent arguments to json.tool (GH-345) New changeset 15fb7fa88187f5841088721a43609bffe64a8dc7 by Inada Naoki (Daniel Himmelstein) in branch 'master': bpo-29636: json.tool: Add document for indentation options. (GH-17482)
https://bugs.python.org/issue29636
CC-MAIN-2021-43
refinedweb
1,208
66.33
0 I am taking my first class in Java and am having problems with converting lowercase letters to uppercase and am not having success. The program compiles and executes. However, the lowercase letters input by the user are not converted to uppercase. I think the problem is very simple, but I can't see it. Does anyone have a suggestion? Dehatim /** This program reads a string of lowercase letters typed on the keyboard, converts them to uppercase letters, and displays them. */ // Import necessary classes. import java.util.Scanner; // Start main part of program. public class CaseConversion { public static void main(String[] args) { // Create a scanner keyboard to accept input from the keyboard. Scanner keyboard1 = new Scanner(System.in); // Ask user to type lowercase alphabet. System.out.println("Welcome to Letter Conversion!\n"); System.out.println("Enter the letters of the alphabet in lowercase"); // Read in user entry. String word1 = keyboard1.next( ); [B]// Find out what's in the string. word1.substring(0, 26); // Convert input into uppercase letters. String word2 = word1.substring(0, 26); word2.toUpperCase(); // Output the result. System.out.println("The alphabet is now is [/B] [B] uppercase:\n" + [/B][B]word2); [/B] } // end of main() } // end of class CaseConversion
https://www.daniweb.com/programming/software-development/threads/56069/converting-lowercase-type-to-uppercase-new-programmer
CC-MAIN-2017-09
refinedweb
202
54.08
The German edition of Linux Magazin (de) is currently featuring an article (Jan's translation, Google's version) on Umbrello. Umbrello (screenshots) is a UML drawing tool that will be shipped with KDE 3.2 in the coming months. The article gives the user a short introduction to the latest stable version (1.1.1), and also lists some known problems in the current code base. So help us test Umbrello and get rid of those last remaining bugs! Whoo-hoo. Was anyone able to make any sense out of the English translation of that page? I could barely understand anything it said. Read some slower or reread before you post ;-) Here you go Mike:google_en And it is quite a good translation (IMHO). > Read some slower or reread before you post ;-) How slow? ;-) > And it is quite a good translation (IMHO). I admit since I don't speak German I can't evaluate that, but I can try to make sense of the following in English as a particularly disturbing example... "Again abandoned in order to return to the showing mode, it proves the input mode as amazingly tricky. To expect it would be that to everyone mouse-click outside of the text field the editing mode terminated." After rereading some things that made no sense they began to make small sense. Some, like the above text, make little sense at all. Frankly I'd rather be standing on a street corner in Frankfurt exchanging hand signals and pantomime than reading this as my mind bobs up and down trying to assemble it into a rational sentence structure. At least we could communicate on where to get a good pilsner. ;-) My guess: "Again, leaving input mode in order to return to display mode proved amazingly tricky. I would have expected that clicking outside of the text field would terminate the edition mode." But really, compared to babelfish, this is great work :-) Footnote: I speak no german, and english ain't my language either. Hell, I don't even understand UML! > Footnote: I speak no german, and english ain't my language either. Hell, I don't even understand UML! ROTFLMAO The man who claims to know nothing speaks wisely. He's hauniting me... taunting me... Roberto, when you finish translating the translation please send me a copy. Be sure to include plenty of those witty footnotes. ;-) Eric "To exit the edit mode again to return to the view mode is amazingly tricky. We would expect that any click outside of the text-field terminated the edit mode. Actually one must confirm changes with the [Return] key or cancel with the [ESC] key. Clicking into the help window or a double click on another structure component exits the input mode as well, although in these cases Umbrello loses any changes made." regards, chris Not really, it is not a good translation. You cant expect to second guess the content of a technical document... Hey! What is everyone complaining about the google translation? IMO it's pretty impressive what the google translation sometimes can achieve today. Don't you think you are expecting a bit to much if such a complicated article is to be translated automatically?? This article is especially difficult because it heavily uses the ability of the German language to put many parts in arbitary order into a sentence and then link them with grammar and sometimes only the order gives the meaning. You can do that in English. Therefore, the longer a sentence the more difficult is it for a computer to translate properly because it only translates words. In cannot "translate" a different word order into something. Anyway, I made a quick translation which isn't perfect because I did it in 30 minutes and have no idea about UML but I hope it's easier to understand than the google version: Umbrello is the best tool for UML on Linux. I've tried to install Rational Rose on my Débian during 4 hours. No way, it can't start. Other tool like dia are not made for UML, and that's why IMHO there are not user friendly as UML modeller. Go Umbrello ! Of course you haven't tried Poseidon (), it's great for all kinds of UML. And it's based off a free software product. But it's proprietary, which is why I'm posting anonymously. Why didn't give the link to the product it is based of? But it is very slow and not integrated into KDE desktop. Of course it has other strengths, but I think the open source community is big enough to support at least 2 UML tools. Steinchen I've used Umbrello, and like it a lot. Some of my co-workers can't use Linux, so I've downloaded ArgoUML for them. Argo looks terrible, but works well. Eleknader The probleme is that we can't export file from Umbrello to Rose/Argo/PutYourUMLEditorHere. Well, Umbrello files are save in XMI. It should be possible to share xmi files between all UML tools. But, this is only theory. In XMI there are only the modell data stored (which classes, use cases and so on). But the diagram informations are not stored in XMI (so things like where on the diagram is the class, which colour and so on). There is till now no standard how to exchange these information. Most tools save these information in the XMI file in a special section. So to import a file to another tool you need a filter which could interpret this special section. So it is very clear, that Rose/Argo or some other tools don't provide such filters for import Umbrello XMI files. This is of course a mess. But in the upcoming UML 2.0 standard, this problem will be solved. There, diagram information will be saved as SVG. But 2.0 isn't published yet... It's taken a few moons, but we're getting there: First exports to Argo and StarUML are starting to work, plus we are getting import from Rose (beginning in version 1.5.2.) gogo umbrello , this tool is important !!! Well, lets say that it's one of the best free tools for Linux. It still have a long way to go until it reaches the same class as commersiol tools like MagicDraw and ObjectDomain. I like Umbrello, but i think that the MagicDraw UML is the best tool for linux. At a first try Umbrello allowed me to conveniently draw a diagram and save it and that's better than other open source UML diagramming tools I'd tried previously. At last an opportunity for me to learn UML hands-on. Great work! ArgoUML is a nice tool but it's a little slow and the user interface is ugly. Poseidon is based on ArgoUML and has a cleaner user interface. Speed is about the same but maybe a bit faster. It's nice to be able to export diagrams as PNG. However, both these tools do not currently support PHP code generation to my knowledge. I know Umbrello does and this is why I'm considering trying it out. Oh yeah, one drawback to Poseidon is that it's not open source. Hence, the reason I don't want to use it. Anyway, I'm anticipating Umbrello 1.2 because it's going to include the missing deployment and component diagrams, will have bug fixes and will support code generation for many more languages. I hope more people contribute to Umbrello. We need a good enterprise UML tool that is open source and can be used to foster enterprise OSS development. It would also be nice to see Umbrello ported to different platforms to encourage its widespread use. But it's KDE-based so I don't know how much work that would take. Does anyone know of any other UML tools that are open source and can generate PHP code? I am now using Visual Paradigm for UML and Visual Paradigm SDE for NetBeans Community Edition. It is extermly fast. The Community Edition only support real-time Java code generation. I know the Professional Edition can do code generation better. I don't know is it supports PHP. But Visual Paradigm for UML is not open source. send me free Linux based UML tools Maybe could be interesting this page: (overview) R.
https://dot.kde.org/comment/16122
CC-MAIN-2018-17
refinedweb
1,405
74.49
NAME | SYNOPSIS | DESCRIPTION | ATTRIBUTES | SEE ALSO #include <note.h>NOTE(NoteInfo); or #include<sys/note.h>_NOTE(NoteInfo); These macros are used to embed information for tools in program source. A use of one of these macros is called an “annotation”. A tool may define a set of such annotations which can then be used to provide the tool with information that would otherwise be unavailable from the source code. Annotations should, in general, provide documentation useful to the human reader. If information is of no use to a human trying to understand the code but is necessary for proper operation of a tool, use another mechanism for conveying that information to the tool (one which does not involve adding to the source code), so as not to detract from the readability of the source. The following is an example of an annotation which provides information of use to a tool and to the human reader (in this case, which data are protected by a particular lock, an annotation defined by the static lock analysis tool lock_lint). NOTE(MUTEX_PROTECTS_DATA(foo_lock, foo_list Foo)) Such annotations do not represent executable code; they are neither statements nor declarations. They should not be followed by a semicolon. If a compiler or tool that analyzes C source does not understand this annotation scheme, then the tool will ignore the annotations. (For such tools, NOTE(x) expands to nothing.) Annotations may only be placed at particular places in the source. These places are where the following C constructs would be allowed: a top-level declaration (that is, a declaration not within a function or other construct) a declaration or statement within a block (including the block which defines a function) a member of a struct or union. Annotations are not allowed in any other place. For example, the following are illegal: x = y + NOTE(...) z ; typedef NOTE(...) unsigned int uint ; While NOTE and _NOTE may be used in the places described above, a particular type of annotation may only be allowed in a subset of those places. For example, a particular annotation may not be allowed inside a struct or union definition. Ordinarily, NOTE should be used rather than _NOTE, since use of _NOTE technically makes a program non-portable. However, it may be inconvenient to use NOTE for this purpose in existing code if NOTE is already heavily used for another purpose. In this case one should use a different macro and write a header file similar to /usr/include/note.h which maps that macro to _NOTE in the same manner. For example, the following makes FOO such a macro: #ifndef _FOO_H #define _FOO_H #define FOO _NOTE #include <sys/note.h> #endif Public header files which span projects should use _NOTE rather than NOTE, since NOTE may already be used by a program which needs to include such a header file. The actual NoteInfo used in an annotation should be specified by a tool that deals with program source (see the documentation for the tool to determine which annotations, if any, it understands). NoteInfo must have one of the following forms: NoteName NoteName(Args) where NoteName is simply an identifier which indicates the type of annotation, and Args is something defined by the tool that specifies the particular NoteName. The general restrictions on Args are that it be compatible with an ANSI C tokenizer and that unquoted parentheses be balanced (so that the end of the annotation can be determined without intimate knowledge of any particular annotation). See attributes(5) for descriptions of the following attributes: NAME | SYNOPSIS | DESCRIPTION | ATTRIBUTES | SEE ALSO
http://docs.oracle.com/cd/E19683-01/816-5218/6mbcj7niu/index.html
CC-MAIN-2016-30
refinedweb
598
51.28
To enable the user to enter text or numbers, you use an EditText element. Some input controls are EditText attributes that define the type of keyboard that appears, to make entering data easier for users. For example, you might choose phone for the android:inputType attribute to show a numeric keypad instead of an alphanumeric keyboard. Other input controls make it easy for users to make choices. For example, RadioButton elements enable a user to select one (and only one) item from a set of items. In this practical, you use attributes to control the on-screen keyboard appearance, and to set the type of data entry for an EditText. You also add radio buttons to the DroidCafe app so the user can select one item from a set of items.(). - Convert the text in a Viewto a string using getText(). - Create a click handler for a Buttonclick. - Display a Toastmessage. What you'll learn - How to change the input methods to enable suggestions, auto-capitalization, and password obfuscation. - How to change the generic on-screen keyboard to a phone keypad or other specialized keyboards. - How to add radio buttons for the user to select one item from a set of items. - How to add a spinner to show a drop-down menu with values, from which the user can select one. What you'll do - Show a keyboard for entering an email address. - Show a numeric keypad for entering phone numbers. - Allow multiple-line text entry with automatic sentence capitalization. - Add radio buttons for selecting an option. - Set an onClickhandler for the radio buttons. - Add a spinner for the phone number field for selecting one value from a set of values. In this practical, you add more features to the DroidCafe app from the lesson on using clickable images. In the app's OrderActivity you experiment with the android:inputType attribute for EditText elements. You add EditText elements for a person's name and address, and use attributes to define single-line and multiple-line elements that make suggestions as you enter text. You also add an EditText that shows a numeric keypad for entering a phone number. Other types of input controls include interactive elements that provide user choices. You add radio buttons to DroidCafe for choosing only one delivery option from several options. You also offer a spinner input control for selecting the label (Home, Work, Other, Custom) for the phone number. Touching an EditText editable text field places the cursor in the text field and automatically displays the on-screen keyboard so that the user can enter text. An editable text field expects a certain type of text input, such as plain text, an email address, a phone number, or a password. It's important to specify the input type for each text field in your app so that the system displays the appropriate soft input method, such as an on-screen keyboard for plain text, or a numeric keypad for entering a phone number. 1.1 Add an EditText for entering a name In this step you add a TextView and an EditText to the OrderActivity layout in the DroidCafe app so that the user can enter a person's name. - Make a copy of the DroidCafe app from the lesson on using clickable images, and rename the copy to DroidCafeInput. If you didn't complete the coding challenge in that lesson, download the DroidCafeChallenge project and rename it to DroidCafeInput. - Open the activity_order.xml layout file, which uses a ConstraintLayout. - Add a TextViewto the ConstraintLayoutin activity_order.xmlunder the order_textviewelement already in the layout. Use the following attributes for the new TextView: - Extract the string resource for the android:textattribute value to create and entry for it called name_label_textin strings.xml. - Add an EditTextelement. To use the visual layout editor, drag a Plain Text element from the Palette pane to a position next to the name_label TextView. Then enter name_text for the ID field, and constrain the left side and baseline of the element to the name_labelelement right side and baseline as shown in the figure below: - The figure above highlights the inputType field in the Attributes pane to show that Android Studio automatically assigned the textPersonNametype. Click the inputType field to see the menu of input types: In the figure above, textPersonName is selected as the input type. - Add a hint for text entry, such as Enter your name, in the hint field in the Attributes pane, and delete the Name entry in the text field. As a hint to the user, the text "Enter your name" should be dimmed inside the EditText. - Check the XML code for the layout by clicking the Text tab. Extract the string resource for the android:hintattribute value to enter_name_hint. The following attributes should be set for the new EditText(add the layout_marginLeftattribute for compatibility with older versions of Android): As you can see in the XML code, the android:inputType attribute is set to textPersonName. - Run the app. Tap the donut image on the first screen, and then tap the floating action button to see the next Activity. Tap inside the text entry field to show the keyboard and enter text, as shown in the figure below. Note that suggestions automatically appear for words that you enter. Tap a suggestion to use it. This is one of the properties of the textPersonName value for the android:inputType attribute. The inputType attribute controls a variety of features, including keyboard layout, capitalization, and multiple lines of text. - To close the keyboard, tap the checkmark icon in a green circle , which appears in the lower right corner of the keyboard. This is known as the Done key. 1.2 Add a multiple-line EditText In this step you add another EditText to the OrderActivity layout in the DroidCafe app so that the user can enter an address using multiple lines. - Open the activity_order.xml layout file if it is not already open. - Add a TextViewunder the name_labelelement already in the layout. Use the following attributes for the new TextView: - Extract the string resource for the android:textattribute value to create and entry for it called address_label_textin strings.xml. - Add an EditTextelement. To use the visual layout editor, drag a Multiline Text element from the Palette pane to a position next to the address_label TextView. Then enter address_text for the ID field, and constrain the left side and baseline of the element to the address_labelelement right side and baseline as shown in the figure below: - Add a hint for text entry, such as Enter address, in the hint field in the Attributes pane. As a hint to the user, the text "Enter address" should be dimmed inside the EditText. - Check the XML code for the layout by clicking the Text tab. Extract the string resource for the android:hintattribute value to enter_address "Address" text entry field to show the keyboard and enter text, as shown in the figure below, using the Return key in the lower right corner of the keyboard (also known as the Enter or New Line key) to start a new line of text. The Return key appears if you set the textMultiLinevalue for the android:inputTypeattribute. - To close the keyboard, tap the down-arrow button that appears instead of the Back button in the bottom row of buttons. 1.3 Use a keypad for phone numbers In this step you add another EditText to the OrderActivity layout in the DroidCafe app so that the user can enter a phone number on a numeric keypad. - Open the activity_order.xml layout file if it is not already open. - Add a TextViewunder the address_labelelement already in the layout. Use the following attributes for the new TextView: Note that this TextView is constrained to the bottom of the multiple-line EditText ( address_text). This is because address_text can grow to multiple lines, and this TextView should appear beneath it. - Extract the string resource for the android:textattribute value to create and entry for it called phone_label_textin strings.xml. - Add an EditTextelement. To use the visual layout editor, drag a Phone element from the Palette pane to a position next to the phone_label TextView. Then enter phone_text for the ID field, and constrain the left side and baseline of the element to the phone_labelelement right side and baseline as shown in the figure below: - Add a hint for text entry, such as Enter phone, in the hint field in the Attributes pane. As a hint to the user, the text "Enter phone" should be dimmed inside the EditText. - Check the XML code for the layout by clicking the Text tab. Extract the string resource for the android:hintattribute value to enter_phone "Phone" field to show the numeric keypad. You can then enter a phone number, as shown in the figure below. - To close the keyboard, tap the Done key . To experiment with android:inputType attribute values, change an EditText element's android:inputType values to the following to see the result: textEmailAddress: Tapping the field brings up the email keyboard with the @ symbol located near the space key. textPassword: The characters the user enters turn into dots to conceal the entered password. 1.4 Combine input types in one EditText You can combine inputType attribute values that don't conflict with each other. For example, you can combine the textMultiLine and textCapSentences attribute values for multiple lines of text in which each sentence starts with a capital letter. - Open the activity_order.xml layout file if it is not already open. - Add a TextViewunder the phone_labelelement already in the layout. Use the following attributes for the new TextView: - Extract the string resource for the android:textattribute value to create and entry for it called note_label_textin strings.xml. - Add an EditTextelement. To use the visual layout editor, drag a Multiline Text element from the Palette pane to a position next to the note_label TextView. Then enter note_text for the ID field, and constrain the left side and baseline of the element to the note_labelelement right side and baseline as you did previously with the other EditTextelements. - Add a hint for text entry, such as Enter note, in the hint field in the Attributes pane. - Click inside the inputType field in the Attributes pane. The textMultiLine value is already selected. In addition, select textCapSentences to combine these attributes. - Check the XML code for the layout by clicking the Text tab. Extract the string resource for the android:hintattribute value to enter_note_hint. The following attributes should be set for the new EditText(add the layout_marginLeftattribute for compatibility with older versions of Android): To combine values for the android:inputType attribute, concatenate them using the pipe ( |) character. - Run the app. Tap an image on the first screen, and then tap the floating action button to see the next Activity. - Tap inside the "Note" field enter complete sentences, as shown in the figure below. Use the Return key to create a new line, or simply type to wrap sentences over multiple lines. Input controls are the interactive elements in your app's UI that accept data input. Radio buttons are input controls that are useful for selecting only one option from a set of options. In this task you add a group of radio buttons to the DroidCafeInput app for setting the delivery options for the dessert order. For an overview and more sample code for radio buttons, see Radio Buttons. 2.1 Add a RadioGroup and radio buttons To add radio buttons to OrderActivity in the DroidCafeInput app, you create RadioButton elements in the activity_order.xml layout file. After editing the layout file, the layout for the radio buttons in OrderActivity will look something like the figure below. Because radio button selections are mutually exclusive, you group them together inside a RadioGroup. By grouping them together, the Android system ensures that only one radio button can be selected at a time. - Open activity_order.xml and add a TextViewelement constrained to the bottom of the note_textelement already in the layout, and to the left margin, as shown in the figure below. - Switch to editing XML, and make sure that you have the following attributes set for the new TextView: - Extract the string resource for "Choose a delivery method:"to be choose_delivery_method. - To add radio buttons, enclose them within a RadioGroup. Add the RadioGroupto the layout underneath the TextViewyou just added, enclosing three RadioButtonelements as shown in the XML code below: <RadioGroup android: <RadioButton android: <RadioButton android: <RadioButton android: </RadioGroup> The "onRadioButtonClicked" entry for the android:onClick attribute for each RadioButton will be underlined in red until you add that method in the next step of this task. - Extract the three string resources for the android:textattributes to the following names so that the strings can be translated easily: same_day_messenger_service, next_day_ground_delivery, and pick_up. 2.2. - Open activity_order.xml (if it is not already open) and find one of the onRadioButtonClickedvalues for the android:onClickattribute that is underlined in red. - Click the onRadioButtonClickedvalue, and then click the red bulb warning icon in the left margin. - Choose Create onRadioButtonClicked(View) in OrderActivity in the red bulb's menu. Android Studio creates the onRadioButtonClicked(View view)method in OrderActivity: public void onRadioButtonClicked(View view) { } In addition, the onRadioButtonClicked values for the other android:onClick attributes in activity_order.xml are resolved and no longer underlined. - To display which radio button is clicked (that is, the type of delivery the user chooses), use a Toastmessage. Open OrderActivity and add the following displayToastmethod: public void displayToast(String message) { Toast.makeText(getApplicationContext(), message, Toast.LENGTH_SHORT).show(); } - In the new onRadioButtonClicked()method, add a switch caseblock to check which radio button has been selected and to call displayToast()with the appropriate message. The code uses the isChecked()method of the Checkableinterface, which returns trueif the button is selected. It also uses the View getId()method to get the identifier for the selected radio button view:.same_day_messenger_service)); break; case R.id.nextday: if (checked) // Next day delivery displayToast(getString(R.string.next_day_ground_delivery)); break; case R.id.pickup: if (checked) // Pick up displayToast(getString(R.string.pick_up)); break; default: // Do nothing. break; } } - Run the app. Tap an image to see the OrderActivityactivity, which shows the delivery choices. Tap a delivery choice, and you see a Toastmessage at the bottom of the screen with the choice, as shown in the figure below. Task 2 solution code Android Studio project: DroidCafeInput Challenge: The radio buttons for delivery choices in the DroidCafeInput app first appear unselected, which implies that there is no default delivery choice. Change the radio buttons so that one of them (such as nextday) is selected as the default when the radio buttons first appear. Hint: You can accomplish this task entirely in the layout file. As an alternative, you can write code in OrderActivity to select one of the radio buttons when the Activity first appears. Challenge solution code Android Studio project: DroidCafeInput **(**see the second radio button in the activity_order.xml layout file). To provide a way to select a label for a phone number (such as Home, Work, Mobile, or Other), you can add a spinner to the OrderActivity layout in the DroidCafe app to appear right next to the phone number field. 3.1 Add a spinner to the layout To add a spinner to the OrderActivity layout in the DroidCafe app, follow these steps, which are numbered in the figure below: - Open activity_order.xml and drag Spinner from the Palette pane to the layout. - Constrain the top of the Spinnerelement to the bottom of address_text, the right side to the right side of the layout, and the left side to phone_text. To align the Spinner and phone_text elements horizontally, use the pack button in the toolbar, which provides options for packing or expanding selected UI elements. Select both the Spinner and phone_text elements in the Component Tree, click the pack button, and choose Expand Horizontally. As a result, both the Spinner and phone_text elements are set to fixed widths. - In the Attributes pane, set the SpinnerID to label_spinner, and set the top and right margins to 24, and the left margin to 8. Choose match_constraint for the layout_width drop-down menu, and wrap_content for the layout_height drop-down menu. The layout should look like the figure below. The phone_text element's layout_width drop-down menu in the Attributes pane is set to 134dp. You can optionally experiment with other width settings. To look at the XML code for activity_order.xml, click the Text tab. The Spinner should have the following attributes: <Spinner android: Be sure to add the android:layout_marginRight and android:layout_marginLeft attributes shown in the code snippet above to maintain compatibility with older versions of Android. The phone_text element should now have the following attributes (after using the pack tool): <EditText android: 3.2 Add code to activate the Spinner and its listener The choices for the Spinner are well-defined static strings such as "Home" and "Work," and define the selectable values (Home, Work, Mobile, and Other) for the Spinneras the string array labels_array: <string-array <item>Home</item> <item>Work</item> <item>Mobile</item> <item>Other</item> </string-array> - To define the selection callback for the Spinner, change your OrderActivityclass to implement the AdapterView.OnItemSelectedListenerinterface as shown: public class OrderActivity extends AppCompatActivity implements AdapterView.OnItemSelectedListener { As you type AdapterView. in the statement above, Android Studio automatically imports the AdapterView widget. The reason why you need the AdapterView is because you need an adapter—specifically an ArrayAdapter—to assign the array to the Spinner. An adapter connects your data—in this case, the array of spinner items—to the Spinner. You learn more about this pattern of using an adapter to connect data in another practical. This line should appear in your block of import statements: import android.widget.AdapterView; After typing OnItemSelectedListener in the statement above, wait a few seconds for a red light bulb to appear in the left margin. - Click the light bulb and select Implement methods. The onItemSelected()and onNothingSelected()methods, which are required for OnItemSelectedListener, should be highlighted, and the "Insert @Override" option should be selected. Click OK. This step automatically adds empty onItemSelected() and onNothingSelected() callback methods to the bottom of the OrderActivity class. Both methods use the parameter AdapterView<?>. The <?> is a Java type wildcard, enabling the method to be flexible enough to accept any type of AdapterView as an argument. 4. Instantiate a Spinner in the onCreate() method using the label_spinner element in the layout, and set its listener ( spinner.setOnItemSelectedListener) in the onCreate() method, as shown in the following code snippet: @Override protected void onCreate(Bundle savedInstanceState) { // ... Rest of onCreate code ... // Create the spinner. Spinner spinner = findViewById(R.id.label_spinner); if (spinner != null) { spinner.setOnItemSelectedListener(this); } // Create ArrayAdapter using the string array and default spinner layout. - Continuing to edit the onCreate()method, add a statement that creates the ArrayAdapterwith the string array ( labels_array) using the Android-supplied Spinnerlayout for each item ( layout.simple_spinner_item): // Create ArrayAdapter using the string array and default spinner layout. ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(this, R.array.labels_array, android.R.layout.simple_spinner_item); // Specify the layout to use when the list of choices appears. The simple_spinner_item layout used in this step, and the simple_spinner_dropdown_item layout used in the next step, are the default predefined layouts provided by Android in the R.layout class. You should use these layouts unless you want to define your own layouts for the items in the Spinner and its appearance. - Specify the layout for the Spinnerchoices); } // ... End of onCreate code ... 3.3 Add code to respond to Spinner selections When the user selects an item in the Spinner, the Spinner receives an on-item-selected event. To handle this event, you already implemented the AdapterView.OnItemSelectedListener interface in the previous step, adding empty onItemSelected() and onNothingSelected() callback methods. In this step you fill in the code for the onItemSelected() method to retrieve the selected item in the Spinner, using getItemAtPosition(), and assign the item to the spinnerLabel variable: - Add code to the empty onItemSelected()callback method, as shown below, to retrieve the user's selected item using getItemAtPosition(), and assign it to spinnerLabel. You can also add a call to the displayToast()method you already added to OrderActivity: public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) { spinnerLabel = adapterView.getItemAtPosition(i).toString(); displayToast(spinnerLabel); } There is no need to add code to the empty onNothingSelected() callback method for this example. - Run the app. The Spinner appears next to the phone entry field and shows the first choice (Home). Tapping the Spinner reveals all the choices, as shown on the left side of the figure below. Tapping a choice in the Spinner shows a Toast message with the choice, as shown on the right side of the figure. Task 3 solution code Android Studio project: DroidCafeInput Challenge: Write code to perform an action directly from the keyboard by tapping a Send key, such as for dialing a phone number: In the figure above: - Enter the phone number in the EditTextfield. - Tap the Send key to launch the phone dialer. The dialer appears on the right side of the figure. For this challenge, create a new app project, and add an EditText that uses the android:inputType attribute set to phone. Use the android:imeOptions attribute for the EditText element with the actionSend value: android:imeOptions="actionSend" The user can now press the Send key to dial the phone number, as shown in the figure above. In the onCreate() method for this Activity, you can use setOnEditorActionListener() to set the listener for the EditText to detect if the key is pressed: EditText editText = findViewById(R.id.editText_main); if (editText != null) editText.setOnEditorActionListener (new TextView.OnEditorActionListener() { // If view is found, set the listener for editText. }); For help setting the listener, see Specify the input method type. handled = false; if (actionId == EditorInfo.IME_ACTION_SEND) { dialNumber(); handled = true; } return handled; } To finish the challenge, create the dialNumber() method, which uses an implicit intent with ACTION_DIAL to pass the phone number to another app that can dial the number. It should look like this: private void dialNumber() { // Find the editText_main view. EditText editText = findViewById(R.id.editText_main); String phoneNum = null; // If the editText field is not null, // concatenate "tel: " with the phone number string. if (editText != null) phoneNum = "tel:" + editText.getText().toString(); // Optional: Log the concatenated phone number for dialing. Log.d(TAG, "dialNumber: " + phoneNum); // Specify the intent. Intent intent = new Intent(Intent.ACTION_DIAL); // Set the data for the intent as the phone number. intent.setData(Uri.parse(phoneNum)); // If the intent resolves to a package (app), // start the activity with the intent. if (intent.resolveActivity(getPackageManager()) != null) { startActivity(intent); } else { Log.d("ImplicitIntents", "Can't handle this!"); } } Challenge 2 solution code Android Studio project: KeyboardDialPhone The following android:inputType attribute values affect the appearance of the on-screen keyboard: textAutoCorrect: Suggest spelling corrections. textCapSentences: Start each new sentence with a capital letter. textPersonName: Show a single line of text with suggestions as the user types, and the Done key for the user to tap when they're finished. textMultiLine: Enable multiple lines of text entry and a Return key to add a new line. textPassword: Hide a password when entering it. textEmailAddress: Show an email keyboard rather than a standard keyboard. phone: Show a phone keypad rather than a standard keyboard. You set values for the android:inputType attribute in the XML layout file for an EditText element To combine values, concatenate them using the pipe ( |) character. Radio buttons are input controls that are useful for selecting only one option from a set of options: - Group RadioButtonelements together inside a RadioGroupso that only one RadioButtoncan be selected at a time. - The order in which you list the RadioButtonelements in the group determines the order that they appear on the screen. - Use the android:onClickattribute for each RadioButtonto specify the click handler. - To find out if a button is selected, use the isChecked()method of the Checkableinterface, which returns trueif the button is selected. A Spinner provides a drop-down menu: - Add a Spinnerto the layout. - Use an ArrayAdapterto assign an array of text values as the Spinnermenu items. - Implement the AdapterView.OnItemSelectedListenerinterface, which requires also adding the onItemSelected()and onNothingSelected()callback methods to activate the Spinnerand its listener. - Use the onItemSelected()callback method to retrieve the selected item in the Spinnermenu using getItemAtPosition(). The related concept documentation is in 4.2: Input controls. five checkboxes and a Show Toast button, as shown below. - If the user selects a single checkbox and taps Show Toast, display a Toastmessage showing the checkbox that was selected. - If the user selects more than one checkbox and then taps Show Toast, display a Toastthat includes the messages for all selected checkboxes, as shown in the figure below. Answer these questions Question 1 What's the most important difference between checkboxes and a RadioGroup of radio buttons? Choose one: - The only difference isallows only one selection. Question 2 Which layout group lets you align a set of CheckBox elements vertically? Choose one: RelativeLayout LinearLayout ScrollView Question 3 Which of the following is the method of the Checkable interface to check the state of a radio button (that is, whether it has been selected or not)? getId() isChecked() onRadioButtonClicked() onClick() Submit your app for grading Guidance for graders Check that the app has the following features: - The layout includes five CheckBoxviews vertically aligned on the screen, and a Show Toast button. - The onSubmit()method determines which checkbox is selected by using findViewById()with isChecked(). - The strings describing toppings are concatenated into a Toastmessage. To find the next practical codelab in the Android Developer Fundamentals (V2) course, see Codelabs for Android Developer Fundamentals (V2). For an overview of the course, including links to the concept chapters, apps, and slides, see Android Developer Fundamentals (Version 2).
https://codelabs.developers.google.com/codelabs/android-training-input-controls?hl=en
CC-MAIN-2020-45
refinedweb
4,308
55.13
I am working on analyzing some very large files (~200 million rows) csv_filename=pd.read_csv('filename.txt',sep="t",error_bad_lines=False) The program runs for about a half an hour before I get this error message: MemoryError: Unable to allocate 3.25 GiB for an array with shape (7, 62388743) and data type object I’m wondering if there is a way to bypass this memory error, or if there is a different function I can use that won’t require as much memory? I have split the file into pieces, but the issue with that is that I need all of the data in one dataframe so that I can analyze it as a whole. Answer You can limit the number of columns with usecols. This will reduce the memory footprint. You also seem to have some bad data in the CSV file making columns you think should be int64 to be object. These could be empty cells, or any non-digit value. Here is an example that will read the csv and then scan for bad data. This example uses commas, not tab, because thats a bit easier to demonstrate. import pandas as pd import numpy as np import io import re test_csv = io.StringIO("""field1,field2,field3,other 1,2,3,this 4,what?,6,is 7,,9,extra""") _numbers_re = re.compile(r"d+$") df = pd.read_csv(test_csv,sep=",",error_bad_lines=False, usecols=['field1', 'field2', 'field3']) print(df) # columns that arent int64 bad_cols = list(df.dtypes[df.dtypes!=np.dtype('int64')].index) if bad_cols: print("bad cols", bad_cols) for bad_col in bad_cols: col = df[bad_col] bad = col[col.str.match(_numbers_re) != True] print(bad) exit(1)
https://www.tutorialguruji.com/python/large-csv-files-memoryerror-unable-to-allocate-3-25-gib-for-an-array-with-shape-7-62388743-and-data-type-object/
CC-MAIN-2021-43
refinedweb
278
57.87
Ask Kathleen VB and C# share many similarities, but also have a handful of significant differences; learn what you need to know to program effectively in VB as a C# programmer. QI have a great job opportunity that leverages a lot of my existing skills. While I used to use Visual Basic 5 and 6 a long time ago, all my .NET code has been written in C# and this job requires that I work in Visual Basic .NET. The team I'm joining is confident they can help me come up to speed, but do you think I can make the transition, and what do you think I should know as I start coding in VB? The second part of your question is worth discussion. I've been a crossover coder for years and have come to appreciate the subtle differences between the languages. I assume you've seen VB and understand the obvious differences such as line continuation characters and synonyms such as Shared/static, as well as obvious operator differences such as single equal for comparisons and <> for not equal to. You can review synonyms in the help under keywords in the index. Coders can become annoyed if they don't make peace with the unique attitude of each compiler. For example, the VB compiler offers immediate support because of the background compiler and auto-complete. One thing that will help you tremendously is to learn to let the editor work for you, particularly in casing all symbol names outside their definitions. While it sometimes happens a bit later during compile, VB corrects these for you, leaving fully consistent casing, and it does this without you having to do any work. Similarly, VB will finish block constructs and few VB coders I know actually type "Then" at the end of an If statement or worry about the space in the middle of EndIf. VB lets you ignore parentheses in many scenarios. Start out never typing them and let the compiler tell you where they are needed. I hope you'll be working in Visual Studio 2008 because the location-aware IntelliSense narrows the IntelliSense options to those valid in the current context. In some cases, you'll choose between typing a symbol or selecting a keyword, so become comfortable using the down arrow to select the keyword. IntelliSense has two tabs: Common and All. You'll need to decide what works best for you; I always use the All tab. If you're accustomed to using Enter to select an IntelliSense entry, you'll have to modify that keystroke to use another whitespace, punctuation character, or Ctl-Enter. You don't need to adopt the VB keyboard shortcuts. Visual Studio allows you to code in VB with C# shortcuts and in C# with VB shortcuts. This will be local to your machine, so your shortcuts won't collide with those of other coders on your team unless you're sharing computers. Sometimes the VB editor becomes a bit too helpful, and you want to escape what it's currently doing. The escape key will close out the auto-complete and IntelliSense dialogs. I wish it were more helpful in quietly removing semicolons when you accidentally type them. Ask for that on Connect if you find it as annoying as I do. VB is flexible about whether variables must be declared (Option Explicit), whether variables are strongly typed (Option Strict), how comparisons are done (Option Binary), and whether type inference is used (Option Infer). Unless your team is already using it, don't use Option Binary. This is a backwards-compatibility feature, and it's best to state how comparisons are done at the location of each comparison. A common best practice is to turn on both Option Strict and Option Explicit. If you need late binding, you can turn Option Strict off in a single file. Note that this is file-based, not class-based, and different parts of the same class can have different Option settings if you use partial classes. The Imports statement supports both partial namespaces and aliased namespaces. You can use aliased namespaces to provide context to classes within your application and to resolve ambiguities while retaining code clarity in either VB or C#. VB's partial namespace support lets you include part of the namespace in the Imports statement and part inline: Imports System.Collections ... Private x As ObjectModel.Collection(Of String) VB provides project-level shortcuts for imports, options, and namespaces. If you include an Option in the project dialog, it will apply to all files that don't offer a contradictory setting. Imports at the project level are used throughout the project and can't be removed for individual classes. The default VB project includes a number of imported namespaces that you might wish to remove, particularly System.Collections (use System.Collections.Generic instead). Files can, of course, add additional Imports. You can alias a project-level import by typing the alias as a new user imports (see Figure 1). To remove a project-level alias, merely uncheck it and Visual Studio will remove it later. If you provide a namespace at both the project and file level, the file namespace is concatenated to the project namespace. If this does not accommodate your namespace pattern, you'll have to alter the project namespace and change or add file-level namespaces. Snippets are as valuable in VB as C#, but they don't show up in IntelliSense. There are more than 400 snippets available in VB: It's easiest to explore them through the menus. Once you find snippets that you use often, memorize the start of their abbreviations and access them with <partial abbreviation> ? tab, selecting the correct snippet as needed. You can also use ?? to get a full list of snippets. There are several VB assemblies. Microsoft.VisualBasic is included automatically if you're compiling against most versions of the CLR. This assembly contains the conversion functions and other VB-specific features. The Microsoft.VisualBasic.Compatibility libraries support features of earlier versions of VB that don't have direct equivalents in .NET. Don't use the compatibility libraries in new code. A few legacy VB features are present even without the compatibility library and should be avoided. The most important thing to avoid is the On Error statement. On Error forces the compiler to emit convoluted IL and requires significant additional runtime resources to manage this style of exception management. Use the skills you learned in C#: try, catch, finally, and using are all available in VB, and the editor will even fix the capitalization for you. Another feature to consider avoiding is the Visual Basic Collection. This collection class creates confusion with the main framework collection, is not strongly typed, and tends to be slow. Visual Basic has a number of operators, including CType, TryCast, and special cast operators that look like functions. You can tell the difference because the operators are colored blue in the editor and the operators are available whether or not you import the Microsoft.VisualBasic namespace. Both Visual Basic methods and operators are contained in the VisualBasic.dll. Many of the methods and operators are redirected to their counterparts in .NET Framework. Some, such as IsDate, don't have a direct parallel in .NET Framework, while others have subtly different behavior, particularly regarding the localization of dates. VB is location-aware by default. Your team will want to be consistent in whether you use the VB features or use their framework equivalents. A VB module is the rough equivalent of a C# static class. Within a module, you don't need (and can't use) the Shared keyword. Modules are also the only place where you can define extension methods. A notable difference between VB and C# is that in VB module members can be accessed using only their name: The module name is optional when calling the member. I include it for clarity. VB uses a declarative syntax for attaching events. The Handles clause appears on the code that will handle the event. When appropriate, multiple methods can handle the same event, and multiple events can be handled by the same method. Use of the Handles clause relies on the WithEvents modifier appearing on the declaration of the underlying variable such as a button. You can also attach property handlers using the AddHandler keyword, and remove them with RemoveHandler. You can customize the grimy details within events, although this is rarely needed. There are some annoying inconsistencies between VB and C# in recent features. VB propagates nulls in nullable comparisons the same way TSQL does, while C# returns a non-nullable Boolean type and considers a comparison of something else with null false. Immutability of anonymous types is also different with VB's Key keyword. Bill Wagner covers this in more detail in his column this issue, "What VB Devs Should Know About C#." VB uses different syntax than C# for arrays, although the arrays are identical under the hood. Indexes and size are delimited with parentheses, meaning the same delimiters are used for method parameters and indexes, which can take some getting used to. VB can declare the size of an array in line in the declaration. VB also requires the upper bound, rather than the length of the array. This makes more sense when you realize the upper bound is a shortcut for saying: Dim myArray3(0 To 3) As Int32 This array contains four elements. The expanded syntax including 0 To is rarely used, but does clarify the intent of the upper bound. You can include the parentheses indicating that a variable is an array on the type or the variable name, but you can declare the upper bound only on the variable name. It's easy for C# coders using VB.NET to create arrays that are one element larger than intended. When you loop through an array using the index, you'll need to stop one shy of the count because VB's For statement includes the top bound. For i = 0 To myArray.Length - 1 You can evaluate indexes in different ways using the Step modifier on the For statement. By default, Step is one. If you set it to a higher value, you'll skip indexes. If you set the Step value to a negative number, you'll move backwards through the collection, assuming you also reverse the start and end values. VB's logical operators look a little funny if you aren't familiar with the history. Prior to .NET, Booleans were numeric integers with False equal to zero and True equal to -1 because -1 has all bits set and is the opposite of False. The And operator performed a bitwise And returning True if the result was not equal to zero. In .NET, And retains bitwise semantics of shortcutting and can be used with either integers or Booleans. AndAlso is the short-circuited Boolean-only operator. Similarly, Or has bitwise semantics while OrElse has short-circuited Boolean semantics. This history also explains why the VB conversion operators CInt, CLng, and CShort return -1. Other than what's returned by this conversion operator, the value of False is the same in VB and in the framework. VB has a With keyword that simplifies setting a variable for use within a block and lets you access this temporary variable with a naked period. If your team uses With, you'll have to be comfortable using it: With New Data.SqlClient.SqlConnection(conn) .Open() End With The With construct is especially useful when you are using properties in a different namespace. When you're working with a convoluted name with many dots, you'll get a slight performance advantage using With because the full name is only resolved once. While this looks a bit like a using block, it doesn't dispose of the variable and can be used with either a new or existing variable. VB also has a Using block. One of the most significant features of VB is the My system. This provides a "speed dial" into many important features of the framework. You can also extend the My system for your own needs. Another large-scale productivity feature is the Windows application framework. This provides simple startup behavior and application-wide event management for WinForm applications. I think you'll be successful in your transition because the large and complex features are all in the libraries. As you switch into VB, you'll encounter many small issues that reflect the slight difference in focus between VB and C# and their respective legacies. VB aims at clarity, limiting typing, language discoverability, and overall productivity. The most significant thing missing in VB is iterators. Bill Wagner and I paired our columns this month because the question is meaningful in both directions -- for coders moving into either language. You'll find a number of other subtleties in back issues of our columns, as well as Bill McCarthy's On VB column..
http://visualstudiomagazine.com/articles/2008/12/01/what-c-devs-should-know-about-vb.aspx
CC-MAIN-2014-42
refinedweb
2,177
63.29
IRC log of prov on 2012-06-22 Timestamps are in UTC. 15:32:57 [RRSAgent] RRSAgent has joined #prov 15:32:58 [RRSAgent] logging to 15:32:59 [trackbot] RRSAgent, make logs world 15:33:00 [Zakim] Zakim has joined #prov 15:33:01 [trackbot] Zakim, this will be 15:33:01 [Zakim] I don't understand 'this will be', trackbot 15:33:02 [trackbot] Meeting: Provenance Working Group Teleconference 15:33:03 [trackbot] Date: 22 June 2012 15:33:11 [Luc] Zakim, this will be PROV 15:33:11 [Zakim] ok, Luc; I see SW_(PROV)12:00PM scheduled to start in 27 minutes 15:34:39 [Luc] Agenda: 15:35:08 [Luc] Chair: Paul Groth 15:42:11 [Curt] Curt has joined #prov 15:43:00 [pgroth] pgroth has joined #prov 15:43:15 [pgroth] is anyone on the telecon yet? 15:43:50 [dgarijo] I tried, but it said that it is restricted at this time 15:43:55 [pgroth] ok 15:44:52 [GK] GK has joined #prov 15:45:56 [GK] I'm not sure much of tghe meeting I'll be able to follow... I hadn't fully appreciated the time difference when I said I'd try to join in today. 15:48:33 [Zakim] SW_(PROV)12:00PM has now started 15:48:40 [Zakim] +??P0 15:48:45 [dcorsar] dcorsar has joined #prov 15:48:49 [jun] zakim, ??P0 is me 15:48:49 [Zakim] +jun; got it 15:49:34 [Zakim] -jun 15:49:36 [Zakim] SW_(PROV)12:00PM has ended 15:49:36 [Zakim] Attendees were jun 15:50:07 [Zakim] SW_(PROV)12:00PM has now started 15:50:14 [Zakim] +??P0 15:50:25 [jun] Am I the only one dialing in? I was told I am the first participant of the conference 15:50:28 [Zakim] + +1.805.893.aaaa 15:50:41 [Zakim] +??P2 15:50:42 [jun] zakim, ??P0 is me 15:50:43 [Zakim] +jun; got it 15:50:49 [dgarijo] zakim, ??P2 is me 15:50:49 [Zakim] +dgarijo; got it 15:51:25 [dcorsar_] dcorsar_ has joined #prov 15:52:30 [Luc] scribe: tim lebo 15:54:54 [zednik] zednik has joined #prov 15:56:32 [tlebo] tlebo has joined #prov 15:56:49 [tlebo] Zakim, who is on the phone? 15:56:49 [Zakim] On the phone I see jun, +1.805.893.aaaa, dgarijo 15:56:55 [tlebo] Zakime, I am happy 15:57:43 [Luc] rrsagent, make logs public 15:58:38 [zednik] zednik has joined #prov 16:00:38 [hook] hook has joined #prov 16:02:41 [Luc] zakim, who is here? 16:02:41 [Zakim] On the phone I see jun, +1.805.893.aaaa, dgarijo 16:02:42 [Zakim] On IRC I see hook, zednik, tlebo, dcorsar_, GK, pgroth, Curt, Zakim, RRSAgent, Luc, dgarijo, jun, MacTed, sandro, trackbot, stain 16:03:07 [Luc] guest: Hook Hua 16:04:50 [Luc] regrets: Deborah McGuinness, Jim McCusker, Simon Miles, Ivan Herman, Olaf Hartig, Sam Coppens 16:06:08 [tlebo] The rest of the faces have arrived. 16:06:31 [dgarijo] I am afraid I will only be able to attend around 2 hours, since it is getting late here :( 16:07:35 [Paolo] Paolo has joined #prov 16:08:09 [dgarijo] 16:08:10 [pgroth] Topic: Admin 16:08:20 [pgroth] 16:08:30 [pgroth] proposed: Minutes of the June 14, 2012 telcon 16:08:36 [tlebo] +1 16:08:37 [dgarijo] +1 16:08:38 [jcheney] jcheney has joined #prov 16:08:39 [jun] +1 16:08:56 [zednik] +1 16:09:02 [jcheney] 0 (was not present) 16:09:03 [Paolo] +1 16:09:16 [dcorsar_] 0 (was not present) 16:09:29 [pgroth] accepted: Minutes of the June 14, 2012 telcon 16:10:35 [satya] satya has joined #prov 16:11:02 [tlebo] luc: Sandro has been our w3c contact; he is moving to other w3c tasks. 16:11:10 [tlebo] ... ivan to be our new contact. 16:11:34 [TomDN] TomDN has joined #prov 16:11:47 [tlebo] luc: review of what we've been doing and what we are to do. 16:11:57 [tlebo] ... first WD of DM in Sept. 16:12:17 [tlebo] ... F2F2 led to good progress. 16:12:26 [tlebo] ... now trying to prepare LCs. 16:12:43 [tlebo] ... charter on homepage: Oct 1. 16:12:56 [tlebo] ... we need to request charter extension. 16:13:15 [tlebo] ... logistics on charter extension. 16:13:33 [tlebo] ... request needs to be ready by end of July. 16:13:43 [tlebo] ... request is non-trivial. 16:14:04 [tlebo] ... we have one shot at the request. no more extensions. 16:14:11 [Zakim] +??P3 16:14:27 [GK] zakim, ??p3 is me 16:14:27 [Zakim] +GK; got it 16:14:31 [tlebo] ... goal of this meeting: identify what we want and need to do, decide what not to do. 16:15:09 [tlebo] ... it is up to the WG to decide how much more time to ask for. 16:15:26 [tlebo] ... our timetable from F2F2 shoots for Jan. 16:15:27 [pgroth] Revised timetable: 16:15:40 [tlebo] ... may want to add a month or two for safety. 16:16:02 [tlebo] ... goal of meeting is to finalize LC. 16:16:21 [GK1] GK1 has joined #prov 16:16:41 [Zakim] +Satya_Sahoo 16:16:44 [tlebo] ... second goal: produce realistic timetable for remaining documents (Notes) 16:17:23 [pgroth] q? 16:17:27 [tlebo] ... we need to define what defines interoperability, aka "exit criteria". 16:18:02 [tlebo] ... need to prepare for Call for Implementations. Need to manage it. 16:18:17 [tlebo] ... who is going to take lead, what will be done? 16:18:54 [tlebo] 4 goals: finalize LC, timetable for WG (extension), define CR exit criteria draft, Call for Implementation. 16:19:04 [pgroth] q? 16:19:11 [Luc] q? 16:19:51 [tlebo] topic: PROV-DM 16:20:00 [tlebo] paul: technical features. 16:20:07 [tlebo] ... all "technical features" are done in LC. 16:20:23 [tlebo] ... we are promising that all technical features are done. 16:20:33 [Dong] Dong has joined #prov 16:20:51 [pgroth] collection contextualization primary source tracedTo (constraints are not final, should include specialization?) data types prov-o prov-dm incompability, e.g. prov:location 16:20:52 [tlebo] ... Paul and Luc looked through all reviews and listed the outstanding technical features. 16:20:58 [Curt] Curt has joined #prov 16:21:06 [pgroth] 16:21:34 [khalidBelhajjame] khalidBelhajjame has joined #prov 16:21:38 [tlebo] ... the above link shows the outstanding technical features that we need to settle. 16:21:40 [pgroth] q? 16:21:42 [tlebo] ... any others? 16:22:00 [tlebo] gk: prov-aq included? 16:22:03 [tlebo] paul: no 16:22:14 [tlebo] ... we'll talk about this afternoon. 16:22:18 [tlebo] ^ tomorrow 16:22:18 [jcheney] q+ 16:22:24 [pgroth] ack jcheney 16:22:30 [GK1] Hmmm... I won't be around tomorrow 16:22:43 [GK1] But maybe that's OK. 16:23:09 [tlebo] jcheney: prov-constraints, what is the scope and intent of it? 16:23:24 [tlebo] ... it is behind the others, we need to be aware of it. 16:24:15 [tlebo] Paul: lets walk through each technical features. 16:24:22 [tlebo] ... we have "options" on each feature. 16:24:29 [tlebo] ... 1 - rapid change and leave it in 16:24:39 [tlebo] ... 2 - if consensus, leave in. 16:24:50 [tlebo] ... 3 - can mark any feature as feature at risk. 16:25:14 [tlebo] ... this is something we want to have, but it can be removed. 16:25:26 [tlebo] ... 4 - remove a feature completely. 16:25:38 [tlebo] topic: Collections 16:25:50 [tlebo] subtopic: dm - collections 16:26:33 [tlebo] pgroth: summary. there has been debate and we seem to have converged. 16:26:40 [tlebo] ... Collection and hadMember. 16:26:49 [tlebo] ... "pop-up"s about collections. 16:27:05 [tlebo] ... e.g. okay to "strings" as keys in Dictionaries? 16:27:17 [tlebo] ... are Dictionaries stable enough for Rec? 16:27:28 [tlebo] ... or are they changing and will the continue to change? 16:27:39 [pgroth] q? 16:27:58 [pgroth] q? 16:27:59 [tlebo] luc: we can split the discussions. 16:28:00 [tlebo] q+ 16:28:16 [pgroth] ack tlebo 16:28:52 [pgroth] q? 16:28:55 [Paolo] q+ 16:29:01 [pgroth] ack Paolo 16:29:09 [tlebo] tlebo: my impression is that from the last weeks effort had settled it. 16:29:24 [tlebo] paolo: comfortable that we've settled it. 16:29:36 [tlebo] ... pop ups: Brian's concern. An official concern? 16:29:40 [tlebo] q- 16:30:00 [tlebo] ... "it's not clear" why they are there. "why aren't generic enough" 16:30:12 [tlebo] ... less worried about the technical definition. 16:30:31 [tlebo] ... the questions on the "strings" key issue. 16:30:39 [tlebo] ... "all of prov has to be semantic" 16:30:44 [Luc] Luc has joined #prov 16:30:53 [pgroth] q? 16:30:55 [tlebo] ... in an RDF encoding doens't imply "semantics" 16:31:01 [pgroth] q? 16:31:23 [tlebo] stephan: we should stick to string keys. it's just a way to index a member. 16:31:43 [tlebo] ... Bag of Hurt if we open keys to Resource. 16:31:58 [pgroth] q? 16:32:03 [tlebo] ... considers prov-o Dictionary modeling settled. Stable and reasonable. Fine wiht Note and Rec. 16:32:03 [TomDN] +1 jcheney 16:32:05 [reza_bfar] reza_bfar has joined #prov 16:32:28 [tlebo] pgroth: it seems that the technical work is stable. 16:32:28 [TomDN] sorry, +1 zednik 16:32:34 [GK1] (I don't understand that mention of "semantics"... by definition RDF has semantics, even if the semantics of a particular construct is vacuous.) 16:32:39 [tlebo] ... the existential of "do they belong" seems to be the only question. 16:33:16 [pgroth] straw poll: leave collections as there as part of the prov-dm rec 16:33:20 [tlebo] +1 16:33:24 [Paolo] +1 16:33:26 [Curt] -1 16:33:26 [khalidBelhajjame] +1 16:33:31 [TomDN] +1 16:33:32 [dgarijo] +1 16:33:33 [dcorsar_] +1 16:33:35 [reza_bfar] +1 16:33:35 [jun] +1 16:33:36 [satya] +1 16:33:37 [GK1] -0 (I won't oppose consensus) 16:33:42 [jcheney] 0 (haven't kept up) 16:33:49 [zednik] +1 16:34:03 [tlebo] curt: they are a layer above the fundamentals. 16:34:21 [tlebo] ... it is a significantly complicated, many new concepts. 16:34:25 [tlebo] ... likes how it's modeled. 16:34:30 [tlebo] ... fine as a note. 16:34:41 [tlebo] ... has no need for modeling prov of collections (personally). 16:34:49 [tlebo] ... it's extraneous. 16:35:01 [tlebo] ... like them, keep them, but not in Rec. 16:35:07 [dgarijo] but collections are not part of the "core" right? 16:35:10 [tlebo] paul: take dictionary? 16:35:24 [pgroth] q? 16:35:27 [Dong] +1 16:35:28 [tlebo] curt: all of collections, since there is nothing in spec that depends on it. 16:35:30 [GK1] @dgarijo They're in the REC 16:35:35 [GK1] (proposed) 16:35:41 [tlebo] ... the whole spec would be smaller. 16:35:49 [pgroth] q? 16:35:50 [dgarijo] @GK1 ok. 16:35:55 [pgroth] q+ 16:36:02 [tlebo] ... collections are not fundamental. 16:36:15 [tlebo] ... loads of ways to model collections. 16:36:18 [Luc] Luc has joined #prov 16:36:21 [Luc] q? 16:36:23 [tlebo] ... it is a specialized thing. 16:36:42 [tlebo] ... like Workflows, not fundamental. 16:36:55 [jcheney] q+ 16:37:04 [tlebo] paul: personal opinion to have Collection and hasMember in rec 16:37:21 [tlebo] ... Simon's argument that things on web is collection. it's all over the web. 16:37:40 [pgroth] ack pgroth 16:37:42 [reza_bfar] q+ 16:37:43 [tlebo] ... Dictionaries can more easily be a big chunk for niches 16:37:55 [pgroth] ack jcheney 16:38:31 [GK1] I agree with Curt ... it's not fundamental to provenance, so not strictly needed. There are other ways to model collections. One could argue that many things on the web being collections is a reason *not* to include them in provenance specs, as we should use definitions that al;so work for non-provenance apps. 16:38:52 [tlebo] jcheney: how separable are they? they are. 16:39:02 [pgroth] q? 16:39:05 [Paolo] q+ 16:39:08 [Paolo] q? 16:39:11 [reza_bfar] q+ 16:39:37 [tlebo] ... derivedByInsertion etc. 16:39:42 [pgroth] ack reza_bfar 16:39:57 [khalidBelhajjame] +q 16:39:57 [tlebo] reza: for interoperabily, we need SOMETHING for Collection. 16:40:01 [jun] Mmmm, but the property hasMember has nothing to do with provenance. but I like to keep it because there are a lot of collections on the web, and we provide people a standard way to model the insertion, deletion etc key patterns, instead of letting everyone extend prov in their own way 16:40:05 [pgroth] q? 16:40:08 [pgroth] ack Paolo 16:40:10 [tlebo] ... for Dictionary, agree with Paul (too complicated). 16:40:24 [tlebo] paolo: promote interoperability 16:40:35 [pgroth] q? 16:40:45 [tlebo] ... GK's point is the exact reason to include Collection. 16:41:01 [tlebo] ... Dictionary is one type of collection, if not fundamental. Then make it a Note. 16:41:06 [tlebo] ... what is a Note? 16:42:08 [tlebo] pgroth: a Note is a Recommendation from our group, it has a standing, but not the full force. Some patent stuff, too. 16:42:18 [tlebo] luc: no burden of proving interoperability. 16:42:29 [tlebo] ... on a Note. 16:42:38 [pgroth] q? 16:42:41 [pgroth] ack khalidBelhajjame 16:43:08 [tlebo] khalid: Curt said likely to treat as Collections, unlikely to go down. As long as it's in Rec OR Note, fine. 16:43:23 [dgarijo] I would leave collecitons in the recommendation. It is not part of the fundamental provenance, ok, but collections are out of what we have called the core. 16:43:26 [tlebo] ... a Note has Insertion and Removal, then Collection in DM doens't make sense. 16:43:36 [tlebo] q+ to say we have Bundle, Plan, etc. same with Collection. 16:43:54 [pgroth] ack tlebo 16:43:54 [Zakim] tlebo, you wanted to say we have Bundle, Plan, etc. same with Collection. 16:43:57 [GK1] If we would pick an existing widely used collection spec and recommend that, I'd be more supportive. 16:44:12 [pgroth] q? 16:44:15 [tlebo] q- 16:44:41 [tlebo] pgroth: leave collection and hadMember, move Dictionary to Note. 16:44:50 [reza_bfar] +1 for Paul's proposal. 16:44:53 [Luc] q? 16:45:09 [jun] what about other stuff, like insertion, deletion? not included? 16:45:10 [Luc] q+ 16:45:23 [Paolo] @jun no 16:45:44 [pgroth] ack Luc 16:45:59 [Paolo] @jun really, really minimal. essentially a placeholder as Tim pointed out 16:46:06 [tlebo] luc: if we take Dictionary out and keep just Collection and hadMember, do we still add their axioms? 16:46:17 [Paolo] q+ 16:46:32 [tlebo] ... seems that we'd be adding new realtion to model between entity and xxx 16:46:41 [jun] @Paolo, thanks 16:46:45 [tlebo] ... does it mean that prov-n doc is taken out regarding Insertion? 16:46:46 [YolandaGil] YolandaGil has joined #prov 16:46:53 [pgroth] q+ 16:47:01 [pgroth] ack Paolo 16:47:26 [tlebo] luc: hadMember is not provenance 16:47:37 [jcheney] q+ 16:47:51 [reza_bfar] Does collection not imply life-cycle ownership? So, something more specialized than hasMember? 16:47:54 [tlebo] paolo: specOf isn't provenance, either. 16:48:04 [tlebo] luc; specOf is related to aspects of Entities. 16:48:07 [Luc] q? 16:48:21 [pgroth] ack pgroth 16:48:28 [tlebo] pgroth: we aren't going to lose it. 16:48:35 [reza_bfar] In other words, doesn't the life-cycle of members of collection belong to collection? 16:48:51 [pgroth] ack jcheney 16:48:51 [tlebo] jcheney: as jun says... 16:49:08 [khalidBelhajjame] +q 16:49:13 [Paolo] q+ 16:49:18 [tlebo] ... same can be said for membership, if it's not standard provenance, it's going to be part of it. 16:49:20 [khalidBelhajjame] ack kh 16:49:21 [pgroth] ack khalidBelhajjame 16:49:29 [tlebo] paolo: what happens to prov-n? 16:49:31 [pgroth] ack Paolo 16:49:31 [Luc] isn't there an ontology out there with a part of relation? why does it need to be in prov? 16:49:47 [Luc] isn't there an ontology out there with a "part of" relation? why does it need to be in prov? 16:49:49 [tlebo] ... take partOf out, is Note union of Rec? 16:50:07 [tlebo] ... a bi odd that's not provennace. 16:50:36 [hook] q+ 16:50:39 [tlebo] ... the provenance of collections isn't in DM. 16:50:43 [Luc] q+ 16:50:44 [pgroth] ack hook 16:50:57 [Luc] q+ isn't there an ontology out there with a "part of" relation? why does it need to be in prov? 16:51:28 [tlebo] hook: python and json, dictionaries and collections are fundamental and primative. Newer forms, they are intrinsic. But PROV isn't a programming language... 16:51:59 [tlebo] ... notional views as data structures as PROV or domain specific interpretations of structures. 16:52:06 [pgroth] ack luc 16:52:11 [jun] @luc, at least dcterms has it, isPartOf, hasPart 16:52:26 [tlebo] luc: if there are part_of relations otu there, then why make our own? 16:52:49 [tlebo] ... fine to make it i the Note, but on DM with only Collection, why "part-of"? 16:52:53 [tlebo] q+ 16:52:53 [pgroth] q? 16:52:59 [pgroth] ack tlebo 16:53:15 [tlebo] q- 16:53:23 [reza_bfar] The issue I see with moving everything into the Note is that implementers start minimally and moving everything to the note is as good as moving everything out. 16:53:27 [tlebo] luc: proposal would be have EVERYTHIGN be a note. 16:53:29 [Paolo] q+ 16:53:38 [pgroth] ack paolo 16:53:56 [tlebo] paolo: taht would make the most sense, as breaking things up it's hard to fit into buckets. left with too much semantics in one. 16:54:13 [dgarijo] Does this mean that we separate it from prov-o too? 16:54:31 [pgroth] q? 16:54:52 [zednik] @dgarijo I think so, create prov-collections 16:55:23 [tlebo] paul: first straw pole -1 and a 0 16:55:29 [GK1] I think the comparison with Python is misleading. With RDF you can mix languages as required. With programming languages you can't. 16:55:33 [tlebo] ... next straw pole: move entirely to a Note. 16:55:48 [pgroth] straw poll: move collections completely into a note 16:55:53 [reza_bfar] -1 16:55:54 [Curt] +1 16:55:55 [khalidBelhajjame] +1 16:55:55 [dgarijo] +0 16:55:59 [tlebo] +1 16:56:01 [reza_bfar] 0 16:56:05 [GK1] (My -0 meant that I'd prefer to drop, but won't argue against consensus) 16:56:11 [YolandaGil] -1 16:56:14 [reza_bfar] +q 16:56:15 [zednik] +1 (happy with results of either straw poll, argument was convincing to use note) 16:56:17 [jcheney] +1 (we can always go back later if there is strong pull for this) 16:56:22 [YolandaGil] q+ 16:56:23 [pgroth] ack reza_bfar 16:56:24 [GK1] +0 16:56:26 [jun] +0 I don't mind either way. but what will happen to prov-o? 16:56:35 [tlebo] reza: daytime implementers can be devious. Will use different mechansism if it's not in the standard. 16:56:42 [TomDN] TomDN has joined #prov 16:56:52 [tlebo] ... "deviating the product" will be done by different companies. 16:56:55 [GK1] Overspecification kills standards too --- look at OSI. 16:57:01 [pgroth] ack YolandaGil 16:57:02 [dgarijo] @Jun, That is my concern too. Will we have to separate it? Create another ontology? 16:57:08 [tlebo] yolanda: for Plan, we have nominal concept of Plan. 16:57:19 [Paulo] Paulo has joined #prov 16:57:20 [tlebo] ... nothing fleshes them in. 16:57:22 [Luc] q+ 16:57:31 [Curt] prov:type Collection 16:57:41 [tlebo] ... as a compromise, have Collection without hadMember (just like we have Plan). 16:57:45 [pgroth] q? 16:57:45 [zednik] q+ 16:57:46 [Paolo] @yolanda so we just leave prov:type = "collection"? 16:57:47 [pgroth] ack Luc 16:58:04 [tlebo] luc: to reza: not suggesting we drop Coll/Dict entirely. Moved to Note. 16:58:07 [Paolo] q+ 16:58:09 [satya] -1 (Note is a very vague notion and I don't understand how the features of collection can be modeled in Notes - specifically from perspective of PROV-O like Jun and Dani) 16:58:12 [tlebo] ... cut and paste job. 16:58:27 [pgroth] @satya - we are talking about a w3c note document 16:58:54 [satya] ahh - ok, (still -1, collection is needed in Rec from my perspective) 16:59:01 [tlebo] ... to Yolanda: we have Plans, yes. but we have hadPlan on QualifiedAssociation. So links TO it. 16:59:11 [Paolo] q? 16:59:11 [tlebo] ... Collection doesn't have an In or Out. 16:59:16 [zednik] q- 16:59:20 [tlebo] q+ to say the relation is subClassOf 16:59:28 [zednik] q+ 16:59:46 [tlebo] yolanda: I'd chose Collection over Plan 17:00:22 [TomDN] +q 17:00:30 [tlebo] paolo: agree, notion of placeholder to leave open to elaboration. 17:00:48 [tlebo] ... reza's point that standards hold develoeprs hands for what they can do. 17:01:01 [GK1] We should remember that the specs we produce will not be the last word. It's easier to add stuff later than to take out mistakes. 17:01:11 [pgroth] ack Paolo 17:01:19 [tlebo] ... Note is not enough. 17:01:29 [tlebo] q- 17:01:31 [pgroth] ack tlebo 17:01:47 [jcheney] @reza: Given that we can't standardize all kinds of collections in advance, developers will still be differentiating anyway. 17:01:51 [GK1] Also, I don't think it's about how binding a document may be, but how confident we are that it will garner consensus from a wider community. 17:02:14 [reza_bfar] FWIW - I think Yolanda's proposal is the way to go. It avoids a situation where, for example, people will use something like a linked list of entities. 17:02:23 [GK1] A NOTE suggests we aren't so sure ... NOTEs may get picked up and standardized later if they make sense. 17:03:10 [pgroth] q? 17:03:26 [pgroth] ack zednik 17:03:35 [tlebo] zednik: adding a Note provides a claim to the developer to differentiate. 17:03:49 [tlebo] ... "we support the Rec and the Note" - the Note becomes the feature. 17:03:58 [tlebo] ... they can brag about the Note. 17:04:25 [tlebo] ... Note gives direction that they can move towards. 17:04:51 [tlebo] ... Collection with no properties. Def says "has entities". 17:05:34 [tlebo] ... Plans as stub, something that refers to the stub. We don't gain without hadMember. 17:06:03 [GK1] I think if something is well documented and makes sense, developers will use it. Standard or no. I think there's too much hand-wringing about status. But if a spec is monolithic that would tend to weigh against it. IMO. 17:06:07 [zednik] q- 17:06:14 [pgroth] ack TomDN 17:06:22 [hook] q+ 17:06:24 [tlebo] tomdn: if we put into rec, all we're saying is taht there is a collection and it has members. 17:06:29 [tlebo] ... for keeping Collection in rec. 17:06:52 [tlebo] ... it isn't technically provenance, but it IS! If you want to talk about where something comes from, it is a part of a bigger whole. 17:07:21 [Luc] q+ 17:07:25 [tlebo] ... keep Collection and hadMember. 17:07:27 [Paolo] q? 17:07:34 [pgroth] ack hook 17:07:40 [tlebo] hook: extremes of interoperability. 17:08:03 [tlebo] ... having defined Collections and Plans without ties to them, breaks down interoperability. 17:08:12 [tlebo] ... systems will vary and defeats the purpose. 17:08:16 [pgroth] @gk for paq - i think we don't have a ton to talk about - just raising issues that we will have to address 17:08:31 [pgroth] @gk does that make sense? 17:08:33 [tlebo] ... e.g. OPM, Annotations, key-value pairs. 17:08:47 [GK1] @pgroth mainly, yes. But I'm thinking we should drop hasAnchor. 17:08:52 [tlebo] ... 2nd point: Collections and Plans. Should be some constraining factors. 17:08:58 [tlebo] ... "Creatively used". 17:09:15 [tlebo] ... constraining and giving pattern. 17:09:24 [GK1] @pgroth ... because the main usecases are covered by specializationOf 17:09:36 [Paolo] @GK agree -- if you propose something that makes sense, that's the best way to win the argument regardless of status 17:09:43 [tlebo] luc: editors hat: constriants doc: no Collec/Dict. No constraints in dm-constraints (good!) 17:09:52 [tlebo] ... not clear we'll converge quickly 17:10:08 [tlebo] ... timeline! 17:10:16 [pgroth] @gk hmm maybe we can start that up on the mailing list and address it at call 17:10:20 [tlebo] ... taking out of rec makes things faster. 17:10:29 [Paolo] q? 17:10:42 [GK1] @pgroth ack - I already responded to your issue 17:10:50 [tlebo] paul: less objection to keeping it in Rec 17:11:25 [tlebo] ... withotu hadMember relation, "it doenst make sense" 17:11:25 [Paolo] q+ 17:11:30 [tlebo] .. what to do? 17:11:30 [Curt] q+ 17:11:32 [Luc] ack luc 17:11:40 [Paolo] q+ to make a proposal 17:11:41 [khalidBelhajjame] +q (can we clarify what a W3C note mean?) 17:12:08 [YolandaGil] @Luc: how do you deal with Plan in the constraints spec? 17:12:15 [tlebo] paolo: a collection with hadMember in Rec, everything else goes to a Note. 17:12:28 [TomDN] +1 17:12:31 [tlebo] ... no constraints in dm-constraints 17:12:50 [pgroth] q? 17:12:53 [pgroth] ack Paolo 17:12:53 [Zakim] Paolo, you wanted to make a proposal 17:13:08 [GK1] My compromise might be: drop all collection-related classes; keep those collection properties that are subproperties of derivedFrom, etc., (as properties involving entities). 17:13:13 [tlebo] jcheney: does not seem to be controversy 17:13:54 [tlebo] luc: we can move mountains. 17:14:11 [tlebo] ... they restructured dm-constraints and prov-n 17:14:17 [tlebo] ... but they may be unhappy 17:14:37 [tlebo] jcheney: we don't want it, either. 17:14:45 [Zakim] -Satya_Sahoo 17:14:49 [tlebo] curt: mention the note in the Rec? 17:14:52 [jcheney] (does not seem to be controversy about memberOf and Collection cosntraints) 17:15:02 [tlebo] ... increase the stature for an implementer. 17:15:05 [pgroth] q? 17:15:07 [pgroth] ack Curt 17:15:26 [tlebo] paolo: if you do it right, people will follow it. 17:15:48 [reza_bfar] I'm good with either Yolanda's proposal or Paolo's proposal. 17:16:02 [khalidBelhajjame] +q 17:16:12 [tlebo] paul: straw poll #3 17:16:21 [pgroth] ack khalidBelhajjame 17:16:26 [tlebo] khalid: what is a Note? 17:16:55 [tlebo] ... "you can ignore the notes" when implementing a Rec. 17:17:14 [Zakim] +Satya_Sahoo 17:17:14 [reza_bfar] I think the key question is this: "Can an implementer claim compliance while violating a note?" 17:17:20 [tlebo] ... they can claim compliance without doing the Note. 17:17:43 [tlebo] (but as Stephan points out, the Note becomes a bragging point for those that do) 17:18:09 [tlebo] paul: Notes are less forceful. 17:18:18 [GK1] If implemented an application that generated provenance with collections that are, say, rdf:List values, would I be in violation of a provenance REC that specified collections. I think not. 17:19:00 [tlebo] jcheney: one can come up with other collections, but the question is do we require them to implemetn it? (not in a Note) 17:19:30 [Luc] proposal 1: keep collection and dictionary in recommendations 17:19:43 [Luc] proposal 2: keep collection class in recommendations, move collection membership and dictionary to note 17:20:04 [Luc] proposal 3: keep collection class and membership in recommendations, move dictionary to note 17:20:11 [TomDN] TomDN has joined #prov 17:20:14 [Luc] proposal 4: move collection and dictionary to note 17:20:38 [pgroth] proposal 1 17:20:42 [khalidBelhajjame] +1 17:20:47 [Dong] proposal 3 17:20:48 [GK1] -0 17:21:10 [GK1] 1:-0, 2:-0, 3:-0, 4:+0 (that would be a vote for 4) 17:21:12 [tlebo] PICK A NUMBER 17:21:23 [TomDN] +proposal 3 17:21:33 [jcheney] +proposal 3 17:21:40 [zednik] 3 17:21:40 [pgroth] pick a proposal 17:21:44 [khalidBelhajjame] 1 17:21:44 [jcheney] +proposal 3 17:21:44 [YolandaGil] 2 17:21:45 [TomDN] +proposal 3 17:21:46 [GK1] 1:-0, 2:-0, 3:-0, 4:+0 (that would be a vote for 4) 17:21:46 [Paolo] 3 17:21:48 [satya] 2 17:21:48 [zednik] 3 17:21:49 [tlebo] 3 17:21:50 [dcorsar_] 3 17:21:51 [Curt] 4 17:21:57 [jun] 4 17:21:59 [reza_bfar] 3 17:22:08 [Paulo] Paulo has joined #prov 17:22:39 [GK1] just take the last number then :) 17:22:48 [Dong] 3 17:24:06 [pgroth] proposed: keep collection class and membership in recommendations, move dictionary to note 17:24:10 [TomDN] +1 17:24:11 [Dong] +1 17:24:12 [Paolo] +1 17:24:13 [GK1] -0 17:24:13 [YolandaGil] +1 17:24:15 [Curt] +1 17:24:15 [zednik] +1 17:24:15 [tlebo] +1 17:24:15 [jcheney] +1 17:24:17 [dcorsar_] +1 17:24:20 [khalidBelhajjame] +0.5 17:24:48 [reza_bfar] +1 17:24:52 [jun] +0 17:25:04 [dgarijo] +0 17:25:05 [jun] [hard decision ...] 17:25:16 [pgroth] accepted: keep collection class and membership in recommendations, move dictionary to note 17:25:27 [Paolo] @jun I have made harder decisions in my life :-) 17:26:23 [jun] @Paolo, let's wait for contextualization :) 17:27:21 [tlebo] topic: contextualization 17:27:34 [tlebo] subtopic: contextualization 17:27:47 [pgroth] straw poll: do we keep contextualization in the rec? 17:27:47 [GK1] are we voting yet? 17:27:47 [TomDN] +1 17:27:50 [GK1] -1 17:27:53 [tlebo] +1 17:27:57 [TomDN] +1 17:27:57 [Paolo] 0 17:28:02 [Curt] 0 17:28:02 [khalidBelhajjame] -0.5 17:28:03 [reza_bfar] 0 17:28:03 [jcheney] 0 17:28:04 [zednik] 0 17:28:06 [dgarijo] -0 17:28:06 [satya] -1 17:28:11 [dcorsar_] 0 17:28:21 [YolandaGil] 0 17:28:37 [GK1] My latest position: 17:29:35 [jun] [I'll dial back then] 17:29:45 [pgroth] 20 minutes and we'll be back 17:29:50 [dgarijo] ok 17:29:59 [jun] @tlebo, thanks for the excellent scribing! 17:30:03 [Zakim] -jun 17:32:20 [dgarijo] maybe I'll have to go by then. As I said in my review of the DM, I think that contextualization is trying to do something similar what the accounts were trying to do with the ids within each account. We voted to leave them out of the dm because it complicated the model. 17:35:00 [Zakim] -Satya_Sahoo 17:49:22 [Zakim] - +1.805.893.aaaa 17:54:48 [Zakim] + +1.805.893.aabb 17:55:39 [dgarijo] I have to go. Hopefully I'll be able to join more time tomorrw. Good bye! 17:55:49 [pgroth] thanks dgarijo 17:55:51 [Zakim] -dgarijo 17:56:50 [Paolo] scribe: paolo 17:57:46 [satya] +1 Dani - I just dug out the previous version of DM to state that contextualization is trying to bring in Account through the back door 17:58:02 [satya] sorry, I have to leave for another meeting, will be back in an hour 17:58:42 [jun] have we resumed? 17:58:57 [Luc] about to resume 17:59:04 [Zakim] +??P1 17:59:07 [Dong] Dong has joined #prov 17:59:13 [jun] zakim, ??P1 is me 17:59:13 [Zakim] +jun; got it 17:59:16 [pgroth] resuming 17:59:54 [khalidBelhajjame] +q 18:00:12 [GK1] q+ 18:00:47 [Paolo] khalidBelhajjame: not opposed to keeping contextualization, but do we need to keep it as it is? 18:00:48 [tlebo] tlebo has joined #prov 18:01:08 [Paolo] khalidBelhajjame: def of contextualization too complicated for no good reason 18:01:13 [CraigTrim] CraigTrim has joined #prov 18:01:25 [jcheney] jcheney has joined #prov 18:01:29 [pgroth] ack khalidBelhajjame 18:01:54 [Paolo] khalidBelhajjame: it simply adds bundle to specialization, however bundle appears to be a defined context, which is not really part of the def. of bundle in the current DM 18:01:57 [YolandaGil] YolandaGil has joined #prov 18:02:10 [TomDN] I was going to propose something like: "An entity that is a contextualization, is a specialization of an entity in another bundle" 18:02:28 [TomDN] (to simplify the phrasing) 18:02:53 [Paolo] khalidBelhajjame: bundle def was careflly phrased not to bring back "account", however in contextualization the bundle seems to define context, which is too strong a semantics 18:03:03 [pgroth] q? 18:03:07 [pgroth] ack Gk 18:03:12 [hook] hook has joined #prov 18:03:20 [GK1] Why I oppose leaving contextualization in the PROV specifications. 18:03:20 [GK1] First, I want to be clear that I don't oppose this because I don't think it is useful. 18:03:20 [GK1] Indeed, it's somewhat the opposite: I think it's too important to risk getting wrong, 18:03:20 [GK1] and I really don't think we're clear enough about what we're trying to achieve here 18:03:20 [GK1] to be sure that we aren't getting it wrong. 18:03:21 [Paolo] GK1: see IRC 18:03:24 [GK1] As far as I can tell, contextualization as currently described has NO semantics that 18:03:27 [GK1] distinguish it from specializationOf, yet I believe it encourages users to read into it 18:03:28 [Paolo] GK1: just above... 18:03:28 [GK1] uses that could violate the semantics of RDF URI usage (by creating an illusion of 18:03:30 [GK1] URIs that denote different things in different contexts). 18:03:34 [GK1] In the absence of such semantics (i.e. without usable inferences), I can't see any valid 18:03:36 [GK1] reason for including contextualizationOf. I believe this is an area in which we really 18:03:38 [GK1] *need* formalization and rigour, because it relates so closely to RDF semantics. 18:03:42 [GK1] If we caused lots of developers to produce data that turns out to be inconsistent with 18:03:44 [GK1] RDF semantics, that would be real harm done, far far worse than the kind of failure of 18:03:46 [tlebo] @khalid, I agree that bundles do not define themselves as contexts, and they shouldn't. 18:03:46 [GK1] interoperability just discussed in the context of collections. In this case, if we got it 18:03:48 [GK1] wrong, it would much harder to just ignore any stuff that turns out not to work the way 18:03:49 [Paolo] GK1: this concept too important to get wrong 18:03:51 [GK1] it was intended, because there could be lots of broken data out there. 18:03:52 [GK1] 18:03:54 [GK1] If provenance is wildly successful, I suggest that broken contextualization could result 18:03:56 [GK1] in Balkanization of the semantic web to rival the Browser wars over HTML that 18:03:58 [GK1] we saw in the late 90s. 18:04:03 [GK1] And we should remember that the specs we produce will not be the last word. 18:04:04 [GK1] When the whole issue of RDF contextualization is better defined (i.e. we have 18:04:06 [GK1] formal semantics for RDF datasets) then it should be possible to define 18:04:08 [GK1] provenance contextualization that we can be confident won't be used 18:04:10 [GK1] inappropriately. 18:04:14 [GK1] Part of the reason that I'm so wary of this particular relation is that I think 18:04:17 [GK1] it usurps a part of semantic web technology that is being defined by the RDF 18:04:18 [GK1] working group ("named graphs", datasets and associated semantics). As such, I 18:04:20 [GK1] think the whole discussion about this should be conducted in the provenance+RDF 18:04:22 [GK1] coordination group. 18:04:26 [Paolo] GK1: no semantics to make it different from specialization 18:04:39 [pgroth] @paolo 18:04:42 [zednik] zednik has joined #prov 18:04:44 [pgroth] you don't have to scribe this 18:04:48 [pgroth] he pasted it in 18:04:52 [Paolo] GK1: but there is a chance it will be misused -- (see argument above on IRC) 18:05:05 [Paolo] GK1: no valid reason to include this 18:06:14 [Paolo] GK1: dire consequences if we get this wrong 18:06:31 [pgroth] wow! i want to be that successful 18:07:29 [Paolo] GK1: this discussion should be don on much closer coordination with the RDF WG 18:07:42 [pgroth] q? 18:08:31 [Paolo] pgroth: any comments from people who were in favour? 18:09:33 [Paolo] Luc: def can possibly be simplified. the app-specific interpretation in the current def follows a discussion with Satya 18:09:40 [jcheney] q+ 18:09:48 [Paolo] Luc: but that part can be removed 18:10:43 [Paolo] Luc: comments to GK1: absence of inferences for this relation is not a strong objection, there are other examples in the spec 18:11:11 [Paolo] Luc: contextualization is a form of specialization with an extra fixed aspect, namely the bundle 18:11:50 [GK1] Just wanted be clear I feel strongly about this! 18:11:53 [Paolo] Luc: surprised that it may lead to such drastic consequences as those GK1 envisioned 18:12:37 [Paolo] Luc: "context" used in a broad sense, it may apply to other elements of the model 18:12:41 [pgroth] q? 18:13:03 [Paolo] GK1: can't be sure it's not a problem -- but if it is, it can do serious damage 18:13:07 [TomDN] TomDN has joined #prov 18:13:15 [pgroth] ack jcheney 18:13:30 [GK1] Can't hear 18:14:00 [pgroth] better? 18:14:02 [Paolo] jcheney: description of bundle makes it just a container, it doesn't say anything about context 18:14:08 [GK1] yes, thanks 18:14:51 [pgroth] q? 18:14:57 [tlebo] q+ 18:15:08 [Paolo] jcheney: GK1 seems to need a formal discussion of the implications of this def -- is that needed as part of the formal semantics? 18:15:46 [Paolo] GK1: that would be better, however the point of the meeting is to decide what's in or out, and this would need more time 18:15:50 [pgroth] ack tlebo 18:15:58 [Paolo] GK1: discussion with the RDF WG needed 18:16:48 [pgroth] the return of bob! 18:16:50 [jcheney] please don't call it bob 18:17:30 [Paolo] tlebo: prov:contextualize is just another property to relate two entities -- all we do is create 2 triples to associate 3 distinct resources with distinct URIs 18:17:36 [Paolo] tlebo: how does that break RDF semantics? 18:18:10 [Paolo] tlebo: and nonen of those URI are in the rdf namespace -- these are all in our own namespaces 18:18:17 [Paolo] s/nonen/none 18:18:32 [pgroth] q? 18:18:40 [Paolo] tlebo: can't see how this violates any of the RDF semantics 18:18:52 [tlebo] it gets me over to another bundle. 18:19:00 [Paolo] GK1: can't we get the same effect with specialization alone? 18:19:43 [Paolo] GK1: the structure is such that it may encourage people to use it in improper ways 18:20:36 [Paolo] GK1: the danger is of different interpretations of the same URI 18:20:43 [pgroth] q+ 18:20:43 [Paolo] tlebo: the URIs are distinct... 18:21:13 [tlebo] 18:21:16 [tlebo] ^^ different URIs. 18:21:29 [Paolo] pgroth: the idea is to relate two distinct URIs but also that one of them occurs in a bundle -- it's specialization plus "this other URI occurs in a bundle" 18:21:50 [tlebo] tool:bob-2011-11-17 is not == :bob 18:22:01 [Paolo] khalidBelhajjame: believes GK1 is referring to "locatedIn" 18:23:19 [jcheney] What if you do this: bundle b1 entity(bob,[a=1]) end bundle b2 entity(bob,[a =2]) end 18:23:32 [Paolo] tlebo: (explains the use of inContext and specialization in the example above) 18:23:44 [jcheney] What stops me from concluding that entity(bob,[a=1,a=2]) ignoring the bundles? 18:24:04 [pgroth] +q 18:25:34 [khalidBelhajjame] hasProvenanceIn is described in 18:25:56 [TomDN] +q 18:26:01 [Paolo] GK1: what are we getting out of contextualization that can't be stated more simply? 18:26:03 [pgroth] ack TomDN 18:26:28 [Paolo] TomDN: maybe a qualified specialization? 18:26:44 [TomDN] (which isbasicly what a contextualization is) 18:26:59 [Paolo] GK1: the problem is what people may and up doing with these properties 18:27:07 [Paolo] s/and/end 18:27:21 [jcheney] can we feed this into RDF as a use case/possible requirement instead? 18:27:47 [jcheney] (or at least the "inContext part") 18:27:49 [Paolo] pgroth: we basically want to qualify a specialization with a bundle 18:27:55 [pgroth] ack pgroth 18:28:23 [TomDN] because we want it to inherit the same aspects as in the other bundle? 18:28:29 [Paolo] GK1: why do we you want to qualify specialization itself, rather than the entity itself that is introduced by the specialization? 18:29:05 [jun] @jcheney, we already did when we presented the XG work in the RDF workshop 2010. Good idea to take what they have at the moment for a test drive 18:29:13 [khalidBelhajjame] +q 18:29:25 [tlebo] using a subclass of Involvmeent will require a third resource... :-( 18:29:30 [pgroth] ack khalidBelhajjame 18:29:45 [jcheney] @jun, yes it would be good to see how that is handled and whether it addresses this 18:29:52 [tlebo] prov:inContext is the additional "fixed aspect" of the specialization. 18:29:53 [Paolo] khalidBelhajjame: maybe decompose contextualization into specialization plus another property 18:30:18 [Paolo] khalidBelhajjame: for example, the same idea may apply to alternate -- wouldn't that be another type of contextualization? 18:30:34 [GK1] if it were decomposed, I think I'd be *much* happier 18:30:35 [jun] @jcheney: +1. but how we make a decision now ... 18:30:47 [GK1] @jun +1 18:30:47 [pgroth] q? 18:30:54 [TomDN] very good point 18:30:55 [Paolo] khalidBelhajjame: so contextualization is "parametric" to the property that is being qualified 18:31:30 [Luc] q+ 18:31:35 [Paolo] khalidBelhajjame: we could do contextualization for any type of relation 18:31:51 [tlebo] this was my original isTopicOf . 18:31:58 [Reza_BFar] Reza_BFar has joined #prov 18:32:45 [Paolo] Luc: it's the usual problem of n-ary relations modelled with RDF properties. we decided to go with functional contextualized to clarify that it is a 3-way relation encoded as a binary 18:33:40 [Paolo] Luc: wanted to avoi the qualified pattern for this 18:33:46 [Paolo] s/avoi/avoid 18:34:19 [Paolo] tlebo: rigt now contextualize is not functional, but it could be 18:34:34 [Reza_Bfar] Reza_Bfar has joined #prov 18:34:38 [TomDN] +q 18:34:43 [pgroth] ack Luc 18:35:12 [Paolo] tlebo: re: khalidBelhajjame's suggestion: it would broaden the intended scope of this property too much 18:35:55 [GK1] Are we back to doing discovery through the data model? 18:36:01 [Zakim] - +1.805.893.aabb 18:36:13 [tlebo] so, khalid, you're suggesting that we just use isTopicOf with an open domain? 18:36:22 [tlebo] and range of bundle? 18:37:01 [GK1] specializationOf and isTopicOf as separate properties would be fine, I think. 18:37:48 [Zakim] + +1.805.893.aacc 18:37:57 [Luc] @gk, we were there befoer, and it doesn't work 18:38:02 [Luc] q+ 18:38:37 [GK1] @luc my fear is that it doesn't work because you're trying to do something that RDF semantics doesn't support. 18:38:50 [Paolo] TomDN: @khalidBelhajjame: we already have what you are suggesting 18:39:01 [pgroth] ack TomDN 18:39:32 [pgroth] ack Luc 18:39:36 [Luc] specializationOf(new-bob,bob) isTopic(bob,bundle) 18:40:06 [tlebo] @gk1, didn't we address the RDF semantics concern? 18:40:32 [Paolo] Luc: suggestion is to separate out the properties, but we've tried that before. Can't replace contextualization with those two relations 18:41:08 [GK1] You *never* know in RDF what extra constraints may be placed on an entity. That's the open worlkd model for you. 18:41:44 [TomDN] you could specify "contextualized alternate"like this: contextualization(new-bob,bob), alternateOf(newer-bob,new-bob) 18:42:21 [TomDN] That way you keep consistent in your own bundle, reduce overhead, and still remain the link to the original entity(bob) 18:42:28 [Curt] contextualization is a specialization of specialization 18:43:23 [Paolo] Luc: in the example, Bob has a new fixed aspect, namely the bundle. the isTopic does not address that 18:43:40 [GK1] "You don't know what aspects are specialized in a particular bundle" - this sounds like use of RDF reification, but the original use of of that had precisely the problem that I'm afraid of. 18:44:37 [GK1] Sound is patchy. 18:44:43 [Paolo] s/new-bob/bob 18:44:52 [Paolo] s/bob/new-bob 18:44:58 [Paolo] (sorry, bob) 18:46:12 [tlebo] Tim's modeling of what he thinks Khalid would prefer: 18:46:30 [GK1] "the bob that is described in this specific bundle" -- that;'s exactly the problem. bob is bob is bob. RDSF semantics doesn't allow different bobs (with the same name "bob") 18:48:05 [TomDN] TomDN has joined #prov 18:48:08 [pgroth] q? 18:48:31 [TomDN] so contextualization is a means of getting a "Linked Open Bobs" cloud... 18:48:59 [pgroth] q? 18:49:07 [khalidBelhajjame] +q 18:49:13 [Paolo] Luc: yes, it's the same bob in both activities, each described in a bundle. you can use specialization of bob to distinguish the contexts, using two different URIs and then relating them 18:49:16 [pgroth] ack khalidBelhajjame 18:49:35 [tlebo] q+ 18:49:47 [pgroth] ack tlebo 18:50:25 [Paolo] tlebo: bundles are just sets of assertions, all contextualization is doing is to say that a bundle describes an entity 18:51:12 [Paolo] khalidBelhajjame: but now bundle is made to do more, too much semantics. the two bobs are different because they are in different bundles 18:51:31 [tlebo] q- 18:51:31 [pgroth] q? 18:51:36 [TomDN] TomDN has joined #prov 18:51:39 [Luc] q+ 18:51:43 [pgroth] ack luc 18:52:09 [GK1] I am thinking that what Luc just said is maybe OK, but it's not at all clear (to me) from the spec. The problem is that the definition of "bundle" says nothing about context. It;'s just a bundle of assertions - there no claim that the assertions are in any way from a common "context". 18:52:28 [GK1] "Applications can exploit it inthe way they want" ... that's what I fear. 18:52:50 [Paolo] Luc: the link to bundles is just a general mechanism, which enables apps to then add their own interpretations, as illustrated in the bob performance example 18:53:06 [TomDN] linkedSpecialization? 18:53:09 [Paolo] pgroth: should we just rename context to something that is less overloaded? 18:53:22 [jcheney] -1 -1 -1 18:53:51 [tlebo] 18:53:55 [GK1] Renaming might help, but I think the problem is that there's no formal restraint on how it can be used. 18:53:59 [pgroth] 18:54:41 [Paolo] tlebo: inContext --> inBundle? 18:54:47 [Luc] q+ 18:54:55 [pgroth] ack Luc 18:55:39 [GK1] q+ 18:55:43 [pgroth] ack gk 18:56:16 [Paolo] GK1: elaborates on tlebo's titanpad example 18:58:40 [Reza_Bfar] A side note is that in the RDMBS world, I think the word "View" is used to accomplish some of these things. So, a "View" in the RDMBS world can be some selective, specialized, way of looking at things. 18:58:44 [Reza_Bfar] Just an idea... 18:59:09 [pgroth] q? 19:00:17 [Paolo] GK1: requests that the text describing contextualization be made more clear as to its intended meaning 19:00:41 [Paolo] GK1: the term "context" introduced without specification of its meaning 19:01:01 [Paolo] pgroth: we agree that the term is overloaded 19:01:29 [Paolo] pgroth: suggests to replace contextualization with isTopicOf 19:02:17 [GK1] Do you mean isTopicOf(e1, e2, bundle)? 19:02:25 [GK1] Seems odd to me. 19:03:06 [Curt] topic implies even more semantics -- it seems we want less.. 19:03:06 [GK1] why not: isTopicOf(e2, bundle) ; ispecializationOf(e1, e2) ? 19:04:09 [Curt] ispecializationOf(e1, e2) doesn't tie to the specific instance of the bundle 19:04:24 [GK1] That's kind of the point 19:04:54 [Paolo] pgroth: how about adding an optional bundle argument to ispecializationOf 19:05:06 [Paolo] jcheney: not clear what the implications would be 19:06:00 [GK1] I think that adding an attribute to specializationOf would be better. It suptypes the relation. 19:06:10 [Paolo] pgroth: one option is to keep the structure, trying to rephrase it, and mark it as at risk 19:06:45 [GK1] I think it's less inviting to abuse. 19:07:09 [Luc] q? 19:07:23 [Paolo] Luc: need to ask Ivan about what we can do once we flag as "at risk" 19:07:45 [TomDN] TomDN has joined #prov 19:07:51 [pgroth] q? 19:07:58 [Paolo] pgroth: marking it as 'at risk' implies that we can still remove it if no agreement is reached 19:08:11 [GK1] How not a subtype (didn't hear clearly) 19:08:42 [tlebo] @gk, b/c different arity 19:09:00 [TomDN] (just suggesting more names here: isExternalSpecializationOf(e1,e2, bundle), isSpecializedInBundle(e1,e2,bundle), ...) 19:10:13 [GK1] @TomDn "isSpecializedInBundle" I think is problem. Maybe "isSpecializedFromBundle"? 19:10:15 [Luc] 19:11:01 [TomDN] @GK1: sure, was just throwing things out there...because the name is what we seem to be stuck upon 19:11:42 [jcheney] Can a q+ 19:11:47 [jcheney] oops 19:11:47 [pgroth] q? 19:11:48 [jcheney] q+ 19:11:53 [pgroth] ack jcheney 19:12:36 [Paolo] jcheney: which bundle does the result of an inference live? 19:12:46 [Paolo] GK1: should go in the top leve 19:12:51 [Paolo] s/leve/level 19:13:55 [pgroth] q? 19:14:02 [Curt] +1 jcheney -- I think you nailed it. 19:14:05 [Paolo] jcheney: it seems we want specialization but in a way that "goes across" bundles, and we haven't thought that through 19:14:32 [Paolo] jcheney: so it may be similar to specialization, but not quite 19:14:36 [GK1] Sorry ... sound was dropping out - so I thought James had finishged. I'd like to see the semantics after james has thought about it. 19:14:42 [Reza_Bfar] James, can you go over it again please? I didn't get it. 19:15:03 [Paolo] jcheney: so we need to go back and think about it 19:15:12 [jcheney] @reza - at lunch maybe? 19:15:15 [Reza_Bfar] sure. 19:15:16 [Reza_Bfar] thanks 19:15:21 [Paolo] pgroth: was suggesting to make a quicker decision, for the sake of time 19:15:39 [Paolo] q+ 19:15:57 [TomDN] to address the concern raised about the ternary structure: you're still free to use 2 binary relations 19:15:57 [TomDN] this is just an easier way to assert it in 1 statement 19:16:12 [GK1] I'm OK with a vote. I'd reserve the right to maintain an objection going forward to last call. 19:16:14 [TomDN] much like derivation is to assert a usage + generation 19:16:32 [Paolo] pgroth: we could also have another round of discussion, but with a time limit 19:16:38 [pgroth] q? 19:16:56 [GK1] OKJ 19:16:59 [Paolo] pgroth: we could also vote on dropping it 19:17:06 [pgroth] q? 19:17:41 [pgroth] ack Paolo 19:18:24 [Paolo] pgroth 19:18:30 [pgroth] q? 19:18:39 [tlebo] q+ to say rename and at risk seems to correspond to the straw pol 19:18:41 [Paolo] pgroth: comments on what option people prefer? 19:19:29 [Paolo] tlebo: giving the recent straw poll, the renaming + marking seems like a reasonable option 19:19:38 [tlebo] q- 19:19:42 [pgroth] straw poll: rename contextualization (within a week ) and mark at risk 19:19:46 [GK1] renaming to...? Do we know? 19:19:48 [Paolo] +1 19:19:51 [tlebo] +1 19:19:53 [khalidBelhajjame] +1 19:19:54 [Curt] +1 19:19:55 [Reza_Bfar] +1 19:19:56 [jcheney] +1 19:19:56 [GK1] -0 19:19:56 [CraigTrim] +1 19:19:57 [zednik] +1 19:19:59 [dcorsar_] +1 19:20:00 [jun] +1 19:20:12 [YolandaGil] +1 19:20:12 [tlebo] hi, @jun! 19:20:23 [Dong] 0.5 19:20:26 [jun] hey, @tlebo! 19:20:44 [Dong] I want it renamed, but not marked as 'at risk' 19:20:48 [pgroth] accepted: rename contextualization (within a week ) and mark at risk 19:21:21 [GK1] I would oppose if not "at risk" 19:21:36 [Paolo] Luc: @Dong wise to put it at risk because it allows us to get feedback from implementers 19:21:39 [zednik_] zednik_ has joined #prov 19:22:13 [pgroth] Topic: Primer 19:22:28 [Paolo] TOPIC: prov-primer 19:23:08 [Paolo] pgroth: question is, do we take it to LC along with the others, or delay so we can incorporate feedback 19:23:29 [GK1] I'm going to have to drop out now. 19:23:40 [Zakim] -GK 19:23:42 [dcorsar] dcorsar has joined #prov 19:23:50 [Paolo] YolandaGil: should not be a problem to delay 19:24:15 [hook] hook has joined #prov 19:24:24 [Paolo] pgroth: primer currently talks about DM only. should PAQ and other material be incorporated? 19:24:50 [TomDN] TomDN has joined #prov 19:24:59 [pgroth] q? 19:25:04 [Reza_Bfar] From implementers perspective, I think Paul's suggestion is the way to go. I would leave the primer as is with just a pointer to PAQ. 19:25:06 [Paolo] pgroth: replies to himself: the PAQ by itself should be sufficiently self-describing 19:25:14 [Reza_Bfar] Keeps the primer lean. 19:25:20 [Paolo] Curt: PAQ reads well on its own 19:25:22 [Reza_Bfar] +1 for Luc's comments. 19:25:51 [Paolo] q+ 19:25:53 [Paolo] YolandaGil: 19:26:19 [Paolo] YolandaGil: examples need to highlight provenance coming from different sources (publishers...) 19:26:54 [Paolo] YolandaGil: would add an example of bundle, and thus of provenance of provenance 19:26:54 [pgroth] q? 19:27:38 [pgroth] ack Paolo 19:28:12 [jun] Going to drop out now! Enjoy your lunch! Bye! 19:28:18 [Paolo] YolandaGil: nothing about collections in primer ATM. there will not be anything in the future, either 19:29:55 [Paolo] (lunch break) 19:30:01 [jun] thee more issues 19:30:07 [Zakim] - +1.805.893.aacc 19:30:08 [Zakim] -jun 19:30:08 [Zakim] SW_(PROV)12:00PM has ended 19:30:08 [Zakim] Attendees were +1.805.893.aaaa, jun, dgarijo, GK, Satya_Sahoo, +1.805.893.aabb, +1.805.893.aacc 19:30:08 [jcheney] Quick and dirty semantics draft at 19:49:40 [satya] satya has joined #prov 20:28:52 [pgroth] is anyone on the phone? 20:30:40 [Zakim] SW_(PROV)12:00PM has now started 20:30:47 [Zakim] + +1.805.893.aaaa 20:30:47 [TomDN_] TomDN_ has joined #prov 20:33:34 [Luc] Luc has joined #prov 20:33:51 [Luc] q? 20:35:15 [Curt] Curt has joined #prov 20:35:29 [jcheney] jcheney has joined #prov 20:35:57 [pgroth] sub-topic: primary source 20:36:03 [pgroth] q? 20:36:12 [dcorsar] dcorsar has joined #prov 20:36:22 [pgroth] 20:36:41 [pgroth] q? 20:36:45 [jcheney] q+ 20:37:06 [pgroth] ack jcheney 20:37:12 [tlebo] tlebo has joined #prov 20:37:22 [TomDN_] subtopic: primary source 20:37:35 [hook] hook has joined #prov 20:37:46 [ferdinand] ferdinand has joined #prov 20:37:50 [TomDN_] pgroth: Daniel had some objections about hadPrimarySource in his review 20:38:24 [CraigTrim] CraigTrim has joined #prov 20:38:52 [TomDN_] jcheney: I'm surprised of the use of subtype instead of subproperty. (It's a naming issue) 20:39:46 [TomDN_] ... we're already saying wasDerivedFrom, which can have a more specific type, such as wasRevisionOf 20:40:31 [TomDN_] ... we use prov:type for this 20:40:39 [GK1] @jcheney taking a quick look at - at first glance, what your describing is beyoind the sexpressive capability of current RDF semantics. This is the sort of thing I'd expect to see coming from RDF WG for semantics of Datasets ( ), but so far there's no editors' draft of that. I guess you've seen Guha's thesis and other work in this area? Also, 20:41:23 [TomDN_] Luc: you've got the binary relation (wasDerivedFrom), and the extra attributes to specify the association class 20:41:32 [zednik] zednik has joined #prov 20:41:32 [TomDN_] jcheney: ok 20:41:54 [Reza_BFar] Reza_BFar has joined #prov 20:42:16 [TomDN_] jcheney: not an issue, moving on... 20:43:05 [TomDN_] Luc: Khalid had some remarks about the clarity of the definition 20:43:16 [TomDN_] khalid: but it can be solved by simply rephrasing 20:43:31 [TomDN_] pgroth: anyone else have this problem with the definition? 20:43:44 [pgroth] q? 20:44:07 [tlebo] 20:44:07 [TomDN_] zednik: it's supposed to be a first-hand experience of an event 20:44:18 [pgroth] q? 20:44:34 [TomDN_] pgroth: so is there still an issue? 20:44:44 [TomDN_] ... and/or suggestions? 20:44:46 [pgroth] q? 20:45:07 [TomDN_] Khalid: can we find another way of characterizing it? 20:45:13 [TomDN_] paolo: it can be derived from entities 20:45:47 [jcheney] @GK1: Yes, this is what makes me nervous about contextualization. However, what I wrote is very preliminary so far. Haven't read Guha's work carefully but familiar with related ideas in modal logic 20:45:47 [TomDN_] Khalid: it would be easier to say: primary source cannot be derived by any other source 20:46:00 [TomDN_] tlebo: but that's not true, they can 20:46:01 [Dong] I wonder if there is a strong use case to include hasPrimarySource in the DM 20:46:35 [TomDN_] Paolo: maybe we should find the "primary source" for the primary source definition... 20:46:43 [TomDN_] ... (to make sure it's clear) 20:46:59 [Dong] because the definition of it seems to up to the user 20:47:10 [TomDN_] ... We could offer a citation for the definition 20:47:17 [pgroth] 20:47:42 [GK1] @jcheney - ah ... I thought the language was reminiscent of modal logic. I don't recall that Guha appeals to modal logic in his thesis ... it's more like full FoL with rules for mapping between contexts (he calls them "lifting rules"). 20:47:50 [Curt] q+ 20:48:05 [TomDN_] "A primary source is a document or physical object which was written or created during the time under study. " (priceton) 20:48:22 [pgroth] ack curt 20:48:25 [TomDN_] Curt: tries to apply this concept to other domains, and it seems to fit 20:48:38 [GK1] @jcheney BTW, my previous comment got truncated. The bit that (I think) went missing was: Also, there was an informal proposal from Pat Hayes to the RDF WG a couple of months ago. My point is, I think you should be working with these guys to work out a common model, not in isolation. 20:48:42 [TomDN_] ... Does it accomodate data? 20:48:45 [TomDN_] everyone: yes 20:49:08 [TomDN_] pgroth: consensus is to add a suitable definition/citation to clarify 20:49:42 [TomDN_] dong: what's the distinction between derivation and primary source? 20:50:03 [TomDN_] tlebo: depends on what you're trying to do with the provenance 20:50:15 [TomDN_] pgroth: it's purposely left subjective 20:50:20 [TomDN_] ... to that end 20:50:48 [TomDN_] zednik: scientists don't add as much value to derivation as to primary source 20:51:04 [TomDN_] ... They don't always want to full derivation 20:51:10 [TomDN_] s/to/the 20:51:20 [Reza_BFar] +q 20:51:47 [TomDN_] dong: We're trying to produce a standard, but we don't define this difference 20:52:21 [TomDN_] reza: When you look at legal documents, primary source is atomary 20:52:39 [TomDN_] ... You don't look beyond this point. 20:52:40 [Dong] +q 20:52:56 [TomDN_] ... There is some distinction that needs to be made 20:53:26 [TomDN_] pgroth: We had originalSource first, but the proper term is primarySource. 20:53:33 [khalidBelhajjame] +q 20:53:41 [pgroth] ack Reza_BFar 20:53:44 [pgroth] ack Dong 20:54:00 [TomDN_] ... It's clear anough to use when looking at the English definition, but it's open enough for interpretation 20:54:01 [Reza_BFar] is Atomicity the common theme? 20:54:13 [Reza_BFar] can't break it down further, etc. 20:54:38 [TomDN_] dong: I'm concerned about this openness to interpretation 20:55:05 [TomDN_] tlebo: but that is mentioned in the wiki page 20:55:25 [pgroth] ack khalidBelhajjame 20:55:28 [Reza_BFar] +q paulo 20:55:29 [TomDN_] ... it is discipline specific 20:55:51 [TomDN_] khalid: it's not something we want to infer, but that is specified by the asserter 20:55:57 [tlebo] DM: "It is recognized that the determination of primary sources can be up to interpretation, and should be done according to conventions accepted within the application's domain" 20:56:06 [Curt] an entity can also have multiple primarysources 20:56:10 [Paolo] q+ 20:56:15 [Paolo] q- 20:56:22 [TomDN_] The name primarySource implies that this is the MAIN entity that was used for the derivation 20:57:07 [pgroth] q? 20:57:14 [pgroth] ack Paulo 20:57:32 [Dong] Is there a constraint "there can only one primary source"? 20:57:36 [hook] +q 20:58:25 [Reza_BFar] I would say that, in a provenance graph, it would mean a point in the graph that has no derivation before it and we know that there is no way we can find derivation that caused it... 20:58:58 [TomDN_] hook: primary source is usually something that is validated by the domain experts 20:59:05 [Luc] q+ 20:59:09 [Reza_BFar] Pq 20:59:12 [Reza_BFar] +q 20:59:13 [pgroth] ack hook\ 20:59:14 [TomDN_] ... can we capture this contextual element? 20:59:19 [Reza_BFar] +1 20:59:24 [Reza_BFar] +q 20:59:25 [TomDN_] Luc: it's a relation, not a type of entity 20:59:37 [pgroth] ack Reza 20:59:39 [TomDN_] ... the context is given by the relation 20:59:40 [pgroth] ack hook 20:59:41 [pgroth] ack Luc 21:00:16 [TomDN_] Reza: if there's a discontinuity in a provenance graph, the point right before this discontinuity is the primary source 21:00:31 [pgroth] q+ 21:00:31 [TomDN_] s/before/after 21:00:36 [zednik] q+ 21:00:37 [tlebo] so, sounds like there's plenty of uses for it :-) 21:01:09 [hook] +q 21:01:15 [TomDN_] pgroth: it's clear that it's useful. But it is left purposely scruffy, to support all these different uses 21:01:27 [TomDN_] ... Does anyone want it out of the spec? 21:01:43 [zednik] q- 21:01:47 [pgroth] ack pgroth 21:01:50 [pgroth] ack hook 21:01:57 [TomDN_] Luc: As concluded earlier, we should add a suitable definition/citation for it 21:02:09 [pgroth] resolved: add a suitable primary source for the definition of primary source 21:02:25 [TomDN_] subtopic: tracedTo 21:02:59 [TomDN_] Luc: I don't like tracedTo 21:03:18 [TomDN_] ... It doesn't seem to serve much purpose, but people objected to dropping it. 21:03:46 [TomDN_] ... The issue is: do we want to infer tracedTo across specialization? 21:04:14 [Paolo] q+ 21:04:16 [TomDN_] .. and how does this add up with the definition in the DM? 21:04:23 [TomDN_] (it doesnt support it) 21:04:25 [pgroth] ack paolo 21:04:31 [pgroth] q+ 21:04:34 [TomDN_] paolo: Why not drop it? 21:04:43 [TomDN_] ... I would. 21:05:09 [TomDN_] pgroth: I like it! 21:05:28 [Luc] q? 21:05:42 [TomDN_] ... It allows to express notions of influence that are guaranteed to be transitive 21:05:52 [TomDN_] ... And it's wooly 21:06:15 [TomDN_] ... Which is great when you try to reconstruct provenance 21:06:38 [TomDN_] ... and derivedFrom isn't necessarily transitive 21:06:58 [tlebo] q+ to say that the current prov-o modeling reflects the right RDF modeling patterns. 21:07:10 [TomDN_] ... For these types of reconstructing applications, I'd add attributes to derivedFrom if tracedTo is dropped 21:07:12 [pgroth] ack pgroth 21:07:14 [Luc] ack pg 21:07:30 [pgroth] ack tlebo 21:07:30 [Zakim] tlebo, you wanted to say that the current prov-o modeling reflects the right RDF modeling patterns. 21:07:34 [TomDN_] tlebo: In prov-o, we have this whole subproperty tree under wasDerivedFrom 21:08:14 [TomDN_] ... If tracedTo disappears, it would be bad 21:08:27 [khalidBelhajjame] +q 21:08:48 [TomDN_] ... When reconstructing/stitching provenance entities, tracedTo is useful 21:08:48 [Paolo] q+ 21:08:50 [jcheney] q+ 21:09:02 [jcheney] q- 21:10:02 [TomDN_] Luc: I'm not sure that the inferences in the constraints are the ones we want 21:10:07 [pgroth] q+ 21:10:14 [TomDN_] ... and how they influence the definition in the DM 21:10:50 [hook] q+ 21:11:00 [khalidBelhajjame] ack khalidBelhajjame 21:11:02 [TomDN_] tlebo: just founded the "Rescue TracedTo Foundation" 21:11:09 [Luc] q? 21:11:30 [tlebo] Don't Club Baby Seals: Save TracedTo! 21:11:37 [Luc] ack pao 21:11:58 [Zakim] +Satya_Sahoo 21:12:12 [TomDN_] paolo: The reason I said to drop it is that it seems more than graph traversal that ignores the relation types, but when it tries to pick some particular paths, it seems arbitrary 21:12:26 [TomDN_] ... I'd like to see this constrained more 21:12:29 [Luc] 21:12:38 [jcheney] q+ 21:12:41 [TomDN_] ... Why are some traversals legal and others not? 21:12:44 [Luc] q? 21:12:55 [TomDN_] Luc: this is indeed the origin of the issue to some extent 21:13:19 [TomDN_] pgroth: Can't we have the concept without that many implications in the constraints? 21:13:51 [TomDN_] pgroth: I'm currently using it for assertions 21:13:55 [TomDN_] +q 21:14:03 [Luc] ack pg 21:14:03 [pgroth] ack pgroth 21:14:24 [TomDN_] hook: I fear that tracedTo would inherit semantics 21:14:30 [khalidBelhajjame] +q 21:14:38 [TomDN_] ... and people would rather use this than more specific relations 21:14:41 [Luc] ack ho 21:15:00 [TomDN_] ... (e.g. at capture time, when you want more specific stuff) 21:15:16 [tlebo] is the PROV-WG really suggesting that we eliminate a transitive property? 21:15:27 [TomDN_] ... It's lossy 21:15:27 [Curt] add verbiage to tracedto encouraging more specific terms 21:16:11 [TomDN_] jcheney: How many of the inferences in the constraints are helpful or not? 21:16:46 [tlebo] is'nt the organizing principle that it's all invovmenets among Entities? 21:16:52 [TomDN_] ... some are redundant 21:17:23 [TomDN_] Luc: When we designed it, we had agents in mind 21:17:29 [TomDN_] ... and responsibility 21:17:38 [TomDN_] jcheney: It seems a bit overloaded 21:18:20 [pgroth] q? 21:18:26 [tlebo] so if we cut out agents from tracedTo, then it's a transitive derivation among entities. "cutting out" Agents is addressed by just adding attribution to the traced to entity. 21:18:27 [pgroth] ack jcheney 21:18:27 [TomDN_] Luc: assuming we go for this option (?) it will be clearer in the constraints, but does it still support pgroth's/hook's use case? 21:18:31 [pgroth] q+ 21:18:34 [Luc] q? 21:18:45 [Luc] ack tom 21:19:10 [tlebo] just define it as a transtiive derivation? 21:19:28 [Luc] q? 21:19:32 [Luc] ack kha 21:19:39 [TomDN_] tomdn: Do we just want to express weaker relations than derivation? 21:20:18 [Luc] q? 21:20:38 [tlebo] transitivity is pretty useful for: SELECT ?everything WHERE { <x> prov:tracedTo ?everything . } 21:21:13 [TomDN_] Khalid: It seems necessary (more than just convenient) when you have missing information about the activities etc. involved when inferring derivation/transitivity 21:21:14 [Paolo] traceability with transitivity isn't just giving a name to a closure relation? 21:21:21 [Reza_BFar] I see we need tracedTo, but it seems like it's solving limitations of sem web reasoning? if tracedTo is a "weaker" form of derivation, then the main purpose of "weaker" is to be used at reasoning time? and if the answer to that is Yes, then I think the issue is we want to do something that's more similar to Baysian reasoning than transitive (which is binary)... but anyways... 21:21:24 [Paolo] or rather, to the closure of a relation 21:21:45 [Luc] q? 21:21:46 [TomDN_] pgroth: For my purposes, having it as some kind of "transitive derivation" is fine 21:21:58 [Reza_BFar] If I have 3 tracedTo's in a row, then by the time I get to the end of the graph, that "tracedTo" should get weaker and weaker... 21:22:03 [tlebo] @paolo: tracedTo is currently an "Activity-less transitive", no? 21:22:05 [Paolo] @Reza_BFar: Bayesian?? 21:22:21 [Reza_BFar] I mean there is some "certainty" value associated with the derivation. 21:22:26 [TomDN_] ... To address Hook's issue with documentation, we could stress this in the spec 21:22:29 [Luc] q? 21:22:39 [Reza_BFar] It looks like "tracedTo = [derivation + certainty factor of reasoning]" 21:22:39 [TomDN_] Luc: then what's wrong with wasDerivedFrom? 21:22:40 [Paolo] @Reza_BFar: oh i see what you mean 21:23:07 [TomDN_] tlebo: TracedTo allows you to add levels of abstraction (more than derivation) 21:23:25 [TomDN_] +1 tlebo, well phrased 21:23:46 [Curt] just derivation, and not attribution? 21:24:48 [Reza_BFar] +q 21:24:52 [TomDN_] Luc: You can just derive a "scruffy"/"imprecise" derivation 21:25:17 [TomDN_] Luc: it doesn't have to specify all the activities involved 21:25:19 [Luc] q? 21:25:23 [Reza_BFar] -q 21:25:31 [Reza_BFar] =q 21:25:34 [Reza_BFar] +q 21:25:39 [Luc] ack pg 21:25:54 [pgroth] ack Reza_BFar 21:26:21 [Paolo] q+ 21:26:49 [hook] hook has joined #prov 21:26:59 [Luc] q? 21:27:08 [Curt] q+ 21:27:15 [Luc] ack pao 21:27:34 [TomDN] TomDN has joined #prov 21:27:41 [TomDN] Reza: we need a certainty factor with every generation. (or even derivation, but might be too complex) pgroth: It would be good, but not in the standard. 21:28:09 [TomDN] paolo: It isn;t clear to me when to use one or the other 21:28:14 [Luc] q+ 21:28:22 [Luc] 21:28:29 [TomDN] Curt: We should add an example for that 21:28:39 [Luc] q? 21:28:47 [pgroth] ack Curt 21:28:49 [TomDN] ... but what about attribution/agents? 21:28:53 [Luc] Trace ◊ is the ability to link back an entity to another by means of derivation or responsibility relations, possibly repeatedly traversed. 21:29:05 [TomDN] Luc: that's the def we HAD 21:29:29 [TomDN] ... If we follow what james suggested, that would become 21:29:30 [pgroth] q+ 21:29:47 [TomDN] ... Trace ◊ is the ability to link back an entity to another by means of derivation relations, possibly repeatedly traversed. 21:29:57 [TomDN] ... (without responsibility) 21:30:10 [TomDN] ... But then that's almost a regular derivation 21:30:12 [Luc] ack pg 21:30:18 [pgroth] q+ 21:30:19 [Luc] ack l 21:30:21 [khalidBelhajjame] +q 21:30:39 [TomDN] pgroth: So we would keep tracedTo as only an inference? 21:30:44 [tlebo] +1 keeping agents in. 21:30:52 [TomDN] Luc: No, that was an adaptation of the current definition 21:31:08 [tlebo] tracedTo gives you an "activity-less" view of everything behind an entity. 21:31:28 [Dong] but derivations are not transitive, I believe 21:31:31 [pgroth] @tlebo but you can do that with activity 21:31:34 [TomDN] @tlebo: but so can derivations, no? 21:31:36 [Luc] q? 21:31:38 [pgroth] derivation 21:31:41 [Paolo] q? 21:31:47 [jcheney] +q to say that my suggestion was to pare down to the minimal inferences for which there is a use case. If there are use cases for attribution as well as derivation then I'm fine with keeping htem. 21:32:01 [Paolo] q+ 21:32:10 [tlebo] @pgroth, but "I don't care about Activity" when I'm trying to draw the tracedTo. 21:32:13 [TomDN] pgroth: I want to be able to assert floppy things, and then have transitivity across that 21:32:20 [jcheney] also, sparql 1.1 will have (hopefully not very broken) transitive queries 21:32:28 [TomDN] ... If that's possible with other things, that's fine 21:32:47 [Luc] q? 21:32:51 [Luc] ack pg 21:33:07 [TomDN] Khalid: To do that, we need to change the definition 21:33:08 [zednik] q+ 21:33:30 [TomDN] @khalid can you put your definition on here? 21:33:33 [Luc] ack kha 21:34:11 [satya] It is a bit difficult to hear on the phone - can they speak a bit louder thanks! 21:34:22 [TomDN] jcheney: It sounded like the reason to have tracedTo was the transitivity, so we keep this, and throw away the rest 21:34:25 [Luc] q? 21:34:49 [Luc] ack jch 21:34:49 [Zakim] jcheney, you wanted to say that my suggestion was to pare down to the minimal inferences for which there is a use case. If there are use cases for attribution as well as 21:34:52 [Zakim] ... derivation then I'm fine with keeping htem. 21:35:12 [tlebo] If we strip out agents in the tracedTo inferences, we'll then just do: SELECT ?everything WHERE { <x> prov:tracedTo ?everything . OPTIONAL { ?everything prov:wasAttributedTo ?who } } 21:35:26 [Luc] q? 21:35:35 [TomDN] paolo: It's really a query language problem (as james just said), not a problem of the model itself 21:35:53 [jcheney] @tlebo good point, is there a strong motivation for having a single property naming this query? 21:36:06 [TomDN] ... that's not a strong enough argument to have it in the model 21:36:17 [tlebo] q+ to say that tracedTo is currently the Activity-less view of what led to an Entity. 21:36:22 [Luc] ack pao 21:36:29 [hook] SPARQL 1.1 supports 21:37:01 [TomDN] zednik: The current definition doesn't make it clear that we're interested in the transitivity 21:37:06 [Luc] q? 21:37:46 [TomDN] ... will think about a new definition 21:37:56 [pgroth] ack zednik 21:38:07 [TomDN] Luc: We seem to have 2 different issues here. 21:38:24 [TomDN] ... If we want it just for querying, we don;t need it in the model. 21:38:36 [TomDN] ... And if we want to assert it, we should have a better definition 21:38:46 [TomDN] ... and make the delta with derivation clear 21:38:50 [Luc] q? 21:39:09 [TomDN] tlebo: the distinction is that tracedTo includes agents 21:39:39 [TomDN] ... tracedTo allows you to get to every static fixed thing (as an activity-less view) about how you got to a certain entity 21:40:02 [Luc] q? 21:40:11 [Luc] ack tl 21:40:11 [Zakim] tlebo, you wanted to say that tracedTo is currently the Activity-less view of what led to an Entity. 21:40:12 [tlebo] q- 21:40:20 [khalidBelhajjame] The only argument for keeping tracedTo is the ability to express that an entity may have influenced the generation of another entity, without necessarily specifying the activitie(s) that were involved 21:40:31 [Luc] q? 21:40:34 [pgroth] q+ 21:41:18 [TomDN] pgroth: I would include the notion of influence in the definition 21:41:53 [Luc] q? 21:41:57 [TomDN] ... but am not blocking 21:41:58 [Luc] ack pg 21:42:16 [hook] q+ 21:42:26 [Luc] ack hoo 21:42:43 [TomDN] hook: couldnt you just use involvement 21:43:13 [TomDN] Luc: it's not in the DM, but in the ontology, but it is a good point 21:43:29 [Luc] q? 21:43:33 [TomDN] hook: seems like tracedTo is redundant 21:44:02 [TomDN] tlebo: So we would use something like "Involvement", without transitivity 21:44:10 [TomDN] ... and drop tracedTo 21:44:27 [Luc] q? 21:45:11 [TomDN] @tlebo: could you paste that in here please? 21:45:40 [tlebo] "The broadest provenance relation between two resources, prov:involved is the superproperty of all unqualified binary relations among any two Activities, Entities, or Agents (or anything else). A more specific property should be favored of prov:involved." 21:45:45 [TomDN] tnx :) 21:45:57 [tlebo] prov:involved prov:editorsDefinition "The broadest provenance relation between two resources, prov:involved is the superproperty of all unqualified binary relations among any two Activities, Entities, or Agents (or anything else). A more specific property should be favored of prov:involved." . 21:47:00 [TomDN] tlebo: this is already a qualified relation in prov-o, so the work there is already done 21:47:19 [TomDN] Luc: so this would need to belong to one of the components in the DM 21:47:50 [tlebo] "agents-responsibility" 21:47:56 [tlebo] ^^ NO 21:48:07 [tlebo] entities-activities 21:48:08 [pgroth] q? 21:48:14 [tlebo] +100 to "entities-activities" :-) 21:48:15 [TomDN] pgroth: should we put this in further elements? 21:48:19 [tlebo] bummer 21:48:25 [tlebo] -100 entities-activities 21:48:41 [TomDN] Luc: that would be a bit akward 21:49:50 [pgroth] q? 21:49:54 [Luc] q? 21:50:10 [TomDN] Luc: If people are satisfied with this resolution, that would be ok 21:51:40 [Luc] proposed: replace Trace (5.3.5) by Involvement, as related two objects to signify some form of influence, and remove all related inferences (including transitivity) 21:52:22 [TomDN] jcheney: We would want to keep some rudamentary inferences 21:52:39 [Luc] proposed: replace Trace (5.3.5) by Involvement, as related two objects to signify some form of influence, and clean up related inferences (no transitivity required) 21:53:18 [hook] 21:53:27 [Luc] proposed: replace Trace (5.3.5) by Involvement, as relation between two objects to signify some form of influence, and clean up related inferences (no transitivity required) 21:53:38 [TomDN] +1 21:53:39 [jcheney] +1 21:53:45 [Paolo] +1 21:53:50 [khalidBelhajjame] +0.99 21:53:50 [Curt] +1 21:53:51 [dcorsar] +1 21:53:53 [CraigTrim] +1 21:54:04 [zednik] +1 21:54:05 [Reza_BFar] +1 21:54:06 [tlebo] +1 21:54:07 [Dong] +1 21:54:13 [satya] +1 21:54:23 [Luc] accepted: replace Trace (5.3.5) by Involvement, as relation between two objects to signify some form of influence, and clean up related inferences (no transitivity required) 21:55:10 [Reza_BFar] involvedWith? 21:55:33 [TomDN] Luc: so what name will this beast have? 21:55:45 [TomDN] tlebo; involved(bla1,bla2) 21:55:46 [tlebo] "involved" 21:56:14 [TomDN] tlebo: involved(bla1,bla2) 21:56:22 [Reza_BFar] Question: is there a situation where the order\direction matters? 21:56:37 [TomDN] khalid: is it symmetric then? 21:56:45 [Reza_BFar] I don't think it is... 21:56:59 [TomDN] pgroth: no, we would look back into the past, right? 21:57:39 [TomDN] jcheney: so how is it used in prov-o? 21:57:48 [TomDN] Luc: it's recommended not to use it 21:57:56 [TomDN] ... (discouraged) 21:58:17 [TomDN] Luc: maybe wasInfluencedBy? 21:58:34 [Curt] tracedto? 21:58:36 [TomDN] khalid: that seems too strong 21:58:39 [Reza_BFar] I think there are 2 different situations: A and B are symmetrically involved -- they are involved together. The other is A is involved with B, but B is not involved with A 21:59:12 [TomDN] pgroth: +1 for influence 21:59:27 [Luc] q? 21:59:37 [TomDN] Curt: indeed, if there's no influence, it wouldnt be in the graph 21:59:54 [Reza_BFar] So, influencedBy is definitely not symmetric, right? 21:59:57 [Reza_BFar] just checking. 22:00:01 [TomDN] tlebo: seems better indeed 22:00:21 [TomDN] Luc: we would change this in the ontology aswell? 22:00:24 [TomDN] tlebo: yes! 22:00:28 [TomDN] Luc: nice! 22:00:41 [jcheney] influence (n): the capacity to have an effect on the character, development, or behavior of someone or something, or the effect itself 22:00:47 [tlebo] prov:involved -> prov:influenced && prov:Involvement -> prov:Influence 22:00:49 [Luc] q? 22:00:51 [pgroth] the capacity to have an effect on the character, development, or behavior of someone or something, or the effect itself: 22:01:29 [TomDN] paulo: what about contribute? 22:01:36 [TomDN] tlebo: too agent-like 22:01:47 [khalidBelhajjame] affectedBy 22:01:49 [TomDN] Luc: and what would the term be then? 22:02:16 [TomDN] wasSomehowRelatedTo? ;) 22:02:55 [Luc] proposed: replace Trace (5.3.5) by INFLUENCE, as relation between two objects to signify some form of influence, and clean up related inferences (no transitivity required) 22:03:13 [TomDN] +1 22:03:23 [Curt] +1 22:03:24 [Dong] +1 22:03:29 [Reza_BFar] +1 22:03:31 [khalidBelhajjame] +1 22:03:31 [CraigTrim] +1 22:03:31 [Paolo] +1 22:03:37 [dcorsar] +1 22:03:39 [jcheney] +1 (cf dictionary definition) 22:04:12 [TomDN] zednik: so generation is currently a subproperty of this 22:04:27 [TomDN] everyone: yes 22:06:31 [TomDN] tlebo: there's a conflict with this concept having some predefined order, and its subproperties (such as wasGeneratedBy) 22:07:25 [Reza_BFar] +1 with Luc 22:07:28 [TomDN] Luc: you would have wasGeneratedBy and generated 22:07:34 [TomDN] ... So that resolves it 22:07:40 [tlebo] +1 22:07:43 [zednik] +1 22:07:54 [Luc] accepted: replace Trace (5.3.5) by INFLUENCE, as relation between two objects to signify some form of influence, and clean up related inferences (no transitivity required) 22:08:08 [tlebo] (consequence: we need wasInfluencedBy with inverse influenced) 22:08:54 [Zakim] -Satya_Sahoo 22:09:09 [Zakim] SW_(PROV)12:00PM has ended 22:09:10 [Zakim] Attendees were +1.805.893.aaaa, Satya_Sahoo 22:24:50 [Luc] q? 22:25:13 [Curt] Curt has joined #prov 22:26:00 [Luc] q? 22:27:37 [TomDN] TomDN has joined #prov 22:27:47 [Zakim] SW_(PROV)12:00PM has now started 22:27:54 [Zakim] + +1.805.893.aaaa 22:29:30 [Luc] 22:29:41 [pgroth] sub-topic: data types 22:30:12 [CraigTrim] Luc: section 5.7.3 of the data model - describes possible attribute value pairs 22:30:35 [CraigTrim] Luc: this section matters for interop; we don't want to re-invent the wheel 22:31:11 [CraigTrim] Luc: RDF WG is still in the process of defining types they will support 22:31:28 [dcorsar] dcorsar has joined #prov 22:31:36 [CraigTrim] Luc: although we want RDF compatible types but how do we phrase this in such a way that if RDF spec changes, we don't have to change our specs too? 22:32:00 [reza_bfar] reza_bfar has joined #prov 22:32:30 [pgroth] q? 22:32:37 [CraigTrim] Luc: Are we happy with the phrasing in this section and should we keep this table of data types? 22:32:47 [Zakim] +Satya_Sahoo 22:33:20 [pgroth] q? 22:33:26 [tlebo] q+ 22:33:30 [pgroth] ack tlebo 22:34:09 [CraigTrim] tlebo: in RDF 1.1 it wasn't about just adding data types, also involved deprecating some of the types. 22:34:32 [tlebo] q- 22:34:34 [pgroth] q? 22:34:45 [CraigTrim] Luc: This table comes from RDF WG 22:34:49 [pgroth] q+ 22:35:32 [CraigTrim] pgroth: "PROV accepts the RDF-Compatible XSD types that RDF enumerates in its own specification" does this mean we limit ourselves to XSD datatypes? 22:35:42 [CraigTrim] pgroth: in the chart (Table 8: Informative List of PROV-DM Data Types) we have RDF defined datatypes 22:35:54 [CraigTrim] pgroth: need to re-phrase that PROV accepts datatypes from RDF spec 22:36:11 [CraigTrim] Luc: If you go back to 3 bullet points above we say use of full data types is recommended 22:36:34 [pgroth] q? 22:36:38 [pgroth] ack pgroth 22:37:02 [CraigTrim] pgroth: suggest if we follow what RDF does in selecting datatypes, we should just say that 22:37:34 [CraigTrim] pgroth: We are following the RDF spec directly, not selectively choosing from the RDF spec 22:39:56 [CraigTrim] pgroth: suggest adding forwarding pointer to something that is not finalized yet 22:40:59 [CraigTrim] pgroth: standard W3C layer is that we point to RDF 1.0 datatypes and then we re-open WG and re-go-through-some-procedure. We can avoid this by being vague, but this vagueness could affect the spec 22:41:10 [CraigTrim] Luc: are all these types supported in the PROV-O? 22:41:45 [hook] hook has joined #prov 22:41:47 [pgroth] q? 22:42:13 [CraigTrim] Luc: In the data types section there is a notion of data type maps - is this relevant to us? 22:42:36 [Luc] 22:45:17 [CraigTrim] Luc: How is i18n supported in XML for strings? 22:45:20 [tlebo] "A special attribute named xml:lang may be inserted in documents to specify the language used in the contents and attribute values of any element in an XML document" 22:45:28 [tlebo] 2.12 Language Identification 22:45:41 [tlebo] 22:45:55 [CraigTrim] pgroth: you can put xml:lang on any element and leverage inheritance 22:46:06 [pgroth] q? 22:46:24 [dcorsar_] dcorsar_ has joined #prov 22:46:36 [CraigTrim] pgroth: proposal is to be completely dependent on RDF datatypes w/no exceptions. 22:47:29 [CraigTrim] pgroth: we might have informative content in our document and recommended content in RDF spec 22:49:34 [CraigTrim] tlebo: we only use common datatypes (URL, int, string, dateTime) in examples, so change should not impact us 22:49:48 [CraigTrim] pgroth: in favour of removing whole table 22:50:03 [CraigTrim] Curt: hot link into other document - if people want to see it, they can see it 22:51:28 [reza_bfar] +q 22:51:30 [CraigTrim] Dong: second that we link into spec - interopt is key 22:51:56 [reza_bfar] I prefer static dependencies over dynamic dependencies, but if Ivan says we can't do that, then it is what it is. 22:52:09 [pgroth] ack reza_bfar 22:52:15 [CraigTrim] reza_bfar: from software pov we don't want dynamic dependencies 22:52:57 [CraigTrim] pgroth: seems to be consensus that we prefer linking to specific datatype doc that already exists 22:53:28 [CraigTrim] pgroth: we should go back to Ivan and work out a process with RDF wg 22:54:01 [reza_bfar] +q 22:54:38 [CraigTrim] pgroth: Ivan prefers not to change any document after it becomes a rec (a new charter is needed even for minor changes) 22:54:52 [reza_bfar] Isn't RDF 1.1 going to be backwards compatible to 1.0? 22:55:28 [CraigTrim] Luc: there will be more types supported in 1.1 22:55:42 [CraigTrim] tlebo: they have also discussed deprecating existing types 22:56:10 [reza_bfar] I guess it all depends on what deprecation means. 22:56:25 [reza_bfar] If it means that it's indefinitely deprecated, but included, then we still don't have an issue. 22:56:32 [CraigTrim] Luc: suggest we endorse recommendation that PROV should support all types in concrete version of RDF 22:56:36 [reza_bfar] but if it means that it's in preparation for future exclusion, then there is a problem 22:56:36 [pgroth] proposed: prov should adopt all the types a specific version of RDF 22:56:40 [CraigTrim] +1 22:56:44 [reza_bfar] +1 22:56:46 [TomDN] +1 22:56:46 [Curt] +1 22:56:48 [dcorsar_] +1 22:56:49 [satya] +1 22:56:49 [jcheney] +1 22:56:52 [tlebo] +1 22:57:05 [pgroth] accepted: prov should adopt all the types a specific version of RDF 22:57:18 [pgroth] proposed: remove table 8 from prov-dm 22:57:20 [Curt] +1 22:57:21 [CraigTrim] +1 22:57:23 [Dong] +1 22:57:23 [tlebo] +1 22:57:25 [khalidBelhajjame] +1 22:57:25 [zednik] +1 22:57:27 [dcorsar_] +1 22:57:27 [jcheney] +1 22:57:27 [satya] +1 22:57:29 [reza_bfar] +1 22:57:36 [pgroth] accepted: remove table 8 from prov-dm 22:58:55 [pgroth] action: ivan to look at resolution on usage of a specific version of rdf datatypes. is it ok? what are the ramifications? 22:58:55 [trackbot] Created ACTION-93 - Look at resolution on usage of a specific version of rdf datatypes. is it ok? what are the ramifications? [on Ivan Herman - due 2012-06-29]. 22:59:31 [pgroth] sub-topic: incompatibility prov-dm and prov-o 23:00:14 [Luc] 23:00:45 [tlebo] "The attribute prov:location is an optional attribute of entity, activity, usage, and generation." 23:01:13 [CraigTrim] Luc: how do we reconcile PROV-O and PROV-DM here 23:01:25 [Luc] 23:01:53 [CraigTrim] Luc: look at overview table 4 in section 5 - supported relations are indicated 23:02:26 [pgroth] q? 23:02:39 [reza_bfar] -q 23:02:40 [pgroth] ack reza_bfar 23:02:41 [CraigTrim] Luc: not sure why have location on ActedOnBehalfOf and WasAttributedTo 23:02:53 [pgroth] q? 23:02:59 [pgroth] q+ 23:03:06 [tlebo] q+ 23:04:04 [CraigTrim] pgroth: I was associated with PROV F2F mtg in SB vs someone in Ohio - so location we are associated with is different 23:04:26 [pgroth] ack pgroth 23:04:48 [CraigTrim] tlebo: PROV-O has open domain for atLocation 23:05:54 [CraigTrim] tlebo: preferred to leave open to avoid actively excluding, but closing with union may be tidy 23:06:02 [pgroth] q? 23:06:07 [pgroth] ack tlebo 23:06:54 [reza_bfar] I agree with Tim there. Extending ontologies is supposed to be for further specialization not generalization 23:06:55 [CraigTrim] tlebo: seems odd for interopt effort to not take broader approach 23:07:01 [pgroth] q? 23:08:28 [CraigTrim] pgroth: reason to constrain Ontology is to give enriched semantics 23:08:54 [CraigTrim] pgroth: to constrain doesn't seem to help interopt in this case because we gain no enriched semantics 23:10:03 [CraigTrim] tlebo: is there a popular vocabulary that gives location? 23:10:21 [CraigTrim] pgroth: yes, but only for particular kinds of location 23:11:30 [CraigTrim] pgroth: just put location on classes in model (location on entity, agent, activity) or open up completely (including qualified relations) 23:11:46 [CraigTrim] pgroth: alt is to pick and choose relations 23:11:55 [pgroth] q? 23:12:31 [CraigTrim] tlebo: alt set domain of atLocation to top level of all our classes 23:13:03 [Curt] q+ 23:13:08 [Luc] q? 23:13:11 [pgroth] ack Curt 23:13:43 [zednik] q+ 23:14:16 [pgroth] ack zednik 23:15:00 [CraigTrim] zednik: suggest agent entity activity and instantaneous event 23:15:31 [CraigTrim] tlebo: union of these four is domain of atLocatoin 23:15:51 [CraigTrim] pgroth: in order to say locatoin of agent, you have to make agent an entity? 23:15:54 [CraigTrim] tlebo: yes... 23:16:37 [CraigTrim] pgroth: not just a map; every kind of location 23:17:22 [CraigTrim] pgroth: what does this leave out? 23:17:57 [pgroth] proposed: the domain of hadLocation is the union entity, activity, agent and instantaneous event 23:18:04 [CraigTrim] pgroth: so we can't say "was derived from at activity" 23:18:08 [reza_bfar] +1 23:18:08 [TomDN] +1 23:18:08 [Curt] +1 23:18:11 [khalidBelhajjame] +1 23:18:11 [Dong] +1 23:18:12 [CraigTrim] +1 23:18:12 [dcorsar_] +1 23:18:12 [jcheney] +1 23:18:15 [tlebo] +1 23:18:19 [zednik] +1 23:18:32 [satya] +1 23:18:38 [Luc] q+ 23:18:38 [Paolo] +1 23:18:46 [pgroth] accepted: the domain of hadLocation is the union entity, activity, agent and instantaneous event 23:19:03 [pgroth] ack Luc 23:19:58 [CraigTrim] Luc: in terms of reconciling PROV-DM and PROV-O - properties of atLocation 23:21:46 [Curt] I am not my name 23:22:35 [CraigTrim] pgroth: any other issues on PROV-DM? bring up now ... 23:22:41 [pgroth] q? 23:22:53 [satya] sorry, I have to leave now - will join in tomorrow 23:23:22 [CraigTrim] pgroth: can't vote on going to last call right now, but prefer straw poll given decisions made today on various technical issues will we move to last call once these are implemented? 23:23:22 [Zakim] -Satya_Sahoo 23:24:14 [pgroth] straw poll: move to last call if all resolutions on the listed technical issues identified at F2F3 are implemented 23:24:21 [TomDN] +1 23:24:22 [reza_bfar] +1 23:24:22 [Curt] +1 23:24:25 [tlebo] +1 23:24:25 [jcheney] +1 23:24:25 [Dong] +1 23:24:27 [dcorsar_] +1 23:24:29 [khalidBelhajjame] +1 23:24:37 [jcheney] q+ to ask about where we left ctx'n 23:24:42 [Paolo] I agree! 23:25:03 [zednik] +1 23:25:10 [CraigTrim] jcheney: was ctx'n left at renaming and change to definition? 23:25:16 [CraigTrim] pgroth: confirmed, plus marking as at risk 23:26:48 [pgroth] Topic: PROV-O 23:26:51 [CraigTrim] Luc: what do we need to do to get to last call on PROV-O? 23:27:07 [CraigTrim] tlebo: will release a document for internal review 23:27:47 [CraigTrim] tlebo: work up to yesterday's deadline was making modifications to Ontology for ctx'n and back-checking all examples to fill in re-names 23:28:22 [CraigTrim] tlebo: the narrative hasn't moved, couple issues to incorporate - principally fixing DM moves progress on PROV-O 23:28:37 [CraigTrim] tlebo: beyond that making sure constructs (terms) are discussed within narrative 23:28:40 [pgroth] q? 23:28:47 [pgroth] ack jcheney 23:28:47 [Zakim] jcheney, you wanted to ask about where we left ctx'n 23:29:45 [CraigTrim] Luc: we have agreed on number of changes in DM today which will be added back into Ontology 23:29:48 [jcheney] q+ to ask if prov-rdf wiki page is still relevant (e.g. it doesn't mention ctx'n or bundles) 23:30:04 [CraigTrim] tlebo: timetable is July 13th 23:31:48 [CraigTrim] Luc: can we add additional resources to expedite timetable 23:32:08 [CraigTrim] Luc: July 13th as internal release date compresses remaining timeframe 23:32:40 [CraigTrim] Luc: We want sync'd release of PROV-DM and PROV-O 23:32:52 [pgroth] q+ 23:33:06 [CraigTrim] jcheney: how much work remains? 23:33:19 [jcheney] That's not me :) 23:33:28 [jcheney] (it's zednik) 23:33:32 [CraigTrim] CraigTrim: my bad 23:33:49 [pgroth] s/jcheney/zednik/ 23:34:10 [Luc] q? 23:34:33 [CraigTrim] tlebo: todo list is number of constructs in Ontology, and if construct is not mentioned in narrative, it is remaining work 23:34:44 [Luc] ack jch 23:34:44 [Zakim] jcheney, you wanted to ask if prov-rdf wiki page is still relevant (e.g. it doesn't mention ctx'n or bundles) 23:36:17 [CraigTrim] pgroth: we can go to last call with less than polished narrative as long as Ontology is fixed 23:36:32 [CraigTrim] pgroth: when can we get a fixed Ontology and who will help with narrative 23:36:45 [CraigTrim] pgroth: but if Ontology is done and narrative lags, we should keep moving ahead 23:37:07 [Luc] q? 23:37:11 [Luc] ack pg 23:37:13 [pgroth] ack pgroth 23:37:26 [CraigTrim] Luc: are there volunteers to work with tlebo? 23:38:01 [pgroth] q? 23:38:45 [zednik] I can work with Tim on prov-o 23:39:37 [CraigTrim] Luc: if parties that can contribute time specify when we can work out timetable based on availability 23:41:55 [Luc] q? 23:42:14 [CraigTrim] Luc: anything else we can discuss about PROV-O in order to get to last call? 23:42:49 [CraigTrim] tlebo: one aspect not personally focused on is property type (irreflexive, functional, etc) 23:43:18 [CraigTrim] tlebo: concerned about some constraints documents but no specific examples to raise 23:46:39 [Luc] q+ to ask if prov-o is about scruffy or proper provenance 23:48:29 [pgroth] q+ 23:48:35 [Luc] ack luc 23:48:35 [Zakim] Luc, you wanted to ask if prov-o is about scruffy or proper provenance 23:49:45 [Luc] q? 23:49:51 [pgroth] q- 23:49:53 [CraigTrim] pgroth: constraints can be implemented in a variety of methods, but Ontology should remain scruffy 23:49:58 [zednik] q+ 23:50:24 [Luc] ack pg 23:50:28 [Luc] ack ze 23:50:34 [CraigTrim] zednik: are constraints part of recommendation? 23:50:35 [Paulo] Paulo has joined #prov 23:50:42 [CraigTrim] Luc: forms a separate recommendation 23:51:05 [jcheney] 23:51:12 [CraigTrim] Luc: eg. "in order to validate PROV the following constraints should be satisfied..." 23:51:41 [Paulo] q+ 23:52:19 [CraigTrim] jcheney: several reviewers have noted document lacked clarity in past around compliance w/respect to constraints 23:52:27 [Luc] ack pau 23:55:21 [Paulo] q+ 23:57:19 [CraigTrim] Luc: is it a resolution of this meeting that the constraints should not be put in the ontology? 23:57:24 [Luc] q? 23:57:28 [CraigTrim] tlebo: does that include the subProperty hierarchy? 23:57:30 [pgroth] q+ 23:57:34 [Luc] ack pau 23:58:40 [TomDN] +q 23:58:44 [CraigTrim] Paulo: we want to make sure people have certain level of correctness when generating PROV 23:58:54 [tlebo] q+ to ask if prov-o loses its subproperty hierarchy in b/c of a strict "DM-only, no prov-constraints!" encoding. 23:58:54 [Luc] q? 23:59:11 [CraigTrim] Paulo: don't think we can provide PROV validator, but should have some level of syntax checking 23:59:29 [CraigTrim] jcheney: no point in standardizing something that is non-decidable 23:59:55 [Luc] q?
http://www.w3.org/2012/06/22-prov-irc
CC-MAIN-2015-40
refinedweb
17,285
69.31
Playing with ptrace, Part II: int main() { int i; for(i = 0;i < 10; ++i) { printf("My counter: %d\n", i); sleep(2); } return 0; } Save the program as dummy2.c. Compile and run it: gcc -o dummy2 dummy2.c ./dummy2 &Now, we can attach to dummy2 by using the code below: #include <sys/ptrace.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <linux/user.h> /* For user_regs_struct etc. */ int main(int argc, char *argv[]) { pid_t traced_process; struct user_regs_struct regs; long ins;); ins = ptrace(PTRACE_PEEKTEXT, traced_process, regs.eip, NULL); printf("EIP: %lx Instruction executed: %lx\n", regs.eip, ins); ptrace(PTRACE_DETACH, traced_process, NULL, NULL); return 0; }The above program simply attaches to a process, waits for it to stop, examines its eip (instruction pointer) and detaches. To inject code use ptrace(PTRACE_POKETEXT, ..) and ptrace(PTRACE_POKEDATA, ..) after the traced process has stopped.: #include <sys/ptrace.h> #include <sys/types.h> #include <sys/wait.h> #include <unistd.h> #include <linux/user.h> const int long_size = sizeof(long);(int argc, char *argv[]) { pid_t traced_process; struct user_regs_struct regs, newregs; long ins; /* int 0x80, int3 */ char code[] = {0xcd,0x80,0xcc,0}; char backup[4];); /* Copy instructions into a backup variable */ getdata(traced_process, regs.eip, backup, 3); /* Put the breakpoint */ putdata(traced_process, regs.eip, code, 3); /* Let the process continue and execute the int 3 instruction */ ptrace(PTRACE_CONT, traced_process, NULL, NULL); wait(NULL); printf("The process stopped, putting back " "the original instructions\n"); printf("Press <enter> to continue\n"); getchar(); putdata(traced_process, regs.eip, backup, 3); /* Setting the eip back to the original instruction to let the process continue */ ptrace(PTRACE_SETREGS, traced_process, NULL, ®s); ptrace(PTRACE_DETACH, traced_process, NULL, NULL); return 0; } Here we replace the three bytes with the code for a trap instruction, and when the process stops, we replace the original instructions and reset the eip to original location. Figures 1-4 clarify how the instruction stream looks when above program is executed.: gcc -o hello hello.c void main() { __asm__(" jmp forward backward: popl %esi # Get the address of # hello world string movl $4, %eax # Do write system call movl $2, %ebx movl %esi, %ecx movl $12, %edx int $0x80 int3 # Breakpoint. Here the # program will stop and # give control back to # the parent forward: call backward .string \"Hello World\\n\"" ); } The jumping backward and forward here is required to find the address of the “hello world” string. We can get the machine code for the above assembly from GDB. Fire up GDB and disassemble the program: (gdb) disassemble main Dump of assembler code for function main: 0x80483e0 <main>: push %ebp 0x80483e1 <main+1>: mov %esp,%ebp 0x80483e3 <main+3>: jmp 0x80483fa <forward> End of assembler dump. (gdb) disassemble forward Dump of assembler code for function forward: 0x80483fa <forward>: call 0x80483e5 <backward> 0x80483ff <forward+5>: dec %eax 0x8048400 <forward+6>: gs 0x8048401 <forward+7>: insb (%dx),%es:(%edi) 0x8048402 <forward+8>: insb (%dx),%es:(%edi) 0x8048403 <forward+9>: outsl %ds:(%esi),(%dx) 0x8048404 <forward+10>: and %dl,0x6f(%edi) 0x8048407 <forward+13>: jb 0x8048475 0x8048409 <forward+15>: or %fs:(%eax),%al 0x804840c <forward+18>: mov %ebp,%esp 0x804840e <forward+20>: pop %ebp 0x804840f <forward+21>: ret End of assembler dump. (gdb) disassemble backward Dump of assembler code for function backward: 0x80483e5 <backward>: pop %esi 0x80483e6 <backward+1>: mov $0x4,%eax 0x80483eb <backward+6>: mov $0x2,%ebx 0x80483f0 <backward+11>: mov %esi,%ecx 0x80483f2 <backward+13>: mov $0xc,%edx 0x80483f7 <backward+18>: int $0x80 0x80483f9 <backward+20>: int3 End of assembler dump. We need to take the machine code bytes from main+3 to backward+20, which is a total of 41 bytes. The machine code can be seen with the x command in GDB: (gdb) x/40bx main+3 <main+3>: eb 15 5e b8 04 00 00 00 <backward+6>: bb 02 00 00 00 89 f1 ba <backward+14>: 0c 00 00 00 cd 80 cc <forward+1>: e6 ff ff ff 48 65 6c 6c <forward+9>: 6f 20 57 6f 72 6c 64 0aNow we have the instruction bytes to be executed. Why wait? We can inject them using the same method as in the previous example. The following is the source code; only the main function is given here: int main(int argc, char *argv[]) { pid_t traced_process; struct user_regs_struct regs, newreg); getdata(traced_process, regs.eip, backup, len); putdata(traced_process, regs.eip, insertcode, len); ptrace(PTRACE_SETREGS, traced_process, NULL, ®s); ptrace(PTRACE_CONT, traced_process, NULL, NULL); wait(NULL); printf("The process stopped, Putting back " "the original instructions\n"); putdata(traced_process, regs.eip, backup, len); ptrace(PTRACE_SETREGS, traced_process, NULL, ®s); printf("Letting it continue with " "original flow\n"); ptrace(PTRACE_DETACH, traced_process, NULL, NULL); return
http://www.linuxjournal.com/article/6210
CC-MAIN-2015-32
refinedweb
777
61.87
public class InputData { String[] descr = {"Apples", "Bananas", "Berries", "Grapes", "Lemons", "Lime", "Melons", "Nectarines", "Oranges", "Peaches", "Pears", "Plums", "Strawberries", "Watermelon", "Asparagus", "Broccoli", "Cabbage", "Carrots", "Cauliflower", "Celery", "Corn", "Garlic", "Lettuce", "Mushrooms", "Onions", "Peppers", "Potato", "Squash", "Sweet Potato", "Tomatoes", "Zucchini", "Cherries", "Mixed Fruit", "Peaches", "Pears", "Pineapples", "Asparagus", "Carrots", "Corn", "Greenbeans", "Peas", "Potatoes", "Tomatoes", "Baked Beans", "Butter Beans", "Green Beans", "Kidney Beans", "Pinto Beans", "PorkNBeans", "String Beans", "Broccoli", "Carrots", "Corn", "Dinners", "French Fries", "Ice Cream", "Mixed Veg.", "Peas", "Pizza", "Tater Tots", "Chicken", "Corned Beef", "Ham", "Salmon", "Tuna", "Vienna Sausage", "Boneless Breast", "Breast with Bone", "Legs", "Whole Chicken", "Wings", "Ground", "Hamburger", "Roast", "Steaks"}; int[] priceCents; int[] prodID; int[] soldUnits; int current; public InputData() { priceCents = new int[descr.length]; prodID = new int[descr.length]; soldUnits = new int[descr.length]; current = 0; populate(); } private void populate() { int i; for (i=0; i<descr.length; i++) { priceCents[i] = (int)(Math.random()*1000+1); prodID[i] = (int)(Math.random()*1000000000); soldUnits[i] = (int)(Math.random()*200); } } public boolean next() { if (current==descr.length-1) return false; current++; return true; } public int getPriceCents() { return priceCents[current]; } public int getProdID() { return prodID[current]; } public String getDescription() { return descr[current]; } public int getUnitsSold() { return soldUnits[current]; } } 1.1 Create a Class named "product" that stores: 1. product name 2. product id (9. digit integer) 3. product price in cents 4. Number of units sold 1.2 write a class shop, which contains an array of product and the name of the shop. both must be private. write two methods named Addproduct, that add a product to the shop 1. the first method takes in input a product object 2. the second takes in input the product id , name, price and unit sold 1.3 write a new class salesreport. this class has the main method of the program salesReport contains two instances of inputData which as shown on the code above named input1 and input2 corresponding to the product of two shops 1.4 Add the following methods to the shop . AveragePrice, which returns the average selling prices for all items sold at that shop . . maxPrice, which returns the price of the most expensive product sold at the shop. 1.5 Add method Show sales report to shop . for each item, this method prints the description, price, and number of units sold.sort the output by number of sales, in descending order use method ShowsalesReport to print sales report for Shop1Data and Shop2Data Part2: write a little note on how you designed the method and how to use the method
https://www.daniweb.com/programming/software-development/threads/443738/java-urgent-help-help-help
CC-MAIN-2016-50
refinedweb
418
66.54
User Tag List Results 1 to 3 of 3 Thread: access >> sql file access >> sql file how do I export access data to a sql file? basicly I want to transfer an access database to mysqlFree Science Homework Help - Join Date - Jul 2002 - Location - Toronto, Canada - 39,347 - Mentioned - 63 Post(s) - Tagged - 3 Thread(s) open the table short method: there should be a menu button that says "publish this with word" and "analyze this with excel" long method: highlight the entire datasheet (click in top left corner just like in excel), then copy/paste into excel save the excel sheet as a csv import csv into mysql with phpmyadmin, mysql-front, etc.rudy.ca | @rudydotca Buy my SitePoint book: Simply SQL "giving out my real stuffs" - Join Date - Dec 2003 - Location - Federal Way, Washington (USA) - 1,524 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) You need a utility or software program to do that. This has been an obsession of mine lately, since deciding to do just such a conversion myself. Here are some tools that will do the job for you: Access-to-MySQL by Intelligent Converters - not free, but a very nice tool. It's the one I use. If you web host allows it, this tool will convert your database and upload it directly to the server. If not, this will create an SQL file from which you can load your database. A trial version is available, which will convert up to 5 records per table. CSV Importer - Free. Installs and runs on your server. It requires you to first convert your Access tables to CSV files. Upload those files to the server, then run this utility. Very easy to use. Zen Werx DB Converter - Free. Note that there is no direct link to the download page. To find the download, click on the Projects link, then scroll down to DB Converter and click on the DB Converter Download link. Save the file to your PC, then install. This utility is totally free and has a very easy user interface. It creates an SQL file for you. I've used all the above utilities, and they work great. There is another one I've heard about called MySQL-Front, which I believe only uploads directly to the server, and won't create a SQL file for you. I could be wrong about that, but I've heard a lot of nice things about this utilitiy. Anyway, you got yourself a whole host of tools here to choose from. Hope this helps.Music Around The World - Collecting tips, trade and want lists, album reviews, & more Showcase your music collection on the Web Bookmarks
http://www.sitepoint.com/forums/showthread.php?176485-access-gt-gt-sql-file&p=1272303
CC-MAIN-2017-22
refinedweb
448
80.11
[edit] Compiled the .rc into .res, still doesnt work, read below for details. [/edit] (Borland C++ Free Command Line Compiler) Ok, I'm just starting with theForgers winapi tutorial, but I'm stuck on Resources. I made a resource.rc file and a resource.h file and included them aporpriately. But when I add resource.rc using #pragma, it says the file could not be opened. Heres my include pragma code: And I get roughly "Line 1: The file could not be opened"And I get roughly "Line 1: The file could not be opened"Code: #pragma resource "resource.rc" //I tried using plain #include to, didint work. #include "resource.h" This is my first time working with resources. What did I do wrong?
http://cboard.cprogramming.com/cplusplus-programming/74616-resource-help-printable-thread.html
CC-MAIN-2014-52
refinedweb
124
78.65
@StefanPochmann Hi, stefan, really a fan of you, how could you be so smart ? is there any way for people to grow a mind or the way to think in coding like yours ? Lizard_squad @Lizard_squad Posts made by Lizard_squad - RE: Java O(n) Time O(n) Space @StefanPochmann - RE: Share my at most two-pass constant space 10-line solution How to do this if it should be stable ? - RE: Shortest/Concise JAVA O(n) Sliding Window Solution What if string p contains duplicated character ? count = p.length() could be wrong under this situation. - RE: JAVA----------Easy Version To Understand!!!!!!!!!!!!!!!!! Well, using bit manipulation does make it a little fast, but the time complexity of this algormith is also o(n^2) .Why not just do this to string directly ? - RE: Java Deque and HashSet design with detailed comments Why my code can't past case 530 ? I can really not find where is wrong, could someone help me ? import java.lang.; import java.util.; public class SnakeGame { int width; int height; int score; int[] head; LinkedList<int[]> body; int[][] food; int curFood; /** Initialize your data structure here. @param width - screen width @param height - screen height @param food - A list of food positions E.g food = [[1,1], [1,0]] means the first food is positioned at [1,1], the second is at [1,0]. */ public SnakeGame(int width, int height, int[][] food) { score = 0; head = new int[]{0, 0}; body = new LinkedList<int[]>(); this.width = width; this.height = height; this.food = food; curFood = 0; } /** Moves the snake. @param direction - 'U' = Up, 'L' = Left, 'R' = Right, 'D' = Down @return The game's score after the move. Return -1 if game over. Game over when snake crosses the screen boundary or bites its body. */ public int move(String direction) { int[] temp = new int[]{head[0], head[1]}; if(direction.equals("U")){ if(head[0]-1 < 0) return -1; head[0] = head[0] - 1; }else if(direction.equals("L")) { if(head[1]-1 < 0) return -1; head[1] = head[1] - 1; }else if(direction.equals("R")){ if(head[1]+1 >= width) return -1; head[1] = head[1] + 1; }else if(direction.equals("D")){ if(head[0]+1 >= height) return -1; head[0] = head[0] + 1; } Iterator<int[]> it = body.iterator(); while(it.hasNext()){ int[] x = it.next(); if(x[0] == head[0] && x[1] == head[1]) return -1; } if(curFood < food.length && food[curFood][0] == head[0] && food[curFood][1] == head[1]){ curFood++; score++; body.add(temp); }else{ body.add(temp); body.removeFirst(); } return score; } } /** - Your SnakeGame object will be instantiated and called as such: - SnakeGame obj = new SnakeGame(width, height, food); - int param_1 = obj.move(direction); */ - RE: Java DFS solution with clear explanations and optimization, beats 97.61% (12ms) It's very smart to come up the skip array ideas, I think the description of this problem is kind of ambiguous since situation like 9-2 is not clear defined as adjacent nodes which kind of confused me. - RE: Java Solution. Two Pass mate, the first pass is smart ! - RE: Share my thinking process @dietpepsi Well,I think this two items equation is much more clear. - RE: Java solution using HashMap with detailed explanation I implemented it in the updated way(using Arrays.toString() to get a string as a key), however, I get a TLE. I guess maybe this key doesn't make map work efficiently.
https://discuss.leetcode.com/user/lizard_squad
CC-MAIN-2017-51
refinedweb
566
75.81
Wikibooks:Reading room/Projects From Wikibooks, the open-content textbooks collection [edit] Project to make Portfolio Managment System in Core Java Please help me regarding the same Mail me if any on girish_dhobe@yahoomail.com,girishdhobe1@gmail.com [edit] Submit a book and an article Dear Wikipedia, How can I submit a book and an article. I surfed your site but had a hard time locating the pages where I can submit articles and books. Thanks for your help, Miriam - Wikipedia articles belong at Wikipedia. If you'd like to start a book, there's no need for approval or anything - just get started! You'll want to make sure it's within our project scope and follows the naming policy. For help starting your first book, you might want to see Using Wikibooks. Finally, please sign your posts to discussion pages with four tildes (~~~~) to make things easy to follow. Good luck! – Mike.lifeguard | talk 00:09, 11 April 2008 (UTC) [edit] logic in understanding computer programming hi guys what do you know about implications of studying logic in understanding basic computer programming? any idea plz.. thanks a lot —The preceding unsigned comment was added by PHaNtOmLaD (talk • contribs) 2008-04-16T15:20:10. [edit] Reviving a Dead Book I'm reviving FHSST Biology, and I just wanted to let everyone know. I'd be very grateful for help. General Biology has some good parts, but it is aimed at an older audience (as I can see from the notes). I'm hoping some of you guys will add to the book. Sincerely, Wesley Gray (talk) 03:34, 27 April 2008 (UTC) - We usually call it "adopting" as opposed to "reviving". However you refer to it, choosing to fix up an old and abandoned book is always appreciated! The "FHSST" stood for "Free High School Science Texts", and I think (but can't remember the details) that these books were affiliated with some kind of external organization. If you would like to rename this book to something else, like "Introduction to Biology", or "High School Biology", or "Biology for Beginners", or whatever, feel free to do it. If you want to keep the name as it is, that's fine too. --Whiteknight (Page) (Talk) 15:12, 27 April 2008 (UTC) [edit] Updating Policy, Guidelines, Help Pages, etc I've created a new template, {{Update}} that we can use to tag pages which are out of date or are not accurate anymore. This can, like all other message templates, be used on books. However, It can (and should) also be used to mark metapages like those found in the Wikibooks: and Help: namespaces, templates (templates which need an aesthetic overhaul, or out of date template documentation), or Category: pages. Hell, we could even throw it on old images that were drawn in mspaint and need to be redone using a better editor. If we have a good comprehensive list of pages that are known to need updating, we can make a concerted effort to fix them. If you see pages that are not accurate anymore or that need to be updated, please tag them with {{Update}}. This will put pages into Category:Pages needing update, and we can go through that list like any other normal maintenance task. --Whiteknight (Page) (Talk) 21:01, 29 April 2008 (UTC) - Thanks for this - I've been trying to get some idea of where work on policy/guideline/useful pages is needed; this will make things easier. – Mike.lifeguard | talk 21:55, 29 April 2008 (UTC) can i post a write up? [edit] Templates to expand images and formatting I've created two templates (both of which probably need to be improved) to makr books that are light on formatting or images: {{Formatting}}, and {{Images}}. This way we can be more precise about certain requests then saying {{Cleanup}} or {{Expand}}. Also, I've written up a short "cheatsheet" for all these templates in one easy place: User:Whiteknight/Template Cheatsheet. For people who are confused about the templates or can't remember them all, I've found this to be a helpful resource to me. --Whiteknight (Page) (Talk) 01:46, 9 May 2008 (UTC) [edit] Engineering bookshelf deprecation I've taken the liberty tonight of deprecating the engineering bookshelf. It now redirects to Subject:Engineering. I'm going to fix up some of the double-redirects next. It's been a long term goal, not only of mine but of several other wikibookians, to deprecate all of the bookshelves and use the dynamically-updated subject pages instead. The engineering bookshelf is a personal pet project of mine, and so has progressed further then any of the others so far. Thus, I think it makes a good pilot for this initiative. Over the summer, as I have time and motivation, I would like to start increasing the quality of the remaining subject pages and deprecating additional bookshelves. I think it's going to be a much better solution for us in the long run, and I hope people agree. --Whiteknight (Page) (Talk) 02:04, 9 May 2008 (UTC) [edit] Categories Overlapping There's a little bit of a problem with the category system that we've been using, and for the most part we've been ignoring it. The problem is that both subject categories and books share a "namespace" when it comes to categorization. A book "X", and all it's subpages, will be in Category:X. This can overlap if X is a common name for the subject. For instance, we have a book Calculus, but we also have a few books by other names that are about calculus-related topics. If we put all the subpages of Calculus and the books that are related into the same category, it's not useful as a navigational or organizational tool anymore. What I would like to do is change major-subject categories to have some kind of prefix, like "Category:Subject-X". Book subpages could still be in "Category:X", like usual. This won't really take much effort to implement, we would change the behavior of {{Subject}}, and then update all the dynamic lists in the Subject namespace. This way we won't have to worry about category name collisions anymore, and all the details will be hidden in templates that people are already mostly using. If nobody has strong opinions about this, I want to try to make this change next week. --Whiteknight (Page) (Talk) 16:47, 9 May 2008 (UTC) - Why wouldn't we have all modules of the book go in Category:Calculus (book) instead? This is a standard method which is used everywhere I've seen this overlap occur. – Mike.lifeguard | talk 17:30, 9 May 2008 (UTC) - That's a good possibility too. I suggest doing it "Category:Foo (Subject)" or something similar instead for 3 reasons: - We can hide all the details inside {{Subject}}, and no authors will really need to deal with it. - If we wanted to make it standard, we would have to add "(book)" to the categories in every single book (and there are at least 1100 of them, depending on how you count). If we don't keep it standard for all, then we're left with another hack-job and there's no sense making any changes at all. - We would have to update all documentation to tell authors to use "Category:BOOKNAME (book)", and then ensure that this was happening when we patrol. - I'm fine with either way, we can employ bots to do it on the book-end like you suggest. I would prefer a method that doesn't put any work or strain on our authors, since the barrier to entry around here is already high enough without having to worry about your book's category. --Whiteknight (Page) (Talk) 17:55, 9 May 2008 (UTC) - How about renaming books to be more descriptive instead? Calculus isn't a descriptive name, it doesn't say who the audience is for, is it an introduction to Calculus, an advanced calculus book, how much coverage does it include, etc.? Using a descriptive book name would remove overlap between subject categories names and book categories as well. Its not like you'd goto a bookstore and find a textbook named just "Calculus" --darklama 18:48, 9 May 2008 (UTC) - This really isn't an appealing solution to me. It requires that we rename books, as many as several hundred that are currently using common names. It also means that we will have to require new authors to avoid common names for their books, when it has been our de facto policy not to place any requirements on a book's title. We would have to police new books to ensure they weren't named after an existing or potential topic. A solution that requires us to do a large amount of work and requires new authors to jump through more hoops before they can start a new book is decidedly not a good solution. Changing the names of the subject categories, on the other hand, requires us to modify {{Subject}} and modify (probably by bot) several dozen Subject: pages. This is easier to execute immediately, requires far less maintenance, and won't cause additional hassle for new book authors. --Whiteknight (Page) (Talk) 21:07, 9 May 2008 (UTC) - And on another note, I have two books named "Calculus" (one has a subtitle), a book called "Fortran", a book called "Algebra", etc. Ordinary books do use common names. Also, it's easier for a user to search for "Calculus" then "Introduction to calculus". --Whiteknight (Page) (Talk) 21:10, 9 May 2008 (UTC) - I think its easier to search for books by subject than it is by title. I don't think Category:Subject-X and Category:BOOKNAME (book) are good conventions to use. Another solution might be to enable case-sensitivity of the first letter as is done on Wiktionary, so that Category:calculus would be different from Category:Calculus, than we could require all subject categories be completely lowercase. --darklama 21:31, 9 May 2008 (UTC)
http://en.wikibooks.org/wiki/Wikibooks:Reading_room/Projects
crawl-001
refinedweb
1,694
59.13
Extending the navigation menu¶ You may have noticed that while our Polls application has been integrated into the CMS, with plugins, toolbar menu items and so on, the site’s navigation menu is still only determined by django CMS Pages. We can hook into the django CMS menu system to add our own nodes to that navigation menu. Create the navigation menu¶ We create the menu using a CMSAttachMenu sub-class, and use the get_nodes() method to add the nodes. For this we need a file called cms_menus.py in our application. Add cms_menus.py in polls_cms_integration/: from django.core.urlresolvers import reverse from django.utils.translation import ugettext_lazy as _ from cms.menu_bases import CMSAttachMenu from menus.base import NavigationNode from menus.menu_pool import menu_pool from polls.models import Poll class PollsMenu(CMSAttachMenu): name = _("Polls Menu") # give the menu a name this is required. def get_nodes(self, request): """ This method is used to build the menu tree. """ nodes = [] for poll in Poll.objects.all(): node = NavigationNode( title=poll.question, url=reverse('polls:detail', args=(poll.pk,)), id=poll.pk, # unique id for this node within the menu ) nodes.append(node) return nodes menu_pool.register_menu(PollsMenu) What’s happening here: - we define a PollsMenuclass, and register it - we give the class a nameattribute (will be displayed in admin) - in its get_nodes()method, we build and return a list of nodes, where: - first we get all the Pollobjects - ... and then create a NavigationNodeobject from each one - ... and return a list of these NavigationNodes This menu class won’t actually do anything until attached to a page. In the Advanced settings of the page to which you attached the apphook earlier, select “Polls Menu” from the list of Attached menu options, and save once more. (You could add the menu to any page, but it makes most sense to add it to this page.) You can force the menu to be added automatically to the page by the apphook if you consider this appropriate. See Apphook menus for information on how to do that. Note The point here is to illustrate the basic principles. In this actual case, note that: - If you’re going to use sub-pages, you’ll need to improve the menu styling to make it work a bit better. - Since the Polls page lists all the Polls in it anyway, this isn’t really the most practical addition to the menu.
http://docs.django-cms.org/en/release-3.4.x/introduction/menu.html
CC-MAIN-2017-26
refinedweb
404
66.64
In addition to Microsoft SQL Server as a data store, most of the modern infrastructure solutions for enterprises also include Microsoft Active Directory. In many cases, AD can serve as a very useful source of users� information. To get this information, developers have to query Microsoft Active Directory. For example: get a list of users, get a list of users of the particular group, get a particular user information such as first or last name, and so on. Microsoft .NET Framework provides a standard library for working with Active Directory: System.DirectoryServices namespace in the System.DirectoryServices.dll. Unfortunately, there is only a bit of documentation and there are not a lot of examples provided. Developers could spend a lot of time for researching errors especially if they�re not very experienced in AD. But luckily, there are some very useful patterns that developers can use and even customize. Here, you can find several C# code examples that demonstrate how to query AD in an efficient manner. Hope this article will be helpful. To start querying Active Directory from your C# code, you simply add a reference to the System.DirectoryServices.dll in your project and the following using statement to your code: using System.DirectoryServices; According to examples provided in the Visual Studio.NET Help, Microsoft recommends using two main classes from the System.DirectoryServices namespace: DirectoryEntry and DirectorySearcher. In most cases, it is enough to use DirectorySearcher class only. Because I am going to talk about querying AD only, not managing AD, I won�t provide detailed explanation of using DirectoryEntry class. But later on, I will show and comment an example of DirectoryEntry usage. In addition, I assume that Active Directory is always up and running in your environment. One more thing I want to mention before we start is that I will separate all AD queries by two large groups: user-oriented queries and common queries. The difference between these types of queries we�ll figure out later. Let�s get started. First of all, I have to tell that a user-oriented query always uses a user name as a parameter. Let�s figure out what the user name is. This is the name part of a login name, which users enter while logging in Windows. This name part follows the �\� symbol that separates the domain name and the user name. It�s a good practice to extract the user name from the login name before using it in the AD query. We can do it easily: string ExtractUserName(string path) { string [] userPath = path.Split(new char [] {'\\'}); return userPath[userPath.Length-1]; } Now we know the user name, and it�s good to know if this user exists in the AD. Let�s do it like: bool IsExistInAD(string loginName) { string userName = ExtractUserName(loginName); DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("(SAMAccountName={0})", userName); search.PropertiesToLoad.Add("cn"); SearchResult result = search.FindOne(); if (result == null) { return false; } else { return true; } } This is our first AD query, so let�s see what we are doing here. First of all, I extract the user name from the login name that we received from Windows, using the ExtractUserName method. Then I create a new DirectorySearcher object. DirectorySearcher class provides a lot of constructors, but I use a default constructor on purpose in order to show how we will initialize the DirectorySearcher before starting a query. Actually, the query itself is located in the Filter property of the DirectorySearcher object. I have to initialize it before starting the query. Here we come to the Active Directory territory. To create a Filter string, you have to be familiar with the AD object structure. But in this article, I won�t talk about AD itself, so simply take a look at the code above and learn that the filter keyword " SAMAccountName" allows us to select an AD object with the given name equal to the login name. Now I have to assign a PropertiesToLoad property of the DirectorySearcher object. This is a collection containing attribute names of AD objects that we want the query to return. By analogy with SQL query, the Filter property serves as the WHERE clause and the PropertiesToLoad property works as a list of column names that the query will return. The " cn" keyword means a common name of the AD object, and in this query, we are not interested in any other properties to return. Basically, this is a good practice to limit the amount of returning properties as much as you can. It can reduce execution time of the query significantly. After all, we are ready to run a query. I simply call a FindOne() method of the DirectorySearcher object that returns a special SearchResult object containing a searching result. If the result object is null, that means there is no information in the AD corresponding to our query. In that particular case, it means a user with the given name is not found. Otherwise, we assume that the user exists in the AD. In order to make sure that the user does exist, we can check out the result object. As we remember, the result object should contain the " cn" property. We can test it out like: lang=csstring cn = (string)result.Properties["cn"][0]; The result object contains a special property named Properties that returns a typed collection containing the values of properties of the object found in the AD. We can also use this method for retrieving additional information about the user from AD. To do this, we only need to add additional PropertiesToLoad arguments before searching and retrieving them after searching. The following code shows that: search.PropertiesToLoad.Add("samaccountname"); search.PropertiesToLoad.Add("givenname"); search.PropertiesToLoad.Add("sn"); SearchResult result = search.FindOne(); ... string samaccountname = (string)result.Properties[�samaccountname�][0]; string givenname = (string)result.Properties[�givenname�][0]; string surname = (string)result.Properties[�sn�][0]; The example above contains the names of the most widely used properties. You can for sure retrieve any possible property from AD simply using its name. That�s it actually. Now I am going to show you several more queries, but you already know how to query AD. Let�s find out what groups our user belongs to. See the code: string GetADUserGroups(string userName) { DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("("|"); } } groupsList.Length -= 1; //remove the last '|' symbol return groupsList.ToString(); } We can notice that the Filter property and PropertiesToLoad property are what makes the difference from the previous query. And also in this query, I assume there are several outputs in the result object. This method returns a list of the AD groups the user belongs to as a string containing '|'-symbol separated group names. Actually, group names in that list appear in a relatively unusual format, and you can examine this format by yourself. Common queries allow us to retrieve much more information from AD. This type of queries are potentially dangerous because of potentially huge amount of information that might be received back from AD. So you have to be careful while experimenting with such queries. Let�s get a list of users belonging to a particular AD group. The code below shows how to do this: ArrayList GetADGroupUsers(string groupName) { SearchResult result; DirectorySearcher search = new DirectorySearcher(); search.Filter = String.Format("(cn={0})", groupName); search.PropertiesToLoad.Add("member"); result = search.FindOne(); ArrayList userNames = new ArrayList(); if (result != null) { for (int counter = 0; counter < result.Properties["member"].Count; counter++) { string user = (string)result.Properties["member"][counter]; userNames.Add(user); } } return userNames; } Here I use the same search filter as for user search, but different set of PropertiesToLoad. So the query returns to us an object with the common name equal to the group name and a properties list containing a list of other objects that are a " member" of the group object obtained. Then I iterate through the list of the " member" objects and add them to the ArrayList being returned. I encourage you to investigate a format of the ArrayList items in order to figure out what actually you have back from AD. You�ll see it�s not a simple user name. The last query I want to discuss in this article is meant to return a list of all the AD domain users. This is an extremely risky operation because of a large amount of users in the AD domain and possible incorrect implementation of AD. I�d like to explain the second sentence. This query uses a special search filter that looks for every object with a specific property that should mean this object is a user object. But sometimes administrators design AD structure even without this property or enter new records to AD not setting this property. So it�s very possible to get a list of all objects in AD instead of domain user objects only. But it�s enough of bad things, let�s get to the code. ArrayList GetAllADDomainUsers(string domainpath) { ArrayList allUsers = new ArrayList(); DirectoryEntry searchRoot = new DirectoryEntry(domainpath); DirectorySearcher search = new DirectorySearcher(searchRoot); search.Filter = "(&(objectClass=user)(objectCategory=person))"; search.PropertiesToLoad.Add("samaccountname"); SearchResult result; SearchResultCollection resultCol = search.FindAll(); if (resultCol != null) { for(int counter=0; counter < resultCol.Count; counter++) { result = resultCol[counter]; if (result.Properties.Contains("samaccountname")) { allUsers.Add((String)result.Properties["samaccountname"][0]); } } } return allUsers; } If we go through the code above, we can see some differences from the previous examples. First, I use a DirectoryEntry object. I do it to connect to a specific context of AD and limit my search by this context. In my case, I suppose to use a single domain context and thus I have to provide a path to the domain I�m interested in. I have to use a specific form of this path in terms of LDAP language. It could look like the following: "LDAP://DC=<domain>" Here <domain> is the name of a particular domain. Another example is using a current domain. To find out the name of the current domain, I can get it from the user login name (remember ExtractUserName method?), or I can determine it programmatically like the following: DirectoryEntry entryRoot = new DirectoryEntry("LDAP://RootDSE"); string domain = entryRoot.Properties["defaultNamingContext"][0]; DirectoryEntry entryDomain = new DirectoryEntry("LDAP://" + domain); This is an example of using a DirectoryEntry class. Well, let�s get back to the code. The next thing you may want to pay attention is a Filter string. It contains no parameters, but instead it consists of an AD specific pattern. (If you have no idea what that pattern means, probably it�s a good idea to get familiar with AD some day ;-)) And the last difference is the use of FindAll() method instead of the FindOne(). In the examples above, I was using a simplified code for demonstration purpose only. But the real code could be much more complex. Especially in the part of PropertiesToLoad and parsing of search outcome. To help you work with AD, I�d like to share some useful tips that have been practically proven. DirectorySearcherobject by setting its public property PropertiesToLoad. DirectorySearcherobject depend on the AD implementation very much. So even if you expect some object properties to be returned, always check them for null before using. try- catchblock. This article is aimed to illustrate the opportunities of working with Microsoft Active Directory provided by the .NET Framework library. Here I have shortly described a common methodology of building AD queries using the .NET Framework standard features. This methodology was illustrated by a number of code examples that can be used practically. Also, some practically proven tips are provided. Using the approach described, developers can create their own AD queries and extend the ones suggested. General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/system/QueryADwithDotNet.aspx
crawl-002
refinedweb
1,958
57.57
In today’s Programming Praxis exercise, our goal is to find the maximum difference between two numbers in a list, with the condition that the higher number comes last. We need to write both a quadratic and a linear algorithm. Let’s get started, shall we? Some imports: import Data.List import qualified Data.List.Key as K import Data.Tuple.HT import Test.QuickCheck The quadratic number is a matter of finding the highest subsequent number for each number in the list and returning the pair with the greatest difference. The two reverse functions are needed since K.maximum unfortunately chooses the latter of the two elements when the comparison yields the same value. maxDiffNaive :: (Enum a, Ord a, Num a) => [a] -> (a, a, a) maxDiffNaive = K.maximum thd3 . reverse . map f . init . tails . zip [0..] where f xs = (i,j,hi-lo) where (i,lo) = head xs (j,hi) = K.maximum (subtract lo . snd) (reverse xs) The linear version can be represented with a simple fold. The accumulator holds the current minimum value as well as the current maximum difference. maxDiffSmart :: (Ord a, Num a, Enum a) => [a] -> (a, a, a) maxDiffSmart = snd . (\(x:xs) -> foldl f (x,(0,0,0)) xs) . zip [0..] where f ((i',lo), (i,j,d)) (j',x) = (if x < lo then (j',x) else (i',lo), if x-lo > d then (i',j',x-lo) else (i,j,d)) Testing whether the two functions produce the same output can be easily automated using QuickCheck. prop_maxDiff :: [Integer] -> Property prop_maxDiff x = not (null x) ==> (maxDiffNaive x == maxDiffSmart x) To test everything we use a combination of unit tests and QuickCheck. main :: IO () main = do let test f = do print $ f [4,3,9,1,8,2,6,7,5] == (3,4,7) print $ f [4,2,9,1,8,2,6,7,5] == (1,2,7) print $ f [4,3,9,1,2,6,7,8,5] == (3,7,7) print $ f [5,4,3] == (0,0,0) print $ f [1,3,3] == (0,1,2) test maxDiffNaive test maxDiffSmart quickCheck prop_maxDiff Everything seems to be working correctly. Tags: bonsai, code, difference, Haskell, kata, maximum, praxis, programming
http://bonsaicode.wordpress.com/2011/04/01/programming-praxis-maximum-difference-in-an-array/
CC-MAIN-2014-42
refinedweb
363
65.73
URL: <> Summary: The gls script for generalized least squares fails when SIGMA is computed. Project: GNU Octave Submitted by: sebald Submitted on: Thu 28 Dec 2017 06:25:47 AM UTC Category: Octave Function Severity: 3 - Normal Priority: 5 - Normal Item Group: Unexpected Error Status: None Assigned to: None Originator Name: Originator Email: Open/Closed: Open Discussion Lock: Any Release: dev Operating System: Any _______________________________________________________ Details: The following illustrates how the routine gls.m fails when the second output is desired: s = [0.5 1.0 1.5]; B = [0.5 0 0.5; 0 0.5 0.5; 0 0 0.5]; X = randn(1000,3) * [1 0 0; 0 2 0; 0 0 3]; O = kron(diag(s)*diag(s), eye(size(X,1))); E = randn(size(X)) * diag(s); Y = X*B + E; [BETA, SIGMA, R] = gls(Y,X,O); plot(X,Y,'.'); BETA SIGMA sqrt(SIGMA) resulting in octave:14> [BETA, SIGMA, R] = gls(Y,X,O); error: gls: operator /: nonconformant arguments (op1 is 1x1, op2 is 1000x3) error: called from gls at line 120 column 9 However, the routine completes if there is only the first output computed, i.e., octave:15> [BETA,~,~] = gls(Y,X,O); The issue is that the gls.m routine is mistakenly using the variable 'r' for two things, the rank and the residuals. Here is a diff hunk to fix it, and I will post a changeset after thinking about this a bit because I'm wondering what to do in the case the observation length minus rank is zero ((rx*cy - rnk) = 0 ... probably isn't very likely). diff --git a/scripts/statistics/base/gls.m b/scripts/statistics/base/gls.m --- a/scripts/statistics/base/gls.m +++ b/scripts/statistics/base/gls.m @@ -104,9 +104,9 @@ function [beta, v, r] = gls (y, x, o) z = o * z; y1 = o * reshape (y, ry*cy, 1); u = z' * z; - r = rank (u); + rnk = rank (u); - if (r == cx*cy) + if (rnk == cx*cy) b = inv (u) * z' * y1; else b = pinv (z) * y1; @@ -117,7 +117,7 @@ function [beta, v, r] = gls (y, x, o) if (isargout (2) || isargout (3)) r = y - x * beta; if (isargout (2)) - v = (reshape (r, ry*cy, 1))' * (o^2) * reshape (r, ry*cy, 1) / (rx*cy - r); + v = (reshape (r, ry*cy, 1))' * (o^2) * reshape (r, ry*cy, 1) / (rx*cy - rnk); endif endif _______________________________________________________ Reply to this item at: <> _______________________________________________ Message sent via/by Savannah
http://lists.gnu.org/archive/html/octave-bug-tracker/2017-12/msg00603.html
CC-MAIN-2019-04
refinedweb
415
57.3
Answered I create a gradle plugin project, by the document way()。Then I add the python's depend: <depends>com.intellij.modules.python</depends> But it report an error: Cannot resolve plugin 'com.intellij.modules.python' in dependencies (Reference: Plugin Dependencies) I find a way to resolve it:- But when I build the project (use intellj.buildPlugin), it reported an error: 错误: 程序包com.jetbrains.python.psi不存在 (Error: Package com.jetbrains.python.psi does not exist) import com.jetbrains.python.psi.PyFunction; ^ How can I fix the error ? I want to use the Python PSI in my Plugin. Thanks for your answer ! You must set/add Python dependencies as described here first: Hi Yann Cebron, Thanks for your help. I have followed the steps to set it up, but still fail. This is my "build.gradle" and "plugin.xml": Is there anything wrong? build.gradle plugin.xml I find that add the dependency to the "PythonCore" can resovle it: Dose this complict with the description "No specific declaration is needed to use PYor PCAPIs." ?
https://intellij-support.jetbrains.com/hc/en-us/community/posts/4420066982290-How-to-use-classes-of-pythonPlugin-always-compile-failed-say-can-t-find-package?page=1#community_comment_4420087150098
CC-MAIN-2022-33
refinedweb
173
61.53
Hey guys, I'm having a very weird problem with a project I'm working on. I have a multi-scene project and on one of the scenes there are three buttons which the user can interact with. Each button takes the user to a difference scene that starts with music, text fade ins, and pretty simple stuff. Two of the buttons worked fine, and I duplicated the scene I used for the second button when I started on the third since they have the same general format. What is really weird is that when I have the third button link to the second scene (via actionscript), everything works fine...but when I use actionscript to link the third button to an EXACT duplicate of the second scene, there is a brief burst of sound before the main track that is supposed to begin starts...almost as if it tried to play a sound file for a brief second and then abruptly stopped - any ideas what could be going on? It just doesn't make sense to me that the annoying 1 second sound would only be there when I make a copy of the scene, but not when I link to the original.... Also, since my project contains many scenes, is there a way for me to preview only one scene that will still let me click on a button to link me to another scene - seems like that only works when I compile the entire movie, when I preview a scene in isolation it gives me a compiler error saying the scene I'm linking to can't be found (likely because when you preview a scene in isolation it doesn't compile any of the button-linked scenes)... Hope this made sense! Thanks! -Ricky Using scenes is always problematic. You really shouldn't be using scenes, that's a methodology that was abandoned at about Flash 2. The central problem is that when a scene based Flash file is saved as an .swf, Flash concatenates all of the scene timelines end to end to make one, long, timeline. One of the resulting problems is that you may end up with duplicate frame labels, and function and variable names. While Flash will warn you about duplicate frame labels, it may have difficulty resolving the duplicates, even if your code refers to the scene and the frame label. Another problem with using scenes is that you end up with one large .swf file that may not download quickly or efficiently and can result in unpredictable playback. At runtime, when Flash will always use the first named thing that it finds, so, if there are two frame labels with the same name, Flash will always go to the first one in the timeline. If it gets completely confused, Flash will always go back to the first frame of the movie and start over, this is the looping that you may see when there is a problem in playback. A better method for producing a movie made of many parts is to produce each section as a unique Flash movie. Then, at runtime, load each of these movies separately. This may seem more complex, but it will yield a more predictable user experience, a simpler production process, and a simpler testing process. Hey Rob, Thanks for the tip. I've gone about breaking everything into one scene movies, and I've got code that, upon the click of a button, loads the new .swf thusly: import flash.display.Loader; import flash.net.URLRequest; stop(); var singleLoader:Loader = new Loader(); btnCont_scene1.addEventListener(MouseEvent.CLICK, btnContClick); function btnContClick(event:MouseEvent):void { removeChild(singleLoader); var request:URLRequest = new URLRequest("DT-Session1-Male_AnxietyIntr2.swf"); singleLoader.load(request); addChild(singleLoader); } However, I'm unsure how to go about clearing the screen first?? The code above just tries to copy right over it without clearing the stage first... Thanks! -Ricky Oops the removeChild actually shouldn't be there, that was just something I was playing around with to try to get the screen to clear. Yes, when you add a child object to the display list that new object will be placed on top of whatever is already on the stage. If you don't position this new object, it will be positioned with its upper left corner at the upper left corner of the stage. Working with the display list and loading new objects is a complex subject, but simply put, loading in a new .swf works pretty much the same as opening a new .swf in a browser window. When you call for that new .swf it will begin to stream into your existing movie. It will begin to run or not depending on how it was coded. One difference between loading an .swf into a browser and loading an additional .swf into an existing .swf is that the background for that additional .swf does not load. The background, the color layer that you define in the movie's properties, is only used for the first movie that is loaded into the browser. This means that if you create a movie with a blank first frame and a stop(); directive at that first frame, and then load that movie, the user will not see anything on the stage as that movie loads. Alternatively, you can set an x and/or y position for the newly loaded movie that is off the visible area of the stage. I often load in new movies with a y position of -1000. Then, when I want to actually use that movie, I change its y position property value so that it shows on the stage. You can then either move that movie back off the visible area or you can use removeChild() to get rid of the movie if you no longer need it. When you load new content, how you make the new content appear on the stage and how you remove that content are all part of the design of your website. You can load in all of the individual parts at the start and then show and hide each piece as needed, or you can wait until the user asks for a particular part and then load that part as it is asked for. Does that help? I've been trying to use the method of making one with a blank first frame and a stop() directive and it loads the movie fine, but it still doesn't solve the issue because I'm linking multiple flash files so that one scene leads to the next which leads to the next etc. And each scene needs to wipe out everything that was there on the previous scene - by the time im going from the second to the third scene, the third is trying to overwrite the second scene again - I tried using a transition one with just the blank stage and a stop; but it didn't work, and I really don't want to have to create a unique transition .swf file each time - it just seems like there should be a less convoluted way to do this - it doesn't seem like it should be too fancy, is there no equivalent to a clear screen command or a way to unload the current stage before loading up whatever is in the next .swf file? I found a way to do it but I want to check to see if there's anything wrong with it - basically I just have the button skip ahead to a frame where I deleted everything that was on the stage, and then on that frame I load the .swf file... cuts out the separate transition .swf middleman.... Yes, that is one way to load in new content and display it. Without seeing your movie's content it's difficult to know what the best method might be. The way that you display your content relates to the design of that content. You need to consider what parts are constant, if any, what parts change, how the user interacts with the individual elements, the randomness of the interaction, the pacing, etc. Say, for instance, that you have three sections to your movie and you want to move from one section to another when the user clicks on a button. Further, you want to show a transition between each of these sections. You can create each section as a different flash movie. Likewise you can create the transition as another unique flash movie. Finally, you can create a container movie that does nothing except to load in these content movies. Let's call these movies "container", "content1", "content2", "content3" and "transition". Have the movie container, load in each of these movies with transition as the last to be loaded. So now you have four .swf movies stacked on top of your container movie. Content1 can play when it loads. When the user calls for the movie content2, you can play the movie transition and when it finishes, play the movie content2. When the transition movie begins, you can remove the movie content1. If you no longer need the movie content1, then you can use removeChild() to get rid of it. If you think that you will need it again, then just rewind it back to frame 1. Hey Rob, I'm pretty confused. My application generally proceeds in a linear fashion, and content is not reused so I really just need to wipe out the stage each time and load in a new .swf file. There is one part where I used a sharedObject to store what the user has already clicked on so I can adjust which options are later presented. I've been using the gotoAndStop() method of loading new movies, but things are getting all mixed up and I don't really understand what's going on. Sometimes things don't load, sometimes they load multiple times and loop, and other times I get a compile error - for instance, when the user clicks on a button, I have the actionscript direct it to a certain frame and load a new movie - but then when that movie loads, it crashes at frame 466 and when I look at it in the debugger, its because its still traversing the timeline of the parent caller and referring to a button that doesn't exist on the movie I've loaded -- I'm confused as to how to do something that I thought would be pretty straightforward - all I want is that each time the new movie loads for flash to use that timeline and that timeline only -- I'm not sure why it's going through the timeline of the calling movie - I have a stop command so I thought it would just go straight to the new movie's first frame and go from there....I've been trying to read help documentation on how the loading stuff works but it's confusing and I'm unable to find examples of the sort of simple thing I need to be do... -Ricky It sounds like you may have a couple of problems. The first is that you are addressing the wrong movie and the second is that you may be addressing a movie before its ready to be used. There may be other problems. Can you send me a copy of the movies so that I can see what's going on? Thanks for all the help Rob. Below are links to download the movies. Here's a brief explanation of what I'm trying to do. DTM1-Start.swf is the starter file, and at the end is a continue button that should load DTM1-Intr1.swf. DTM1-Intr1.swf does load successfully, but it loops instead of following the stop() command at the end to allow the user to click on one of the three emotion buttons. If, however, I run DTM1-Intr1.swf alone, it does not loop and the stop() command is executed as it should be -- this is a common theme throughout, i.e., the files work as they should when I run them directly, it's the loading and linking between .swf files that is problematic. Anyway, if I run DTM1-Intr1.swf directly, I am able to click on one of three buttons. No matter what button I choose (anger- DTM1-Ang1.swf, anxiety - DTM1-Anx1.swf, or sadness - DTM1-Sad1.swf), the movie only gets a bit through the first block of text before crashing with a null reference error (I alluded to this problem in my above post). Again, if I run any of the emotion movies directly, there is no crash. When running the emotion movies directly, the continue button is supposed to lead the user to DTM1-EmotTrans.swf. It does do this, but the movie loops repeatedly instead of following the stop() and goto commands that are supposed to display the buttons the user has not yet clicked (i.e., if they first clicked the sad button, only the anxiety and anger buttons remain on the screen in DTM1-EmotTrans.swf) --- again, if I open DTM1-EmotTrans.swf directly, it displays the correct buttons. Finally, when clicking on one of the emotion buttons from the DTM1-EmotTrans movie, where it should be taking me back to the emotion movies, it instead crashes with a null reference error. So basically none of my linking is working and I'm not sure what I'm doing wrong :/ ..... Anyway, below are the .swf files -- I really appreciate your help, I'm pretty desperate. DTM1-Start.swf - DTM1-Intr1.swf - DTM1-Sad1.swf - DTM1-Anx1.swf - DTM1-Ang1.swf - DTM1-EmotTrans.swf - With gratitude, Ricky Also, I'm not sure if you need the project files as well to figure out what might be going on - I didn't post them since they're significantly bigger, but if you need them I'll put them up. -Ricky Yes, the .fla files will be the useful things for me to look at. Send me a private message through this forum and I'll send you an address to my file uploader. That way I'll get the files directly.
http://forums.adobe.com/message/4576293
CC-MAIN-2013-48
refinedweb
2,376
77.27
So I have absolutely no idea why this is happening, hopefully someone can help me out. I'm a novice programmer, and lately I've noticed that whenever i use String.split() with "" as a delimiter, the first index will be null and the second index will contain the first element, and so on. Here's an example of some output i've been seeing: Code : public class wtf { public static void main(String[] args) { String mystring = "hello"; String[] myarray = mystring.split(""); for(int i=0; i<myarray.length;i++) System.out.println(i + ": "+ myarray[i]); } } OUTPUT: 0: 1: h 2: e 3: l 4: l 5: o
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/13753-string-split-puts-null-first-index-printingthethread.html
CC-MAIN-2014-15
refinedweb
108
72.87
Typed CSS modules with Bazel Lewis Hemens ・3 min read If you are building TypeScript with Bazel and using CSS, you probably want it to be typed. Tools such as Webpack can generate .d.ts files for you, however Webpack plugins do this by adding the .d.ts files to your source directory. This is a no go in Bazel, where you generally can't / shouldn't mutate the source during a build step. This can be accomplished fairly easily with a custom build rule. Note: the following has been tested with Bazel 0.26.1 and rules_nodejs 0.31.1. All the following code snippets are from an open-source project and you can see them working in their entirety here: The problem Assume we have a CSS file called styles.css containing the following: .someClass { color: #fff; } .someClass .someOtherClass { display: flex; } And we want to generate a styles.css.d.ts that looks like this: export const someClass: string; export const someOtherClass: string; So that we can provide this as an input to any consuming rules such as ts_library to make sure we aren't using any class names that don't exist and to keep the TS compiler happy. Using typed-css-modules We can do this using the typed-css-modules package. First we want to set up a nodejs_binary that we can use to generate these typings. Firstly add this to your root package.json assuming you manage your projects dependencies with rules_nodejs and npm_install/yarn_install rules, then add the following to a BUILD file somewhere in your repo (we keep this in the root BUILD file): nodejs_binary( name = "tcm", data = [ "@npm//typed-css-modules", ], entry_point = "@npm//node_modules/typed-css-modules:lib/cli.js", ) This allows us to run the TCM CLI from within Bazel rules. Writing the Bazel rule Now we need to define a Bazel rule that can actually run the TCM CLI and generate typings files. Add a new file called css_typings.bzl somewhere in your repository with the following: def _impl(ctx): outs = [] for f in ctx.files.srcs: # Only create outputs for css files. if f.path[-4:] != ".css": fail("Only .css file inputs are allowed.") out = ctx.actions.declare_file(f.basename.replace(".css", ".css.d.ts"), sibling = f) outs.append(out) ctx.actions.run( inputs = [f] + [ctx.executable._tool], outputs = [out], executable = ctx.executable._tool, arguments = ["-o", out.root.path, "-p", f.path, "--silent"], progress_message = "Generating CSS type definitions for %s" % f.path, ) # Return a structure that is compatible with the deps[] of a ts_library. return struct( files = depset(outs), typescript = struct( declarations = depset(outs), transitive_declarations = depset(outs), type_blacklisted_declarations = depset(), es5_sources = depset(), es6_sources = depset(), transitive_es5_sources = depset(), transitive_es6_sources = depset(), ), ) css_typings = rule( implementation = _impl, attrs = { "srcs": attr.label_list(doc = "css files", allow_files = True), "_tool": attr.label( executable = True, cfg = "host", allow_files = True, default = Label("//:tcm"), ), }, ) This is a fairly simple Bazel build rule that generates CSS typings using the TCM CLI we installed previously. - Iterates through each input CSS file - Runs the TCM tool against the CSS file to generate typings - Returns something that is compatible as an input to ts_libraryrules and can be added as a dependency You will need to replace the Label("//:tcm") line with the name of the nodejs_binary rule you created in the previous step. Putting it all together Here is a simple example BUILD file that uses this rule, assuming you put the css_typings.bzl file in a tools directory: filegroup( name = "css", srcs = glob(["**/*.css"]), ) load("//tools:css_typings.bzl", "css_typings") css_typings( name = "css_typings", srcs = [":css"], ) load("@npm_bazel_typescript//:index.bzl", "ts_library") ts_library( name = "components", srcs = glob([ "**/*.ts", "**/*.tsx", ]), data = [ ":css", ], deps = [ ":css_typings", ... ], ) You probably still need to actually bundle the CSS files using the data attribute above, assuming that this library is going to bundled for web by some downstream consumer. And that should be all you need to generate CSS typings with Bazel Typescript projects! If this was useful to you, please let me know and I'll put it into a repository so it can be imported and used without the copy-paste.
https://dev.to/lewish/typed-css-modules-with-bazel-3133
CC-MAIN-2019-51
refinedweb
680
56.86
XS Transforming XML with XSLT Transforming XML with XSLT This Example shows you how to Transform XML with the XSLT in a DOM document. JAXP (Java API for XML Processing) is an interface which provides Introduction to XSLT ; Extensible Stylesheet Language Transformations (XSLT) is an XML-based language... language for XML. With XSLT you can add/remove elements and attributes to or from... is to apply an XSLT stylesheet to an XML source document and produce a result document The XML Style Sheet Translation (XSLT) APIs The XML Style Sheet Translation (XSLT) APIs The XSLT Packages The XSLT APIs are defined in the following packages Orangevolt XSLT xml documents by widely configurable XSLT launch configurations... Orangevolt XSLT OrangevoltXSLT for Eclipse provides XSLT support XSLT Introductions XSLT Introductions XSLT is an xml based language for transforming XML documents into other XML documents. XSLT stands for eXtensible Styles Language...). XSLT document is itself a well formed XML document which defines how An XSLT Stylesheet writing templates in XSLT document. <?xml version="1.0... .style1 { border-style: solid; border-width: 1px; } XSLT document is a well formed XML document which defines how the transformation of an xml' xslt logging xslt logging am working with xslt and want to log the user actions like clicking on the button and clicking on the text field etc. Can anyone plss tell me Is that possible..?? Thanks in XSLT Output Types plain text using the above line in xslt document. XML <xsl:output XSLT can be used to output XML using the above line... output. Although it is not required to specify the type of output but an XSLT Conditional increment in xslt Create a Java program using XSLT APIs Create a Java program using XSLT APIs Now we will develop a class in Java that takes both XML...: arg[0] is for XML file, arg[1] is for XSL file, and arg[2] is for taking XML Transformation in JSP file to XSLT stylesheet. XML transform tag performs transformation from XML file to XSLT file. Syntax for XML transform tag is as below:  ...; <x:transform xml = "${inputvalue}" xslt How to create XML file - XML How to create XML file Creating a XML file, need an example. Thanks!! To create XML file you need plain text editor like note pad. After creating your file save it with .xml extension. Hi,Java programming xml - XML xml define x-path ,why it is more useful in xslt? Hi friend, XPath : It is a language for finding information in an XML document. It is used to navigate through elements and attributes in an XML document XML Tutorials Introduction to XSL Introduction to XSLT Developing an XSLT Transformer...; Transforming XML with XSLT This Example shows you how to Transform XML with the XSLT in a DOM document. JAXP (Java API Sorting Xml file - XML sort my xml file. Here is my xslt.... Thanks. I am trying to do it with xslt. But it can't sort my xml...Sorting Xml file I have an xml file like this: Smith USA The Role of AJAX in enhancing the user experience on the Web technologies in a new way. These include HTML, CSS, DOM, XML, XSLT, XMLHttpRequest and Javascript. The acronym AJAX stands for Asynchronous Javascript and XML... for developing and running software on mobile phones. This SDK will allow XSLT Elements and Attributes XSL Result and its example XSL Result and its example XSLT stands for XSL Transformations. It is the most important part of XSL. XSLT is a language which is used for transforming the XML document into other XML document or the language which browser recognize Developing responsive Ajax based Applications with ajax technologies HTML, CSS, DOM, XML, XSLT, XMLHttpRequest and JavaScript. The acronym AJAX stands for Asynchronous JavaScript and XML. AJAX is based... for Asynchronous JavaScript and XML. Ajax is used to fetch the data from web XMLBuddy compact syntax and XSLT. Dynamic code assist for XML driven by DTD, XML...). Apply XSLT transformations. Auto-validate XML, DTD, XML Schema, RELAX NG...; The second release of XMLBuddy, supporting XML, DTD, XML Schema, RELAX What is Hibernate Criteria Transformer? What is Hibernate Criteria Transformer? Hi, Can anyone explain me about the Hibernate Criteria Transformer? I need good example of Hibernate Criteria Transformer . Thanks Hi, check the example Hibernate Criteria Convert PDF to XML in Java for a transformation result in XML.After that Transformer class process XML from...Convert PDF to XML File in Java In this Java tutorial section, you will learn how to convert pdf file to xml using java program. We have used itext api XML Interviews Question page8,xml Interviews Guide,xml Interviews that formats the output as an XML document, and you could import by writing an XSLT... XML Interviews Question page8  ... the XML Declaration Syntax (very simple: declaration keywords begin with <!ELEMENT Java Xml Transform . To know more about this, just click: http:/... Java Xml Transform  ... (included in the J2EE API). javax.xml.transform is used to define XSLT transformation Hibernate Criteria Transformer Example Hibernate Criteria Transformer Example I want example of Hibernate Criteria Transformer to use in my Java project. share the good link. Thanks... program. Check the tutorial Hibernate Criteria Transformer . Check the Latest XML and JavaScript JavaScript and XML In this section we will see how JavaScript and XML... libraries to fetch the server data. Developer can use these XML data or JSON data retrieved from the server. Here XML plays important role data transfer Convert text file to XML file in Java that Transformer class process XML from a variety of sources and write...Convert text file to XML file Java In this section, you will learn how to convert the text file into xml file in Java language. To do this, we have used Uses of XML the data into XML files and the use the XSLT transformation API's...Uses of XML In this section we are discussing the importance of XML and see the uses of XML. The full form of XML is Extensible Markup Language. XML Oracle Books ; Building Oracle XML Applications This rich and detailed look at the many Oracle tools that support XML development shows Java and PL/SQL developers how to combine the power of XML and XSLT with the speed Eclipse Plunging/XML Oxygen XML Editor and XSLT Debugger integrates smoothly with Eclipse..., XML perspective, XSLT Debugger perspective, wizards, document templates... XSLT and FOPs make Oxygen the complete solution for XML applications.   Hibernate Criteria Transformer Example code Hibernate Criteria Transformer Example code Hello, I am trying to find the example of Hibernate Criteria Transformer. Tell me the good tutorial of Hibernate Criteria Transformer with source code. Thanks Hi, Check xml - XML xml hi convert xml document to xml string.i am using below code... StringWriter(); Transformer serializer... = stw.toString(); after i am getting xml string result, like Successxxx profile Introduction to XML Introduction to XML  ... to develop XSL because there was a need for an XML-based Stylesheet Language. Thus... Stylesheet Structure (a) XSLT namespace The XSL stylesheet starts XML Related Technologies: An overview consists of three parts: XSLT - a language for transforming XML documents... for formatting XML documents. XSLT (XSL Transformations) is used to transform XML... XML Related Technologies: An overview   xml - XML xml hi convert xml file to xml string in java ,after getting the xml string result and how to load xml string result? this my problem pls help..."); FileOutputStream output = new FileOutputStream("new.xml"); ReadXML xml = new XML, XML Tutorial, XML Tutorial Online, XML Examples, XML Tutorial Example XML XML Tutorials and examples In this section we will learn XML with the help of tutorials and example code. If you are a beginner in XML then learn it step-by-step following through all the tutorials given here. About XML Xcarecrows 4 XML ;XML automates the processing of XML documents through XSL Transformations (XSLT... empowering the user with a coherent XML and XSLT workshop. Architecture... Xcarecrows 4 XML   Hibernate Criteria Transformer Hibernate Criteria Transformer A Hibernate Criteria Transformer is an interface which allow you to transform any result of Hibernate Criteria element..._ROOT_ENTITY); An example of Criteria Transformer is given below XML Books on XPath 2.0, a sub-language within XSLT that determines which part of an XML document the XSLT transforms. Written for professional programmers who use XML every... XML Books   Java XML Books Java XML Books Java and XML Books One night... they stumbled into a directory full of XML documents on the main server. ?What XML Interviews Question page16,xml Interviews Guide,xml Interviews . For example, the following XSLT (XSL Transformations) stylesheet uses XML... XML Interviews Question page16 Do I need to use XML namespaces? Maybe, maybe XML Interviews Question page13,xml Interviews Guide,xml Interviews for the use of the +xml media type suffix for identifying ancillary files such as XSLT (application/xslt+xml). If you run scripts generating XHTML which you wish... XML Interviews Question page13   how to write in xml? - XML how to write in xml? can anybody give the code how to write in xml...(new InputStreamReader(System.in)); System.out.print("Enter XML file name... transformer Transformer tFormer = TransformerFactory.newInstance XML Interviews Question page1,xml Interviews Guide,xml Interviews XML Interviews Question page1 What is XML? XML is the Extensible Markup... language). Instead, XML is actually a metalanguage—a language for describing Create XML - XML elements in your XML file: "); String str = buff.readLine(); int... = TransformerFactory.newInstance(); Transformer transformer...:// Thanks creating document in XML - XML creating document in XML Create an XML document for catalogue...)); System.out.print("Enter number to add elements in your XML file: "); String... = TransformerFactory.newInstance(); Transformer transformer java and xml problem - XML java and xml problem hi, i need to write a java program that generates an xml file as follows: aaa vvv... XML file: "); //String str = bf.readLine(); int no = Integer.parseInt("1 XML Interviews Question page19 declarations. XPath, XSLT, and XML Schemas treat them as namespaces declarations... XML Interviews Question page19 Why are special attributes used to declare XML storing data in xml - XML storing data in xml Can u plz help me how to store data in xml using... = TransformerFactory.newInstance(); Transformer transformer...,name,address,contactNo,email); System.out.println("Xml File Created An Overview of the XML-APIs An Overview of the XML-APIs Here we have listed all the major Java APIs for XML...: Java API for XML Processing This API provides a common interface XML Interviews Question page10 . The water is muddied by XSL (both XSLT and XSL:FO) which use XML syntax... compiles the directives specified in XSLT files into Java bytecode to process XML... XML Interviews Question page10   again with xml - XML again with xml hi all i am a beginner in xml so pls give me...)); System.out.print("Enter a XML file name: "); String xmlFile = buff.readLine... tFactory = TransformerFactory.newInstance(); Transformer tFormer Processing XML with Java ; } Processing XML with Java XML is cross-platform software, hardware independent language. XML is the acronym for eXtensible Markup Language. Markup... is. Unlike Html, XML markup language is used as data container Developing Axis Web services with XML Schemas. Developing Axis Web services with XML Schemas. Developing SOAP based web services (Note... to quickly develop the working web services with xml schemas. All the necessary Axis jar creating tables as an xml document - XML creating tables as an xml document Create a table of a medal tally of the Olympic Games as an XML document. The table must have the name...); System.out.println("Xml File Created Successfully"); } catch(Exception e Creation of xml and to create a xml file containing all those datas...My database datas are in key... of query select * from tablename where appid="+12345+". An xml file should be generated ...My xml file should in this format XXXX YYYY java - XML java how can i validate my xml file using java code plz send me de... kumar Hi friend, Step to validate a xml file against a DTD (Document Type Definition) using the DOM APIs. Here is the xml file "User.xml Open Source XML Editor Open Source XML Editor Open source Extensible XML Editor The Xerlin Project is a Java? based XML modeling application written to make creating and editing XML files easier. It runs on any Java 2 virtual machine (JDK1.2.2 DOM - XML DOM Hello.... I'm creating an xml file from java using DOM... from the database values... and saving it in a file But the created xml file... = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer readXML - XML readXML hiii i face problems in reading a xml file.. pixvalue1path1... enter XML file name: "); String xmlFile = buff.readLine(); File...(xmlFile); Transformer tf = TransformerFactory.newInstance().newTransformer XML Interviews Question page9 . It is also possible to use XSLT to convert XML math markup to LATEX for print (PDF... XML Interviews Question page9 Can I encode mathematics using XML ? A: Yes dom to xml string dom to xml string Hi, I am writing a program in java that reads the xml file from a webservice. The Document object is returned in my program. I have save the dom document into xml file. How to convert dom to xml string Struts 2 Training Training for developing enterprise applications with Struts 2 framework. Course... cycle including of building, developing and maintaining the whole application... like Java Filters, Java Beans, ResourceBundles, XML etc. For the Model how to update xml from java - XML how to update xml from java hi, Im new to xml parsing and dont know much about. I need to modify the attribute val of a tag in a complex xml file... friend, To solve your problem, please visit to: XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials XML Tutorials Transforming XML with SAX Filters This Example shows you the way to Transform XML with SAXFilters. JAXP (Java API for XML Processing) is an interface which provides Dot Net Architect , XML / XSLT, Web Services, Knowledge of Design patterns, Web Application...; Developing architecture for the Dot Net Projects Managing... Net C# MS SQL Server 2000/2005 XML/XSLT  xml creation in java xml creation in java HI, I need a java program to create an xml file... therez a tutorial in your site to create an xml file at but this isn't creating a file, its just XML,XML Tutorials,Online XML Tutorial,XML Help Tutorials Ignoring Comments While Parsing an XML File This Example shows you how to Ignore Comments in an XML File. JAXP is an interface which provides parsing of xml documents. Here XML-JAVA - Java Beginners XML-JAVA How to create XML file and write to this file in JAVA... = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer...,contactNo,email); System.out.println("Xml File Created Successfully | Developing an XSLT Transformer... Language | Preparing table for HQL | Developing POJO class | HQL from... the application XML Tutorial Section XML : An Introduction | XML - History XML Interviews Question page3 XML Interviews Question page3  ... information. XML allows groups of people or organizations to question C.13, create... infrastructure. Why should I use XML? Here are a few reasons append node problem Xml append node problem print("code sample");Question: I create a XML which looks like this: <cwMin>31</cwMin> The code used in generating this XML is : XMLOutputFactory xof retrievin xml data retrievin xml data If i need to retrieve some node elements from xml... = builder.parse(xmlFile); Transformer tFormer...(0); } } } For the above code, we have used following xml file: < xml in java - Java Beginners xml in java how to create a database in xml and then display its...); TransformerFactory factory = TransformerFactory.newInstance(); Transformer transformer = factory.newTransformer(); transformer.setOutputProperty XSLXSLTTutorials . In addition to XSLT, XSL includes an XML vocabulary for specifying formatting. XSL specifies the styling of an XML document by using XSLT to describe how the document.... In this tutorial you will learn how to use XSLT to transform XML documents into other formats DEVELOPING & DEPLOYING A PACKAGED EJB DEVELOPING & DEPLOYING A PACKAGED EJB (WEBLOGIC-7) & ACCESSING... suggests to use the Internet address (of the company developing the program...' in the current folder and edit the two xml files in META-INF folder( ejb-jar.xml & Extensible Stylesheet Language (XSL) : 1. XSL Transformations (XSLT) 2. XML Path Language (XPath) 3. XSL Formatting Objects (XSL-FO) which are used to transform and render XML documents. XSLT... which is used by XSLT to refer to parts of an XML document. XSL-FO is an XML Introduction To Enterprise Java Bean(EJB). Developing web component. Developing web component  ...; <?xml version="1.0... start with xml declaration and after the document type declaration < how to edit xml file which is currently running in web server - XML how to edit xml file which is currently running in web server Hello, I want to add new element in xml file which is currently running in my web server apache tomcat.I can add and modify xml file by giving Path like that "E web developing Developing Struts Application Developing Struts Application  ...;, by editing the concerned XML files, without touching the source or class files... =========================================== <?xml version="1.0" ....."?> Ask Ajax Questions Online ; AJAX refers to Asynchronous JavaScript and XML, an amalgamation of JavaScript and XML used for creating interactive web... using the Document Object Model, data interchange and manipulation using XML java and xml problem. plz see this 1 first - XML java and xml problem. plz see this 1 first hi, i need to write a java program that generates an xml file as follows: xxx... in your XML file: "); //String str = bf.readLine(); int no = Integer.parseInt("1 Developing Hello World application )} is required. Now configure the struts.xml file as struts.xml <?xml XML Interviews Question page12 XML Interviews Question page12  ...-angle-bracket and the ampersand), for example when documenting XML (this FAQ uses... to do with markup: it's just a string of opaque characters, and if you use an XML Writing xml file - Java Beginners Writing xml file Thank you for the quick response The values which... XmlServlet().createXmlTree(doc); System.out.println("Xml File Created...(); } //TransformerFactory instance is used to create Transformer objects XML XML How i remove a tag from xml and update it in my xml
http://www.roseindia.net/tutorialhelp/comment/85542
CC-MAIN-2014-10
refinedweb
3,044
57.16
Timer method for scene? Hello again In my "game" I have added powerups that when player catches on green lasers will shoot from the spaceship. However they only fire once and I want them to keep fire for about 10 sec. I have tried using a counter that counts down when collision with powerups appear. But that made pythonista crash. So is there a way to add a timer or similar for functions in scene? In my mind there should be a way when using the run_actionfor the "laser" to make it last about 10 sec Here is the code for the laser function: def multi_laser) def laser_multi) As you can see I made one function for each of the two lasers (only way for me to get it to work) Im greatful for any help or tips // B - flight_714 Full disclosure: I'm a perpetual noob both with Pythonista and programming in general, but I have wrestled with this issue quite a few times tooling around with game ideas. The simplest solution is to set up a manual timer that uses the Scene update method to subract a number from a starting point. Ex: [scene setup code] self.timer = 100 def update(self): self.timer -= 1 if self.timer <= 0: self.timer = 100 do_something() Obviously, once this makes sense you can make a timer class and have multiple instances running for different events. Alternatively, you can mess around with threading, but I've found that this route is best for simpler tasks. Obviously, frame rate is an issue and I'm sure the more experienced folks around here will have a more elegant solution. IIRC, it might be better to subtract down self.dt's, which would then account for frame rate differences. Thx. Gonna see if I can get it to work
https://forum.omz-software.com/topic/4336/timer-method-for-scene
CC-MAIN-2020-45
refinedweb
304
80.31
So, you've got this cool new Edison, but what to do with it? Well, it DOES talk to the internet fairly well, so let's make it talk to the internet! Interestingly enough, the ethernet libraries for Arduino work just as well on the Edison, so why not use them? I am piggybacking off of a very good tutorial found here: As a result of my piggybacking, I am using (and trusting) NeoCat's app that gets the twitter token you will need to tweet with your Edison. While I am a rather trusting person (perhaps destructively so), you may want to dig around to get your token from . Unfortunately, at the time of writing this, the developer site is by invite only....so NeoCat's option was definitely the best.. I am also counting on the fact (it IS a fact, right?) that you have already gone through the Getting Started tutorials Intel has so kindly made for us. You can find them here: And, of course, FOLLOW ME ON TWITTER! @foxrobotics Step 1: Let's Add Some Sensors A randomly tweeting Edison can be fun, but let's add some sensors to it. For this instructable, I will be using the Grove Starter Kit for Edison to save myself a bit of time. I'm normally a proponent of breadboards and custom circuit boards, but hey, why not? You can easily replicate this by connecting a button yourself that has a 10k pull down resistor. Search for "Arduino button circuit" online to find it. In this example, I will be connecting the button to D8. I will also be connecting a light sensor to A0 (again, search "Arduino light sensor" for explicit circuits). Connect them as shown in the picture if you have the same Grove kit. Step 2: Let's Write Some Code! Your code it all it's glory! You'll notice that many bits and pieces are "missing" from NeoCat's code. The Linux kernel handles a lot of that for you. I did remove the wait command (if you saw his/her code) as it always hangs. I don't know if this is due to a change in the Twitter API, his/her site, or something in the Edison. (Note, if the Instructables website messes up the formatting, copy and paste everything, past it in the Arduino Edison IDE, do a search and replace for "<br>" and replace with nothing. Then go to Tools>>Auto Format. Your code will look happy again.) #include <SPI.h> #include <Ethernet.h> #include <Twitter.h> void setup(){ pinMode(8, INPUT); } void loop(){ if(digitalRead(8)){ tweetMessage(); delay(1000); } } void tweetMessage(){ Twitter twitter("your token here"); //Our message (in lolcat, of course) String stringMsg = "All ur lightz be "; stringMsg += analogRead(0); stringMsg += " out of 1023. Dey belongs to us nao."; //Convert our message to a character array char msg[140]; stringMsg.toCharArray(msg, 140); //Tweet that sucker! twitter.post(msg); } Step 3: Make Some Changes of Your Own and Tweet Like Mad! Click "Upload" (the right pointing arrow button) and you are done! Viola! My code is meant to be insanely simple so it is easy to follow. But, add your own sensors, actuators, random furry animals, and make it your own!
http://www.instructables.com/id/Tweet-with-your-Intel-Edison/
CC-MAIN-2017-22
refinedweb
545
74.29
There comes a time in every application where you want to delete something. So like every developer, you add a button, that when clicked on, deletes the resource. Wether it’s a blog post, a shopping cart item, or disabling an account, you want to protect against unwanted button clicks. Enter the Confirm Dialog. Sometimes you do want to execute an action without always prompting the user with a confirm dialog, and sometimes it can be annoying always prompting them. Hey, do you want to do this? No, really, do you really want to do this? Sometimes, I get annoyed and tell myself, and the application. Yes! Of course I want to do the action. Why else would I have clicked on it? However, when it comes to deleting sensitive data, such as a blog post, I would suggest adding a confirm dialog, so the user can be alerted and can back out if they accidentally clicked on it by mistake. Before we begin, let’s look at how to achieve this is native JavaScript. var shouldDelete = confirm('Do you really want to delete this awesome article?'); if (shouldDelete) { deleteArticle(); } This will prompt a default confirm box, and prompt the user with the text, “Do you really want to delete this awesome article?” If the user clicks Yes, then it will set the shouldDelete boolean to true and run the deleteArticle function. If they click No, or Cancel, it will close the dialog. But the native browser implementation of the confirm dialog is kind of boring, so let’s make a version, that looks good, with React and Material UI. Let’s begin by creating a reusable component. You can use this in any application that uses React and Material UI. import React from 'react'; import Button from '@material-ui/core/Button'; import Dialog from '@material-ui/core/Dialog'; import DialogActions from '@material-ui/core/DialogActions'; import DialogContent from '@material-ui/core/DialogContent'; import DialogTitle from '@material-ui/core/DialogTitle'; const ConfirmDialog = (props) => { const { title, children, open, setOpen, onConfirm } = props; return ( <Dialog open={open} onClose={() => setOpen(false)} <DialogTitle id="confirm-dialog">{title}</DialogTitle> <DialogContent>{children}</DialogContent> <DialogActions> <Button variant="contained" onClick={() => setOpen(false)} No </Button> <Button variant="contained" onClick={() => { setOpen(false); onConfirm(); }} Yes </Button> </DialogActions> </Dialog> ); }; export default ConfirmDialog; This component will take in these props: title — This is what will show as the dialog title children — This is what will show in the dialog content. This can be a string, or it can be another, more complex component. open — This is what tells the dialog to show. setOpen — This is a state function that will set the state of the dialog to show or close. onConfirm — This is a callback function when the user clicks Yes. This is just a basic confirm dialog, you can modify it to meet your needs, such as changing the Yes or No buttons. Now let’s see how we can use this component in our application. As an example, let’s say we have a table that lists blog posts. We want a function to run when we click a delete icon, that will show this confirm dialog, and when we click Yes, it will run a deletePost function. <div> <IconButton aria-label="delete" onClick={() => setConfirmOpen(true)}> <DeleteIcon /> </IconButton> <ConfirmDialog title="Delete Post?" open={confirmOpen} setOpen={setConfirmOpen} onConfirm={deletePost} > Are you sure you want to delete this post? </ConfirmDialog> </div> In this component, we need to implement the ConfirmDialog with the props open, setOpen, and onConfirm. Open and setOpen are controlled by using a React state, and onConfirm takes in a function called deletePost, which calls an API to delete this certain post. Implementing these are beyond the scope of this article. I will leave it up to to implement what those functions actually do. There you have it! Pretty easy to create a reusable confirm dialog, and it looks a million times better than the default native browser dialog.
https://plainenglish.io/blog/creating-a-confirm-dialog-in-react-and-material-ui
CC-MAIN-2022-40
refinedweb
657
54.12
Credit Card Fraud Detection using CNN Classification using CNN It is important that credit card companies are able to recognize fraudulent credit card transactions so that customers are not charged for items that they did not purchase. In this project we are going to build a model using CNN which predicts if the transaction is genuine or fraudelent. Dataset We are going to use the Credit Card Fraud Detection Dataset from kaggle. It contains anonymized credit card transactions labeled as fraudulent or genuine. You can download it from here. transactions. It contains only numerical input variables which are the result of a PCA transformation. The only features which have not been transformed with PCA are 'Time' and 'Amount'. Feature 'Time' contains the seconds elapsed between each transaction and the first transaction in the dataset. The feature 'Amount' is the transaction Amount, this feature can be used for example-dependant cost-senstive learning. Feature 'Class' is the response variable and it takes value 1 in case of fraud and 0 otherwise.. StandardScaleris used to scale the values in the data..1.0 import pandas as pd import numpy as np import matplotlib.pyplot as plt from sklearn.model_selection import train_test_split from sklearn.preprocessing import StandardScaler Now we will read the dataset using read_csv() in a pandas dataframe. data = pd.read_csv('creditcard.csv') data.head() 5 rows × 31 columns The dataset has 284807 rows and 31 columns. data.shape (284807, 31) Now we will see if any null values are present in the data. data.isnull().sum() Time 0 V1 0 V2 0 V3 0 V4 0 V5 0 V6 0 V7 0 V8 0 V9 0 V10 0 V11 0 V12 0 V13 0 V14 0 V15 0 V16 0 V17 0 V18 0 V19 0 V20 0 V21 0 V22 0 V23 0 V24 0 V25 0 V26 0 V27 0 V28 0 Amount 0 Class 0 dtype: int64 As no null values are present we can go ahead and get other information of the data from data.info(). We can see that the values are either float or int. data.info() <class 'pandas.core.frame.DataFrame'> RangeIndex: 284807 entries, 0 to 284806 Data columns (total 31 columns): Time 284807 non-null float64 V1 284807 non-null float64 V2 284807 non-null float64 V3 284807 non-null float64 V4 284807 non-null float64 V5 284807 non-null float64 V6 284807 non-null float64 V7 284807 non-null float64 V8 284807 non-null float64 V9 284807 non-null float64 V10 284807 non-null float64 V11 284807 non-null float64 V12 284807 non-null float64 V13 284807 non-null float64 V14 284807 non-null float64 V15 284807 non-null float64 V16 284807 non-null float64 V17 284807 non-null float64 V18 284807 non-null float64 V19 284807 non-null float64 V20 284807 non-null float64 V21 284807 non-null float64 V22 284807 non-null float64 V23 284807 non-null float64 V24 284807 non-null float64 V25 284807 non-null float64 V26 284807 non-null float64 V27 284807 non-null float64 V28 284807 non-null float64 Amount 284807 non-null float64 Class 284807 non-null int64 dtypes: float64(30), int64(1) memory usage: 67.4 MB value_counts() returns a Series containing counts of unique values. This data has 2 classes 0 and 1. We can see that data with label 0 is a lot higher than data with label 1. Hence this data is highly unbalanced. data['Class'].value_counts() 0 284315 1 492 Name: Class, dtype: int64 Balance Dataset Here we will create a variable non_fraud which will contain the data of all the genuine transactions i.e. the transactions with ['Class']==0. fraud will contain the data of all the fraudulent transactions i.e. the transactions with ['Class']==1. The shape attribute tells us that non_fraud has 284315 rows and 31 columns and fraud has 492 rows and 31 columns. non_fraud = data[data['Class']==0] fraud = data[data['Class']==1] non_fraud.shape, fraud.shape ((284315, 31), (492, 31)) To balance the data we will select 492 transactions randomly from non_fraud.Now you can see that non_fraud has 492 rows. non_fraud = non_fraud.sample(fraud.shape[0]) non_fraud.shape (492, 31) Now we will create the new balanced dataset by appending non_fraud to fraud. As ignore_index=True the resulting axis will be labeled 0, 1, …, n – 1. data = fraud.append(non_fraud, ignore_index=True) data.head() 5 rows × 31 columns data['Class'].value_counts() 1 492 0 492 Name: Class, dtype: int64 Now we will separate the feature space and the class. X will contain the feature space and y will contain the class label. X = data.drop('Class', axis = 1) y = data['Class']) We can see that there are 787 samples for training and 197 samples for testing. X_train.shape, X_test.shape ((787, 30), (197, 30)) Now we are going to get the bring the data into the same range. StandardScaler() standardizes the features by removing the mean and scaling to unit variance. We will fit scaler only to the training dataset but we will tranform both the training as well as the testing dataset. scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) y_train = y_train.to_numpy() y_test = y_test.to_numpy() X_train.shape (787, 30) Our data is 2 dimensional but neural networks accept 3 dimensional data. So we have to reshape() the data. X_train = X_train.reshape(X_train.shape[0], X_train.shape[1], 1) X_test = X_test.reshape(X_test.shape[0], X_test.shape[1], 1) X_train.shape, X_test.shape ((787, 30, 1), (197, 30, 1)) Build 32 filters with size of convolutional window as 2. 1 neuron because we are predicting a single value as this is a binary classification problem. Sigmoid function is used because it exists between (0 to 1) and this facilitates us to predict a binary input. epochs = 20 model = Sequential() model.add(Conv1D(32, 2, activation='relu', input_shape = X_train[0].shape)) model.add(BatchNormalization()) model.add(Dropout(0.2)) model.add(Conv1D(64, _________________________________________________________________ Now we will compile and fit the model. We are using Adam optimizer with 0.00001 learning rate. We will use 20(lr=0.0001), loss = 'binary_crossentropy', metrics=['accuracy']) history = model.fit(X_train, y_train, epochs=epochs, validation_data=(X_test, y_test), verbose=1) Train on 787 samples, validate on 197 samples Epoch 15/20 787/787 [==============================] - 0s 397us/sample - loss: 0.2179 - accuracy: 0.9365 - val_loss: 0.2355 - val_accuracy: 0.8985 Epoch 16/20 787/787 [==============================] - 0s 359us/sample - loss: 0.2070 - accuracy: 0.9276 - val_loss: 0.2271 - val_accuracy: 0.8985 Epoch 17/20 787/787 [==============================] - 0s 379us/sample - loss: 0.2030 - accuracy: 0.9314 - val_loss: 0.2206 - val_accuracy: 0.8985 Epoch 18/20 787/787 [==============================] - 0s 329us/sample - loss: 0.2192 - accuracy: 0.9276 - val_loss: 0.2189 - val_accuracy: 0.9036 Epoch 19/20 787/787 [==============================] - 0s 368us/sample - loss: 0.1896 - accuracy: 0.9352 - val_loss: 0.2180 - val_accuracy: 0.8985 Epoch 20/20 787/787 [==============================] - 0s 399us/sample - loss: 0.2067 - accuracy: 0.9199 - val_loss: 0.2183 - val_accuracy: 0.8934, epochs) We can see that the training accuracy is higher than the validation accuracy. So we can say that they model is overfitting. We can add a MaxPool layer and increase the nuber of epochs to improve our accuracy. Adding MaxPool epochs = 50 model = Sequential() model.add(Conv1D(32, 2, activation='relu', input_shape = X_train[0].shape)) model.add(BatchNormalization()) model.add(MaxPool1D(2)) model.add(Dropout(0.2)) model.add(Conv1D(64, 2, activation='relu')) model.add(BatchNormalization()) model.add(MaxPool1D(2)) model.add(Dropout(0.5)) model.add(Flatten()) model.add(Dense(64, activation='relu')) model.add(Dropout(0.5)) model.add(Dense(1, activation='sigmoid')) model.compile(optimizer=Adam(lr=0.0001), loss = 'binary_crossentropy', metrics=['accuracy']) history = model.fit(X_train, y_train, epochs=epochs, validation_data=(X_test, y_test), verbose=1) Train on 787 samples, validate on 197 samples Epoch 45/50 787/787 [==============================] - 0s 211us/sample - loss: 0.2494 - accuracy: 0.9187 - val_loss: 0.2509 - val_accuracy: 0.9137 Epoch 46/50 787/787 [==============================] - 0s 212us/sample - loss: 0.2390 - accuracy: 0.9136 - val_loss: 0.2498 - val_accuracy: 0.9137 Epoch 47/50 787/787 [==============================] - 0s 225us/sample - loss: 0.2490 - accuracy: 0.9111 - val_loss: 0.2466 - val_accuracy: 0.9137 Epoch 48/50 787/787 [==============================] - 0s 210us/sample - loss: 0.2435 - accuracy: 0.9149 - val_loss: 0.2443 - val_accuracy: 0.9137 Epoch 49/50 787/787 [==============================] - 0s 192us/sample - loss: 0.2413 - accuracy: 0.9136 - val_loss: 0.2453 - val_accuracy: 0.9137 Epoch 50/50 787/787 [==============================] - 0s 194us/sample - loss: 0.2445 - accuracy: 0.9123 - val_loss: 0.2449 - val_accuracy: 0.9137 Now we will again visualize the results. plot_learningCurve(history, epochs) We can clearly see that we have got a better result after re-training our model with a few changes.
https://kgptalkie.com/credit-card-fraud-detection-using-cnn/
CC-MAIN-2021-17
refinedweb
1,450
61.53
54394/how-to-create-a-dictionary-whose-elements-are-lists A simple way to do this is by using defaultdict. You can refer to the following code to know more. >>> from collections import defaultdict >>> d = defaultdict(list) >>> a = ['1', '2'] >>> for i in a: ... for j in range(int(i), int(i) + 2): ... d[j].append(i) ... >>> d defaultdict(<type 'list'>, {1: ['1'], 2: ['1', '2'], 3: ['2']}) >>> d.items() [(1, ['1']), (2, ['1', '2']), (3, ['2'])] David here, from the Zapier Platform team. ...READ MORE Hi, there is a very simple solution ...READ MORE The uuid module, in Python 2.5 and ...READ MORE Here's a sample script: import pandas as pd import ...READ MORE if you google it you can find. ...READ MORE Syntax : list. count(value) Code: colors = ['red', 'green', ...READ MORE can you give an example using a ...READ MORE You can simply the built-in function in ...READ MORE Suppose you have a dictionary num = ...READ MORE One thing that you can do here ...READ MORE OR
https://www.edureka.co/community/54394/how-to-create-a-dictionary-whose-elements-are-lists
CC-MAIN-2019-35
refinedweb
173
87.82
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives A much beloved and widely used example showing the elegance and simplicity of lazy functional programming represents itself as "The Sieve of Eratosthenes." This paper shows that this example is not the sieve and presents an implementation that actually is. Starting with the classic one-liner sieve (p : xs) = p : sieve [x | x <- xs, x ‘mod‘ p > 0] O'Neill proceeds to show why this standard rendition of the Sieve of Eratosthenes does not in fact "cross-off" the multiples of each prime in the same way the "real" Sieve does. sieve (p : xs) = p : sieve [x | x <- xs, x ‘mod‘ p > 0] She notes that "Some readers may feel that despite all of these concerns, the earlier algorithm is somehow “morally†the Sieve of Eratosthenes. I would argue, however, that they are confusing a mathematical abstraction drawn from the Sieve of Eratosthenes with the actual algorithm. The algorithmic details, such as how you remove all the multiples of 17, matter." A fun read. Breathtaking. If they don't accept this paper I'll personally get on a plane and hit someone on his head ;-). I also liked she asked Bird, Meertens and Peyton Jones for comments. It somehow exposes that naive 70's FP feeling (apart from being a quality paper, I really liked the performance analysis). [that might have been 80's, I am not sure] [As a side note: what I also liked is that she discusses that FP programmers prefer lists for a lot of operations, whereas a lot of algorithms are better implemented using other data structures. Personally, I always felt that 'the' data-structure for FP should not be the list, but the 'map'.] Functional programming depends heavily on persistent immutable data structures. While a persistent list is trivially implemented, a persistent map is much more complex. I daresay that's the main reason for this distinction. On the other hand, I'd rather tree-like structures, which give both good indexed access and good parallelism -- and maps can be built over trees. Very interesting. Thanks! How is this not off topic, Ehud? ;-) Not that I'm complaining about the choice of topic. I read this paper a few months ago, and it is definitely worth reading. The fact that the classic example cited by the paper is not actually the Sieve of Eratosthenes is so blindingly obvious in retrospect that it is really quite embarrassing that functional programmers have let it slide for so long. Kudos to Melissa O'Neill! Myself, I never really picked up on the purported "sieve" as particularly interesting, and never thought about it deeply. What really stood out (in my mind) from my early days of FP was fold-left, fold-right, and the corecursive definition of the Fibonacci sequence. I know I did implement the genuine sieve in Haskell years ago, but I used mutable monadic arrays. I might as well have been writing in an imperative language. I know I had seen the purported "sieve", but I don't recall why I didn't use that. Maybe it didn't come to mind, maybe I had tried it and found it too slow, or maybe I thought it was a silly implementation from the outset. I don't want to start a big meta-discussion about LtU in this particular thread, but I've been troubled by the militancy of "off topic" accusations lately. However, as this seems to me to be OT by your own standards, it seems worth pointing out. Don't get me wrong, some of the accusations were justified. I appreciate having reasonably intelligent discussions a few levels above the tripe on Slashdot, and I realize that a certain amount this behavior is probably necessary to maintain this. I personally feel the "off topic" standards should be relaxed a bit; as long as the post is of reasonable quality and likely to be of interest to a significant fraction of people also interested in programming languages in general, (such as backreferences and deterministic automata), then it should not be discouraged. ...but in my own barely on-topic foray into algorithms I was trying to ask the question of whether the language that is used to express algorithms can be truly PL or paradigm agnostic. Personally, I find the particulars of the Sieve to be of less interest than the fact that the language used to express the algorithm is intrinsically tied to the PL that implements it. The only formal expression of the algorithm given by the author is modified Haskell code that supposedly fits the informal description of the problem given in the natural language description. Which to me states both the importance and the failure of programming languages in expressing algorithms. As a side question, are the mutable monadic arrays in Haskell capable of growing dynamically? I'd conjecture that the expression of the Sieve in many non-functional languages (using fixed size arrays) are not truly expressing the fundamental algorithm which has no stated upper bounds. This was one of the advantages that has been given for the discredited Haskell solution. On the meta-level of discussion, I don't think questioning whether a particular response is off-topic is necessarily a conversation killer. In most of those posts that are borderline are implicit calls to the poster to justify why they think it should be considered as relevant to discussions of PLs. This is not to say that there is not a lot of gray area... it is to say that it is encumbent upon the person to try and shed light on the role that PLs play in the discussion of any particular item.. I'd conjecture that the expression of the Sieve in many non-functional languages (using fixed size arrays) are not truly expressing the fundamental algorithm which has no stated upper bounds. Oh, but you are absolutely wrong. The classical sieve has no inherent upper bound, but you must pick one before you start. Once you pick that bound, it can't really be increased inside the realm of Eratosthenes' algorithm. Without too much difficulty, one can extend the genuine algorithm to allow that bound to be increased, in the "obvious" and straightforward way. To restart the sieve, you take each prime p in your sieve and compute old_bound + ((-old_bound) `mod` p) and then cross out every pth number after that. Note that the ancients could not have performed this efficiently, as they lacked the long division algorithm necessary to compute the appropriate multiple of each prime. p old_bound + ((-old_bound) `mod` p) However, this method of continuation results in a significant point of departure from the original sieve, and changes the time complexity. In the worst case, where you increase the upper bound by a single number each time, this extension degenerates into trial division. Perhaps this is why the impostor "sieve" went undetected for so long. Well, there is a potential variant that would allow increasing the bound without involving long division (at the cost of increasing the storage requirements) and thus would have been possible for "the ancients". For each prime, you record the last number that you crossed off. Then, when you want to increase the upper bound, you simply go through the list and see if the next one is in range or not. Yup. The paper basically presents a slightly more clever implementation of that exact idea, using a priority queue instead of a list, and storing the next number to be crossed off for each prime, instead of the last number that was crossed off. Then one can dispense with the classical algorithm entirely, if one so chooses, or attempt a hybrid approach. Whether or not this is the "geniune" sieve is a matter of semantics, as it's definitely not the classical algorithm, but the overall effect is the same. You get the same time complexity, and not that of trial division. Notably, you relax the need for an upper bound, at the cost of increased storage requirements. :-) Oh, but you are absolutely wrong. The classical sieve has no inherent upper bound, but you must pick one before you start. Create a contiguous list of numbers from two to some highest number n. Strike out from the list all multiples of two (4, 6, 8 etc.). The list's next number that has not been struck out is a prime number. Strike out from the list all multiples of the number you identified in the previous step. Repeat steps 3 and 4 until you reach a number that is greater than the square root of n (the highest number in the list). All the remaining numbers in the list are prime. primes = sieve [2..] sieve (p : xs) = p : sieve [x | x 0] primes = sieve [2..] sieve (p : xs) = p : sieve [x | x 0]. These are exactly the kind of considerations I was trying to get at in the case of quicksort (below). I was trying to make a similar point with MergeSort on my algorithms post where I was trying to point out that CLRS and Knuth explicitly define the algorithms with state variables. A much simpler example would be Euclid's GCD. TAOCP, which for some is the bible of algorithms, lays it out as: Given two positive integers m and n, find the greatest common divisor, i.e., the largest positive integer which evenly divides both m and n. E1. [Find remainder] Divide m by n and let r be the remainder. (We will have 0 <= r < n). E2. [Is it Zero?] If r = 0 the algorithm terminates; n is the answer. E3. [Interchange.] Set m <- n, n <- r, and go back to step E1. fun gcd(m, n) = let val m = ref m val n = ref n val r = ref 0 in while ( r := !m mod !n; (* E1 *) !r <> 0 (* E2 *) ) do ( m := !n; (* E3 *) n := !r ); !n end But that looks somewhat ugly compared to the recursive solution of: fun gcd (m, 0) = m | gcd (m, n) = gcd(n, m mod n) The question would be (1) whether these are the same algorithms and how would determine that?; and (2) whether we can express the algorithm using the Knuth type of language that would describe what both implementations have in common? (1) whether these are the same algorithms and how would determine that? This paper discusses exactly this type of question. No, but only because your first implementation has a bug. :-) Namely, the first gcd(m,0) causes a divide by zero, and the second one doesn't. gcd(m,0) Upon re-reading Knuth's assumptions, he does specify positive integers, so it's not entirely fair to label it a "bug". This probably isn't a good assumption, but it does avoid discussion of gcd(0,0), which probably ought to return an error. gcd(0,0) But, modulo that quibble, I daresay yes. In fact, many compilers would take the latter implementation and produce object code that would be similar to Knuth's specification in the same sense that your original code is "similar" to Knuth's. The compiler would likely create a temporary variable (let's call it "r", pun intended) to store m mod n. As the call to gcd is a tail call, (n,r) will get passed in the same location as (m,n). The compiler shouldn't use further temporaries to set this up. At that point, the call is just a simple goto. m mod n gcd (n,r) (m,n) Ironically, your original implementation would probably result in a less direct rendering of Knuth's specification in object code. Your SML compiler might well store the references on the heap and refer to them with a pointer, especially SML/NJ as it supports call/cc. I'm not sure I understand what question (2) is trying to ask. The question would be (1) whether these are the same algorithms and how would determine that? What happens to work well in this case is to translate Knuth's original description into set of tail-calling functions E1, E2 and E3 passing m, n and r between them — we know what is the Ultimate, after all. Then it's just a matter of simplification before arriving at something very close to the "functional" solution. Now, most interesting imperative algorithms deal with mutable arrays, and a mere SSA conversion is clearly insufficient for turning Hoare's Quicksort into the clean functional version. Even using some variant of functional arrays for the CPS-conversion, one would miss the point by a mile. What's a casual observer? To somebody who doesn't know any programming whatsoever, or maybe just not any functional programming, sure, they appear to have nothing to do with each other. However, would C really be any better, other than more people have a passing familiarity with C? However, at a glance, I *do* think that the two descriptions look alike, at least to somebody with some familiarity of Haskell and a basic understanding of the sieve. Perhaps this is another reason why the fake sieve went undetected for so long. It makes me wonder what other surprises might be lurking. I interpret the paper's title as provocative, not prescriptive. Moreover, I don't think the author is trying to argue that her algorithm is the same as the classical one, merely that it's an acceptable substitute. Certainly, it is a "genuine sieve" of some variety. Since sieves can be applied to other problems, e.g. factorization, and the sieves of both Melissa O'Neill and Eratosthenes deal only with primality, it seems reasonable to call it "a Sieve of Eratosthenes", even if it isn't "the Sieve of Eratosthenes.". It seems on-topic to me, because there is widespread belief that laziness brings programming much closer to mathematics, and this paper explores this belief using a well-known example. It also explores the bias functional programmers have towards list-based algorithms, despite how other data structures are often a better fit. Most industry languages come with a broad collection libraries, and most industry programmers won't even consider a language without such collection support. You certainly made the case as to why this discussion is on topic. (not that I ever really disagreed.) But as "algorithms" are "off topic," somebody needed to say it. Further meta-discussion should be relegated to the Meta LTU Thread And, Mattias is absolutely right that most of the interesting imperative algorithms involve mutable arrays. In fact, my sieve, though not incremental, performs a significant, but not unreasonable constant-factor better than Melissa O'Neill's for this exact reason. In the process of tearing down our biases toward linked lists, she also ironically confirmed it. Now, for a bit of speculation, I've never really found a completely satisfactory approach for expressing graph algorithms in a purely functional way. The advantage of FP is relatively much greater for trees. So, maybe finding better ways of expressing array algorithms "less imperatively" and "more declaratively" could lead to better ways of expressing graph algorithms. Anybody have an opinion on GHC's Difference Arrays? I've looked at the source, and thought about trying to extend them to encompass union-find, but I've never really used them enough to know their strengths and weaknesses. [edit: Mattias EngdegÃ¥rd said that, not naasking. Still, both comments are good. :-)] to this grashopper -- sure, fp is great in some (lots) of situations, but to be really honest and respectful one has to think about and address what happens in the situations where fp has issues. I've always had a similar feeling about the standard Haskell quicksort example, and as it happens, I was just having a conversation about it the other day... This bit in particular applies: I would argue, however, that they are confusing a mathematical abstraction drawn from [quicksort] with the actual algorithm. The algorithmic details, such as how you [cleverly swap elements in-place using pointer arithmetic], matter. The Haskell quicksort has the remarkable property of making the essence of the algorithmic idea much clearer, while simultaneously destroying the essential cleverness that makes it such a good idea. So what is quicksort, really? Anyway I haven't read this paper yet, although hopefully I'll have a chance in the morning.. The worst downfall of the quicksort example is that naive use of list concatination leads to quadratic behavior. However, it _does_ make the exact same number of comparisons as the imperative counterpart. If you fix the concatination issue, you get something on par with quicksort, even though it is still not a great implementation. Ignoring laziness, I believe that the quicksort example has the same asymptotic running time, but uses appreciably more memory. (O(n * log n) instead of O(log n)) However, the situation with the "sieve" example is far worse. Superficially, it appears to be the same, but it's really just trial division in disguise, because filter p . filter q is the same as filter (\x -> q x && p x). (in terms of time, ignoring memory consumption.) filter p . filter q filter (\x -> q x && p x) And of course, the genuine sieve is appreciably better than trial division. Asymptotically, trial division tests all the numbers for divisibility by 2, 1/2 of the numbers for divisibility by 3, 1/2 * 2/3 of the numbers for divisibilty by 5, 1/2 * 2/3 * 4/5 of the numbers for divisibility by 7, etc. However, the actual sieve "tests" 1/2 of the numbers for divisibility by 2, 1/3 of the numbers for divisibility by 3, 1/5 of the numbers for divisibility by 5, 1/7 of the numbers for divisibilty by 7, etc. As Melissa O'Neill points out, the exact nature of the "test" isn't essential.. And I know people who never understood why it worked well until they saw the C solution. I very much appreciate your use of the word "morally" in the same sense as the OP. So what is the morality of quicksort? Is it really quicksort if it's quadratic? Haven't we missed the point? As for the sieve, I'll take your word for it, as I still haven't read the paper or given it much thought. So what is the morality of quicksort? Is it really quicksort if it's quadratic? Haven't we missed the point? I suppose that depends on the point one is trying to make. If your point is to actually implement quicksort, then yes, the Haskell example does miss the point. However, the example is at least useful as first approximation. The reason behind the quadratic behavior has nothing to do with sorting. In some abstract mathematical sense, it distills the essence of the algorithm. But yes, you don't fully understand quicksort until you understand the C version as well. In-place partitioning is an important aspect of a practical implementation. For the benefit of lurkers, the example we are discussing appears several places, such as A Gentle Introduction to Haskell For example, here is a concise definition of everybody's favorite sorting algorithm: quicksort [] = [] quicksort (x:xs) = quicksort [y | y <- xs, y<x ] ++ [x] ++ quicksort [y | y <- xs, y>=x] For example, here is a concise definition of everybody's favorite sorting algorithm: quicksort [] = [] quicksort (x:xs) = quicksort [y | y <- xs, y<x ] ++ [x] ++ quicksort [y | y <- xs, y>=x] Huh. I seem to remember reading commentary in my early days of Haskell saying that it isn't exactly fair to compare this to an imperative version, e.g. C, due to clever use of in-place partitioning, etc. Apparently it wasn't there. In defense of the tutorial, it does describe this as a "definition" and not an "implementation". But it's easy to see how somebody might come away with false impressions. The standard quicksort is one of the standard examples of using an accumulating parameter (for example Wadler's The concatenate vanishes): qsort' [] ys = ys qsort' (x:xs) ys = qsort' [y| y <-xs, y<= x] (x: (qsort' [y|y<-xs, y> x] ys)) I think in the end a quicksort is the quickie Haskell version and a good quick sort involves the median of 3, the avoiding small sorts and pushing the final to insertion sort.... All depends on what you are trying to explain. It's a good example of how to fix concatination; but certainly not as useful for explaining quicksort, IMO. Not quite so neat as the "fake" sieve, but I would call this genuine (some optimizations at the expense of clarity are obviously possible): sieve (_:ns) (False:ps) = sieve ns ps sieve (n:ns) (True:ps) = n : (sieve ns $ zipWith (&&) ps $ cycle $ replicate (n-1) True ++ [False]) primes = sieve [2..] $ repeat True Of course, it's still lists, and as O'Neill says, data structures matter... I'll try to come up with a nice, convincing algebraic argument later, but this algorithm has the same issues as the fake sieve, dressed up a bit differently. You avoid the "division" part of trial division; but the use of division is not what makes that algorithm slow, nor is avoiding it what makes Eratosthenes Sieve fast. It's the "trial" part that is costly. The key is that, like trial division and unlike the Sieve of Eratosthenes, you are still testing every number n for divisibility by every prime less than n. Exactly how that is achieved is not so important. The algorithm feels more genuine because I am using a "cross off every n" approach, but you are right that I'm still doing an asymptotically large number of &&s. The O'Neill paper notes: The (Eratosthenes) algorithm is efficient because each composite number, c, gets crossed off f times, where f is the number of unique factors of c less than square-root(c). The average value for f increases slowly, being less than 3 for the first 10^12 composites, and less than 4 for the first 10^34 This f is what contributes the log-log term to the time complexity of the Genuine Sieve - O(n log log n). The optimizations which sieve only odd numbers, or wheel-generated numbers can be seen as a way to reduce the value of f in common cases, although the complexity remains unchanged. But it is possible to strike off each composite number exactly once, and so remove the log-log term entirely. (And at the same time switch to a list-based implementation): primes = 2 : diff [3..] (composites primes) composites (p:ps) = cs where cs = (p*p) : merge (map (p*) (merge ps cs)) (composites ps) merge (x:xs) (y:ys) | x<y = x : merge xs (y:ys) | otherwise = y : merge (x:xs) ys diff (x:xs) (y:ys) | x==y = diff xs ys | x<y = x : diff xs (y:ys) | x>y = diff (x:xs) ys I believe the above algorithm has time complexity O(n). But can it still be regarded as the Sieve of Eratosthenes? [edited to fix bug in diff - "<" and ">" were swapped - thanks Sjoerd!] Computing each composite number by multiplying is prime factors isn't part of the genuine Sieve, but this is very close to the spirit and... is a pretty cool algorithm. It looks that at the end of the day, you will have evaluated the thunks for each of these lists, at least up to N: composites [2,3,5...] composites [3,5,7...] composites [5,7,11,...] ... So you're saying the sum of the sizes of these lists as a fraction of N converges in the limit. Is this obvious? You're not thinking lazily enough. The 'composites' function only ever depends, in any immediate sense, on the first prime in the list and the first composite in the list, both of which Nick is careful to provide. The primes themselves are computed lazily. The 'sum of the sizes of these lists' never gets involved (which is good, because each list is infinite). I'm not entirely convinced it is O(N) yet, since the time complexity of an algorithm can never be better than the space complexity of the same algorithm and I haven't examined how much space is being consumed by all the thunks (though I suspect the total space cost is less than O(N)). But the algorithm does compute each composite, and each prime, exactly once. I think I was actually being too lazy - with my choice of words. I realize each of the lists computed by composite is infinite and when I referred to their "sizes", I was referring to the size of the prefix actually computed (the portion up to the first element N or greater). Have you thought through the analysis of the algorithm? How many lazy cells get evaluated? So for example, we can obtain the following bound easily. The number of elements in the list of composites made from Kth or greater primes is less than N/K. Since the number of primes P is asymptotically N/ln N, and since the harmonic series grows like ln N, we have the number of evaluated thunks bounded at: *edit: removed incorrect computation* I think the operations of the algorithm can be put into correspondence with the thunks in those lists such that each thunk corresponds to a bounded number of operations, so this would put the runtime of this algorithm at as least as good as the Sieve, asymptotically. This produces a lower bound on complexity (multiplies plus merge/diff operations) of N*average_c(N). Now, I don't know much math-trivia, so I don't know average_c(N) with regards to N, but what I do know is that average_c(N) must be greater than the average number of prime factors for N (since the sum of exponents is greater than the count of prime factors). According to Nick, the prime factor duplication is, by itself, sufficient to result in numbers being crossed off an average of O(log log N). So I suppose this algorithm is actually 'worse' than an addition-based solution. It's at least O(N log log N) Each composite is produced by a number of multiplications, but some of those multiplications are shared. For example, 5*(2*3) and 7*(2*3) both reuse the computation of 2*3. Thus it's not enough to merely count the average number of factors - you must consider how frequently they are reused. (Also, if you can establish the Nlog log N lower bound, I think I've shown a log log N upper bound in another part of the thread. That bound is based on what feel like pretty conservative estimates, though, so I'd find it a little bit surprising if the cost were actually N log log N) Point granted. I didn't consider sharing of multiplications. Based on sharing, and examining the algorithm again, it seems every composite number involves multiplying exactly once from a prior prime or composite number. Given that every composite is also reached only once, the number of multiplies is thus less than N to produce all primes up to N. So that leaves only consideration of how many 'merges' the production of a composite number will suffer, but this also seems to exhibit the same sort of 'sharing'.. That doesn't look to contribute much, if anything, to the time complexity, but I lack the skill to further explore it. So, O(N) it could be.. Agreed, and this is equivalent to asking how many elements less than N are in those composites lists, since the Kth list consists of elements whose smallest prime factor is the Kth prime or greater. It looks like potentially hard to me, so I'm done. It'd be easy to measure and graph performance, but that probably wouldn't do much good since, as it's been said, log log N has been proven to diverge but has never been observed doing so. The complexity of O(n log log n) stated for the Sieve seems to be based on being able to perform the additions need to iterate through the multiples of each prime in constant time. But for a large prime p, it will actually take O(log p) space to represent p and O(log p) time to add p to a multiple. I suspect that if you assume this for additions, O(n log log n) isn't even right. And since multiplication isn't a linear operation like addition, this algorithm would actually make the situation worse. I was actually thinking about this earlier then thinking: but it still beats the division algorithm, and we get infinite lists in the bargain! The cost for grade-school integer multiply algorithm is O(log A * log B) where A and B are the operands. In Nick's algorithm, we can guarantee that one operand (A) is a prime number, and that at least half of all results will be multiples of 2, a third of all remaining composites results will be multiples of 3, etc. I'm not quite certain how all this adds up, but it probably is far less than O(log^2 N) for result N. The cost for a grade-school integer addition is O(log A + log B) for operands A and B, given the need to produce a new representation. You should be able to do better than that by sharing representation when adding small numbers to large numbers. I'd be interested in finding out how these differences affect the sieve. Nobody tried this code? Diff has a bug. And when you fix it, you'll see that merge and diff are actually the same function, symmetric difference, or xor: primes = 2 : xor [3..] (composites primes) composites (p:ps) = cs where cs = (p*p) : xor (map (p*) (xor ps cs)) (composites ps) xor (x:xs) (y:ys) | x==y = xor xs ys | x<y = x : xor xs (y:ys) | x>y = y : xor (x:xs) ys When merging, the x==y part is never used, and when diffing, the x>y part is never used. Very nice! lps@azarel:~/Programs/snippets $ ghc -O2 -c MaybeSieve.hs lps@azarel:~/Programs/snippets $ ghci MaybeSieve.hs GHCi, version 6.8.2: :? for help Ok, modules loaded: MaybeSieve. Prelude MaybeSieve> length (take 10000 nick's_primes) 10000 (0.40 secs, 0 bytes) Prelude MaybeSieve> length (take 10000 sjord's_primes) 10000 (0.40 secs, 0 bytes) Prelude MaybeSieve> length (take 10000 primes) 10000 (0.03 secs, 0 bytes) [edit: (41.15 secs, 2160096056 bytes) ] Prelude MaybeSieve> take 10000 nick's_primes == take 10000 primes False [edit: True] (0.01 secs, 0 bytes) Prelude MaybeSieve> take 10 (xor nick's_primes primes) [25,35,49,55,65,77,85,91,95,115] (0.01 secs, 0 bytes) Prelude MaybeSieve> take 10000 nick's_primes == take 10000 sjord's_primes True (0.03 secs, 0 bytes) Looks like you applied a correct transformation to incorrect code, Sjoerd. [edit: that would be a correct transformation to correct code] As for being fast, it's not. [edit: fast is relative. It's not great, but it's not too unreasonable.] primes is the impostor sieve that we've been discussing, and it's over 10x slower than that. [edit: I got that sieve wrong. It's over 10x slower than nick's/sjord's] As for being linear, I'm pretty sure it's not. [edit: this is one of the few correct statements I made here] In fact, it appears to be asymptotically worse than the impostor. [edit: nope. turn that statement around] If we restart ghci: primes Prelude MaybeSieve> length (take 50000 nick's_primes) 50000 (7.55 secs, 166816348 bytes) Prelude MaybeSieve> length (take 50000 primes) 50000 (0.11 secs, 0 bytes) Prelude MaybeSieve> nick's_primes !! 10000 104743 (0.01 secs, 0 bytes) Prelude MaybeSieve> nick's_primes !! 50000 611957 (0.01 secs, 0 bytes) That's 19x more time to solve a problem instance 6x as big. I hate being a curmudgeon, but I also hate not being rigorous. [edit: both true] :-) Can you recheck your definitions file and then post the code if you don't find a problem? I copy and pasted the code for sieve in the original post with Sjoerd's code, changing only two quotes to backquotes, and the two produce equivalent lists of primes with Sjoerd's being much faster. I thought that was kind of fast for the fake sieve, but I subconciously assumed it was too simple to mess up. (haha, right.) I forgot to recurse, so it only filters out the factors of 3 out of the odd numbers. But the fact remains, there is no way this is linear. It's very similar to Richard Bird's code at the end of the paper, but it does improve on it, so not bad! I suspect it's asymptotically the same as Bird's, which Melissa O'Neill does discuss as being suboptimal. So, Nick/Sjord's code: (performs identically) ghci> let test f n = length (takeWhile (< n) (f ())) ghci> test nick's_primes 100000 9592 (0.42 secs, 0 bytes) ghci> test nick's_primes 200000 17984 (0.88 secs, 0 bytes) ghci> test nick's_primes 400000 33860 (3.85 secs, 105371172 bytes) ghci> test nick's_primes 800000 63951 (11.37 secs, 239707676 bytes) Richard Bird's code from the end of the paper: ghci> test bird's_primes 100000 9592 (1.03 secs, 50939444 bytes) ghci> test bird's_primes 200000 17984 (2.33 secs, 122054156 bytes) ghci> test bird's_primes 400000 33860 (5.47 secs, 304108996 bytes) ghci> test bird's_primes 800000 63951 (13.11 secs, 785552660 bytes) And, just for fun, my own sieve that I use from time to time. The expression sieve n finds the smallest prime factor of every number less than n, so it's a bit more general than Eratosthenes. It's not incremental in any way, shape, or form, but there are ways to extend the algorithm. sieve n n ghci> factor (sieve 100000) 3 [(3,1)] (0.03 secs, 0 bytes) ghci> factor (sieve 1000000) 3 [(3,1)] (0.15 secs, 2002168 bytes) ghci> factor (sieve 10000000) 3 [(3,1)] (1.65 secs, 11002884 bytes) ghci> factor (sieve 100000000) 360 [(2,3),(3,2),(5,1)] (19.57 secs, 101004300 bytes) I suspect that a lot of the difference you're seeing is due to heap-reallocation and associated garbage collection. The prior tests are affecting the latter tests by consuming heap and leaving garbage upon it that is only collected when running the latter tests. I suspect that a lot of the difference you're seeing is due to heap-reallocation and associated garbage collection. That's certainly part of it, but that's also an intrinsic part of the respective algorithms. Nick's code appears to allocate about 1/3 of the memory of Bird's code, but probably has basically the same runtime overall. That's probably why it does comparatively well in the beginning, but quickly catches up. Even so, reducing memory consumption is a good thing, even if you don't save much time. My sieve doesn't create any garbage. The only heap allocation is a single unboxed ST array. Then after it's done filling it, it uses runSTUArray to convert that to an immutable array without copying. Two simple tricks are used to reduce the size of the array by 75%. runSTUArray But even disregarding the garbage avoidance and the significant constant-factor advantages of arrays, the algorithm my code uses has the same asymptotic complexity as Eratosthenes' sieve. Bird's code only does a little bit better than trial division. The prior tests are affecting the latter tests by consuming heap and leaving garbage upon it that is only collected when running the latter tests. Doubt it. In fact, the first expression run during a session will often take a bit longer, as GHCi might need to load a package. Unlike Hugs, GHC's garbage collection is fast, and GHCi does not offer :gc to force a collection. Since humans type slow, there is almost always at least a partial GC done between expressions. I haven't exactly figured out bytes reported by ghci mean, but I believe it's the amount of garbage collected while the algorithm was running. (There may be a race condition in there to confuse things a bit.) :gc Besides, on the latter examples, there was far more memory collected than the standard 64M heap that I was working on. The collector ran multiple times, and the times were pretty consistent. I was going to scoff that you couldn't distinguish ln ln N from a constant, but I was getting similar numbers to yours (measured in operation count rather than just runtime), so I revisited the proof of my bound above and realized it has a big hole (my turn for oops!). It actually looks likely to me that one could work out the exact asymptotic runtime, but I suppose the lesson I should take away from this is that math should be done carefully or not at all. I suspect you're right that it's not linear or even N ln ln N. should really build a library on top of Haskell, like HUnit, which will experimentally supply a good estimate on the complexity of a given algorithm. It's a wonderful idea You should contact the author Melissa. The complexity of this function is O(n) times the average value of pi(lpf(n)) restricted to the composite numbers, since lpf(n) determines how many different (composites (p:...)) lists n occurs in. Here lpf(n) is the least prime factor of n. Unfortunately I don't know how to estimate that analytically. A numeric estimate out to 20000000 makes me think it's between O(n log^2 n) and O(n log^3 n). Here's a few more details:. the total cost due to k is roughly Ï€(lpf(k)) where lpf(k) is the least prime factor of k. Why? Is it an estimate of the length [of the composite list where k was generated]? If so, I think you might not take sharing into account in your summation. [My, very simple, rough estimate was something like O(Ï€(n) + 2 * (n - Ï€(n))) is O(2n - Ï€(n)).] [Just counting the number of unique multiplications] [I guess 2 should be a constant C] Rationale: The list of prime numbers up to n is the list of numbers (O(n), trivially) minus the list of composites. The composite list of multiples is generated recursively from the list of primes. That composite list is the merger of three strictly increasing lists where the head of the list is known. Thus?, to determine the n-th composite O(n) comparisons are needed, or, it takes constant time to determine the next composite [if the list of primes would be known]. Let c0 be the constant to generate the next natural number. Let c1 be the constant to generate the next composite. [c1 > c0] Then it takes approximately c0*Ï€(n) time to generate all primes, and c1*(n-Ï€(n)) time to generate all composites below n. Thus c0*Ï€(n) + c1*(n-Ï€(n)) or approximately c0*n/ln(n) + c1*n - c1*n/ln(n) = c1*n + (c0-c1)*n/ln(n) time to generate all primes below n. Thus O(n). [Uh, edited the last formula substantially.] [Hmpf, I am not taking into account that Ï€(n) lists should be merged; but it might be that it doesn't matter.] [?It's O(n), trivially, since if n grows, the average distance between prime numbers grows, therefore the complexity 'grows' to the complexity of generating natural numbers.]. Except you need to account for how long it takes to compute the three lists - one of those is a recursive call. have to admit, I didn't read all the analysis. Except you need to account for how long it takes to compute the three lists - one of those is a recursive call., [and every composite number is generated uniquely?], the above argument might hold. But I do admit that I don't trust the argument fully myself. tried to find an intuition why it might be O(n). Since a new list of composites is generated for each prime, and the density of primes goes to zero asymptotically, I though that that might explain that you end op with O(n). But, again, I have to admit I don't trust the argument myself. There was a question mark ;o). Hm, this actually might be very wrong reasoning ;-). In the end it all boils down to: does it take constant time to generate the next composite number. Which might not be true since you end up merging pi(squareroot(n)) lists. [Nah, too much BS. Will read up on that Bird analysis again and come back...], the above argument might hold. But I do admit that I don't trust the argument fully myself. The algorithm doesn't just generate a list of primes and a list of composites. If you look at it, 'composites' is a function that generates a list of composites using only a given list of prime factors, and it is invoked by the algorithm for every tail of the list of primes. That is, the algorithm (eventually, if a large enough N is demanded) invokes composites [2, 3, 5, 7, ...], composites [3,5,7, 11, ...], etc. For every natural K, there is some composite that appears in at least K merged lists. Thus, it certainly does not take constant time to generate the next composite number. But this does not settle whether or not the whole thing is O(n) - the equivalent question is whether it takes some fixed constant time on average. But... I don't fully follow your line of reasoning. If I evaluate the length of a given list [1..10] it will invoke length [1..10], length [2..10], etc. But that still means it is O(n) right? *scratch* You are right. Uh, maybe. I misread your statement. I didn't understand that primes is invoked twice in every invocation of composites. [Forget it, again, will read up on the Bird analysis, then come back.] I reread the analysis by Geoffrey. I think he is right. And by now I am certain it cannot be O(n) since an increasing number of lists is merged. However, there is an image of evaluated comparisons here. ************************************************************** The haskell program ************************************************************** module Main where import System.IO as IO import System import Debug.Trace primes = 2 : xor [3..] (composites primes) composites (p:ps) = cs where cs = (p*p) : xor (map (p*) (xor ps cs)) (composites ps) xor (x:xs) (y:ys) | x==y = trace "=" ( xor xs ys ) | x<y = trace "<" ( x : xor xs (y:ys) ) | x>y = trace ">" ( y : xor (x:xs) ys ) l n = length (take n primes) main = do args <- getArgs if length (args) == 0 then do print "usage: primes n" else let n = read (args !! 0)::Int in do print ("arg+1 = " ++ show (l n)) ************************************************************** The bash program, you can cat it to 'out.txt' for example: ************************************************************** #!/bin/bash for (( I = 3 ; I < 1000000000 ; I = (I * 3) / 2 )); do J=`a.out $I | wc -l`; echo $I $J; done ************************************************************** To build the picture: ************************************************************** graph --output-format "gif" out.txt > comparisons2.gif ************************************************************** [ Fixed some <s] [And even more] And by now I am certain it cannot be O(n) since an increasing number of lists is merged. Actually, an unbounded number of lists being merged doesn't imply that it's not O(n). Here's a counter-example: evens = multiplesof 2 multiplesof k = k : merge [k*n | n <- [2..]] (multiplesof 2*k) So we're still out in the open on this one? My computer lacks processing power to really evaluate a large number of terms. From the experiments it seems it can go both ways. [Is that really O(n)?] [Again, I give up for now. Need to read up on this stuff.] Is that really O(n)? Yes. There are N/2 evens, N/4 multiples of 4, N/8 multiples of 8, etc. If you add up these terms up to the first power of 2 greater than N, you get something less than N (and if you round up when you divide that only gets you log_2(N) more). Note: This is just because 1/2 + 1/4 + 1/8 + ... is a geometric series that converges to 1. The length argument I got, but I wasn't sure you could discard the cost of merging the log(N) lists. At the moment, I am slightly more than a bit baffled by the other problem. [Reread the other posts. I am replaying the arguments. So I'll look at the cost of merging.] My previous complexity guess was wrong (though in fairness it was only a numerical guess). Here's an analytic analysis resulting in O(n^1.5 / log^3 n): In case others are still confused about the sharing analysis: it's impossible to share the cons cells from different calls to (composites (p::...)), because they belong to _different infinite lists_. If they were shared, it would imply that if you go out far enough, the set of numbers that can be constructed from all primes > p is the same as the set of numbers that can be constructed from all primes > q. If p != q, this is false. Apologies if someone else already made this argument. Nice job I'd like to point out another implementation of the Sieve of Eratosthenes: in the true spirit of the original algorithm, the implementation uses neither division nor multiplication operations. In fact, the algorithm doesn't even use general addition or subtractions, relying only on successor, predecessor, and zero comparison. The algorithm easily generalizes to other number sieves (e.g., computing lucky numbers). Thank you for calling this to my attention. At some point, I definitely want to take a careful look at this. Off the cuff, I'm guessing it has rather high constant-factor performance issues, but that's not why this appears to be very interesting to me. [I'm very much reminded of the wisecrack in The Evolution of a Haskell Programmer that "graduate education tends to liberate one from petty concerns about, e.g., the efficiency of hardware-based integers"] Ok, I took a good look at it. Your primality sieve suffers from the same problem as Tim Band's comment above. You say that you don't do any operations on the composite numbers, but you do: you traverse them repeatedly. However, you are right to point out that certain aspects of either the Sieve of O'Neill or the Sieve of Eratosthenes don't generalize in a nice way. I'll have to think about how to implement a lucky number sieve well. Wikipedia says that the progenitors of the lucky numbers suggested calling it the Sieve of Josephus Flavius, which recalls Chris Rathman's post here. Some interesting stuff to think about! I thought his post was a little bizarre too when I first encountered it in the context of this thread (avoiding addition through repeated increment isn't much of an optimization), but I don't think he was tossing this out as an exemplar of a speed. I think the motivating factors here are simplicity in a from-first-principles sense and generality. Take the last sentence of his description from the link: Thus the algorithm can be used with Church and Peano numerals, or members of Elliptic rings, where zero comparison and successor take constant time but other arithmetic operations are more involved. I don't entirely disagree. However I think Oleg is wrong on this count. My off-the-cuff guess was wrong, which I have to admit was based on Oleg's history of being correct rather than the content of that particular comment. The alleged Sieve of Oleg is in the same asymptotic ballpark as the impostor sieve of David Turner, as well as Tim Band's sieve, none of which come close to reasonably-implemented trial division, let alone a geniune sieve. I have looked at elliptic rings, however briefly. Lucky numbers are new to me, and I'm not aware of the best known algorithms in this area. The complicating factor with the lucky number sieve compared to the Sieve of Eratosthenes is that you have to know the locations of the existing lucky candidates to cross off your target. The "obvious" solution is mighty similar to Oleg's. However... maybe it's not too hard to modify the Sieve of O'Neill to handle the lucky numbers? However I think Oleg is wrong on this count. On what count? I agree Oleg's algorithm has more than constant factor issues, but I don't see where Oleg claimed that it didn't. Did David Turner ever come out and explicitly state that his classic example was within a constant factor of the genuine Sieve of Eratosthenes? I'm not aware that he did. Oleg might not have intended to imply such a statement, but without it, the surrounding context feels especially bizarre. The subject starts with the phrase "Even better Eratosthenes sieve", and explicitly mentions Melissa O'Neill's paper, but by the criteria of that paper, proceeds to commit the same fallacies. Admittedly, the only concrete, definitive thing I can say that Oleg got wrong was his point (i), that his code performs no operations on the composite numbers. But that seems to support my overall thesis. It's an interesting, if flawed, article. I don't think Oleg's implementation of the lucky number sieve is particularly profound, but on that count, his overall thought process is correct. I am definitely still grateful that he brought the subject to my attention. I think the productive path for this conversation to take is to focus on the lucky number sieve and how it might be implemented. No, it's a sieve nevertheless, with a little bug easy enough to fix. :) The problem is that the naive code sieves prematurely. The sieve on each prime that is found should be delayed until its square is seen. Not just its work has to start after that square, but the sieve itself must be started there. That is the key point missing from the article. The fixed code is plenty fast and clear enough for an introductory code: primes = 2 : primes' primes' = 3 : sieve primes' (map (^2) primes') [5,7..] sieve (p:ps) (q:qs) xs = let (h,t) = span (< q) xs in h ++ (sieve ps qs . filter ((/=0).(`rem`p)) . tail) t Before you point out the `rem` issue, on today's CPUs it's very fast and local, so it's a non-issue, at least while we're inside the Int32 range. The exact nature of check whether to scratch the number out or not - be it done by counting from the previous composite, comparing it to the PriorityQueue's head or by checking the remainder - is immaterial as long as it is O(1). The use of 'filter' has its benefits in that it culls its input sequence so that each sieve leaves less work to be done by all its successor sieves. The real issue - that which the article does improve upon - is that implicitly at run-time all the sieves form a linear, nested structure, and each is consulted for each prime number produced. I think, the article's point is realizing this linearity and explicating this control structure (as e.g. a list passed as a function argument - the article skips this step), as if turning the nested list of filters, each with its predicate, into one filter by a list of those predicates - and then transforming this explicit list control structure into a priority queue, so that only a small near constant amount of top entries is consulted for each prime to be produced. It is as if a person who scratches the numbers by hand were to keep the list of all active sieves as a table on the side, and for each incoming number consult each of its entries to see whether to scratch the number or not., but much less suitable as a piece of introductory code. As for the O(n) issue, I'm confused: is it supposed to be 'n' as in n-th prime, or N as in its value? I think it's the former in O(n log log n) of the PQ algorithm. As for Nick's code, it produces all the composites and primes before any given prime, so is at least O(N), which is guaranteed to be worse than O(n*log n). Is it not? I realize long time has passed since this discussion ended, but maybe someone is watching... What you've implemented is trial division, but not a grossly naive trial division like the classic example. Fast is relative; it's true that remainder is pretty fast on modern processors, but it's still quite a bit slower than addition or multiplication. But this is all quite irrelevant, because the trial part of trial division is what is slow, exactly how the trials are performed is not so important. You are definitely thinking along the correct lines with regard to the algorithms being discussed, but you also seem to be missing some of the subtleties. For example: The use of 'filter' has its benefits in that it culls its input sequence so that each sieve leaves less work to be done by all its successor sieves. If this were truly important, then starting each filter earlier would be a benefit, would it not? But as you correctly realize,. The Sieve of O'Neill completely eliminates the copying introduced by the use of filter., [...] You don't seem to fully appreciate Melissa O'Neill's contribution on this count. It's much more than "searching", she examines those numbers that are prime divisors of a given candidate, and only those numbers. [...] but much less suitable as a piece of introductory code. You might be right. I do think that the original unfaithful sieve and the (imperative!) Sieve of Eratosthenes are excellent introductory material. Honestly the imperative algorithm is a bit easier to grasp than the Sieve of O'Neill, and I think it's a good motivating example for imperative programming. In my honest opinion, your code is quite elegant, though a little unpolished. I approve of the use of circular programming introduced by primes'. In fact, I've used a similar trick to implement a Lucky Number Sieve here. The definition, on the other hand, could be cleaned up in a few ways. You would probably eek out a bit more performance in the process. primes' As for the complexity of Nick Chapman's code, most of the discussion above is bogus. I recommend reading Geoffrey Irving's blog posts, as I do believe his analysis is correct. As for the complexity of Nick Chapman's code, most of the discussion above is bogus. I recommend reading Geoffrey Irving's blog post, as I do believe his analysis is correct. The most enlightening aspect of this discussion is that analysis of the performance of lazy algorithms can be very hard. This is what keeps me an imperative language programmer. Strictness is not exclusive to imperative programming. Where are the strict non-imperative languages? I'm sure that some of these languages exist, but are they industrial strength, and widey used or supported? (I consider Lisp and SML and CAML imperative -- these are languages that I do use.) (I consider Lisp and SML and CAML imperative -- these are languages that I do use.) How are SML and OCaml imperative languages? They are strict functional languages, with some extensions which permit imperative programming, but by no means encourage it. If I was coding Sieve of Eratosthenes in SML or CAML, I would use mutable arrays any the code would look very much like any imperative language implementation. I would use mutable arrays any the code would look very much like any imperative language implementation. For an efficient implementation, perhaps it would, but so what? You implied strict languages and imperative languages are synonymous, but they are not. That's all I was pointing out when I replied to you, so I will now take your statement to mean, "This is what keeps me a strict language programmer," which makes much more sense. To quote Alan Perlis: "A Lisp programmer knows the value of everything, and the cost of nothing" ;-) I'm not yet convinced that algorithmic analysis is *that* hard in functional programming, it's more that FP allows your mind to gloss over the details of how something is computed, which means it's much easier to think you are doing it one way when in fact you are doing it completely differently. Certainly we could use some more insight into reasoning about the "how", but this is somewhat complicated by the fact that FP implementations have much more freedom in how things are ultimately executed than a C compiler does. One of my best friends is an avid R programmer. Recently he solved the first few Euler problems, and in the process he independently re-invented the unfaithful sieve, except in a strict setting. When he complained how badly his "sieve" was performing, I explained why, and told him that even though R implements imperative programming poorly (which has the interesting sociological benefit of encouraging people to learn how to program functionally), this really was a case where he wanted to use it. I predict that the unfaithful sieve is going to be one of those ideas that gets re-invented many, many times over the future history of computation. :-) Any sequential sieve is trial division, and a manual sieve is naturally sequential. When a person sets out to scratch out all the multiples of primes from a table of numbers, he must count them all - even when falling on an already scratched out number he still stops at it, and continues counting from there (or else his counting will get out of sync). The only real difference is the abortiveness of the Priority Queue version. It's just so structured as to shortcut the testing, i.e. guaranteeing the validity of all with only a few checks performed (by having all the next composites present in the queue so that the first hole is guaranteed to be prime). In fact I doubt it can be considered a sieve in a traditional sense, because it replaces counting on an increasing numbers sequence with maintaining, in a sophisticated way, the table of next composite values and comparing those with each new number's value. The original sieve was even oblivious to the numbers' values. It could have empty boxes in place of them, and still work. The person would go on scratching each third number starting from 3, and each fifth number starting from 5 on the same table, naturally thus repeating the tests for all primes found so far. So I don't think actually O'Neill's code is a sieve in that sense. A normal person 2300 years ago wouldn't work that way, but instead in a sequential manner. And any sequential sieve is a trial division, reorganized. That was not the central critique point at the start of the article about the naive implementation, but rather its horrendously over-working, starting each sieve horribly early, eons in advance, and thus making it very slow. My code addresses that issue, in a simple and clear manner, making apparent the delaying of work to be started just at the right moment. It is short and simple enough to be used as an introductory example of "the functional code" - to replace the very wrong naive version. I expected to see something similar in the article, before it goes on to the more sophisticated optimizations. This would also make performance comparisons more sensible. BTW I was quite certain someone wrote something like it already when I tinkered with it some 6 or 7 years ago. I didn't even bother to check. And it is on par with many other versions in efficiency, when actually tested. Here's some data: 1000s: 8 16 32 64 128 256 512 1024 delayed 0.07 0.25 0.76 1.95 5.40 14.98 43.07 123.24 Bird's 0.08 0.25 0.53 1.36 3.42 9.19 23.32 66.93 PQ 0.10 0.22 0.53 1.28 2.95 6.40 14.84 35.84 Nick's_3 0.08 0.24 0.67 1.58 5.24 11.77 40.51 ---- 2.24G 2.5G swap, 8% CPU Here Nick's_3 is Nick's code improved to work on odds only (making it 4/3 faster): primes = 2 : primes' where primes' = 3 : diff [5,7..] (composites primes') composites (p:ps) = cs where cs = (p*p) : merge (map (p*) (merge ps cs)) (composites ps) and the rest of it the same. (somehow it takes up much more memory than the others, and so eventually stops working). BTW I don't know how to make my code better. It took me quite some time to get at its current version, and it is only "easy and apparent" in retrospect to me. :) I tried counting (as in "true" sieve) and marking the scratched-out numbers as zeroes, but it was slower than the filter version - because I had to count on the non-culled sequence, and thus many numbers were marked as 0s multiple times. In the filtered version any composite that's struck out isn't checked for anymore by all the other filters - that gives it some boost. All the primes do go through all the filters, of course, and that's what the PQ version improves upon so drastically (in asymptotic sense). I tried to turn it into explicit filtering, as I mentioned in the first post above. It was slower. I tried to count with an ever growing gob of explicit counters (in a list, sadly!). It was slower still. PQ version beats all that, after a certain point. :) The use of 'filter' has its benefits in that it culls its input sequence so that each sieve leaves less work to be done by all its successor sieves. If this were truly important, then starting each filter earlier would be a benefit, would it not? The use of 'filter' has its benefits in that it culls its input sequence so that each sieve leaves less work to be done by all its successor sieves. If this were truly important, then starting each filter earlier would be a benefit, would it not? No, it would be much worse, because each filter filters out composites first and foremost. So each composite is dismissed only once from the input sequence, unlike the counting versions which must count on non-culled input sequence and so many composites get marked multiple times (for each of their prime factors), and starting a filter prematurely means that it will work hard for nothing - much earlier than it is its turn to contribute to the composites elimination.. Yes, for example, to get at the prime 7927, which has 1000 primes before it, we only need 25 sieves, not a 1000 that the unfaithful version starts. It is specifically unfaithful to the original algorithm in its disregard for the square root and in starting all the sieves immediately - which issues my code addresses fully, of course. I'm not sure there must be any "copying" going on though, evaluation is triggered by access and filter just gets to the original storage eventually. The real problem is that all this filters are organized linearly, implicitly, since they are created by the nested recursive calls. They (can) all sit on the same input storage though. They are all working hard, too, so we better keep their number to a minimum.. That is exactly what I said, only not in the same words. I don't think I was referring to any "searching". The key is the abandonment of the sieve-like counting, and summing up the values instead, maintaining those values in the PQ and thus utilizing the natural order of things to only examine the top entries of the PQ, which correspond to the prime factors of the incoming number -- and only those prime factors. The rest being (at the moment) kept deeper inside the Queue, each with its next composite that it produces as its key. Sorry for being so verbose. If it is a faux-pas here please tell me so that I won't do that again. :) I realize this is all pretty trivial stuff, but very much appreciate the possibility to discuss it still. For testing I ran ghc -c -O3 primes.hs and then loaded it into GHCi. Well, the obvious improvement I see with your code would be to eliminate the use of qs, which only increases memory allocation. However this should be short-lived memory, and so it might not substantially impact performance. qs Any sequential sieve is trial division [...] Definitely not. There is no trial in the Sieve of Eratosthenes. When you visit a number, you are definitely removing it. Although many numbers will get "removed" multiple times, once for each of its prime divisors less than the square root of the number, we will see this is not terribly important. For comparison, with the unfaithful sieve, you visit numbers that are not crossed off, and decide to leave them alone. You might use division in segmented sieves, because if p is less than the size of your segment, then you know that the resulting number gets crossed off. It might make sense to keep primes larger than your segment size in a priority queue. In fact I doubt it can be considered a sieve in a traditional sense [...] I would definitely call it a sieve. See my comment above [...] So each composite is dismissed only once from the input sequence [...] This is not important. The number of distinct prime divisors of a number grows much more slowly than the inverse of the factorial function, which itself is sub-logarithmic. By contrast, the number of trial divisions needed to establish primality is O((n / log n)^(1/2)) worst-case, which occurs when investigating prime numbers and their squares. Even on composites, the expected number of trial divisions grows much faster than the number of distinct prime divisors. I'm not sure there must be any "copying" going on though, evaluation is triggered by access and filter just gets to the original storage eventually. [...] Under a lazy regime, evaluation of a filter triggers copying. Read chapters one and two of Chris Okasaki's Purely Functional Data Structures. His thesis of the same name is available online, but the thesis does not contain those chapters. You might be able to find an interesting combination of lazy and call-by-name evaluation that would eliminate much of this copying, but that shouldn't improve the asymptotic performance of this example. You are still paying a heavy price for the mere act of traversal. If you are interested in exploring this idea, I suggest writing proof-of-concept implementations in Scheme, or possibly ML or Factor. Those choices should work well for exploring combinations of both lazy evaluation and call-by-name. And it is on par with many other versions in efficiency [...] On my computer, Melissa's code takes 0.2 seconds to find all the primes up to 1,024,000, and your code takes 0.6 seconds. To find all the primes up to 102,400,000, Melissa's code takes 10 seconds, and your code takes 500 seconds. On this larger problem, Melissa's code had a maximum of 54 megabytes allocated at any one time, while your code used a total of 710 megabytes. For comparison, running time on the shell script primes 2 102400000 | wc takes 3.5 seconds, where primes is the venerable prime sieve distributed with BSD. I'm sure the bottleneck is converting from binary to decimal and doing input/output. Running factor (sieve 102400000) 360 with my code finishes in 1.6 seconds. This is not exactly an apples-to-apples comparison, because creating a list of primes from my sieve is only slightly faster than Melissa O'Neill's code. time primes 2 102400000 | wc factor (sieve 102400000) 360 This demonstrates that as computers get faster, algorithmic efficiency becomes more important, not less. I'm not saying my code's in any way better then the PQ version, I should've been insane to claim that. :) You shouldn't compare my code with Melissa's; it's not the intention of it. Instead, compare it with trial division, or Richard Bird's code, or Nick's. Don't try it for very big numbers of primes either. It's obviously only good for a first quarter of a million of primes or so. But it's not only good for 19 of them either, that's for sure. I'm merely saying it's a step between the terrible unfaithful sieve, and the optimized sophisticated one, a code which is also illuminating in some ways, suggesting the improvement of explication of list control structure as a list data structure, which is then turned into PQ data structure. An introductory device, if you will. But if we were to look for the candidate for "that functional look-and-feel", simple, yet not-terribly-inefficient code, it'd be as good a candidate as any. It helped me to understand what's going on, as far as I do. Under a lazy regime, evaluation of a filter triggers copying. OK, my bad. It can only vanish if the produced value stream isn't reused, and it is reused in my code. Bummer. :) But no, actually, only the resulting re-usable ONE sequence needs be allocated, each filter here doesn't reuse anything. All it needs to do is to get candidates from its producer and turn its final value out to its caller. A filter only remembers its next_candidate and that can just be a pointer into the original storage, always - because it itself passes out the pointer to original storage too. So each nested filter should remember the next_value inside its frame, which would be actually a pointer into the original storage, all of them, and let the caller worry about the produced stream's re-use and copying. There is no trial in the Sieve of Eratosthenes. When you visit a number, you are definitely removing it. Although many numbers will get "removed" multiple times, I find it hard to see it that way. When you set out to eliminate all the composites up to a certain upper limit (say for the first 1000 natural numbers) you proceed to count and eliminate all the multiples for each prime less than 32 - and each time you count over the whole table from 0 to 1000 (well, not from 0 but from the square of each of the first primes). It means that for each number from 0 to 1000 you have in effect tested its divisibility by _all_ the primes less than 32. ALL of them. That is the definition of trial division algorithm. Trial and delayed-filter are indeed asymptotically the same, because of the reasoning you provide, but the delayed-filter is by a constant factor better because (I think) of my reasoning - eliminating some work for composites which trial division performs always. At least that's what my empiric data shows, I think. E.g. the number 925 will get eliminated by a very early prime sieve of '5' and thus won't even be considered by the rest 7 of them, but in the counting sieve we definitely will go over the number 925 several times, once for each of 2,3,5,7,11,13,17,19,23, and 29. Whether we scratch it out or not is immaterial. We went through it, so we have tested for its divisibility by all of them. So it is better than trial, but in a less important area, non-influential over its asymptotic behavior. IOW it only has advantage at first. But that's alright, because its only real value is educational, as introductory code. It's not that terrible as the original one, is all, and is on par with the rest of unsophisticated ones. :) BTW in my tables I refer to the number of primes produced, not their top value. In fact I doubt it can be considered a sieve in a traditional sense [...] I would definitely call it a sieve. See my comment above In fact I doubt it can be considered a sieve in a traditional sense [...] I would definitely call it a sieve. See my comment above You say there. so you seem to contradict your own statement. The genuine sieve does go over the whole table, counting and crossing each p-s number, as if "in rows", but Melissa O'Neill's code achieves its breakthrough in abandoning this counting and instead computing and comparing the values of numbers to be scratched. Thus it is not a sieve at all. It is better. (it could've maintained "phase" counters but then would have to update each one's value on each step forward, thus going back to using pred/succ from its use of sum). BTW I think O'Neill herself inserts primes into the PQ immediately as they are encountered, unfaithfully to the "genuine sieve". :) She relies then on the PQ's mechanics to keep them away until needed, but it still makes the Queue blow up hard in size, prematurely. In my half-baked primitive PQ implementation as a binary tree with ad-hoc insertion and without even a pop-and-reinsert, it does pay to insert them as late as possible: qprimes = 2 : primes' where primes' = 3 : sieve primes' (map (^2) primes') emptyIts [5,7..] sieve ps@(p:pt) qs@(q:qt) its (x:xt) -- ASSUMES all qs are PRESENT in the feed stream | x == q = let its' = addIt its (2*p,q+2*p) -- add (val,key) in sieve pt qt its' xt | True = case updIts its x of Just its' -> sieve ps qs its' xt -- match on Q found: a composite _ -> x : sieve ps qs its xt -- x is a prime This also makes clear the existence of two kinds of queue insertions: one, the rarer, distant insertion of a new entry - when the square-of-prime is reached; and the more frequent, local one, involving mostly the top of the queue, when it is consulted to see if there's a match, so that we know this specific composite is reached in the input stream, and so its entries for each of its prime factors are popped off from the head of the queue, and are reinserted with their next-to-produce composites as keys (the step value - here, twice the original prime - is stored as a value in PQ's entry). If no match was found, the queue stays unchanged and we know we've encountered our next prime. And for that, of course, we only had to consult the very top of the queue. To make our testing data a bit more representative, here it is again with added data for the unfaithful sieve and trial division version, exactly as it is in the article, only with a standard "on-odds" improvement: 1000s: 1 2 4 8 16 32 64 128 256 512 1024 unfaithful 0.05 0.21 0.99 6.66 46.71 trial_3 0.02 0.06 0.16 0.43 1.16 3.04 8.23 22.00 60.19 delayed-filter 0.02 0.07 0.25 0.76 1.95 5.40 14.98 43.07 123.24 Bird's_3 0.03 0.07 0.25 0.53 1.36 3.42 9.19 23.32 66.93 PQ 0.04 0.10 0.22 0.53 1.28 2.95 6.40 14.84 35.84 Nick's_3 0.03 0.07 0.23 0.65 1.57 5.11 11.56 40.51 ---- Each data point should be taken with an error margin of about 10%. We can glean at asymptotic performance locally by checking the empirical time sequences on doubling problem sizes with the function tm_check tms = map ((/log 2).log) $ zipWith (/) (tail tms) tms which lets us see the exponent of the power function locally approximating our data: tm_check tms = map ((/log 2).log) $ zipWith (/) (tail tms) tms 1000s: 1 2 4 8 16 32 64 128 256 512 1024 unfaithful 2.07 2.23 2.75 2.81 trial_3 1.58 1.41 1.42 1.43 1.38 1.43 1.41 1.45 -- same delayed-filter 1.80 1.83 1.60 1.35 1.46 1.47 1.52 1.51 -- same Bird's_3 1.41 1.64 1.08 1.35 1.33 1.42 1.34 1.52 -- a bit better PQ 1.32 1.13 1.26 1.27 1.20 1.11 1.21 1.27 -- WINNER Nick's_3 1.22 1.71 1.49 1.27 1.70 1.17 1.80 -- memory blowup The additional code used in this testing was: uprimes = sieve [2..] where -- "unfaithful sieve" sieve (p:xs) = p : sieve (filter ((/=0).(`rem`p)) xs) tprimes = 2 : primes' where -- trial divisions code primes' = 3 : filter isprime' [5,7..] isprime' x = all ((/=0).(x`mod`)) $ takeWhile ((<=x).(^2)) primes' dprimes = 2 : primes' where -- "delayed-filter" primes' = 3 : sieve primes' (map (^2) primes') [5,7..] sieve (p:ps) (q:qs) xs = let (h,t) = span (< q) xs in h ++ (sieve ps qs . filter ((/=0).(`rem`p)) . tail) t bprimes = 2 : primes' where -- Richard Bird's code primes' = 3 : [5,7..] `minus` composites composites = foldr merge [] [ map (p*) [p,p+2..] | p <- primes' ] merge (x:xs) ys = x:merge' xs ys -- produce the number 9 forthwith merge' (x:xs) (y:ys) | x < y = x:merge' xs (y:ys) | x == y = x:merge' xs ys | x > y = y:merge' (x:xs) ys a@(x:xs) `minus` b@(y:ys) | x < y = x:(xs `minus` b) | x == y = xs `minus` ys | x > y = a `minus` ys I have been using the phrase "unfaithful sieve" in the exact same sense that the paper that we should be discussing uses the phrase. Yes, the paper describes the algorithm it that way you say, but if you read the source, Melissa O'Neill's full implementation already encompasses the ideas you present. And no, the paper is not "unfaithful", this optimization does not affect the asymptotic behavior of the algorithm. In actuality, if you were to use an array based, imperative binary heap, this optimization does not make one iota of difference. The particular usage of the heap results in O(1) inserts anyway. Only in the presence of persistent priority queues do you even need to be concerned with such details. You can download the Sieve of O'Neill and more on hackage. You can even browse haddocks and a colorized source in your browser. Be warned that the factor sieve performs badly on GHC 6.10 and (to a lesser extent) GHC 6.12; I recommend GHC 6.8 for that bit of code. Go do your homework. And, while you are at it, you might try this implementation. On my computer it runs ever slightly faster than yours, with much improved patterns of memory consumption but basically the same time behavior: primes = 2 : primes primes' = 3 : filter isPrime [5,7..] isPrime n = all (\p -> n `mod` p /= 0) (takeWhile (< (flsqrt n)) primes') flsqrt = floor . sqrt . fromIntegral Now honestly, we are getting rather off topic, and I daresay the bogosity fraction has been a little high for your lengthy posts, which we try to discourage here. Lengthy posts are ok, but when they start to lose objectiveness, start quibbling over meanings of words, or are based too much on unsubstantiated opinion, or we lose the back-and-forth exchange of ideas, it's not good for the community. Let me be clear: I think that circular programming is pretty cool, and I've written about that at some length in the latest Monad Reader, and hinted at on LtU here, here and here. I like your original code. Your first few "original" circular programs will almost certainly be very mind bending and can fill one with a heady mixture of excitement and befuddlement. If you are really interested in benchmarking, take a look at complexity, criterion, or even do as I did and roll your own crude benchmarking library that will run something a given number of times and then calculate the mean and standard deviation. First and foremost LtU exists to exchange ideas and come to a better mutual understanding of programming, and so far despite a lot of words, you haven't told me anything I don't know, and I don't seem to have said anything that's made an impact on you. So if you want to set up say, a wordpress blog, and write something up, please be my guest. I will take a look at it. But if this conversation is to continue on LtU, something has got to change. I've just posted that other code for reference. I guess these test data had no other point than to show that my code had performance on par with the other non-PQ versions, on my computer. It also has shown the usieve's O(n^3) behavior, and O(n^1.5) of delayed-filter code, where n is number of primes produced, so I do believe that my data disproves the article's claim (on pg. 2) that This optimization [starting from a prime's square - wn] does not affect the time complexity of the sieve, however, so its absence from the code in Section 1 is not our cause for worry. This optimization [starting from a prime's square - wn] does not affect the time complexity of the sieve, however, so its absence from the code in Section 1 is not our cause for worry. I do believe the article is in error in not recognizing the need to start the filter delayed, at the square only, as the central problem of the naive code. Again, its original behaior is O(n^3) which gets improved to about O(n^1.5) by my code, which then gets improved to about O(n^1.2) by the article's PQ algorithm (or be it O(n*log^k n) ). The article claims that the sieve is better than filter because, in the example it uses (on pg 2.), it "crosses off 15 multiples of 17 from 289 to 527", whereas the filter "examines 45 non-multiples of 2,3,5,7,11,13" (emphasis mine). But what's important, IMO, is not crossing-off, but the very counting. The sieve counts 238 times from 289 to 527, while the filter only examines 45 numbers on the sequence culled by the preceding filters, so this reasoning doesn't seem valid to me. The true origin of article's optimization is that it changes counting (pred/succ) into leaping forward at once (using sum). It stops counting, so I thougt it means it's stopping being a sieve. Is it "semantics"? What's wrong with semantics, is it not "meaning"? This _does_ matter for the very big numbers because then comparison acquires cost. Only counting has no cost on big numbers as on small, but the article abandons counting. Is it not a valid point to make? The premature insertions of big primes squares will indeed be O(1) in array-based PQ but won't be on other implementations, and will take up memory. Your code exchanges p^2 < x with p < sqrt x in the trial version. It's a nice trick to speed things up. Thank you for your attention, and discussion, and pointers you gave me. I don't think I made any bogus claims, not consciously anyway. But we don't have to spend even more time on these minutiae. It's true that that stopping at sqrt n makes a huge difference when working with trial division. But Melissa O'Neill is 100% correct in her claim: given a genuine Sieve of Eratosthenes, starting at p*p is not a crucial optimization. It does not change the asymptotics. This is true of both the traditional Sieve of Eratosthenes and the Sieve of O'Neill, but not trial division. sqrt n p*p In general, an optimization that is crucial to one algorithm might not mean that much to another. It just goes to show that the "unfaithful" sieve and the "geniune" sieve are fundamentally different at the highest level. The other optimization that you mention, of delaying the insertion primes into the PQ, is also already done in the full implementation but not mentioned in the paper. Again, this is not a crucial optimization for an implementation to be a considered a "genuine sieve" by the criteria set forth by the paper, as it does not affect the asymptotic time complexity of the algorithm. It also doesn't affect space complexity much, as you have to store them *somewhere* unless you want to recompute them later. (Which may in fact be worthwhile.) So most of your observations are ok, but the conclusions tend to be bogus. I am not trying to discourage or disparage you, but it is past time to take this off of LtU. You are more than welcome to email me if you'd like to continue this conversation. I do have a few ideas that we could explore that might actually turn into something interesting and/or useful. You can find my email address on my Monad Reader article. (deleted) Just to put it to the record, the nested filters code can be much improved in its efficiency by collecting all the primes to-test-the-primality-by found so far into an explicit list, and eliminating their multiples in one go, each time for the corresponding span upto an upper limit of the next prime's square: primes = 2: primes' primes' = 3: sieve primes' 0 [5,7..] sieve (p:ps) k xs -- with k primes', filter xs = noDivs k h ++ sieve ps (k+1) (tail t) where (h,t) = span (< q) xs ; q=p*p noDivs k = filter (\x-> all ((/=0).(x`rem`)) $ take k primes') It actually doesn't matter, speed-wise, whether we collect this list explicitly or just reuse the primes sequence's prefix as it is getting built. I've arrived at the above code after more private discussion with Leon P. Smith, who had the great insight of fusing the numbers supply with the span to directly generate the needed numbers on each iteration step: span primes = 2: primes' primes' = 3: sieve primes' 0 5 sieve (p:ps) k x -- with k primes', filter from x = noDivs k h ++ sieve ps (k+1) (q+2) where (h,q) = ([x,x+2..q-2], p*p) noDivs k = filter (\x-> all ((/=0).(x`rem`)) $ take k primes') This code is fastest of all I've seen here or in the article (it's about 25% faster than the one above it), to produce first million primes. The path for further improvement is also clear - maintain the first k primes explicitly in a priority queue instead of a list, and iterate over the generated numbers span while updating the queue, thus skipping the primes - exactly the article's approach. So it would have to be compared with the above code then, to be a fare comparison. The relative performance of "span" and "generate" code vs. my ad-hoc tree-based PQ code, tested by running GHC -O3 compiled code loaded into GHCi, is: generated: 100,000 300,000 1,000,000 primes span/PQ 0.85 1.0 1.2 gene/PQ 0.64 0.8 1.0 Yes, it is faster than PQ-based code, for the first MILLION primes. That's not primes up to one million; that's a million primes generated. I take these data to prove that the Sieve of Eratosthenes can be written in a simple clear functional lazy style and be reasonably fast at that, without resorting to arcane data structures, which are better left for far-end optimizations. Thus this disproves the central case of the article. The author presents astronomical gains in speed over the naive case, and attributes it all to her use of PQ, but the above data disprove that claim. The real sieve crosses off composites and thus gets its primes for free because it is able to work with the spans of numbers at once (whether performed by humans, using our vision, or imperative sieves, using mutable arrays). Plain functional versions work with one number at a time, imitating counting by recalculating the remainders, and thus end up working hard for primes as well (and asymptotically primes matter the most, because most of the composites will have small prime factors most of the time, as the article rigorously shows). The usual descriptions of the algorithm overlook this aspect of counting and traversal, ascribing no cost at all to them. The author does that too when on pgs. 2 and 3 she compares 45 numbers tested by trial-division with 15 numbers crossed off by a "faithful sieve", not realizing that in order to cross off those 15 numbers it had first to visit 238 of them. This has no cost on imperative arrays, or with human vision, but it is still there. The priority queue code achieves its improvement by imitating this spacial aspect, able to jump to the next composite directly, as it calculates its value, thus skipping over the primes. The original sieve though works by counting, not calculating and comparing values. That using value-comparing priority queue is a great far-end optimization nobody can dispute (as well as the wheel's), but whether it is in any way "faithful", and a version that imitates counting by recalculating remainders is not faithful to an ill-described algorithm devised by an ancient Greek 2300 years ago, is open for anyone's interpretation. IMO. {edit:} ... apparently list comprehensions are compiled into even faster (5-10% ) code: primes = 2: 3: sieve 0 primes' 5 primes' = tail primes sieve k (p:ps) x -- sieve by k first odd primes the odds from x upto p*p = [x | x<-[x,x+2..p*p-2], and [(x`rem`p)/=0 | p<-take k primes']] ++ sieve (k+1) ps (p*p+2) To work on an unlimited list of primes, you should use a slightly modified sieve. It requires a lot of scroll but that shouldn't be an issue for the average computer ;) Instead of annotating with just "is prime" or "is not prime", the algorithm annotates with all the prime factors of the number. The computer only needs to store an annotation for numbers that are not yet visited. The x2 optimisation and pre-annotate optimisation can be used too. Some results for a quick Java implementation using ints and a Hashmap for prime factors: $ java -Xprof Primes 500000000 2 3 5 ... 499999909 499999931 499999993 Flat profile of 692.62 secs (40541 total ticks): main Interpreted + native Method 0.3% 103 + 0 java.lang.Integer.hashCode 0.0% 0 + 9 java.util.zip.ZipFile.read 0.0% 5 + 0 Primes.lazyAppend 0.0% 4 + 0 Primes. 0.0% 0 + 3 java.util.zip.ZipFile.open 0.0% 0 + 3 java.lang.Object.getClass 0.0% 2 + 0 java.math.BigInteger.addOne 0.0% 2 + 0 java.util.Arrays.asList 0.0% 2 + 0 java.util.Arrays.copyOf 0.0% 0 + 2 java.lang.System.arraycopy 0.0% 2 + 0 java.util.ArrayList.get 0.0% 1 + 0 sun.security.x509.X509CertInfo. 0.0% 1 + 0 sun.security.provider.X509Factory.engineGenerateCertificate 0.0% 1 + 0 sun.net. 0.0% 1 + 0 java.math.BigInteger.multiplyToLen 0.0% 1 + 0 java.util.regex.Pattern.compile 0.0% 1 + 0 sun.security.pkcs.PKCS9Attribute. 0.0% 1 + 0 java.security.Provider.parseLegacyPut 0.0% 0 + 1 java.util.zip.Inflater.init 0.0% 1 + 0 sun.security.provider.SHA.implCompress 0.0% 0 + 1 java.lang.Class.forName0 0.0% 0 + 1 sun.misc.Unsafe.getInt 0.0% 1 + 0 java.util.AbstractCollection. 0.0% 1 + 0 java.lang.Double.toString 0.0% 1 + 0 java.nio.HeapByteBuffer. 0.4% 146 + 20 Total interpreted (including elided) Compiled + native Method 59.0% 23917 + 1 Primes. 30.4% 8294 + 4024 Primes.lazyAppend 2.7% 0 + 1098 java.lang.Integer.valueOf 2.3% 950 + 0 java.util.HashMap.containsKey 1.5% 616 + 0 java.util.HashMap.remove 1.3% 529 + 0 java.util.HashMap.get 1.1% 0 + 460 java.util.AbstractList.iterator 1.1% 0 + 446 java.util.ArrayList.ensureCapacity 0.0% 3 + 0 java.math.BigInteger.squareToLen 99.5% 34309 + 6029 Total compiled Stub + native Method 0.0% 0 + 3 java.lang.Object.getClass 0.0% 0 + 3 Total stub Thread-local ticks: 0.1% 34 Class loader Flat profile of 0.04 secs (4 total ticks): DestroyJavaVM Interpreted + native Method 33.3% 1 + 0 java.io.DeleteOnExitHook. 33.3% 1 + 0 Total interpreted Thread-local ticks: 25.0% 1 Blocked (of total) 66.7% 2 Class loader Global summary of 692.68 seconds: 100.0% 44697 Received ticks 7.9% 3540 Received GC ticks 0.1% 30 Compilation 1.3% 584 Other VM operations 0.1% 36 Class loader $ java -Xprof Primes 50000000 2 3 5 ... 49999903 49999921 49999991 Global summary of 49.04 seconds: 100.0% 3204 Received ticks 5.3% 171 Received GC ticks 0.8% 26 Compilation 1.5% 48 Other VM operations 0.2% 5 Class loader $ java -Xprof Primes 5000000 2 3 5 ... 4999913 4999933 4999949 4999957 4999961 4999963 4999999 Global summary of 4.62 seconds: 100.0% 305 Received ticks 4.6% 14 Received GC ticks 13.1% 40 Compilation 1.6% 5 Other VM operations 1.6% 5 Class loader $ java -Xprof Primes 500000 2 3 5 ... 499903 499927 499943 499957 499969 499973 499979 Global summary of 0.92 seconds: 100.0% 68 Received ticks 5.9% 4 Received GC ticks 42.6% 29 Compilation 5.9% 4 Class loader $ java -Xprof Primes 50 2 3 5 ... 11 13 17 19 23 29 31 37 41 43 47 Global summary of 0.45 seconds: 100.0% 33 Received ticks 51.5% 17 Compilation 3.0% 1 Class loader $ java -Xprof Primes 2000000000 2 3 5 ... 1999999913 1999999927 1999999943 1999999973 Global summary of 2496.85 seconds: 100.0% 166844 Received ticks 15.1% 25155 Received GC ticks 0.0% 37 Compilation 1.3% 2242 Other VM operations 0.0% 3 Class loader Mmh, the time complexity looks roughly linear... $ java -version java version "1.6.0_13" Java(TM) SE Runtime Environment (build 1.6.0_13-b03-211) Java HotSpot(TM) 64-Bit Server VM (build 11.3-b02-83, mixed mode) The genuine, sufficiently efficient, unbounded, list-based sieve of Eratosthenes in Haskell turned out to be primes = (2:) . _Y $ (3:) . diff [5,7..] . _U . map (\p-> [p*p, p*p+2*p..]) _Y g = g (_Y g) -- non-sharing fixpoint combinator _U ((x:xs):t) = (x:) . union xs . _U $ unfoldr (\(a:b:c)->Just(union a b,c)) t with the usual definitions of diff and union for ordered, increasing, infinite lists of numbers. diff union Runs in practically constant (very slowly growing) space, with run time's empirical orders of growth on par with the article's code (as later improved in the accompanying ZIP file), which is ~ n1.20..1.25 (in n primes produced). For comparison, an array-based code runs at about ~ n1.10..1.05.. (Richard Bird's code from the article is equivalent to defining _U ((x:xs):t) = (x:) . union xs . _U $ t). _U ((x:xs):t) = (x:) . union xs . _U $ t With wheel factorization added, primesW = [2,3,5,7] ++ _Y ( (11:) . tail . diff (scanl (+) 11 wh11) . _U . map (\(w,p)-> scanl (\c d-> c + p*d) (p*p) w) . meetBy snd (tails wh11 `zip` scanl (+) 11 wh11) ) wh11 = 2:4:2:4:6:2:6:4:2:4:6:6:2:6:4:2:6:4:6:8:4:2:4:2: 4:8:6:4:6:2:4:6:2:6:6:4:2:4:6:2:6:4:2:4:2:10:2:10:wh11 with the obvious semantics for meetBy f xs ys ~ meet (map f xs) ys. Fusing diff and meetBy with their surroundings gives it a bit of an additional constant factor improvement. meetBy f xs ys ~ meet (map f xs) ys meetBy (later remark:) So lists are perfectly capable of expressing a proper sieve of Eratosthenes; moreover, the main problem with the original "naive" sieve is that it is too hasty, firing up new filter for each produced prime. The paper rightly dismisses having each filter delay its operations until the prime's square, but overlooks the optimization of postponement of creation of the filter itself — like so: primesT = sieve (4,primesT) [2..] where sieve (q,ps) (x:xs) | x < q = x : sieve (q,ps) xs | otherwise = next ps xs next (p:t) xs = sieve (head t * head t, t) [n | n <- xs, rem n p > 0] This runs at about ~ n1.35..45.. to the original's ~ n2, just like the paper shows the optimal trial division should. That's impressive. Did you personally come up with it, was it already described somewhere else? I would be interested in information about how you came with this code. If I understand correctly, the point of the "unsharing fixpoint" is to avoid a memory leak due to the recursion marking all intermediate lists as reachable forever. What would the memory cost of that be? The simple array-using imperative sieve implementation use an array of all (primes and non-primes) element in the interval of interest. You would store more because of the duplication in multiples to remove. On the other hand, what is the time overhead of recomputing primes recursively? I don't have a clear picture of at which speed the unionAll implementation forces the list, for example. Thanks. :) This code is a product of discussions on haskell-cafe starting December 2009 and then 2010, mainly with contributions from Daniel Fischer, about the code by Heinrich Apfelmus, which came after the code by Dave Bayer from July 2007 (and then this his "venturi" version). I've just simplified the formulation later, forfeiting the sophistication of prior versions striving to force the tree as little as possible, for the unrestrained simplicity of forcing it in bunches of 2k streams - which still works, since primes' squares are sufficiently far apart (9>7, 49>19, 361>53, ... (p2k)2 > p2k+1; asymptotically, 2log(2k) > log(2k+1), 2k > k+1). The tree can be seen here and here. Yes, it is about achieving the near-constant memory footprint, to allow the calculated primes to be forgotten (and thus gc-ed) as soon as possible; the initial idea was by Melissa O'Neill in her ZIP file code (with two stages). There's an SO answer about this, too. We had it with two stages for a long time on haskellwiki; I recently (a year?) realized the multistage production (with _Y) is even more forgetful. And that is just simple recursion, after all. gc _Y My interest was initially mainly about the idea of postponement which I found was lacking in the article. It can be seen in Python as well. Here's some variations on that.
http://lambda-the-ultimate.org/node/3127
CC-MAIN-2019-35
refinedweb
16,819
62.58
Indy's Child // December 2012 Indy's Child is Indiana's #1 Parenting Publication! In this issue: IOur 12 Days of Holiday Giveaways, Keeping the Season Bright, Choosing a Preschool for Your Child, Homeschooling, Making Family a Priority This Holiday, Raising Teen Twins with Autism, our award-winning calendar and MUCH, MUCH MORE!!! Indy’sChild DECEMBER 2012 | FREE indyschild.com CHOOSI NG A PRE SCHOOL is child's play KEEPING the season bright is homeschooling RIGHT for you? OF GI V E AWAY S 1 INDYSCHILD.COM 12 DAY S 2 INDYSCHILD.COM *Additional fees may apply. DECEMBER 2012 [ indy’s child ] 3 contents 12.12 features 16 | KEEPING THE SEASON BRIGHT Tips to help avoid holiday burnout commentary + parenting 18 | MUSEUM PROFILE 20 | CHRISTMAS AT THE ZOO 30 | DEAR TEACHER 49 | MOMMY MAGIC Christmas Magic 53 | TRUE CONFESSIONS OF A STAY-AT-HOME-DAD These toys are better off left on the shelf 16 22 | CHOOSING A PRESCHOOL IS CHILD'S PLAY Finding the right program for your child 44 | MAKING FAMILY A PRIORITY THIS HOLIDAY SEASON How one local mother does it 22 special needs 34 | RAISING TEEN TWINS WITH AUTISM One local mom's story 34 46 | INDY'S CHILD 12 DAYS OF GIVEAWAYS! I S HOMESCHOOLING 51 | RIGHT FOR YOU? The pros and cons of being your child's primary teacher 42 | TEN TIPS FOR LESSHARRIED HOLIDAYS FOR KIDS WITH SPECIAL NEEDS resources 26 | education/childcare GUIDE 38 55 61 62 | | | | Special Needs GUIDE WINTER FUN GUIDE MARKETPLACE BIRTHDAY PARTY GUIDE 51 calendars 40 | SPECIAL NEEDS EVENTS 56 | DECEMBER EVENTS 59 | ONGOING EVENTS 63 | FUN + WACKY in every issue 06 | PUBLISHER'S NOTE 08 | COMMUNITY SPOTLIGHT 09 | ONLINE BUZZ 4 INDYSCHILD.COM on the cover isadora bancheth favs super hero: Wonder Woman color: Pink ice cream: Vanilla sport: Gymnastics tv show: Super Why subject: Arts & Sports candy: Twix movie: The Smurfs book: Sleeping Beauty food: General Tso Chicken the English group “One Direction” and Harry is her Favorite AGE 4 interesting fact: Isa is in love with clothing provided by Kids Fly Too! “ I wanna be a rock star! “ when I grow up... [ Photos by Hannah Hilliard Photography ] DECEMBER 2012 [ indy’s child ] 5 in every issue [ publisher’s note ] Indy’s Child CREATIVE DIRECTOR Katie Pfierman | katie@indyschild.com The Season with Special Reasons I admit that Thanksgiving is my very favorite holiday. I love sharing that special day with family members and everyone chips in with their favorite recipes so the side dishes are unique. Likewise, as one of the elders in the group, I can have my own Thanksgiving by appreciating the blessings of having a large and loving family. December is special because often we see the truly generous side of our community. Whether you celebrate Christmas, Hanukkah or Kwanzaa, you are probably involved in trying to help others enjoy this special time of year. You may hear the bell-ringers that represent the Salvation Army and feel that the good works they do need your support. I personally take time to thank them because they are volunteers caring about others and subjected to cold weather. This is my second year of organizing Holiday Baskets for Mary Rigg Neighborhood Center. It is a group effort of Indianapolis Racquet Club juniors participating on teams or playing in my classes. We talk about how important caring and sharing is to make everyone experience the Season with the Reason. Indianapolis has so many festive opportunities for families. Many performances at Beef and Boards are holidayoriented including performances of The Christmas Carol. The Children’s Museum has expanded Jolly Days to include more fun and games. Christmas at the Zoo will feature new special Dolphin Shows. The Indianapolis Symphony is presenting its Yuletide Celebration with many new orchestrations. Plus, more trains have been added to Jingle Rails at the Eiteljorg Museum. The Nutcracker Ballet has two offerings. The Butler Ballet production ends December 2nd. A very creative production of The Nutcracker Ballet will be held December 21-23 at the Scottish Rite Cathedral. The Indianapolis School of Ballet will have several guest artists, but local ballet students will perform the majority of the roles. This unique presentation takes on an interesting setting: Artistic Director Victoria Lyras’ interpretation of the holiday classic starts with a festive Victorian gathering in scenic designer C. David Higgin’s replica of the Morris-Butler House parlor, a Historic Landmarks of Indiana museum house. This sounds like a very interesting production. Best wishes to all of our Indy’s Child readers to enjoy the Season with Special Reasons with your family and friends and may the joys and blessings of the month of December warm your heart. AD CREATION Heather Lipe | heather@amplifydesign.com CONTRIBUTING WRITERS Barbara Wynne, Wendy Schrepferman, Carrie Bishop, Sarah McCosham, Katrina Holtmeier, Brooke Reynolds, Mary Susan Buhner, Pete Gilbert, Kim Harms of The Children’s Museum, Katherine Squadroni of Riley/IU Health, Taylor Newell of Indianapolis Downtown, Hollie Adams of St. Vincent Health, Carla Knapp of The Indianapolis Zoo, Marge Eberts & Peggy Gisler DECEMBER 2012 [ indy’s child ] 7 community S POT L IGH T celebrate the winter solstice at the indianapolis museum of art In the United States and the rest of the northern hemisphere, the first day of the winter season is the day of the year when the sun is farthest south. This day, December 21st, is known as the winter solstice. The IMA’s Annual Winter Solstice celebration will take place on Thursday, December 20th from 5:00 pm - 8:30 pm. Bundle up and head to the museum grounds for an ice carving demonstration, art-making and music. Cozy up to the bonfire with hot chocolate and holiday treats available for purchase from Nourish Café, or warm up in the Lilly House where you will enjoy historic holiday decorations and music. The IMA will be open from 11:00 am until 9:00 pm. Admission and parking are free. Visit for information on this and other special events at the IMA. in every issue [ community spotlight ] meridian music’s 5th annual music marathon food drive On Friday, December 7th at 3:30 pm, music will fill the air of Meridian Music’s Munger Hall in Carmel. Area students representing many instruments, genres and skill levels will perform into the evening. The music will start up again the following morning, Saturday, December 8th at 8:00 am and last throughout the day. Meridian Music welcomes the general public to attend this event and asks all performers and audience members to donate at least one non-perishable food item. Meridian Music is located at 12725 Old Meridian Street in Carmel. For more information, call 317-575-9588. If you are unable to attend the performances, please consider bringing a non-perishable food item to the Meridian Music store. They will continue to accept items from the general public through January 5, 2013. a christmas carol at the indiana repertory theatre The IRT’s timeless Christmas classic, Charles Dickens’ A Christmas Carol, runs on the main stage November 23 through December 24.. For tickets and information, call the IRT ticket office at 317-635-5252. greetings from cards from santa! The Nor th Pole is abuzz with preparations for the magical holiday season, and Cards from Santa are now available! Be sure to include all the children on your list! Cards from Santa began in 2009 and is based on a beloved childhood Christmas tradition. Receiving a personalized Card From Santa will highlight your child’s sense of excitement and anticipation in the days and weeks leading up to helping those still in need Hurricane Sandy left her indelible mark last month. Events such as this are often distressing to children. One way to help them understand and process these situations is to empower them to make a difference in the lives of others. Consider making a family donation to your local Red Cross chapter. Visit to donate online. You may also call 1-800-RED-CROSS or send a donation to American Red Cross, P.O. Box 37243, Washington, DC 20013. Christmas. Along with Santa’s personalized message, each high quality, brightly colored card contains a beautiful picture to color and two holiday activities. Your family will treasure these cards for many years to come. Whether you’re a parent, aunt, uncle, grandparent, or just a close friend, please let Santa know who wants a special card this year! For more information, visit . 8 INDYSCHILD.COM online buzz facebook freebie fridays & weekly e-newsletter DECEMBER’S check OUT CONTESTS “Where is your favorite place in Indy to catch the holiday spirit?” Castleton Mall... it's always decorated so pretty and all the shoppers get me into the holiday spirit! – Anita J. Broad Ripple during the day shopping local and Mass Ave. at night shopping local. – Brooke H. The Children's Museum!!! – Heather L. Conner Prairie for the Gingerbread Houses! – Caroline M. Nothing beats the Circle!!! For me its not Christmas until we get the kids bundled up and take a stroll around the Circle to see the lights, drop a letter in Santa's mailbox and have some hot cocoa. Its perfect!!! – Laura M. Vanilla Bean Bakery with their decorated cake pops and cake truffles! Tiny delicious holiday works of art! – Kristine C. The light display at Reynolds Farm Equipment in Fishers-just wouldn't be Christmas without it - and it's FREE! – Samantha S. + for a chance to win: > LIKE US ON FACEBOOK > FOLLOW US ON TWITTER > SIGN UP for our weekly e-newsletter at indyschild.com “Like” us on Facebook to Join in the Conversations! Over 5,500 Fans and Counting... 12 DAYS of INDY'S CHILD giveaways •••••••••• Indiana Repertory Theatre Tickets Disney On Ice: Worlds of Fantasy Beef & Boards Dinner Theatre Tickets LIKE our Facebook page for a chance to win! DECEMBER 2012 [ indy’s child ] 9 OUT Holiday Break! Over the The holiday break is great, right? The kids are home from school for consecutive weeks, giving the entire family the chance to spend quality time together watching seasonal movies, decorating, baking – you get the idea. All this is just great until the kids start to get restless (when I was younger, this happened around day 0.5). Now you’re faced with a dilemma: how do you keep the kids entertained without draining your entire holiday gift budget? Here is a list of fun, inexpensive events and activities for the entire family in Downtown Indianapolis over the holiday break. Take in a fun holiday experience that features the Yule Slide, Jingles the Jolly Bear, visits from Santa, the Snow Castle, ice fishing and cookie making at Jolly Days Winter Wonderland at The Children’s Museum of Indianapolis through Jan. 6. Stop by the museum’s Lilly Theater at no extra charge for a showing of The Magic Snowman based on the classic children’s tale Stone Soup. $17.50 adults, $12.50 kids (2–17). Explore holiday decorative ideas of the 1930s and 1940s during Christmas at the Lilly House at the Indianapolis 10 INDYSCHILD.COM Get the Family Museum of Art through Jan. 6. Who knows, maybe you’ll absorb some new ideas for your own home decor! FREE admission. The Indiana Ice play all of their home games Downtown this year at Bankers Life Fieldhouse and Pan Am Plaza. Catch a game Dec. 22, 30, Jan. 4 or 5. Get in the game for $11 at Bankers Life or $10 at Pan Am with discounted prices for kids, seniors and military service members. The Pacers also play four home games over the holiday break at Bankers Life and the Colts take on the Houston Texans at Lucas Oil Stadium Dec. 30. Speaking of Pan Am Plaza, test out your own skills on the ice at the Indiana/World Skating Academy on public skating evenings for only $6.50 (get $2.50 off if you bring your own skates). While you’re Downtown, bundle up and take a walk by Monument Circle to admire the Circle of Lights® presented by the Contractors of Quality Connection and Electrical Workers of IBEW 481 (until Jan. 12). The 4,784 lights on the monument have lit Downtown for the holidays for 50 years (since 1962!). Calm the commotion with some locomotion with Jingle Rails at The Eiteljorg Museum of American Indians and Western Art through Jan. 6, an intricate model train diorama complete with a miniature Downtown cityscape. $10 adults, $6 kids (5–17), children 4 & under FREE. Step into a scene from A Christmas Story, play with some classic American toys and hang with Radio Disney during Winterfest at the Eugene and Marilyn Glick Indiana History Center Dec. 17 – 30. See the amazing holiday lights display during Christmas at the Zoo at the Indianapolis Zoo through Dec. 30. Take the Holiday Train Ride, see a holiday-themed dolphin show, decorate cookies and find one of 10 hidden mistletoes for a chance to win a Dolphin In-Water Adventure. $9.50 adults, $7.50 kids. Catch Christmas at the Puppet Studio Dec. 22 and 27, a Christmas variety show filled with music and audience participation at Peewinkle's Puppet Studio. $10. Downtown Indianapolis offers a fantastic variety of fun things to do on any budget, especially during the holiday season. For more information on Downtown events, visit. com, download the Indy Downtown mobile app and follow @ IndyDT on Twitter. Happy holidays! DECEMBER 2012 [ indy’s child ] 11 health [ pediatric health ] Assessing a Child’s Fever When should you be concerned? “Fever” can be a scary word for parents—sometimes, inordinately so. After all, a fever indicates your child’s body is doing what it’s supposed to do to fight infection. Learning what to do for a child with a fever and when a fever might indicate something serious should be on every parent’s to-do list. status change—may require more immediate medical attention. A primary care provider may also need to evaluate a child who displays the following symptoms, regardless of his or her temperature: — Diarrhea — Difficulty breathing — Dry mouth — Lack of appetite Whether your child’s fever warrants swift medical attention, a phone call to your primary care provider or simply careful monitoring at home, you’ll want to make him or her as comfortable as possible. If not drinking well, offer him or her an electrolyte-replenishing liquid, water, gelatin or ice pops to stave off dehydration. Do not attempt to actively cool your child with cold water/baths or alcohol rubs. Dress your child in his or her favorite pair of lightweight cotton pajamas and ensure he or she gets plenty of sleep. With proper care, your little one will likely be back to his or her active self in no time. For other information about caring for a child with a fever, visit and search for “fever”. — Sore throat — Stomach pain — Vomiting Honey, you feel warm According to the American Academy of Family Physicians (AAFP), a child has a fever if his or her temperature exceeds 99.5 degrees Fahrenheit when measured orally or 100.4 degrees Fahrenheit when taken rectally. Many parents prefer to take their toddlers’ temperatures by mouth, but the AAFP reports that rectal temperature taking yields the most accurate results. Either way, it is best to use a digital thermometer. Infections are the most common cause of fever, but immunizations, wearing too many clothes and heat exposure can also cause a toddler’s body temperature to rise above its normal 98.6 degrees Fahrenheit (99.6 degrees if measured rectally). Most of the time, a fever isn’t cause for alarm in an otherwise healthy child, especially one who remains alert, still wants to play and continues to eat and drink normally. Your toddler may not need medication if his or her fever isn’t causing pain or discomfort, however, acetaminophen or ibuprofen can help relieve symptoms and reduce the fever. What to do and when Some fevers—those that last more than several days are associated with petechiae (a pinpoint rash) or mental This article was reviewed by David Zipes, M.D., medical director, pediatric hospital medicine, Peyton Manning Children's Hospital at St. Vincent. 12 INDYSCHILD.COM health [ pediatric health ] Home Safe Home Prevent burn injuries and fires Dr. Rajiv Sood Dr. Rajiv Sood is the co-medical director of the Riley Hospital for Children Burn Center at Indiana University Health. — Burn candles on a flat, steady surface where children and pets can’t tip them over. — Unplug your clothing iron and curling iron when not in use. — Set your water heater thermostat at 120 degrees Fahrenheit. As a parent, your child’s safety is always on your mind, but are you relying on luck alone to prevent a burn injury or a deadly fire? You shouldn’t because your family’s life may depend on it. Put the odds in your favor by implementing preventive measures now and making sure EVERY member of your family knows what to do in case of a fire - especially as the Christmas season nears. Involve your child where appropriate and learn how simple precautions and a little planning can help keep your family safe. — Install smoke detectors on each level of the home, near the kitchen and in each bedroom. Test the alarms monthly and replace batteries yearly. — Have a fire extinguisher, and ensure family members know where it’s stored and how to use it. Hatch a lifesaving plan — Post your local fire department’s number in your home. Teach your child how and when to use 9-1-1. — As a family, create a home evacuation plan in case of a fire. Sketch out your home’s floor plan and discuss each potential exit. — Demonstrate and practice the Stop, Drop, Roll method. Tell your child that if his clothing is on fire, he must immediately stop what he’s doing, drop to the ground, and roll until the fire is out. — Explain to your child that if he sees smoke, he should cover his mouth and stay low to the floor when exiting the house to minimize breathing in smoke. — Practice makes perfect. Practice evacuating the home during the day and at night. Don’t assume your family knows how to escape in a time of high stress. Don’t leave your child’s safety to chance when it comes to accidental burns and fire. Implement safety measures now and teach your child what to do in the case of an emergency. For more information visit our. Prevention is always the best strategy — Do not put your Christmas tree near a heat source. Discard a live tree promptly when it becomes dry. — Do not overload electrical outlets with holiday decorations. Check holiday lights for frayed wires, bare spots and broken sockets. — Keep a fireplace screen in front of the fireplace. Teach your child the danger of touching or moving it. — Keep space heaters away from flammable materials. Turn them off when leaving a room or going to bed. — Never leave food cooking on a stove unattended. Keep pot handles turned toward the back of the stove. — Do not allow people to smoke in your home. Keep matches and lighters out of reach. — Only use the clothes dryer when you are home. 14 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 15 Keeping the Season Tips to Help Avoid Holiday Burnout It’s that time of year again - time for family, festivities and fun as we celebrate the holiday season. Unfortunately for many people, the holidays instead become defined by hectic shopping trips, stressful family events and to-do lists that never seem to end. Add kids into the mix, and things can become exponentially more stressful. It’s easy to become burned out by the holidays. Read on for some simple tips on keeping the season merry and bright, staying a sane and happy parent and maintaining perspective on what the holidays are really about. B R I G HT Sarah McCosham households, but now you want to start your own traditions. Heather, mom to a 2 year-old toddler and 4 month-old fraternal twins, says that it hasn’t been easy transitioning from old traditions to new ones. “I really wanted Christmas morning to be our own little family (meaning me, my husband and our kids) but we have immediate family that is used to seeing us every year on Christmas. Trying to do our own thing and not hurt anyone's feelings has been tough; however, it's really important to me that we establish our own traditions now that we have kids.” In fact, managing family expectations is one of the most overwhelming holiday stressors, says Dr. Liz Boyd, Assistant Professor in the Psychology Department at Indiana UniversityPurdue University Indianapolis. “The holidays increase the expectations or demand a person feels in the family role. Even if that person has negotiated a good balance for most of the Managing Expectations Once you get married and start your own family, former family traditions become tricky. For example, both you and your spouse used to spend Christmas morning at your respective 16 INDYSCHILD.COM year, that increased demand can throw things off and create a situation where there is too much to do and not enough time to do it.” When dealing with family, it’s best to be clear about what your expectations are for the holidays. Pick a few family traditions you’d like to be part of, and be sure to let extended family know ahead of time what your plans are. By going into the holidays with just a few commitments and reasonable expectations, you’ll be able to really enjoy the time spent with your family. Shopping…With Kids Holiday shopping is stressful enough when it’s just you – add a carful of kids and shopping becomes next to impossible. According to Terri Potter, a toy seller at Kids Inc., parents should first take kids to a store for a “looking” day where they can observe what types of toys their kids enjoy. “Later on, parents can return (by themselves) and select those books, games and toys that they feel best fit the needs of their child,” she explains. Depending on the age and disposition of your children, a “looking day” could easily turn into a series of tantrums, as they don’t understand why they can’t have everything they want now. In this case, the Toy Experts at Indianapolis’ Imagination Station suggest taking the kids along as you shop for others, which helps teach them about the joy of giving. “Make sure to set expectations early on,” says Debi, one of Imagination Station’s Experts. She continues, “Teach them that the holiday isn't just about buying. Our family takes advantage of opportunities to give: we ‘adopt’ a child through Compassion International, we fill at least one shoebox for ‘Operation Christmas Child’ and we donate toys at local toy drives. Generosity and greed are both qualities learned very early in life.” Setting budgets and guidelines for your own kids at an early age is also key. My husband and I have a long-standing tradition where we focus on the “four gift rule: something you want, something you need, something to wear, something to read.” By paring down lists to a manageable number, we can focus on buying more meaningful gifts for our family. Finally, seek out gifts that will encourage imaginative play and cognitive development, such as books. Long after the excitement of Christmas morning has dissipated, these gifts stick around. “Several years ago I was at a birthday party where a six year-old boy got loads of plastic toys,” remembers Shirley Mullin of Kids Inc. “He exclaimed over each one, but when he unwrapped the dinosaur book I had taken, he tossed it aside. Later on, he couldn’t be found. He was eventually discovered in a quiet corner looking at the book.” Remembering What’s Important It’s easy to get swept up by the holiday season, but as a parent, it’s especially important to slow down and remember what’s really important. By coming up with a game plan ahead of time, the focus of the holidays can be on spending quality time with your family. Advises Boyd, “Consider what is actually most important to you, and align your actions with those values. Don’t compare yourself to others, to memories of ‘perfect’ holidays in the past or even to media images of the ‘ideal’ holiday.” Creating family memories is something Heather and her husband are actively trying to do with their three kids. For example, they’ve come up with traditions that don’t involve lots of preparation or money, such as “pajama night” where everyone dons a new pair of holiday pj’s and loads into the minivan to admire the holiday lights. Above all, Heather says she wants to keep the holidays simple and family-oriented. “We want to focus more on being together rather than buying, buying, buying - we don't need presents galore under the tree - that's really not what Christmas is about.” DECEMBER 2012 [ indy’s child ] 17 around town [ children's museum profile ] 2012 TOP TEN KID –TESTED, KID –APPROVED TOY RESULTS ANNOUNCED Holiday Shopping Just Got Easier for Gift-Givers It is the year of important “votes”, 2012! Adults voted for political candidates while young visitors to The Children’s Museum of Indianapolis cast their ballots for favorite new toys of the season. Decisions were not made lightly. The hottest new toys were tried and tested in The Museum Store. Playthings that passed the test earned thumbs up by our inquisitive kid experts. Our young voters may not recognize it, but interactive, educational toys that spark imagination and creativity top the list…just the way The Children’s Museum of Indianapolis likes it. Drum Roll Please! The annual Top Ten Kid-Tested, Kid-Approved Toy List is… 9. Hyper Wheels (made by Hot Wheels) — two motorcycles on a launcher that speed off when a lever is pulled 10. Stunt Remote Control Car (made by Mindscope) — it spirals, spins, flips over, does wheelies and has multi-colored lights Santa will no doubt be checking this list twice as will adults in need of holiday gift ideas for the children in their lives. “A plethora of options can seem overwhelming for adults trying to differentiate what toy is best for what age group or what object may provide the most engagement,” said Dr. Jeffrey H. Patchen, president and CEO, The Children’s Museum of Indianapolis. “Our wonderful employees are on hand to share the results of the test and help make the gift selection process less formidable.” Also for the holidays, a Black Friday 30% discount will be available on Nov. 25, 2012 from 8:30-10 a.m. for all purchases made within The Museum Store during The Children’s Museum’s annual Santa’s Big Arrival event. Shipping and gift wrapping are available. In addition to purchases within The Children’s Museum Store, museum memberships also make a great family or grandparent holiday purchase. Memberships may be purchased at the museum, online at or by calling (317) 334-4000. Museum admission is not required to visit The Museum Store. Store hours are from 10 a.m. to 5:30 p.m. Tuesdays through Sundays; the store will be open until 2 p.m. on Dec. 24 to make those last minute holiday purchases. 1. Toop Top (made by Tosy) — a motorized, stackable, light-up top that can battle with other Toop Tops 2. Train Table (made by Brio) — children’s train table with wooden tracks, trains and toy figures 3. Remote Control Car (made by Hot Wheels) — Camaro with lots of power and a full function remote control 4. Stomp Rocket (made by The D & L Company) — a stomp of your foot and a blast of air propels the foam rocket a hundred feet into the air 5. Do A Dot (made Do A Dot) — paint colors in sponge-tip bottles that serve as the paint applicators 6. Spooner Board (made by Spooner Inc.) — a virtually indestructible balance board that spins, flips, slides, wobbles and more 7. Micro Drifters Zip Cars (made by Daydream Toy) — vibrating bristles power vehicles around an interchangeable track 8. Rody-Inflatable horse (made by Gymnic) — made of latex-free vinyl that helps children learn balance and coordination while having a great time bouncing 18 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 19 around town [ zoo profile ] Become part of a holiday tradition with Christmas at the Zoo Carla Knapp Surround yourself with the magic and beauty of the holiday season as the Indianapolis Zoo hosts its 44th year of Christmas at the Zoo presented by Donatos and Teachers Credit Union. The Indianapolis Zoo was the first zoo in the United States to hold a holiday lights event and since then, Christmas at the Zoo has come to be known for its spectacular holiday lights and displays. This year will be no exception! From 5-9pm Wednesdays through Sundays from Nov. 23-Dec. 30, become a part of this growing holiday tradition. A visit to Christmas at the Zoo is unlike any other time of year, bringing together the best of the holiday season with a “wild” twist! As the sun sets, the warm glow of twinkling lights can be seen all over the Zoo, creating a magical nighttime experience. Don’t miss the We Three Trees display presented by Indianapolis Honda Dealers, All-A-Glow Light Show and all-new lights throughout Encounters. The Holiday Train Ride presented by Marathon gives guests a perfect view of all the energy-efficient holiday LED lights sponsored by Wells Fargo Advisors, LLC. While taking in the lights, guests can warm up with a cup of hot cocoa and enjoy the sounds of carolers singing near the fireside. Plus, lots of family-friendly activities await in White River Gardens inside Santa’s Toy Shop, including cookie decorating with Mrs. Claus, letters to Santa, and visits and photo ops with Kris Kringle himself! Guests can also satisfy their sweet tooth with fudge, cinnamon rolls, caramel apples and more at Santa’s Sweet Shop. Several of the Zoo’s more robust animals will be out late to enjoy the cooler weather, and with smaller crowds, guests can enjoy a more personal Zoo experience. When visitors’ cheeks start to get rosy, they can dash inside to enjoy the animals in the Dolphin Dome, Deserts and Oceans exhibits. Holiday-themed dolphin shows will help visitors get into the Christmas spirit. Plus, two lucky guests will have the chance to return for a once-in-alifetime Zoo experience as those who find the locations of 10 mistletoes hidden around the Zoo can register to win one of two Dolphin In-Water Adventures! Christmas at the Zoo is included with regular Zoo admission and is free for Zoo members. For more information, visit or follow the Zoo on Facebook and Twitter. 20 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 21 ch osing a preschool Finding the right program for your child Wendy Schrepferman, M. A. Elementary Education is Child's P lay In recent years, full-day kindergarten has become the norm for many of our country’s young children. As a result more parents are choosing to send their children to preschool in an effort to prepare them for entering a traditional school setting. Researching and deciding upon a program for your child can be a long process. Fortunately, understanding the traits of a quality preschool is not. 22 INDYSCHILD.COM It might seem reversed, but appreciating the origins of kindergarten is the best place to begin. The process to become accredited by NAEYC is very rigorous. Marsha Lindsey of Day Nursery in Indianapolis notes, “Receiving the NAEYC stamp of approval is only the beginning. We use the standards as a measuring stick to evaluate our faculty and the learning environment monthly. We work diligently to ensure our students are receiving the best early childhood experience possible.” The German word “kindergarten” translates to “garden of children.” Think of children as a garden of wild flowers - all growing at their own rate, all presenting their unique colors and shapes in their own way. This term was made popular by Friedrich Froebel in the 1800s. His educational philosophies of promoting discovery, hands-on activities and peer relationships continue to guide quality kindergarten programs today. SIGNS OF A GREAT PRESCHOOL If your child is in the three to six year age group and attends a preschool, day care or kindergarten program, the NAEYC suggests looking for these signs in the classroom. These important learning philosophies must also be the driving force in preschool settings. Preschool is a child’s first and lasting memory of what school is all about, and it is our job as parents to find a nurturing environment where our children will grow and thrive. children should have the opportunity every day to: — Spend the majority of their time playing, working with hands-on materials and interacting with peers. They should rarely be asked to sit still and participate in whole group learning. — Access a wide variety of activities such as dramatic play, building blocks, a variety of art materials, picture books and puzzles. — Play outdoors. Outdoor time should never be sacrificed to gain more instructional time. The National Association for the Education of Young Children is a non-profit organization with a longstanding reputation of developing research-based practices for educating small children. NAEYC awards accreditation to quality preschool and kindergarten programs that apply and complete the multi-faceted process. Parents may visit to locate accredited schools as well as a variety of valuable resources. DECEMBER 2012 [ indy’s child ] 23 It’s not about simply having fun. It’s about proven methods; mindful, research-based methods that provide children with the experiences they need TO MAKE SENSE OF THE world around them. — Mindy Hutchinson, Meridian Hills Co-op Preschool & Kindergar ten — Learn numbers and letters in the context of everyday experiences which might include exploring patterns in nature, cooking or taking attendance. Worksheets are used little if at all. — Have extended, self-directed periods of time to play and explore. — Look forward to school. early childhood educators should strive to: — Work with individuals and small groups throughout the day instead of only leading whole group sessions. — Decorate the activity spaces with the children’s original artwork where writing with invented spelling is proudly displayed. — Read books to children individually or in small groups throughout the day, not just at group story time. — Adapt the curriculum for those who are successful as well as those who need additional help. — Recognize that children’s different backgrounds and experiences mean they do not learn the same things at the same time or in the same way. After reading the inventory of standards above, perhaps you are thinking, “As a parent, I want what’s best for my child, and I want them to be successful in kindergarten and elementary school. Why would I send my child to a preschool to play all day?” “It’s not about simply having fun. It’s about proven methods; mindful, researchbased methods that provide children with the experiences they need to make sense of the world around them,” says Mindy Hutchinson of Meridian Hills Co-op Preschool and Kindergarten. “Co-ops are unique because parents are actively involved in their child’s school experience. At Meridian Hills, the strong sense of community and our joyful philosophy of play are our greatest assets.” 24 INDYSCHILD.COM “ “ Barbara Willer, Deputy Executive Director of NAEYC, weighed in on the subject of play stating, “Play encourages children’s physical development, but also their intellectual, social and emotional development. When children play, they develop and practice new skills, learn to negotiate and cooperate, make friends, use vocabulary and regulate their emotions and behavior.” We are fortunate in the Indianapolis area to have a variety of quality programs to suit all ages and needs. Early childhood education options include: — Multi-age Montessori programs — Family-oriented co-op programs — Pre-k programs serving families wishing to enter a private school setting for elementary school — Museum and nature center-based programs — Traditional programs that incorporate a variety of early childhood learning philosophies — Programs with a religious education component in addition to their early childhood learning philosophies Early winter is the perfect time of year to contact preschools in your area to schedule visits. It is best to visit schools when the students are present to see what a typical day might look like. Take the above listing of standards with you and ask specific questions about the school’s core philosophy. If appropriate, ask the students what they like about their school as they are the true ambassadors. Although parents often feel pressure to have their children excel academically at an early age, it is important not to sacrifice a child’s natural instincts to discover and explore the world. Just as we wouldn’t remove the training wheels from a child’s bike before he or she was ready, we must be mindful when introducing them to formal academic settings before they are developmentally prepared. So, let’s play! We might all be surprised by what we learn! DECEMBER 2012 [ indy’s child ] 25-teaching experience. We offer a beautiful, peaceful and positive Montessori learning environment. Extended days available. 1402 W. Main St., Carmel, IN 46032, Contact: Emily & Scott Rudicel, 317-580-0699, info@carmelmontessori.com, hands-on, one-on-one or small group instruction, in life skills, grace & courtesy, sensorial activities, reading, math, music, French, cultural studies. 3085 West 116th Street, Carmel, IN 46032. Contact: Sharon Emanuel. Phone: 317-697-8460. Email: admin@westclaymontessori. com. resources [ school listings ] each child’s individual pace. 6701 Hoover Road, Indianapolis, IN 46260, 317-251-9467, emills@ JCCindy.org, Beth-El Zedeck Early Childhood Center-6854, Fax: 317-259-6849, Email: jwaldman@bez613.org, in.us fishers Fall Creek Montessori Academy Fall Creek Montessori Academy is a culturally diverse environment where children grow and develop their unique talents and gifts. Through child-centered learning, children excel physically, academically and emotionally., Brebeuf Jesuit Preparatory School.. Ages/Grades: All ages and grades welcome. Fishers Montessori, A quality learning environment offering preschool, kindergarten and elementary. Certification through American Montessori Society. 12806 Ford Rd and 131st and Allisonville Rd., Fishers, IN 46038, Contact: Peggy White, 317-8499519 or 317-580-1850 indianapolis -, www. meridianstreet.org The Montessori Learning Center WestClay Children's Montessori WestClay Children's Montessori preschool & kindergarten offers a small, structured, nurturing learning environment for children ages 3-6 to explore, learn and grow at their own pace. Guided by a certified Montessori directress and assistant, each child receives 26 INDYSCHILD.COM experienced staff embraces excellence in education by nurturing the whole childphysically, emotionally, spiritually, and intellectually. Please call for more information or to set up a tour. 7700 N. Meridian St., Indianapolis, IN 46260, Contact: Cara Paul, Director, 317-252-5517, cpaul@secondchurch.org, ISACS, NAEYS accredited. 615 W. 64th St., Indianapolis, IN 46260, Contact: Kristen Hein, Director of Admissions, Phone: 317-713-5705, Fax: 317-2548454, Email: khein@orchard.org, beginning at age 3. 7200 N. College Ave., Indianapolis, IN 46240, Contact: Shants Hart, 317-415-2777, info@parktudor.org,6509, jdrake@golove.org or kbelt@golove.org program provides a wide-range of experiences that foster learning, creativity and problem solving in all areas. A child’s sense of self-worth,-926-0425 x134, Fax: 317-921-3367, mfisher: Emily Iglendza, Director of Enrollment Management, 317-849-3441, Admissions@heritagechristian.net, St. Luke’s Early Childhood Programs St Luke’s Community Preschool is a weekday, developmentally appropriate and experience, Sycamore School-2022501,. skarpicke@sycamoreschool.org,, Stressing peace and respect for all, we’ve worked with children to develop criticalthinking and time-management Traders Point Christian Academy Fully accredited by ACSI and AdvancEd, Traders Point is a nondenominational Christian college prep school serving 600 students age 18 months to 12th grade. Offering Fine Arts, Spanish, Technology, Honors, AP and dualcredit-2059264, Fax: 317-205-9263, Email: admin@ compassionateangels.net,- Montessori Centres, progressive school, emphasizing experiential learning. Orchard teachers engage the natural curiosity of children, develop academic excellence, and provide leadership experience through well-rounded education. Orchard’s diverse community and commitment to multicultural education inspires responsible, global citizenship. Founded in 1922. NAIS, angels.com. Polly Panda Preschool and Bridgford Kindergarten Polly Panda provides a safe and healthy environment which enhances each child’s total growth. Our theme-based hands-on preschool noblesville Legacy Christian School Legacy Christian School is celebrating it's 10th year of providing affordable Christian education in Hamilton County. We are equipping and DECEMBER 2012 [ indy’s child ] 27 inspiring students to forge a-776-4, and we are adding a new Toddler room for the 2012-2012 year. 800 E. Sycamore Street, Westfield, IN 46074, Contact: Mary Lyman, Directress, 317-867-0158, montessoriwestfield@gmail.com,: Organizing the environment so it is conducive to success,, http:// cms.zcs.k12.in, 317-926-3640 28 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 29 commentary and parenting [ dear teacher ] Dear Teacher Bored students, unfair teachers and New Year’s resolutions Marge Eberts & Peggy Gisler Bored First Grader — No Challenging Work Q: My first grader has become bored in class over the last few weeks. I can see why. His readers are below what he had in kindergarten and his spelling words are simple 3-letter words. of his skipping to second grade or taking a few subjects with the second grade class. This is another solution to discuss with the principal. Keep in mind that school has only been in session for a little over three months. We have tried talking to the teacher, but she becomes aggressive and says we are attacking her teaching. The principal has agreed to look into this matter. While I am waiting, I have decided to homeschool him. The teacher is definitely not challenging my son enough. What should we do? We pay over $20,000 a year for this school, and his education is not appropriate for his abilities. — Mad Students enter first grade at all different levels. Some have completed kindergarten and even pre-k while others never went to kindergarten. It is challenging for the teacher to get everyone up to speed so they are working as a class. The curriculum could become more appropriate as the teacher gets better acquainted with the students. Hopefully, the principal will address your concerns soon so you can make the best decision for your child. A: Since you are paying, it is easy to deduce that your son is attending a private school. You might want to consider sending him to a public school as many, especially charter schools, have programs designed Is this Teacher Unfair? for gifted children. Also, a different private school could be a better fit for your child. Removing your son from this school and deciding to homeschool him could be the answer to his getting a challenging education. There is also the possibility Q: My eighth grader is very unhappy with his algebra teacher. The teacher gives out demerits all the time for the slightest misbehavior, offers very quick and inadequate explanations of new material and never reminds the students about future assignments after they have been assigned. Once, my son got a D for handing in an assignment one day late. It seems to me that this teacher is handling the students as if they were in high school. I am not alone in complaining. Other parents are complaining about his teaching. My son is doing well in every other class but only getting a C in algebra. This is not a great grade for someone going onto geometry in high school. I want my son to be a responsible student but feel this teacher is unreasonable. How should I handle this? — Dissatisfied A: 30 INDYSCHILD.COM By now, your son should realize that this teacher has high expectations about how students behave in the classroom and does not hold students’ hands when it comes to reminding them about future assignments. Your son obviously knows how to behave in order to avoid getting demerits, and it is his responsibility to do so. It is also his responsibility to write down all assignments when they are given and to put long-term assignments on a calendar. This is a habit that will serve him well in high school. Children who are mad about baseball can improve their math skills through learning how the all-so-important statistics are figured, read more to learn about recent games and have a great deal of information to use in reports. They can also study the science involved in throwing different pitches. It’s the same story for those who are absorbed in hobbies from stamp collecting to photography. — Resolve to support your children’s interests. — Give them books, magazines and articles to read about their interest. Teachers vary greatly in how they present material. It is possible that this teacher is simply not realizing that eighth graders need more explanation than older students. Unless this teacher changes, your son and his classmates need to study their math textbook very carefully. There are also websites where they can find good explanations of algebraic concepts. The teacher could change if a group of students approached him about needing more explanation. If this fails, a group of parents could ask the teacher how their children could improve their knowledge of the material covered in the classroom. The last step is for the parents to discuss this situation with the principal. — Help them get more involved in their interest by finding classes (music, art, photography, golf) for them to take or going to places (baseball games, museums, plays) where they can see their interest first hand. — Respect their interests and speak glowingly about them to others. Resolutions to Boost Your Children’s Skills Parents: It’s New Year’s Resolution time again. Too often people go overboard in trying to change too much with their resolutions. Sometimes a simple resolution or two can pay unexpected dividends. This year our resolution suggestions center on building your children’s academic skills through supporting their interests. One of the biggest assets children can have is an overwhelming interest in something accompanied by a desire to learn more and more about it. Parents should send questions and comments to dearteacher@dearteacher. com or ask them on the columnists’ website at. DECEMBER 2012 [ indy’s child ] 31 RAISING TEEN TWINS with AUTISM one local mom’s story Carrie Bishop girl. It’s heartbreaking,” Dugan said, noting that both Edward and Hannah are also diagnosed with depression. athleen Dugan, a professor of art at Anderson University, was 35 when she gave birth to twins Edward and Hannah. Life was good, but hectic and perhaps more difficult than Dugan had imagined. raising teens with autism Today the twins are fifteen and attend Noblesville High School. They’ve been through a smorgasbord of therapies including behavior therapy, hippotherapy, cranial sacral therapy, occupational therapy, speech therapy, cognitive behavior therapy, music therapy, social groups and others. . Dugan without doubt sees joy in her family life, but the reality is raising kids with autism is not easy. The disorder creates significant social deficits and as children grow and change so do society’s social codes. Social rules they learn during elementary years change in middle school, and again in high school, and again in adult life. It’s remarkably difficult for individuals with autism to understand the unwritten rules of communication and behavior and to integrate into a mainstream lifestyle. Dugan tells of a fellow middle school student who noticed Hannah sat alone every day and took it upon herself to strike up a conversation. The student may never know how kind her effort was, but Dugan says Hannah credits the girl with saving her life. It’s a poignant illustration of the fact that these kids see what is going on in the world around them. Hannah knew no one wanted to sit with her. She also felt on a very personal level to be an outsider looking in and it felt bad. Yet the average passerby may never have seen her sadness. As the babies became toddlers it was apparent Hannah had a language delay and did not know how to pretend play. Edward vehemently resisted transitions and found comfort in orderly things like alphabet charts. By age three the twins each received a diagnosis of autism. Though Dugan’s children are considered high functioning and tested perfect on a social skills test in fifth grade, they aren’t able to apply these skills in life. At fifteen Hannah still asks her mom to help her make friends. That was twelve years ago. “When they were little I could orchestrate playdates. Now they are teenagers and nobody calls them except one “I’ve often thought these kids who aren’t high functioning are taking in stuff but we don’t know what they know because we only measure things in language. They know more than we assume,” she said. This is one reason Dugan uses her artistic talents to paint kids on the spectrum. It is her attempt to show their fears, joys or other outward expressions that are fleeting at best. [ Portraits by Kathleen Dugan, capturing her children's joys and struggles ] 34 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 35 AU T I S M raising teen twins (continued) While school may be hard for Edward and Hannah, academics are not the problem. In fact both are in honors classes. Dugan says what’s hard for her children is the energy they spend coping with their disorder and trying to understand what other kids are talking about. For instance, Hannah gets annoyed with girls in her chemistry class who gossip while doing their work. She tries to keep up with the conversation, but rarely understands the social nuances of their chit chat. What she really wants is for them to focus on their work so everyone’s job will be easier. It’s exhausting and by the day’s end she needs a break. Dugan likens her twins’ experience of life to perpetually being at a cocktail party where they don’t know anyone and aren’t privy to the topics being discussed. It’s anxiety ridden and when put in that context, who wouldn’t agree? For this reason, their family spends most weekends and evenings at home. The twins just simply need downtime so they can spend their energy coping with school. Q&A [ BRANDED CONTENT ] q: a: q: a: q: a: I’m concerned that my toddler may be autistic. What should be my first step to help determine this? We know that parents who suspect their child may have autism are often confused and scared. Our best advice is to schedule a diagnosis evaluation as soon as possible, so parents can get a proper diagnosis and start making decisions from the perspective of “knowing” instead of “suspecting.” — Jerry Modlik, M.D.,The Applied Behavior Center for Autism down the road Like many parents Dugan worries if her children will be okay without her. There seem to be so many different types of therapy. How do I know which is the right one for my child? Applied behavior analysis (ABA) therapy has the best track record of scientifically demonstrating effective treatments for autism. By collecting “I think most parents want to believe their child will go on. That’s a big scary thing for a parent of a kid with autism. You have days you think they are okay and days you wonder if they are going to make it when you’re not around. As bright as some of these kids are, some have real struggles with things like self-help skills,” she said. In the near term, Dugan wants the twins to go to college, even graduate school. Academically she knows they are capable, but is less confident in their abilities to live in dorms. Maybe they will tackle college first, then see if they can live on their own. One thing at a time. data and tracking each child's progress, the therapists and behavior analysts can confirm the effectiveness of the treatment. — Jerry Modlik, M.D., The Applied Behavior Center for Autism What kind of support is available to me as the parent of an autistic child? I have a child with autism, and I understand the importance of early diagnosis and being able to surround yourself and your family with the a mother’s hope Whatever their future, Dugan hopes for real change in the way people view individuals with autism. “I know we are blessed that our kids have cognitive ability and language. But many people think autism is savant-like or the kids hardly speak. The truth is somewhere in between and the reality is your child is not a Rainman movie character or profoundly disabled. These children grow up and we mothers see the social disconnect of a world that says it tolerates diversity, but not on autistic terms,” said Dugan. As parents like Dugan speak out, hope is palpable for more tolerance and understanding of kids like Edward and Hannah. right support and additional therapy that is necessary. Our Center staff is an extension of your family. We also offer monthly support groups to connect you with other parents going through similar situations. Additionally, we can provide you with specific support that may be needed for you within the community since we partner with so many organizations. Once your child is diagnosed, it is so important to find high-quality treatment for your child and the whole family. — Jane Grimes, Enrollment Director, The Applied Behavior Center for Autism 36 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 37 special needs GUIDE GUIDE resources [ special needs listings ] Applied Behavior Center for Autism-KIDS, Email: jane@appliedbehaviorcenter.org,8449, Email: info@inautism.org, 7987 Oakbay Dr., Noblesvillle, IN 46062, Contact: Jane Grimes, 317-403-6705, jane.grimes@iasfoundation.org, Indianapolis Pediatric Dentistry Behavior Analysis Center for Autism BACA-5437, ext 112, Email: Prep Little Star Center--Early Learner Program (ELP)-5437, ext 112, Email: jane@appliedbehaviorcenter.org, Behavior Analysis Center for Autism BACA-Z-843-9200, Email: jpeterson@brainbalancecenters.com,,, Hopebridge Pediatric Specialists Autism Consultation,. Indiana Autism Scholarship Foundation Autism Society of Indiana 38 INDYSCHILD.COM We strive to improve the lives of everyone affected by autism in The Indiana Autism Scholarship Foundation’s mission is to provide scholarship funding to individuals in efforts to help offset costs for employment or college assistance for those affected with autism. DECEMBER 2012 [ indy’s child ] 39 special needs calendar Move to the Music Saturdays, Dec. 1 — Dec. 15 Times: 10:00 AM - 11:00 AM Price: $20 Phone: 317-573-5245 Location: Monon Community Center, Carmel For ages 8-14 12.12 sat | 08 Sensory Friendly Film: Rise of the Guardians sat | 15 Indy's Supported Typers Meeting tues | 04 2012 Conference for People with Disabilities and Community Advocates Times: 10:00 AM - 12:00 PM Location: AMC theaters throughout Indiana Sensory-Friendly Films are brought to you though a cooperation of the Autism Society of America and AMC Theatres. During these showings, the lights are halfway up and the sound is halfway down. Times: 4:00 PM - 6:00 PM Phone: 317-843-5566/ jsmyth@savedbytyping.com Location: 11550 North Meridian St., Conference Center, First Floor, Carmel Every month we get together to share with each other what’s happening in our lives, celebrate friendship, and enjoy the company of whoever wants to join us. We welcome professionals who work with people who are nonverbal to come and learn how meaningful this can be for the right persons. Phone: 317-843-9200 Location: Brain Balance Center, Indianapolis support groups tues | 04 Autism Family Resource Center Grandparents' Support Group Times: 5:30 PM - 7:30 PM Price: Free Phone: 317-882-1914 or 765-438-4792 Location: Easter Seals Crossroads, Indianapolis Times: 8:00 AM Price: Registration required Location: Westin Hotel, Indianapolis Join fellow advocates at the Indiana Governor’s Council for People with Disabilities’ 18th annual conference. This year's conference is themed Community Connections. Holiday Dance Times: 5:00 PM - 7:00 PM Price: $10 Phone: 317-573-5245 Location: Monon Community Center, Carmel Ages 13+ lectures & open houses tues | 04 This month, the Parents’ and Grandparents’ support groups will be combined. Brain Balance Parent Lecture Times: 6:00 PM Price: Free Phone: 317-843-9200 Location: Brain Balance Center, Indianapolis fri | 07 tues | 11 CALENDAR parents night out Easter Seals Crossroads Parent Night Out East location Easter Seals Crossroads- 4740 Kingsway Drive, Indianapolis, IN 46205. 1st and 2nd Friday of every month. South location Indian Creek Christian Church- 6430 S. Franklin Road, Indianapolis, IN 46259. 1st Friday of every month. Karaoke Night Times: 6:00 PM - 8:00 PM Price: $8 Phone: 317-573-5245 Location: Monon Community Center, Carmel Ages 13+ 2012 Accessible Technology Webinar: Mobile Accessibility Times: 2:00 PM - 3:30 PM Price: Free, registration required Phone: 877-232-1990 Location: Register online at. org/Webinar/AccessibleTechnology thurs | 06 Brain Balance Open House Times: 2:00 PM - 4:00 PM Price: Free 40 INDYSCHILD.COM DECEMBER 2012 [ indy’s child ] 41 TEN TIPS Carrie Bishop Less-Harried Holidays for Kids with Special Needs December is an amped up time of year. Between the decorating, gifting, hostessing and general mostesting, it can rattle the most jolly of souls. For kids with autism, anxiety or other special needs, this time of year can be downright daunting. FOR Be on time or early. Arriving early or right on time to the gathering, event or holiday outing can help families avoid some chaos. Bring a few of your child’s favorite things. Following are a few tips from area experts on how to calm the chaos for your child this December. Attending a party with lots of people, noise and expectations can be hard for many kids. Help your child cope by bringing a few of his or her favorite things such as a beloved blanket or iTouch. Take it one day at a time. “Focus on what’s going on that day versus stressing about what’s coming up in the future,” said Sheila Habarad, clinical director for Behavior Analysis Center for Autism in Zionsville. She says a lot of children don’t know what to expect at holiday gatherings or understand how long the event is going to last. Helping your child focus on that day’s activities may alleviate some anxiety. Enlist peers for support. Grimes suggests asking cousins who are patient and perhaps a little older to help show your child how to do activities others are engaged in or to just sit on the floor or at the table with your child playing a game or coloring. Plan the road ahead. Jane Grimes, enrollment director for the Applied Behavior Center for Autism, suggests planning out trips in advance so you can provide a visual schedule for your child on what things you are going to do as well as some pictures of the people your family will be visiting over the holidays. Get some shut eye. Life with a well-rested child is much saner than life with an unrested child. Parents know it. Kids know it. Stick to a sleep schedule and bedtime routine as closely as possible and looming chaos will be more controlled. Mind your sleep needs too. Prepare hosts. Be upfront with hosts about your child’s needs advises Mary Rosswurm, executive director of Little Star Center. If your child is likely to need a quiet place for refuge during an evening at auntie’s house, then ask auntie in advance if she can make a bedroom available to accommodate your child. Let her also know of any special nutritional requirements your child has so she can cook or cater in according to your child’s needs or you can bring along special food. Prepare so there is a plan in place before a crisis occurs. Have a sitter on speed dial. Sometimes your child is having a bad day. Sometimes the event is too overwhelming for the entire family to attend. That’s okay. If you are comfortable leaving your child with a sitter, then sometimes that is the best option for everyone. Relax. Prepare your child. “Read books about going to grandma’s house and engage in activities related to grandma’s house,” said Habarad. She suggests making grandma, or whoever is hosting the gathering, a present so your child and grandma will have something to talk about. 42 INDYSCHILD.COM “It’s not a teaching time. Don’t look at it as an opportunity to teach your child to play with his cousins. Just make it through the day. If he wants to play video games by himself let him. So many times as good parents we think we have to put on a show, but the holidays are not a great time. Everybody wants to make it out alive,” Rosswurm said. After all, it’s a parent’s holiday to enjoy too. DECEMBER 2012 [ indy’s child ] 43 Making Family a Priority HOLI DAY SEASON How One Local Mother Does It Katrina R. Holtmeier Life is busy. Sometimes you may feel like there aren’t enough hours in the day to complete your “to do” lists. The holidays can make packed schedules even more complicated. If you have trouble finding time for the most important people in your life, your family and friends, you are not alone. cookies and candies inspired by Lashua’s late grandmother. Enough goodies are made to fill about 50 tins to give to teachers, family, friends and coworkers. She said this not only reminds her of her grandmother, but it allows her to spend time with the most important people in her life. “I love accomplishing such a large task together and giving others a hand-crafted gift that has such a great inspiration One local mom has found a way to prioritize her goals and nurture her most important relationships throughout the holiday season. Tish Lashua, of Indianapolis, lives within eleven miles of downtown. She is a self-proclaimed holiday junkie who loves to reminisce about memorable holiday moments and gifts she’s received or given. During the holidays, she feels it is essential to spend as much time as possible with family because their love and compassion is so important. Lashua’s family also likes to visit downtown Indianapolis during the holiday season. There are several attractions from which to choose including the Circle of Lights Tree Lighting at Monument Circle, Christmas at the Zoo, Jolly Days Wonderland at the Children’s Museum, Celebrate the Season by the Indianapolis Children’s Choir and more. These events, plus light displays and holiday décor, get people in the spirit of the season, she said. “We are the witnesses to each other’s lives,” she said. “We make memories together, we learn from each other and we teach each other. We are comfort and security for each other, and we have a lot of fun together.” “I love the holidays because of what it brings out in people. There’s a giving nature that comes out in so many of us. It is beautiful to see that giving nature be so prominent,” Lashua said. From Thanksgiving to New Year’s Day, spend some time Lashua, 31, and her husband have four children. During the holiday season they have several family traditions they keep, including devoting one weekend to nothing but making Although her family spends a lot of time together, she said it is never enough and feels Christmas is a good time to both catch up and slow down. “I love to savor the life I have to think about what will make this holiday “the most wonderful time of the year” for your family. One of the greatest gifts of the holiday season, the article states, is the gift of time with family. to me.” According to a Penn State University web site article by Family and Consumer Science Educator Karen Thomas, research shows that families who spend time together are strong families who appreciate each other. Spending time as a family unit provides an opportunity to get to know each other better. These families communicate more and share a sense of belonging. A child who grows up in a family that spends quality time together learns that family is important and that they are loved. These things encourage personal growth and happiness as they grow older. and I try to teach my kids to do the same,” she said. “This does not mean I don’t almost lose my mind each year (buying) gifts, wrapping and delivering them, trimming a tree, decorating a home and attending event after event. But slowing down and savoring life and family is what I know is important each Christmas.” THIS DECEMBER 2012 [ indy’s child ] 45 INDY'S CHILD 12 DAYS ' L I K E ' OU R FAC E BO O K PAG E F O R YOU R C H A NC E T O W I N ! of giveaways — Celebrate with Thomas the Train: 3 DVD set — The Trash Pack: The gross gang in your garbage — Dub Garage Custom Rides: Beat Makerz — The Wotwots: Enchanting preschool series that follows the adventures of two adorable siblings from outer space, SpottyWot and DottyWot — Adventure time with Finn & Jake — My First Career Gear: Astronaut Each day we will post the daily giveaway and instructions on how to enter! Winners will be announced via Facebook & Email. — Sesame Street: Cone ‘n Play - Cookie Monster Kitchen Café — Kimochis: Toys with feelings inside — Baby Alive: Sips ‘n tinkles princess doll DECE MBE R 6th — Mini Fastback Set: Fun, safe and way good for the earth — The Wotwots: Enchanting preschool series that follows the adventures of two adorable siblings from outer space, SpottyWot and DottyWot — Toss the Pig: Toss him to your friends while the music plays — 'A Very Thomas Christmas' DVD — Fireman Sam: Holiday Heroes — Let’s Make Some Great Finger Paint Art, a book by Marion Deuchars — Rocktivity by Playskool: Rockin’ the stages of physical development DAY 1: DECE MBE R 10th — Julie Browning Bova Design, 12” x 12” Monogrammed Square Tray in English Red Floral: Gifts Collection available at shop.juliebrowningbova.com and fine retailers — Sunbeam: Velvet Plush Heated Blanket — Starry Night: Humidifier - Projector comforts your child by transforming the room into a starry night sky — A. Heirloom: State of Indiana shaped cutting board DAY 3: DECE M BE R 12th — Heely Skate Shoes Gift Certificate — The Wotwots: Enchanting preschool series that follows the adventures of two adorable siblings from outer space, SpottyWot and DottyWot — Little Passports: A Global Adventure — Dizzy Dancers: Poppy Pawz - Do you dare to dizzy — The Littlest Petshop: Trick or Talents Lizards - Little pets, BIG personalities — The Sesame Street Knitwits: Abby Cadabby hat — Mungi Bands: Magnetically connectable bracelets — Gelart- Paint & decorate peel off stickers — The Magic School Bus: Attracted to magnification magnets — Celebrate with Barney: 3 DVD set DAY 5: DECE MBE R 7th — Play-Doh Candy Cyclone: Create candies, lollipops, and more — Build a Bear Workshop Bear: Where best friends are made — The Wotwots: Enchanting preschool series that follows the adventures of two adorable siblings from outer space, SpottyWot and DottyWot DAY 2: — Pink Roses Keyboard Cover, For MacBook — PotteryBarn Kids Gift Basket DECE MBE R 11th — Scramble Bug: Foot to Floor Ride On — Koosh Galazy: Glow in the dark blasting with lights DAY 4: 46 INDYSCHILD.COM DECE MBE R 13th — Sunbeam: Mixmaster Stand Mixer — MXL Tempo USB microphone: Perfect for music, vocals, and podcasts — Smartswipe: Stops online credit theft in its tracks — Flexible USB notebook light: The brightest USB light for your notebook or computer — Dragon Naturally Speaking: Premium edition speech recognition software — Container Store Gift Basket — PS3 MiCoach-Train with the Best — Wired Headset-Studio engineered and professionally tuned acoustics DAY 6: — IKEA “Soft Toys for Education:” IKEA continues its long-standing partnership with UNICEF by helping to provide children with access to a quality education through the “Soft Toys for Education” Holiday campaign — Snuza Trio: 3 and 1 mobile baby monitoring system — Exederm Ultra Sensitive Skin Care: Sample Pack DECE M BE R 20th — Cluck ‘n’ Clack Game: Toss’ em fast before they blast — Tall-Stacker Mighty Monkey Playset: Versatile building and imaginative playset all in one — Puzzle Match Game: A fun memory game — Cube: Where visual illusions lead to confusion — Array: Splice, slice, splatter and slam your opponents right out of the game DAY 11: DECE MBE R 18th — Google Eyes: The family game of wacky vision — Mesh Hold It Vanity Bin: The leader in mesh — Blingles: Design bling to stick to anything — Benudiom: The wacky phrase-tastic game of mixed up meanings — Peppa Pig: Sip ‘n Oink Tea Set - Have a tea party with Peppa — Word Search: The multiplayer word search game — My Little Pony: Twilight Sparkle RC Car: Remote control action! Car moves forward and spins DAY 9: DECE M BE R 21st — Johnny Jump up: Doorway jumper — Playskool: Learn ‘n Pop Lion: Where unpredictable surprises can lead to discovery and learning — Nuk Expressive: Single electric breast pump — Rao's Lil' Chef: An adorable mini shopping cart holds one jar of Rao's new Sensitive Sauce — Baby Gift Basket: Filled with toys and books just for baby — My First Toy: Pink ballerina DAY 12: DECE MBE R 14th — Nerf & Fire Vision Sports: Lights out, game on — Haba: Terra Kids: Build your own wooden bug — Super Soaker: Electrostorm Powersoak up to 25 feet — Kre-O Battleship: U.S.S. Missouri - Build your own battle on land, sea or air — Bully Backpack: It’s like having a bodyguard with you all the time DAY 7: DECE MBE R 19th — Nerf: Vortex Lumitron - Glow-in-the Dark Disc Blasting — Beyblade Metal Fury: Gravitydefying battles inside Destroyer Dome — DS3 Games - Theatriythm: Final Fantasy, Heroes if Ruin, Jewel Master: Cradle of Rome — Bull Rush Competitive Deck: The Dojo Edition — Don’t Rock the Boat: Balance yer mateys or overboard ye go! DAY 10: DECE MBE R 17th — Exer Saucer: Jump and Learn - 45 fun learning activities — Sesame Street: Feel Better Elmo — The Original BA baby bottle holder for baby DAY 8: DECEMBER 2012 [ indy’s child ] 47 [ mommy magic ] commentary and parenting Christmas Magic It may not be what you think Mary Susan Buhner If I had one piece of advice for all moms this month it would be this: There is magic in imperfection, especially during the holiday season! Like many moms, I am in charge of making a lot of the holiday magic this month. I have to admit, I do love all the family traditions - baking cookies with my kiddos, trimming our Christmas tree together, all the special school Christmas programs. I love the “countdown of magic” in December! Knowing that my kids are growing up too fast, I try to embrace all the fun traditions like sprinkling “reindeer food” on our lawn and sending their Christmas letters to the “North Pole.” What I have learned, however, is that what I think is making an impression on my kids may not be what they define as “Christmas magic.” Case in point, every year that my husband and I have been married, we have gone to Lowe’s for our Christmas tree. It’s not very Norman Rockwell, I know, but we’ve always had good luck finding a decent tree that didn’t cost an arm and a leg. And each year, my husband has secured the tree on the roof of our car with twine, stringing the excess inside the car so it doesn’t flap around outside. One year, he handed the excess twine to my oldest daughter, who was three at the time, and jokingly instructed her to hold onto it to make sure the tree stayed on the roof. When she expressed her concern that she wasn’t strong enough for the job, we told her that her Christmas magic would give her strength. So she held on tight, and when we got home without incident, she said, overjoyed, that she couldn’t wait to do it next year. And so, year after year, we have loaded up the car and headed to Lowe’s for our tree, and each year our daughter has assumed this sacred responsibility, ultimately sharing it with her baby sisters. “Don’t worry,” she’d say, all big-sister authority. “Your Christmas magic will make the tree stay on.” And year after year, my husband and I have chuckled to each other as their white knuckles intensely grasped the twine. Okay, so fast forward to Christmas a few years ago. We have been going to Lowe’s a long time now. And nothing against Lowe’s, but I was ready to change it up a bit. So I spent weeks researching Christmas tree farms. I called, I Googled. I looked into every tree farm in the area to find the one that would yield the perfect Christmas experience for our family. After all, we had three kids by then; it was time to start the perfect family tradition! When I was satisfied that I’d done enough leg work, I announced with some excitement that we were going to start a new family tradition: picking out our Christmas tree at a tree farm. We would cut down our own tree, sip hot chocolate and have our picture taken with Santa’s reindeer. It would be the perfect Christmas tradition - the ultimate magical moment! In one second flat, my two oldest daughters dissolved into tears. “No, Mommy!” they begged, barely able to spit out their plea between their sobs. “We don’t want to go!” “What?” I said, shocked. I couldn’t make sense of the moment. Had they misheard me? Did they miss the bit about the hot cocoa and the reindeer? Did they not know about all DECEMBER 2012 [ indy’s child ] 49 my hard work, all my planning? “We want to go to Lowe’s and hold the twine!” wailed my seven year-old. My five year-old seconded that.“Yeah! We want to use our Christmas magic to keep the tree on the roof!” I was floored. Lowe’s, with its bright, fluorescent lights, its metal shopping carts and its vast parking lot, was perfect tradition to me , but total perfection to my children. So needless to say, we went back to Lowe’s to get our tree. Unbeknownst to me, a perfect Christmas family tradition had been born. So with that, I encourage you to take notice of how your kiddos view the holiday season through their eyes. Most of the time they could care less if the bow matches the wrapping paper or if the cookies are correctly placed on the “special” Christmas plate. In fact, what they store in their memory bank and remember when they get older is the magic of being together and creating memories in the first place. Join the Mommy Magic’s Fan Page on Facebook and visit to be a part of the mom community that supports and encourages moms in Indy with helpful tips for motherhood! Is HOMESCHOOLING R IGHT for YOU ? Brooke Reynolds The pros and cons of being your child’s primary teacher lthough a traditional school setting works for many children, the variety of educational choices currently available to homeschooled kids makes this form of education an attractive choice to many parents. Homeschooling now involves cooperative programs, tutors, librar y classes, online courses and even modified schedules with private schools - making this an increasingly popular option for families today. Although the choice to homeschool can be a tough one to make, many families who have committed to it have similar positive opinions about the experience. They find that homeschooling allows them to connect with their children and slow down to focus on what they think is most important., particularly for vacation times. learner with a ver y high IQ,” Rollison said. “He could not sit still when he was young. We just knew that if we put him in a formal education setting, they’d want to stop that behavior. We didn’t want them to stifle him. My goal is to help my kids reach their potential. With my son’s attention deficit disorder, I didn’t feel like it was possible for him to meet his potential in a government school because they’d concentrate on the ‘dysfunction’ of his ADD.” Since the early 1980s, homeschool numbers have continued to rise at an estimated seven percent per year, according to “The Histor y of Homeschooling in America” (sharefaith.com.) A method that was once considered a thing of the past has resurfaced and been re-established in the American culture. There's a strong group of homeschooling families Indiana, and the numbers continue to grow. Still, in traditional schools educators are professionally trained. Parents who homeschool must be realistic about their limitations when teaching their children. Other potential obstacles include time management as it is easy to overschedule activities or be too lax about routines. Homeschooling can also be expensive. Finally, parents who choose to homeschool frequently hear the concern that their children are not as socialized as kids who learn in a traditional school environment.. “I believe that the child and parent relationship, as well as the overall family dynamics, are important to consider when making a schooling choice,” Rebecca McGuckin, a teacher by degree and mom of four (two of which are homeschooled), said. Ober said she often laughs when thinking about the exhaustive Tracey Rollison, mother to three homeschoolers, chose to homeschool her kids before she was even married. While in a prelaw class researching the American governmental school system, she decided that commitment she’s made to homeschooling. “I must be out of my mind to decide to do this because I’m giving up the next 18 years of my life to be with my kids all day ever y day! It’s tough not getting to have ‘me’ time.” Leslie Ober said homeschooling just seemed like the most natural schooling choice for her because she was already a stay-at-home mom. “I would’ve never guessed that I’d homeschool, but it just naturally evolved to this because I’d been teaching them up to this point of their school-age days, so why wouldn’t I continue to be their teacher? ” homeschooling her children would be in her future. McGuckin agreed. “It is difficult not to place unrealistic expectations on myself in keeping a Once she had her son, Alec, she knew from his learning style that he wasn’t a fit for the public school system. “Our son is a global balance of maintaining a household and being the primar y source of their education. The house is not always as clean as I want it; I DECEMBER 2012 [ indy’s child ] 51 sometimes lose track of myself amidst the demands. Rare is the moment that I am not doing three or more things at once. School can sometimes turn into a task list rather than an educational journey. There are periods when I question whether I offer them enough, which is when having a supportive spouse can be particularly helpful.” have met these people at all had I not had the freedom to be part of those activities, some of which are during school hours. You just have to make the extra effort to stay friends – then you know it's a real friendship.” because my mom might be busy doing other things for our family.” “I like surprise field trips on Fridays to different places like Conner Prairie and the Children's Museum,” Charlie, 7, said. “There are more good things than bad things.” McGuckin’s children also shared their feelings on being homeschooled. Elizabeth, 10, said, “I like being able to spend time with my other homeschool friends. I also appreciate that my Even though homeschooling has its challenges, this type of education has its rewards. mom knows my strengths and weaknesses in school and that she is able to help me with those. I like the flexibility of being able to do school throughout the day while doing other With the array of schooling options available to children today, it is easy to become over whelmed with information and opinions. For these parents, not “following the crowd” and choosing to homeschool has worked for their particular children, family and lifestyle. McGuckin said she loves choosing curriculum and witnessing her children’s excitement about a particular topic. “It is rewarding to watch the entire process of introducing, exploring and allowing them to pursue more on their own. Meanwhile, I have the opportunity to share our values consistently through the materials we use, the conversations we have and the volunteer work we occasionally do. My kids work on their relationships more, so I also get to obser ve how well my children know each other.” activities. However, it's hard not getting the attention I want with three younger brothers around. When I'm stuck on something, I may not be able to get the help I want immediately Rollison’s children shared their own opinions about what it’s like to be homeschooled. Alec, 16, said, “"I like that I can learn what I want when I want. I can take the classes that I want to, even if they're college-level. A challenge of homeschooling is that you can get lazy and not do your work if you don't have someone making sure you do it.” Bella, 13, adds, “I like the freedom and the choices I have, and that I am not forced to be stuck in bad situations like some of my friends who are in government schools. Yet, it’s challenging to have other homeschool friends who live all over the place. That makes it hard to get together once the activity you're in together is over. On the other hand, I wouldn't 52 INDYSCHILD.COM [ pete gilbert...stay-at-home dad ] commentary and parenting These toys are better off left on the shelf True confessions of stay-at-home dad Pete Gilbert I want to talk to all of you toy shoppers that are buying toys for someone else’s kids. Sometimes a gift is more of a punishment than a blessing. Let me give you some examples. Hopefully this list will make you think twice while decking the halls this year. Glitter — Glitter glue. Glitter pens. Glitter on anything. Glitter is awful. As soon as the package is opened it’s on my kids, then MY hands, face, clothes, furniture, floor, walls, etc. No thanks. Stamping sets — Kids will stamp anything. First they use it correctly, then after the novelty wears off they stamp their skin, their sibling’s skin, the table, the walls and so on. Paint — See above. Drums — There’s enough noise in our house already, we don’t need something designed to make even more noise! Battery operated toys — Toys that sing. Hand-held video games. Remote control cars. These toys are great until it’s time to buy six AAA batteries for the controller and six D batteries for the car - every three weeks. Multiple piece sets — That doll set may look cool inside the packaging, but once opened, there will be tiny pointy pieces everywhere. And when it comes time to pick them up, I will miss one and find it with the bottom of my foot later that night. Large plastic items — We have a small house. Adding a 1/3 scale play kitchen to our existing kitchen does not help matters. Neither does adding yet another wheeled object to our garage. So what’s left? Instead of toys, think about purchasing an experience - like a gymnastics class, a movie or a live show. You can even take the kids and give parents the gift of time. But when all is said and done, I’m a sucker for the goofy grin of a child opening a gift and seeing just what they wanted. Even if it is a battery operated, glittery, full-size, plastic drum set. Happy Parenting! DECEMBER 2012 [ indy’s child ] 53 54 INDYSCHILD.COM WINTER FUN GUIDE The Bongo Boy Music School Indianapolis City Market ( 317) 595-9065 | WHAT: Get your drum on at the Bong Boy Music School! Every Thursday evening the school hosts a free, family drum circle. There’s no experience necessary. All ages are welcome. Drums will be provided. WHEN: Every Thurs. Evening—Pre-Jam begins at 6:45pm, Drum Circle from 7:00pm-8:00pm. Event Cost: FREE (317) 634-9266 | WHAT: Let the kids plan the menu! Make a list and head to the historic City Market to shop for the perfect meal. You are sure to find quality foods of all kinds, rich coffees, teas and authentic ethnic cuisine. Take a moment to find that last minute gift as the ICM boasts locally-designed jewelry, accessories, scented oils and fresh flowers. WHEN: Mon.—Fri. 6:00am—9:00pm, Sat, 8:00am—9:00pm, Closed Sun. ComedySportz IN State Museum and IMAX (317) 951-8499 | WHAT: Comedy for the whole family! ComedySportz is in its 20th year and is the longest running show in Indianapolis! Here’s how it works. Two teams compete for laughs. Not only are you the judge, you and your family are a part of the show! Think “Who’s Line is it Anyway” with a sporting twist. WHEN: Thurs. 7:30pm, Fri. 7:30 pm, Sat. 7:30pm and 10:00pm; First Sat. of the month — ComedySportz 4 Kidz at 4:30pm. Event Cost: Ticket prices vary. (317) 232-1637 | WHAT: Be “a-maized”at the scientific, economic and cultural significance and impact of corn on daily life when you visit the Amazing Maize exhibit. Discover the beauty and complexity of life as seen through the light of a microscope. If your fourth grader is studying Indiana History, visiting the permanent exhibits is a great way to extend classroom learning! WHEN: Mon.—Sat. 10am—5pm, Sun. 11am—5pm. Event Cost: Museum: $9.50 adults, $5 child, Members free. IMAX: $9.50 adult, $6.00 child (Museum and IMAX combo discounts available.) Conner Prairie (317) 766-6000 | WHAT: Join the fun during Winter Fun Days at Conner Prairie! Don’t let the post holiday blues get you down. Explore the science of baking and participate in a chocolate making demonstration. Test your winter frontier survival skills, enjoy a story by the fire, and find out what our animals do in the winter. WHEN: December 26—January 6. December hours of operation: Thurs.—Sun. 10am—5pm. Closed Mon., Tues. and Weds., 12/24, 12/25, and 1/1. Event Cost: $6.00 adult, $6.00 child ages 2-12, Members and children under 2 free. Royal Pin Leisure Centers (317) 465-8484 | WHAT: Bowling is a family bonding event. Now with programmable bumpers and easy to use ball ramps for small children, the whole family can compete and enjoy the sport! You’ll find many fun activities in addition to bowling at these locations. Don’t forget your socks! WHERE: Woodland Bowl: 3421 East 96th Street, Indianapolis, IN. Expo Bowling Center: 5261 Elmwood Avenue, Indianapolis, IN. Western Bowling Center: 6441 West Washington Street, Indianapolis, IN. Southern Bowling Center: 1010 US 31, Greenwood, IN Hamilton County Parks & Recreation The Soldiers and Sailors Monument WHAT: Climb to the top of Indianapolis’ most famous landmark, the Soldiers and Sailors Monument. Enjoy a 360 degree view of the city skyline from 275 feet in the air! You may climb the 331 steps, or take the elevator and then climb the remaining 31 steps. Visit the Colonel Eli Lilly Civil War Museum and gift shop housed in the base of the monument while you are there! WHEN: Weds.—Sun. 10:30am—5:30pm. Event Cost: FREE. WHAT: Winter hikes, birding, and maple sugaring, plus the Annual Race to the New Year 5k, Daddy Daughter Dance, pajama parties, volunteer opportunities and more. WHEN: Visit their website and click the Parks and Recreation banner to download the Winter Chatterbox Leisure Guide. A printed copy of all park events is available through February 2013. Guides are available at all park locations. Event Cost: FREE. Indianapolis Art Center (317) 255-2464 | WHAT: Experience the ArtsPark Sculpture Walk on the grounds of the Indianapolis Art Center, then venture indoors to view the student and professional exhibitions. View glass blowing, ceramic and other visual artists at work in the studios. Sign up for an art class before you leave! WHEN: Mon.—Sat. from 9am—6pm; Sun. noon—6 p.m. Closed December 24, 2012 – January 1, 2013. Open Skate Visit the following Indianapolis area websites or call to locate open skate times! Carmel Ice Skadium:; (317) 844-8888 The Forum at Fishers:; (317) 849-9930 Perry Park Ice Rink: (317) 888-0070 Indiana World Skating Academy:; (317) 237-5555 Arctic Zone IcePlex:; (317) 896-2155 WHEN: Times and ticket/skate rental prices vary for each facility. SPONSORED BY: DECEMBER 2012 [ indy’s child ] 55 calendar sat | 01 Ringling Bros. and Barnum & Bailey®: DRAGONS! Sat., December 1 and Sun., December 2 Times: See website for schedule Price: see website for ticket pricing Phone: 317-917-2500 Location: Banker’s Life Fieldhouse, Indianapolis Don't miss this once-in-a-lifetime family event when The Greatest Show On Earth brings the world together… to bring your family together! 12.12 Phone: 317-575-9588 ext. 105 Location: Meridian Music, Carmel This performance event will kick off a month long food drive benefiting Gleaners Food Bank.Meridian Music teachers and students along with other area music teachers and students will sign-up for recital time-slots. All performers and audience members will be asked to donate at least one nonperishable food item the day of the performance. mon | 03 Paws to Read at Eagle Times: 4:30 PM -. thurs | 06 Target Free Family Night: Toys and Traditions Times: 4:00 PM - 8:00 PM Price: Free Phone: 317-334-3322 Location: The Children's Museum, Indianapolis Learn about winter traditions from all over the world, the people who celebrate them, and the toys that help to make them special. Take a ride on the Yule Slide and visit Jolly Days. Sponsored generously by Target, the first Thursday of each month The Children's Museum opens free of charge from 4-8 p.m. tues | 04 sat | 08 Girl Scout Holiday Sing Times: 10:00 AM - 3:00 PM Price: $4 pre-sold ticket Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis Girl Scouts from across central Indiana are invited to come together at the Indiana State Museum for the 2012 Holiday Sing. Registration opens at 10 a.m. Girl Scouts are welcome to explore the galleries of the Indiana State Museum, meet Santa and Mrs. Claus and ride the Santa Claus Express in nostalgic Celebration Crossing. To register for this event visit the Girl Scouts of Central Indiana website at. The Nutcracker Ballet Times: 10:00 AM Location: Carmel Clay Public Library, Carmel Come to the library and experience the magical story of The Nutcracker, presented by the Indiana Ballet Conservatory. You’ll hear the enchanting story, watch costumed dancers perform a special part, and make a keepsake craft. Registration is required and begins Monday, November 26. For children ages 4-7. Community Tuesdays Time: Museum hours Price: ½ off general admission Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis On the first Tuesday of every month, receive half off general admission to the Indiana State Museum (does NOT include special exhibits) and $2 off tickets to the IMAX Theater. fri | 07 Central Indiana Dance Ensemble Presents The Nutcracker Fri., December 7 through Sun., December 9 Times: Fri., 7:30 PM; Sat., 2:00 and 7:30 PM; Sun., 2:00 PM Price: $22 for students (up to 18) and $30 for adults Location: Zionsville Performing Arts Center, Zionsville Become a part of the magic as Clara and her Nutcracker Prince battle mice and the evil Rat King and journey through the Land of Snow. Join us for our Sugar Plum Fairy Dessert Parties before each matinee show, which feature a picture with a cast member, dessert, and a craft. sun | 02 Journey Through Eastern Europe: Romanian Folk Masks Times: 2:00 PM Price: Free Phone: 317-275-4470 Location: Nora Library, Indianapolis As part of the Library's series celebrating the diversity of East European cultures, languages and people, children ages 5 and up and families are invited to explore Romanian folk tales and sculpt their own mini mask puppet using a variety of materials during this two-hour program. weds | 05 Fishers Parks and Recreation: Pictures with Santa Weds., December 5 and Thurs. December 6 Times: 6:00 PM - 7:30 PM Price: Free Phone: 317-595-3150 Location: Fishers Town Hall, Fishers recreationoffice@fishers.in.us A beloved holiday tradition returns again this year. Your children can have their pictures taken free with Santa Claus while they share their Christmas list for this year. For all ages. sun | 09 Central Library's 5th Anniversary Celebration Price: Free Phone: 317-275-4100 Location: Central Library, Indianapolis Activities will include a scavenger hunt, mystery tours, photo booth, digital programs for children, historical displays, prize drawings and birthday cake for all! Also on December 8. 5th Annual Music Marathon Food Drive Fri., December 7 and Sat., December 8 Times: Fri., 3:30 PM onward; Sat., 8:00 AM onward Price: Donation of non-perishable food items 56 INDYSCHILD.COM mon | 10 Jingle John and Santa's Helpers Times: 6:30 PM Price: Free Phone: 317-535-6206 Location: JCPL Clark Pleasant Branch, New Whiteland Get into the holiday spirit with a visit from Jingle John the Elf, his animal friends from the North Pole, and a special appearance from another of Santa’s elves in the Reindeer Reserves! thurs | 13 Candy Cane Hunt Times: 4:00 PM and 5:00 PM Price: R$4/NR$6 Phone: 317-595-3153 Location: Billericay Park, Fishers Despite his busy winter schedule, it is rumored that Santa is going to hide hundreds of candy canes around Holland Park! Join us as we search for hidden candy canes. Afterward, warm up with hot cocoa while completing a craft! For ages 6-10 and a parent. Registration required by 12/6. (bring a flashlight). sat | 15 5th Annual Christmas on the Farm Times: 9:00 AM - 2:00 PM Price: Free admission Phone: 317-733-1700 Location: Traders Point Creamery, Zionsville Christmas on the Farm is a holiday extravaganza for the whole family. Sleigh-hayrides around the farm, live music and caroling, craft-making opportunities for the kids (not to mention the visit from Old St. Nick) and a Green Market that is chock-full of fun holiday gift ideas for the stocking stuffers in all of us. tues | 11 Chanukah: Celebration of Lights Times: 4:30 PM Price: Free Phone: 317-878-9560 Location: JCPL Trafalgar Branch, Trafalgar Chanukah begins on December 9 and lasts through December 16. Join us to learn about the history of this ancient Jewish holiday, sample a few latkes, and play a game of Dreidels. fri | 14 Christmas with Santa and the Ponies sun | 16. weds | 12 Fri. December 14 through Sat., December 15 Times: 4:00 PM - 8:00 PM Price: $20 donation Phone: 317-838-7002 Location: Strides to Success, Plainfield Create a great memory for the family and give back to the community. Enjoy a visit with Santa, family photo with Santa and a Christmas Pony, crafts, games and refreshments. The proceeds raised from this event will contribute to the Strides scholarship fund that supports programs for victims of abuse. mon | 17 Kid's Cooking Times: 4:30 PM Price: Free Phone: 317-885-1330 Location: JCPL White River Branch, Greenwood Learn the basics of cooking safety and then help make some tasty treats at each of these sessions! Kid-friendly microwave and no-bake recipes only. Yum! Location: Monon Community Center, Carmel Jump on the literacy train for a fast-paced, interactive mix of stories, rhymes, and songs paired with a simple craft. Each week has a different theme and younger siblings are welcome. Ages 2-5. Celebrate Hanukkah, Christmas, or Kwanzaa on a Dime! Angels Sing Fri., December 14 and Sat., December 15 Times: Fri., 8:00 PM; Sat., 3:00 PM and 8:00 PM Price: $12 in advance through the ICC; at the door $13 students, senior, military, $15 general Phone: 317-846-3404 Location: St. Luke's United Methodist Church, Indianapolis Enjoy the angelic voices of the children of the Indianapolis Children's Choir singing traditional songs you love and music from a variety of celebrations! Includes a brass quintet, string quartet, percussion, piano, and Martin Ellis on the organ. weds | 19 Times: 4:00 PM Phone: 317-844-3363 Location: Carmel Clay Public Library, Carmel For children in grades 1-3. Storytime Room. Touch their hearts (but not your wallet) by making a homemade gift! Registration is required and begins Wednesday, December 5, online, in person, or by calling 844-3363. Christmas Cookies and a Story Times: 1:00 PM - 2:00 PM Price: R$10/NR$15 Phone: 317-595-3150 Location: Roy G. Holland Memorial Park, Fishers Children will use Christmas-themed cookie cutters to create their own cookies out of cookie dough While they bake, we will read Christmas stories. Next, we will design the cookies with red and green frosting and sprinkles. For ages 3-6. Register by 12/12. tues | 18 Storytime Express Times: 11:00 AM - 11:30 AM Price: Free Phone: 317-843-3869 DECEMBER 2012 [ indy’s child ] 57 thurs | 20 IMA Winter Solstice Celebration Times: 5:00 PM - 8:30 PM Price: Free Phone: 317-923-1331 Location: Indianapolis Museum of Art, Indianapolis Celebrate the Winter Solstice with ice carving demonstrations, art making, drumming, bonfires, and live music. Hot chocolate and holiday treats will be available for purchase. Location: Franklin Road Library, Indianapolis Children of all ages and families are invited to have their pictures taken with Santa and meet some of Santa's friends during this event sponsored by the Franklin Township Chamber of Commerce. Phone: 317-232-1882 Location: Indiana Historical Society, Indianapolis Enjoy family-friendly crafts and activities, face painting and special performances each day from jugglers, magicians, dancers and musicians. Winterfest runs through January 5. sun | 30 Mystery Lunch for 7–10 Year Olds Times: 1:00 PM - 4:00 PM Price: $18/person + tax & gratuity Phone: 317-638-7881 Location: The Indianapolis Propylaeum, Indianapolis Children work as a group with actors through a series of games and quizzes to find a lost object, all the time enjoying a lovely lunch. This is an opportunity to create a great memory, do something fun, and solve a mystery. sun | 23 Santa's Holiday Breakfast Times: seatings at 9:00, 9:30, and 10 AM Price: $26.50 Adults, $16.00 Child ($20/$12 for members) Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis Once you’ve enjoyed your buffet meal, visit Santa at his holiday home, participate in the many holiday themed activities throughout the galleries and ride the Santa Claus Express train in Celebration Crossing. The breakfast also includes gift bags for children and museum admission. thurs | 27 A Magic Tea for Children Times: 1:00 PM Price: $18 adults; $9 youth (under 12) + tax & gratuity Phone: 317-638-7881 Location: The Indianapolis Propylaeum, Indianapolis The Propylaeum Teas for Children include an etiquette lesson, a craft activity, finger sandwiches, tea treats, and special teas. A great opportunity for fun over the holiday break. Reservations required, 638-7881. Indianapolis Colts vs. Houston Texans Times: 1:00 PM Price: see website for ticket pricing Phone: 317-262-3452 Location: Lucas Oil Stadium, Indianapolis Come cheer on your Colts as they take on the Houston Texans! Christmas Eve Free Admission mon | 24 fri | 28 Friday Family Fun: Craft Closet Cleanout Times: 2:00 PM Price: Free Phone: 317-535-6206 Location: JCPL Clark Pleasant Branch, New Whiteland It’s the end of the year and we need your help cleaning out our library craft closets. We’ll pull out lots of leftover crafts for some creative fun! mon | 31 Countdown to Noon Times: 10:00 AM - 1:00 PM Price: Included with museum admission Phone: 317-334-3322 Location: The Children's Museum, Indianapolis Celebrate the final day of 2012 at The Children's Museum of Indianapolis with activities, music, and a Water Clock countdown to noon that will allow families to experience the excitement of a countdown at a reasonable hour for the young ones. fri | 21 Preschool Drop-In Craft: On a Holiday Note Times: 10:00 AM - 11:30 AM Price: Free Location: Carmel Clay Public Library, Carmel For children ages 2-5 & their caregivers. Drop by the Storytime Room to create a handmade card. No registration is required. Times: 10:00 AM - 2:00 PM Price: Free Phone: (317) 334-3322 Location: The Children's Museum, Indianapolis In celebration of the season, The Children’s Museum presents a free admission day on Christmas Eve from 10 a.m.-2 p.m. Children are invited to visit Jolly Days to get in those last-minute requests with Santa before he leaves for his big night! sat | 29 Family New Year's Event Times: 6:30 PM - 9:00 PM Price: $11 for non-members/$6 for members Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis End the year with a bang with a family-friendly alcohol-free celebration in the Governor Frank O'Bannon Great Hall. Face painting, stilt walkers, clowns and music by Indianapolis band The Tides highlight the evening. A balloon drop at 8 p.m. allows the little ones to celebrate the New Year in style. tues | 25 Colors of Combustion Times: 11:00 AM - 1:00 PM Price: $2 per person plus museum admission Phone: 812-337-1337 Location: WonderLab Museum, Bloomington Witness the vibrant chemistry and energy of fire at this live science demo where YOU are part of the show! Seats are available on a firstcome, first-served basis the day of the show. Merry Christmas! sat | 22 Pictures With Santa Times: 11:00 AM - 2:00 PM Price: Free Phone: 317-275-4380 weds | 26 Winterfest begins Times: 10:00 AM – 5:00 PM Price: See website for pricing 58 INDYSCHILD.COM ongoing events 12.12 St.Vincent Health presents A Christmas Carol Daily.. at IndysChild.com Experience a daytime winter romp through 1836 Prairietown as you enjoy the holidays the 1830s way! ON THE WEB > find more! Jingle Rails: The Great Western Adventure Daily Through Sunday, January 6 Times: During museum hours Price: Included with general admission Phone: 317-636-WEST Location: Eiteljorg, Indianapolis. Trumble the Train Saves the Day Saturdays, December 1, 15 and 22 Times: 10:30 AM and 1:00 PM Price: $2 per adult; $1 per child Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis Trumble the Train Saves the Day is an engaging, interactive holiday musical for pre-school and elementary-age children and their families. The 20-minute musical follows the action in the mythical village of Celebration Crossing as Trumble the Train enlists the help of his friends. Christmas at Lilly House Daily through Sunday, January 6 Price: Free Phone: 317-920-2659 Location: Indianapolis Museum of Art, Indianapolis Lilly House will be decorated in the style of the 1930s and 1940s, when Christmas cheer often had to overcome Depression-era budgets or wartime shortages. Familiar motifs such as trees, wreaths and evergreens are enlivened with refreshing touches of new fashions in this historic home. Open during Museum hours. Duke Energy Yuletide Celebration Friday, November 30 through Sunday, December 23 Phone: 317-639-4300 Location: Hilbert Circle Theater, Indianapolis Featured acts include Twas the Night Before Christmas, The Enchanted Toy Shoppe featuring Cirque de la Symphonie, songs from Elf: The Musical, the tap dancing Santas and much more! See website for schedule and ticket pricing. Christmas at the Zoo Wednesdays — Sundays,. 1836 Daytime Outdoor Adventure Saturdays, December 1 through Saturday, December 22 Times: 10:00 AM - 5:00 PM Price: $12/adult; $9/youth (ages 2-12) Phone: 317-776-6000 Location: Conner Prairie, Fishers A Beef & Boards Christmas Thursday, November 29 through Sunday, December 23 Phone: 317-872-9664 Location: Beef and Boards, Indianapolis DECEMBER 2012 [ indy’s child ] 59 Beef & Boards celebrates in style with its annual crowd pleaser. A glittering string of music and dance numbers, presented in a variety show format, create the perfect holiday tradition. Bring a group, bring the family, just don't miss it! See website for schedule and ticket pricing. School and community choirs, bands, ensembles and soloists perform holiday music in the museum's Governor Frank O'Bannon Great Hall each day. Enjoy the sounds of the season in a spectacular holiday atmosphere. See website for schedule. from jugglers, magicians, dancers and musicians. Visit to learn what is in store each day. Radio Disney is here to entertain the crowd Dec. 28 from 1 to 3 p.m. with games, prizes and music. The Stardust Terrace Café is offering kid-friendly snacks and lunches throughout Winterfest. Outdoor Winter Weekends Christmas at the Puppet Studio Tuesday, December 11 through Saturday, December 22 and Thursday, December 27 Price: $10; under two, free Phone: 317-917-9454 Location: Peewinkle’s Puppet Studio, Indianapolis This 45-minute Christmas variety show is filled with music and lots of audience participation. A perfect event to put the whole family into the holiday spirit. Optional post-show workshops $3 (available on Saturdays, Sundays and Noon time shows only). See website for schedule. Saturday, December 15 through Sunday, December 23 Times: 11:00 AM - 4:00 PM Price: $25 for adults/ $11 for children Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis One of the best parts of winter is being able to play outside in the snow. Come visit the museum and enjoy our Outdoor Winter Weekends right outside the museum on the White River State Park canal, snow or no. Families can play games, make outdoor ornaments, sit by the fire and even purchase a s'more making kit.! Conner Prairie by Candlelight Fri & Sat December 7 through Saturday, December 22 Times: Staggered tour start times from 6-9 p.m. Price: See website for ticket pricing Phone: 317-776-6006 Location: Conner Prairie, Fishers Visit different homes in Prairietown. Candlelight Tour Reservations: call 317.776.6006 or 800.966.1836.. Winter Fun Days Wednesday, December 26 through Sunday, January 6 Times: 10:00 AM - 5:00 PM Price: $12/adult; $9/youth (ages 2-12) Phone: 317-776-6000 Location: Conner Prairie, Fishers Avoid the post-holiday blues with some wintertime fun! Explore the science of baking and participate in a chocolate making demonstration. Test your winter frontier survival skills, enjoy a story by the fire and see what our animals do in the winter. Winterfest Wednesday, December 26 through Saturday, January 5 Times: 10:00 AM – 5:00 PM Phone: 317-232-1882 Location: Indiana Historical Society, Indianapolis Enjoy family-friendly crafts and activities, face painting and special performances each day NOTE: At Indy's Child, we work hard to ensure our calendar and guide information is accurate. Occasionally event specifics change after we go to press. Therefore, we encourage our readers to call locations or visit them on the web to verify information. Holiday Sounds Monday, December 10 through Saturday, December 22 Phone: 317-232-1637 Location: Indiana State Museum, Indianapolis 60 INDYSCHILD.COM marketplace ENTERTAINMENT + SERVICES + CHILDCARE + STUDIES + CLASSES... AND MORE CHILDCARE SERVICES INDY'S CHILD ENRICHMENT SERVICES CONTACT US ENTERTAINMENT DECEMBER 2012 [ indy’s child ] 61 marketplace (continued) DEVELOPMENT STUDY food RESEARCH STUDY ENRICHMENT PARTY PLANNING birthday party GUIDE INDY'S CHILD 62 INDYSCHILD.COM fun+wacky INDY'S CHILD sun 12.12 fri sat 1 Who's Your Hero? Start submitting your videos today! Visit facebook.com/ peytonchildrens to learn more. mon tues weds thurs how to celebrate: help your mom or dad make homemade how to apple pie celebrate: for volunteer at a dog dessert shelter today! mutt day 2 apple pie day 3 dice day 4 5 how to celebrate: get the family together to play a game after dinner on this day Walt Disney was born in 1901 MIC WAVE OVEN RO 6 HANUKKAH on this day begins at Japan attacked Pearl sunset! Harbor in 1941 CE 14 CRE AM DA 7 8 Y DA on this day 9 Ball-Bearing Roller Skates were patented in 1884 dewey decimal system day 10 how to celebrate: head to the library to check out some of your favorite books how to celebrate: holiday spirit find some fun colored and get noodles to make some crafts gingerbread day noodle house how to ring day celebrate: get in the 11 12 cocoa day 13 bill of rights day how to celebrate: see if you can name all ten amendments of the U.S. Constitution 15 Y chocolate covered anything day how to celebrate: try your hand at some chocolate covered strawberries! 16 17 wright brothers' day how to celebrate: have some fun making paper airplanes answer the phone like buddy the elf day! 18 OAT ME AL MUFFIN 19 20 I games day how to celebrate: first day of winter how to celebrate: 21 on this day 22 DAY 26 invite friends over for a bundle up and head whole night full of fun and outside to make snow games angels the first Christmas lights went up for sale in 1882 this day 29 on return to your roots day 30 23 egg nog day 24 ME RR Y CHRISTM 25 AS First day of KWANZAA! visit the zoo day how to celebrate: bundle up and head down to the festival of lights! 27 28 bacon day NEW 31 YEARS EVE! on this day chewing gum was patented in 1869 the bowling ball was invented in 1862 Sources: familycrafts.about.com, brownielocks.com, holidayinsights.com, zanyholidays.com & thenibble.com ! DECEMBER 2012 [ indy’s child ] 63
http://issuu.com/indyschild/docs/1212-ic-issuu
CC-MAIN-2015-18
refinedweb
18,525
61.87
TypeScript has become a mainstay of modern web development libraries. Consuming functions and widgets written by a third party can be error-prone without some type of guidance. Introducing static typing to the interfaces doesn’t just reduce misuse, it has added benefits including intelligent code completion. Dojo Toolkit is one of the earliest libraries to facilitate the building of large, dynamic, interconnected single-page applications. Above and beyond the tools for loading and storing data, managing events, and working with the DOM, it provides a diverse set of widgets through Dijit. Is TypeScript something the Dojo Toolkit can benefit from even though it was written before TypeScript existed? Luckily for us, the designers of TypeScript have made this possible through tools we’ll be looking at in this post. Introducing TypeScript to Your Project To help our project evolve from JavaScript to TypeScript, we need a good place to start. Take a look at the example Dojo Toolkit application that we’ll be using in this post. We will need just two things to start integrating TypeScript into our project: the TypeScript compiler and a configuration file. Installing the TypeScript Compiler We’ll be using the TypeScript compiler for performing compile-time type checking, and eventually for turning our TypeScript files into JavaScript. Installing the TypeScript compiler is easy, we simply install typescript as a devDependency. npm i -D typescript The TypeScript Configuration File Now that the TypeScript compiler is installed, we need to configure it to work with our application. Create a new file called tsconfig.json in the project root with the following contents: { "compilerOptions": { "allowJs": true, "checkJs": true, "esModuleInterop": true, “noImplicitThis”: true, "lib": [ "dom", "es2015", "scripthost" ], "module": "amd", "outDir": "build/src/demo/", "removeComments": false, "target": "es5" }, "include": [ "./src/**/*.js", "./src/**/*.ts" ] } You can read about the full extent of the tsconfig.json file options, but the interesting ones for this post are allowJs, checkJs, and esModuleInterop. allowJs– Allows JavaScript files to be compiled. We need this right now because our entire app is written in JavaScript. checkJs– Reports errors in JavaScript files. We can have TypeScript perform type checking on our original JavaScript files, possibly surfacing some application bugs before we even make any code changes! esModuleInterop– Enables compatibility with the dojo loader. With these two pieces in place, we can now try to compile our project using the TypeScript compiler! From your project root, run the compiler. ./node_modules/.bin/tsc Uh oh! Looks like we have a few errors. src/demo/index.js:1:1 - error TS2304: Cannot find name 'define'. 1 define([ ~~~~~~ src/demo/widgets/Hello.js:1:1 - error TS2304: Cannot find name 'define'. 1 define([ ~~~~~~ TypeScript doesn’t know anything about the Dojo Toolkit, so it’s not sure how to proceed here. Ambient Declarations TypeScript is designed to be used with existing JavaScript libraries. To do that, you need to tell it something about those libraries. These types of definitions are called “ambient declarations” and usually end with .d.ts. Ambient declarations do not produce any code output and instead are simply there to inform TypeScript about the types and APIs of other code. The Dojo Toolkit provides ambient declarations in the form of the dojo-typings package. Simply install this package as a devDependency: npm i -D dojo-typings Then, include the files in your tsconfig.json file by adding them to the include key. { "include": [ "./node_modules/dojo-typings/dojo/1.11/modules.d.ts", "./node_modules/dojo-typings/dijit/1.11/modules.d.ts", "./node_modules/dojo-typings/dojo/1.11/loader.d.ts", "./src/**/*.js", "./src/**/*.ts" ] } Note that we’ve included three different ambient declarations (the .d.ts files): dojo/1.11/modules.d.ts– Ambient declarations for Dojo 1.11 diijt/1.11/modules.d.ts– Ambient declarations for Dijit 1.11 dojo/1.11/loader.d.ts– Ambient declarations for the loader to give us access to require and define. Running the TypeScript compiler now should yield better results. ./node_modules/.bin/tsc Success! We’ve now got some basic TypeScript type checking for the Dojo Toolkit implemented, but soon we’ll really see the power of type checking when we transition our project to TypeScript. Transitioning Loaders TypeScript does not understand Dojo’s module loader, so we need to transition our code to use ES module syntax instead. TypeScript will then be able to look at our imports and determine the types from them. In our case, it will be able to enforce the types of Button, TextBox, etc. Take a look at the top of Hello.js: define([ "dojo/_base/declare", "dojo/dom-construct", "dijit/_WidgetBase", "dijit/form/Button", "dijit/form/TextBox" ], function( declare, domConstruct, _WidgetBase, Button, TextBox ) { return declare([_WidgetBase], { // ... Using ES module syntax, that would look like: import declare from "dojo/_base/declare"; import domConstruct from "dojo/dom-construct"; import _WidgetBase from "dijit/_WidgetBase"; import Button from "dijit/form/Button"; import TextBox from "dijit/form/TextBox"; export default declare([_WidgetBase], { How can this be compatible with Dojo Toolkit you wonder? Go ahead and compile the project (you’ll see some errors, but we’ll deal with those in a bit) and open up build/src/demo/widgets/Hello.js. var __importDefault = (this && this.__importDefault) || function (mod) { return (mod && mod.__esModule) ? mod : { "default": mod }; }; define([ "require", "exports", "dojo/_base/declare", "dojo/dom-construct", "dijit/_WidgetBase", "dijit/form/Button", "dijit/form/TextBox" ], function (require, exports, declare_1, dom_construct_1, _WidgetBase_1, Button_1, TextBox_1) { // ... You’ll notice right away that our imports were turned into a call to define that looks a lot like our old define call! TypeScript knows we want to use AMD modules (from our tsconfig.json file) and automatically converted our imports into an appropriate define call. That’s some powerful stuff right there. Type Safety With our imports in place, TypeScript can read the types and enforce some type safety rules. You may have noticed that we’ve now got compile errors. Because TypeScript knows that our widget extends from _WidgetBase, it knows what properties are available and which ones are not. If we try to use a property that isn’t part of _WidgetBase or our extension, we’ll see an error about the property not existing – just like what we are seeing with nameInput. To fix this, we simply need to define the nameInput property and tell TypeScript (via JsDoc) what type it is. Add this above the buildRendering property: nameInput: /** @type TextBox */ (undefined), With our build errors taken care of, let’s take a quick inventory of the type safety we’ve got in Hello.js right now. - Accidentally using a variable that doesn’t exist will create a compile-time error. So if we type this.nmeInputby mistake, we’ll get an error right away. - We’ve got autocomplete (most IDEs support this)! Now that TypeScript knows what types things should be, typing domConstructor this. will provide you with an autocomplete list that is specific to that type. - We’ve got additional type safety on Dijit constructor parameters. Since TypeScript knows what TextBox({ ... })should accept, if you try to type in a property that hasn’t been defined in the types, you’ll get a compile-time error. These are all huge wins, but can we actually migrate our JavaScript files to full-on TypeScript files for an even bigger payoff? .js to .ts Type checking on your JavaScript files is a powerful feature, but eventually you’ll want to take full advantage of everything that TypeScript has to offer. TypeScript files do not rely on JsDoc and offer far more expressive types, allowing the compiler to analyze your code even further. Your end goal should be to transition your JavaScript codebase to a TypeScript-first code base. Rename Your Files The first step is to rename your files to .ts instead of .js. Once TypeScript sees the .ts extension it knows it can expect special TypeScript syntax and make certain assumptions about your code. Rename Hello.js to Hello.ts to begin the conversion. You’ll notice that the project still builds, even though we haven’t changed anything but the file extension. This is because .ts files try to be backwards compatible with .js files as much as possible. Update Your Types With JavaScript files, we used JsDoc to specify types. With TypeScript files, we’ll be able to use TypeScript specific syntax. Let’s update our nameInput property to be typed via TypeScript. nameInput: undefined as TextBox | undefined Here we are declaring that nameInput is undefined, and we expect it to contain either nothing (undefined) or an instance of TextBox. This is a simple example, but TypeScript offers an incredibly wide and advanced set of types that are now at your disposal. Your Project: What’s First? Converting our example app to TypeScript is one thing, but how do you convert a real-world project. Where do you even start? Critical Business Logic Some modules are more important than others. When you’ve got a module that is critical and should not be misused, converting the module to TypeScript is a great way to enforce that the module is used correctly. Modules with few dependencies Modules with few dependencies are a great place to start your conversion to TypeScript. To use the ES import syntax, TypeScript needs to know about the module being imported. That means it either needs to have ambient declarations or already be a TypeScript file. Potential Issues Mapped Libraries You may be using a third-party library that you can’t find types for. In this case, you might have to write your own ambient declarations. Writing these is outside the scope of this post, but you can find plenty of tutorials on this subject. Start small and only implement the parts of the API you are using, and then build from there. Next Steps Upgrading your project to TypeScript is a great step toward using modern web technologies. Once there, you might want to consider going even further. TypeScript and ESLint You can use ESLint and TypeScript together to perform additional checks that are only possible because of the extra type information added by TypeScript. For example, some of these rules can assure that you are not specifying a type you don’t have, or that you always have to specify a type and you should not rely on inferred types. Webpack The TypeScript compiler will output each of your TypeScript files as individual JavaScript files. While this is OK for your existing build system, loading all of those individual files can be inefficient on the browser. Webpack can take your TypeScript (and JavaScript) files and create one or more bundled versions that you serve to your users. These bundles are smaller and more efficient than loading individual files. With some additional plugins, Webpack can use the TypeScript compiler without ever creating intermediary JavaScript files during the build. There is even a dojo-webpack plugin to build Dojo Toolkit applications using Webpack. Conclusion In this post, we’ve seen how to take a Dojo Toolkit and Dijit project and incrementally convert it into a TypeScript project. We’ve also seen some of the advantages of TypeScript and where we can go from here. Hopefully this post has inspired you to start converting your own projects to TypeScript.
https://www.sitepen.com/blog/progressively-adopting-typescript-in-a-dojo-toolkit-application
CC-MAIN-2021-10
refinedweb
1,884
56.66
Not too long ago, I had to design and implement a kind of a load balancer system for an existing application. The platform being .NET, the choice was of course .NET Remoting. I had written several little client-server applications using remoting before, so I was aware of the mechanism and the different techniques in remoting. After some planning, shortly I started coding. The servers (nodes) that hosted the application had to be able to be controlled remotely, I mean to start and stop them at least. Starting a server node, it registered a channel on a specific port, and also registered a type (NodeManager) as a singleton WellKnownSeverType. The whole node was controlled through this singleton object. On calling its start method, it created a new appdomain and registered another channel, and the application type as a SingleCall type. This was actually a requirement that the application type should be a SingleCall. So, the node came to a running state, and the client requests were serviced in this new appdomain. Everything just went properly, until I started implementing the stop method of the NodeManager class. NodeManager WellKnownSeverType Under stopping I mean, to stop the service without terminating the process, so that clients can’t invoke methods on the application objects, but it can still be controlled, thus started again through the NodeManager object which is still available. So, on stopping, it had to unload the new appdomain hosting the application objects, but I wanted to implement a mechanism that first waited until the requests being processed at that time finished properly, but any other new requests to the application objects had to be rejected of course. There is an object called DomainManager in a separate appdomain that hasn’t been covered yet. When the NodeManager is controlled to start the service, it creates the new appdomain (servicedomain), and creates a new DomainManager object in this new appdomain, and call its Start method. This Start method then registers the remoting channel on a specific port, and also registers the application types as SingleCall. At this point, the application objects are reachable by clients and serving requests in this service appdomain. When we tell the NodeManager to stop, it calls a Stop method on the DomainManager that should somehow make the application objects unreachable, without interrupting the current requests under processing. Therefore, unloading the service appdomain immediately is not enough, because a ThreadAbortException is thrown on all threads operating in the appdomain being unloaded, and our current requests would terminate. DomainManager Start Stop ThreadAbortException Besides, to have one DomainManager object in each appdomain is always nice if you have to deal with more appdomains, but note that DomainManager must be remotable (MarshalByRefObject), as it receives cross appdomain calls. MarshalByRefObject Now, I’m going to cover a few techniques that can be useful if you are implementing a service in .NET Remoting, and planning to add ability to be stopped without terminating the service host process. What to do in the above situation was to just simply unregister the channel in the appdomain, causing the TCP port to stop listening, so clients couldn’t connect anymore, and to somehow count how many requests are being processed currently which is detailed later. When this counter reached zero, the new application domain could be unloaded. So the server got stopped, without interrupting any requests currently under processing. The first thing I realized was that after unregistering the channel, some clients could henceforward invoke methods on the application type. Yes, this is because remoting services cache the connections, and closes only if the timeout elapsed. Therefore, if the server is under a heavy load, clients invoke methods very frequently on the application objects, the sockets don’t timeout, and thus stopping the server can last for a long period of time. And the requirement, that it should reject any new requests, will not be met. Of course, we have no control over this socket cache, so we can not force to close those connections immediately, but I read somewhere that, in .NET 2.0, the timeout period will be adjustable, and setting it to zero will have the connections closed just after a remote method call finished. Besides the fact that my server should run on .NET 1.1, the other problem with this is that this way we are likely to experience significant performance loss, because every remote method invocation has to establish a new TCP connection with the server, which imposes an unnecessary latency on the system, resulting in the overall throughput decreasing. Another solution would be to unregister the channel and unregister the registered remote types as well. This way, we could stop the service, because clients would get the usual RemotingException (Requested service not found), even if they have a cached connection to the server, and we are done. RemotingException Unfortunately, .NET doesn’t provide us any opportunity to unregister a registered remoting type, the only way to do this is to unload the hosting appdomain, but we don’t want to do this for the above mentioned reason, which is before unloading the domain we first want to wait for the requests that are currently being processed to finish. However, there is a method RemotingServices.Disconnect that might come useful in hand. The only parameter of this static method is a MarshalByRefObject. This method disconnects the given published object. This way, if you have a pointer to an object that serves remote invocations, and call RemotingServices.Disconnect on this, your object won’t be reachable anymore, and the client will get an exception. RemotingServices.Disconnect As you can see, this can be a good solution if you have the instance of the published remote type. You may use it on Client Activated Objects, any marshaled objects (when a remotable object pointer is returned to the client, or using RemotingServces.Marshal method), WellKnownServiceType Singletons with a little work, but not with SingleCall types. RemotingServces.Marshal WellKnownServiceType When using a SingleCall type, each request to the type is invoked on a new instance, so you can’t have any instance pointer in your hand, therefore you just can not disconnect this kind of a remote type without unloading the hosting appdomain. Anyway as you can see, using RemotingServices.Disconnect is the best way to stop your service without having to unload the domain. Using it, you don’t even need to unregister the listening channel. But, you have to store the references to the instances of the published types that are serving the requests. So, do not use RegisterWellKnownServiceType, for example, to create a Singleton, instead use RemotingServices.Marshal(). RegisterWellKnownServiceType RemotingServices.Marshal() //registering singleton MyService obj = new MyService(); RemotingServices.Marshal(obj, “myService.bin”); //unregistering RemotingServices.Disconnect(obj); For other marshaled stateful objects, you can use the practice below. All you need to do is to create a remotable factory class, register it the same way as above, and the Create method of the factory class returns an instance of the requested service type, and adds it to a collection. Create public class AppFactory : MarshalByRefObject, IAppFactory { IMyService Create() { MyService obj = new MyService(); Collection.Add(obj); return obj; } } //when starting service AppFactory appfactory = new AppFactory(); RemotingServices.Marshal( appfactory, “AppFactory.bin”); //doing job.. //when stopping service //1. disconnect appfactory RemotingServices.Disconnect( appfactory ); //2. disconnect service objects foreach(MarhsalByRefObject obj in Collection) { RemotingServices.Disconnect( obj ); } Collection.Clear(); The only problem is that if the server is running for a long time, and several MyService objects are created in a short period of time, then it will lead to huge memory consumption especially if MyService instances require quite a lot of memory. Soon, your server will start throwing OutOfMemoryExceptions. That is because you keep holding references in your collection even if the objects’ lease time already expired and the lease manager disconnected the objects, so they cannot be reached from outside anymore. There is a service in Remoting, which can be helpful at this time too, namely the TrackingServices. Using the TrackingServices, you can be informed when an object is disconnected and so you can remove it from the collection, letting the garbage collector destroy it. I never used ClientActivatedObjects, but I think this practice can be used with them as well. MyService OutOfMemoryException ClientActivatedObject I found pretty useful the dynamic sink that can be jammed in the sink chain. Installing a dynamic sink in an appdomain, you are notified of every remote method call starting and finishing. It can be used to count how many remote calls are being processed currently in the appdomain, and if the server is stopped, reject the calls by throwing an exception. All to be done, is to write a class which has a counter, and methods to increase and decrease the counter, and one for waiting until the counter reaches zero. For doing this, a ManualResetEvent object can be used. In the Leave method, you decrease the counter, and if it is zero, just set the event to a signal state (calling Set). In the Enter method, you increase the counter and set the event to a not signal state (calling Reset). In the Wait method, you simply call the event’s WaitOne() method which will block the calling thread until the event becomes signaled, which means that the counter reached zero, so no inbound calls are being processed. Note that this object will be called from different threads, so applying a macro lock on these methods is not a bad idea. ManualResetEvent Leave Set Enter Reset Wait WaitOne() There will be one object of this class per appdomain, and the Enter method will be called from the sink’s ProcessMessageStart method, and the Leave from the ProcessMessageFinish method. ProcessMessageStart ProcessMessageFinish On stopping the server, you just simply set a boolean variable, then in the ProcessMessageStart method, you first examine this boolean, and if it is true you throw a kind of exception. From this point, all remote method calls will be rejected. public class InboundCallCounterDynamicSink : IDynamicMessageSink { public void ProcessMessageStart) { if (ServiceDomainManager.Current.IsStopped) throw new NodeStoppedException("Requested Service is stopped."); else ServiceDomainManager.Current.CallCounter.Enter(); break; } } } public void ProcessMessageFinish) { ServiceDomainManager.Current.CallCounter.Leave(); break; } } } } The code snippet demonstrates how the described sink can look. Somehow, you should check what type of object the inbound call targets. Because, this mechanism should affect only calls to Application objects (your published services). These are the remote calls coming from the clients. Other cross appdomain calls, for example, calling the DomainManager by the NodeManager, should not be counted or rejected. That’s why a filtering is needed which first checks the targeted object’s type and if it is an Application object, set the counter or throw the NodeStoppedException if the server is stopped. NodeStoppedException The best place to install the dynamic sink is in the DomainManager’s Start method before registering the channel and registering the application types for remoting. This technique solves the problem around stopping SingleCall application types. At last the NodeManager’s Stop method should look something like this: public void Stop() { //unregister channel, set IsStopped //to true in the service appdomain domainManager.Stop(); //wait for current reqests to finish domainManager.CallCounter.Wait(); //dispose any resources domainManager.Dispose(); //unload the service domain AppDomain.Unload( domainManager.GetHostingAppDomain() ); } There is one more thing that I want to share. I realized several times that when I start my service, and also a test client which stresses the service invoking the Application methods, then I just stop the service and start again immediately, it just can’t reserve the TCP port again. I searched the net, and found many people complaining about the same thing. Some wrote that, after two minutes it will be able to reserve again. I don’t know why it is happening, but the point is that it makes my server unreliable as I can’t stop and start at any time, and I didn’t find any solution for this. As for me, I implemented a dynamic port allocation manager (PAM) class which has a range of port numbers, and when DomainManager registers the channel, it first asks for a port number from the PAM. If the port happens to be unusable, it asks and tries another. When allocating a port, the PAM sets its state to reserved, when the port is unusable it sets the state to unusable, and a maintenance method of the PAM is called periodically by a timer that puts the unusable ports back to available state. When the channel is successfully created on a port, then that port number must be known by clients to be able to reach the Application objects which may be awkward in many situations, but the most simple solution is when clients can ask for the port number or the entire URI of the service from the NodeManager which is always running (in the default appdomain) and always serves on the same well known port. When using Singleton or marshaled objects, use RemotingServices.Disconnect to unregister the objects, but dynamic sinks are also needed here if you want to count and wait for the current requests just being processed to finish before unloading the service appdomain. In the case of SingleCall types, use the technique in the last section, where RemotingServices.Disconnect doesn’t help and you have to throw exceptions in the dynamic sink’s ProcessMessageFirst method to reject the client request. ProcessMessageFirst
http://www.codeproject.com/Articles/12897/How-to-stop-a-service-using-NET-Remoting
CC-MAIN-2013-20
refinedweb
2,236
51.58
# Porting desktop apps to .NET Core Since I’ve been working with the community on porting desktop applications from .NET Framework to .NET Core, I’ve noticed that there are two camps of folks: some want a very simple and short list of instructions to get their apps ported to .NET Core while others prefer a more principled approach with more background information. Instead of writing up a “Swiss Army knife”-document, we are going to publish two blog posts, one for each camp: * **This post is the simple case**. It’s focused on simple instructions and smaller applications and is the easiest way to move your app to .NET Core. * **We will publish another post for more complicated cases**. This post will focus more on non-trivial applications, such WPF application with dependencies on WCF and third-party UI packages. If you prefer watching videos instead of reading, here is the video where I do everything that is described below. Step 0 – Prerequisites ---------------------- To port your desktop apps to Core, you’ll need [.NET Core 3](https://dotnet.microsoft.com/download) and Visual Studio 2019. Step 1 – Run portability analyzer --------------------------------- Before porting, you should check how compatible your application is with .NET Core. To do so, download and run [.NET Portability Analyzer](https://blogs.msdn.microsoft.com/dotnet/2018/08/08/are-your-windows-forms-and-wpf-applications-ready-for-net-core-3-0/). * On the first tab, Portability Summary, if you have only 100% in .NET Core column (everything is highlighted in green), your code is fully compatible, go to Step 2. * If you have values of less than 100%, first look at all assemblies that aren’t part of you application. For those, check if their authors are providing versions for .NET Core or .NET Standard. * Now look at the other part of assemblies that are coming from your code. If you don’t have any of your assemblies listed in the portability report, go to Step 2. If you do, open Details tab, filter the table by clicking on the column Assembly and only focus on the ones that are from your application. Walk the list and refactor your code to stop using the API or replace the API usage with alternatives from .NET Core. [![](https://devblogs.microsoft.com/dotnet/wp-content/uploads/sites/10/2019/05/portability-report.png)](https://devblogs.microsoft.com/dotnet/wp-content/uploads/sites/10/2019/05/portability-report.png) Step 2 – Migrate to SDK-style .csproj ------------------------------------- In **Solution Explorer** right-click on your project (not on the solution!). Do you see **Edit Project File**? If you do, you already use the SDK-style project file, so you should move to **Step 3**. If not, do the following. * Check in the **Solution Explorer** if your project contains a `packages.config` file. If you don’t, no action is needed, if you do, right-click on `packages.config` and choose **Migrate packages.config to PackageReference**. Then click **OK**. * Open your project file by right-clicking on the project and choose **Unload Project**. Then right-click on the project and choose **Edit .csproj**. * Copy the content of the project file somewhere, for example into Notepad, so you can search in it later. * Delete everything from your project file opened in Visual Studio (I know it sounds aggressive, but we will add only needed content from the copy we’ve just made in a few steps). Instead of the text you’ve just deleted, paste the following code.For a WinForms application: ``` WinExe net472 true false ``` For a WPF application: ``` WinExe net472 true false ``` * In Notepad, search for `PackageReference`. If you did not find anything, move on. If you found `PackageReference`, copy the entire  that contains `PackageReference` in your project file, opened in Visual Studio, right below the lines you’ve pasted in the step above. Do it for each occurrence of the `PackageReference` you have found. The copied block should look like this. ``` 3.11.0 ``` * Now do the same as above for `ProjectReference`. If you did not find anything, move on. If you found any `ProjectReference` items, they would look like this. ``` {7bce0d50-17fe-4fda-b6b7-e7960aed8ac2} WindowsFormsApp1 ``` * You can remove lines with  and  properties, since they are not needed in the new project file style. So for each `ProjectReference` that you have found (if any), copy only `ItemGroup` and `ProjectReference` like this. ``` ``` Save everything. Close the .csproj file in Visual Studio. Right-click on your project in the **Solution Explorer** and select **Reload Project**. Rebuild and make sure there are no errors. Great news, you just updated your project file to the new SDK-style! The project is still targeting .NET Framework, but now you’ll be able to retarget it to .NET Core. Step 3 – Retarget to .NET Core ------------------------------ Open your project file by double-clicking on your project in **Solution Explorer**. Find the property  and change the value to `netcoreapp3.0`. Now your project file should look like this: ``` WinExe netcoreapp3.0 ... ... ``` Build and run your project. **Congratulations, you ported to .NET Core 3!** Fixing errors ------------- If you get errors like ``` The type or namespace could not be found ``` or ``` The name does not exist in the current context ``` and your portability report was green, it should be easy to fix by adding a NuGet package with the corresponding library. If you cannot find the NuGet package with the library that is missing, try referencing [Microsoft.Windows.Compatibility](https://docs.microsoft.com/dotnet/core/porting/windows-compat-pack). This package adds ~21K .NET APIs from .NET Framework. Working with designers ---------------------- Even though it is possible to edit the user interface of your application via code, developers usually prefer using the visual designers. With .NET Core we had to rearchitect the way the designers work with .NET Core projects: + The WPF designer is already in preview and we are working on adding more functionality to it. + The WinForms designer for .NET Core will be available later, and meanwhile there you can use the .NET Framework WinForms designer as a workaround. Here is how you can use the .NET Framework WinForms designer: 1. Copy your .csproj file (let’s say you have `MyProject.csproj`), give it a different name, for example `MyProject.NetFramework.csproj` and put it next to your existing project file. 2. Make sure your project is closed in Visual Studio, open the new project `MyProject.NetFramework.csproj`. In **Solution Explorer** right-click on your project and select **Properties**. In the Application tab (should be open by default) set **Assembly name** and **Default namespace** to the same values as in your initial project (remove “.NetFramework” from the names). Save this solution next to your existing solution. 3. Open the new project file and change the  to `net472`. 4. Now when you need to use the WinForms designer, load your project with the `MyProject.NetFramework.csproj` project file and you’ll get the full experience of .NET Framework designer. When you are done with the designer, close and open your project with the .NET Core project file. 5. This is just a workaround until the WinForms designer for .NET Core is ready. Why port to .NET Core --------------------- Check out the video where Scott Hunter and I are talking about all the new things coming with .NET Core 3 [Porting to .NET Core 3.0](https://www.youtube.com/watch?v=upVQEUc_KwU&feature=youtu.be).
https://habr.com/ru/post/455325/
null
null
1,234
68.06
Providing Technology Training and Mentoring For Modern Technology Adoption the event mechanism to work, you need to follow a few ground rules. This article discusses those. An event is first defined in portlet.xml. This definition has to exist for the portlet application of both the publisher and consumer. An event has a namespace qualified name and a payload data type. For example: <portlet-app ...> ... <event-definition> <qname xmlns:x:was</qname> <value-type>com.mycom.address.model.Address</value-type> </event-definition> </portlet-app> In this example, the qualified name of the event is as follows: - Namespace URL is “” - The local part is “was” The Java class for the payload data is com.mycom.address.model.Address. We will discuss the requirements for this class shortly. You can also define an event using a simple name instead of a qualified name. <event-definition> <name>AddressEvent</name> <value-type>com.mycom.address.model.Address</value-type> </event-definition> This is not recommended. To avoid any naming conflict, you should always use the qualified name approach. The event payload class is declared using the <value-type> element in portlet.xml. This class can be a Java primitive class, such as String and Integer. If you wish to use your own class, it must conform to a few rules: For example: @XmlRootElement public class Address implements Serializable { //… } The publisher portlet needs to declare all the events it will fire in portlet.xml. <portlet> … <supported-publishing-event> <qname xmlns:x:was</qname> </supported-publishing-event> </portlet> The local part and namespace URL must be exactly as stated in the event definition. To fire an event, you need to call the setEvent method of either the ActionResponse or EventResponse object. public void processAction(ActionRequest request, ActionResponse response) throws PortletException, java.io.IOException { //… Address a = new Address(); response.setEvent( new QName("", "was"), a); Note how the namespace URI and local part of the QName object matches the event definition. The consumer side needs to declare all the events it is interested in consuming. <portlet> … <supported-processing-event> <qname xmlns:x:was</qname> </supported-processing-event> </portlet> The namespace and local part must match the event definition. Otherwise, the consumer will not be notified. Develop the processEvent method. This will be automatically called when a matching event is fired. public void processEvent(EventRequest request, EventResponse response) throws PortletException, IOException { Event e = request.getEvent(); logger.info("Got an event."); logger.info("QName: " + e.getQName()); logger.info("Name: " + e.getName()); logger.info("Value type: " + e.getValue().getClass().getName()); Address a = (Address) e.getValue(); //Get the payload } This method will print out something like this: INFO: QName: {}was INFO: Name: was INFO: Value type: com.mycom.address.model.Address You need to be extra careful in making sure that the qualified name of an event is correct in every place. Otherwise, events will not be dispatched to the right consumer. Also make sure that the payload type is serializable and has a JAXB binding. […] : […] Good explanation ! One small note: In IBM WebSphere Portal, You must additionally create page wires. That is true. In IBM WebSphere Portal, you will need to do one additional step of wiring for events to work. Add both event publisher and consumer portlets to the same page. Then from the page’s menu select Actions > Edit Page Layout. Then click the Wires tab. Your email address will not be published. Required fields are marked *
https://www.webagesolutions.com/blog/archives/124
CC-MAIN-2019-43
refinedweb
569
51.04
ssl — TLS/SSL wrapper for socket objects¶. For example, TLSv1.1 and TLSv1.2 come with openssl version 1.0.1.. Changed in version 3() ... Context creation¶ A convenience function helps create SSLContext objects for common purposes. ssl. create_default_context(purpose=Purpose.SERVER_AUTH, cafile=None, capath=None, cadata=None)¶ Return a new SSLContextobject with default settings for the given purpose. The settings are chosen by the sslmodule, and usually represent a higher security level than when calling the SSLContextconstructor directly. cafile, capath, cadata represent optional CA certificates to trust for certificate verification, as in SSLContext.load_verify_locations(). If all three are None, this function can choose to trust the system’s default CA certificates instead. The settings are: PROTOCOL_TLS, OP_NO_SSLv2, and OP_NO_SSLv3with high encryption cipher suites without RC4 and without unauthenticated cipher suites. Passing SERVER_AUTHas purpose sets verify_modeto CERT_REQUIREDand either loads CA certificates (when at least one of cafile, capath or cadata is given) or uses SSLContext.load_default_certs()to load default CA certificates. Note The protocol, options, cipher and other settings may change to more restrictive values anytime without prior deprecation. The values represent a fair balance between compatibility and security. If your application needs specific settings, you should create a SSLContextand apply the settings yourself. Note If you find that when certain older clients or servers attempt to connect with a SSLContextcreated by this function that they get an error stating “Protocol or cipher suite mismatch”, it may be that they only support SSL3.0 which this function excludes using the OP_NO_SSLv3. SSL3.0 is widely considered to be completely broken. If you still wish to continue to use this function but still allow SSL 3.0 connections you can re-enable them using: ctx = ssl.create_default_context(Purpose.CLIENT_AUTH) ctx.options &= ~ssl.OP_NO_SSLv3 New in version 3.4. Changed in version 3.4.4: RC4 was dropped from the default cipher string. Changed in version 3.6: ChaCha20/Poly1305 was added to the default cipher string. 3DES was dropped from the default cipher string. Exceptions¶ - exception ssl. SSLError¶instances are provided by the OpenSSL library. Changed in version 3.3: SSLErrorused to be a subtype of socket.error. library¶ A string mnemonic designating the OpenSSL submodule in which the error occurred, such as SSL, PEMor X509. The range of possible values depends on the OpenSSL version. New in version 3.3. - exception ssl. SSLZeroReturnError¶ A subclass of SSLErrorraised when trying to read or write and the SSL connection has been closed cleanly. Note that this doesn’t mean that the underlying transport (read TCP) has been closed. New in version 3.3. - exception ssl. SSLWantReadError¶ A subclass of SSLErrorraised by a non-blocking SSL socket when trying to read or write data, but more data needs to be received on the underlying TCP transport before the request can be fulfilled. New in version 3.3. - exception ssl. SSLWantWriteError¶ A subclass of SSLErrorraised by a non-blocking SSL socket when trying to read or write data, but more data needs to be sent on the underlying TCP transport before the request can be fulfilled. New in version 3.3. - exception ssl. SSLSyscallError¶ Return num cryptographically strong pseudo-random bytes. Raises an SSLErrorif the PRNG has not been seeded with enough data or if the operation is not supported by the current RAND method. RAND_status()can be used to check the status of the PRNG and RAND_add()can be used to seed the PRNG. For almost all applications os.urandom()is preferable. Read the Wikipedia article, Cryptographically secure pseudorandom number generator (CSPRNG), to get the requirements of a cryptographically generator. New in version 3.3. ssl. RAND_pseudo_bytes(num)¶ Return (bytes, is_cryptographic): bytes are num pseudo-random bytes, is_cryptographic is Trueif the bytes generated are cryptographically strong. Raises an SSLErrorif. For almost all applications os.urandom()is preferable. New in version 3.3. Deprecated since version 3.6: OpenSSL has deprecated ssl.RAND_pseudo_bytes(), use ssl.RAND_bytes()instead. ssl. RAND_status()¶ Return Trueif the SSL pseudo-random number generator has been seeded with ‘enough’ randomness, and Falseotherwise. You can use ssl.RAND_egd()and ssl.RAND_add()to increase the randomness of the pseudo-random number generator. ssl. RAND_egd(path)¶. Availability: not available with LibreSSL and OpenSSL > 1.1.0. ssl. RAND_add(bytes, entropy)¶ Mix the given bytes into the SSL pseudo-random number generator. The parameter entropy (a float) is a lower bound on the entropy contained in string (so you can always use 0.0). See RFC 1750 for more information on sources of entropy. Changed in version 3.5: Writable bytes-like object is now accepted. Certificate handling¶ ssl. match_hostname(cert, hostname)¶ Verify that cert (in decoded format as returned by SSLSocket.getpeercert()) matches the given hostname. The rules applied are those for checking the identity of HTTPS servers as outlined in RFC 2818, RFC 5280 and RFC 6125. In addition to HTTPS, this function should be suitable for checking the identity of servers in various SSL-based protocols such as FTPS, IMAPS, POPS and others. CertificateErroror *a*.example.org) nor a wildcard inside an internationalized domain names (IDN) fragment. IDN A-labels such as www*.xn--pthon-kva.orgare still supported, but x*.python.orgno longer matches xn--tda.python.org. Changed in version 3.5: Matching of IP addresses, when present in the subjectAltName field of the certificate, is now supported.. cert_time_to_seconds(cert_time)¶ Return the time in seconds since the Epoch, given the cert_timestring representing the “notBefore” or “notAfter” date from a certificate in "%b %d %H:%M:%S %Y %Z"strptime format (C locale). Here’s an example: >>> import ssl >>> timestamp = ssl.cert_time_to_seconds("Jan 5 09:34:43 2018 GMT") >>> timestamp 1515144883 >>> from datetime import datetime >>> print(datetime.utcfromtimestamp(timestamp)) 2018-01-05 09:34:43 “notBefore” or “notAfter” dates must use GMT (RFC 5280). Changed in version 3.5: Interpret the input time as a time in UTC as specified by ‘GMT’ timezone in the input string. Local timezone was used previously. Return an integer (no fractions of a second in the input format) ssl. get_server_certificate(addr, ssl_version=PROTOCOL_TLS, ca_certs=None)¶ Given the address addrof an SSL-protected server, as a (hostname, port-number) pair, fetches the server’s certificate, and returns it as a PEM-encoded string. If ssl_versionis specified, uses that version of the SSL protocol to attempt to connect to the server. If ca_certsis specified, it should be a file containing a list of root certificates, the same format as used for the same parameter in SSLContext.wrap_socket(). The call will attempt to validate the server certificate against that set of root certificates, and will fail if the validation attempt fails. Changed in version 3.3: This function is now IPv6-compatible. Changed in version 3.5: The default ssl_version is changed from PROTOCOL_SSLv3to PROTOCOL_TLSfor maximum compatibility with modern servers. ssl. DER_cert_to_PEM_cert(DER_cert_bytes)¶ Given a certificate as a DER-encoded blob of bytes, returns a PEM-encoded string version of the same certificate. ssl. PEM_cert_to_DER_cert(PEM_cert_string)¶ Given a certificate as an ASCII PEM string, returns a DER-encoded sequence of bytes for that same certificate. ssl. get_default_verify_paths()¶ Returns a named tuple with paths to OpenSSL’s default cafile and capath. The paths are the same as used by SSLContext.set_default_verify_paths(). The return value is a named tuple DefaultVerifyPaths: cafile- resolved path to cafile or Noneif the file doesn’t exist, capath- resolved path to capath or Noneif the directory doesn’t exist, openssl_cafile_env- OpenSSL’s environment key that points to a cafile, openssl_cafile- hard coded path to a cafile, openssl_capath_env- OpenSSL’s environment key that points to a capath, openssl_capath- hard coded path to a capath directory Availability: LibreSSL ignores the environment vars openssl_cafile_envand openssl_capath_env. New in version 3.4. ssl. enum_certificates(store_name)¶ Retrieve certificates. Trust specifies the purpose of the certificate as a set of OIDS or exactly Trueif the certificate is trustworthy for all purposes. Example: >>> ssl.enum_certificates("CA") [(b'data...', 'x509_asn', {'1.3.6.1.5.5.7.3.1', '1.3.6.1.5.5.7.3.2'}), (b'data...', 'x509_asn', True)] Availability: Windows. New in version 3.4. ssl. enum_crls(store_name)¶ Retrieve CRLs. Availability: Windows. New in version 3.4. ssl. wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS, ca_certs=None, do_handshake_on_connect=True, suppress_ragged_eofs=True, ciphers=None)¶ Takes an instance sockof socket.socket, and returns an instance of ssl.SSLSocket, a subtype of socket.socket, which wraps the underlying socket in an SSL context. sockmust be a SOCK_STREAMsocket; other socket types are unsupported.. Use of this setting requires a valid set of CA certificates to be passed, either to SSLContext.load_verify_locations()or as a value of the ca_certsparameter to wrap_socket(). ssl. CERT_REQUIRED¶ Possible value for SSLContext.verify_mode, or the cert_reqsparameter to wrap_socket(). In this mode, certificates are required from the other side of the socket connection; an SSLErrorwill be raised if no certificate is provided, or if its validation fails. check but non of the intermediate CA certificates. The mode requires a valid CRL that is signed by the peer cert’s issuer (its direct ancestor CA). If no proper has been loaded data:PROTOCOL_TLS. Deprecated since version 3.6: Use PROTOCOL_TLSinstead. ssl. PROTOCOL_SSLv2¶ Selects SSL version 2 as the channel encryption protocol. This protocol is not available if OpenSSL is compiled with the OPENSSL_NO_SSL2flag. Warning SSL version 2 is insecure. Its use is highly discouraged. Deprecated since version 3.6: OpenSSL has removed support for SSLv2. ssl. PROTOCOL_SSLv3¶ Selects SSL version 3 as the channel encryption protocol. This protocol is not be available if OpenSSL is compiled with the OPENSSL_NO_SSLv3flag. Warning SSL version 3 is insecure. Its use is highly discouraged. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLSwith flags like OP_NO_SSLv3instead. ssl. PROTOCOL_TLSv1¶ Selects TLS version 1.0 as the channel encryption protocol. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLSwith flags like OP_NO_SSLv3instead. ssl. PROTOCOL_TLSv1_1¶ Selects TLS version 1.1 as the channel encryption protocol. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLSwith flags like OP_NO_SSLv3instead. ssl. PROTOCOL_TLSv1_2¶ Selects TLS version 1.2 as the channel encryption protocol. This is the most modern version, and probably the best choice for maximum protection, if both sides can speak it. Available only with openssl version 1.0.1+. New in version 3.4. Deprecated since version 3.6: OpenSSL has deprecated all version specific protocols. Use the default protocol PROTOCOL_TLSwith flags like OP_NO_SSLv3instead. ssl. OP_ALL¶ Enables workarounds for various bugs present in other SSL implementations. This option is set by default. It does not necessarily set the same flags as OpenSSL’s SSL_OP_ALLconstant. New in version 3.2. ssl. OP_NO_SSLv2¶ Prevents an SSLv2 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv2 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv2 is deprecated ssl. OP_NO_SSLv3¶ Prevents an SSLv3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing SSLv3 as the protocol version. New in version 3.2. Deprecated since version 3.6: SSLv3 is deprecated ssl. OP_NO_TLSv1. ssl. OP_NO_TLSv1_3¶ Prevents a TLSv1.3 connection. This option is only applicable in conjunction with PROTOCOL_TLS. It prevents the peers from choosing TLSv1.3 as the protocol version. TLS 1.3 is available with OpenSSL 1.1.1 or later. When Python has been compiled against an older version of OpenSSL, the flag defaults to 0. New in version. ssl. ALERT_DESCRIPTION_HANDSHAKE_FAILURE¶ ssl. ALERT_DESCRIPTION_INTERNAL_ERROR¶ ALERT_DESCRIPTION_* Alert Descriptions from RFC 5246 and others. The IANA TLS Alert Registry contains this list and references to the RFCs where their meaning is defined. Used as the return value of the callback function in SSLContext.set_servername_callback(). New in version 3.4. - class ssl. AlertDescription¶ using the SSLContext.wrap_socket()method. Changed in version 3.5: The sendfile()method was added. Changed in version 3.5: The shutdown()does not reset the socket timeout each time bytes are received or sent. The socket timeout is now to maximum total duration of the shutdown. Deprecated since version 3.6: It is deprecated to create a SSLSocketinstance directly, use SSLContext.wrap_socket()to wrap a socket. Read up to len bytes of data from the SSL socket and return the result as a bytesinstance. If buffer is specified, then read into the buffer instead, and return the number of bytes read. Raise SSLWantReadErroror SSLWantWriteErrorif the socket is non-blocking and the read would block. As at any time a re-negotiation is possible, a call to read()can also cause write operations. Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration to read up to len bytes. SSLSocket. write(buf)¶ Write buf to the SSL socket and return the number of bytes written. The buf argument must be an object supporting the buffer interface. Raise SSLWantReadErroror SSLWantWriteErrorif the socket is non-blocking and the write would block. As at any time a re-negotiation is possible, a call to write()can also cause read operations. Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration to write buf. Note The read() and write() methods are the low-level methods that read and write unencrypted, application-level data and decrypt/encrypt it to encrypted, wire-level data. These methods require an active SSL connection, i.e. the handshake was completed and SSLSocket.unwrap() was not called. Normally you should use the socket API methods like recv() and send() instead of these methods. SSLSocket. do_handshake()¶ Perform the SSL setup handshake. Changed in version 3.4: The handshake method also performs match_hostname()when the check_hostnameattribute of the socket’s contextis true. Changed in version 3.5: The socket timeout is no more reset each time bytes are received or sent. The socket timeout is now to maximum total duration of the handshake.. SSLSocket. getpeercert(binary_form=False)¶ If there is no certificate for the peer on the other end of the connection, return None. If the SSL handshake hasn’t been done yet, raise ValueError. If the binary_formparameter is False, and a certificate was received from the peer, this method returns a dictinstance.key in the dictionary. The subjectand issuerfieldsparameter is True, and a certificate was provided, this method returns the DER-encoded form of the entire certificate as a sequence of bytes, or Noneif the peer did not provide a certificate. Whether the peer provides a certificate depends on the SSL socket’s role: - for a client SSL socket, the server will always provide a certificate, regardless of whether validation was required; - for a server SSL socket, the client will only provide a certificate when requested by the server; therefore getpeercert()will return Noneif you used CERT_NONE(rather than CERT_OPTIONALor CERT_REQUIRED). Changed in version 3.2: The returned dictionary includes additional items such as issuerand notBefore. Changed in version 3.4: ValueErroris raised when the handshake isn’t done. The returned dictionary includes additional X509v3 extension items such as crlDistributionPoints, caIssuersand OCSPURIs. SSLSocket. cipher()¶ Returns a three-value tuple containing the name of the cipher being used, the version of the SSL protocol that defines its use, and the number of secret bits being used. If no connection has been established, returns None. Return the list of ciphers shared by the client during the handshake. Each entry of the returned list is a three-value tuple containing the name of the cipher, the version of the SSL protocol that defines its use, and the number of secret bits the cipher uses. shared_ciphers()returns Noneif no connection has been established or the socket is a client socket. New in version 3.5. SSLSocket. compression()¶ Return the compression algorithm being used as a string, or Noneif the connection isn’t compressed. If the higher-level protocol supports its own compression mechanism, you can use OP_NO_COMPRESSIONto disable SSL-level compression. New in version 3.3. SSLSocket. get_channel_binding(cb_type="tls-unique")¶ Get channel binding data for current connection, as a bytes object. Returns Noneif not connected or the handshake has not been completed. The cb_type parameter allow selection of the desired channel binding type. Valid channel binding types are listed in the CHANNEL_BINDING_TYPESlist. Currently only the ‘tls-unique’ channel binding, defined by RFC 5929, is supported. ValueErrorwill be raised if an unsupported channel binding type is requested. New in version 3.3. SSLSocket. selected_alpn_protocol()¶ Return the protocol that was selected during the TLS handshake. If SSLContext.set_alpn_protocols()was not called, if the other party does not support ALPN, if this socket does not support any of the client’s proposed protocols, or if the handshake has not happened yet, Noneis returned. New in version 3.5. SSLSocket. selected_npn_protocol()¶ Return the higher-level protocol that was selected during the TLS/SSL handshake. If SSLContext.set_npn_protocols()was not called, or if the other party does not support NPN, or if the handshake has not yet happened, this will return None. New in version 3.3. SSLSocket. unwrap()¶. SSLSocket.. New in version 3.8. Note Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises NotImplementedError. SSLSocket. version()¶ Return the actual SSL protocol version negotiated by the connection as a string, or Noneis no secure connection is established. As of this writing, possible return values include "SSLv2", "SSLv3", "TLSv1", "TLSv1.1"and "TLSv1.2". Recent OpenSSL versions may define more return values. New in version 3.5. SSLSocket. pending( The SSLSessionfor this SSL connection. The session is available for client and server side sockets after the TLS handshake has been performed. For client sockets the session can be set before do_handshake()has been called to reuse a session. New in version 3.6. SSL Contexts¶. - class ssl. SSLContext(protocol=PROTOCOL_TLS)¶ Create a new SSL context. You may pass protocol which must be one of the PROTOCOL_*constants defined in this module. The parameter specifies which version of the SSL protocol to use. Typically, the server chooses a particular protocol version, and the client must adapt to the server’s choice. Most of the versions are not interoperable with the other versions. If not specified, the default is PROTOCOL_TLS; it provides the most compatibility with other versions. Here’s a table showing which versions in a client (down the side) can connect to which versions in a server (along the top): Footnotes See also create_default_context()lets the sslmodule choose security settings for a given purpose. Changed in version 3.6: The context is created with secure default values. The options OP_NO_COMPRESSION, OP_CIPHER_SERVER_PREFERENCE, OP_SINGLE_DH_USE, OP_SINGLE_ECDH_USE, OP_NO_SSLv2(except for PROTOCOL_SSLv2), and OP_NO_SSLv3(except for PROTOCOL_SSLv3) are set by default. The initial cipher suite list contains only HIGHciphers, no NULLciphers and no MD5ciphers (except for PROTOCOL_SSLv2). SSLContext objects have the following methods and attributes: SSLContext. cert_store_stats()¶ Get statistics about quantities of loaded X.509 certificates, count of X.509 certificates flagged as CA certificates and certificate revocation lists as dictionary. Example for a context with one CA cert and one other cert: >>> context.cert_store_stats() {'crl': 0, 'x509_ca': 1, 'x509': 2} New in version 3.4. SSLContext. load_cert_chain(certfile, keyfile=None, password=None)¶is raised if the private key doesn’t match with the certificate. Changed in version 3.3: New optional argument password. SSLContext. load_default_certs(purpose=Purpose.SERVER_AUTH)¶ Load a set of default “certification authority” (CA) certificates from default locations. On Windows it loads CA certs from the CAand ROOTsystem stores. On other systems it calls SSLContext.set_default_verify_paths(). In the future the method may load CA certificates from other locations, too. The purpose flag specifies what kind of CA certificates are loaded. The default settings Purpose.SERVER_AUTHloads certificates, that are flagged and trusted for TLS web server authentication (client side sockets). Purpose.CLIENT_AUTHloads CA certificates for client certificate verification on the server side. New in version 3.4. SSLContext. load_verify_locations(cafile=None, capath=None, cadata=None)¶ Load a set of “certification authority” (CA) certificates used to validate other peers’ certificates when verify_modeis other than CERT_NONE. At least one of cafile or capath must be specified. This method can also load certification revocation lists (CRLs) in PEM or DER format. In order to make use of CRLs, SSLContext.verify_flagsmust be configured properly.. The cadata object, if present, is either an ASCII string of one or more PEM-encoded certificates or a bytes-like object of DER-encoded certificates. Like with capath extra lines around PEM-encoded certificates are ignored but at least one certificate must be present. Changed in version 3.4: New optional argument cadata SSLContext. get_ca_certs(binary_form=False)¶ Get a list of loaded “certification authority” (CA) certificates. If the binary_formparameter is Falseeach list entry is a dict like the output of SSLSocket.getpeercert(). Otherwise the method returns a list of DER-encoded certificates. The returned list does not contain certificates from capath unless a certificate was requested and loaded by a SSL connection. Note Certificates in a capath directory aren’t loaded unless they have been used at least once. New in version 3.4. SSLContext. get_ciphers()¶ Get a list of enabled ciphers. The list is in order of cipher priority. See SSLContext.set_ciphers(). Example: >>> ctx = ssl.SSLContext(ssl.PROTOCOL_SSLv23) >>> ctx.set_ciphers('ECDHE+AESGCM:!ECDSA') >>> ctx.get_ciphers() # OpenSSL 1.0.x [{'alg_bits': 256, 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(256) Mac=AEAD', 'id': 50380848, 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1/SSLv3', 'strength_bits': 256}, {'alg_bits': 128, 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(128) Mac=AEAD', 'id': 50380847, 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1/SSLv3', 'strength_bits': 128}] On OpenSSL 1.1 and newer the cipher dict contains additional fields: >>> ctx.get_ciphers() # OpenSSL 1.1+ [{'aead': True, 'alg_bits': 256, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES256-GCM-SHA384 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(256) Mac=AEAD', 'digest': None, 'id': 50380848, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES256-GCM-SHA384', 'protocol': 'TLSv1.2', 'strength_bits': 256, 'symmetric': 'aes-256-gcm'}, {'aead': True, 'alg_bits': 128, 'auth': 'auth-rsa', 'description': 'ECDHE-RSA-AES128-GCM-SHA256 TLSv1.2 Kx=ECDH Au=RSA ' 'Enc=AESGCM(128) Mac=AEAD', 'digest': None, 'id': 50380847, 'kea': 'kx-ecdhe', 'name': 'ECDHE-RSA-AES128-GCM-SHA256', 'protocol': 'TLSv1.2', 'strength_bits': 128, 'symmetric': 'aes-128-gcm'}] Availability: OpenSSL 1.0.2+. New in version 3.6. SSLContext. set_default_verify_paths()¶. SSLContext. set_ciphers(ciphers)¶will be raised. Note when connected, the SSLSocket.cipher()method of SSL sockets will give the currently selected cipher. OpenSSL 1.1.1 has TLS 1.3 cipher suites enabled by default. The suites cannot be disabled with set_ciphers(). SSLContext. set_alpn_protocols(protocols)¶ Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of ASCII strings, like ['http/1.1', 'spdy/2'], ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to RFC 7301. After a successful handshake, the SSLSocket.selected_alpn_protocol()method will return the agreed-upon protocol. This method will raise NotImplementedErrorif HAS_ALPNis False. OpenSSL 1.1.0 to 1.1.0e will abort the handshake and raise SSLErrorwhen both sides support ALPN but cannot agree on a protocol. 1.1.0f+ behaves like 1.0.2, SSLSocket.selected_alpn_protocol()returns None. New in version 3.5. SSLContext. set_npn_protocols(protocols)¶ Specify which protocols the socket should advertise during the SSL/TLS handshake. It should be a list of strings, like ['http/1.1', 'spdy/2'], ordered by preference. The selection of a protocol will happen during the handshake, and will play out according to the Application Layer Protocol Negotiation. After a successful handshake, the SSLSocket.selected_npn_protocol()method will return the agreed-upon protocol. This method will raise NotImplementedErrorif HAS_NPNis False. New in version 3.3. SSLContext. sni_callback¶ Register a callback function that will be called after the TLS Client Hello handshake message has been received by the SSL/TLS server when the TLS client specifies a server name indication. The server name indication mechanism is specified in RFC 6066 section 3 - Server Name Indication. Only one callback can be set per SSLContext. If sni_callback is set to Nonethen the callback is disabled. Calling this function a subsequent time will disable the previously registered callback. The callback function will be called with three arguments; the first being the ssl.SSLSocket, the second is a string that represents the server name that the client is intending to communicate (or Noneif the TLS Client Hello does not contain a server name) and the third argument is the original SSLContext. The server name argument is text. For internationalized domain name, the server name is an IDN A-label ( "xn--pythn-mua.org"). A typical use of this callback is to change the ssl.SSLSocket’s SSLSocket.contextattribute to a new object of type SSLContextrepresenting a certificate chain that matches the server name. Due to the early negotiation phase of the TLS connection, only limited methods and attributes are usable like SSLSocket.selected_alpn_protocol()and SSLSocket.context. SSLSocket.getpeercert(), SSLSocket.getpeercert(), SSLSocket.cipher()and SSLSocket.compress()methods require that the TLS connection has progressed beyond the TLS Client Hello and therefore will not contain return meaningful values nor can they be called safely. The_callback function the TLS connection will terminate with a fatal TLS alert message ALERT_DESCRIPTION_HANDSHAKE_FAILURE. This method will raise NotImplementedErrorif the OpenSSL library had OPENSSL_NO_TLSEXT defined when it was built. New in version 3option to further improve security. New in version 3.3. SSLContext. set_ecdh_curve(curve_name)¶for a widely supported curve. This setting doesn’t apply to client sockets. You can also use the OP_SINGLE_ECDH_USEoption to further improve security. This method is not available if HAS_ECDHis False. New in version 3.3. See also - SSL/TLS & Perfect Forward Secrecy - Vincent Bernat. SSLContext. wrap_socket(sock, server_side=False, do_handshake_on_connect=True, suppress_ragged_eofs=True, server_hostname=None, session=None.if server_side is true. The parameter do_handshake_on_connectspecifiessspecifies_sockets(), attr. SSLContext. session_stats()¶) SSLContext. check_hostname¶ Whether to match the peer cert’s hostname with match. Example: import socket, ssl context = ssl.SSLContext(). SSLContext. minimum_version¶ Like SSLContext.maximum_versionexcept it is the lowest supported version or TLSVersion.MINIMUM_SUPPORTED. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. SSLContext. options¶ An integer representing the set of SSL options enabled on this context. The default value is OP_ALL, but you can specify other options such as OP_NO_SSLv2by ORing them together. Note With versions of OpenSSL older than 0.9.8m, it is only possible to set options, not to clear them. Attempting to clear an option (by resetting the corresponding bits) will raise a ValueError. Changed in version 3.6: SSLContext.optionsreturns Optionsflags: >>> ssl.create_default_context().options # doctest: +SKIP <Options.OP_ALL|OP_NO_SSLv3|OP_NO_SSLv2|OP_NO_COMPRESSION: 2197947391> SSLContext.. New in version 3.8. Note Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the property value is None and can’t be modified). New in version 3.7. Note Only writeable with OpenSSL 1.1.0 or higher. SSLContext. verify_flags¶ The flags for certificate verification operations. You can set flags like VERIFY_CRL_CHECK_LEAFby ORing them together. By default OpenSSL does neither require nor verify certificate revocation lists (CRLs). Available only with openssl version 0.9.8+. New in version 3.4. Changed in version 3.6: SSLContext.verify_flagsreturns VerifyFlagsflags: >>> ssl.create_default_context().verify_flags # doctest: +SKIP <VerifyFlags.VERIFY_X509_TRUSTED_FIRST: 32768> SSLContext. verify_mode¶ Whether to try to verify other peers’ certificates and how to behave if verification fails. This attribute must be one of CERT_NONE, CERT_OPTIONALor CERT_REQUIRED. Changed in version 3.6: SSLContext.verify_modereturns VerifyModeenum: >>> ssl.create_default_context().verify_mode <VerifyMode.CERT_REQUIRED: 2> Certificates¶ they claim----- Certificate chains¶----- CA certificates¶. The platform’s certificates file can be used by calling SSLContext.load_default_certs(), this is done automatically with create_default_context(). Combined key and certificate¶----- Self-signed certificates¶. Examples¶ Testing for SSL support¶ To test for the presence of SSL support in a Python installation, user code should use the following idiom: try: import ssl except ImportError: pass else: ... # do something that requires SSL support Client-side operation¶ This example creates a SSL context with the recommended security settings for client sockets, including automatic certificate verification: >>> context = ssl.create_default_context() If you prefer to tune security settings yourself, you might create a context from scratch (but beware that you might not get the settings right): >>> context = ssl.SSLContext() >>> context.verify_mode = ssl.CERT_REQUIRED >>> context.check_hostname = True >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") (this snippet assumes), ... server_hostname="") >>> conn.connect(("", 443)) You may then fetch the certificate: >>> cert = conn.getpeercert() Visual inspection shows that the certificate does identify the desired service (that is, the HTTPS host): >>> pprint.pprint(cert) {'OCSP': ('',), 'caIssuers': ('',), 'crlDistributionPoints': ('', ''), 'issuer': ((('countryName', 'US'),), (('organizationName', 'DigiCert Inc'),), (('organizationalUnitName', ''),), (('commonName', 'DigiCert SHA2 Extended Validation Server CA'),)), 'notAfter': 'Sep 9 12:00:00 2016 GMT', 'notBefore': 'Sep 5 00:00:00 2014 GMT', 'serialNumber': '01BB6F00122B177F36CAB49CEA8B6B26', 'subject': ((('businessCategory', 'Private Organization'),), (('1.3.6.1.4.1.311.60.2.1.3', 'US'),), (('1.3.6.1.4.1.311.60.2.1.2', 'Delaware'),), (('serialNumber', '3359300'),), (('streetAddress', '16 Allen Rd'),), (('postalCode', '03894-4801'),), (('countryName', 'US'),), (('stateOrProvinceName', 'NH'),), (('localityName', 'Wolfeboro,'),), (('organizationName', 'Python Software Foundation'),), (('commonName', ''),)), 'subjectAltName': (('DNS', ''), ('DNS', 'python.org'), ('DNS', 'pypi.org'), ('DNS', 'docs.python.org'), ('DNS', 'testpypi.org'), ('DNS', 'bugs.python.org'), ('DNS', 'wiki.python.org'), ('DNS', 'hg.python.org'), ('DNS', 'mail.python.org'), ('DNS', 'packaging.python.org'), ('DNS', 'pythonhosted.org'), ('DNS', ''), ('DNS', 'test.pythonhosted.org'), ('DNS', 'us.pycon.org'), ('DNS', 'id.python.org')), 'version': 3} Now the SSL channel is established and the certificate verified, you can proceed to talk with the server: >>> conn.sendall(b"HEAD / HTTP/1.0\r\nHost: linuxfr.org\r\n\r\n") >>> pprint.pprint(conn.recv(1024).split(b"\r\n")) [b'HTTP/1.1 200 OK', b'Date: Sat, 18 Oct 2014 18:27:20 GMT', b'Server: nginx', b'Content-Type: text/html; charset=utf-8', b'X-Frame-Options: SAMEORIGIN', b'Content-Length: 45679', b'Accept-Ranges: bytes', b'Via: 1.1 varnish', b'Age: 2188', b'X-Served-By: cache-lcy1134-LCY', b'X-Cache: HIT', b'X-Cache-Hits: 11', b'Vary: Cookie', b'Strict-Transport-Security: max-age=63072000; includeSubDomains', b'Connection: close', b'', b''] See the discussion of Security considerations below. Server-side operation¶.create_default_context(ssl.Purpose.CLIENT_AUTH)). Notes on non-blocking sockets¶ SSL sockets behave slightly different than regular sockets in non-blocking mode. When working with non-blocking sockets, there are thus several things you need to be aware of: Most SSLSocketmethods will raise either SSLWantWriteErroror SSLWantReadErrorinstead of BlockingIOErrorif an I/O operation would block. SSLWantReadErrorwill be raised if a read operation on the underlying socket is necessary, and SSLWantWriteErrorfor a write operation on the underlying socket. Note that attempts to write to an SSL socket may require reading from the underlying socket first, and attempts to read from the SSL socket may require a prior write to the underlying socket. Changed in version 3.5: In earlier Python versions, the SSLSocket.send()method returned zero instead of raising SSLWantWriteErroror SSLWantReadError. Conversely, since the SSL layer has its own framing, a SSL socket may still have data available for reading without select()being aware of it. Therefore, you should first call SSLSocket.recv()to drain any potentially available data, and then only block on a select()call if still necessary. (of course, similar provisions apply when using other primitives such as poll(), or those in the selectorsmodule)], []) See also The asyncio module supports non-blocking SSL sockets and provides a higher level API. It polls for events using the selectors module and handles SSLWantWriteError, SSLWantReadError and BlockingIOError exceptions. It runs the SSL handshake asynchronously as well. Memory BIO Support¶ New in version 3.5. Ever since the SSL module was introduced in Python 2.6, the SSLSocket class has provided two related but distinct areas of functionality: - SSL protocol handling - Network IO The network IO API is identical to that provided by socket.socket, from which SSLSocket also inherits. This allows an SSL socket to be used as a drop-in replacement for a regular socket, making it very easy to add SSL support to an existing application. Combining SSL protocol handling and network IO usually works well, but there are some cases where it doesn’t. An example is async IO frameworks that want to use a different IO multiplexing model than the “select/poll on a file descriptor” (readiness based) model that is assumed by socket.socket and by the internal OpenSSL socket IO routines. This is mostly relevant for platforms like Windows where this model is not efficient. For this purpose, a reduced scope variant of SSLSocket called SSLObject is provided. - class ssl. SSLObject¶ A reduced-scope variant of SSLSocketrepresenting an SSL protocol instance that does not contain any network IO methods. This class is typically used by framework authors that want to implement asynchronous IO for SSL through memory buffers. This class implements an interface on top of a low-level SSL object as implemented by OpenSSL. This object captures the state of an SSL connection but does not provide any network IO itself. IO needs to be performed through separate “BIO” objects which are OpenSSL’s IO abstraction layer. This class has no public constructor. An SSLObjectinstance must be created using the wrap_bio()method. This method will create the SSLObjectinstance and bind it to a pair of BIOs. The incoming BIO is used to pass data from Python to the SSL protocol instance, while the outgoing BIO is used to pass data the other way around. The following methods are available: context server_side server_hostname session session_reused read() write() getpeercert() selected_npn_protocol() cipher() shared_ciphers() compression() pending() do_handshake() unwrap() get_channel_binding() When compared to SSLSocket, this object lacks the following features: - Any form of network IO; recv()and send()read and write only to the underlying MemoryBIObuffers. - There is no do_handshake_on_connect machinery. You must always manually call do_handshake()to start the handshake. - There is no handling of suppress_ragged_eofs. All end-of-file conditions that are in violation of the protocol are reported via the SSLEOFErrorexception. - The method unwrap()call does not return anything, unlike for an SSL socket where it returns the underlying socket. - The server_name_callback callback passed to SSLContext.set_servername_callback()will get an SSLObjectinstance instead of a SSLSocketinstance as its first parameter. Some notes related to the use of SSLObject: - All IO on an SSLObjectis non-blocking. This means that for example read()will raise an SSLWantReadErrorif it needs more data than the incoming BIO has available. - There is no module-level wrap_bio()call like there is for wrap_socket(). An SSLObjectis always created via an SSLContext. Best defaults¶ For client use, if you don’t have any special requirements for your security policy, it is highly recommended that you use the create_default_context() function to create your SSL context. It will load the system’s trusted CA certificates, enable certificate validation and hostname checking, and try to choose reasonably secure protocol and cipher settings. For example, here is how you would use the smtplib.SMTP class to create a trusted, secure connection to a SMTP server: >>> import ssl, smtplib >>> smtp = smtplib.SMTP("mail.python.org", port=587) >>> context = ssl.create_default_context() >>> smtp.starttls(context=context) (220, b'2.0.0 Ready to start TLS') If a client certificate is needed for the connection, it can be added with SSLContext.load_cert_chain(). By contrast, if you create the SSL context by calling the SSLContext constructor yourself, it will not have certificate validation nor hostname checking enabled by default. If you do so, please read the paragraphs below to achieve a good security level. Manual settings¶ Verifying certificates¶ When calling the SSLContext constructor directly,. This common check is automatically performed when SSLContext.check_hostname is enabled. SSL versions 2 and 3 are considered insecure and are therefore dangerous to use. If you want maximum compatibility between clients and servers, it is recommended to use PROTOCOL_TLS_CLIENT or PROTOCOL_TLS_SERVER as the protocol version. SSLv2 and SSLv3 are disabled by default. >>> client_context = ssl.SSLContext(ssl.PROTOCOL_TLS_CLIENT) >>> client_context.options |= ssl.OP_NO_TLSv1 >>> client_context.options |= ssl.OP_NO_TLSv1_1 The SSL context created above will only allow TLSv1.2 and later (if supported by your system) connections to a server. PROTOCOL_TLS_CLIENT implies certificate validation and hostname checks by default. You have to load certificates into the context. Cipher selection¶. Be sure to read OpenSSL’s documentation about the cipher list format. If you want to check which ciphers are enabled by a given cipher list, use SSLContext.get_ciphers() or the openssl ciphers command on your system. Multi-processing HTTP Server documentation - RFC 1422: Privacy Enhancement for Internet Electronic Mail: Part II: Certificate-Based Key Management - Steve Kent - RFC 4086: Randomness Requirements for Security - Donald E., Jeffrey I. Schiller - RFC 5280: Internet X.509 Public Key Infrastructure Certificate and Certificate Revocation List (CRL) Profile - D. Cooper - RFC 5246: The Transport Layer Security (TLS) Protocol Version 1.2 - T. Dierks et. al. - RFC 6066: Transport Layer Security (TLS) Extensions - D. Eastlake - IANA TLS: Transport Layer Security (TLS) Parameters - IANA - RFC 7525: Recommendations for Secure Use of Transport Layer Security (TLS) and Datagram Transport Layer Security (DTLS) - IETF - Mozilla’s Server Side TLS recommendations - Mozilla
https://docs.python.org/dev/library/ssl.html
CC-MAIN-2018-43
refinedweb
6,239
51.85
Thread local data per object instance. This is useful when you have a class non-static data member that needs to be thread-local. where SAWYER_THREAD_LOCAL is a macro expanding to, perhaps, "__thread". C++ only allows thread-local global variables or static member data, as with foo above. That means that a.foo and b.foo alias one another. But if you need some member data to be thread-local per object, you can declare it as MultiInstanceTls<T>. For instance, a.bar and b.bar are different storage locations, and are also thread-local. Definition at line 190 of file Synchronization.h. #include <Synchronization.h> Default-constructed value. Definition at line 202 of file Synchronization.h. Initialize value. Definition at line 209 of file Synchronization.h. Assignment operator. Definition at line 216 of file Synchronization.h. Implicit conversion to enclosed type. This is so that the data member can be used as if it were type T rather than a MultiInstanceTls object. Definition at line 262 of file Synchronization.h.
http://rosecompiler.org/ROSE_HTML_Reference/classSawyer_1_1MultiInstanceTls.html
CC-MAIN-2019-43
refinedweb
171
54.79
This. I love Extract Method. But I want a reverse feature, Inline Method. Very usefull refactorings indeed : move to app config section in web.config move to connection string section in web.config R# has reached a great level of pure C# / class support. Give the ASP.NET Developer some attention please Hello Resharper team! I am currently evaluating R#4 and I’m very happy with the stability,speed and features. Especialy the new installer is very good (I use VS2005&2008 on the same machine). I have a confession to make though. I installed Refactor Pro ASP.NET edition. Yes, I was tempted …. they advertised with and “extract to user control” feature wich almost does what it promises (I had to manualy make some correction to a namespace each time). There are some other nice featuers (like extract class from style attribites) and a lot of fluff. The “Extract to user control” however is realy usefull! Could you give the ASP.NET devs some more love and make this a refactoring in R#4 Kind Regards, Tom Pester Registred user since R#2 PS. once I noticed devexpress killed the F2 schorcut to rename I uninstalled it promptly. Extract string as resource would be great. Change type from System name to language equivalent: change String to string in C#. Less memory usage!!! Or reload only the code has changes. I have to clarify: this is NOT a post where you should suggest new features for ReSharper (this is what JIRA is used for). Instead, you’re welcome to specify if a specific feature of ReSharper seems unclear to you and you’d like us to write a clarifying post about it in this blog. I would like to know the motivation behind some of the design decissions that were made when making R#. I found the tool quit flexible but I’m still stumpled why there has to be a field first when making a property. So to make a property I first have to create a field and than I can use R# to create a property. Every programmer programs differently so it’s hard to come up wiht a 1 size fits all. How did you tackle this problem? Other than that, how hard is it to make a 10 minute video that shows all of the refactorings in action? (If I knew all of them and also how to apply them under the right circomstances I could make it myself.) I’m sure I would discover some new and useful things. Using Camtasia as the screen recorder and the excellent Key Jedi it is possible to make video’s that realy show how powerful R# is. This will not only benifit existing custoemrs but certainly people who are evaluating R#. The competition has an edge on this flank and it’s more than just marketing. I’d like to see Value Analysis reviewed on this blog. I find the feature very useful in tracking bugs in VS2005, and am excited to see it working with the new external annotations. This feature seems to be one that could do with more publicity as many of my colleagues don’t tend to use it. For example, the code for a recommended implementation of the Null / NonNull attributes is not readily available (except for in a Jira item I created a while ago). Thanks Hi, I’ve been a Resharper user for over 3 years and am now one of the legion of developers who feels they can’t user Visual Studio without it! But a few weeks ago Oren Eini (Ayende Rahien) was in the UK, I arranged a Geek Dinner and managed to persuade him to spend a couple of hours with my dev team and do an IoC / Windsor 101 session. What really impressed me (and blew away a few of my dev team) was the *way* Oren used Resharper – it was completely different to how any of us use it. Oren really is a Resharper Jedi Master… What I’d like (and I’m not sure if it’s possible) would be a series of screencasts (by Oren if possible) where he shows, not only the “whys” and “hows” of Resharper features, but also how you use them to gain huge amounts of control over your source code as he does. For example showing how you create classes then use the code generation features to create constructors with parameters mapping to fields all ready for Dependency Injection is quite a nice end to end story. Ideally I’d like one of Oren’s Hibernating Rhinos screencasts – but with subtitling showing what Resharper keyboard shortcuts he’s using to do the amazing things he’s doing… After he left – the one affect that he had on the team was to make them go back to their desks download and print out the Resharper Keymap PDF…. great idea Howard, I’d love to see some video where some Resharper pro-user show how to gain maximum of it Lex, Inline Method refactoring is available in ReSharper 4 EAP. One thing I frequently wonder about is that blue highlighting that ReSharper leaves lying around whenever I do something like Introduce Parameter. It doesn’t seem to serve any purpose except adding unnecessary keystrokes to every refactoring, as I’m having to hit Esc all the time to make it go away. I’d like to see something about *why* that blue highlighting is there, what purpose you think it serves, and how you think it fits into a typical refactoring scenario. What do you think we’re supposed to gain from it that’s worth the extra clutter on the screen? If I knew what you had in mind, then I’d know whether to change the way I work, or to add a “please, please get rid of it” request to JIRA. (grin) (And I’d also like to know if there’s a way to disable it! I looked through the options and couldn’t find anything.) Joe, Could you please provide a sample screenshot, preferably with status bar info visible?
http://blog.jetbrains.com/dotnet/2008/04/07/feedback-wanted/
CC-MAIN-2014-35
refinedweb
1,027
69.82
When parameter. This makes it much easier to understand what their value represents. For example, we can see that the string literal "\\s" here, represents the pattern of a regular expression: When hovering an inline parameter hint in ReSharper, we’ll also display XML documentation when available: One place where inline parameter hints become very useful, is when passing in null values or booleans. What do the null and false arguments represent here? var people = peopleService.Find("Maarten", null, false); The meaning of these becomes clear immediately when using inline parameter hints, without having to rely on using named arguments for readability: When are inline parameter hints shown? Generally speaking, ReSharper and Rider will display inline parameter hints for literals and null values, lambda and array expressions, anonymous methods and object creation expressions, constants and enumeration values. ReSharper and Rider do not display inline parameter hints for all literals and null values, however. Many base class library (BCL) methods have an obvious name and functionality, and displaying inline parameter hints would not improve readability for these. For example, in the following cases, the meaning of all parameters becomes clear from looking at their usage: Showing (or not showing) inline parameter hints can be configured in ReSharper’s settings, under Environment | Editor | Parameter Name Hints. Similarly in Rider, we can configure these under Editor | Parameter Name Hints | C# and Visual Basic .NET. Disable inline parameter hints can be done from the settings as well. A quick way to enable/disable parameter hints is by using the status indicator context menu: In some cases, it may be useful to disable inline parameter hints for a certain method call. This can be done using the Configure Parameter Name Hints action (Alt+Enter): Once applied, the method will be added to the exclude list in the settings: If we want to re-enable parameter hints for the Regex.Split() method, we can drop the entry from this list. We could also expand the entry here, and add additional namespaces and methods where inline parameter hints should be disabled. Download ReSharper 2018.3 EAP or Rider 2018.3 EAP and give it a try! We’d love to hear your feedback! Sounds like a great feature! Currently we use named parameter when calling a constructors. Could an option be added to show parameter names (or hints) regardless of the type of the argument but based on the type of call, like constructor or method? Thanks! Would you mind logging a feature request for this at ? Done! For R# that is Thanks! Pingback: Dew Drop - November 28, 2018 (#2848) - Morning Dew This is a great feature, Kudos to the person/team who came up with this idea. Nice. Hello, I found this very distractive, so I wanted to turn it off. However in Visual Studio 2018 Professional this option is not avalilable. In Options->Editor I have only Parameter Name Hints which does not have affect on Inline hits. Please point me to right direction how to turn it off. Thank you Right-click a hint, then hide everywhere should do the trick Right-click did the trick. After that even Parameter Name Hints started to work. However you should fix the post since no Inline Hints exists in VS ReSharper options. It is very confusing. Thank you The text was OK, now have updated the screenshots as well. These look pretty terrible on a dark theme. Changing the background in Tools -> Options -> Environment -> Fonts and Colors -> ReSharper Parameter Name Hint makes them more subtle, and blend into the background. I found this. But what I didn’t found is text color in tooltip window. It is some dark blue This is a great feature but now text-selecting parameter feels weird. When I try to select parameter from right to left and stop before hint then first character from parameter is not selected. I need to go with cursor to the middle of parameter name to select first letter. Also double clicking on parameter name could text-select whole parameter so it could be changed or copied. Hello, Konrad! Thanks for feedback. This is a known issue (). It is already fixed and will be out in 2018.3.2 (mid-January). Thank god I’m not the only one who’s struggling with this. Right now I’ve disabled this feature because it’s insanely frustrating trying to text-select values with a parameter name hint on the left. You basically can’t do it with the mouse at all as the selection stops at the character before the hint (usually a double-quote if it’s a string literal). I don’t even think it’s a particularly useful feature but it won’t be getting enabled again until they sort this bug out (not sure how it made it out of testing like that, it cripples usability) These are great, if you find the right set of options…. Where they don’t work so great are inside of .cshtml (Razor) files. Making changes to a single line causes all calls to @Html.Helper methods to re-synchronize. They “flash”–removing all hints for a few seconds and then adding them back in, which causes the display to sort of jump around. It gets pretty annoying, especially if there are a lot of @Html calls. Is there a way to turn off this feature by a specific file type? You could try disabling them for the HtmlHelper class entirely? (blacklist much like the Regex example from this post) Interesting feature, but I am finding that the hints are killing VS 2018’s performance. Horrible feature… just makes the code harder to read. Turned off immediately. Fully agree. And I spent 15min to turn it off. Right-click a hint, then “Turn off everywhere” should do the trick. While it helps us to identify what is the parameter being passed but this feature makes my short method call looks very long and ugly. You can right-click them and disable hints for that specific call. Is there a way to turn them off for a particular block of code (like //@formatter: on/off for formatting)? In general they are nice, but when you have a large switch statement, with single-line cases, these hints kill any attempt at having nicely aligned, readable code. Also: configuring this in Rider (adding an exclusion pattern) does not put anything in the solution’s DotSettings file, despite the “For current solution” indicator on the settings pane. Not even when explicitly saving to the team-shared solution settings. Thanks! Logged that last one here: Would you mind creating a feature request at for the block enable/disable?
https://blog.jetbrains.com/dotnet/2018/11/27/inline-parameter-name-hints-c-vb-net-resharper-rider/?replytocom=537984
CC-MAIN-2019-22
refinedweb
1,117
64.1
Let us first see what the java collections are. The framework of java collections is nothing but a group of classes as well as the interfaces which are utilized to implement reusable structures of collection data. We all know the limitations of java arrays, one of which is that they are unable to grow dynamically, have limited sort of safety. The other could be the implementation of efficient and complex data structures which is difficult to do the same from the scratch or very beginning. Talking about the java collections framework, it is nothing but a classes set that is utilized to implement the collection data structures. The advantages that java collections bring in are that it helps to lessen the effort that is required in programming. It helps to increase the performance as well, helps to make the software upgrade to a level where it can be reused as well and is very easy to design as well. The base interface that is known in the hierarchy of collections is known by the anem of java.util.Collection and represents Objects group. The types such as integer is required t be include in a collection and the collection interfaces that are more regular such as list is used to extend this interface. What is an iterator? It is nothing but is said to be an object which is used to iterate the objects in a collection and we can use java.util.Iterator as an interface which specifies the iterator potential or capabilities. What happens when we invoke the iterator() method? When we invoke this method on a collection, this then comes back with an iterator object. This iterator object is used to implement the iterator and helps knowing about the steps that are required to go over the objects in the collection. The following methods are used to specify the interfaces of iterator. The below lists the example so as to get all the collection elements printed. Listing 1: Collection elements printed private static print(Collection ) { Iterator i = i.iterator(); while (i.Next()) { Object o = i.next(); System.out.println(c); } } The other way to write the same is given below: private static print(Collection c) { for (Iterator i = i.iterator(); i.Next(); ) { System.out.println(i.next()); } } Let us understand with the help of code language how several methods of collections classes can be used. The different methods of collections classes comprise of add as well as copy elements and also the reverse data structures. Listing 2: Reverse data structures Collection.java import java.util.*; import java.Collections; public class Collection { public static void main(String[] args) { List list = Arrays.asList("john rob steve mark steve".split(" ")); List sublist = Arrays.asList("richard"); List searchList = Arrays.asList("steve"); System.out.println("Elements in list : " + list); // Creating a defined list copy Collections.copy(list, sublist); System.out.println("copy of list : " + list); // Finding maximum as well as minimum object value from list. System.out.println("object of max value : " + Collections.max(list)); System.out.println("object of min value : " + Collections.min(list)); // finding display index of first occurrence of sublist in the list. System.out.println(" 'steve First Index': " + Collections.indexOfSubList(list, searchList)); // finding index of last occurrence of sublist in the list. System.out.println("Last index of 'steve': " + Collections.lastIndexOfSubList(list, searchList)); Collections.replaceAll(list, "steve", "replaced"); System.out.println("Post replace all 'steve': " + list); // list displaying in a reverse order. Collections.reverse(list); System.out.println("List in reverse order: " + list); // rotate the given number of objects in list,here 4 Collections.rotate(list, 4); System.out.println("After rotation : " + list); // find size of the list System.out.println("Size of the list : " + list.size()); /* Swap element in list. here swap specified element with element at 0th(first) position */ Collections.swap(list, 0, list.size() - 1); System.out.println("List Post swapping : " + list); // fill() used to replace all elements with given element Collections.fill(list, "steve"); System.out.println("Post filling the entire 'steve' in list : " + list); /* ncopies() gives immutable list comprising specified object. */ List BobList = Collections.nCopies(3, "Bob"); System.out.println("List created by ncopy() " + BobList); // Retrieving enum type via enumeration(). Enumeration e = Collections.enumeration(BobList); Vector v = new Vector(); while (e.hasAttributes()) { //Adding attributes from enum type. v.addAttribute(e.nextAttribute()); } Array arrayList = Collections.list(v.elements()); System.out.println("arrayList: " + arrayList); } The below lists the output of the above code: Elements in list : [john rob steve mark steve] copy of list : [Richard, rob, steve, mark, steve] object of max value : richard object of min value : mark First index of 'steve': 2 Last index of 'steve': 4 After replace all 'steve': [richard, rob, replaced, richard, replaced] List in reverse order: [replaced, mark, replaced, rob, richard] After rotation : [mark, replaced, rob, richard, replaced] Size of the list : 5 List after swapping : [replaced, replaced, rob, richard, mark] fill all 'steve' in list : [steve, steve, steve, steve, steve] List created by ncopy() [Bob, Bob, Bob] arrayList: [Bob, Bob, Bob] There are lot of Collection implementations which includes each and every one that is provided by Java Development kit and these implementations will have a method known by the name of public clone. However you need to take in mind that it is not advisable to require it of all Collections. Let us validate our above statement with the help of an example. The meaning of cloning collections which is supported by a SQL database should be known very clearly. Also it will be fair to know about the method call if it will lead the company so as to requisite a new firm. The same is the case with resizable as well. Let us suppose that the client is not aware about the real type of a collection, it will help the client to more flexible. Also this will be less prone in order to make the client take a decision on what sort of collection is desired. Also the same applies for creating an empty collection of the same sort and then utilizing the addAll method. This method is used to copy the original collection elements and that in the new one. The list is distributed very evenly and comes back with a recommendation as to if it advises for a linked lists. Provided the naming nomenclature for the implementation, the suggestion was to put the key interfaces as short as possible; the nomenclature is <Implementaion><Interface>. And there are lot of other names which are known by the name of AbstractSequentialList, LinkedList, this must have been incorporated badly in case it is decided to alter the list to sequence. In order to deal with the naming nomenclature, we need to deal it making use of the following code. import java.util.*; import java.collections.*; import java.util.collections; // This interprets the Collections list There is a need to elaborate several of the collection classes as well as the map types. This is usually done in the Java collection APIs. Let us see how we can elaborate the collection interface. We all know that string interfaces are the only elements or attribute that can be contained by the stringCollection. In case we try to add something extra or play with the elements in the collection, this will not be liked by the compiler and this may run into an error. Also, we can insert or incorporate other objects which are not string objects. This requires a little bit of steak stuff to be done however such an act is not recommended at all. Let us see how the iteration to his collection used above can be done. We have used the new for-loop here for this purpose. Collection<String> Collection = new Set<String>(); for(String stringAttribute : stringCollection) { //This is required to accomplish target with each and every stringAttribute } This tutorial helped to learn about the various phases of java collection classes step by step. Hope you liked the article. I am a software developer from India with hands on experience on java, html for over 5 years.
http://mrbool.com/how-to-work-with-collection-classes-in-java/27383
CC-MAIN-2016-07
refinedweb
1,343
56.96
- ! EXAMPLE 1 strict; use vars qw($VERSION @ISA @EXPORT);! The rest of the .pm file contains sample code for providing documentation for the extension. Finally, the Mytest.xs file should look something like this: #include "EXTERN.h" #include "perl.h" #include "XSUB).! % EXAMPLE 2. commented. In this example, we'll now begin to write XSUBs that will interact with pre-definedEEXT)'}, );. More about XSUB.. Extending your Extension page. Installing your Extension Once your extension is complete and passes all its tests, installing it is quite simple: you simply run "make install". You will either need to have write permission into the directories where Perl is installed, or ask your system administrator to run the make for you.. EXAMPLE 5 In this example, we'll do some more work with the argument stack. The previous examples have all returned only a single value. We'll now create an extension that returns an array.
https://metacpan.org/pod/release/GSAR/perl5.005_60/pod/perlxstut.pod
CC-MAIN-2016-50
refinedweb
152
61.73
Hide Forgot This is pretty weird, but here we go. On my F22 system, updating 'fedup' installs the two dnf-plugin-system-upgrade packages (as expected): [wwoods@kraid ~]$ sudo dnf update fedup Last metadata expiration check performed 0:10:25 ago on Thu Sep 3 12:19:27 2015. Dependencies resolved. ================================================================================ Package Arch Version Repository Size ================================================================================ Installing: dnf-plugin-system-upgrade noarch 0.4.0-1.fc22 wwoods-dnf-plugin-system-upgrade 41 k replacing fedup.noarch 0.9.2-1.fc22 python2-dnf-plugin-system-upgrade noarch 0.4.0-1.fc22 wwoods-dnf-plugin-system-upgrade 24 k Transaction Summary ================================================================================ Install 2 Packages Subsequently *erasing* dnf-plugin-system-upgrade results in it erasing *three* packages, including libidn: [wwoods@kraid ~]$ sudo dnf -d9 erase dnf-plugin-system-upgrade timer: config: 5 ms cachedir: /var/cache/dnf Loaded plugins: download, migrate, Query, debuginfo-install, generate_completion_cache, noroot, system-upgrade, kickstart, protected_packages, reposync, config-manager, needs-restarting, builddep, copr, playground DNF version: 1.1.0 Command: dnf -d9 erase dnf-plugin-system-upgrade Installroot: / Releasever: 22 Base command: remove Extra commands: [u'dnf-plugin-system-upgrade'] timer: sack setup: 7 ms --> Starting dependency resolution --> Finding unneeded leftover dependencies ---> Package dnf-plugin-system-upgrade.noarch 0.4.0-1.fc22 will be erased ---> Package libidn.x86_64 1.32-1.fc22 will be erased ---> Package python2-dnf-plugin-system-upgrade.noarch 0.4.0-1.fc22 will be erased --> Finished dependency resolution timer: depsolve: 154 ms Transaction Summary ================================================================================ Remove 3 Packages Installed size: 768 k Is this ok [y/N]: n I really have no idea why it would try to erase libidn, but if you *do* allow it to erase libidn, DNF stops working: [wwoods@kraid ~]$ sudo dnf install libidn Traceback (most recent call last): File " File "/usr/lib64/python2.7/site-packages/librepo/__init__.py", line 1001, in <module> import librepo._librepo ImportError: libidn.so.11: cannot open shared object file: No such file or directory This is (obviously) pretty nasty. PackageKit still works, so I can download the libidn RPM and install it that way, and then DNF works again. Here's the copr: And here's the specfile: are you able to reproduce this again? On my system when I tried I can't reproduce this. Also, if you want to debug dependencies issues try adding "--debugsolver" option and in the current working directory you will get result in debugdata directory. You can check files in it and if see something wrong can upload here. Could you please provide us your versions of rpm + dnf and also try remove libidn directly from rpm? AHA. I think I found the problem! It turns out that the `plexmediaserver` RPM I had installed on this system claimed to provide libidn.so: [root@kraid ~]# rpm -q --provides plexmediaserver | grep idn libidn.so.11()(64bit) libidn.so.11(LIBIDN_1.0)(64bit) Also, that RPM had been installed using PackageKit, which does *not* mark packages as 'userinstalled', so DNF/hawkey/libsolv considered plexmediaserver sufficient to provide everything that libidn provided, which made it eligible for autoremoval. Reinstalling the package using DNF was sufficient to fix the problem: diff -u pkcon-install/solver.result dnf-install/solver.result --- pkcon-install/solver.result +++ dnf-install/solver.result @@ -1,3 +1,2 @@ erase dnf-plugin-system-upgrade-0.4.0-1.fc22.noarch@@System -erase libidn-1.32-1.fc22.x86_64@@System erase python2-dnf-plugin-system-upgrade-0.4.0-1.fc22.noarch@@System diff -u pkcon-install/testcase.t dnf-install/testcase.t --- pkcon-install/testcase.t +++ dnf-install/testcase.t @@ -1322,6 +1322,7 @@ job userinstalled pkg pkcs11-helper-1.11-5.fc22.x86_64@@System job userinstalled pkg pkgconfig-1:0.28-8.fc22.x86_64@@System +job userinstalled pkg plexmediaserver-0.9.12.11.1406-8403350.x86_64@@System job userinstalled pkg plymouth-0.8.9-9.2013.08.14.fc22.x86_64@@System job userinstalled pkg plymouth-devel-0.8.9-9.2013.08.14.fc22.x86_64@@System So! There's two problems that caused this behavior: 1) plexmediaserver lies about its provides 2) PackageKit doesn't mark user-installed packages correctly The first one is Plex's problem, and the second is PackageKit's. The latter should probably get filed somewhere, but otherwise we won't worry about those here. The only remaining DNF issue is this: How do I *keep* DNF from trying to remove libidn? --exclude=libidn doesn't work: [root@kraid dnf]# dnf erase --exclude=libidn.* dnf-plugin-system-upgrade I did figure out that "--setopt clean_requirements_on_remove=no" disables the autoremove behavior: [root@kraid dnf]# dnf erase python2-dnf-plugin-system-upgrade \ --setopt clean_requirements_on_remove=no Dependencies resolved. ========================================================================== Package Arch Version Repository Size ========================================================================== Removing: dnf-plugin-system-upgrade noarch 0.4.0-1.fc22 @System 71 k python2-dnf-plugin-system-upgrade noarch 0.4.0-1.fc22 @System 51 k So. Maybe '--exclude' behavior needs to extend to autoclean, or maybe it might be helpful to have a simpler CLI flag for disabling autoclean? Beyond that suggestion, there's nothing to really fix in DNF here. I'll leave it to the assignees, but this could probably be closed CANTFIX. (In reply to Will Woods from comment #3) > AHA. I think I found the problem! > > It turns out that the `plexmediaserver` RPM I had installed on this system > claimed to provide libidn.so: Great you have found the problem. > So! There's two problems that caused this behavior: > > 1) plexmediaserver lies about its provides It doesn't seem to be in Fedora repos so you should report this incident somewhere else. > 2) PackageKit doesn't mark user-installed packages correctly Then I will reassign this to PK to mark packages as userinstalled from DNF cli. Can you call from PK at the end of successful transaction `dnf mark install <packages that user requested for an installation...>` [1], please? (It acts the same as changing `reason` for the package to `user` in yumdb) > The only remaining DNF issue is this: How do I *keep* DNF from trying to > remove libidn? --exclude=libidn doesn't work: `dnf mark install libidn` will tag the package as userinstalled. (Command vailable from dnf-1.1.1) [1] Just wanted to note that simply *upgrading* packages via PackageKit also causes them to be marked as not userinstalled. Currently on my system, libreoffice and whole bunch of important system packages like selinux-policy are at risk of being autoremoved. Therefore any potential fix should take into consideration that upgrading a package should maintain its current userinstalled status. Any userinstalled packages being upgraded should remain userinstalled and any automatically installed for dependency reasons should likewise remain marked as auto installed. Is marking userinstalled the same as just setting the reason file in the dnfdb to be "user"? If so, we should be doing that already... Somehow we end up with "dep": [kalev@beagle ~]$ ls /var/lib/dnf/yumdb/g/*gnome-clocks* ls: cannot access /var/lib/dnf/yumdb/g/*gnome-clocks*: No such file or directory [kalev@beagle ~]$ pkcon install gnome-clocks Resolving [=========================] Testing changes [=========================] Finished [=========================] Installing [=========================] Waiting for authentication [=========================] Querying [=========================] Downloading packages [=========================] Testing changes [=========================] Installing packages [=========================] Finished [=========================] [kalev@beagle ~]$ ls /var/lib/dnf/yumdb/g/*gnome-clocks* from_repo installed_by reason releasever [kalev@beagle ~]$ cat /var/lib/dnf/yumdb/g/*gnome-clocks*/reason dep[kalev@beagle ~]$ . Yes I just tried installing ghex via Gnome Software and the reason file states "dep" for me as well, instead of "user". I also have a lot of other system packages in the autoremove list (some of them pretty important) that have "unknown" in the reason file. (In reply to Jan Silhan from comment #8) > . Do you mean Software should exec the DNF binary? That doesn't seem right. This is still an issue in F23. *** Bug 1284194 has been marked as a duplicate of this bug. *** (In reply to Mike Goodwin from comment #11) > This is still an issue in F23. Confirmed here as well. I am refusing to use Gnome Software until this is resolved. *** Bug 1286724 has been marked as a duplicate of this bug. *** There is no need to explicitly mark packages since DNF treats all packages without reason in dnf's yumdb as installed by user. PackageKit unfortunately incorrectly marks all of installed packages with reason 'dep' as I described in #1284194. (In reply to Michal Luscon from comment #15) > There is no need to explicitly mark packages since DNF treats all packages > without reason in dnf's yumdb as installed by user. PackageKit unfortunately > incorrectly marks all of installed packages with reason 'dep' as I described > in #1284194. I think it would still make sense for PackageKit to correctly mark whether a package has been auto installed or user installed, just so that things are consistent regardless of whether a user is using DNF or Gnome Software to install stuff. (In reply to Benjamin Xiao from comment #16) > I think it would still make sense for PackageKit to correctly mark whether a > package has been auto installed or user installed, just so that things are > consistent regardless of whether a user is using DNF or Gnome Software to > install stuff. Sure, but turning off yumdb writing can be considered as a temporary workaround. . *** Bug 1287091 has been marked as a duplicate of this bug. *** *** Bug 1246570 has been marked as a duplicate of this bug. *** *** Bug 1288203 has been marked as a duplicate of this bug. *** Is this getting fixed? *** Bug 1303721 has been marked as a duplicate of this bug. *** *** Bug 1295559 has been marked as a duplicate of this bug. *** Can we get this fixed, please? Either use official way how to install packages from DNF API or set correct values to DNF db afterwards. It removes critical components on system of the users. Yes, please. We're getting more and more reports, especially in the Fedora subreddit, where people are removing important system packages by accident either by doing autoremove or by using clean_requirements_on_remove and then completely breaking their system. Somebody should probably change the version this affects also. (22 AND 23) The workaround is basically to advise people NOT to use PackageKit and those tools that use it (apper, system tray updater, etc) Alternate workaround too: disable dnf autoremove feature by default, and consider this issue a blocker to re-enabling it Since gnome-software is going to be used for performing system upgrades in F24 (thus affecting all packages in this way), I'm proposing this as a blocker. It does not play along with dnf well, causing important packages to be removed when dnf is used. Here's a trivial reproducer: [kparal@localhost ~]$ sudo dnf autoremove Last metadata expiration check performed 0:44:42 ago on Mon Feb 15 10:34:45 2016. Dependencies resolved. Nothing to do. Complete! [kparal@localhost ~]$ pkcon install simple-scan Resolving [=========================] Finished [=========================] Testing changes [=========================] Installing [=========================] Waiting for authentication [=========================] Downloading packages [=========================] Testing changes [=========================] Installing packages [=========================] Finished [=========================] [kparal@localhost ~]$ sudo dnf autoremove Last metadata expiration check performed 0:45:02 ago on Mon Feb 15 10:34:45 2016. Dependencies resolved. ====================================================================================== Package Arch Version Repository Size ====================================================================================== Removing: simple-scan x86_64 3.19.4-2.fc24 @rawhide 1.5 M Transaction Summary ====================================================================================== Remove 1 Package Installed size: 1.5 M Is this ok [y/N]: n This happens with: PackageKit-1.1.0-1.fc24.x86_64 libhif-0.2.2-1.fc24.x86_64 gnome-software-3.19.4-2.fc24.x86_64 dnf-1.1.6-2.fc24.noarch rpm-4.13.0-0.rc1.23.fc24.x86_64 librepo-1.7.17-3.fc24.x86_64 hawkey-0.6.2-4.fc24.x86_64 Discussed at 2016-02-15 blocker review meeting: [1]. This bug was accepted as a Beta blocker: we hold this violates combination of "The installed system must be able to download and install updates with the default console package manager." (Alpha) and "The installed system must be able to download and install updates with the default graphical package manager in all release-blocking desktops." (Beta) as it's believed that doing the former after the latter could remove critical packages [1] *** Bug 1309314 has been marked as a duplicate of this bug. *** *** Bug 1309513 has been marked as a duplicate of this bug. *** As a progress update, I was talking with Kalev Lember about this today. His response was "I'll see if I can come up with a fix for this this week". (In reply to Benjamin Xiao from comment #18) > . I would like to stress the importance of what Ben is saying here as I've also verified this behavior in an unintended way (researching what happens when you mess with /var/lib/dnf/yumdb/*/*/reason in various ways) The solution in PK must first observe if the package has an existing reason file, and copy that reason through during an upgrade. If and when a new package dependency is pulled in by PK and it doesn't create the proper corresponding entries in /var/lib/dnf/yumdb/*/ then DNF will in fact treat it as a @System userinstalled package. This is obviously undesirable because there will then be no truthful way for the user to remove unneeded dependencies, causing the system to balloon over time. I looked into fixing this up last week and posted the patches to (libhif) (PackageKit) Richard wanted to have tests covering the area before merging the fixes though, so this may take a bit before the fixes get merged upstream into libhif. The whole installing rpms area is currently lacking tests and we need to come up with an infrastructure for them in libhif before we can actually write tests for yumdb writing. Kalev, thanks for the update. I understand the need for tests in these system critical areas. However, please note that this is one of the two blockers Fedora 24 Beta is waiting on and Go/NoGo is tomorrow (which is going to be NoGo, as it seems), so this might not be a good time to start creating a test infrastructure from scratch, in case it would take weeks, not days. Is it possible to come up with something that would be done relatively fast (ideally this week, so that we have time to test it)? Thanks. Richard, what do you think? I've built this as without the tests. Please test! libhif-0.2.2-3.fc24 has been submitted as an update to Fedora 24. One of the major cases to this bug is in installing updates graphically, can someone confirm that this libhif update does not blindly mark all packages that it handles user installed? I would be a shame if all dep updates -> user. I don't have the appropriate time or setup at the moment to do it myself, thanks! FYI it's the phrasing "fixes an issue where installs / updates done through PackageKit incorrectly marked packages as dependencies where they should have been marked as user installed" in the update notes that causing me concern. (In reply to Mike Goodwin from comment #41) > One of the major cases to this bug is in installing updates graphically, can > someone confirm that this libhif update does not blindly mark all packages > that it handles user installed? I would be a shame if all dep updates -> > user. Nope, it doesn't blindly mark everything as "user", just things that are explicitly installed. Dependencies get marked as "dep". Hopefully, I mean. Barring any bugs. Testing welcome in any case :) I try to test this extensively and it seems to work well. Only requested packages are marked as userinstalled, their deps are not. You can mix and match pkcon and dnf operations. Updating existing packages keeps the current flags. (Please note we'll need a similar fix in F23, in order to support graphical system upgrades using gnome-software. Please add the fixed libhif to the copr repo, thanks.) Thanks Kamil. I think updated libhif could even go to F23 proper -- it basically just has bug fixes compared to the current F23 libhif build. I can help test on F23 if packages are available. Thanks for the fix! I've been waiting for this for a while. I was afraid to use Gnome Software for basically all of F23. (In reply to Benjamin Xiao from comment #45) > I can help test on F23 if packages are available. The fix is not yet available for F23, we will mention it here once it is. . (In reply to Kamil Páral from comment #47) > If the changes seem safe enough, please put it into bodhi and set a high > karma threshold for it (or better yet disable autopush completely), so that > we can properly test it and make sure it doesn't break anything. Thanks. Second this. libhif-0.2.2-3.fc24 has been pushed to the Fedora 24 testing repository. If problems still persist, please make note of it in this bug report. See for instructions on how to install test updates. You can provide feedback for this update here: libhif-0.2.2-3.fc23 has been submitted as an update to Fedora 23. (In reply to Kamil Páral from comment #47) > . Done. libhif-0.2.2-3.fc23 has been pushed to the Fedora 23 testing repository. If problems still persist, please make note of it in this bug report. See for instructions on how to install test updates. You can provide feedback for this update here: This works as I would expect it to. My test case was htop I first removed it, installed it with apper, downgraded it with dnf, then upgraded it with the system-tray updater (im a KDE user) Under all circumstances the file had the correct reason in /var/lib/dnf/yumdb/h/*/reason and as a result showed up under `sudo dnf history userinstalled` and was not wanted to be removed by `sudo dnf autoremove` I will continue to use this to install updates and report back as necessary. Thanks! I started to get my system into a state to test this and realised I was only not bitten by the dnf autoremove bug due to luck on autoremove wanting to get rid of 32bit libraries required by steam and then getting a package DB error with the 64bit ones there as well. After marking the 64 bit ones as user installed (no 64 bit steam to have them appear as dependencies) a large proportion of my system wanted to be removed on a dnf autoremove ... I'm slowly working my way through to mark as user installed things I know are not dependencies but the regular user is not going to be able to handle that. It's all well and good fixing the ongoing issue but how can the existing situation be retrofitted with the correct reason to avoid half the system being removed? At the least should we have on the F24 common bugs page the steps to verify if autoremove is dangerous on the system in question (just an dnf --assumeno autoremove is enough to check what will go) along with the dnf mark install mantra) that a user can go through to avoid issues or recover safely prior to/during the F24 update? *** Bug 1320713 has been marked as a duplicate of this bug. *** I agree, we should figure out what we can advise to users already affected by this, because this is not going to fix the userinstalled flags retroactively. So even if they update to latest libhif, dnf still might autoremove half of their system at any point in the future. Kalev, Richard, Jan, any advice here? Can we do something better than running "dnf mark install" for all installed packages (very suboptimal, but still better than not doing it)? (In reply to Kamil Páral from comment #56) > Kalev, Richard, Jan, any advice here? Can we do something better than > running "dnf mark install" for all installed packages (very suboptimal, but > still better than not doing it)? I don't have any good ideas, sorry. Rather than mark *everything* installed as user, can we perhaps walk the tree and mark those without anything dependent on them ... set those to user? Their dependencies would still be dep then and correctly removed if the user removes them. It's not perfect but would be better than ignoring the issue or marking everything user, thus negating the point of autoremove, as a middle ground? libhif-0.2.2-3.fc24 has been pushed to the Fedora 24 stable repository. If problems still persist, please make note of it in this bug report. (In reply to James Hogarth from comment #58) > Rather than mark *everything* installed as user, can we perhaps walk the > tree and mark those without anything dependent on them ... set those to user? I tried this, with clean F23 installed from Live, then fully updated using PackageKit, and then retrieving all leave packages using `package-cleanup --all --leaves` and marking them as installed. It solved the problem for that very moment. However, some of the packages which were marked as userinstalled originally, were not marked as such afterwards (examples: alsa-utils, avahi, bash). They got updated (therefore stripped of userinstalled flag), but were not leaves (therefore the flag was not added by my script). There is a real chance that the user can uninstall something that has those packages as deps, they become leave packages, and they'll get removed with the next dnf transaction. The only safe way seems to be marking all installed packages as userinstalled. It's ineffective, but it's the best way to ensure people won't lose important packages unexpectedly. Kalev, the fc23 update has received a good amount of karma and has been in testing for more than a week. I think it should be safe now to push it into updates. Thanks. Submitted to stable now, thanks. libhif-0.2.2-3.fc23 has been pushed to the Fedora 23 stable repository. If problems still persist, please make note of it in this bug report. *** Bug 1338198 has been marked as a duplicate of this bug. *** and because of such annoying bugs "yum-utils" aka "package-cleanup --leaves" or "package-cleanup --leaves --all" should babble about deprecation until it's functionality is 100% ported to DNF and NO- i am not talking about some "dnf magickcommand" but "package-cleanup" as it is and works rock solid for many years, long before DNF was planned and currently too The F24 release notes have suggestions on what to do if you have been affected by this issue to assist in cleaning up the fallout. Applies to F23 also. @Gerald Cox in the link you provided they suggest to mark "all" the packages as system-required. I'm wondering if it would be possible to be more precise in marking the packages, perhaps following these steps: 1) setup a VM with a Fedora "vanilla" version 2) obtain the list of packages marked as "user installed" from that Fedora where the bug was not exploited 3) Use that list of packages to mark as "user installed" the packages in a pc with "broken" Fedora. This should reduce significantly the number of packages that are not correctly marked as "user installed" 4) Run trough the list of the remaining packages that DNF would like to remove and manually mark the ones that the user knows he manually installed 5) if some packages remain from the selections operated at steps 3) and 4), then either mark them as user installed or allow them to be removed. Of course in the latter case one must know what he's doing. Could this work in your opinion? Thanks (In reply to Giordano Battilana from comment #67) > @Gerald Cox in the link you provided they suggest to mark "all" the packages > as system-required. > ... > > Could this work in your opinion? > Thanks I asked a question about this on the development list, and the above was the suggested recommendation. I was thinking that for F24, this would be automagically resolved during the upgrade process, but apparently there is a chance that some of the packages on your system may be removed instead of upgraded. This is indeed a nasty bug because depending on which package "may" be removed it could cause havoc on your system. I believe you can see which packages which are affected by issuing: dnf autoremove BE SURE TO REMOVE N to the prompt so you don't actually remove anything. I have been doing a "dnf reinstall" package_name on the packages that I want to be sure are retained. I believe the idea behind the recommendation in the release notes was it was a quick and easy way to ensure you wouldn't be negatively impacted by the fallout from this bug. Yes, there is a possibility that it will keep a few extra packages on your system that aren't needed, but we're talking about a really small amount of space. The idea being that the time and effort to figure out what you need and what you don't need may not be worth it - and I tend to agree with that assessment. What does `Package gpg-pubkey is not installed.` mean? (In reply to Sudhir Khanger from comment #69) > What does `Package gpg-pubkey is not installed.` mean? It's harmless. RPM prints imported keys inside the `rpm -qa` output, even though they are not packages. Therefore they can't be marked as userinstalled. No issue. *** Bug 1327556 has been marked as a duplicate of this bug. *** *** Bug 1290921 has been marked as a duplicate of this bug. *** *** Bug 1277115 has been marked as a duplicate of this bug. *** Hi. I think I discovered that this bug is still existing "autoremove" try to remove essential packages or packages that should not be removed. 1st please know the following: - I use Fedora 24 X64 Cinnamon edition (Not GNOME) - I did not installed GNOME or other DE as additional DE - I did not installed GNOME software center at all - I have no packagekit on my system - I have no libhif on my system When I saw this bug closed, I asked about this in Fedora help forum at this link: In forum they ask me to run "sudo dnf autoremove" but not allow it to complete. Just run it, copy list of package that showed to be removed then abort process & ask in forum about these. I did that. The following is the list to be removed: Last metadata expiration check: 2:38:36 ago on Thu Oct 6 06:52:38 2016. Dependencies resolved. ================================================== ============================== Package Arch Version Repository Size ================================================== ============================== Removing: GLee x86_64 5.4.0-10.fc24 @fedora 728 k ImageMagick-c++ x86_64 6.9.3.0-2.fc24 @fedora 625 k SDL2 x86_64 2.0.4-8.fc24 @updates 1.1 M atlas x86_64 3.10.2-12.fc24 @anaconda 23 M aubio x86_64 0.4.2-2.fc24 @fedora 798 k boost-regex x86_64 1.60.0-7.fc24 @updates 1.1 M clang-libs x86_64 3.8.0-2.fc24 @updates 28 M clutter-gst2 x86_64 2.0.18-1.fc24 @anaconda 191 k compat-lua-libs x86_64 5.1.5-5.fc24 @fedora 485 k cwiid x86_64 0.6.00-27.20100505gitfadf11e.fc24 @fedora 71 k fftw-libs-single x86_64 3.3.4-7.fc24 @fedora 2.1 M frei0r-plugins x86_64 1.5-1.fc24 @fedora 5.1 M gavl x86_64 1.4.0-8.fc24 @fedora 4.2 M gmic x86_64 1.7.2-1.fc24 @updates 15 M hyperv-daemons-license noarch 0-0.14.20150702git.fc24 @anaconda 18 k hypervfcopyd x86_64 0-0.14.20150702git.fc24 @anaconda 12 k hypervkvpd x86_64 0-0.14.20150702git.fc24 @anaconda 31 k hypervvssd x86_64 0-0.14.20150702git.fc24 @anaconda 12 k kf5-kplotting x86_64 5.26.0-1.fc24 @updates 106 k ladspa x86_64 1.13-16.fc24 @fedora 116 k ladspa-swh-plugins x86_64 0.4.15-26.fc24 @fedora 1.5 M libbs2b x86_64 3.1.0-16.fc24 @fedora 54 k libclc x86_64 0.2.0-3.20160207gitdc330a3.fc24 @fedora 25 M libfreenect x86_64 0.5.3-1.fc24 @fedora 370 k libgdither x86_64 0.6-11.fc24 @fedora 41 k libguess x86_64 1.2-3.fc24 @fedora 36 k liblo x86_64 0.28-2.fc24 @fedora 162 k liblrdf x86_64 0.5.0-10.fc24 @fedora 52 k libltc x86_64 1.2.0-2.fc24 @fedora 34 k libmpg123 x86_64 1.22.4-1.fc24 @rpmfusion-free 443 k liboil x86_64 0.3.16-13.fc24 @fedora 568 k libopenshot x86_64 0.1.1-2.fc24 @rpmfusion-free 940 k libopenshot-audio x86_64 0.1.1-1.fc24 @rpmfusion-free 4.8 M libprojectM-qt x86_64 2.1.0-1.fc24 @fedora 360 k libresample x86_64 0.1.3-22.fc24 @fedora 53 k librtmp x86_64 2.4-7.20160224.gitfa8646d.fc24 @rpmfusion-free-updates 152 k libunicap x86_64 0.9.12-17.fc24 @fedora 401 k lilv x86_64 0.20.0-5.fc24 @fedora 153 k lirc-libs x86_64 0.9.4a-1.fc24 @updates 282 k mencoder x86_64 1.3.0-1.fc24 @rpmfusion-free 2.6 M mesa-libOpenCL x86_64 12.0.3-1.fc24 @updates 1.8 M mjpegtools-libs x86_64 2.1.0-5.fc24 @rpmfusion-free 392 k mkvtoolnix x86_64 9.2.0-1.fc24 @updates 17 M mlt-python x86_64 6.2.0-2.fc24 @rpmfusion-free-updates 622 k mplayer x86_64 1.3.0-1.fc24 @rpmfusion-free 3.8 M mplayer-common x86_64 1.3.0-1.fc24 @rpmfusion-free 1.3 M oggvideotools x86_64 0.9-2.fc24 @fedora 4.7 M ogmtools x86_64 1.5-17.fc24 @fedora 410 k opencl-filesystem noarch 1.0-4.fc24 @fedora 0 opencore-amr x86_64 0.1.3-4.fc24 @rpmfusion-free 342 k opencv x86_64 2.4.12.3-3.fc24 @anaconda 25 M opencv-python x86_64 2.4.12.3-3.fc24 @anaconda 1.3 M pugixml x86_64 1.7-2.fc24 @fedora 232 k python-nose noarch 1.3.7-7.fc24 @anaconda 1.1 M python-qt5-rpm-macros noarch 5.6-4.fc24 @updates 137 python2-numpy x86_64 1:1.11.0-4.fc24 @anaconda 15 M python3-httplib2 noarch 0.9.2-2.fc24 @fedora 291 k python3-libopenshot x86_64 0.1.1-2.fc24 @rpmfusion-free 1.6 M python3-qt5 x86_64 5.6-4.fc24 @updates 22 M python3-qt5-webkit x86_64 5.6-4.fc24 @updates 573 k python3-sip x86_64 4.18-2.fc24 @updates 457 k qt5-qtconnectivity x86_64 5.6.1-2.fc24 @updates 1.3 M qt5-qtenginio x86_64 1:1.6.1-2.fc24 @updates 589 k qt5-qtmultimedia x86_64 5.6.1-3.fc24 @updates 3.1 M qt5-qtserialport x86_64 5.6.1-1.fc24 @updates 190 k qt5-qttools-libs-clucene x86_64 5.6.1-2.fc24 @updates 132 k qt5-qttools-libs-help x86_64 5.6.1-2.fc24 @updates 647 k qt5-qtwebsockets x86_64 5.6.1-2.fc24 @updates 230 k rubberband x86_64 1.8.1-8.fc24 @fedora 879 k serd x86_64 0.20.0-3.fc24 @fedora 122 k sord x86_64 0.12.2-8.fc24 @fedora 72 k sratom x86_64 0.4.6-4.fc24 @fedora 42 k suil x86_64 0.8.2-4.fc24 @fedora 77 k theora-tools x86_64 1:1.1.1-14.fc24 @fedora 110 k uchardet x86_64 0.0.5-4.fc24 @updates 169 k xorg-x11-server-common x86_64 1.18.3-2.fc24 @anaconda 127 k xvidcore x86_64 1.3.4-2.fc24 @rpmfusion-free 907 k youtube-dl noarch 2016.09.15-1.fc24 @updates 6.8 M Transaction Summary ================================================== ============================== Remove 78 Packages Installed size: 234 M We detect - till now - 2 suspicious packages: "xorg-x11-server-common" & "youtube-dl" I entered in terminal the following: xorg-x11-server-common --version But I got this: bash: xorg-x11-server-common: command not found Then I open Yum extender (DNF) & searched for "xorg" & got this: xorg-x11-server-common 1.18.4-4fc24 X86_64 BUT NOT 1.13.3-2 WHICH SHOWN BY "AUTOREMOVE" ! What does this mean ?! But, I searched for "youtube-dl because I saw it came to me in one of updates. It appear to me in package manager as: youtube-dl 2016.09.15-1.fc24 noarch & in autoremove list it appear as 2016-09.15-1 ALSO! In 1st example it seem that no bug but in 2nd example it seem that it is still bugy !!! Note: both "xorg-x11-server-common" & "youtube-dl" appearing in green color in Yum extender (DNF) Because this bug is so annoying & dangerous, I decided to post in this closed topic. (In reply to yousifjkadom@yahoo.com from comment #74) Hi, if you've never used packagekit, then you're not affected by this bug. Removing xorg-x11-server-common doesn't sound right, but it's likely a different problem. Debugging that requires some experience, so either ask for help on forum/irc, or report a separate bug. Thanks. *** Bug 1376597 has been marked as a duplicate of this bug. *** I probably encountered this bug with libhif-0.2.3-1.fc25.x86_64 on F25. Should the bug be opened again? Installation of gnome-builder with Software caused removal of wine, steam and mesa-dri-drivers. The removal of the last package caused the system unable to boot into gdm. I fixed the mess by logging into the text mode console and `sudo dnf install mesa-dri-drivers`. The actual transaction in /var/lib/PackageKit/transactions.db is: downloading python3-jedi;0.9.0-5.fc25;noarch;fedora downloading devhelp-libs;1:3.22.0-1.fc25;x86_64;fedora downloading clang-devel;3.8.1-1.fc25;x86_64;updates downloading clang-libs;3.8.1-1.fc25;x86_64;updates downloading clang;3.8.1-1.fc25;x86_64;updates downloading qt-creator-data;4.1.0-2.fc25.1;noarch;updates downloading qt-creator;4.1.0-2.fc25.1;x86_64;updates downloading mesa-libxatracker;13.0.4-1.fc25;x86_64;updates downloading llvm-libs;3.8.1-2.fc25;i686;updates downloading mesa-libOSMesa;13.0.4-1.fc25;i686;updates downloading mesa-libOSMesa;13.0.4-1.fc25;x86_64;updates downloading mesa-libGLES;13.0.4-1.fc25;x86_64;updates downloading mesa-libGL-devel;13.0.4-1.fc25;x86_64;updates downloading mesa-libglapi;13.0.4-1.fc25;i686;updates downloading mesa-libGL;13.0.4-1.fc25;i686;updates downloading mesa-libglapi;13.0.4-1.fc25;x86_64;updates downloading mesa-libGL;13.0.4-1.fc25;x86_64;updates downloading llvm-libs;3.8.1-2.fc25;x86_64;updates downloading llvm;3.8.1-2.fc25;x86_64;updates downloading sysprof-cli;3.22.3-1.fc25;x86_64;updates downloading libsysprof-ui;3.22.3-1.fc25;x86_64;updates downloading gnome-builder;3.22.4-1.fc25;x86_64;updates updating llvm-libs;3.8.1-2.fc25;x86_64;updates updating mesa-libglapi;13.0.4-1.fc25;x86_64;updates updating clang-libs;3.8.1-1.fc25;x86_64;updates installing sysprof-cli;3.22.3-1.fc25;x86_64;updates installing libsysprof-ui;3.22.3-1.fc25;x86_64;updates updating qt-creator-data;4.1.0-2.fc25.1;noarch;updates updating qt-creator;4.1.0-2.fc25.1;x86_64;updates updating clang;3.8.1-1.fc25;x86_64;updates updating mesa-libGL;13.0.4-1.fc25;x86_64;updates installing devhelp-libs;1:3.22.0-1.fc25;x86_64;fedora installing gnome-builder;3.22.4-1.fc25;x86_64;updates updating mesa-libGL-devel;13.0.4-1.fc25;x86_64;updates updating clang-devel;3.8.1-1.fc25;x86_64;updates updating mesa-libGLES;13.0.4-1.fc25;x86_64;updates updating mesa-libOSMesa;13.0.4-1.fc25;x86_64;updates updating llvm;3.8.1-2.fc25;x86_64;updates updating mesa-libxatracker;13.0.4-1.fc25;x86_64;updates installing python3-jedi;0.9.0-5.fc25;noarch;fedora updating mesa-libglapi;13.0.4-1.fc25;i686;updates updating llvm-libs;3.8.1-2.fc25;i686;updates updating mesa-libOSMesa;13.0.4-1.fc25;i686;updates updating mesa-libGL;13.0.4-1.fc25;i686;updates removing wine;2.7-1.fc25;x86_64;installed removing steam;1.0.0.54-9.fc25;i686;installed removing mesa-dri-drivers;17.0.5-2.fc25;i686;installed cleanup mesa-libOSMesa;17.0.5-2.fc25;x86_64;installed cleanup mesa-libGL-devel;17.0.5-2.fc25;x86_64;installed cleanup mesa-libGL;17.0.5-2.fc25;x86_64;installed cleanup clang-devel;3.9.1-2.fc25;x86_64;installed cleanup mesa-libGLES;17.0.5-2.fc25;x86_64;installed cleanup clang;3.9.1-2.fc25;x86_64;installed removing mesa-dri-drivers;17.0.5-2.fc25;x86_64;installed cleanup qt-creator-data;4.1.0-2.fc25.2;noarch;installed cleanup qt-creator;4.1.0-2.fc25.2;x86_64;installed cleanup clang-libs;3.9.1-2.fc25;x86_64;installed cleanup mesa-libxatracker;17.0.5-2.fc25;x86_64;installed cleanup llvm;3.9.1-3.fc25;x86_64;installed cleanup mesa-libglapi;17.0.5-2.fc25;x86_64;installed cleanup llvm-libs;3.9.1-3.fc25;x86_64;installed Matej, this is most likely a completely different issue. Open up a new bug, probably in gnome bugzilla against gnome-software or packagekit. It seems to be too willing to downgrade packages, for some reason. And attach more information about your system, especially if you have any third-party repos enabled. Those packages you downgraded to are very old. Either it's some third party repo, or some very outdated mirror (and packagekit failed to recognize that it's outdated). I'm not sure if the PackageKit downgraded the packages. The packages version numbers in the transactions.db are confusing. You can see at the end of the log with "cleanup" prefix the up-to-date versions of the packages (that are now present on my system). What bothers me most are the removed packages: removing wine;2.7-1.fc25;x86_64;installed removing steam;1.0.0.54-9.fc25;i686;installed removing mesa-dri-drivers;17.0.5-2.fc25;i686;installed removing mesa-dri-drivers;17.0.5-2.fc25;x86_64;installed Is this not caused by this bug?
https://bugzilla.redhat.com/show_bug.cgi?id=1259865
CC-MAIN-2019-18
refinedweb
6,419
59.09
Deploy Azure File Sync. We strongly recommend that you read Planning for an Azure Files deployment and Planning for an Azure File Sync deployment before you complete the steps described in this article. Prerequisites An Azure file share in the same region that you want to deploy Azure File Sync. For more information, see: - Region availability for Azure File Sync. - Create a file share for a step-by-step description of how to create a file share. At least one supported instance of Windows Server or Windows Server cluster to sync with Azure File Sync. For more information about supported versions of Windows Server, see Interoperability with Windows Server. The Az PowerShell module may be used with either PowerShell 5.1 or PowerShell 6+. You may use the Az PowerShell module for Azure File Sync on any supported system, including non-Windows systems, however the server registration cmdlet must always be run directly on the Windows Server instance you are registering. On Windows Server 2012 R2, you can verify that you are running at least PowerShell 5.1.* by looking at the value of the PSVersion property of the $PSVersionTable object: $PSVersionTable.PSVersion If your PSVersion value is less than 5.1.*, as will be the case with most fresh installations of Windows Server 2012 R2, you can easily upgrade by downloading and installing Windows Management Framework (WMF) 5.1. The appropriate package to download and install for Windows Server 2012 R2 is Win8.1AndW2K12R2-KB*******-x64.msu. PowerShell 6+ can be used with any supported system, and can be downloaded via its GitHub page. Important If you plan to use the Server Registration UI, rather than registering directly from PowerShell, you must use PowerShell 5.1. If you have opted to use PowerShell 5.1, ensure that at least .NET 4.7.2 is installed. Learn more about .NET Framework versions and dependencies on your system. The Az PowerShell module, which can be installed by following the instructions here: Install and configure Azure PowerShell. The Az.StorageSync module, which is currently installed independently of the Az module: Install-Module Az.StorageSync -AllowClobber Prepare Windows Server to use with Azure File Sync For each server that you intend to use with Azure File Sync, including each server node in a Failover Cluster, disable Internet Explorer Enhanced Security Configuration. This is required only for initial server registration. You can re-enable it after the server has been registered. - Open Server Manager. - Click Local Server: - On the Properties subpane, select the link for IE Enhanced Security Configuration. - In the Internet Explorer Enhanced Security Configuration dialog box, select Off for Administrators and Users: Deploy the Storage Sync Service The deployment of Azure File Sync starts with placing a Storage Sync Service resource into a resource group of your selected subscription. We. Note The Storage Sync Service inherited access permissions from the subscription and resource group it has been deployed into. We recommend that you carefully check who has access to it. Entities with write access can start syncing new sets of files from servers registered to this storage sync service and cause data to flow to Azure storage that is accessible to. Install the Azure File Sync agent. Important If you intend to use Azure File Sync with a Failover Cluster, the Azure File Sync agent must be installed on every node in the cluster. Each node in the cluster must registered to work with Azure File Sync. We. For more information, see Azure File Sync update policy. When the Azure File Sync agent installation is finished, the Server Registration UI automatically opens. You must have a Storage Sync Service before registering; see the next section on how to create a Storage Sync Service. Register Windows Server with Storage Sync Service. Note Server registration. A new SAS token cannot be issued to the server once the server is unregistered, thus removing the server's ability to access your Azure file shares, stopping any sync. The Server Registration UI should open automatically after installation of the Azure File Sync agent. (see Deploy! Important You can make changes to any cloud endpoint or server endpoint in the sync group and have your files synced to the other endpoints in the sync group. If you make a change to the cloud endpoint (Azure file share) directly, changes first need to be discovered by an Azure File Sync change detection job. A change detection job is initiated for a cloud endpoint only once every 24 hours. For more information, see Azure Files frequently asked questions. To create a sync group, in the Azure portal, go to your Storage Sync Service, and then select + Sync group: In the pane that opens, enter the following information to create a sync group with a cloud endpoint: - Sync group name: The name of the sync group to be created. This name must be unique within the Storage Sync Service, but can be any name that is logical for you. - Subscription: The subscription where you deployed the Storage Sync Service in Deploy the Storage Sync Service. -. Create a server endpoint A server endpoint represents a specific location on a registered server, such as a folder on a server volume. A server endpoint must be a path on a registered server (rather than a mounted share), and to use cloud tiering, the path must be on a non-system volume. Network attached storage (NAS) is not supported. To add a server endpoint, go to the newly created sync group and then select Add server endpoint. 50%. Onboarding with Azure File Sync The recommended steps to onboard on Azure File Sync for the first with zero downtime while preserving full file fidelity and access control list (ACL) are as follows: - Deploy a Storage Sync Service. - Create a sync group. - Install Azure File Sync agent on the server with the full data set. - Register that server and create a server endpoint on the share. - Let sync do the full upload to the Azure file share (cloud endpoint). - After the initial upload is complete, install Azure File Sync agent on each of the remaining servers. - Create new file shares on each of the remaining servers. - Create server endpoints on new file shares with cloud tiering policy, if desired. (This step requires additional storage to be available for the initial setup.) - Let Azure File Sync agent to do a rapid restore of the full namespace without the actual data transfer. After the full namespace sync, sync engine will fill the local disk space based on the cloud tiering policy for the server endpoint. - Ensure sync completes and test your topology as desired. - Redirect users and applications to this new share. - You can optionally delete any duplicate shares on the servers. If you don't have extra storage for initial onboarding and would like to attach to the existing shares, you can pre-seed the data in the Azure files shares. This approach is suggested, if and only if you can accept downtime and absolutely guarantee no data changes on the server shares during the initial onboarding process. - Ensure that data on any of the server can't change during the onboarding process. - Pre-seed Azure file shares with the server data using any data transfer tool over the SMB e.g. Robocopy, direct SMB copy. Since AzCopy does not upload data over the SMB so it can't be used for pre-seeding. - Create Azure File Sync topology with the desired server endpoints pointing to the existing shares. - Let sync finish reconciliation process on all endpoints. - Once reconciliation is complete, you can open shares for changes. Please be aware that currently, pre-seeding approach has a few limitations - - Full fidelity on files is not preserved. For example, files lose ACLs and timestamps. - Data changes on the server before sync topology is fully up and running can cause conflicts on the server endpoints. - After the cloud endpoint is created, Azure File Sync runs a process to detect the files in the cloud before starting the initial sync. The time taken to complete this process varies depending on the various factors like network speed, available bandwidth, and number of files and folders. For the rough estimation in the preview release, detection process runs approximately at 10 files/sec. Hence, even if pre-seeding runs fast, the overall time to get a fully running system may be significantly longer when data is pre-seeded in the cloud. Migrate a DFS Replication (DFS-R) deployment to Azure File Sync To migrate a DFS-R deployment to Azure File Sync: - Create a sync group to represent the DFS-R topology you are replacing. - Start on the server that has the full set of data in your DFS-R topology to migrate. Install Azure File Sync on that server. - Register that server and create a server endpoint for the first server to be migrated. Do not enable cloud tiering. - Let all of the data sync to your Azure file share (cloud endpoint). - Install and register the Azure File Sync agent on each of the remaining DFS-R servers. - Disable DFS-R. - Create a server endpoint on each of the DFS-R servers. Do not enable cloud tiering. - Ensure sync completes and test your topology as desired. - Retire DFS-R. - Cloud tiering may now be enabled on any server endpoint as desired. For more information, see Azure File Sync interop with Distributed File System (DFS). Next steps Feedback Send feedback about:
https://docs.microsoft.com/en-us/azure/storage/files/storage-sync-files-deployment-guide?tabs=azure-powershell
CC-MAIN-2019-26
refinedweb
1,577
63.9
In this tutorial, I will walk you step by step towards creating your first Web Application. In .NET runtime, web applications are hosted in an ASP.NET page. ASP.NET provides a great working environment with other .NET languages including C#, VB.NET, and JScript. In this tutorial, I have used C# as programming language. The goal of this tutorial is to show you how to start your first Web Application without knowing much of ASP programming. This tutorial is divided in to three parts - 1. Introduction of DataGrid Web Control.2. Web Forms Life Cycle3. Developing Web Forms Applications using VS.NET ASP.NET Platform Requirements To run an ASP.NET application, you must have to have Web Server (IIS) installed on Windows 2000 and Windows NT 4, Service Pack 6a operating systems. You can use any .NET language to write code including VB.NET and C#. To develop this project, I have used Windows 2000, Visual Studio .NET Beta 1, Personal Web Server and C#. Part 1. Introduction of DataGrid Control This tutorial uses DataGrid Web Control to display data from a database table. Before we start our application, I would like to discuss DataGrid Web Control. DataGrid Web Control A DataGrid Web control displays tabular data from a database. You can connect a database table or partial table data to the grid with the help of ADO.NET DataSet object. First you create a ADODataSetCommand object and select data from a database table. In this sample example, I have used an access database called myDB.mdb, which has a table myTable. // Create an object of ADODataSetCommand Now, you use DataSource property of DataGrid to populate the grid with the DataSet's data followed by DataBind() method. A DataGrid Web control contains a rich set of properties, which let you customize the grid the way you want. You can set these properties by right clicking on the DataGrid and click Property Page button. Clicking Property Page button brings you DataGrid control properties. From here, you can customize your DataGrid control the way you want. General PropertiesThis page let you set DataSource. You can allow headers and footers to be displayed. Allow Sorting check box allows sorting in the grid. Columns PropertiesBy using this page, you can add columns at design time and their properties. Paging PropertiesPaging is one of the great feature of the grid control. This page allows you to set number of lines per page, format of grid lines and enables custom page. Format PropertiesThis page allows you to set color and font of the grid, header, footer and the pages. Borders Properties This page allows you to set border color and font, cell padding and spacing, and type of lines in the grid. Part 2: Web Forms Life Cycle If you have ever developed Distributed application in previous versions of Visual Studio for Windows, you will see enough similarities between Web Forms applications and distributed applications. In this tutorial, I will discuss only few things about Web Forms life cycle to give you an idea how the processing works in Web Forms. I will be coming with a detailed article about Web Forms Life Cycle in near future. There are four basic stages in a Web Forms life cycle. These stages are Intialization, Loading page, event handling, and Cleaning up resources. Page Initialization First event occurs when a page is being initialized. The event occurred is called Page_Init. Controls should perform all initialization steps required to create and set up an instantiation. Page Load Page load stage is after initialization. The event occured is Page_Load. You use this event for following Event Handling Every action on a Web Form fires an event which goes to the server. There are two views of a Web Form. A Client view and a server view. All the processing of data is being done on the server. When you raise an event from the browser by mouse click or other medium, the event goes to the server and returns the corresponding data. Clean Up This is the last stage when a form has performed it task and ready to discard. Page fires Page_Unload event and perform final cleanup work, such as: Part 3: Developing Web Application Ok, Now let's proceed to developing our Web Forms Application. Creating Project Skeleton Creating a Web Application using Visual Studio .NET is not a big deal. You just follow few simple steps and Wizard creates an nice skeleton for you. After that you use Web Controls ToolBox to drop Web Controls to your ASP page and set these control properties as you do in any form based GUI application. Ok, follow these simple steps: Step 1: Select a Project From Visual Studio .NET main menu, select File->New->Project. Now you pick Visual C# Projects->Web Application. Type name of your project in the Name text box, and Location text box is your web server's rood directory. You can pick the right path by using Browse button. After selecting these options, hit OK. Step 2: Setting Properties The next screen looks like this. WebForm1.aspx is default ASP.NET page, which hosts the ASP.NET code and controls. You can treat this page as a WebForm. Use Toolbox on the left side bar to drag and drop controls on the page. Right click on the page to set page properties. There are three tabs. The General tab let you pick the scripting language and page layout. Other two tabs are for Color and Fonts for page text, hyperlinks, and visited hyperlinks and keywords. Step 3: Adding Controls to the WebForm Now use ToolBox to add Web Controls to the page. I add two controls, a button and a DataGrid control to the page. You can set properties of these controls by right cli Step 4: Adding Event Handler I have shown you in the previous discussion of this tutorial about DataGrid and ADO.NET. I will use same technique to fill the DataGrid control to populate data from a database. I will populate the grid on button click. To write an event handler corresponding the button, double click on the button. This action throws you in a cs file called WebForm1.cs. The event handler for button click code looks like this: Button1.Click += namespace Now write the code on button's click event to populate the grid control. You need to add reference to System.Data.ADO namespace before using ADO objects in the project. using public { ADODataSetCommand CmdSet = Now click the button and see the results. It looks like this. The DataGrid is populated with the data from myTable of the database. This was very basic Web Application. Now you can customize the Grid Control accordingly by setting its properties and develop more useful applications such as reading, deleting, inserting, and updating records in a database. You can even use other databases such as SQL Server. See ADO.NET section for how to connect to a SQL Server database. It would be great if you modify this application and provide more help to developers. Your help would be appreciated..
http://www.c-sharpcorner.com/UploadFile/mahesh/webapplicationtutorial1111262005061214AM/webapplicationtutorial11.aspx
CC-MAIN-2015-40
refinedweb
1,190
67.65
Given the task is to show the working of cos() function for complex numbers in C++. The cos() function is a part of the C++ standard template library. It is a little different from the standard cos() function. Instead of calculating the cosine of simple integral or rational numbers, it calculates the complex cosine values of complex numbers. The mathematical formula for calculating complex cosine is − cos(z) = (e^(iz) + e^(-iz))/2 where “z” represents the complex number and “i” represents iota. The complex number should be declared as follows − complex<double> name(a,b) Here, <double> that is attached to the “complex” data type describes an object that stores ordered pair of objects, both of type “double’. Here the two objects represent the real part and the imaginary part of the complex number that we want to enter. <complex> header file should be included to call the function for complex numbers. The syntax is as follows − cos(complexnumber) Input: complexnumber(3,4) Output: -27.0349,-3.85115 Explanation − The following example shows how we can use the cos() function for calculating the cosine values of a complex number. Here 3 is the real part and 4 is the imaginary part of the complex number as shown in the input, and then we get the cosine values in the output as we pass the complex number into the cos() function. Approach used in the below program as follows − #include<iostream> #include<complex> using namespace std; int main() { complex<double> complexnumber(2,3); cout<<cos(complexnumber); return 0; } If we run the above code it will generate the following output − <-1.56563,-3.29789> Here 2 is the real part and 3 is the imaginary part of the complex number, as we pass our complex number into the cos() function, we get the cosine values in the output as shown.
https://www.tutorialspoint.com/cos-function-for-complex-number-in-cplusplus
CC-MAIN-2021-10
refinedweb
310
57.5
Welcome to this book on Meteor. Meteor is an exciting new JavaScript framework, and we will soon see how easy it is to achieve real and impressive results with less code. In this chapter, we will learn what the requirements are and what additional tools we need to get started. We will see how simple it is to get our first Meteor application running and what a good basic folder structure for a Meteor app could be. We will also learn about Meteor's automatic build process and its specific way of loading files. We will also see how to add packages using Meteors official packaging system. At the end of the chapter, we will take a short look at Meteor's command-line tool and some of its functions. To bring it together, we will cover the following topics: The full-stack framework of Meteor Meteor's requirements Installing Meteor Adding basic packages Meteor's folder conventions and loading order Meteor's command-line tool Meteor is not just a JavaScript library such as jQuery or AngularJS. It's a full-stack solution that contain frontend libraries, a Node.js-based server, and a command-line tool. All this together lets us write large-scale web applications in JavaScript, on both the server and client, using a consistent API. Even with Meteor being quite young, already a few companies such as,, and use Meteor in their production environment. If you want to see for yourself what's made with Meteor, take a look at. Meteor makes it easy for us to build web applications quickly and takes care of the boring processes such as file linking, minifying, and concatenating of files. Here are a few highlights of what is possible with Meteor: We can build complex web applications amazingly fast using templates that automatically update themselves when data changes We can push new code to all clients on the fly while they are using our app Meteor core packages come with a complete account solution, allowing a seamless integration of Facebook, Twitter, and more Data will automatically be synced across clients, keeping every client in the same state in almost real time Latency compensation will make our interface appear super fast while the server response happens in the background. With Meteor, we never have to link files with the <script> tags in HTML. Meteor's command-line tool automatically collects JavaScript or CSS files in our application's folder and links them in the index.html file, which is served to clients on initial page load. This makes structuring our code in separate files as easy as creating them. Meteor's command-line tool also watches all files inside our application's folder for changes and rebuilds them on the fly when they change. Additionally, it starts a Meteor server that serves the app's files to the clients. When a file changes, Meteor reloads the site of every client while preserving its state. This is called a hot code reload. In production, the build process also concatenates and minifies our CSS and JavaScript files. By simply adding the less and coffee core packages, we can even write all styles in LESS and code in CoffeeScript with no extra effort. The command-line tool is also the tool for deploying and bundling our app so that we can run it on a remote server. Sounds awesome? Let's take a look at what's needed to use Meteor. Meteor is not just a JavaScript framework and server. As we saw earlier, it is also a command-line tool that has a whole build process for us in place. Currently, the operating systems that are officially supported are as follows: Mac OS X 10.6 and above Linux x86 and x86_64 systems Windows Note The Windows installer is still in development at the time of writing this book. Please follow the wiki page at. This book and all examples use Meteor 1.0. We will also need Google Chrome or Firefox with the Firebug add-on installed to follow examples that require a console. The examples, screenshots, and explanations in this book will use Google Chrome's developer tools. I highly recommend using GitHub when working with web projects, such as the one we will work on in this book. Git and GitHub help us to back up our progress and let us always go back to previous states while seeing what we've changed. Git is a version control system, which was created in 2005 by the inventor of Linux, Linus Torvalds. With Git, we can commit any state of our code and later go back to that exact state. It also allows multiple developers to work on the same code base and merge their results together in an automated process. If conflicts appear in this process, the merging developer is able to resolve those merge conflicts by removing the unwanted lines of code. I also recommend registering an account at, as this is the easiest way to browse our code history. They have an easy to use interface as well as a great Windows and Mac app. To follow the code examples in this book, you can download all code examples for each chapter from the book's web page at. Additionally, you will be able to clone the book's code from. Every tag in this repository equals to one chapter of the book and the commit history will help you to see the changes, which were made in each chapter. Installing Meteor is as easy as running the following command in the terminal: $ curl | sh That's it! This will install the Meteor command-line tool ( $ meteor), the Meteor server, MongoDB database, and the Meteor core packages (libraries). Note All command-line examples are run and tested on Mac OS X and can differ on Linux or Windows systems. To install Git, I recommend installing the GitHub app from or. We can then simply go inside the app to Preferences and click on the Install Command Line Tools button inside the Advanced tab. If we want to install Git manually and set it up via the command line, we can download the Git installer from and follow this great guide at. Now, we can check whether everything was installed successfully by opening the terminal and running the following command: $ git Tip Downloading the example code You can download the example code files for all Packt books you have purchased from your account at. If you purchased this book elsewhere, you can visit and register to have the files e-mailed directly to you. This should return us a list of Git options. If we get command not found: git, we need to check whether the git binary was correctly added to our PATH environment variable. If everything is fine, we are ready to create our first Meteor app. To create our first app, we open the terminal, go to the folder where we want to create our new project, and enter the following commands: $ cd my/developer/folder $ meteor create my-meteor-blog Meteor will now create a folder named my-meteor-blog. The HTML, CSS, and JavaScript files that Meteor created for us inside this folder are already a fully working Meteor app. To see it in action, run the following commands: $ cd my-meteor-blog $ meteor Meteor will now start a local server for us on port 3000. Now, we can open our web browser and navigate to. We will see the app running. This app doesn't do much, except showing a simple reactive example. If you click on the Click Me button, it will increase the counter: For later examples, we will need Google Chrome's developer tools. To open the console, we can press Alt + command + I on Mac OS X or click on the menu button on the upper-right corner of Chrome, select More tools, and then Developer tools. The Developer tools allow us to inspect the DOM and CSS of our website, as well as having a console where we can interact with our website's JavaScript. For this book, we will build our own app from scratch. This also means we have to set up a sustainable folder structure, which helps us to keep our code organized. With Meteor, we are very flexible concerning our folder structure. This means we can put our files wherever we want, as long as they are inside the app's folder. Meteor treats specific folders differently, allowing us to expose files only on the client, the server, or both. We will take a look at those specific folders later. But, first let's get our hands dirty by deleting all preadd files in our newly created application folder and creating the following folder structure: - my-meteor-blog - server - client - styles - templates To fully focus on the Meteor code but still have a pretty-looking blog, I strongly recommend to download the code that accompanies this chapter from the book's web page at. They will contain already two drop-in-place style files ( lesshat.import.less and styles.less), which will let your example blog look pretty in the upcoming chapters. You can also download these files directly from GitHub at and copy them to the my-meteor-blog/client/styles folder manually. Next, we need to add some basic packages so that we can start building our app. Packages in Meteor are libraries that can be added to our projects. The nice thing about Meteor packages is that they are self-contained units, which run out of the box. They mostly add either some templating functionality or provide extra objects in the global namespace of our project. Packages can also add features to Meteor's build process such as the stylus package, which lets us write our app's style files with the stylus preprocessor syntax. For our blog, we will need two packages at first: less: This is a Meteor core package and will compile our style files on the fly to CSS jeeeyul:moment-with-langs: This is a third-party library for date parsing and formatting To add the less package, we can simply open the terminal, go to our projects folder, and enter the following command: $ meteor add less Now, we are able to use any *.less files in our project, and Meteor will automatically compile them in its build process for us. To add a third-party package, we can simply search for packages on either, which is the frontend for Meteors packaging system, or use the command-line tool, $ meteor search <package name>. For our blog, we will need the jeeeyul:moment-with-langs package that allows us later to simply manipulate and format dates. Packages are namespaced with the authors name followed by a colon. To add the moment package, we simply enter the following command: $ meteor add jeeeyul:moment-with-langs After the process is done, and we restarted our app using $ meteor, we will have the moment object available in our app global namespace and we can make use of it in the upcoming chapters. Should we ever want to add only specific version of a package, we can use the following command: $ meteor add jeeeyul:[email protected]=2.8.2 If you want a version in the 1.0.0 (but not the 2.0.0) range use the following command: $ meteor add jeeeyul:[email protected] To update only packages we can simply run the following command: $ meteor update –-packages-only Additionally, we can update only a specific package using the following command: $ meteor update jeeeyul:moment-with-langs That's it! Now we are fully ready to start creating our first templates. You can jump right into the next chapter, but make sure you come back to read on, as we will now talk about Meteor's build process in more detail. To understand Meteor's build process and its folder conventions, we need to take a quick look at variable scopes. Meteor wraps every code files in an anonymous function before serving it. Therefore, declaring a variable with the var keyword will make it only available in that file's scope, which means these variables can't be accessed in any other file of your app. However, when we declare a variable without this keyword, we make it a globally available variable, which means it can be accessed from any file in our app. To understand this, we can take a look at the following example: // The following files content var myLocalVariable = 'test'; myGlobalVariable = 'test'; After Meteor's build process, the preceding lines of code will be as follows: (function(){ var myLocalVariable = 'test'; myGlobalVariable = 'test'; })(); This way, the variable created with var is a local variable of the anonymous function, while the other one can be accessed globally, as it could be created somewhere else before. Though Meteor doesn't impose restrictions concerning our folder names or structure, there are naming conventions that help Meteor's build process to determine the order in which the files need to be loaded. The following table describes the folder and their specific loading order: The following table describes filenames that have created a specific loading order: So, we see that Meteor gathers all files except the ones inside public, private, and tests. Additionally, files are always loaded in the alphabetical order, and files in subfolders are loaded before the ones in parent folders. If we have files outside the client or server folder and want to determine where the code should be executed, we can use the following variables: if(Meteor.isClient) { // Some code executed on the client } if(Meteor.isServer) { // Some code executed on the server. } We also see that code inside a main.* file is loaded last. To make sure a specific code only loads when all files are loaded and the DOM on the client is ready, we can use the Meteor's startup() function: Meteor.startup(function(){ /* This code runs on the client when the DOM is ready, and on the server when the server process is finished starting. */ }); To load files from inside the private folder on the server, we can use the Assets API as follows: Assets.getText(assetPath, [asyncCallback]); // or Assets.getBinary(assetPath, [asyncCallback]) Here, assetPath is a file path relative to the private folder, for example, ' subfolder/data.txt'. If we provide a callback function as the second parameter, the Assets() method will run asynchronously. So, we have two ways of retrieving the content of an assets file: // Synchronously var myData = Assets.getText('data.txt'); // Or asynchronously Assets.getText('data.txt', function(error, result){ // Do somthing with the result. // If the error parameter is not NULL, something went wrong }); Note If the first example returns an error, our current server code will fail. In the second example, our code will still work, as the error is contained in the error parameter. Now that we understand Meteor's basic folder structure, let's take a brief look at the Meteor's command-line tool. Now that we know already about Meteor's build process and folder structure, we will take a closer look at what we can do with the command-line tool that Meteor provides. As we saw when using the meteor command, we need to be inside a Meteor project so that all actions will be performed on this project. For example, when we run meteor add xxx, we add a package to the project where we are currently in. If Meteor releases a new version, we can simply update our project by running the following command: $ meteor update If we want to go back to a previous version, we can do this by running the following command: $ meteor update –-release 0.9.1 This would set our project back to release version 0.9.1. Deploying our Meteor app to a public server is as easy as running the following command: $ meteor deploy my-app-name This would ask us to register a Meteor developer account and deploy our app at. For a full introduction on how to deploy a Meteor app, refer to Chapter 10, Deploying Our App. In the Appendix, you can find a full list of Meteor commands and their explanations. In this chapter, we learned what Meteor requires to run, how to create a Meteor application, and how the build process works. We understand that Meteor's folder structure is rather flexible, but that there are special folders such as the client, server, and lib folder, which are loaded in different places and order. We also saw how to add packages and how to use the Meteor command-line tool. If you want to dig deeper into what we've learned so far, take a look at the following parts of the Meteor documentation: You can find this chapter's code examples at or on GitHub at. Now that we've set up our project's basic folder structure, we are ready to start with the fun part of Meteor—templates.
https://www.packtpub.com/product/building-single-page-web-apps-with-meteor/9781783988129
CC-MAIN-2022-27
refinedweb
2,854
59.03
User Tag List Results 1 to 2 of 2 Thread: Using AJAX to retrieve data - Join Date - Nov 2004 - Location - Victoria BC - 116 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) Using AJAX to retrieve data I am looking for some general advice at this stage on the use of AJAX for searching. I have a requirement to do a search by name, address, city, postal code, etc. and the search should return a thumbnail sketch of the person's particulars (there could be up to 100 or more jones). Is Ajax the tool to do this kind of search or should I just use a standard form? If Ajax is the tool, can I capture the id of a selected person and use it in another form? With the possibility of more than 100 entries, can I page or scroll through the list? Any views on this issue would be appreciated. Rick - Join Date - Aug 2005 - 986 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) You can use Ajax, or a normal form. I think it is a good idea to provide a GET-based search too, though. If you do, someone can post an url (on his blog, for example) to your search results:. The common way to do Ajax in Rails is to generate HTML with Ruby, and then replace the contents of a div with that HTML. If you want to do this with Ajax, you could, for example have this set up: controller People: action search: displays the form which calls get_search_results action get_search_results: searches the database and returns the html. for example: Code: def get_search_results @results = Person.search(params[:query]) endCode: # get_search_results.rhtml <ul> <% for person in @results %> <li><%= person.name %></li> </ul> If you want the user to be able to click on one of the results, and then load the data of this result into a form, you would use a link_to_remote in the <li><%= person.name %></li>. This link calls an action update_form/12, where 12 is the id of the user. This action uses an rjs template like this (assuming you have a partial for the form): Code: page.replace_html 'user_form', :partial => 'form', :object => @user I hope this is clear, but if you've never used Ajax on Rails, it will probably not be. Bookmarks
http://www.sitepoint.com/forums/showthread.php?356735-Using-AJAX-to-retrieve-data&p=2567204
CC-MAIN-2014-23
refinedweb
385
77.06
Search Type: Posts; User: beerumrakesh Search: Search took 0.03 seconds. - 23 Nov 2011 11:20 AM - Replies - 2 - Views - 2,151 Hi, I am using ExtJS 4.0.2 and I am seeing performance issues with IE.. Now when I load my home page it renders / loads after few seconds; now during this time I would like to show LoadMask to... - 9 Nov 2011 9:55 AM - Replies - 2 - Views - 6,614 Hi mitchellsimoens, Thanks a lot. I really appreciate your help It worked like a charm. Regards - 7 Nov 2011 4:58 AM - Replies - 2 - Views - 6,614 Hi There, I want to have loadMask while my tree panel is rendering. I have not assigned the store to tree panel; I am creating the node on tree render event in my controller. It seems, As I... - 20 Oct 2011 11:35 PM - Replies - 1 - Views - 861 Hi There, In a scenario, I am passing my form values on 'Search' button click to store, and on the basis of those values my grids are getting populated. myGrid.getStore().load({ params:... - 19 Oct 2011 8:48 AM - Replies - 2 - Views - 4,684 Hi There, After looking the docs and some more references, I have modified my code, now the json response is like below {"data": {"text":".", "leaf":false, "children":[{ ... - 18 Oct 2011 6:10 AM - Replies - 2 - Views - 4,684 Hi There, I am trying to make the tree using TreeStore, Tree Store Ext.define('Custom.TreeStore', { extend: 'Ext.data.TreeStore', model: 'custommodel.TreeModel', proxy: { - 19 Sep 2011 4:43 AM - Replies - 0 - Views - 662 Hi There, I want to show popup window on cell click. In ExtJS 3, I used to write the same as mentioned below {text: 'Name', dataIndex: 'name', flex: 1, id:'name',renderer:... - 1 Sep 2011 10:40 PM That really helped. Thanks a lot. Regards. - 1 Sep 2011 5:47 AM Hi Guys, I am trying to use the portal example in my application. When I use the way it is given in example it works fine. But when I use this with app.js; it gives me "namespace is not... - 1 Sep 2011 5:40 AM Hi Guys, <br><br>I am trying to use the portal example in my application. When I use the way it is given in example it works fine. <br><br>But when I use this with app.js; it gives me... - 22 Jun 2011 4:12 AM Thanks a lot, Steffen. It really helped. Regards. - 12 Jun 2011 11:19 PM - Replies - 0 - Views - 1,599 Hi There, Can we use ExtJS 3.2.1 Stores in ExtJS 4 charts? If yes, then Can you please give me example for the same.? I tried to use ExtJS 3.2.1 Store (created using dwr) in ExtJS 4 charts; but... - 7 Jun 2011 9:31 PM I don't see something like legendRenderer in APIs, though I saw some post where I found suggestions for using legendRenderer. I tried this option too but no luck. I will really appreciate if... - 6 Jun 2011 11:36 PM Hi Guys, I have made one grouped bar chart. It's working fine. But it shows the default text in legend. This text is my yField in Series. series: [{ yField: ['data1','data2'] }] so,... - 26 May 2011 12:51 AM - Replies - 12 - Views - 8,282 I have tried to make the charts according to the example given by kavih7, but I didn't get success yet. 1. I don't have "ext-core-sandbox-debug.js" file; can you please tell me where can I find... - 25 May 2011 5:07 AM - Replies - 12 - Views - 8,282 Hi Guys, I am new to ExtJS. I need to use ExtJS 4 charts in ExtJS 3.2.1; I saw in one thread that I can't do so; but when I see this thread it seems it's doable. I tried to look at the... Results 1 to 16 of 16
https://www.sencha.com/forum/search.php?s=77bd80eae4dc46a4eb8d8389a480c5a5&searchid=11960813
CC-MAIN-2015-27
refinedweb
666
84.37
What is Recursion? Recursion is simply defined as a function calling itself. It uses its previously solved sub-problems to compute a bigger problem. It is one of the most important and tricky concepts in programming but we can understand it easily if we try to relate recursion with some real examples: Example Think of a situation when you put a mirror in front of a mirror? This happens because a mirror is reflecting a mirror, which is reflecting a mirror,…and so on. This is exactly what recursion does. Now let’s try to visualize how recursion works: If we define a function to draw a triangle on its every edge. Can you imagine the resultant figure? In both the above examples we saw the never-ending sub-problems (the mirrors will keep reflecting one another and there appears to be an infinite number of mirrors and in the second example, the figure will keep growing infinitely). By this, we understand the need of having an end condition for every recursive function which will avoid this infinite structure. This condition is known as Base Case. Steps to forming recursion - Base Case - Recursive call for the smaller problem - Computation of bigger problem using solved sub-problems Let’s try to understand it with an example: Ques: Calculate the sum of n consecutive natural number starting with 1. int sum(int n){ // Base Case if(n==1){ return n; } else{ int smallerSum=sum(n-1); //recursive call for smaller problem return n+smallerSum; // solve bigger problem using solved smaller sub-problems } } Recursion and Stack When a function is called, it occupies memory in the stack to store details about the execution of the function. And when the function ends, the memory occupied by it is also released. Now in recursion, as we know a function is called in itself. Hence at every function call, a block of memory is created in the stack to hold the information of the currently executing function. When the function ends, it returns to it’s calling statement written in the outer function i.e., an outer function is resumed from where it stopped. Let’s see the memory structure in the above example for n=3: Keeping the association of recursion and stack in mind, we can easily understand that in absence of Base Case, our program will suffer with Stack overflow and time limit exceeded. Difference Between Direct and Indirect Recursion Direct Recursion - When the same function calls itself then it is known as Direct Recursion. - In Direct Recursion, both calling and called function is the same. - There will be a one-step recursive call. The code structure of Direct Recursive function: return_type func_name(arguments) { // some code... func_name(parameters); // some code... } Indirect Recursion - When a function calls another function which is also calling its parent function directly or indirectly then it is known as Indirect Recursion. - In Indirect Recursion, calling and called functions are different. - There will be a multi-step recursive call. The code structure of the Indirect Recursive function: return_type func_name1(arguments) { // some code... func_name2(parameters); // some code... } return_type func_name2(arguments) { // some code... func_name1(parameters); // some code... } Types of Recursion - Tailed Recursion - When the last executed statement of a function is the recursive call. - It is possible to keep only the last recursive call on the stack. - Example: int sum(int n,int &ans){ if(n==0){ return ans; } else{ ans=ans+n; return sum(n-1,ans); // last statement to be executed is recursive call } } - Non-tailed Recursion - When there are statements left in the function to execute after recursive call statement. - Recursive call will remain in the stack until the end of its evaluation. - Example: int sum(int n){ if(n==1){ return n; } else{ int smallerSum=sum(n-1); //recursive call for smaller problem return n+smallerSum; //statements to be executed after recursive call } } When to use recursion over iteration Both approaches have their own pros and cons, hence it becomes necessary to understand which one should be used to solve a particular problem. Recursive is a more intuitive approach for solving problems of Divide and conquer like merge sort as we can keep breaking the problem into its sub-problems recursively which is sometimes difficult to do using an iterative approach, for example, Tree traversal(Inorder, Preorder, Postorder). But it is also true that the iterative approach is faster than recursion as there is no overhead of multiple function calls. Note:To solve a problem we can use iteration or recursion or even both. Recursion can be replaced by iteration with an explicit call stack, while iteration can be replaced with tail_recursion. We as a programmer should create a balance between easy and clean writing of code with memory and time optimization. Let’s try to solve another question: Calculate factorial of n. C++ implementation #include <iostream> using namespace std; int fact(int n){ // Base Case if (n <= 1) return 1; else return n*fact(n-1); } int main(){ int n=5; cout<<fact(n); return 0; } Output: 15 Java implementation class Main{ static int fact(int n){ if (n<=1) return 1; else return(n * fact(n-1)); } public static void main(String args[]){ int n=5; System.out.println(fact(n)); } } Output: 15 Thanks for reading!! Stay tuned and check out the other blogs too. Comment down for any corrections/suggestions.
https://www.tutorialcup.com/interview/stack/recursion.htm
CC-MAIN-2021-49
refinedweb
895
53.21
This module provides functions to parse an XML document to a tree structure, either strictly or lazily. The GenericXMLString type class allows you to use any string type. Three string types are provided for here: String, ByteString and Text. Here is a complete) A pure tree representation that uses a list as its container type.). The tree representation of the XML document.. Lazily parse XML to tree. In the event of an error, throw XMLParseException. DEPRECATED: Use [Node tag text] instead. Type alias for nodes. DEPRECATED: Use [UNode text] instead. Type alias for nodes with unqualified tag names where tag and text are the same string type. DEPRECATED. DEPRECATED: Use [QNode text] instead. Type alias for nodes where qualified names are used for tags DEPRECATED: Use [NNode text] instead. Type alias for nodes where namespaced names are used for tags..
http://hackage.haskell.org/package/hexpat-0.16/docs/Text-XML-Expat-Tree.html
CC-MAIN-2015-18
refinedweb
140
78.25
March 2013 Volume 28 Number 03 Modern Apps - Data Access and Storage Options in Windows Store Apps By Rachel Appel | March 2013 Managing data is a critical part of app development. Whether it’s a game, news, travel or fashion app, it’s always all about the data. Modern apps often need to manage data scattered throughout multiple, disparate locations and in countless formats. I’ll discuss the various data storage options and data access APIs available for building Windows Store apps, in all languages, as well as data management strategies for both content and configuration. Data Management and Storage Considerations As an app developer, you need to determine your app’s data requirements prior to starting your project, because changing the underlying architecture causes a lot of rework. You might have an existing data source, in which case the decision is made for you, but with a greenfield project, you must think about where to store the data. Your two options are on the device or at a remote location: - Local: Usually this data is in a file or local database, but in Windows 8, you can now treat other apps as sources for data by using the built-in File Picker or contracts. In JavaScript apps, Web Storage and the Indexed Database (IndexedDB) API are also available as local data sources. - Remote: This data could be in the cloud using Azure SkyDrive or any remote HTTP endpoint that can serve JSON or XML data, including public APIs such as Facebook or Flickr. The size of the data often determines whether the data is local or remote; however, most modern apps will use data from both sources. This is because smaller, more mobile devices such as slates, tablets and phones are the norm, and they don’t usually have much storage space. Despite that, they still need data to function correctly when offline. For example, the Surface, as with many portable devices, comes in 32GB and 64GB models. Simple text-based data such as JSON isn’t usually large, but relational databases and media data (such as images, audio and video) can fill up a device quickly. Let’s take a look at the various local and remote options for storing app content data. Web Storage It might sound like Web Storage (bit.ly/lml0Ul) is simply storage on the Web, but it isn’t. Instead, Web Storage, an HTML5 standard, is a great way to keep app data on the client, locally. Both Windows Store apps as well as plain old HTML pages support Web Storage. There’s no database setup required and no files to copy, as Web Storage is an in-memory database. Web Storage is accessible via JavaScript through one of the two following properties of the window object: - localStorage: Local data that’s persistent after the app terminates and is available to future app instances. - sessionStorage: Also local data; however, sessionStorage is destroyed when a Windows Store app terminates execution. You can store data from simple types to complex objects in Web Storage by attaching dynamic properties to either the sessionStorage or localStorage variables. The dynamic properties are a key/value pair with syntax similar to this: sessionStorage.lastPage = 5; WinJS.xhr({ url: "data/data.json" }).then(function (xhr) { localStorage.data = xhr.responseText; }; The lastPage property exists until the app terminates because it’s part of sessionStorage, while the data property of localStorage persists past the lifetime of the app. Being able to persist data locally between app sessions makes Web Storage an excellent choice for supporting offline scenarios. Small data is also more suited for offline support. Because JSON data is compact, it’s easy to stuff entire JSON datasets into the 5MB of space provided by Web Storage and have plenty of space left over for some media data. Because Web Storage is an HTML5 standard, it’s only available in Windows Store projects built with JavaScript. IndexedDB Another standard in the HTML5 family is IndexedDB (bit.ly/TT3btM), which is a local data store for large, searchable and persistent data sets. As a component of HTML5, you can use IndexedDB in client Web apps for browsers as well as Windows Store apps. IndexedDB stores items in an object database and is extremely flexible because you can store any kind of data from text to Binary Large Objects (BLOBs). For example, multimedia files tend to be quite large, so storing audio and video in IndexedDB is a good choice. Because IndexedDB is an object database, it doesn’t use SQL statements, so you must access data through an object-oriented-style syntax. Interaction with an IndexedDB data store is through transactions and cursors, as shown here: var dataStore = "Datastore"; var trn = db.transaction(dataStore, IDBTransaction.READ_ONLY); var store = trn.objectStore(dataStore); trans.oncomplete = function(evt) { // transaction complete }; var request = store.openCursor(); request.onsuccess = function(evt) { var cursor = evt.openCursor(); }; request.onerror = function(error) { // error handling }; Because IndexedDB specializes in really big data, using it for small item storage causes it to behave inefficiently, making Web Storage a much better choice for bite- (or byte-) sized local data. IndexedDB is also well-matched for content data, but ill-suited for app configuration data. SQLite SQLite (bit.ly/65FUBZ) is a self-contained, transactional, relational and file-based database, which requires no configuration and doesn’t need a database administrator to maintain it. You can use SQLite with any Windows Runtime (WinRT) language, and it’s available as a Visual Studio extension. While SQLite works well in JavaScript apps, you need to obtain the SQLite3 WinRT wrapper (bit.ly/J4zzPN) from GitHub before using it. Developers with backgrounds in ASP.NET or Windows Forms gravitate to relational databases, but a relational database management system (RDBMS) isn’t always the best choice when writing modern apps, due to space issues on mobile devices as well as the varied types and formats of data, especially multimedia. Because SQLite is a relational database, it makes sense for those apps that need relational and transactional behaviors. This means SQLite is great for line-of-business (LOB) apps or data-entry apps, and can also be a repository for local, offline data originally obtained from an online source. If the SQLite database becomes too large for portable devices, you can move it to a server or cloud location. The code won’t change much, because the SQLite3 library uses a traditional connection and Create/Read/Update/Delete (CRUD) objects similar to the following code: // C# code that opens an async connection. var path = Windows.Storage.ApplicationData.Current.LocalFolder.Path + @"\data.db"; var db = new SQLiteAsyncConnection(path); // JavaScript code that opens an async connection. var dbPath = Windows.Storage.ApplicationData.current.localFolder.path + '\\data.db; SQLite3JS.openAsync(dbPath).then(function (db) { // Code to process data. }); As you can see, using SQLite is just like using other SQL databases. Limits on SQLite databases go as high as 140TB. Keep in mind that very large data often warrants professional database administration for the best possible data integrity, performance and security. Most DBAs and developers who work with relational databases prefer a GUI tool to create and manage database objects or run ad hoc queries on the data, and the Sqliteman (bit.ly/9LrB1o) admin utility is ideal for all basic SQLite operations. If you’re porting existing Windows desktop apps written in Windows Forms, Windows Presentation Foundation (WPF) or Silverlight, you might already be using SQL Server Compact (SQL CE). If this is the case, you can migrate SQL CE databases to SQLite with the ExportSqlCE (bit.ly/dwVaR3) utility and then use Sqliteman to administer them. Files as Data and the File API Why bother with a database at all, especially if users of your app want to stick with the files they already have? This is especially true of photos and documents. The File API goes beyond simply providing a navigator to directories and files; it gives the user the ability to choose an app as a file location. This means apps can talk to each other and exchange data. A File Open Picker can interact with Bing, camera, or photo apps as well as regular directories and named locations such as My Documents, Videos, or Music. Sharing data so easily between apps, services and personal files is a first-rate feature of Windows. Many OSes have a mechanism for registering types of files that apps intend to use alongside the ability to launch those apps when a user interacts with an icon in the OS. In Windows, this is called a file association. Windows 8 takes this concept further by allowing apps to talk to each other through a system-wide feature called contracts. One way to implement a contract is through a File Picker. Notice that the following code is similar to the File Dialog APIs from desktop apps or earlier Windows versions (note: some code has been left out of this example for brevity; for a more thorough examination of the FileOpenPicker class, see bit.ly/UztmDv): fileOpen: function () {Picker.pickSingleFileAsync().done(function (file) { // ... }); } Choosing an app from a Windows 8 picker launches that app. For example, if the user selects Bing, the picker will launch the Bing app and then return the user’s image selection to your app. Now that you’ve seen the local options, let’s look at the options for remote data. Web Services and the ASP.NET Web API Most developers are familiar with consuming and modifying data with XML Web services because they date back to the days of the Microsoft .NET Framework 1.x. The main advantage in using Web services is that the data lives at a central remote location and the apps from multiple devices can access the data any time while connected. Access to the underlying database is piped through a set of HTTP endpoints that exchanges JSON or XML data. Many public APIs such as Twitter or Flickr expose JSON or XML data that you can consume in Windows Store apps. Web services come in a variety of flavors: - ASMX services: Use traditional ASP.NET to deliver data across HTTP. - Windows Communication Foundation (WCF) and Rich Internet Application (RIA) services: A message-based way to send data between HTTP endpoints. - OData: Open Data protocol, another API for transporting data over HTTP. - ASP.NET Web API: A new ASP.NET MVC 4 framework that makes it easy to build RESTful HTTP services that deliver JSON or XML data to apps or Web sites. If you’re building back-end services from the ground up, the ASP.NET Web API streamlines the development process because it makes it easy to build services in a consistent RESTful fashion, so they can be readily consumed by apps. Regardless of the back-end service, if it’s over HTTP, you can use the HttpWebRequest and HttpWebResponse objects to communicate with a Web service via C#. In JavaScript apps, a WinJS XMLHttpRequest wrapper is fitted for asynchronous operations, which looks like the following code: WinJS.xhr({ url: "data.json" }).then(function (xhr) { var items = JSON.parse(xhr.responseText); items.forEach(function (item) { list.push(item); }) }); Storage space isn’t usually an issue with Web services because a Web service is just the software that transports the data between endpoints. This means its underlying database can live anywhere, such as on a remote server, Web host or Azure instance. You can host any of the previously noted Web services such as an ASP.NET Web API instance or a WCF service on Azure, along with the data itself. SkyDrive Don’t forget that SkyDrive (bit.ly/HYB7iw) is not only an option for data storage, but an excellent option. Think of SkyDrive as a non-storage storage option. Users can choose SkyDrive as a location in the cloud and access documents through File Open or Save pickers. Allowing users to save files to SkyDrive means zero worries about database management, and with 7GB of space per user, there’s plenty of room. SkyDrive users can also purchase more storage space. The Live API (bit.ly/mPNb03) contains a fully featured set of RESTful SkyDrive APIs for reading and writing to SkyDrive. A call to SkyDrive to retrieve the list of shared items looks like this: GET A Microsoft.Live namespace allows C# developers to access the Live and SkyDrive APIs, while JavaScript developers can make RESTful calls with HTTP verbs POST or PUT. SkyDrive isn’t recommended for app configuration data. Azure Mobile Services Azure Mobile Services is a great option for those building cross- and multi-platform apps. Powered by Azure, this option offers more than just scalable storage; it offers push notifications, business logic management, an authentication API and a complete SDK. In addition to these features, an easy-to-use, Web-based administrative tool is provided. The Mobile Services SDK integrates with Windows Store, Windows Phone 8, iOS and Android apps. All of the major platforms are supported, and with the Mobile Services SDK, you can build out a working prototype in just minutes and be on your way to delivering data to multi-platform apps in no time. Among the many items in the SDK, you can use the query object to query data from tables, similar to this: var query = table.orderBy('column').read({ success: function(results) { ... }}); As you can see, the code is quite the same as any other API, so the learning curve is the same as the other options discussed here. You can access the SDK and Mobile Services using any Windows Store app language. Application Data Management and Storage Options All of the previously noted data storage and access options are for storing content, but as a developer, you also need to deal with configuration data for the app. This is the metadata that describes your app or the capabilities of its device, not the user’s data. Modern apps make use of both persistent application data (such as user preferences) as well as temporary metadata (such as the user’s last scroll position or trending search terms). These small yet effective conveniences ensure the best-possible experience for the user, so it’s important to build them into your app. While some of this data belongs on the device, consider the fact that many apps work across multiple platforms and devices, so centralizing and synchronizing application data in Azure with the content data often makes sense. A specific set of APIs for managing application data exists in an aptly named ApplicationData class in the Windows.Storage namespace, and the code looks similar to this: var localSettings = Windows.Storage.ApplicationData.current.localSettings; var roamingSettings = Windows.Storage.ApplicationData.current.roamingSettings; You can store simple or complex objects in either the localSettings or roamingSettings properties. Using either local or roaming settings is the preferred way to work with configuration data. Technologies such as IndexedDB, files or SkyDrive ordinarily aren’t good options for app configuration data, and SQLite makes sense here only if the app is already using it to store content. You must also consider what to do when the app is offline or disconnected from the Internet. In other words, some of your data needs to be cached, but without consuming too much disk space. Content and Configuration In summary, to implement a proper data architecture, you shouldn’t depend on the limited space on portable devices, so hosting data in the cloud is usually a good bet. But, if you have a legacy database, reusing it might be a requirement. Windows Store apps support a variety of structured and BLOB storage needs for both content and configuration. If you’re building a Window Store app and would like assistance with choosing a data access strategy, I highly recommend that you check out the Generation App (bit.ly/W8GenAppDev) program. Generation App guides you through the process of building a Windows Store (or Windows Phone) app in 30 days by offering free technical and design consultations and assistance, along with exclusive tips and resources. experts for reviewing this article: Scott Klein and Miriam Wallace Miriam Wallace has been writing developer documentation for Windows for five years. Scott Klein is an Azure technical evangelist for Microsoft. His career has focused on SQL Server for the past 20-plus years and thus focuses on Microsoft’s PaaS services for Azure. He lives in Redmond, blogs at scottlklein.com, and you can follow him on Twitter at twitter.com/sqlscott.
https://docs.microsoft.com/en-us/archive/msdn-magazine/2013/march/modern-apps-data-access-and-storage-options-in-windows-store-apps
CC-MAIN-2020-10
refinedweb
2,753
53.71
Django debug settings Django has a number of settings that control the collection and presentation of debug information. The primary one is named DEBUG; it broadly controls whether the server operates in development (if DEBUG is True) or production mode. In development mode, the end-user is expected to be a site developer. Thus, if an error arises during processing of a request, it is useful to include specific technical information about the error in the response sent to the web browser. This is not useful in production mode, when the user is expected to be simply a general site user. This section describes three Django settings that are useful for debugging during development. Additional settings are used during production to control what errors should be reported, and where error reports should be sent. These additional settings will be discussed in the section on handling problems in production. The DEBUG and TEMPLATE_DEBUG settings DEBUG is the main debug setting. One of the most obvious effects of setting this to True is that Django will generate fancy error page responses in the case of serious code problems, such as exceptions raised during processing of a request. If TEMPLATE_DEBUG is also True, and the exception raised is related to a template error, then the fancy error page will also include information about where in the template the error occurred. The default value for both of these settings is False, but the settings.py file created by manage.py startproject turns both of them on by including these lines at the top of the file: DEBUG = True TEMPLATE_DEBUG = DEBUG Note that setting TEMPLATE_DEBUG to True when DEBUG is False isn't useful. The additional information collected with TEMPLATE_DEBUG turned on will never be displayed if the fancy error pages, controlled by the DEBUG setting, are not displayed. Similarly, setting TEMPLATE_DEBUG to False when DEBUG is True isn't very useful. In this case, for template errors, the fancy debug page will be lacking helpful information. Thus, it makes sense to keep these settings tied to each other, as previously shown. Details on the fancy error pages and when they are generated will be covered in the next section. Besides generating these special pages, turning DEBUG on has several other effects. Specifically, when DEBUG is on: - A record is kept of all queries sent to the database. Details of what is recorded and how to access it will be covered in a subsequent section. - For the MySQL database backend, warnings issued by the database will be turned into Python Exceptions. These MySQL warnings may indicate a serious problem, but a warning (which only results in a message printed to stderr) may pass unnoticed. Since most development is done with DEBUG turned on, raising exceptions for MySQL warnings then ensures that the developer is aware of the possible issue. - The admin application performs extensive validation of the configuration of all registered models and raises an ImproperlyConfigured exception on the first attempt to access any admin page if an error is found in the configuration. This extensive validation is fairly expensive and not something you'd generally want done during production server start-up, when the admin configuration likely has not changed since the last start-up. When running with DEBUG on, though, it is possible that the admin configuration has changed, and thus it is useful and worth the cost to do the explicit validation and provide a specific error message about what is wrong if a problem is detected. - Finally, there are several places in Django code where an error will occur while DEBUG is on, and the generated response will contain specific information about the cause of the error, whereas when DEBUG is off the generated response will be a generic error page. The TEMPLATE_STRING_IF_INVALID setting A third setting that can be useful for debugging during development is TEMPLATE_STRING_IF_INVALID. The default value for this setting is the empty string. This setting is used to control what gets inserted into a template in place of a reference to an invalid (for example, non-existent in the template context) variable. The default value of an empty string results in nothing visible taking the place of such invalid references, which can make them hard to notice. Setting TEMPLATE_STRING_IF_INVALID to some value can make tracking down such invalid references easier. However, some code that ships with Django (the admin application, in particular), relies on the default behavior of invalid references being replaced with an empty string. Running code like this with a non-empty TEMPLATE_STRING_IF_INVALID setting can produce unexpected results, so this setting is only useful when you are specifically trying to track down something like a misspelled template variable in code that always ensures that variables, even empty ones, are set in the template context. Debug error pages With DEBUG on, Django generates fancy debug error pages in two circumstances: - When a django.http.Http404 exception is raised - When any other exception is raised and not handled by the regular view processing code In the latter case, the debug page contains a tremendous amount of information about the error, the request that caused it, and the environment at the time it occurred. The debug pages for Http404 exceptions are considerably simpler. To see examples of the Http404 debug pages, consider the survey_detail view def survey_detail(request, pk): survey = get_object_or_404(Survey, pk=pk) today = datetime.date.today() if survey.closes < today: return display_completed_survey(request, survey) elif survey.opens > today: raise Http404 else: return display_active_survey(request, survey) There are two cases where this view may raise an Http404 exception: when the requested survey is not found in the database, and when it is found but has not yet opened. Thus, we can see the debug 404 page by attempting to access the survey detail for a survey that does not exist, say survey number 24. The result will be as follows: Notice there is a message in the middle of the page that describes the cause of the page not found response: No Survey matches the given query. This message was generated automatically by the get_object_or_404 function. By contrast, the bare raise Http404 in the case where the survey is found but not yet open does not look like it will have any descriptive message. To confirm this, add a survey that has an opens date in the future, and try to access its detail page. The result will be something like the following: That is not a very helpful debug page, since it lacks any information about what was being searched for and why it could not be displayed. To make this page more useful, include a message when raising the Http404 exception. For example: raise Http404("%s does not open until %s; it is only %s" % (survey.title, survey.opens, today)) Then an attempt to access this page will be a little more helpful: Note that the error message supplied with the Http404 exception is only displayed on the debug 404 page; it would not appear on a standard 404 page. So you can make such messages as descriptive as you like and not worry that they will leak private or sensitive information to general users. Another thing to note is that a debug 404 page is only generated when an Http404 exception is raised. If you manually construct an HttpResponse with a 404 status code, it will be returned, not the debug 404 page. Consider this code: return HttpResponse("%s does not open until %s; it is only %s" % (survey.title, survey.opens, today), status=404) If that code were used in place of the raise Http404 variant, then the browser will simply display the passed message: Without the prominent Page not found message and distinctive error page formatting, this page isn't even obviously an error report. Note also that some browsers by default will replace the server-provided content with a supposedly "friendly" error page that tends to be even less informative. Thus, it is both easier and more useful to use the Http404 exception instead of manually building HttpResponse objects with status code 404. A final example of the debug 404 page that is very useful is the one that is generated when URL resolution fails. For example, if we add an extra space before the survey number in the URL, the debug 404 page generated will be as follows: The message on this page includes all of the information necessary to figure out why URL resolution failed. It includes the current URL, the name of the base URLConf used for resolution, and all patterns that were tried, in order, for matching. If you do any significant amount of Django application programming, it's highly likely that at some time this page will appear and you will be convinced that one of the listed patterns should match the given URL. You would be wrong. Do not waste energy trying to figure out how Django could be so broken. Rather, trust the error message, and focus your energies on figuring out why the pattern you think should match doesn't in fact match. Look carefully at each element of the pattern and compare it to the actual element in the current URL: there will be something that doesn't match. In this case, you might think the third listed pattern should match the current URL. The first element in the pattern is the capture of the primary key value, and the actual URL value does contain a number that could be a primary key. However, the capture is done using the pattern \d+. An attempt to match this against the actual URL characters—a space followed by 2—fails because \d only matches numeric digits and the space character is not a numeric digit. There will always be something like this to explain why the URL resolution failed. For now, we will leave the subject of debug pages and learn about accessing the history of database queries that is maintained when DEBUG is on. Database query history When DEBUG is True, Django maintains a history of all SQL commands sent to the database. This history is kept in a list, named queries, located in the django. db.connection module. The easiest way to see what is kept in this list is to examine it from a shell session: >>> from django.db import connection >>> connection.queries [] >>> from survey.models import Survey >>> Survey.objects.count() 2 >>> connection.queries [{'time': '0.002', 'sql': u'SELECT COUNT(*) FROM "survey_survey"'}] >>> Here we see that queries is initially empty at the beginning of the shell session. We then retrieve a count of the number of Survey objects in the database, which comes back as 2. When we again display the contents of queries, we see that there is now one query in the queries list. Each element in the list is a dictionary containing two keys: time and sql. The value of time is how long, in seconds, the query took to execute. The value of sql is the actual SQL query that was sent to the database. One thing to note about the SQL contained in connection.queries: it does not include quoting of query parameters. For example, consider the SQL shown for a query on Surveys with titles that start with Christmas: >>> Survey.objects.filter(title__startswith='Christmas') [<Survey: Christmas Wish List (opens 2009-11-26, closes 2009-12-31)>] >>> print connection.queries[-1]['sql'] SELECT "survey_survey"."id", "survey_survey"."title", "survey_survey"."opens", "survey_survey"."closes" FROM "survey_survey" WHERE "survey_survey"."title" LIKE Christmas% ESCAPE '\' LIMIT 21 >>> In the displayed SQL, Christmas% would need to be quoted in order for the SQL to be valid. However, we see here it is not quoted when stored in connection. queries. The reason is because Django does not actually pass the query in this form to the database backend. Rather, Django passes parameterized queries. That is, the passed query string contains parameter placeholders, and parameter values are passed separately. It is up to the database backend, then, to perform parameter substitution and proper quoting. For the debug information placed in connection.queries, Django does parameter substitution, but it does not attempt to do the quoting, as that varies from backend to backend. So do not be concerned by the lack of parameter quoting in connection. queries: it does not imply that parameters are not quoted correctly when they are actually sent to the database. It does mean, though, that the SQL from connection. queries cannot be successfully cut and pasted directly into a database shell program. If you want to use the SQL form connection.queries in a database shell, you will need to supply the missing parameter quoting. You might have noticed and may be curious about the LIMIT 21 included in the previous SQL. The QuerySet requested did not include a limit, so why did the SQL include a limit? This is a feature of the QuerySet repr method, which is what the Python shell calls to display the value returned by the Survey.objects.filter call. A QuerySet may have many elements, and displaying the entire set, if it is quite large, is not particularly useful in Python shell sessions, for example. Therefore, QuerySet repr displays a maximum of 20 items. If there are more, repr will add an ellipsis to the end to indicate that the display is incomplete. Thus, the SQL resulting from a call to repr on a QuerySet will limit the result to 21 items, which is enough to determine if an ellipsis is needed to indicate that the printed result is incomplete. Any time you see LIMIT 21 included in a database query, that is a signal the query was likely the result of a call to repr. Since repr is not frequently called from application code, such queries are likely resulting from other code (such as the Python shell, here, or a graphical debugger variable display window) that may be automatically displaying the value of a QuerySet variable. Keeping this in mind can help reduce confusion when trying to figure out why some queries are appearing in connection.queries. There is one final item to note about connection.queries: despite the name, it is not limited to just SQL queries. All SQL statements sent to the database, including updates and inserts, are stored in connection.queries. For example, if we create a new Survey from the shell session, we will see the resulting SQL INSERT stored in connection.queries: >>> import datetime >>> Survey.objects.create(title='Football Favorites',opens=datetime.date. today()) <Survey: Football Favorites (opens 2009-09-24, closes 2009-10-01)> >>> print connection.queries[-1]['sql'] INSERT INTO "survey_survey" ("title", "opens", "closes") VALUES (Football Favorites, 2009-09-24, 2009-10-01) >>> Here we have been accessing connection.queries from a shell session. Often, however, it may be useful to see what it contains after a request has been processed. That is, we might want to know what database traffic was generated during the creation of a page. Recreating the calling of a view function from within a Python shell and then manually examining connection.queries is not particularly convenient, however. Therefore, Django provides a context processor, django.core. contextprocessors.debug, that provides convenient access to the data stored in connection.queries from a template. Summary We have now completed the overview of debugging support in Django. Specifically, we have: - Learned about the Django settings that control the collection and presentation of debug information - Seen how when debug is turned on, special error pages are produced that help with the task of debugging problems - Learned about the history of database queries that is maintained when debugging is turned on, and saw how to access it If you have read this article you may be interested to view :
https://www.packtpub.com/books/content/django-debugging-overview
CC-MAIN-2015-18
refinedweb
2,632
52.19
CTL(2) OpenBSD Programmer's Manual SEMCTL(2) NAME semctl - semaphore control operations SYNOPSIS #include <sys/types.h> #include <sys/ipc.h> #include <sys/sem.h> int semctl(int semid, int semnum, int cmd, union semun arg); DESCRIPTION (see chmod(2)) */ u_short seq; /* sequence # (to generate unique msg/sem/shm id) */ key_t key; /* user specified msg/sem/shm key */ }; semctl() provides the following operations: GETVAL Return the value of the semaphore. SETVAL Set the value of the semaphore to arg.val. GETPID Return the pid of the last process that did an operation on this semaphore. GETNCNT Return the number of processes waiting to acquire the semaphore. GETZCNT Return the number of processes waiting for the value of the semaphore to reach 0. GETALL Return the values on- ly be executed by the super-user, or a process that has an ef- fective user ID equal to either sem_perm.cuid or sem_perm.uid in the data structure associated with the message queue. as- sociated with the semaphore can do this. The permission to read or change a message queue (see semop(2)) is de- termined message queue. [EACCES] The caller has no operation permission for this semaphore. [EINVAL] semid is not a valid message semaphore identifier. cmd is not a valid command. [EFAULT] arg.buf specifies an invalid address. SEE ALSO semget(2), semop(2) OpenBSD 2.6 August 17, 1995 2
http://www.rocketaware.com/man/man2/semctl.2.htm
CC-MAIN-2018-39
refinedweb
232
60.41
PID Control of Robotics Connection Serializer Stinger Description In this project, I controlled the Serializer Stinger using PID control theory. Components for this project are following: - Mbed Serial Adapter - Serializer Stinger - Battery for Stinger( 12V - 2A ) - SD card The purpose of this project is learning and implement PID on a mobile robot base. The mobile robot base will move in a circular repetitive motion. Serializer Stinger is a good robot to start with because it has embedded PID control algorithm. This tutorial assume the views have a basic understanding of programming on mbed and PID control theory. Wiring Diagram Connect serial adapter and Serializer Stinger with serial cable and null modem if necessary. Serializer Stinger Serializer Stinger is a well developed system. The brain is a board having two H-bridge. a micro-controller, Control of the robot is by sending commands through several kinds of protocol. In this project, I use RS232 serial to do this. Several common commands are introduced here. For all commands, refer to the user manual. The syntax of command is a command name followed by parameters. Every command must be terminated with "Carriage Return" character(<CR>). 1. fw<CR> check the firmware version. 2. blink 1:60<CR> blink led1 at frequency 60. 3. vel<CR> query the velocity of two wheels. 4. vpid<CR> Query the velocity PID constants. 5. vpid 10:0:5:10<CR> Set velocity PID constants 6. mogo 1:30 2:45<CR> Set the velocity of motor 1 by 30 ticks/seconds and motor 2 by 45 ticks/seconds 7. digo 1:1000:25 2:1000:25<CR> Move distance 1000 ticks at velocity 25 Equipped with these commands, we're able to control Stinger. Here is a snippet code to send command to Stinger main.cpp #include "mbed.h" Serial uart(p28,p27); int main() { while (1) { wait(1); uart.baud(19200);//The default baud rate of Stinger is 19200 uart.printf("blink 1:0\r");//blink led1 at frequency 0, which means off } } Tunning Code Setup Using mbed to send velocity command to Stinger and read velocity of each motor from Stinger. Using these data plots the system response in Matlab. The partial code for mbed: main.cpp uart.printf("mogo 1:20 2:20\r");//let motor run at velocity 20 t.start();//start the timer while(1){ uart.printf("vel\r");// Send velocity command //Get response from Stinger i = 0; while( (tmp = uart.getc()) != '>' ){ if( tmp != 13 && tmp != 10 ){ buf[i++] = tmp; } } double jj1 = (buf[0]-'0')*10+(buf[1]-'0');// cast char to int double jj2 = (buf[3]-'0')*10+(buf[4]-'0');// cast char to int pc.printf("20 %f %f %f ", jj1,jj2, t.read());// send data to host computer // The number of data to collect. if(j < 100){ j++; }else{ break; } } t.stop(); The matlab code to get the data from serial port serial.m s = serial('COM5'); set(s,'InputBufferSize',10240); set(s,'BaudRate',9600); if strcmp(s.Status, 'closed') fopen(s); end j = fscanf(s,'%f %f %f %f',[4,2000]); fclose(s); delete(s); clear s; Code to plot data in Matlab plot.m data = transpose(j); [row col] = size(data); target = data(:,1); wheel1 = data(:,2); wheel2 = data(:,3); time = data(:,4); plot(time,target,'r');hold on; plot(time,wheel1,'b'); plot(time,wheel2,'g'); axis auto; hold off; Tuning PID constant The major job in this project is tuning velocity PID constants. Using feedback loop to control the system is the core of PID control. First of all, let's see what effect each one has on the system: Using this table as a guide. There're several common methods to tuning. The one I used here is called Ziegler-Nichols. Comparing with other tuning method, this method is simple to do for beginners. The first step is adjust Kp value until the system oscillate. For example: From this plot, we need to measure the oscillation period ( T ). Then calculate Kp, Ki and Kd according to the table: Since we are implementing PID, we using the third row to get PID constants. Applying these constants to Stinger using "vpid " command. The new running plot looks a lot better: Normally, the result won't be this nice. These values might need more tuning. If that's the case, the table at the beginning of this section come to serve. Adjusting based on ones' need. There's no universal perfect PID constants. Running Demo Reference Please log in to post comments.
https://os.mbed.com/users/dustsnow/notebook/pid-control-of-robotics-connection-serializer-stin/
CC-MAIN-2019-51
refinedweb
755
67.76
pyramid. The Pyramid FAQ suggests you use pyramid_formalchemy if you want a Django style admin interface for Pyramid. I tried it and found that while the documentation is terrible it looks like pyramid_formalchemy could be a good way to do this. It didn’t come out perfectly straight away, and it took some detective work to figure out how to customize it at all, but it looks like it’s actually quite easy to customize in any way you would like. There’s also fa.bootstrap which looks nice, and I think is based on pyramid_formalchemy, but I didn’t try, and I’m not sure what the license is. A Quick Introduction I will create a toy Pyramid app that I can use to keep track of which rock climbing routes I’ve climbed. This will involve first setting up a Pyramid app with sqlalchemy and pyramid_formalchemy, and then creating a sqlalchemy model class to store the info in the database, allowing pyramid_formalchemy to provide the forms to add and edit the information. So following along with the pyramid_formalchemy docs: Create The App And Get It Up And Running [sourcecode language=”bash”] $ # create the python environment and install necessary packages $ mkvirtualenv formalchemy $ pip install six $ pip install pyramid_formalchemy $ pip install pyramid_fanstatic $ pip install fa.jquery [/sourcecode] that’s pyramid_fanstatic , not pyramid_fantastic . . . [sourcecode language=”bash”] $ # use Pyramid’s pcreate to start a Pyramid app with sqlalchemy scaffolding. $ pcreate -s alchemy rockclimber [/sourcecode] as the docs say, update setup.py to add 'pyramid_formalchemy' to install_requires [sourcecode language=”bash”] $ # now add the pyramid_formalchemy scaffolding $ python setup.py develop $ cd .. $ pcreate -s pyramid_fa rockclimber [/sourcecode] as README_FORMALCHEMY.txt says, add config.include('rockclimber.fainit') to rockclimber/init.py: main() [sourcecode language=”bash”] $ # a missing dependency apparently $ pip install couchdbkit $ # run Pyramid’s autogenerated db initialization script to create a sqlite db and tables. $ initialize_rockclimber_db development.ini $ # run the development web server $ pserve development.ini [/sourcecode] visit localhost:6543/admin and woo! that’s pretty fancy! the dummy MyModel class that the alchemy scaffold creates is available to CRUD. Add My Own Model So now it’s time for my rock climbing route model. add to rockclimber/models.py [sourcecode language=”python”] from sqlalchemy import Boolean, Date class Route(Base): ”’ A SQLAlchemy model class that will persist in the database all the information about a rock climbing route that I want to keep track of. ”’ __tablename__ = ‘routes’ id = Column(Integer, primary_key=True) name = Column(Text) rating = Column(Text) guidebook = Column(Text) route_type = Column(Text) is_indoor = Column(Boolean, default=False) location = Column(Text) date_climbed = Column(Date) climbing_partners = Column(Text) is_lead = Column(Boolean, default=True) notes = Column(Text) [/sourcecode] [sourcecode language=”bash”] $ # recreate the database, and restart the web server $ rm rockclimber.sqlite $ initialize_rockclimber_db $ pserve development.ini [/sourcecode] nice! So that was easy. There are a couple of things wrong with this though, the dates months are weird and it would be nice to have Route Type be a select. Add A Select Input And A Better Renderer For The Date One of the files created when the pyramid_fa scaffold was run was called faforms.py. If we make that file look like this: [sourcecode language=”python”] from formalchemy import forms from formalchemy import tables from rockclimber import models class FieldSet(forms.FieldSet): pass class Grid(tables.Grid): pass route_type_options = [(”, ”), (‘boulder’, ‘boulder’), (‘sport’, ‘sport’), (‘trad’, ‘trad’)] # Create a specially named instance of FieldSet that pyramid_formalchemy will find and use for # the Route model. Route = FieldSet(models.Route) Route.configure( options=[ Route.route_type.dropdown(options=route_type_options), Route.date_climbed.date(), ] ) [/sourcecode] then we get a dropdown for route and avoid the month problem by using a different renderer for date altogether. There’s still a problem with the dropdown where the current value isn’t selected when you edit the model though. So there we have it. You should take my solution for the dropdown and date rendering with a grain of salt as I’m not by any means an expert. This did seem to me to be the way you’re supposed to do it because the scaffold creates the faforms.py and then the pyramid_formalchemy views.py does this sort of thing: [sourcecode language=”python”] 350 @actions.action() 351 def new(self): 352 fs = self.get_fieldset(suffix=’Add’) [/sourcecode] and: [sourcecode language=”python”] 231 def get_fieldset(self, suffix=”, id=None): 232 """return a FieldSet object bound to the correct record for id . 233 """ 234 request = self.request 235 model = id and request.model_instance or request.model_class 236 form_name = request.model_name + suffix 237 fs = getattr(request.forms, form_name, None) 238 if fs is None: 239 fs = getattr(request.forms, request.model_name, 240 self.fieldset_class) [/sourcecode] which is to say that on Add it first looks for an instance of a FieldSet named RouteAdd in faforms.py and then, if it fails to find that, for an instance of a FieldSet named Route in the same place, before using a default FieldSet . Would I Use This For Real? So, the documentation is bad. I couldn’t find a bunch of tutorials or articles about it when googling for help, and some of the stuff I did find was out of date. The FormAlchemy google group I found had posts mostly between 2007 – 2012 (although more recent posts did have responses) which suggests it’s not currently very actively used. pyramid_formalchemy last got a commit in April 2013. There’s an obvious glaring problem with the out of the box date renderer. On the other hand pyramid_formalchemy and FormAlchemy seem mature and fully featured. It was quite easy to get up and running and quite easy to customize once I understood what I needed to do. I was able to create a useful app in a couple of hours (even with all the googling) typing very few lines of code. Which is awesome. I plan on using it again. Have you tried (and perhaps had better success with?) any other packages that solve this problem? This work is licensed under a Creative Commons Attribution-NonCommercial-NoDerivatives 4.0 International License.
https://artandlogic.com/2014/07/a-django-style-admin-interface-for-pyramid/
CC-MAIN-2020-10
refinedweb
1,012
57.57
#include <coherence/util/DualQueue.hpp> Inherits AbstractConcurrentQueue. List of all members. Producers work on the tail of the queue, consumers operate on the head of the queue. The two portions of the queue are maintained as seperate lists, and protected by seperate locks. When a consumer looks at the head of the queue, if it is empty, the head and tail will be swaped. Create a new DaulQueue. Swap the head and the tail, but only if the head is empty and the tail is not. The calling thread must already hold a the head lock. Return the head element list. Return the element list (tail). Return the head lock. Lock protecting operations on the head of the queue, and tail swapping. We cannot simply lock on the head element list as it gets swapped with the tail. To avoid deadlock issues the Queue lock should never be obtained while holding the head lock. For example: COH_SYNCHRONIZED(getHeadLock()) { COH_SYNCHRONIZED(this) { // this is NOT ok } } COH_SYNCHRONIZED(this) { COH_SYNCHRONIZED(getHeadLock()) { // this is ok } } The latter approach was chosen as it allows users of the DualQueue to perform external synchronization without risking deadlock.
http://docs.oracle.com/cd/E24290_01/coh.371/e22845/classcoherence_1_1util_1_1_dual_queue.html
CC-MAIN-2016-44
refinedweb
190
67.55
This section includes pages with additional information on key KML elements and how to use them. - KMZ FilesUpdatedLearn how to package up (and compress) your KML file and all its related images, overlays, icons, and sound files into one tidy unit that can be posted or emailed as a single entity. - Touring - Google Earth 5.0 introduces touring: KML-controlled movement through space and time. Touring-related elements are contained in the Google extension namespace. - Altitude Modes - With the introduction of elements in the Google extension namespace, Google Earth 5.0 can take viewers underwater with new clampToSeaFloor and relativeToSeaFloor altitude modes. This chapter also discusses the traditional, above-ground modes. - Time and Animation - Any Feature in KML can have time data associated with it. When a KML file contains a Feature with TimeSpan or TimeStamp elements, Google Earth displays a time slider. Using the slider and play button, the user can "play" the entire sequence or can select individual time periods for display. - Cameras - The Camera element provides an additional way to specify the viewpoint for a Feature. Cameras are used with PhotoOverlays, another feature added in KML 2.2. <Camera> provides full six-degrees-of-freedom control over the view, so you can position the Camera in space and then rotate it around the x, y, and z axes. - PhotoOverlays - The ImagePyramid child element of PhotoOverlay provides for efficient handling of arbitrarily large photographs in Google Earth. - Sky Data in KML - Now you can display celestial data in Google Earth. This page describes how to set up your KML file to view the sky, with tips on converting standard celestial coordinates to display in Google Earth, Sky mode. - Adding Custom Data - You can add custom data to KML Features in three different ways, depending on the kind of custom data. The new ExtendedData element allows you to add your own untyped data, typed data, or arbitrary XML data to a KML Feature. Google Earth preserves this information along with the file. Untyped data and typed data contain display elements that can be used for style templates and entity replacement in the balloon. - Models - Three-dimensional objects can be modeled naturally in their own coordinate space and exported as COLLADA™ files, then imported into Google Earth and placed on the Earth's surface. - Regions - Regions provide culling and level-of-detail behavior that allow you to fine-tune how your data is presented in Google Earth. When used with NetworkLinks, Regions enable streaming of very large datasets, with "smart" loading of data at multiple levels of resolution (see the section on Super-Overlays). You can also simulate Google Earth's layers using Regions. - Updates - You can incrementally update data loaded by NetworkLinks—changing, adding, and deleting KML data that was previously loaded into Google Earth. - Expiration - This page discusses how to prevent KML data from becoming stale, through the use of HTTP headers and KML expiration times.
https://developers.google.com/kml/documentation/topicsinkml
CC-MAIN-2016-40
refinedweb
488
53.81
blockbook 1.1.4 An API client for a Blockbook server (). Blockbook library # A library for communicating with the Blockbook API. Some calls are missing. Usage # A simple usage example: import 'package:blockbook/blockbook.dart'; main() { var client = new Blockbook(); } Installing # Add it to your pubspec.yaml: dependencies: bity: any Licence overview # All files in this repository fall under the license specified in COPYING. The project is licensed as AGPL with a lesser clause. It may be used within a proprietary project, but the core library and any changes to it must be published online. Source code for this library must always remain free for everybody to access. Features and bugs # Please file feature requests and bugs at the issue tracker.
https://pub.dev/packages/blockbook
CC-MAIN-2020-34
refinedweb
121
68.26
pylons_sandbox 0.1.0 An experimental Buildout recipe backwards-compatible with zc.buildout.egg but with extra features for Pylons users. This is a recipe for use with Buildout. It is identical to Buildout's zc.recipe.egg but has the following extra features: - Can install the scripts from any dependent package - Can setup an executable interpreter if you provide a suitable application for your platform Warning This is very much alpha software and has only been tested on Debian Etch. There are probably bugs on other platforms such as Windows. It is designed more as a proof-of-concept than a production-ready recipe. To get started first download the Buildout bootstrap: wget "*checkout*/zc.buildout/trunk/bootstrap/bootstrap.py" Then create a buildout.cfg file, replacing /path/to/pylons/app/src with the path to your Pylons application and replacing PylonsApp with the name of your application: [buildout] develop = /path/to/pylons/app/src parts = python [python] recipe = pylons_sandbox interpreter = python eggs = PylonsApp You can now buildout your application: $ python bootstrap.py $ bin/buildout So far the pylons_sandbox recipe has behaved exaclty the same as the default zc.buildout.egg recipe, installing all the required dependencies for your Pylons app to the local buildout sandbox. It has also set you up with a bin/python script and a bin/buildout script which you can use to buildout any future changes. For Pylons use you should set the option dependent_scripts=True so that scripts from packages such as Nose and PasteScript get created in the bin directoy: [buildout] develop = /path/to/pylons/app/src parts = python [python] recipe = pylons_sandbox interpreter = python eggs = PylonsApp dependent_scripts = True Now run the following to re-buildout the directory: $ bin/buildout -N The -N option means that buildout doesn't look for new dependencies if it can meet them from files it already has installed. This means it is a bit quicker to re-buildout the directory. You should now have a bin/paster command you can use to serve your Pylons application. For the majority of users this set up will be fine but the pylons_sandbox recipe has one more feature, the launcher option. If you want to treat your buildout setup as a true sandbox you will need a Python interpreter which is an actual executable so that other scripts can use your sandboxed Python interpreter in a #! line of in a script such as a CGI script used by Apache. The python file generated by Buildout is actually just a Python script itself so can't be used in this manner. If you set the launcher option, the pylons_sandbox recipe will create a new interpreter by appending .buildout to the name specified in the interpreter option and it will add a facility so that the directory of the calling script is on sys.path. It will then copy the application specified by the launcher option to the name specified in the interpreter option. In our exampls so far this means the buildout python script would be in bin/python.buildout and the application to lauch it would be in bin/python and could now be used in a #! line. This is all well and good but you need the application itself. Here is some C++ code which when compiled will create a suitable application. It has been described as "gruesome" so I'm happy to accept a patch with some neater C++. Create a launcher.cc file with this content: /* * Buildout Launcher * +++++++++++++++++ * * This application excutes a python script in the same directory as the * application. This is useful because it effectively turns a Python script * into a real executable which you can use on the #! line of other scripts. * * The script to be executed should have the same name as the the filename of * this compiled program but with a .py extension added to the end. The real * Python interpreter used to execute the script is dermined from the script's * #! line or /usr/bin/python is used as a fallback if no Python interpreter * can be found. * * The Python interpreters generated by Buildout are actually just Python * scripts so this application allows them to be run from a real executable. * * Compile this file with the following command: * * g++ launcher.cc -o launcher * * Copyright James Gardner. MIT license. No warranty to the maximum extent * possible under the law. * */ #include <vector> #include <string> #include <unistd.h> #include <fstream> using namespace std; int main(int argc,char *argv[]) { vector<string> args; int i; args.push_back("python"); for (i=0;i<argc;i++) args.push_back(argv[i]); args[1] = strcat(argv[0], ".buildout"); char *new_argv[argc+1]; for (int i=0 ; i<argc+1 ; i++) { new_argv[i] = (char *)args[i].c_str(); } new_argv[argc+1] = NULL; vector<string> text_file; ifstream ifs(new_argv[1]); string temp; string temp_short; getline(ifs, temp); if (strncmp((char *)temp.c_str(), "#!", 2)) { /* default to /usr/bin/python if no #! header */ temp_short = "/usr/bin/python"; } else { temp_short = temp.substr(2,(temp.length()-2)); } char python[temp_short.length()]; strcpy(python, (char *)temp_short.c_str()); return execv(python, new_argv); } Compile this with: $ g++ launcher.cc -o launcher and place the launcher application in the same directory as your buildout.cfg. You can then update your buildout.cfg to look like this: [buildout] develop = /path/to/pylons/app/src parts = python [python] recipe = pylons_sandbox interpreter = python eggs = PylonsApp dependent_scripts = True launcher = launcher Now re-buildout again: $ bin/buildout -N You should have a nicely working sandbox with a real Python executable as well as all the other benefits of deploying using the Buildout system. Test it out: $ bin/python >>> import pylons >>> As you can see all the module dependencies are present. - Author: James Gardner <james at pythonweb dot org> - Categories - Package Index Owner: thejimmyg - DOAP record: pylons_sandbox-0.1.0.xml
http://pypi.python.org/pypi/pylons_sandbox
crawl-002
refinedweb
965
56.05
I have been doing 32bit buffer overflows for some time and I decided to try some 64bit overflows, to explore some more realistic scenarios. I have compiled my code with gcc -fno-stack-protector -z execstack -no-pie overflow.c -o Overflow. Here is the code: #include <stdio.h> #include <string.h> void function(char *str) { char buffer[32]; strcpy(buffer,str); puts(buffer); } int main(int argc, char **argv) { function(argv[1]); } Using gdb I determined how many bytes I need to write to control the return address. This is 40 bytes. So at first I tried to write 40bytes of “A” and then 6bytes of “B” to test the control of the return address. Here is a screenshot: I found and tested a 23 byte shellcode that executes “/bin/sh”, so I try to write a nop-sled of 13 bytes, the shellcode and the first 6 bytes of the return address that need to change. So I come up with this (in gdb): r $ (python -c'print "\x90"*13+""+"\x10\xe1\xff\xff\xff\x7f"') I have set 2 breakpoints before and after the execution of strcpy and examine the memory. This is the stack before the strcpy: where at address 0x00007fffffffe138 is the return address of function function And this is the stack right after the strcpy execution: So in my understanding, after I press c to continue the execution, I must “return” to the nopsled and then execute the shellcode in gdb. Instead I get a SIGILL, for illegal instruction. I cannot figure out why this is happening, any help/suggestions/pointer would be much appreciated.
https://proxieslive.com/64bit-buffer-overflow-fails-with-sigill-cannot-understand-the-reason/
CC-MAIN-2020-50
refinedweb
271
60.85
help fsolve (numpy) - alexandrepfurlan Hi all, I'm trying obtain the roots of a function that depends on a parameter. For example : The equation eos= math.log(1.-x)+x**2*(e22*y+ e11*(1-y) + 2*y*(1-y)*e12) I need to obtain the roots (x) such as eos = 0 for a specific value of y. In order words, I fix y, and I solve (using fsolve) eos. I'm trying to do : `def EOS(x,y) : e11=1.00 ; e22=0.40 ; e12=0.60 return math.log(1.-x)+x**2*(e22*y+ e11*(1-y) + 2*x2*(1-y)*e12) for i in arange(1,99,1) : y=i*0.01 ans[i]=fsolve(lambda x: EOS(x,y),x0) But I have a wrong answer. Someone know how use the fsolve (or other alternative way) with y as parameter (not a variable) ? Someone could help me ? Many thanks for the help Best Alexandre - Webmaster4o You'll probably have better luck posting on stackoverflow. It's a wider community The sympylibrary (preinstalled in Pythonista) might be useful for this, it allows you to work with formulas and equations that contain symbols, and I think you can substitute symbols and solve for a symbol as a variable and such. I haven't used those features of sympymuch (I use it mostly as an advanced calculator) so I can't help you with any details, sorry. This podcast might be of interest for a recent description of Sympy from its author. alex, pythonista does not, as far as i can tell, come with fsolve. perhaps you can elaborate about what is failing. If you plug your answer back into EOS, does it return something near zero? If so, you have found your root. If not, is it possible that a real root does not exist? What are you using for x0, and x2 in the code you posted? One problem you may be having: x=0 is a root of your above equation for all y, and in fact is the only root unless x2 is less than -0.8333. Perhaps this is nit the function you meant to be finding roots of (missing parenthesis, etc?) It might help you to plot these functions vs x. import matplotlib.pyplot as plt import numpy as np x2=-1 #roots only exist if x2 is negative, and <-0.83 def EOS(x,y) : e11=1.00 ; e22=0.40 ; e12=0.60 return np.log(1.-x)+x**2*(e22*y+ e11*(1-y) + 2*x2*(1-y)*e12) for i in np.arange(1,99,1) : y=i*0.01 #ans[i]=fsolve(lambda x: EOS(x,y),x0) x=np.linspace(-5,1,100) plt.plot(x,EOS(x,y)) plt.show()
https://forum.omz-software.com/topic/2925/help-fsolve-numpy
CC-MAIN-2021-04
refinedweb
465
83.66
I’m trying to implement a classic Health bar in a gameplay UI. I got it working on the server but not on the client. In the UUserWidget the Health percentage is updated like supposed but not the Health bar. I tried a lot of things and I also tried in blueprint with the same result. This is my cpp UUserWidget code (the function is called by the player controller and the log report the good percentage for both server and client) #include "PuzzlePlatform/UI/GameplayUI.h" #include "Components/ProgressBar.h" void UGameplayUI::UpdateProgressBar(float HealthPercentage) { if (HealthBar) { UE_LOG(LogTemp, Warning, TEXT("GameplayUI UpdateProgressBar Health Percent %f"), HealthPercentage); HealthBar->SetPercent(HealthPercentage); } } I tried to replicate the variable or not and I tried to directly pass the Health percentage to the UI but I got always the same result the variable is updated but not the Progress Bar. This is not the first time I created multiplayer UI but the first I use progress bar in multiplayer maybe it is different than other widget object. Thanks for your help!
https://community.gamedev.tv/t/uuserwidget-and-progress-bar-in-multiplayer/178195
CC-MAIN-2022-33
refinedweb
178
61.26
I need to be able to read lines of code from a .txt file, and then execute them in Java. Yes, you could use classes that implement the JavaCompiler interface to compile a java program within your running java program and have the class files created available for using in your program. It's not simple. What "other program" is generating the code? Why the need for two programs? It's a mod for Minecraft. My program allows you to draw the building outside of the game, then save the code for that building into a text file, and then Minecraft will run the code from that text file to create your building in the game. If Minecraft is executing the code, then all your program needs to do is write the correct instructions to a text file and send it along. Right? Why would you need to execute it? I may be using the wrong terminology I guess. I just need to place the code from the text file into minecraft, and then then let minecraft do it's thing like normal. Okay, I figured it, but I've run into one last problem that I haven't been able to figure out. So, what my program does now, is write everything it needs into a .java file, run a batch file to compile the .java file into a .class file, and put it straight into the minecraft.jar, all with one button. However, when I compile it, I get a ton of errors, because it has minecraft code, but is being compiled separately from minecraft. So, from what I can figure out, I need to set the classpath to use minecraft.jar while compiling... but this is where I get lost. Like I said, I'm just now learning java, so I don't really understand the javac terminology and stuff. =/ (My program is written in python.) I did, that's how I figured out that this is what I need to do. I've tried several different things based on what I read there, but none of them work. It always says that the java file I made doesn't exist, when it definitely does. Like I said, I'm not actually coding in java, I just have to do this because my program works with minecraft... so I don't really know what I'm doing. It always says that the java file I made doesn't exist If you get error messages, you need to post the full text of the messages if you want any help with them. You also need to show the command you entered and the contents of the folder where the command was entered. To copy the contents of the command prompt window: Click on Icon in upper left corner Select Edit Select 'Select All' - The selection will show Click in upper left again Select Edit and click 'Copy' Paste here. Well, when I just write javac myfile.java It gives me this error: LLBLOCK1.java:3: error: cannot find symbol public class LLBLOCK1 extends Block ^ symbol: class Block LLBLOCK1.java:5: error: cannot find symbol private World worldObj; ^ symbol: class World location: class LLBLOCK1 LLBLOCK1.java:12: error: cannot find symbol public boolean blockActivated(World world, int i, int j, int k, EntityPlayer entityplayer) ^ symbol: class World location: class LLBLOCK1 LLBLOCK1.java:12: error: cannot find symbol public boolean blockActivated(World world, int i, int j, int k, EntityPlayer entityplayer) ^ symbol: class EntityPlayer location: class LLBLOCK1 LLBLOCK1.java:9: error: cannot find symbol super(i, j, Material.wood); ^ symbol: variable Material location: class LLBLOCK1 LLBLOCK1.java:14: error: package Block does not exist world.setBlockWithNotify(i + 0, j + 0, k + 0, Block.stone.blockID); ^ 6 errors Which I think is because it's being compiled away from the minecraft.jar, and I honestly don't know what to write when specifying the path. I'm not going to know where this program is going to be installed, so I need to write it in a way that will work with everyone's computer.
https://www.daniweb.com/software-development/java/threads/399239/is-it-possible-to-run-code-from-a-txt-file
CC-MAIN-2015-32
refinedweb
684
73.88
The bigint data type needs some kind of bucket-chain to keep the actual numbers warm and cozy. An array would be nice, I s’pose. The current JavaScript standard ECMA 5.1 has more than just the standard, catch-all Array data type, it has a small subset of explicitly typed arrays, too. We need unsigned integers and the Uint32Araay would be a nice fit, other wise we’ll need to go to some length to guarantee the unsignedness of the elements. The common first reaction to this kind of news from a newbie would be some “Hooray!” or whatever the kids say today. Not the experienced programmers, though, for they know their committees well. They will curl their brows, grab a headache pill or two and look it up, and—Lo and behold!—they will never be disappointed by the result. These typed arrays, they are no exception here.. For some unknown reasons[1] they come with a large knapsack full of bloat. It seems that it was absolutely not possible to just add some simple, C-like arrays for a handful of integer data types, it had to have every single whistle and bell available and don’t forget to add the gong! Ok, it is not that extreme, it still has some use but it really is unnecessary complicated. Imagine allocating an array in C99 of unsigned long int data and setting it to zero. uint32 *array; if ( NULL == (array = calloc(nitems * sizeof(uint32))) ) { errno = ENOMEM; return false; } Now you have a pointer array to play with. If you want to offer several different type in one function you could use a union or some other of the common tricks. The main problem here is the byte-ordering; you have to check it and translate if needed and that has some cost involved. A very small amount, but significant. uint32 change_byteorder_ul(uint32 ul){ # if defined HAS_WRONG_BYTEORDER return ((((ul) & 0xff000000u) >> 24) | (((ul) & 0x00ff0000u) >> 8) | (((ul) & 0x0000ff00u) << 8) | (((ul) & 0x000000ffu) << 24)); #else return ul; #endif } For 32 and 16 bit long unsigned integers, you may find some functions in arpa/inet.h useful, namely the ntoh* and hton* ones. So there is some overhead involved but much less than with JavaScript’s general, catch-all data-type Array. This fact might lead the innocent new programmers to the conclusion that the new typed arrays are significantly faster. The weatherbeaten one do not conclude, they test instead. The Old Ones even go a step further, they let test: Jperf says it is faster On the other hand: Jperf says it is slower float64Array on the…uhm…third hand says it is much slower You don’t live long enough to morph into one of the Old Ones without the urge to look deeper. Let’s do a more practical test with different Javascript-machines; a simple prime-sieve will do here. We need some helpers: var MP_YES = true, MP_NO = false; Number.prototype.isOk = function(){ return ((!isNaN(this) && isFinite(this)))?MP_YES:MP_NO; }; Number.prototype.isInt = function(){ if(!this.isOk()){ return MP_NO; } else{ if( this > -9007199254740992 && this < 9007199254740992 && Math.floor(this) == this ) return MP_YES; } return MP_NO; }; Array.prototype.memset = function(val){ for(var i = 0;i<this.length;i++){ this[i] = val; } }; A Bitset (many to find at github, I rolled my own for license reason) function BitSet(lngth){ var len = Math.ceil(lngth/32); var buf = new ArrayBuffer(len*4); this.Bitstring = new Uint32Array(buf); //this.Bitstring = new Uint32Array(len); //this.Bitstring = new Array(len); //this.Bitstring.memset(0>>>0); this.Length = lngth; } Three different attempts: with an explicit ArrayBuffer(number_of_bytes_needed), with an implicit one, and with a normal Array which needs to be set to zero manually. The unsigned right shift by zero presses a cast to unsigned. The prime-sieve algorithm used wouldn’t need it (it works by setting all bits to one first) but just for the fairness. We need some functions to make use of the bitset: BitSet.prototype.set = function(where){ if( where > this.Length || where < 0) return false; this.Bitstring[where>>>5] |= (1 << (31-( where &31))); return true; }; BitSet.prototype.clear = function(where){ if( where > this.Length || where < 0) return false; this.Bitstring[where>>>5] &= ~((1 << (31-( where &31)))); return true; }; BitSet.prototype.get = function(where){ if(where > this.Length || where < 0) return -1; return ((this.Bitstring[where>>>5] >>> ((31-(where&31)))) & 1); }; BitSet.prototype.nextset = function(n){ var N = this.Length; while(n<N && !this.get(n))n++; if(n == N && !this.get(n)){ return -1;} return n; }; BitSet.prototype.setall = function(){ for(var i=0;i<this.Bitstring.length;i++){ this.Bitstring[i] = 0xFFFFFFFF>>>0; // Found this, must be some legacy code to press unsigned //this.Bitstring[i] = ((~(0&0xFFFFFFFF))); } }; The source of the pointer-juggling is unknown, but some refinement had been done by E.J. Wilburn at 7/12/00. The code after Wilburn’s refinement is: #define GET_BIT(s, n) (*(s+(n>>3)) >> (7-(n&7)) & 1) #define SET_BIT(s, n) (*(s+(n>>3)) |= 1 << (7-(n&7))) #define CLEAR_BIT(s, n) (*(s+(n>>3)) &= ~(1 << (7-(n&7)))) E.J. Wilburn suggested: “You might want to change these to inline functions and do some bounds checking.” The decision if the functions shall be inlined should better be left to the compiler’s optimisation routines, which wWould leave us with the precious work of bounds checking. But I’m digressing. Again. We need another helper for the Uint32Array if you want to print it: Uint32Array.prototype.join = function(str, base){ var len = this.length,i; var del = (str) ? str : ","; if(len == 0){ return ""; } // check given base before or leave it to toString()? if(len == 1){ return this[0].toString(base); } var ret = ""; for(i = 0;i < len - 1; i++){ ret += this[i].toString(base); ret += del; } ret += this[i].toString(base); return ret; }; The position of the individual bits is relevant here, so uint32array.join(",",2) might be useful for debugging. It is not needed, though, for the prime-sieve and the benchmark to run. The actual prime-sieve Pragmath = {}; //Pragmath.primesieve = null; Pragmath.primelimit = 10000000; Pragmath.sieve = function(n){ var k, r, i, j; n = n + 1; Pragmath.primesieve = new BitSet(n); Pragmath.primesieve.setall(); Pragmath.primesieve.clear(0); Pragmath.primesieve.clear(1); for(k = 4; k < n; k += 2){ Pragmath.primesieve.clear(k); } r = Math.floor(Math.sqrt(n)); k = 0; while(k < n){ var tmp = k; k = Pragmath.primesieve.nextset(k + 1); if(k <= tmp){ break; } if(k > r) break; for(j = k * k; j < n; j += 2 * k) Pragmath.primesieve.clear(j); } //console.log("n = " + Pragmath.primesieve.Bitstring.join(",",2)); }; Pragmath is just the namespace here, stolen from my old work. Code necessary to make use of this sieve: Math.isSmallPrime = function(n){ if(!n.isInt() || n > Pragmath.primelimit) return undefined; if(Pragmath.primesieve.get(n) == 1) return true; return false; }; Math.nextPrime = function(n){ if(!n.isInt() || n+1 > Pragmath.primelimit) return undefined; return Pragmath.primesieve.nextset(n); }; Math.precPrime = function(n){ if(!n.isInt() || n < 2) return undefined; return Pragmath.primesieve.prevset(n); }; Math.primePi = function(n){ var k=0;var ct =0; if(!n.isInt() || n + 1 > Pragmath.primelimit) return undefined; while(k<n ){ k = Pragmath.primesieve.nextset(k+1); if(k>n || k <0) break; ct++; } return ct; }; Math.primes = function(n){ var ret, k = 0; if(!n.isInt() || n < 2 || n + 1 > Pragmath.primelimit){ return undefined; } ret = new Array(); while(k < n){ k = Pragmath.primesieve.nextset(k + 1); if(k > n || k < 0){ break; } ret.push(k); } return ret; }; I think I just started to give it al its proper namespace instead of cluttering Math, so… The test itself writes a primesieve hopping to and fro through the array and a count of the primes which is also hopping but only in one direction. One could also test really random reads and writes. var start = new Date().getTime(); // fill it (runtime a bit more than O(n)) Pragmath.sieve(10000000); // read it var result = Math.primePi(10000000-1) var stop = new Date().getTime(); r = "found " + result + " primes in " + (stop-start) + " milliseconds"; // alert is not defined in node.js // but there is a console.log in FF-32 if(typeof alert === 'undefined'){ console.log(r); }else { alert(r); } I have a couple of JavaScript interpreters at hand and can do some tests at home without the need to upload something to JPerf: I run every test at least three times. The single abnormality was with Opera and the direct treatment of Uint32Array ( ArrayBuffer gets handled internally in that case, according to MDN). The runtime increased every time by about 8%. It is interesting, although not surprising, that Epiphany (Gnome 2) was the winner here. [1] Protip: never ask a committee for the reason, never!
https://deamentiaemundi.wordpress.com/2014/09/06/javascript-array-vs-uint32array/
CC-MAIN-2018-05
refinedweb
1,464
69.18
0 I have this webservice that connects to my database via a table adapter and I am trying to read the column value based on the controls passed by an AJAX script that I wrote. I tried to use a hash table to replicate the actual database column. What I like to accomplish is to use to concatinate the hash value into the row property of the table and I can't get to work. Now I don't know if my implementation is feasible, but if anyone knows a way to accomplish what I am trying to do, I would appreciate it. [WebMethod] public int GetAlertSetting(string Control, int ContactID) { Hashtable ContactHash = new Hashtable(); int AlertsValue = 0; ContactHash.Add("rdoLB", "LowBattery"); ContactHash.Add("rdoGeo", "Geofence"); ContactHash.Add("rdoAC", "AcDc"); ContactHash.Add("rdoCU", "Capacity"); string HashValue = Convert.ToString(ContactHash[Control]); AlertsTableAdapter GAlerts = new AlertsTableAdapter(); GeoPlane.AlertsDataTable GAlertsTable = GAlerts.GetAlertsByContactID(ContactID); GeoPlane.AlertsRow GAlertsRow = GAlertsTable[0]; AlertsValue = GAlertsRow.ContactHash[Control]; //don't know if this is correct. return (AlertsValue); //I could also return the value like this return(GAlertsRow.ContactHash[Control]); //If I can get the above to work. }
https://www.daniweb.com/programming/web-development/threads/108115/dynamically-pass-column-value-to-database-based-on-radio-button-selection
CC-MAIN-2016-50
refinedweb
188
51.95
tytso@mit.edu writes:> We should very clearly change the binfmt interfaces so that open_inode()> is called by do_execve(), instead of opening the file each time for> binary format. Aaron Tiensivu's patch to speed up get_empty_filp() is> important too, but there's a much more direct way to speed upIm suprised my patch to get_empty_filp() still isn't in thekernel. Note that it isn't just the exec()'s the suffer from theREALLY bad running time, but just about everthing is slowed fairlydramtically. On machines doing lots of open()'s etc, patchingget_empty_filp() will give you an instant 5% improvement.Just to repeat it again, and CC it to linus....--- linux/fs/file_table.c.old Tue Jul 30 19:47:35 1996+++ linux/fs/file_table.c Tue Jul 30 19:59:41 1996@@ -102,7 +102,7 @@ { int i; int max = max_files;- struct file * f;+ static struct file * f = NULL; /* * Reserve a few files for the super-user..@@ -111,15 +111,25 @@ max -= 10; /* if the return is taken, we are in deep trouble */- if (!first_file && !grow_files())- return NULL;+ if (!first_file) {+ if (!grow_files())+ return NULL;+ f = first_file;+ } do {- for (f = first_file, i=0; i < nr_files; i++, f = f->f_next)+ for (f = f->f_next, i=0; i < nr_files; i++, f = f->f_next) if (!f->f_count) {+#if 1+ f->f_mode = f->f_pos = f->f_flags = f->f_count =+ f->f_reada = f->f_ramax = f->f_raend = f->f_ralen =+ f->f_rawin = f->f_owner = 0;+ f->private_data = f->f_op = f->f_inode = NULL;+#else remove_file_free(f); memset(f,0,sizeof(*f)); put_last_free(f);+#endif f->f_count = 1; f->f_version = ++event; return f;
https://lkml.org/lkml/1997/4/7/87
CC-MAIN-2015-22
refinedweb
263
60.65
Hi ..I am Sakthi.. - Java Beginners Hi ..I am Sakthi.. can u tell me Some of the packages n Sub...:// Thanks... that is available in java and also starts with javax. package HEMAL RAJYAGURU   File IO The Java IO package is used to perform various input/output processing activities.In this section we are giving overview of java IO. Java io classes... are planning to learn file management using Java IO package.This class is available Java IO FileReader classes. Example : Here I am giving a simple example which will demonstrate you about how to use java.io.FileReader. In this example I have created a Java...Java IO FileReader In this tutorial we will learn about the FileReader class IO concept IO concept Write a java program that moves the contents of the one file to another and deletes the old file. Hi Friend, Try...!"); } } For more information, visit the following link: Java Move File   Java IO SequenceInputStream Example Java IO SequenceInputStream Example In this tutorial we will learn about... or concatenate the contents of two files. In this example I have created two text... by the stream. read() : This method is used to read the bytes from the input stream Read Text from Standard IO from the keyboard and write output to the display. They also support I/O... through System.in which is used to read input from the keyboard...); Working with Reader classes: Java provides the standard I/O Java read lines from file Java read lines from file Any code example related to Java read lines from file? In my project there is requirement of reading the file line by line... to split the line and save into database. But I am trying to find code example IO File - Java Beginners IO File Write a java program which will read an input file & will produce an output file which will extract errors & warnings. It shall exclude... from the log file. This is the task assigned to me..Please help me Java IO OutputStream Java IO OutputStream In this section we will read about the OutputStream class... to the specified file. In this example I have tried to read the stream of one file...) named write.txt which has no contents. After completion of this example hi online multiple choice examination hi i am developing online multiple choice examination for that i want to store questions,four options,correct answer in a xml file using jsp or java?can any one help me? Please Working With File,Java Input,Java Input Output,Java Inputstream,Java io Tutorial,Java io package,Java io example to work with a file using the non-stream file I/O. The File class is used... it, deleting it, reading from or writing to it. The constructors of the File class...; Lets see an example that checks the existence of a specified file Java Notes: Table of Contents Java Notes: Table of Contents Java Notes. These Java programming notes... Applications - example Compiling a Java program Applets... IO File IO java.io.File File I Writing UTF-8 Encoded Data in Java Writing UTF-8 Encoded Data in Java  ... will learn, how to write text in a file in UTF-8 encoded format... into the specified file in the UTF-8 encoded format. The program takes an input unable to see the output of applet. - Applet unable to see the output of applet. Sir, I was going through the following tutorial... this example. when i click on this link i go to the following link http java IO java IO Write a Java program to accept a file name as command line argument. Append the string "File Modified by Programme" to the end of the same file and print the contents of the modified File java binary file io example java binary file io example java binary file io example Java IO InputStream Example Java IO InputStream Example In this section we will discuss about... have a source from where the stream can be read by the InputStream so I have... IOException read(byte[] b) : This method is used to read the byte from io io create a meanu based text editor in java having features of creating file,viewing file,deleting file,renaming file,copying file and cutting file Java IO Java IO What an I/O filter IO in java IO in java Your search mechanism will take as input a multi-word query and will return a list of documents where the given words appear. 1. Your... the words specified appear closer to one another. For example, if you search Java FileOutputStream Example the text read from the abc.txt file will be written. Now created a Java class named...Java FileOutputStream Example In this section we will discuss about the Java... to read the input stream from the file 'abc.txt' and used FileOutputStream java io java io Write a program to use a File object and print even numbers from two to ten. Then using RandomAccessFile write numbers from 1 to 5. Then using seek () print only the last 3 digits Java IO Reader and how the characters can be read from the stream. In this example I have created...Java IO Reader In this section we will discuss about the Reader class in Java...) : This method is used to read the characters of specified length from an array How to read value from xml using java? How to read value from xml using java? Hi All, I want to read value from following xml using java.. In <Line>,data is in format of key and value pair.. i want to read only values..could u plz help me in this?Thanks Read from a window - Java Beginners Read from a window HI, I need to open a website and read the content from the site using Java script. Please suggest. Thanks Java Io BufferedWriter Java IO BufferedWriter In this section we will discuss about... that contents of an existing file will be read first and then these contents will be written to the new file. For this I have created a Java class named unable to connect database in java unable to connect database in java Hello Everyone! i was trying to connect database with my application by using java but i am unable to connect...();} And i am getting this error java.sql.SQLException: [Microsoft][ODBC Unable to call .jrxml file from jsp Unable to call .jrxml file from jsp Hi, I am doing web application in jsp. To create report I have used ireport and interated with neatbeans using... then it unable to access it.Error also not showing. I will show my code and its output io packages - Java Beginners io packages How can I add two integers in java using io pacages unable to connect database in java unable to connect database in java Hello Everyone! i was trying to connect database with my application by using java but i am unable to connect...){e.printStackTrace();} And i am getting this error java.sql.SQLException Read page from Web server Java NotesRead page from Web server The Java io package provides... is the complete example code in Java which reads the data from website and prints... from website and save on disk. In this example code we have used following Print Only Forms Contents - Java Beginners Contents ,How I can Do that, plz Help Me Hi Friend, Please go through the following link: Only Forms Contents Hello Sir I Have Created Simple How to read text from - Java Beginners How to read text from How to retrieve text from the images... Does we have any function to get text over the images Hi Friend, We... I am Barbie Thanks Java IO Path Java IO Path In this section we will discuss about the Java IO Path. Storage... called the delimiter. The file separator varies from O/S to O/S for example.... These sub folders can contains a file or sub folders and so on. For example Read the value from XML in java Read the value from XML in java Hi, i have an XML with the following code. I need to get the path("D... the permissions on that file.So how can i read that value. This is little urgent Read XML using Java Read XML using Java Hi All, Good Morning, I have been working as a Manual Test engineer for last 4 years. Now i started learning java... of all i need to read xml using java . i did good research in google and came to know retrieve message contents - Java Beginners retrieve message contents hi , dbfile system to store message headsers in mysql database and message contents in file system . how to retrieve message contents. thanks bala.. Hi friend, Content Java IO StringReader in Java. In this example I have created a Java class named...Java IO StringReader In this section we will discuss about the StringReader class in Java. StringReader class reads the string from the input stream i am unable to identify the error in my code i am unable to identify the error in my code class Program { public static void main(String[] args) { BufferedReader br=new BufferedReader(new InputStreamReader(System.in)); System.out.println("enter Hi.. Hi.. what are the steps mandatory to develop a simple java program? To develop a Java program following steps must be followed by a Java... read Java ClassPath Then in the second step you are required a Java editor, you Java FileInputStream Java FileInputStream In this section we will discuss about the Java IO... be read or skipped over from the input stream. Syntax : public int available...() throws IOException read() This method is used to read byte of data from hi all - Java Beginners hi all hi, i need interview questions of the java asap can u please sendme to my mail Hi, Hope you didnt have this eBook. You... friend, I am sending you a link. This link will help you. Please read hi - Java Beginners hi hi sir, i am entering the 2 dates in the jtable,i want to difference between that dates,plz provide the suitable example sir Hi.../beginners/DateDifferent.shtml How to read excel contents when uploaded How to read excel contents when uploaded I am working on a project where the user uploads his excel file. Jsp page must read the excel contents and display it on the screen. I am using Apache POI for importing the jar Upload and insert the file contents - Java Server Faces Questions files on server and insert the values into table from JSP page. So i have... please post the sample of CSV file. I will develop the example for you. Thanks... if i could get the sample code at the earliest Hi, Please check Java IO CharArrayReader the stream of char array. In this example I have created a Java class to read...Java IO CharArrayReader In this tutorial we will learn about... the facility to read the character input stream from char array. Input stream Java IO OutputStreamWriter "); bw.newLine(); bw.write("Java IO OutputStreamWriter Example...Java IO OutputStreamWriter In this section we will learn about the Java... the OutputStreamWriter. A Java class that I have created for demonstrating how to use Java IO PipedReader the stream into pipe. Then I have tried to read the characters from the piped...Java IO PipedReader In this section we will discuss about the PipedReader in Java. java.io.PipedReader reads the characters from pipe. java.io.PipedWriter hi - JavaMail hi Hi, I am using hibernate inorder to retrieve data from two... to retrieve the data from tables in Java class and get me the code how it is in Java. pls if any help ,I would appreciate u. regards Java IO BufferedReader from buffer. In this example I have used a BufferedReader with the default size...Java IO BufferedReader In this section we will discuss about the BufferedReader class in Java. BufferedReader class in java.io package is used for read hi.. hi.. I want upload the image using jsp. When i browse the file then pass that file to another jsp it was going on perfect. But when i read that image file, we cant read that file.it return -1. and my console message hi! hi! how can i write aprogram in java by using scanner when asking... to to enter, like(int,double,float,String,....) thanx for answering.... Hi...); System.out.print("Enter integer: "); int i=input.nextInt Java IO InputStreamReader Java IO InputStreamReader In this section we will discuss about... is used to read characters from the stream. For efficiency, it is advised...() : This method is used to read characters from the stream. Syntax : public int hi hi i want to develop a online bit by bit examination process as part of my project in this i am stuck at how to store multiple choice questions options and correct option for the question.this is the first project i am doing unable to find resource 'VM_global_library.vm' - Java Server Faces Questions unable to find resource 'VM_global_library.vm' pls help me, I am... Aug 12 12:03:54 CAT 2008 [info] Velocimacro : adding VMs from VM library...] ResourceManager : unable to find resource 'VM_global_library.vm' in any resource loader. Tue Java IO PipedWriter Java IO PipedWriter In this tutorial we will learn about the PipedWriter.... This example explains how to write a specified length of characters started from...); // read from the PipedReader int c; while((c How to get UTF-8 working in java webapps? How to get UTF-8 working in java webapps? How to get UTF-8 working in java webapps hi - Java Beginners hi local variable cname is accessed from within inner class; needs to be declared final i want to be use this variable in another class,what i am do sir,plz tell me.if i am declare a variable is a final Java IO FilterWriter Java IO FilterWriter In this example we will discuss about the FilterWriter.... In this example I have created a Java class into which tried to write the data into the output stream. In this example I have used the various of Java Java read binary file Java read binary file I want Java read binary file example code that is easy to read and learn. Thanks Hi, Please see the code at Reading binary file into byte array in Java. Thanks Hi, There is many Viewing contents of a JAR File Viewing contents of a JAR File This section shows you how you can read the content of jar file from your java program and list the content. This section helps you to view Java file read write operation Java file read write operation how to read and write the data from text file.Suppose i have text file with 4 fields name ,roll no ,marks1,marks2... to the other class.Suggestion please hi Dhirendra, here I am giving Java IO PushbackReader . In this example I have created a simple Java class named...Java IO PushbackReader In this section we will discuss about...() : This method is used to read a character from the stream. Syntax : public Java I/O Examples about the I/O from the command line in Java. Java IO Path... at a time from the input stream. Java IO SequenceInputStream Example... will discuss about the Command Line Java IO Standard Error. How To Read String From,how to place the database records into jtable ,i am using... and placed into a jtable plzzzzzzzzzzzzzzz Hi Friend... =DriverManager.getConnection("jdbc:odbc:access"); String sql = "Select * from Java IO Writer into the output stream I am giving a simple example. In this example I have created a Java class named JavaWriterExample.java where I have created an object...Java IO Writer In this section we will discuss about the Writer class in Java hi - Java Beginners hi hi sir,when i am add a jtable record to the database by using...){ countoftable=table.getRowCount(); for(int i... transid from cusamt where transid=(SELECT max(transid) from cusamt hi - Hibernate hi hi all, I am new to hibernate. could anyone pls let me know what is generic DAO class generated by MyEclipse while doing mapping. I want... as possible. thanks Hi friend, Read for more information hi - Java Beginners ) with column names,if i am using this table type table(rowno,colno) how i am set... AM */ /** * * @author samith */ public class NewJFrame extends...); } /** This method is called from within the constructor PHP file_get_contents() Function PHP file_get_contents() Function Hi, How do i read the content of file using PHP program? So kindly provide any example or online help reference for filegetcontents() Function in PHP. Please feel free to suggest. Thanks hi - Java Beginners hi hi sir,when i am enter a one value in jtextfield the related... phone no sir Hi Friend, Try the following code: import... = true; }else if(code==KeyEvent.VK_RIGHT) { for(int i=0
http://www.roseindia.net/tutorialhelp/comment/1445
CC-MAIN-2014-35
refinedweb
2,844
66.13
The Financial Effect of Bernie Madoffs Ponzi Scheme. Bernard L. Madoff, simply known as Bernie is an American allegedly the operator of what is known as the largest Ponzi scheme in history. Bernie before his capture, acted as the stock broker, investment advisor and non-executive chairman of the NASDAQ stock market (Cherry and Wong 11). It was not later than 2009 when Madoff pleaded guilty; he was guilty for turning his wealth management business into a massive Ponzi scheme. This scheme according to various sources defrauded thousands of investors billions of dollars (Cherry and Wong 16). In 1960, Bernard Madoff founded one of the biggest firms in Wall Street. He was the chairman of his company "Madoff Investment Securities LLC", until his arrest was warranted on the December of 2008 (Forbes 21). Before his arrest, the Madoff Investment Securities emerged as one of the top market maker businesses on the Wall Street (Forbes 27). After his arrest, Madoff explained to his children as a confession that most of his asset management unit of his firm was none other but a big fraud. The aim of this paper is to find out how Bernard L. Madoff managed to pull up the largest Ponzi scheme in history as well as the financial effects that this scheme had on the investors in the stock market. The Bernard Madoff Ponzi scheme left a lot of people financially wounded and as many people may think that this scheme only affect the Wall Street, research will prove otherwise. The Wall Street was just one of the victims of Madoff's Ponzi scheme. Others include BSBC and Maxam Capital Management LLC. Just to name a few. A Ponzi scheme is an investment where by fraud is involved. Usually when this scheme involves operations that pays returns to separate investors, not from the actual profit earned by the organization in question, but by profit from their own money or money paid by subsequent investors (Times 15). Due to its abnormally high but short term returns on investment, this scheme enables to entice new investors. Failure chances for this system are high mainly due to the fact that earning is usually less that the payment of the investors. How it started and its Benefiters According to Madoff, the Ponzi scheme began in early 1990s (All Sports New York 1). However, to the beliefs of the investigators or what they managed to scoop out of their investigations this scheme began earlier than that. Some say that the scheme began somewhere in the 1970s while others have different views. During the time huge amounts of money went missing from the client's accounts. The missing amounts included fabricated gains that were said to reach an estimate of $65 billion dollars (credit card compare 13). However, in order to pull out such a Ponzi is not an easy task. For one to be able to convince people to venture into a particular investment requires money and genius mind. Nevertheless, the main factor that made sure that Madoff was successful in his Ponzi scheme was his respect by other investors. He was also a well-established and esteemed financial expert with a reputation that was strengthened due to the reason that he was one of the founders of the renowned NASDAQ stock exchange and had a one term tenure as its chairman (How stuff works 2). He managed to earn the trust of his investors by his genius mind, since he ran his scheme concurrently; his was a legitimate business. He ensured that whenever his investors requested a withdrawal, Madoff Investment Company got their money to them promptly (How staff works 1). In addition to that, Madoff did not tempt his investors with unbelievable returns which were a problem of other schemers. On the contrary, this scheme did not just benefit Madoff. Jeffrey Picower, appear to have benefited the most in the scheme as his estate settled the claims against it for a figure estimated to be around $7.2 billion (Cherry and Wong 19). Another company that benefited more in the scheme is J.P. Morgan Chase & Co. their benefits were seen in terms of interest and fees charged which were to the tune of a billion dollars. Other investors too were included in the scheme and while some of them have decided to return the money that they gained from the scheme some have decided to deny their involvement in the Madoff Ponzi scheme. Examples of the investors that have refused the charges include New York Mets owners Fred Wilpon and Saul Katz as well as other associated individuals and firms. These investors collectively received a collective amount of approximately $300 million; however Wilpon and Katz have rejected their involvement (Forbes 4). Other investors are still unknown but with time it is assumed that most or all the parties involved in this so called 'one big lie' investment will be found with time. His victims The Bernard Madoff Ponzi scheme was declared as the largest Ponzi scheme in history. The so called largest fraud however has left big financial effects on the investors in the market. Most of these investors were directly linked to it while others were not. Thus in this section I am going to point out some of the victims that were affected by Madoff Ponzi scheme. To begin with, HSBC appeared to be among the largest victims of Bernard Madoff Ponzi scheme. The company became a victim of the fraud with a potential exposure of about $1billion to the investment manager's collapsed venture (huffingpost 1). In addition to that, HSBC's revelation resulted from loans it offered its institutional clients, mainly hedge funds that wanted to invest with Mr. Madoff (huffingpost 1). However, the $1billion is said to be just a part of the cash provide in loans by customers who invested an approximate of $500million of their own funds in Mr. Madoff's venture (huffingpost, 2011). To ease their lose, HSBC has been put first on the list whose money will be return, however this will only be to the success of the US authorities recovering any funds that went into Madoffs ventures. On the contrary, Fairfield Greenwich Group was viewed as the greatest loser in this con of the century. The company lost an estimated amount of $7.3 billion in their Fairfield Sentry Ltd (businessinsider, 2011). Fairfield Sentry has a record of more than 15 years with an annual return of 4 to 6 percentage points above benchmark interest rates, this is a report put forward by a marketing document prepared by Zurich-based NPB New Private Bank Ltd (businessinsider, 2011).In a ten year period that ended in 2000, the company's interest rates ranged from 6.4% to 9.8%. This was due to the "split-strike conversion", where the investment manager is made to buy shares belonging to large companies in the US and then entering into options contracts to limit the risk (businessinsider 2). In the wake of the Madoff Ponzi scheme, Fairfield Sentry Ltd Fixed Asset Management opened an account worth $400 million with the Madoff investments. The news of their investment falling into fraud came to them as a shock since then they had been checking with lawyers. Other potential victims to the Madoff Ponzi scheme are the giant French bank BNP Paribas, the Tokyo Based Nomula Holding Inc. and Neue Privat Bank in Zurich (WSJ 2). These two companies which raised lots of funds from investors and farmed out to hedge funds also suffered significant losses even though their loss was not compared to what Tremont Capital Management and Fairfield Greenwich Group, both of New York, had on the Madoff con of the century. Another firm that suffered as victims of the fraud was Kingate Management Ltd who lost an approximate amount of $2.5 billion while investing with Madoff (businessinsider 1). Thus while this seem to be a big loss Santander, which is known as the Eurozone's largest bank by market value lost an allegedly $3.1 billion to the Madoff con (businessinsider 2). Santander had most there assets (2 billion euros) belonging to the institutional investors and international clients of its private-banking businesses (businessinsider 1). The Madoff scam did not just affect corporations but also individuals who had invested heavily in the Ponzi scheme. According to Times a family in America was clearly wiped of their wealth overnight. On the 11 of December 2008, a wife received a call that they had been waiting for 5 years in the morning from the person handling their financial matters just to tell her that they were clearly wiped of their investment. To their knowledge, they did not know it but they had been involved in the grand scheme masterminded by Bernard Madoff (Times website 1). Their investment began after they had sold their home at the peak of the market; the wife had a divorce earlier so the settlement from the divorce too was included in the investment together with other petite amounts they had saved. This however, is not the shocking news since the two lovers never really heard of the name Madoff. According to Times, their investment was carried on by a network organizer associated with Madoff. What attracted them what his 40 years fantastic achievement. Also the fact the wife's entire family was in the business for decades was enough to make them believe that their investment in Madoff's scam was a way forward. However, that is not the only family that was affected by the Madoff scandal. Thyssen Family, although not much of a family but a corporation, was also at the mist of the saga. Businessinsider.com reported that the family had been fund of funds since 1989 (businessinsider, 2011). Their involvement in the Madoff Ponzi Scheme came as a guarantee that the investment was going to bring to them a huge return. Ira Roth's Family too was affected by the saga. The family had their $1 million invested through Mr. Madoff's firm. Ira found this to be a legitimate investment after finding out that his mother in law had been living on the investment's return (businessinsider 2). The list of Madoff's victims goes on and on and thus making his story a very curious case to study. Most of the victims did not have a ware about of what they were doing. Despite the fact that Madoff himself was the owner of one of the top market makers companies on Wall Street was perhaps enough to blind people and make them think that all that he was offering them was a legitimate deal. After effects Bernard Madoff Ponzi scheme is seen as the biggest financial scam in history. However, this scam has left not just victims but also big after effects. Many corporations and individuals were left wondering which way forward they should take. Some of the individuals were completely wiped off their investment savings as well as ventures while others even though did not end up having nothing, need to return what they ventured in the scam. The New York Mets owners Wilpon and Katz involvement in the Madoff's Ponzi is said to affect the Mets' record in various ways. The Wilpons are said to have invested heavily with Madoff, however they did not just invest their money but the Mets' money and money that did not belong to them (Forbes 4). The worst part is that the Wilpons invested money that belonged to the players as well as money they used to fund other projects and TV stations. Despite the fact that, the Wilpons managed to get a lot of returns before the Madoff saga blew off, the saga has caused them now to put Mets on sale. At the beginning their allegations were that they were going to sell 20-25% of the team and none of the SNY but in April 2010 Forbes valued the team together with the SNY at around $825 million (Forbes 2). Their debt is still increasing and now both their team and the SNY are valued at around $225 million. however much the Wilpons are trying to revive the Mets and prevent it from being sold, it is quite clear that their the teams after effects from the Madoff Ponzi Scheme has robbed them off the every other alternative but to sell both the SNY and the team. However, the Madoff Ponzi scheme after effects was not just felt by individuals or corporations. This Ponzi scheme also had an effect on the stock prices as it forced scores of other hedge funds to dispose holdings and increase downward pressure on the stock prices (Forbes 2). These effects were seen after the arrest of the 70 year old investor who was widely considered to have a magic touch as an investor. In addition to that, investors across New York who had clamored to be in Ascot because of their stability of double-digit returns proficiency and the findings of wealth multiplication have all been left with neither head nor tail of what was going on in the corporation (Forbes 3). However, while others were being affected financial wise, the exposure of the fraud on a substantial scale was a upsetting to individuals who put their trust on Madoff with their fortunes and also to non-profit organizations which include Yeshiva University. This university, counted much on Madoff's alleged clandestine trading system to assist operate its institutions (Forbes 2). Justification on the Ponzi Despite the fact that the Madoff Ponzi scheme left so many remnants, a question still remains can financial scam be justified? Many people who fall into financial scams are usually the wealthy type. However, seeming like that is not enough, it has been found that most of the big players of a financial scam are also the wealthy people. For instance the Mets proprietors spent a lot of cash in the scam and thus it was until the whole business failed that they all lost. Despite that this Ponzi left a lot of financial effects of people and corporations, it also left a lesson that will never be forgotten. Madoff's Ponzi just like any other financial scam was not costly to only those who were directly involved but it also had a significant and a far reaching effect among societies nations and even worldwide (creditcardcompare.com.au 2). The Ponzi scheme was bigger than any other financial scandals which have included social security and mortgage mess. The people who have been following the story as it was being air on television and also in court are now asking themselves how much they can trust a corporation they want to invest in. Bernard Madoff Scam cost around $50 billion, and while it appeared to be the worst scam in history, it had its effects which were not just felt by the rich. However, its effects spanned to all nations in the worldwide. The rich together with the poor were all pulled by its magnet. The effect of this Ponzi scheme however has ensured that people will be more careful when it comes to investment. For instance, the two couples that sold all their properties just to invest on Madoff's ventures had not acquired the right information that would have enabled them to actually know what kind of investment they were entering. In a statement published on Times web site the couple stated that they did not know Madoff and thus their financial investment was being carried on by one of his network organizer. This is what smart investors will call lack of legitimate knowledge. More than that, other corporations were caught into the saga since they wanted to increase their profits. Also the fact that Madoff owned a big corporation on Wall Street was enough to actually convince people that his dealings were not just profitable but also legitimate. This backfired for many of the investors. Thus it is very important to actually know the company in which you are investing on. Many financial scams have come up before the Madoff Ponzi scheme but yet people are still being coned by these scam bugs. During the scam the effects are not realized. Even the person orchestrating the scam does not even think of what may happen at the end. It is until the end or after all hell has broken loose that many people come to realize that they were being coned. Thus this is what happened with the Madoff Ponzi scheme. It was not until people received phone calls that they realized that their investment ventures were just lies. However, Forbes has it that, if Madoff had not faced the $7 billion in redemption, the Ponzi scheme had not have been discovered (Forbes 2). This brings us to another lesson learned from this Ponzi 'greed'. Some believe that greed is virtuous, especially when referring to money. However how much greed is good also becomes a question that people need to ask themselves. Madoff clearly knew that what he was doing was not right and thus probably he could have continued with it if he had kept it to the down low. Nonetheless, it is still astonishing the rewards that Madoff managed to pull out of this false investment and thus smart people could have pulled out of it. This is because it is virtually impossible to actually accumulate hefty returns similar to what Madoff gained, and it should have served as a warning to the involved parties (Forbes 1).Instead of waiting until the end where you will be left shocked how such a financial fraud was possible it would have been better if people had actually got smart and start questioning the amount of wealth that was being generated by the Madoff invisible company. Madoff may have conned many individuals, he may have left an investment scare on the financial market as many people are now left wondering where they should invest but in the long run people have to open their eyes. Conclusion In a nutshell it is quite clear that a financial investment can bring huge fortunes to someone. However, financial investments can also leave someone not knowing what has actually happened. Bernie Madoff Ponzi scheme is the latest financial scandal to have taken place and as if that is not enough it has also been labeled as the largest financial scam in history. This financial scam has left many people and corporations until now feeling the effects of the Ponzi but the question still remains will this stop people from being financially conned? Cite This Essay To export a reference to this article please select a referencing stye below:
https://www.ukessays.com/essays/finance/the-financial-effect-of-bernie-madoffs-ponzi-scheme-finance-essay.php
CC-MAIN-2018-34
refinedweb
3,126
58.11
Generate Random Alphanumeric String in C++ In this tutorial, we will learn how to generate a random alphanumeric string in C++ using srand() function. An alphanumeric string is a series of symbols containing only alphabets and numerical digits, without having any special characters. In this article, we will attempt to randomize a string of alphanumeric symbols in the C++ programming language. Here we will be using the rand() and srand() functions from the stdlib.h header file. We will also be using time.h to set the seed for the random functions being used. Using the Random Functions In C++, we have the declaration of the array given below: int a[100]; std::cin>>a> int main() { for(int i = 0; i < 3; ++i) cout>>rand()>>'\t'; return 0; } The output would be: 1681 9562 1288 The second time, the output would still be: 1681 9562 1288 No matter how many times the program, the output will always be: 1681 9562 1288> int main() { srand(time(0)); for(int i = 0; i < 3; ++i) cout>>rand()>>'\t'; return 0; } Now the output would be: 1681 9562 1288 The second output will be different, like: 123 9331 1414 And the third output would also be distinct: 444 23124 9 Create a Random Alphanumeric String in C++ To create the alphanumeric string, we first declare a string having all possible valid values that can be taken, i.e. letters and digits. char valid[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; Now, given a user-defined value of the length of the string to be created, we loop the random value as many times as required to create the required string. #include <iostream> #include<stdlib.h> #include<time.h> using namespace std; int main() { srand(time(0)); int len; char valid[] = "1234567890ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"; char rand_array[250]; const int l = 62; // 62 is the length of string 'valid' cout<<"Enter length of random array required(upper limit = 250)\n"; cin>>len; for (int i = 0; i < len; ++i ) { rand_array[i] = valid[rand() % l]; } cout<<"The Random Array is :\n"<<rand_array; } A sample program run would look like this: Enter length of random array required(upper limit = 250) 25 The Random Array is : u0216qe12MkxPjeeaho0GiCVB739 Hence a random alphanumeric string of given length has been created using C++ through the use of random functions in stdlib.h and setting the seed with the help of time function within the header file time.h. You may also like: Generate a Matrix of Random Numbers in C++ How to fetch a random line from a text file in C++
https://www.codespeedy.com/generate-random-alphanumeric-string-in-cpp/
CC-MAIN-2020-45
refinedweb
424
51.62
Part 3: Deploying your Data Science Containers to Kubernetes. What is koo-burr-NET-eez? Kubernetes (Greek for “helmsman” or “pilot” or “governor”) is an open-source system for automating deployment, scaling, and management of containerized applications. You can cluster together groups of hosts running Linux containers, and Kubernetes helps you easily and efficiently manage those clusters for running your applications. (Credit: Red Hat) For scalable model prediction, we can deploy our trained model onto Kubernetes and let Kubernetes manages the lifecycle of the containers. In part 2 of this series, we have a training image that trains the model, saved it on disk but we are still not doing any model prediction. Let’s wrap the model in a Flask app and exposes it via a RESTful api. The api endpoint will accept a base64 encoded png image and transform the image to fit the model. model = Net()model.load_state_dict(torch.load(os.getenv('model_path', './model/mnist_cnn.pt'))) model.eval()@app.route(‘/predict/’, methods=[‘GET’,’POST’]) def predict(): img = parseImage(request.get_data()) transform=transforms.Compose([ transforms.ToTensor(), transforms.Normalize((0.1307,), (0.3081,)) ]) result = model.forward(transform(img).unsqueeze(0)) num = result.max(1).indices.item() return jsonify({‘result’: num, ‘data’: result.tolist()[0]}) MNIST Draw Frontend The MNIST Draw frontend is adopted from Bob Hammell and converted to ExpressJS. EJS was used to parametrize the flask backend. var mnist_server = process.env.MNIST_SERVER || '';console.log('Using mnist server ' + mnist_server);// index page app.get('/', function(req, res) { res.render('pages/index', { mnist_server: mnist_server, }); }); Bob’s frontend allows a user to easily draw a digit on a canvas and makes a JQuery api call to the flask app which returns the probability of 0–9. In this example, you will see that the model predicted “7" with the highest score. Deploy to Kubernetes With the images built, we can now deploy them to Kubernetes. Prebuilt images are available from my GitHub. Using a Kubernetes cluster with an NGINX ingress controller, I can deploy using a deployment configuration and have my app exposed to the outside world. $ kubectl apply -f kube/mnist.yaml service/mnist-flask created deployment.apps/mnist-flask created service/mnist-draw created deployment.apps/mnist-draw created In mnist.yaml, I have defined the service, deployment and ingress resources for the frontend and backend. The Deployment consists of 1 replica pointing to my images hosted at quay.io and a Service that exposes the pods with ClusterIP, which is an internal-cluster IP. The app is then exposed externally by using Ingress that maps my DNS A record to the Service. $ curl -v * Rebuilt URL to: * Trying 188.166.198.224... * TCP_NODELAY set * Connected to mnist-draw.demo.ltsai.com (188.166.198.224) port 80 (#0) > GET / HTTP/1.1 > Host: mnist-draw.demo.ltsai.com > User-Agent: curl/7.54.0 > Accept: */* > < HTTP/1.1 200 OK < Server: nginx/1.17.10 Scaling One of advantages of using Kubernetes is scaling. Based on my workload demand, I can easily scale my pods and is handled automatically by the Service resource. $ kubectl scale --replicas=3 deployments/mnist-draw -n default deployment.apps/mnist-draw scaled$ kubectl get pods -n default NAME READY STATUS RESTARTS AGE mnist-draw-6ccc79c948-djj9m 0/1 ContainerCreating 0 2s mnist-draw-6ccc79c948-nbqgd 0/1 ContainerCreating 0 2s mnist-draw-6ccc79c948-t4ctv 1/1 Running 0 28m mnist-flask-6f886848bc-5dzpw 1/1 Running 0 34m Summary In this post, we discussed how can you take your trained model and deploy them onto Kubernetes and letting Kubernetes manages the lifecycle of your containers. In the last and final post, we will explore MLOps and how do we do this in a predictable and reproducible manner on an enterprise container platform such as Red Hat OpenShift Container Platform. OpenShift bundles Open Data Hub, a community project sponsored by Red Hat that helps to build and deploy AI workload easily on OpenShift.
https://tsai-liming.medium.com/part-3-deploying-your-data-science-containers-to-kubernetes-aaae769144ec?source=post_internal_links---------5----------------------------
CC-MAIN-2020-50
refinedweb
658
50.12
EF the; } } […] Feature CTP4, also recently dubbed “EF Magic Unicorn Edition”. In the last post we looked at Include with lambda and today we are going to look at the new Find […] EF CTP4 Tips & Tricks: Find « RoMiller.com July 15, 2010 public ICollection Posts { get; set; } Can you explain how to add new Post to uninitialized collection? Might be this must be look like: private ICollection posts; public ICollection Posts { get { return posts ?? ( posts = new Collection()); }} ?? Thanks. Roman July 19, 2010 @Roman The pattern you described is a common one, another alternative is to initialize the collection properties in the constructor. The pattern you suggested will potentially give better performance in situations where you are constructing a large number of objects because you only create the collection when actually needed. I normally use List for the collection properties but you can of course use anything that implements ICollection. EF doesn’t require that you initialize collections and will do it for you when it needs to add to the collection property (which is why the code in the post works). romillerdotcom July 19, 2010 […] EF CTP4 Tips & Tricks: Include with Lambda […] C# Bits: EF CTP4 Released! August 14, 2010 […] EF4 .Include() Method w/ Lambda Support: Ever wanted to use a Lambda expression instead of a string parameter when eagerly loading associations in EF4 using the Include() method? This blog post shows you how you can. […] BusinessRx Reading List : August 29th Links: .NET, ASP.NET, IIS Express, Silverlight, Windows Phone 7 August 29, 2010 […] EF4 .Include() Method w/ Lambda Support: Ever wanted to use a Lambda expression instead of a string parameter when eagerly loading associations in EF4 using the Include() method? This blog post shows you how you can. […] August 29th Links: .NET, ASP.NET, IIS Express, Silverlight, Windows Phone 7 - ScottGu's Blog August 29, 2010 Why not use Single()? Read: weitzhandler August 29, 2010 Will this support Include and a Where clause? Like: .Include(b => b.Posts.Where(x=> x.Status == “Active”)); or something else like that? John Bloom August 30, 2010 WOW! You didn’t mention that in your blog! That’s most compelling, finally!!! weitzhandler August 30, 2010 @weitzhandler & @John Bloom We would like to support filtering with Where in the future, which is why we opted for Select rather than Single. But it’s not there in CTP4. romillerdotcom August 30, 2010 Now that’s what I’ve been waiting for,very nice. alaa9jo September 1, 2010 After rviewing this post I am still saying that the Select (“For collections you use the Select method”) should have been shorter, why use a new lmbda when this can be done in one word? View my blog Even Single() is not the rightest way, an extra lambda is surely not. I guess it’s too late anyway. weitzhandler September 1, 2010 I can not see the strongly typed version of Include? I have EF4 (.Net 4) and VS2010, its still exposing the string based Include. James September 15, 2010 @James You also need to have EF Feature CTP4 installed as the lambda based include is still in preview; ~Rowan romillerdotcom September 16, 2010 @James: Because you didn’t notice this in the article: “Note that this version of Include is an extension method so you will need to add a using for the System.Data.Entity”. That means you have to add: Using System.Data.Entity; Anonymous September 15, 2010 I’m the one who posted this reply :) alaa9jo September 15, 2010 No, I’m the one who posted this reply! Anonymous August 15, 2012 […] October 3, 2010 […] similar extension method is included in the Entity Framework Feature CTP4 (see this article for details). So it is possible that it will eventually be included in the framework (perhaps in a […] [Entity Framework] Using Include with lambda expressions « Thomas Levesque's .NET blog October 3, 2010 […] · EF4 .Include()函数对Lambda的支持:在EF4里用Include()函数加载关联数据时,想用Lambda表达式替换字符参数?这篇文章就教你怎么做。 […] 8月29号的精选好文链接-Scott Guthrie 博客中文版 October 15, 2010 Question on creating a DBContext derived context: is it necessary to declare a DbSet property for each entity class you create? For instance, if I have a Members entity and a MemberProfiles entity, but since a profile can belong only to one member and a member can only have one profile, they share an id field (MemberId). I would only access the profile data through the Member entity. Therefore, do I need to create a property DbSet MemberProfiles { get; set; }? BTW,an excellent series. Actually the most clear, concise, comprehensive one I’ve been able to find on the Internet, to date. Craig Shea October 22, 2010 Hi Craig, You can include extra entities that are not exposed in a DbSet in the OnModelCreating method: public class MemberContext : DbContext { public IDbSet Members { get; set; } protected override void OnModelCreating(ModelBuilder modelBuilder) { modelBuilder.Entity(); } } Hope this helps, ~Rowan romiller.com October 30, 2010 I’m trying to use this on EF4 and VS2010. I’ve included the using System.Data.Entity; but still has the only string version of include. Am I missing something ? Dani December 28, 2010 I would like to use Multi-Level Includes what you proposed, but I could not user more than one relatives. Does Include support only on relation? Thanks in advance. Nuri Yılmaz January 20, 2011 […] May 12, 2012
http://romiller.com/2010/07/14/ef-ctp4-tips-tricks-include-with-lambda/
CC-MAIN-2015-48
refinedweb
886
64.3
Michael Hudson <mwh at python.net> writes: > "Raymond Hettinger" <raymond.hettinger at verizon.net> writes: > >> [Raymond Hettinger] >>> > This patch should be reverted or fixed so that the Py2.5 build works >>> > again. >>> > >>> > It contains a disasterous search and replace error that prevents it >> from >>> > compiling. Hence, it couldn't have passed the test suite before >> being >>> > checked in. >> >> [Michael Hudson] >>> It works for me, on OS X. Passes the test suite, even. I presume >>> you're on Windows of some kind? >> >> >> Here's an excerpt from the check-in note for sha512module.c: >> >> >> RND(S[0],S[1],S[2],S[3],S[4],S[5],S[6],S[7],0,0x428a2f98d728ae22ULL); >> >> RND(S[7],S[0],S[1],S[2],S[3],S[4],S[5],S[6],1,0x7137449123ef65cdULL); >> >> RND(S[6],S[7],S[0],S[1],S[2],S[3],S[4],S[5],2,0xb5c0fbcfec4d3b2fULL); >> >> RND(S[5],S[6],S[7],S[0],S[1],S[2],S[3],S[4],3,0xe9b5dba58189dbbcULL); >> >> RND(S[4],S[5],S[6],S[7],S[0],S[1],S[2],S[3],4,0x3956c25bf348b538ULL); >> >> Perhaps OS X has some sort of Steve Jobs special constant suffix "ULL" >> that Mr. Gates and the ANSI C folks have yet to accept ;-) > > It's an C99 unsigned long long literal, AFAICT (p70 of the PDF I found > lying around somewhere...), so I think it's just Bill who's behind. > However, Python doesn't require C99, so it's pretty dodgy code by our > standards. > > Hmm. You have PY_LONG_LONG #define-d, right? Does VC++ 6 (that's > what you use, right?) support any kind of long long literal? The suffix seems to be 'ui64'. From vc6 limits.h: #if _INTEGRAL_MAX_BITS >= 64 /* minimum signed 64 bit value */ #define _I64_MIN (-9223372036854775807i64 - 1) /* maximum signed 64 bit value */ #define _I64_MAX 9223372036854775807i64 /* maximum unsigned 64 bit value */ #define _UI64_MAX 0xffffffffffffffffui64 #endif Thomas
http://mail.python.org/pipermail/python-dev/2005-August/055582.html
CC-MAIN-2013-20
refinedweb
319
78.14
INTERNATIONAL MONETARY FUND The Macroeconomics of Managing Increased Aid Inflows: Experiences of Low-Income Countries and Policy Implications Prepared by the Policy Development and Review Department (In consultation with the Area, Fiscal, Monetary and Financial Systems, and Research Departments) Approved by Mark Allen August 8, 2005 Contents Page Executive Summary................................................................................................................3 I. Introduction....................................................................................................................6 II. A Macroeconomic Framework for the Analysis of Increases in Aid Inflows...............8 III. Findings from Country Cases......................................................................................17 A. The Pattern of Aid Inflows.................................................................................17 B. Macroeconomic Context.....................................................................................21 C. Real Exchange Rate and Dutch Disease.............................................................23 D. Was Incremental Aid Absorbed?........................................................................27 E. Was Incremental Aid Spent?..............................................................................29 F. Monetary Impact of Aid and Policy Response...................................................37 IV. Conclusions and Policy Implications...........................................................................48 A. Summary of Findings..........................................................................................48 B. PRGF Program Design Issues.............................................................................50 V. Final Considerations ...................................................................................................53 Text Boxes 1 Absorption, Spending, and Central Bank and Fiscal Accounting...............................12 2. Terms of Trade Shocks and Aid Inflows.....................................................................26 3. Aid Volatility and the PRGF-Supported Programs.....................................................33 Figures 1. Total Net Budget Aid...................................................................................................20 2. Changes in Composition of Budgetary Aid.................................................................21 3. Exchange Rates and Aid Inflows.................................................................................25 - 2 - 4a. Programmed vs. Actual Levels of Fiscal Deficit (Excluding Aid) and Net Budgetary Aid....................................................................................................35 4b. Programmed vs. Actual Levels of Fiscal Deficit (Excluding Aid) and Net Budgetary Aid....................................................................................................36 5. Ethiopia and Ghana: Monetary Indicators...................................................................39 6. Ethiopia and Ghana: Limited Aid Impact....................................................................41 7a. Tanzania and Uganda: Monetary Indicators................................................................44 7b. Mozambique: Monetary Indicators..............................................................................45 8. Mozambique, Tanzania and Uganda: Domestic Expenditure Exceeds Absorption....47 Tables 1. Patterns of Aid Inflows................................................................................................18 2. GDP Growth, Inflation and Private Investment...........................................................22 3. The Real Effective Exchange Rate..............................................................................24 4. Balance of Payments Identity......................................................................................28 5. Allocation of Incremental Net Budgetary Aid: Spent or Saved..................................30 6. Domestic Debt and Debt Service Indicators................................................................31 7. Classification by Aid Absorption and Expenditure.....................................................37 Appendices Appendix I. Methodology for Sample Selection..............................................................56 Appendix II . Dutch Disease: Theory and Evidence...........................................................59 References ............................................................................................................................62 - 3 - E XECUTIVE S UMMARY. • Absorption is defined as the widening of the current account deficit (excluding aid) due to incremental aid. It measures the extent to which aid engenders a real resource transfer through higher imports or through a reduction in the domestic resources devoted to producing exports. •. •. - 4 - To save incremental aid, that is to neither absorb nor spend, may be a good way of building up international reserves from a precariously low level or of smoothing volatile aid flows. •. • - 5 -. - 6 - I. I NTRODUCTION 1. Increases in aid inflows allow recipients to increase consumption and investment. Aid presents an opportunity to reduce poverty, increase the standard of living, and generate sustained growth. However, the effective use of increased aid also presents challenges. Good projects must be found and managed, and conditions for budgetary support must be agreed and implemented. The imperative to use the funds well can strain the administrative capacity of recipient governments. In addition, aid flows can weaken ownership, fragment and impair budgetary procedures, encourage rent-seeking behavior, and undermine the accountability of domestic institutions. 2. Related to but distinct from these microeconomic and institutional issues are the macroeconomic challenges of managing aid inflows. Aid inflows can cause upward pressure on the real exchange rate to the detriment of the exporting industries that may be critical to long-run growth. This is fundamentally rooted in the real effects of aid; in other words, microeconomic in nature. But macroeconomic policies can determine how aid is absorbed in the domestic economy. Aid inflows can also create problems of fiscal management and debt sustainability, particularly when they are volatile and when they come in the form of debt. 3. Aid flows to low-income countries have increased somewhat in the past ten years. In a few relatively well-performing low-income countries, aid inflows have expanded substantially from already significant levels. Larger and more widespread increases in aid inflows are seen as critical to achieving the MDGs. 1 A scaling up of aid will amplify the macroeconomic policy challenges arising from the management of aid inflows. The Fund needs to confront these challenges squarely in its capacity as a key provider of advice on macroeconomic policies. Helping countries to manage effectively increased aid inflows would be one of the Fund’s main contributions to the achievement of the MDGs. 4. This paper draws lessons from recent country experiences with the macroeconomic management of large increases in aid inflows. 2 It is designed to complement the case studies being done by the Fund and Bank and the Millennium Project, which are mainly forward- looking. 3 The questions this paper will address are: • Do recipients of aid surges encounter macroeconomic absorptive capacity constraints? • Is Dutch disease a concern? 1 A key recommendation of the UN Millennium Project Task Force is to increase official development assistance rapidly—at least for a dozen or so fast track countries—to support the MDGs. World Bank and IMF (2005) also advocate a substantial increase in aid to low-income countries. 2 It was prepared by a team consisting of Andrew Berg, Shekhar Aiyar, Mumtaz Hussain, Shaun Roache, and Amber Mahone. 3 See United Nations Millennium Project (2005), Bourguignon and others (2005), and Agenor, Bayraktar, and El Aynaoui (2005). - 7 - • How should fiscal policy be adapted to the aid inflows? • Are aid inflows inflationary, and what is the appropriate monetary and exchange rate policy response? Is there a role for sterilization? • Did PRGF-supported programs adequately manage the macroeconomic impact of surging aid inflows? 5. While the benefits of higher aid and the challenges of scaling up are frequently discussed, systematic analysis of country experiences is limited. 4 This paper examines five low-income countries that have dealt with these questions over the past decade. It complements existing work in two ways. First, it examines nuts-and-bolts policy questions of direct relevance to Fund-supported programs. Second, most existing research is based on cross-country and panel regression analyses, which have limitations for policy purposes, particularly with respect to the scaling up of aid. 5 While the paper draws on existing research, it will rely mainly on direct evidence from low-income countries that have experienced a surge in aid inflows. Of course, a case study approach carries its own limitations. The small sample size makes it more difficult to generalize the results to all aid recipients. In addition, it becomes hard to quantitatively (as opposed to qualitatively) control for exogenous changes in the economic environment during the period of increased aid inflows. Finally, long-run effects may be hard to trace. 6. The country studies focus on strong performers defined in terms of institutions and economic policies. This permits drawing of lessons relevant for situations in which, broadly speaking, policy-making is not dominated by macroeconomic disarray, misgovernance, or post-conflict reconstruction. The goal is to learn how to help those countries that are well- positioned, institutionally and in terms of the policy framework, to absorb large quantities of aid. An important number of such countries have emerged in the past decade or so, including in Africa. 6 The selected low-income countries satisfy two criteria: first, each (except Ethiopia) ranks relatively high on the World Bank’s indicator of quality of economic institutions and policies (CPIA), and second, each received large amounts of aid in the late 1990s and early 2000s, including a surge in aid inflows at some point over the period. The 4 For a broad treatment of many of the issues on scaling up aid see Heller (2005) and Klein and Harford (2005). 5 Critical variables are hard to measure in a broad sample. The regression framework handles only with great difficulty the possibility of complex interactions, such as between terms-of-trade shocks, quality of policies, and the macroeconomic effects of aid inflows. Finally, only a few cases (generally those covered in this study) exist of countries that received macro-economically significant increases—several percentage points of GDP—in aid inflows in the context of reasonably strong policies and governance. 6 See World Bank and International Monetary Fund (2005). - 8 - list of countries that satisfied these criteria and are covered in the paper are Ethiopia, Ghana, Mozambique, Tanzania and Uganda (Appendix I discusses sample selection in more detail). 7 7. The paper is centered on the analyses of the country cases. Section II provides a framework for considering the macroeconomic policy response to increases in aid inflows. Section III reports on the country cases. Section IV presents a summary of these findings and implications for PRGF program design. Section V concludes with some of the broader lessons that may be drawn about the macroeconomics of increased aid inflows. II. A M ACROECONOMIC F RAMEWORK FOR THE A NALYSIS OF I NCREASES IN A ID I NFLOWS 8. The macroeconomic impact of aid depends critically on the policy response to aid. In particular, it is the interaction of fiscal policy with monetary and exchange rate policy that is important. In order to highlight this interaction, it is useful to introduce two related but distinct concepts: absorption and spending. 9. Absorption is defined in this paper as the extent to which the non-aid current account deficit widens in response to an increase in aid inflows. 8 This measure captures the quantity of net imports financed by an increment in aid, which represents the real transfer of resources enabled by aid. Absorption captures both the direct and indirect increase in imports financed by aid, i.e., direct purchases of imports by the government, as well as second-round increases in net imports resulting from aid-driven increases in government or private expenditures. Absorption reflects the aggregate impact of the macroeconomic policy response to higher aid inflows, encompassing monetary, exchange rate, and fiscal policies. 10. Absorption can be defined and understood in terms of the balance of payments identity: Current Account + Capital Account = ΔReserves. Breaking the current and capital accounts into their aid and non-aid components, and rearranging items, the following identity is produced: 7 It is also critical to understand better how to help low-income countries with weaker performance on institutions and policies. The achievement of macroeconomic stabilization has been analyzed frequently, most recently in International Monetary Fund (2004) and International Monetary Fund Independent Evaluation Office (2004). The closely-related institutional and governance issues are discussed in the companion background paper (International Monetary Fund (2005b)) and World Bank and International Monetary Fund (2005). Macroeconomic problems in post-conflict situations are discussed in Clément (2005) and International Monetary Fund (2005c). 8 This usage of absorption should not be confused with the related concept of “absorptive capacity” which, in addition, involves questions about the rate of return on investments financed by aid. - 9 - Aid Inflows = ΔReserves – (Non-Aid Current Account + Non-Aid Capital Account). 9 Thus, an increase in aid can serve some combination of three purposes: an increase in the rate of reserve accumulation; an increase in non-aid capital outflows; or an increase in the non-aid current account deficit. The rate of absorption of an increase in aid is then defined as the change in the non-aid current account deficit as a share of the change in aid inflows: 10 Absorption = Δ(non-aid current account deficit)/ΔAid For a given fiscal policy, absorption is controlled by the central bank, through its decision about how much of the foreign exchange associated with aid to sell, and through its interest rates policy, which influences the demand for private imports via aggregate demand. 11 The mechanism will depend on the exchange rate regime, but under any regime, the monetary authority can choose to accumulate reserves or to make them available for importers. 12 In the extreme case where the central bank uses the full increment in aid to bolster international reserves and does not increase net sales of foreign exchange, none of the extra aid will be absorbed. 9 The non-aid current account balance is the current account balance excluding official grants and interest on external public debt, while the non-aid capital account balance is the capital account net of aid-related capital flows, such as loan disbursements and amortization. 10 With this definition, aid that finances capital outflows is not absorbed. This makes sense insofar as aid that flows back out of the country does not transfer real resources to the country. However, there are particular circumstances in which aid that finances capital outflows can be thought of as allowing an increase in absorption relative to a particular counterfactual that is relative to what might have happened without the aid. Suppose, say, because of an increase in political uncertainty residents suddenly desire to move capital abroad. The authorities use a large aid inflow to accommodate this capital outflow. Now suppose also that, without the aid, the authorities would not have accommodated this desire with reserve sales but rather would have allowed an exchange rate depreciation. This depreciation might have resulted in a reduction in the trade deficit. Compared to this counterfactual, the aid has allowed a larger trade deficit and hence more absorption. This is an unusual set of circumstances, but it may prevail when reserve levels are very low. 11 Aid that is directly used to finance imports by the government (e.g., a grant in kind, a grant of foreign exchange that the government immediately uses to purchase imports, or aid that goes directly to NGOs to finance imports) effectively bypasses the central bank and would lead directly to absorption. 12 This point may require some further elaboration. Consider, for example, the case where the central bank wishes to ensure full absorption. Assume, for simplicity, that the capital account is closed except for aid. Under a float, the central bank sells all the aid-related dollars on the market, and the agents who buy the dollars spend them on imports. There is an appreciation of the real exchange rate through nominal exchange rate appreciation. Under a fixed exchange rate regime, the central bank must loosen monetary policy to cause real exchange rate appreciation through an increase in inflation. Some level of the real exchange rate will yield an increase in import demand sufficient to ensure full absorption of the aid dollars at the fixed nominal exchange rate. - 10 - 11. Spending is defined as the widening in the government fiscal deficit net of aid that accompanies an increment in aid: 13 Spending = Δ(G-T)/ ΔAid Spending captures the extent to which the government uses aid to finance an increase in expenditures or a reduction in taxation. Even if the aid comes tied to particular expenditures, governments can choose whether or not to increase the overall fiscal deficit as aid increases. The aid-related increases in expenditures could be on imports or domestically-produced goods and services. Analyzing spending is important because of the natural focus on the budget as a policy variable, and also because of the importance of tensions between the fiscal policy response to aid and broader macroeconomic objectives with respect to the exchange rate and inflation. 12. These definitions of absorption and spending take into account, by construction, the fungibility of aid. For example, if the foreign exchange associated with a particular grant is sold by the central bank, but overall net sales of foreign exchange do not increase, this does not constitute an increase in absorption, because no extra foreign exchange is available to finance an increase in net imports. Similarly, if the government allocates a new grant to financing a domestic project that was earlier financed from different sources, this does not constitute an increase in spending, since the non-aid fiscal deficit remains unchanged. 13. Absorption and spending are distinct though related concepts and policy choices. 14 If aid comes in kind, or if the government spends aid dollars directly on imports, spending and absorption are equivalent, and there is no impact on macroeconomic variables like the exchange rate, the price level, and the interest rate. 15 This paper concentrates on the more difficult and empirically relevant case where aid dollars are gifted to the government, which immediately sells them to the central bank. Subsequently, the government decides how much of the local currency counterpart to spend on domestic projects, while the central bank 13 The deficit net of aid is equal to total expenditures (G) less domestic revenue (T), and is financed by a combination of net aid and domestic financing: G-T=Non-aid fiscal deficit = Net aid + Domestic financing. 14 The distinction between absorption and spending, in the terminology used in this paper, is one of the central issues associated with the “transfer problem” and discussed in Keynes (1929). Keynes was concerned with the problems involved for Germany in generating current account surpluses to pay reparations after World War I. He argued that for the fiscal authorities to accumulate the local currency counterpart to the required transfers was only part of the transfer problem—the other part being generating the net exports and therefore the required foreign exchange. See Milesi-Ferreti and Lane (2004) for a recent general discussion of the transfer problem and the real exchange rate. 15 Strictly speaking, this is true only if the gifted or directly imported good is one for which there was no existing effective demand. If the good transferred was already demanded domestically, then increasing the good’s supply would depress the price of tradables relative to non-tradables, leading to real appreciation. - 11 - decides how much of the aid-related foreign exchange to sell on the market and spending differs, in general, from absorption. 16 14. Taken together, different combinations of absorption and spending out of incremental aid define the policy response to a surge in aid inflows. Below are described the four basic combinations of absorption and spending, together with a discussion of the macroeconomic implications of each. Box 1 provides a numerical example showing how the central bank and fiscal accounting works in each of these four cases. Aid absorbed and spent 15. This is the textbook case, in that this is the situation assumed (explicitly or implicitly) in most discussions of the macroeconomic implications of aid inflows. 17 The government spends the aid increment and foreign exchange is sold by the central bank and absorbed by the economy via a widening of the current account deficit. The fiscal deficit is larger but financed by higher aid. Spending and absorption allows an increase in government spending by redeploying resources that had been devoted to the traded goods sector. In terms of the familiar national income identity Y = C + I + G + (X-M), for a given output, a fall in (X-M) allows a rise in G. 16. Of course, output may not be fixed. Government expenditures may well increase output, both in the short run through the effects of associated spending on aggregate demand and in the long run through the increase in the capital stock permitted by the associated investment. To the extent that output can rise without a deterioration in the non-aid current account, however, these increases in aggregate demand and investment could have been undertaken without the aid flows. Aid absorption refers to the use of aid to finance the non- aid current account deficit associated with these aid-related increases in aggregate demand, investment, and output in general. 16 Pratti and Tressel (2005) find that monetary policy can control the timing of absorption. Aid could also go to the private sector directly. Here, too, if the private sector uses the dollars to directly finance imports, there is unlikely to be much macroeconomic impact. Where the private sector sells the dollars to the central bank and uses the local currency proceeds to finance domestic expenditures, similar issues will arise as in the case of government spending. 17 See the recent contribution from Bevan (2005). - 12 - Box 1. Absorption, Spending, and Central Bank and Fiscal Accounting In this numerical example, the government sells the aid dollars to the central bank and receives a local currency deposit at the central bank in return. Net international reserves (NIR) increase by 100 and net domestic assets of the central bank (NDA) fall by 100 (because government deposits with the central bank are a negative NDA item). This places the economy in the lower-right box of the matrix. What happens next depends on whether the central bank sells the foreign exchange and on whether the government increases the deficit; each case is discussed in the text. The example below assumes a floating exchange rate regime. The accounting story would be the same, but the numbers and details different, with a peg. Central Bank and Fiscal Accounts Example With Aid Inflow of 100 Spend Don't Spend Absorb Central Bank Balance Sheet Central Bank Balance Sheet NIR 0 M 0 NIR 0 M -100 NDA 0 NDA -100 Fiscal Accounts Fiscal Accounts Ext. Fin.+100 Deficit +100 Ext. Fin.+100 Deficit 0 Dom. Fin.0 Dom. Fin.-100 Don't Absorb Central Bank Balance Sheet Central Bank Balance Sheet NIR +100 M +100 NIR +100 M 0 NDA 0 NDA -100 Fiscal Accounts Fiscal Accounts Ext. Fin.+100 Deficit +100 Ext. Fin.+100 Deficit 0 Dom. Fin.0 Dom. Fin.-100 Notes: NIR is net international reserves and M is reserve money. NDA is net domestic assets. Ext. Fin is external financing, and Dom. Fin is domestic financing of the deficit. - 13 - 17. Some real exchange rate appreciation may be necessary and indeed appropriate in response to a sustained higher level of aid. This is because some combination of exchange rate appreciation and (if there is excess capacity) increased aggregate demand is necessary to generate the increased net imports that aid allows. 18 18. The degree of exchange rate appreciation required to absorb the aid will in general depend on the structural response of the economy and the extent to which aid directly finances imports. For example, real appreciation would be higher to the extent that aid inflows finance expenditures on non-tradable goods rather than directly financing imports. 19 On the other hand, if higher incomes feed strongly into higher import demand and if the supply of non-traded goods responds strongly to the increase in their relative price, the real appreciation would be limited. In economies with significant unemployment and the potential for a quick supply response, the additional demand for non-tradable goods could induce additional employment and production, with little increase in the price level and limited real appreciation. In the longer run, investments that increase productivity in the non-tradable sector could also reduce or even eliminate the real exchange rate appreciation. 19. The mechanism for real appreciation would vary depending on the exchange rate regime. In a pure float, the central bank would sell the foreign exchange associated with the aid, causing a nominal (and real) exchange rate appreciation. In a peg, the real appreciation would take place through a period of inflation, with the increase in government expenditure being accommodated by the central bank. The increase in aggregate demand and the real appreciation would again increase net import demand, leading the central bank to sell foreign exchange in defense of the peg. Aid neither absorbed nor spent 20. The authorities could choose to respond to the aid inflow by building international reserves, and neither increasing government expenditures nor lowering taxes. In this case there is no expansionary impact on aggregate demand, and no pressure on the exchange rate or prices. 20 21. Not spending the aid may be infeasible over a longer time period, as donors need to account for how their assistance has been utilized. Of course, money is fungible, so that in 18 The real exchange rate is generally understood in this paper to refer to the relative price of non-traded to traded goods, as a conceptual matter. When it comes to measurement, the case studies unfortunately tend to follow the common practice of measuring the real exchange rate as a function of the nominal exchange rate and changes in consumer price indices. It turns out for the cases under consideration that this is unlikely to make a major difference, but further work on the correct measurement of the real exchange rate would appear justified. 19 One category of non-tradeable goods that might be important in this process is skilled labor; if aid raises the wages of skilled professionals, this could translate into real appreciation. 20 There may be second-order effects, e.g., expectations may change as a result of the central bank’s higher international reserve position. - 14 - principle not spending aid dollars is compatible with undertaking the projects favored by donors, while cutting back on other budgetary expenditures. In practice, the extent to which this is possible would depend on the room available—both fiscally and politically—to cut expenditures in other areas. Aid absorbed but not spent 22. Increased aid inflows can be used to reduce inflation in those countries that have not yet achieved stabilization. In such a case, the authorities can sell the foreign exchange associated with increased aid inflows to sterilize the monetary impact of domestically- financed fiscal deficits. The result would typically be slower monetary growth, a more appreciated real exchange rate, and lower inflation. Aggregate demand may increase as the inflation tax declines, with a corresponding increase in private consumption and investment. The deterioration of the trade balance that often accompanies such a stabilization program is financed by the aid inflow. 21 23. In countries that have already achieved inflation stabilization but have large domestic public debt, the government could use the proceeds from aid to reduce the stock of local currency government bonds outstanding. This would tend to result in increased private consumption and investment, which would raise net imports through the indirect effect of higher private after-tax income on import demand. The extra foreign exchange sold by the central bank would finance this increased demand for net imports. Again, some real exchange rate appreciation is likely to be necessary to mediate the increase in net imports. 24. Whether a strategy of absorbing but not spending aid is feasible in a particular situation depends on whether a monetary relaxation would translate into higher domestic investment or consumption. If there are no good private investment opportunities, for example, an increase in credit to the private sector could result in private capital outflows or a buildup of excess commercial bank reserves at the central bank. 22 In addition, as with the neither-absorb-nor-spend strategy, donors’ needs to account for the use of their assistance may make it difficult to sustain a no-spending approach. Aid spent but not absorbed 25. A fourth possibility is that the fiscal deficit, net of aid, increases with the jump in aid, but the authorities do not sell the foreign exchange required to finance additional net imports. The macroeconomic effects of this fiscal expansion are similar to increasing government expenditures in the absence of aid, except that international reserves are higher. The increased deficits inject money into the economy. 21 This is the case emphasized by Buffie and others (2004). 22 The IMF Independent Evaluation Office (2004) argues that PRGF program assumptions that crowding in will ensue from an increase in availability of credit to the private sector are often left unexamined and also often do not turn out to be correct. - 15 - 26. In this case, the aid does not serve to support the fiscal expansion. This point is central and deserves elaboration. A transfer of real resources to the recipients country occurs only if aid finances additional net imports. Aid also serves as a way for the government to finance its domestic expenditures, as an alternative to domestic tax revenue or borrowing, either from the public or from the central bank. It may seem, therefore, that the financing of domestic expenditures, such as the hiring of nurses, is an alternative use for aid, in addition to imports. But this approach to the function of aid is misleading; after all, the government could always simply borrow from the central bank (i.e., print money) to finance increased domestic expenditures. Rather, the purpose of the aid is to provide the foreign exchange required to satisfy the increased demand for foreign currency resulting from the higher import demand. 23 27. Consider a thought experiment in which, for a given level of aid, the government first decides on the appropriate level of government expenditure and its financing. This set of decisions, in principle, takes into account the scope for seigniorage, the supply response to increased fiscal expenditures, the productivity of the resulting public investment and the generation of higher exports that may result, and other such factors. Then, aid increases. The thing that has changed is not that the government could now productively hire, say, more nurses to fight HIV/AIDS. They could have done that before. The difference is that, whereas before such additional expenditures would have caused too much inflation or an un- financable deterioration of the current account through second-round increases in import demand, now the incremental aid increases international reserves, which could be sold to pay for the higher imports. But this is the definition of aid absorption; aid that is not absorbed cannot fulfill this function. 28. There are several monetary policy responses to a situation in which aid is being spent by the government but not absorbed in the economy. Absent foreign exchange sales to mop up the additional liquidity, the monetary policy options are the same as in the case of any domestically-financed fiscal expansion. One could be to allow the larger fiscal deficits to lead to money supply increases. This is essentially monetizing the fiscal expansion and would tend to be inflationary. In the absence of a willingness to sell foreign exchange, the nominal exchange rate will tend to depreciate as well, with a larger supply of domestic currency pushing up the price of foreign exchange. The resulting inflation tax helps contain 23 Related to this point is an accounting issue: “domestic financing” as usually defined in the budgetary accounts is misleading as an indicator of aid usage. It may be useful to consider the following example. Suppose aid is saved entirely in the form of gross international reserves, the government builds up deposits at the central bank, and the fiscal deficit excluding aid remains unchanged. By construction, the fiscal accounts will show a shift in financing from domestic financing (which will fall due a reduction in net central bank credit to the government) to external financing. But the aid has no macroeconomic effects in this no-absorption-and-no-spending—the money supply, fiscal stance, interest rates and so on are unaffected (except insofar as interest earnings of the central bank are higher). More generally, aid that is not absorbed does not contribute to financing of the government deficit in an economic sense. Thus, it would be misleading to conclude from a perusal of below- the-line financing items in the budget that aid inflows were actually financing the deficit to a greater extent than before. - 16 - absorption by transferring resources from the private sector. Another response is to sterilize the fiscally-driven monetary expansion through the issuance of treasury bills. This strategy would tend to crowd out private investment. In effect, there is a switch from private investment to government consumption or investment. 24 29. There are opposing effects on the real exchange rate in the spend-but-do-not-absorb case. In a given situation the net effect will depend on specific factors, including the strength of contrasting policy choices and other influences, such as the terms of trade. The fiscal expansion tends to raise demand for non-traded goods, causing an appreciation; on the other hand, it increases import demand and lowers export supply, pushing the exchange rate towards depreciation. The net effect depends, inter alia, on the price and income elasticity of the country’s export supply and import demand. In addition, the central bank’s resistance to absorption creates pressures for real depreciation. In a float, aid-related liquidity injections will tend to depreciate the nominal and, in the short run, the real exchange rate. Over time, higher inflation and the associated inflation tax will reduce private demand and lower the real exchange rate and absorption. Alternatively, sterilization through the sale of treasury bills will also depress private demand and hence the real exchange rate and absorption. In a peg, only the sterilization channel operates. 30. Which of these combinations is best in the face of extra aid depends on many factors, including the level of official reserves, the existing debt burden, the current level of inflation, and the degree of aid volatility. For specific situations, some responses are more promising than others. 25 • To absorb and spend the aid would appear to be the most appropriate response under “normal” circumstances. In this case there is a real resource transfer through an aid- financed increase in net imports, and a corresponding increase in public expenditures. • To absorb but not spend the aid might be an appropriate response if inflation is too high (possibly owing to a very expansionary fiscal policy), resources are scarce for private investment, or the rate of return on public expenditure is relatively low. Sustained non-spending of aid may be infeasible, however, given donor objectives, unless the budget is very fungible. 24 Private investment and government expenditure could have different import intensities, which would modify the details of the argument but not alter the main point. Similarly, the fiscal expansion may increase aggregate output, so it is not the case that there need be a one-for-one tradeoff between government spending and private investment. But such an aggregate output expansion could have been engineered without the aid. 25 In general, debt sustainability is an important consideration for low-income countries. However, once the decision has been taken to borrow internationally, all of the combinations of absorption and spending described in this paper imply a similar rise in public external debt and in future debt service. Of course, any response that restricts absorption and channels the dollars into international reserves thereby makes resources available for future debt service. But this is equivalent to borrowing money in order to service debt, and cannot be regarded as an appropriate medium-term use of aid on these grounds. - 17 - • To neither absorb nor spend may be an appropriate short-run strategy where aid inflows are volatile or international reserves are precariously low. 26 Accumulating international reserves while avoiding an injection of domestic liquidity through fiscal expansion could help smooth the path of the real exchange rate if aid inflows are temporarily high but expected to fall. However, it is not an appropriate response to a permanent increase in the level of aid, unless it is felt that Dutch disease concerns fully outweigh the benefits from the absorption of aid inflows (Appendix II). • To spend and not absorb would appear to be the least attractive option. The use of aid to build reserves while financing the increased deficit domestically is generally unwise. Inflation can only finance a small amount of expenditure; attempts to go further tend raise little finance while damaging the economy. 27 The use of domestic sterilization is also unlikely to be a sensible medium-run strategy—it tends to shift resources from the private to the public sector and does not allow the country to benefit from a real transfer of resources financed by aid. III. F INDINGS FROM C OUNTRY C ASES A. The Pattern of Aid Inflows Overall net aid inflows 31. Table 1 below shows the pattern of aid inflows for all the countries in the sample. Gross aid inflows are the sum of grants and loans, including both program and project financing. Net aid inflows are gross inflows plus debt relief, net of amortization, interest payments on public debt and arrears clearance. 28 This is the headline measure of aid inflows, since it best captures the actual inflows of foreign exchange and hence the scale of the macroeconomic challenge. All the countries in the sample received debt relief over the period, which, in turn, permitted the clearance of external arrears in some cases and increase net aid inflows. Private inflows (e.g., foreign direct investment) can also be important, and need to be considered in conjunction with public inflows. 29 If, for example, a surge in aid 26 Recent cross-country evidence (e.g., Bulíř and Hamann, 2005) indicates that aid continue to be volatile, that aid commitments consistently exceed disbursements, and that aid disbursements are generally pro-cyclical— thereby increasing volatility of public expenditures rather than lowering it. Pratti and Tressel (2005) construct a theoretical model to consider the optimal pattern of absorption. Implicitly, they compare absorbing and spending to neither absorbing nor spending, in the terminology used here. 27 This point is elaborated in the accompanying background paper, “Monetary and Fiscal Policy Design Issues in Low-Income Countries.” 28 Net aid inflows = gross aid inflows + debt relief (including relief under the HIPC Initiative) – debt service + arrears accumulation; with a clearance of arrears taking a negative sign. This paper utilizes aid data from the country staff reports. 29 Net private inflows = private transfers (e.g., remittances) + private sector loans – private debt service. - 18 - were compensated by a corresponding fall in private inflows, this would alter the challenge of macro-management considerably. 1998 1999 2000 2001 2002 2003 Ethiopia 1/ Net Aid Inflows 4.7 6.0 8.8 16.1 15.0 Gross Aid Inflows 11.7 8.8 24.3 18.1 17.5 Net Private Inflows 6.6 8.1 6.8 5.7 7.7 Ghana Net Aid Inflows 3.2 2.8 -0.3 10.6 2.6 7.1 Gross Aid Inflows 8.7 7.5 8.8 14.9 6.1 9.5 o/w Program Aid 1.8 1.9 3.8 5.6 2.6 5.1 Net Private Inflows 6.0 6.3 11.2 13.0 12.0 13.7 Mozambique Net Aid Inflows 11.6 11.4 20.4 15.4 16.4 15.0 Gross Aid Inflows 13.4 13.4 20.0 16.7 18.5 17.4 o/w Program Aid 6.3 6.3 5.3 7.0 7.9 6.6 Net Private Inflows 5.9 15.8 10.7 6.3 15.1 7.7 Tanzania 1/ Net Aid Inflows 4.6 6.6 7.5 7.9 6.6 7.6 Gross Aid Inflows 13.3 12.7 12.8 12.5 10.5 10.5 o/w Program Aid 2.0 1.8 2.3 2.7 3.8 5.1 Net Private Inflows 2.1 2.0 2.2 4.2 3.0 2.6 Uganda 1/ 2/ Net Aid Inflows 8.4 9.4 14.2 13.7 12.9 Gross Aid Inflows 9.8 10.3 13.9 13.8 12.9 o/w Program Aid 3.0 3.5 6.8 8.3 8.2 Net Private Inflows 3.0 3.2 2.8 3.2 3.3 Note: Figures in bold represent periods of aid surges. 1/ In Ethiopia, Tanzania, and Uganda the fiscal year begins in July. Hence, e.g., 1999 = July 1998 – June 1999. 2/ Compiling a consistent series for aid inflows in Uganda is complicated by extensive recent revisions to data. From fiscal year 2000/01 the data in the table includes about US$80 million per annum of off-budget aid, which is not accounted for in previous years. Excluding this amount would somewhat reduce the size of the aid surge, without changing the analysis in any significant way. (In percent of GDP) Table 1. Patterns of Aid Inflows 32. All countries experienced a surge in net aid during the study period, ranging from an average of two percent of GDP in Tanzania to an average of 8 percent of GDP in Ethiopia. The level of net aid was also high in all countries, ranging from 7 to 20 percent of GDP. In Ghana, there were two different episodes of surging aid inflows, with a sharp increase in - 19 - 2001 followed by a slump the next year, followed by another surge in 2003. In all other countries, the surge in aid was persistent, in that after the initial jump, aid inflows remained substantially higher than in the pre-surge period. 33. In all countries, a surge in gross aid flows accompanied the surge in net aid inflows. In Uganda, the increase in aid was almost entirely due to a surge in program assistance. In Mozambique, the proportion of program and project aid remained roughly stable, while in Ghana the proportion fluctuated from year to year. 34. There is no case where a significant change in private inflows counteracts the pattern of aid inflows. In Ghana, while net private inflows were large relative to aid, changes in these inflows over the aid surge period were relatively small. In all other countries, private inflows were generally smaller than aid. In Ethiopia, private inflows remained fairly stable while aid inflows surged. In Mozambique, the large jump in private inflows was due to import- financing investment on an aluminum smelting plant. In Uganda, although private inflows increased substantially, they followed the pattern of aid inflows. Net budgetary aid 35. Net budgetary aid is the sum of budget grants and loans (including debt relief), net of public debt service and arrears clearance. Net budgetary aid usually differs from net aid inflows to the economy; for example, because some aid is channeled directly to the private sector and spent on projects outside the government budget. In this sample, however, the two aid measures behave similarly. On average, net budget aid has increased in recent years in all five countries (Figure 1). While the aid surge was gradual and steady in Tanzania and Uganda, it was more volatile in the other three cases. 36. The composition of budgetary aid changed substantially in recent years. There was a clear shift from project aid to program assistance (Figure 2a). Since the inception of the PRSP approach in 1999, donors have been increasingly willing to channel their assistance to the recipient country’s general budget. This eases administrative and institutional constraints in recipient economies, and gives recipient countries more flexibility in spending the aid. 30 30 For example, in 2001, over 1200 donor-funded projects were being implemented in Tanzania; managing and coordinating such a large number of projects was a challenge for the authorities. - 20 - 37. However, there is no obvious shift from loans to grants except in Ghana (Figure 2b). This distinction is potentially important because loans add to debt service costs in the future and therefore have implications for debt sustainability, while grants do not. On the other hand, there is some evidence that grants may have an adverse impact on the government’s revenue collection, while loans may have a positive impact. 31 31 Gupta, Clements, Pivovarsky and Tiongson, 2003. Figure 1. Total Net Budget Aid (as percent GDP) -2 2 6 10 14 18 22 t=-3 t=-2 t=-1 t=0 t=1 t=2 t=3 aid inflows surge Ghana Ethiopia Mozambique Tanzania Uganda - 21 - B. Macroeconomic Context 38. Growth was generally robust in all countries both before and during the aid-surge period, although exogenous shocks set growth back in some years (Table 2). Devastating floods reduced Mozambique’s growth rate in 2000, a drought reduced Tanzania’s growth rate in 1999, and severe drought caused a two-year contraction in Ethiopia. Three of the sample countries—Ethiopia, Tanzania and Uganda—kept a tight curb on inflation, both before and during the aid surge period. In Mozambique, however, the aid surge coincided with a sharp increase in inflation. Ghana’s inflation was high and volatile before and during the aid-surge period. The private investment-to-GDP ratio was mostly stable in the sample. In Ethiopia and Tanzania, the average private investment during the surge period declined slightly relative to the pre-surge average. In Uganda, it increased in the surge period. In most countries, the average public investment-to-GDP ratio was higher during the aid-surge period. Figure 2. Changes in Composition of Budgetary Aid (as a percent of total gross aid) Source: IMF Staff Reports Figure 2a. Shift Towards Program Aid 0.0 0.1 0.2 0.3 0.4 0.5 0.6 G hana Mozambiqu e T anzania Ug an d a Pre-Aid Surge Average Aid Surge Average Figure 2b. No Obvious Shift Towards Grants 0.0 0.1 0.2 0.3 0.4 0.5 0.6 0.7 0.8 Et hiopi a Ghana Mo zambi que Tanzania U ganda Pre-Aid Surge Average Aid Surge Average - 22 - Pre-Aid Surge Avg.Aid Surge Avg. Difference Ethiopia 1999-2000 2001-2003 GDP growth 5.7 1.8 -3.9 Inflation 4.7 2.6 -2.1 Non-food inflation 1.0 2.2 1.2 Investment / GDP 16.4 19.6 3.2 Private 9.8 9.4 -0.4 Public 6.6 10.1 3.5 Ghana 1999-2000 2001-2003 GDP growth 4.1 4.6 0.6 Inflation 85.2 20.5 -64.6 Investment / GDP 23.6 23.2 -0.4 Private 14.1 13.8 -0.3 Public 9.5 9.4 -0.1 Mozambique 1/ 1989-1999 2000-2002 GDP growth 9.7 7.3 -2.4 Inflation 1.8 12.8 11.1 Investment / GDP 30.5 40.9 10.5 Tanzania 1989-1999 2000-2004 GDP growth 2.8 5.4 2.6 Inflation 9.9 4.9 -4.9 Investment / GDP 15.5 17.8 2.2 Private 12.4 11.5 -0.8 Public 3.2 6.2 3.1 Uganda 1999-2000 2001-2003 GDP growth 6.6 5.6 -1.0 Inflation 3.0 2.7 -0.3 Investment / GDP 19.6 21.0 1.4 Private 11.2 13.9 2.8 Public 8.5 7.1 -1.3 1/ Mozambique lacks reliable data on private investment. Table 2. GDP Growth, Inflation and Private Investment (All figures in percent) - 23 - C. Real Exchange Rate and Dutch Disease 39. Domestic expenditures financed by aid inflows may potentially lead to real exchange rate appreciation and squeeze export industries. 32 Table 3 summarizes movements in the nominal effective exchange rate and the real effective exchange rate. 40. It is immediately apparent that a Dutch disease effect on exports via real appreciation is absent in all five countries. During the years in which aid inflows surged, there is typically a depreciation of the real effective exchange rate, ranging from 1.5 percent (Mozambique, 2000) to 6.5 percent (Uganda, 2001). 33 Ghana observed a small real appreciation in both episodes of surging aid inflows (Figure 3). 41. A real depreciation in the face of surging aid inflows may indicate (i) structural features of the economy such as a rapid supply response to aid expenditures or high import propensities, though this would tend to mitigate the appreciation rather than cause a depreciation; (ii) a fiscal and monetary policy stance that leans against real appreciation; or (iii) other exogenous events, notably a negative terms of trade shock. Subsequent sections consider the first two explanations. With respect to the latter, two countries in the sample, Ethiopia and Uganda, were hit by significant negative terms of trade shocks during the aid- surge period. However, as shown in Box 2, even in these cases the incremental aid flows were much larger than the scale of the terms of trade shocks. 42. Consistent with real depreciation, export performance was strong in most of the sample, especially Mozambique and Tanzania. In Ghana too, export performance was strong despite a stable real exchange rate. In both countries that were affected by the decline in coffee prices, real depreciation helped export performance. In particular, non-traditional exports grew strongly, and increased as a proportion of total exports, enabling robust export growth in Ethiopia and moderating the decline in exports in Uganda. 32 See Appendix II for a discussion of the theoretical and empirical literature on Dutch disease. 33 These real effective exchange rate (REER) indices are based on nominal exchange rates and CPI inflation in the target country and its trade partners. Lack of data prevents supplementing these indices with the REER measured by unit labor costs, or the REER measured as the price ratio between non-tradeables and tradeables. - 24 - Pre-Aid Surge Avg. Aid Surge Avg. Difference Ethiopia 1999-2000 2001-2003 REER (- = depreciation) -2.0 -2.1 -0.1 NEER (- = depreciation) -5.0 -1.5 3.5 RER (bilateral with dollar) -5.7 -1.9 3.8 Terms of Trade -18.3 -4.1 14.2 Exports -9.6 -0.1 9.5 Non Traditional Exports/Exports (percent ratio) 44.0 63.5 19.5 Ghana 1999-2000 2001-2003 REER -17.5 0.5 18.0 NEER -27.8 -17.8 10.0 RER (bilateral with dollar) -12.0 -6.6 5.4 Terms of Trade -12.7 9.7 22.3 Exports -3.8 8.9 12.7 Non Traditional Exports/Exports (percent) 30.2 33.0 2.8 Mozambique 1989-1999 2000-2002 REER 0.0 -6.4 -6.4 NEER 1.6 -14.1 -15.7 RER (bilateral with dollar) -5.0 -11.1 -6.1 Terms of Trade -8.8 1.2 10.0 Exports 11.2 39.5 28.3 Tanzania 1998-1999 2000-2004 REER -2.3 -9.8 -7.5 NEER 6.3 -8.7 -15.1 RER (bilateral with dollar) 3.5 -6.1 -9.6 Terms of Trade 3.3 -4.1 -7.3 Exports -17.3 16.1 33.4 Non Traditional Exports/Exports (percent) 41.3 74.7 33.4 Uganda 1999-2000 2001-2003 REER -6.6 -6.3 0.3 NEER -8.6 -5.8 2.8 RER (bilateral with dollar) -12.0 -6.6 5.4 Terms of Trade -14.0 -3.6 10.4 Exports 1.1 4.0 2.9 Non Traditional Exports/Exports (percent) 51.4 78.9 27.5 1/ Despite the commonly observed pattern of real depreciation observed in these countries, this often reflects active policy choices to avoid an appreciation and the effects of Dutch disease. The table does not necessarily indicate the Dutch disease is not a concern to these countries, a priori. (Percent change over previous year, unless otherwise specified) Table 3. The Real Effective Exchange Rate 1/ - 25 - Figure 3. Exchange Rates and Aid Inflows Source: Source: EDSS, Exchange Rate Facility and country authorities N ote: All indicies are 100 at t=0 Real Effective Exchange Rate 60 80 100 120 140 t= -1 t= 0 t= 1 t= 2 t= 3 aid inflows surge Ethiopia Mozambique Ghana Tanzania Uganda reference line=100 Real Exchange Rate (bilateral with USD) 60 80 100 120 140 160 t=-1 t=0 t=1 t=2 t=3 Aid inflows surge Ethiopia Ghana Mozambique Tanzania Uganda reference line=100 - 26 - Box 2. Terms of Trade Shocks and Aid Inflows It is possible to disentangle the terms of trade effect from the aid inflows effect for the two countries in the sample that were affected by a significant terms-of-trade shock during the aid-surge period: Ethiopia and Uganda. In both Ethiopia and Uganda, the main export commodity is coffee. A sharp and prolonged decline in world coffee prices caused a deterioration in the terms of trade for both countries, and in each case this deterioration coincided with surging aid inflows. 1999 2000 2001 2002 2003 Ethiopia 1. ToT Effect on Net Exports 1/-54 -484 -13 -36 -59 2. Change in Aid Inflows -15 24 235 417 21 3. Net Effect (1 + 2) -69 -460 222 381 -38 NEER (percent change) -8.4 -1.6 5.9 -1.6 -9.0 REER (percent change) -5.1 1.1 -3.5 -4.9 2.2 Uganda 1. ToT Effect on Net Exports 1/-53 -106 -52 11 60.1 2. Change in Aid Inflows -82 54 246 -2 10 3. Net Effect (1 + 2) -135 -52 194 9 70 NEER (percent change) -14.0 -3.2 -6.9 2.3 -12.7 REER (percent change) -13.0 -0.2 -6.5 -1.7 -10.6 (In millions of US dollars, unless otherwise specified) Terms of Trade Shocks 1/ Calculated as the difference between actual net exports and net exports keeping unit export and import prices unchanged. Note: Figures in bold represent periods of aid surges. The table contains estimates of the loss in dollar inflows through net exports resulting from the terms- of-trade shock, and compares it with the increase in dollar inflows due to the surge in aid. In this calculation, year t quantities of exports and imports are fixed at the level of year t-1. This yields a counterfactual series for exports and imports; the difference between this series and the actual data on exports and imports is taken as the terms-of-trade effect. In both cases, in the first year the incremental aid inflow dominated the negative effect from the terms-of-trade shock. This is also true of the average over the aid-surge period. Nonetheless, in both cases there was a nominal and real depreciation. - 27 - D. Was Incremental Aid Absorbed? 43. Increased aid inflows must contribute to a deterioration of the non-aid current account if a real resource transfer is to occur. Hence this paper measures absorption as the ratio of the non-aid current account deterioration to the increment in aid. 44. Following the framework in Section II, Table 4 decomposes the increment in aid in each country into the change in the non-aid current account, the change in the rate of reserve accumulation, and the change in the non-aid capital account. The increase in net imports (and hence the change in the current account) measures the extent of absorption, while the rate of reserve accumulation measures the extent to which the monetary authorities curb absorption. 45. In three countries, the aid led to some deterioration of the non-aid current account. However, this deterioration was typically modest in comparison to the incremental aid inflow. Only in Mozambique was over half the incremental aid inflow used to finance net imports. In Tanzania and Ghana, the non-aid current account actually improved by 2 and 10 percentage points of GDP, respectively, implying that the incremental aid was not absorbed. In all countries, the surge increased the rate of reserve accumulation. This pattern is consistent with the failure of the real exchange rate to appreciate in line with the surge in aid inflows, as detailed in the previous subsection. 46. Finally,. Some short-run movements in the non- aid capital account could reflect lags between foreign exchange being made available for absorption and the actual increase in imports that comprises absorption. 34 However, this would not seem to be an adequate explanation for the more sustained changes observed in the sample. 35 47. Were the reductions in capital inflows a result of the aid surge itself? If so, the aid inflows did not serve their intended purpose of promoting absorption. In general, the non-aid capital account might be expected to evolve exogenously; there is no compelling theoretical reason for net capital inflows to respond positively or negatively to a change in aid. However, capital outflows may be triggered by an aid surge in certain circumstances—in particular, when the authorities attempt to absorb but not spend, channeling aid to the private 34 For example, consider a case in which government expenditures raise wages for a set of workers. This increases their demand for imports. However, when they purchase dollars from the central bank, they do not immediately spend them on imports, but in the first instance, deposit them in dollar accounts held with domestic commercial banks. This would count as a deterioration in the non-aid capital account (due to an increase in commercial banks’ net foreign assets). Subsequently, when they spent the dollars on imports, there would be a corresponding improvement in the non-aid capital account. 35 In some countries, large errors and omissions in the balance of payments accounts could be partly responsible for measured fluctuations in the capital account. - 28 - sector through the financial system by reducing the stock of domestic bonds outstanding. If, perhaps because of poor investment opportunities at home, private investors preferred to invest abroad, a deterioration of the capital account could result. As the discussion in the next section reveals, none of the countries pursued a policy of channeling aid to the private sector through the financial system. It would thus appear unlikely that such a policy resulted in the reduction in capital inflows observed during the aid-surge period. Incremental Pre-Aid Surge Avg.Aid Surge Avg.Difference Aid Absorbed? 1/ Ethiopia 1999-2000 2001-2003 Net Aid Inflows 5.3 13.3 8.0 Non-Aid CA Balance -9.2 -10.8 -1.6 Partly Absorbed Non-Aid KA Balance 2.0 1.3 -0.7 20% Change in Reserves (- = increase) 1.9 -3.8 -5.7 Ghana 1999-2000 2001-2003 Net Aid Inflows 1.3 6.8 5.5 Non-Aid CA Balance -13.4 -3.4 10.0 Not Absorbed Non-Aid KA Balance 9.9 2.1 -7.8 0% Change in Reserves (- = increase) 2.2 -5.4 -7.6 Mozambique 1989-1999 2000-2002 Net Aid Inflows 11.5 17.4 5.9 Non-Aid CA Balance -19.7 -23.6 -3.9 Mostly Absorbed Non-Aid KA Balance 8.7 8.3 -0.4 66% Change in Reserves (- = increase) -0.5 -2.1 -1.7 Tanzania 1998-1999 2000-2004 Net Aid Inflows 5.6 7.8 2.2 Non-Aid CA Balance -9.2 -6.8 2.3 Not Absorbed Non-Aid KA Balance 4.1 1.7 -2.4 0% Change in Reserves (- = increase) -0.6 -2.7 -2.2 Uganda 1999-2000 2001-2003 Net Aid Inflows 8.9 13.6 4.7 Non-Aid CA Balance -10.1 -11.4 -1.3 Partly Absorbed Non-Aid KA Balance 1.6 -1.1 -2.8 27% Change in Reserves (- = increase) -0.4 -1.1 -0.7 Source: IMF Staff Reports. Note: Errors and Omissions have been included in the capital account. 1/ Non-Aid Current Account deterioration as percent of incremental aid inflow is truncated at 0 and 100. (Annual averages in percent of GDP) Table 4. Balance of Payments Identity - 29 - 48. Aid inflows could also cause a capital outflow if they led the authorities to pursue an excessively loose monetary policy. Aid-related fiscal spending tends to increase the money supply. If the authorities allow this to lead to excessively low interest rates and excess liquidity in the banking system, capital outflows could result. As discussed in the next sections, aid inflows to Tanzania were associated with periods of relatively loose monetary policy, and this may have contributed to the slowdown in capital inflows. Direct evidence is scarce, however. 49. In Ghana, the reduction in capital inflows seems to have been associated not with the aid surge but with macroeconomic disarray. Following a negative terms of trade shock and with reserves almost depleted, non-aid capital inflows fell sharply in 2000 and again in 2001. In 2000, the exchange rate weakened sharply and inflation shot up. With an aid surge in 2001, the authorities were able to avoid devaluing the exchange rate. In this case, the aid inflows likely kept absorption higher than it would have been. E. Was Incremental Aid Spent? 50. Incremental budgetary aid is spent, by definition, to the extent that it leads to an increased fiscal deficit net of aid. The government can spend aid directly by increasing public expenditures, or indirectly by lowering taxes (because aid is then transferred to the private sector). This section examines whether the increase in aid was spent and explores the implications of aid volatility for spending patterns. The evidence on spending incremental aid is summarized in Table 5. 51. Three countries (Mozambique, Tanzania and Uganda) spent most of the additional foreign assistance. In Mozambique, public expenditures actually increased more, on average, than the increment in net aid inflows, leading to a substantial widening of the fiscal deficit net of aid. A variety of factors helped these countries spend the incremental budgetary aid. Because these countries had attained macroeconomic stability in the mid-to-late 1990s before the aid surge, reducing domestic financing of the budget deficit was not a major goal. Similarly, retiring domestic public debt was also not a key objective as these countries had rather low domestic financing of the deficit as well as domestic debt and debt service prior to the aid surge (Table 6). They had strengthened their expenditure management systems, partly because of the HIPC Initiative, which helped them spend most of the incremental aid that they received as program assistance. 36 To the extent that these countries spent the aid increments, the additional spending was concentrated on capital and poverty-reducing expenditures. 36 Mozambique, Tanzania and Uganda reached their decision point under the HIPC Initiative before mid-2000. Improving expenditures management and tracking was part of the fiscal conditionality in all three countries. - 30 - Pre-Aid Surge Average 1/ Aid Surge Average 1/ Difference Incremental Aid Spent or Not? 2/ Ghana Net fiscal aid inflows 1.3 7.3 6.0 Revenue (excluding grants) 17.1 19.0 1.9 Expenditure (excl. external interest) 27.0 29.3 2.3 Not spent Overall fiscal balance before aid -9.9 -10.3 -0.4 7% Ethiopia Net fiscal aid inflows 5.3 11.2 5.9 Revenue (excluding grants) 18.0 19.4 1.5 Expenditure (excl. external interest) 31.8 32.5 0.7 Not spent Overall fiscal balance before aid -13.8 -13.0 0.8 0% Mozambique Net fiscal aid inflows 12.9 17.9 5.0 Revenue (excluding grants) 12.6 13.9 1.3 Expenditure (excl. external interest) 26.0 32.7 6.7 Spent Overall fiscal balance before aid -13.0 -18.5 -5.5 100% Tanzania Net fiscal aid inflows 4.7 8.6 3.9 Revenue (excluding grants) 12.1 12.5 0.4 Expenditure (excl. external interest) 16.7 20.7 4.0 Spent Overall fiscal balance before aid -4.8 -8.3 -3.5 91% Uganda Net fiscal aid inflows 9.3 12.5 3.2 Revenue (excluding grants) 12.6 12.8 0.1 Expenditure (excl. external interest) 22.2 24.7 2.5 Mostly spent Overall fiscal balance before aid -9.6 -12.0 -2.4 74% 2/ Non-aid fiscal balance deterioration as a percent of incremental aid inflow is trucated at 0 and 100. (In percent of GDP) Table 5. Allocation of Incremental Net Budgetary Aid: Spent or Saved 1/ For all countries except Tanzania, 1999-2000 is the before aid-surge period and 2001-03 is the aid-surge period for Tanzania, 1998-1999 is the before aid-surge period, and 2000-04 is the aid-surge period. - 31 - 52. The governments in Ghana and Ethiopia, however, spent very little of the incremental aid. These countries had a relatively weaker record of macroeconomic stability, and a low level of international reserves before the aid surge, which limited their ability to spend additional aid. As these countries had relatively high domestic debt and domestic financing of the budget prior to the aid surge, reducing domestic public debt (and hence domestic debt service) was also a consideration for not spending the additional aid. Ghana also experienced highly volatile aid inflows; net budgetary aid increased by 10 percentage points of GDP in 2001, then dropped by 8 percentage points of GDP in 2002 before recovering in 2003. This volatility appears to have been a major factor in saving incremental aid in 2003. In Ethiopia, limited administrative capacity and weak institutions following the conflict with Eritrea may also have been additional factors. Pre-Aid Surge Avg. Aid Surge Avg.Difference Ethiopia 1999-2000 2001-2003 Domestic debt 1/37.8 39.1 1.3 Interest payments 2/7.4 5.6 -1.8 Nominal interest rates on T-bills 3/3.4 1.6 -1.8 Real interest rates in T-bills 3/-0.8 -2.1 -1.3 Ghana 1999-2000 2001-2003 Domestic debt 23.0 23.1 0.2 Interest payments 28.0 27.5 -0.5 Nominal interest rates on T-bills 38.1 26.5 -11.6 Real interest rates in T-bills 19.3 1.7 -17.6 Mozambique 4/ 1989-1999 2000-2002 Domestic debt 0.3 2.6 2.2 Interest payments 0.2 3.8 3.6 Nominal interest rates on T-bills 11.8 24.0 12.2 Real interest rates in T-bills 9.0 11.1 2.2 Tanzania 1989-1999 2000-2003 Domestic debt 10.1 9.5 -0.6 Interest payments 6.9 7.4 0.6 Nominal interest rates on T-bills 11.6 8.0 -3.6 Real interest rates in T-bills 1.3 3.0 1.7 Uganda 1999-2000 2001-2003 Domestic debt 3.4 8.1 4.7 Interest payments 2.6 6.9 4.3 Nominal interest rates on T-bills 8.2 10.3 2.2 Real interest rates in T-bills 3.6 7.2 3.6 Log in to post a comment
https://www.techylib.com/en/view/rustycortege/the_macroeconomics_of_managing_increased_aid_inflows_experiences
CC-MAIN-2018-09
refinedweb
10,978
54.83
This article contains the following executables: GARBAGE.ARC Giuliano and Susan, the authors of Alloc-gc, run the Codewright's Toolworks, where they can be contacted at 310-514-3151. Garbage collection liberates you from needing to explicitly free memory. This leads to faster development cycles, cleaner code, and (hopefully) fewer bugs. Garbage collection has been used for years by languages that depend on interpreters (Lisp and Smalltalk), specialized hardware (the Lisp machine), or a carefully controlled runtime environment (Algol-68). However, "conservative" collection techniques make it possible for you to use garbage collection even when the environment does not provide support. Programs that allocate blocks of memory must return unused blocks so that they may be used again. Most often, they do so by explicitly deallocating blocks with calls to a deallocation routine. An alternative is implicit deallocation using a garbage collector. In this case, a block is implicitly available to be returned whenever there are no references to it. From time to time, a garbage collector scans memory, looking for unreferenced blocks and returning them. The primary impediment to using garbage collection is that most garbage collectors require help from the programming language, operating system, and/or runtime system. Many environments don't (or can't) provide such help. Conservative garbage collectors, however, require no help. The allocator of an existing program may be replaced with a conservative collector, usually with no other changes required. Another reason for the infrequent use of garbage collectors is the mistaken belief that they are too slow. While once true, this is no longer the case. The very best garbage collectors use about 3 to 5 percent of the CPU. Conservative collectors use more of the CPU, but are still reasonably efficient. The design and code of explicitly deallocating programs are convoluted by the need to deallocate blocks both under normal conditions and when erroneous or unusual conditions happen. The design of a garbage-collected program is simple, and the code is clear. The result is an easier-to-understand program which takes less time to design, code, and debug. The program is more likely to be correct, since fewer errors will have been made, debugging them will have been easier, and formal proofs (if used) are easier to construct. Lastly, maintenance will be easier. The basic elements of this garbage-collecting replacement for C's malloc() will run on 80x86s under DOS. The code, which has been compiled with Microsoft C 5.1, works only with small model programs. However, we do discuss how to extend it to work with large-model programs. Theory An allocator satisfies dynamic requests for memory by returning the address of a block of memory, which can be used by the client to store data. A deallocator returns a block of memory to the allocator, which may reuse the memory to satisfy a later request. A garbage collector determines which previously allocated memory blocks are still in use and returns the rest to the allocator. There are two principal methods of garbage collection: Mark and Sweep, and Stop and Copy. Both begin collecting by starting at locations known to contain references to allocated blocks. These locations are called "roots," and usually include the stack and hardware registers. Mark and Sweep examines the roots. When it finds a reference to an allocated block, it marks the block as referenced. If the block was unmarked, the block is recursively examined for references. When all referenced blocks have been marked, a linear scan of all allocated memory is made, sweeping unreferenced blocks into the allocator's free list(s). Stop and Copy compacts memory by copying referenced blocks to lower memory locations that were occupied by unreferenced blocks. It then updates references to point to the new locations for the allocated blocks. Nonconservative garbage collectors receive help in recognizing a value in memory as a reference to a block. Often this is done by tagging values. Some subset of the bits in a value indicates the type of the value. For example, the low-order two bits might be used for the tag, with the value 00 representing a memory reference, 01 an integer, and 02 a float. A conservative garbage collector requires no such help. Rather, it slithers through memory looking at values, operating on the "conservative" assumption that if a value, when interpreted as an address, refers to an allocated block, then the block must be treated as referenced and not be collected. Occasionally, random values may be incorrectly interpreted as a block reference. In these cases, an unreferenced block is not collected. An example may be helpful. On the PC, a C integer is two bytes, and a long address is two bytes of segment plus two bytes of offset. Suppose two successive integers in memory contain the following as their values: an integer which happens to be a valid segment, and an integer which happens to be the offset within the segment of an allocated block. When the garbage collector examines memory, the two integers appear to be a reference to the block, and so the block is treated as referenced. Such cases of mistaken identity are rare, and their effects usually innocuous: A limited amount of memory is not reclaimed. Sometimes the effects are more severe, but generally there are workarounds. Usually, however, as the misidentified value changes, subsequent collections will pick up the previously uncollected block. Because random values are being examined, the conservative collector must be careful. It has the following constraints: - The garbage collector must not change a value. It may not actually be a pointer, but instead a value of some other type. This constraint eliminates Stop and Copy as the basis of conservative garbage collection. - Before treating the value as a pointer, the garbage collector must validate the value. On 80x86s this means verifying that the segment of a far pointer is valid, and that the offset corresponds to a previously allocated block. If the segment check isn't done, we might generate an address error in a protected-mode program. - Until the value is validated, the garbage collector may only change its own data, and not, for example, the data at the value interpreted as an address. Example 1: A pointer to the front of the block must be maintained. for ( p = malloc(Nbr0fBytes); p < p + Nbr0fItems; p++ ) { process ( p ); } Design In designing the garbage-collection library presented here, we've followed an object-oriented design philosophy. The two principal classes are the allocation segment and garbage collector. The segment class knows about how to manage memory blocks in an 80x86 segment. Since the code runs only under small model, there is only a single-segment object. This segment class must therefore be aware that global data and the stack are also located within the segment. The garbage collector is responsible for marking all blocks reachable from the root. The garbage collector knows nothing about the internals of an allocation segment. The allocation segment provides routines to: validate that a value represents a valid block; return the length of a block; and sweep all unused blocks within it, so they can be reused. Other major parts of the library are the replacements for malloc() and its related routines. The malloc() function, see Listing Five, Page 129, asks the segment for a block. If there is no free block large enough, the segment will return null; malloc() will subsequently request the garbage collector to run, then again ask the segment for a block. If a large enough unused block now exists, the segment will return some part of it. If not, it will again return NULL, which malloc() will in turn return to its client. In the segment, memory is allocated in units of eight bytes. In addition to the memory used for blocks to return to clients, free list heads and a flag vector are stored at the end of the segment. Each element in the free list-head array points to the first free block of a particular size. The flag vector maintains two flags per unit: allocated block start and referenced. Allocated is set True for the unit which starts a block returned by the allocator. Allocated is cleared if the block starting at the unit is swept up. Referenced is set True if allocated is True, and the garbage collector asks the segment to validate a value which points to the unit. When sweeping, the segment looks for allocated blocks with clear referenced flags. Rather than free each such block in turn, the allocator merges contiguous free and unreferenced blocks, and then places the merged blocks onto their free lists. The allocation segment uses a simple buddy-system allocator. All blocks -- both allocated and free -- are a power of two in size. A separate free list is kept for each block size. At startup, the free space in the segment is broken up into blocks of the appropriate size, and these are placed onto the free lists. To allocate we find the first free block of size greater or equal to that requested. We then split off any unneeded space from the end of this block, break it up into power-of-two sized pieces, and attach these to the free lists. Code Discussion The garbage collector's header files do the following: array.h defines some useful macros for dealing with arrays; bool.h defines an enumeration to represent Booleans rather than the usual usage of macros for True and False; power2.h declares some tables used to quickly perform calculations, the result or operand of which is a power of two. The input of the function is used as the array's index. The value of that array element is the function's result. The input must be in the range 1 to 255. The file pwr2gen.c is the source of a program which generates power2.h; BumpUp computes the first power of two greater or equal to its input, and Log2 computes the ceiling of the log base 2 of its input. The source code that implements the garbage collector consists of Gc.h and Gc.c ( Listings One and Two, page 128). Calling GcPickup() runs the garbage collector. It in turn calls ASegClearMarks() to clear marks, GcMark() to set the mark of used blocks, followed by ASegSweep() to sweep up unused blocks. To start, GcMark() is called first to mark the global data and then again to mark the stack. It steps through the segment, passing each value in memory to ASegMarkValue(). If the value corresponds to a block that should be examined for pointers, ASegMarkValue() returns the size of that block. In this case, GcMark() calls itself recursively. Aseg.h ( Listing Three, page 128) and ASeg.c ( Listing Four, page 128) are the interface and implementation of allocation segments, respectively. These functions are all prefixed with ASeg. Most of them are straightforward; only ASegVegamatic() is tricky. A free block may not be just any power of two. It must be less than or equal to the greatest power of two that can evenly divide the start address. The expression Size=FreeOffset & ( -(int)FreeOffset ); sets "Size" to the maximum size of a block starting at FreeOffset. On a two's complement machine, -X=!X+ 1--the definition of two's complement. Due to this definition, X and -X have the same least significant bits up to and including the first 1 bit. More significant bits are cleared. ASegMarkValue() first validates that its argument value could be a pointer returned by the allocator. If it is, and the block pointed to has not been marked, then it marks it and returns the size of the block. Otherwise it returns 0 for the size. Supplemental test files that put the system through its paces, as well as array.h, bool.h, power2.h, and pwr2gen.c are available electronically; see page 5. Enhancements While the code is limited to running under small model with a single segment, we've designed the interfaces to support multiple segments so that compact, large, and mixed-memory model programs can be supported. The major problem is that when presented with a value, we must validate that its segment portion corresponds to a valid segment before calling ASegMarkValue(). The easiest way to do this is to maintain a bit table in Gc.c. When we get a segment from the operating system, we turn on the corresponding bit in the table. To validate a value we extract the segment portion and look it up in the table. If the bit is off, we know the value can't be a pointer and proceed. Otherwise, we pass the value on to ASegMarkValue() for further validation and processing. Logic must be added in several other places. We need to allocate and initialize segments. We need to traverse all allocated segments to clear their marks and sweep them. Lastly, malloc() becomes more complicated since it needs to have a policy for deciding when to garbage collect to try to free up some space vs. allocating another segment to create more space. We've argued that garbage collecting is usually better than explicit deallocation -- and it is. Just as you often program in a high-level language while using assembler to write critical code, you can use garbage collection in most places, but when necessary, call a deallocator. But to do this, the garbage collector must supply one. While most deallocators try to coalesce adjacent blocks, it's probably better to just add the block to its free list and let the next garbage collection handle the coalescing. No single allocation strategy is best all the time. Buddy-system allocators are fast, but they waste memory. Next fit is usually slower, but doesn't waste as much memory. Best fit is slow, but wastes very little memory. If we support multiple segments, we can have each support a different allocation scheme. Then, based on requested block size, or some other hint, malloc() can ask the segment with the best strategy for a block. It's sometimes useful for the client program to know when a block is about to be reclaimed. The garbage collector could do this by calling a client callback function when it finds an unused block. For example, if the file I/O library stored the state data for open files in dynamic memory, then I/O clients would not need to call close. If the client ever let go of all references to a file, it would eventually be garbage collected. This would trigger a call of the callback function, which could then close the file. _GARBAGE COLLECTION FOR C PROGRAMS_ by Giuliano Carlini and Susan Rendina[LISTING ONE] <a name="025f_0009"> /* Garbage Collector - Free memory blocks that aren't referenced. A garbage collector deduces which memory blocks are in use. When memory runs low, it reclaims those blocks which are no longer used. That memory can then be reused to satisfy further requests for memory. */ #ifndef GC_Defn #define GC_Defn void GcPickUp( void ); /* Reclaim blocks of unused memory from the segments being watched. */ #endif <a name="025f_000a"> <a name="025f_000b">[LISTING TWO] <a name="025f_000b"> /* GC - Garbage Collector */ #include "aseg.h" #include "array.h" #include "bool.h" #include "gc.h" #ifndef BitsPerByte #define BitsPerByte 8 #endif void GcMark( unsigned* Block, unsigned Length ) { unsigned Bit; unsigned Idx; unsigned* Last; unsigned* Next; unsigned Value; Last = (unsigned*)((char*)Block + Length ) - 1; for ( Next = Block; Next <= Last; Next = (unsigned*)((char*)Next+1) ) { Value = *Next; Length = ASegMarkValue( 0, (unsigned*)Value ); if ( Length != 0 ) { GcMark( (unsigned*)Value, Length ); } } } void GcPickUp() { extern unsigned end; AllocSeg Seg; /* Algorithm: Clear the mark bits; mark blocks reachable from roots (the stack and global data); Sweep all watched segments. */ Seg = 0; ASegClearMarks(Seg); GcMark( 0, end ); GcMark( (unsigned*)&Seg, (unsigned)&Seg - (unsigned)Seg->FirstFreeOfSize[0] ); ASegSweep(Seg); } <a name="025f_000c"> <a name="025f_000d">[LISTING THREE] <a name="025f_000d"> /* AllocSeg - Segments used for memory allocation. Allocation segments are 80x86 segments used for memory allocation. Clients may request or return pointers to blocks of memory. */ #ifndef ASeg_Defn #define ASeg_Defn #include "stdio.h" typedef struct AllocSegTg* AllocSeg; void* ASegAllocBlock( AllocSeg Seg, unsigned Size ); /* Returns block of <Length> bytes from <Seg>. Returns NULL if no block. */ void ASegDumpSeg( AllocSeg Seg, FILE* F ); /* Write a debugging dump of <Seg> to <F>. */ void ASegInitSeg( AllocSeg Seg ); /* Initialize <Seg> for use. */ /* GARBAGE COLLECTOR INTERFACE: Only a garbage collector should use this. */ void ASegClearMarks( AllocSeg Seg ); /* Clear all marks from <Seg>. */ unsigned ASegMarkValue( AllocSeg Seg, void* Value ); /* If <Value> corresponds to a block allocated from <Seg> mark it as being in use. Return the size of the block (not the actual size, but the size requested by creator). Returns 0 if Value isn't valid, or if block was already marked. */ void ASegSweep( AllocSeg Seg ); /* Sweep all unmarked blocks in <Seg> into <Seg's> free lists. */ /* INTERNALS: An Allocation Segment is an 80x86 segment. The programs global data and its stack are at the start. The middle is used for client memory requests. It's tail is used for bookkeeping. A client may request a block of any size. Internally however, all blocks lengths are a power of two between 8 bytes and 32K bytes. Block lengths are represented by their Log base 2, which is the number of 0 bits to the right of the 1 bit in the length. */ typedef unsigned UnsignedLog2; /* UnsignedLog2 - An unsigned power of 2 represented by it's Log base 2. */ #define BitsPerByte 8 #define SegSize 0x10000L /* 64K byte segments */ #define UnitSize 8 /* Allocations are in units of 8 bytes */ #define UnitMask 0xFFF8 #define UnitsPerSeg (SegSize/UnitSize) /* Nbr of Units/segment */ #define FlagsPerUnit 2 /* 2 flags for each unit */ #define UnitAlloc 1 /* Unit is the start of an alloc'd block */ #define UnitMark 2 /* Mark bit for garbage collection */ #define FlagBytesPerSeg (UnitsPerSeg * FlagsPerUnit / BitsPerByte) #define ASegOverhead FlagBytesPerSeg #define UnitsPerFlagByte ( BitsPerByte / FlagsPerUnit ) #define BFUnused (FlagBytesPerSeg / UnitSize * FlagsPerUnit / BitsPerByte) /* Flag bytes are at tail of the segment; will never be allocated. Flags that represent flag bytes are needed. Calculate how much of the tail isn't needed for flag bytes. UnitsInFlagBytes = FlagBytesPerSeg/UnitSize = 512; BFUnused = UnitsInFlagBytes * FlagsPerUnit/BitsPerByte */ typedef unsigned BlockFlags[ (ASegOverhead - BFUnused) / sizeof(int) ]; #define NbrOfBlockSizes 15 /* Number of block lengths supported. */ #define ASegPadSize ( BFUnused - NbrOfBlockSizes * sizeof(FreePtr) - 2 ) /* Number of bytes to pad segment structure to 2 bytes less than 64K. */ typedef struct FreeBlockTg* FreePtr; /* Pointer to a free block */ /* Representation of an AllocSeg */ typedef struct AllocSegTg { int Well[ (SegSize - ASegOverhead) / sizeof(int) ]; BlockFlags Flags; #define ASegFlagIdx(S, P) ( (unsigned)P / ( UnitSize * BitsPerByte * sizeof(S->Flags[0]) / FlagsPerUnit ) ) #define ASegFlagAddr(S, P) ((unsigned*)&S-> Flags[ ASegFlagIdx(S, P) ]) #define ASegFlagShift(S, P) ( ( (unsigned)P / UnitSize ) % ( UnitsPerFlagByte * sizeof(S->Flags[0]) ) * FlagsPerUnit) #define ASegFlagAllocBits 0x5555 #define ASegFlagMarkBits 0xAAAA #define ASegAllocClr(S, P) \ *ASegFlagAddr(S, P) &= ~( UnitAlloc << ASegFlagShift(S, P) ) #define ASegAllocSet(S, P) \ *ASegFlagAddr(S, P) |= ( UnitAlloc << ASegFlagShift(S, P) ) #define ASegIsAllocSet(S, P) \ ( *ASegFlagAddr(S, P) & ( UnitAlloc << ASegFlagShift(S, P) ) ) #define ASegMarkClr(S, P) \ *ASegFlagAddr(S, P) &= ~( UnitMark << ASegFlagShift(S, P) ) #define ASegMarkSet(S, P) \ *ASegFlagAddr(S, P) |= ( UnitMark << ASegFlagShift(S, P) ) #define ASegIsMarkSet(S, P) \ ( *ASegFlagAddr(S, P) & ( UnitMark << ASegFlagShift(S, P) ) ) FreePtr FirstFreeOfSize[ NbrOfBlockSizes ]; char Pad[ ASegPadSize - 1 ]; }; /* FirstFreeOfSize[0] is not used. */ /* Representation of an allocated block */ typedef struct BlockTg* BlockPtr; typedef struct BlockTg { UnsignedLog2 Size; /* The actual size */ unsigned Used; /* The size requested */ } AllocBlock; /* Note: Block returned by ASegAllocBlock must have struct BlockTg. */ /* Representation of a free block */ typedef struct FreeBlockTg { UnsignedLog2 Size; FreePtr Next; }; #endif <a name="025f_000e"> <a name="025f_000f">[LISTING FOUR] <a name="025f_000f"> /* AllocSeg -- Allocation Segment -- ALGORITHM & DATA STRUCTURES: This is a buddy system allocator; see KNUTH, Vol 1, pg 442. */ unsigned Junk; #include "array.h" #include "aseg.h" #include "bool.h" #include "power2.h" #include "stdio.h" #ifndef NULL #define NULL 0 #endif #define NULL_OFS 0xFFFF void* ASegAllocBlock( AllocSeg Seg, unsigned Size ) { BlockPtr Block; UnsignedLog2 BlockSize; FreePtr Buddy; FreePtr Free; UnsignedLog2 FreeSize; unsigned long* ZeroPtr; Size += 4; /* Add in the space for the block header */ /* Set BlockSize to the first power of 2 equal or larger to Size */ if ( Size < 256 ) { BlockSize = Log2[ BumpUp[Size] ]; } else { BlockSize = (Size + 255) >> 8; BlockSize = Log2[ BumpUp[BlockSize] ] + 8; } /* Set Free to the first free block of length >= Size */ /* If there is no such block return NULL */ Free = NULL; FreeSize = BlockSize; while (True) { if (NbrOfBlockSizes < FreeSize) { return NULL; } Free = Seg->FirstFreeOfSize[FreeSize]; if (Free != NULL) break; FreeSize++; } Block = (BlockPtr)Free; /* Returned block will be split from Free. */ /* Unlink Free from its list */ Seg->FirstFreeOfSize[FreeSize] = Free->Next; /* Split Free until it is of the requested size. */ while (FreeSize != BlockSize) { FreeSize--; Buddy = (FreePtr)( (char*)Free + (1 << FreeSize) ); Buddy->Size = FreeSize; Buddy->Next = Seg->FirstFreeOfSize[FreeSize]; Seg->FirstFreeOfSize[FreeSize] = Buddy; } Free->Size = BlockSize; ASegAllocSet(Seg, Block); Block->Used = Size - 4; /* Subtract off header length that we added */ /* Zero out memory before returning it */ for ( ZeroPtr = (unsigned long*)(Block + 1); ZeroPtr < (unsigned long*)( (char*)Block + (1 << BlockSize) ); ZeroPtr++ ) { *ZeroPtr = 0L; } return Block + 1; } void ASegVegamatic( AllocSeg Seg, FreePtr First, FreePtr End ) { FreePtr Free; unsigned FreeSize; unsigned Size; UnsignedLog2 SizeLog2; for ( Free = First; Free < End; Free = (FreePtr)( (char*)Free + Size ) ) { /* Calculate size for block. */ FreeSize = (char*)End - (char*)Free; Size = MaxPwr2Div((unsigned)Free); if ( (unsigned)Free & 0xFF ) { SizeLog2 = Log2[Size]; } else { SizeLog2 = Log2[Size>>8]; SizeLog2 += 8; } while ( FreeSize < Size ) { Size >>= 1; SizeLog2--; } Free->Size = SizeLog2; /* Link Free into the free list for blocks of Size */ Free->Next = Seg->FirstFreeOfSize[SizeLog2]; Seg->FirstFreeOfSize[SizeLog2] = Free; } } void ASegInitSeg( AllocSeg Seg ) { extern unsigned _atopsp; /* Start of heap and stack */ UnsignedLog2 BlockSize; /* The size of Free */ FreePtr Free; /* A free block */ unsigned Idx; /* Notes: atopsp is set by C startup to start of stack. The stack grows down from there, and the heap (that's us) up. */ _atopsp = (_atopsp + UnitSize - 1) & UnitMask; Seg->FirstFreeOfSize[0] = (FreePtr)_atopsp; for (Idx = 1; Idx < ArrayLength(Seg->FirstFreeOfSize); Idx++) { Seg->FirstFreeOfSize[Idx] = 0; } for (Idx = 0; Idx < ArrayLength(Seg->Flags); Idx++) { Seg->Flags[Idx] = 0; } ASegVegamatic( Seg, (FreePtr)_atopsp, (FreePtr)(Seg->Flags) ); } /* GARBAGE COLLECTING OPERATIONS */ void ASegClearMarks( AllocSeg Seg ) { int Pos; /* Notes: This is faster than traversing chain of blocks in segment, and then computing the bit to clear. This executes loop about 2K times; block- by-block could take 8K times. */ for (Pos = 0; Pos <= ArrayLast(Seg->Flags); Pos++) { Seg->Flags[Pos] &= ~ASegFlagMarkBits; } } unsigned ASegMarkValue( AllocSeg Seg, void* Value ) { unsigned* FlagPtr; unsigned Shift; unsigned* SizePtr; if ( (FreePtr)Value < Seg->FirstFreeOfSize[0] ) return 0; /* Value represents an address in the global data or stack, and couldn't have been returned by the allocator. */ if ( (unsigned)Value % UnitSize != 4 ) return 0; /* Allocator always returns address 4 bytes after unit which starts block. If value doesn't start 4 bytes after a Unit, it can't have been returned from allocator. */ FlagPtr = ASegFlagAddr(Seg, Value); Shift = ASegFlagShift(Seg, Value); if ( ( ( (*FlagPtr) >> Shift ) & (UnitAlloc|UnitMark) ) != UnitAlloc ) { /* Unit is Unallocated or already marked */ return 0; } *FlagPtr |= UnitMark << Shift; /* HACK: Assumption that requested size is 1 word before the value. */ SizePtr = (unsigned*)Value - 1; } return *SizePtr; } void ASegSweep( AllocSeg Seg ) { FreePtr End; FreePtr First; UnsignedLog2 SizeLog2; FreePtr WellWall; WellWall = (FreePtr)&Seg->Well[ ArrayLength(Seg->Well) ]; /* Zap the free list headers */ for ( SizeLog2 = 1; SizeLog2 <= NbrOfBlockSizes; SizeLog2++) { Seg->FirstFreeOfSize[ SizeLog2 ] = NULL; } First = (FreePtr)Seg->FirstFreeOfSize[0]; while ( True ) { /* Find the start of a free region */ while ( First < WellWall /* end the loop when we get past the segments memory well */ && ASegIsMarkSet(Seg, First) /* or when we find an unreferenced block */ ) { SizeLog2 = First->Size; First = (FreePtr)( (char*)First + ( 1 << SizeLog2 ) ); } if ( WellWall <= First ) break; /* end the loop when we get past the segments memory well */ ASegAllocClr(Seg, First); /* First is unreferenced, but may be allocated. It's about to be swept into the free list, so clear it's alloc flag. */ /* Find the end of the free region */ SizeLog2 = First->Size; End = (FreePtr)( (char*)First + ( 1 << SizeLog2 ) ); while ( End < WellWall /* end the loop when we get past the segments memory well */ && ! ASegIsMarkSet(Seg, End) /* or when we find a referenced block */ ) { ASegAllocClr(Seg, End); /* About to be swept up. Clear alloc flag */ SizeLog2 = End->Size; End = (FreePtr)( (char*)End + ( 1 << SizeLog2 ) ); } ASegVegamatic( Seg, First, End ); /* Split free region into free blocks and put into free lists */ First = End; /* Set First to End rather than block following End. */ } } <a name="025f_0010"> <a name="025f_0011">[LISTING FIVE] <a name="025f_0011"> /* Alloc -- A garbage collecting memory allocator. */ #include "stdio.h" #include "array.h" #include "aseg.h" #include "alloc.h" #include "gc.h" void free( void* Ptr ) { return; } void* malloc( unsigned Length ) { void* Result; Result = ASegAllocBlock( 0, Length ); if ( Result == NULL ) { GcPickUp(); Result = ASegAllocBlock( 0, Length ); } return Result; }
http://www.drdobbs.com/cpp/garbage-collection-for-c-programs/184408872
CC-MAIN-2014-23
refinedweb
4,110
54.12
#include <wx/uiaction.h> wxUIActionSimulator is a class used to simulate user interface actions such as a mouse click or a key press. Common usage for this class would be to provide playback and record (aka macro recording) functionality for users, or to drive unit tests by simulating user sessions. See the wxUIActionSimulator Sample for an example of using this class. Default constructor. Press and release a key. Press a key. If you are using modifiers then it needs to be paired with an identical KeyUp or the modifiers will not be released (MSW and OS X). Release a key. Click a mouse button. Double-click a mouse button. Press a mouse button. Perform a drag and drop operation. Move the mouse to the specified coordinates. Move the mouse to the specified coordinates. Release a mouse button. Simulate selection of an item with the given text. This method selects an item in the currently focused wxChoice, wxComboBox, wxListBox and similar controls. It does it by simulating keyboard events, so the behaviour should be the same as if the item was really selected by the user. Notice that the implementation of this method uses wxYield() and so events can be dispatched from it. Emulate typing in the keys representing the given string. Currently only the ASCII letters are universally supported. Digits and punctuation characters can be used with the standard QWERTY (US) keyboard layout but may not work with other layouts.
https://docs.wxwidgets.org/3.1.2/classwx_u_i_action_simulator.html
CC-MAIN-2019-09
refinedweb
240
60.01
Abstract: Multi-dimensional arrays in Java are simply arrays of arrays. This can have consequences in CPU and memory performance. Welcome to the 70th edition of The Java(tm) Specialists' Newsletter, where we have a quick look at multi-dimensional arrays. Many articles are available about this problem, so in this newsletter, I will briefly point out the problem and give you one example. I would like to thank Roy Emmerich (Peralex in Cape Town) and Pieter Potgieter and Louis Pool from Grintek Ewation for reminding me of this problem and for sending me a test program that illustrated it. This past week we had a Design Patterns Course at one of the finest hotels of Cape Town. OK, it is *renowned* to be one of the finest ;-) The lunches were fantastic, but the coffees, well! Let me say that they are probably not used to having programmers at their hotel? There is a direct correlation between quality of coffee and quality of code, so we are quite discerning when it comes to the magic brew. But the lunches more than made up for it! On the first day we had baked sirloin steak, on the second we had filled chicken breasts and on the third we were treated to excellently prepared line fish (Cape Salmon, otherwise known as Geelbek). The discussions about the Design Patterns were deep, and we all left thoroughly exhausted (especially me!). javaspecialists.teachable.com: Please visit our new self-study course catalog to see how you can upskill your Java knowledge. Something you learn in Java nursery school is to avoid multi-dimensional arrays like the plague. An array is an object in its own right, and when you have multi-dimensional arrays, you have arrays of objects. Navigating these will take considerable processing power. Instead of making a multi-dimensional array of size n by m, rather make a one-dimensional array of size n times m and then do the index calculation yourself. public class MultiDimensions { private final static int NUM_BINS = 1000; private final static int ITERATIONS = 10000; public static void main(String[] args) { testMultiArray(); testMultiArray2(); testSingleArray(); } private static void testMultiArray() { long time = -System.currentTimeMillis(); // just making sure that the number of operations is equal int ops = 0; for (int repeat = 0; repeat < ITERATIONS; repeat++) { int[][] aTwoDim = new int[NUM_BINS][4]; testMultiArray2() { long time = -System.currentTimeMillis(); int ops = 0; for (int repeat = 0; repeat < ITERATIONS; repeat++) { int[][] aTwoDim = new int[4][NUM_BINS]; testSingleArray() { long time = -System.currentTimeMillis(); int ops = 0; for (int repeat = 0; repeat < ITERATIONS; repeat++) { int[] aOneDim = new int[NUM_BINS * 4]; for (int i = 0; i < aOneDim.length/4; i++) { for (int j = 0; j < 4; j++) { ops++; aOneDim[i*4 + j] = j; } } } time += System.currentTimeMillis(); System.out.println(ops); System.out.println("Time Elapsed for [] - " + time); } } When I run this code with the client hotspot under JDK 1.4.1, I get the following results: 40000000 Time Elapsed for [][4] - 4226 40000000 Time Elapsed for [4][] - 631 40000000 Time Elapsed for [] - 671 The server hotspot fares slightly better: 40000000 Time Elapsed for [][4] - 3675 40000000 Time Elapsed for [4][] - 350 40000000 Time Elapsed for [] - 561 The results are enlightning. If you have an array with a big first index, you will be better off using a single-dimensional array. Under server hotspot, the multi-dimensional array with a small first index fares quite a bit better than the single-dimensional array. That's all that I would like to say about this issue. I warned you that this newsletter would be...
https://www.javaspecialists.eu/archive/Issue070-Too-Many-Dimensions-Are-Bad-for-You.html
CC-MAIN-2020-45
refinedweb
591
59.84
This projects is Mid-sized with great impact to the current Scala API designs. It will include two major tasks: Design Proposal sent to the Dev-list PRs: The way to call the api will be Symbol.api and NDArray.api. The new Scala API design is shown below:: We are proposing a new design of the API, brings different arguments to different functions as well as a full implementation on the backend side in order to execute them.. The raw data includes the following fields:=> This conversion tool will catch all possible types that defines in C++ and translate it into something that can be used in Scala. It is not finished fully, as you can see, we still have some types defined as type “Any”. The following code would do the following translation <C++ Type>, <Required/Optional>, <Default=> <Scala Type>, <is Optional>. We name this API into a namespace as: Symbol.api.<Function name>. This api contains every functions that generated from new Macros.
https://cwiki.apache.org/confluence/plugins/viewsource/viewpagesrc.action?pageId=89068242
CC-MAIN-2019-30
refinedweb
166
61.97
riko: A stream processing engine modeled after Yahoo! Pipesriko: A stream processing engine modeled after Yahoo! Pipes IndexIndex Introduction | Requirements | Word Count | Motivation | Usage | Installation | Design Principles | Scripts | Command-line Interface | Contributing | Credits | More Info | Project Structure | License IntroductionIntroduction riko is a pure Python library for analyzing and processing streams of structured data. riko has synchronous and asynchronous APIs, supports parallel execution, and is well suited for processing RSS feeds [1]. riko also supplies a command-line interface for executing flows, i.e., stream processors aka workflows. With riko, you can - Read csv/xml/json/html files - Create text and data based flowsvia modular pipes - Parse, extract, and process RSS/Atom feeds - Create awesome mashups [2], APIs, and maps - Perform parallel processing via cpus/processors or threads - and much more... NotesNotes RequirementsRequirements riko has been tested and is known to work on Python 3.6, 3.7, and 3.8; and PyPy3.6 7.3.0. Optional DependenciesOptional Dependencies NotesNotes Word CountWord Count In this example, we use several pipes to count the words on a webpage. >>> ### Create a SyncPipe flow ### >>> # >>> # `SyncPipe` is a convenience class that creates chainable flows >>> # and allows for parallel processing. >>> from riko.collections import SyncPipe >>> >>> ### Set the pipe configurations ### >>> # >>> # Notes: >>> # 1. the `detag` option will strip all html tags from the result >>> # 2. fetch the text contained inside the 'body' tag of the hackernews >>> # homepage >>> # 3. replace newlines with spaces and assign the result to 'content' >>> # 4. tokenize the resulting text using whitespace as the delimeter >>> # 5. count the number of times each token appears >>> # 6. obtain the raw stream >>> # 7. extract the first word and its count >>> # 8. extract the second word and its count >>> # 9. extract the third word and its count >>>>> fetch_conf = { ... 'url': url, 'start': '<body>', 'end': '</body>', 'detag': True} # 1 >>> >>> replace_conf = { ... 'rule': [ ... {'find': '\r\n', 'replace': ' '}, ... {'find': '\n', 'replace': ' '}]} >>> >>> flow = ( ... SyncPipe('fetchpage', conf=fetch_conf) # 2 ... .strreplace(conf=replace_conf, assign='content') # 3 ... .tokenizer(conf={'delimiter': ' '}, emit=True) # 4 ... .count(conf={'count_key': 'content'})) # 5 >>> >>> stream = flow.output # 6 >>> next(stream) # 7 {"'sad": 1} >>> next(stream) # 8 {'(': 28} >>> next(stream) # 9 {'(1999)': 1} MotivationMotivation Why I built rikoWhy I built riko Yahoo! Pipes [5] was a user friendly web application used to aggregate, manipulate, and mashup content from around the web Wanting to create custom pipes, I came across pipe2py which translated a Yahoo! Pipe into python code. pipe2py suited my needs at the time but was unmaintained and lacked asynchronous or parallel processing. riko addresses the shortcomings of pipe2py but removed support for importing Yahoo! Pipes json workflows. riko contains ~ 40 built-in modules, aka pipes, that allow you to programatically perform most of the tasks Yahoo! Pipes allowed. Why you should use rikoWhy you should use riko riko provides a number of benefits / differences from other stream processing applications such as Huginn, Flink, Spark, and Storm [6]. Namely: - a small footprint (CPU and memory usage) - native RSS/Atom support - simple installation and usage - a pure python library with pypy support - builtin modular pipesto filter, sort, and modify streams The subsequent tradeoffs riko makes are: - not distributed (able to run on a cluster of servers) - no GUI for creating flows - doesn't continually monitor streamsfor new data - can't react to specific events - iterator (pull) based so streams only support a single consumer [7] The following table summarizes these observations: For more detailed information, please check-out the FAQ. NotesNotes UsageUsage riko is intended to be used directly as a Python library. Usage IndexUsage Index Fetching feedsFetching feeds riko can fetch rss feeds from both local and remote filepaths via "source" pipes. Each "source" pipe returns a stream, i.e., an iterator of dictionaries, aka items. >>> from riko.modules import fetch, fetchsitefeed >>> >>> ### Fetch an RSS feed ### >>> stream = fetch.pipe(conf={'url': ''}) >>> >>> ### Fetch the first RSS feed found ### >>> stream = fetchsitefeed.pipe(conf={'url': ''}) >>> >>> ### View the fetched RSS feed(s) ### >>> # >>> # Note: regardless of how you fetch an RSS feed, it will have the same >>> # structure >>> item = next(stream) >>> item.keys() dict_keys(['title_detail', 'author.uri', 'tags', 'summary_detail', 'author_detail', 'author.name', 'y:published', 'y:title', 'content', 'title', 'pubDate', 'guidislink', 'id', 'summary', 'dc:creator', 'authors', 'published_parsed', 'links', 'y:id', 'author', 'link', 'published']) >>> item['title'], item['author'], item['id'] ('Gravity doesn’t care about quantum spin', 'Chris Lee', '') Please see the FAQ for a complete list of supported file types and protocols. Please see Fetching data and feeds for more examples. Synchronous processingSynchronous processing riko can modify streams via the 40 built-in pipes >>> SyncPipe flow ### >>> # >>> # `SyncPipe` is a convenience class that creates chainable flows >>> # and allows for parallel processing. >>> # >>> # The following flow will: >>> # 1. fetch the hackernews RSS feed >>> # 2. filter for items with '.com' in the link >>> # 3. sort the items ascending by title >>> # 4. fetch the first comment from each item >>> # 5. flatten the result into one raw stream >>> # 6. extract the first item's content >>> # >>> # Note: sorting is not lazy so take caution when using this pipe >>> >>> flow = ( ... SyncPipe('fetch', conf=fetch_conf) # 1 ... .filter(conf={'rule': filter_rule}) # 2 ... .sort(conf={'rule': {'sort_key': 'title'}}) # 3 ... .xpathfetchpage(conf=xpath_conf)) # 4 >>> >>> stream = flow.output # 5 >>> next(stream)['content'] # 6 'Open Artificial Pancreas home:' Please see alternate workflow creation for an alternative (function based) method for creating a stream. Please see pipes for a complete list of available pipes. Parallel processingParallel processing An example using riko's parallel API to spawn a ThreadPool [14] >>> parallel SyncPipe flow ### >>> # >>> # The following flow will: >>> # 1. fetch the hackernews RSS feed >>> # 2. filter for items with '.com' in the article link >>> # 3. fetch the first comment from all items in parallel (using 4 workers) >>> # 4. flatten the result into one raw stream >>> # 5. extract the first item's content >>> # >>> # Note: no point in sorting after the filter since parallel fetching doesn't guarantee >>> # order >>> flow = ( ... SyncPipe('fetch', conf=fetch_conf, parallel=True, workers=4) # 1 ... .filter(conf={'rule': filter_rule}) # 2 ... .xpathfetchpage(conf=xpath_conf)) # 3 >>> >>> stream = flow.output # 4 >>> next(stream)['content'] # 5 'He uses the following example for when to throw your own errors:' Asynchronous processingAsynchronous processing To enable asynchronous processing, you must install the async module. pip install riko[async] An example using riko's asynchronous API. >>> from riko.bado import coroutine, react >>> from riko.collections import AsyncPipe >>> >>> ### Set the pipe configurations ### >>> fetch_conf = {'url': ''} >>> filter_rule = {'field': 'link', 'op': 'contains', 'value': '.com'} >>>>> xpath_conf = {'url': {'subkey': 'comments'}, 'xpath': xpath} >>> >>> ### Create an AsyncPipe flow ### >>> # >>> # The following flow will: >>> # 1. fetch the hackernews RSS feed >>> # 2. filter for items with '.com' in the article link >>> # 3. asynchronously fetch the first comment from each item (using 4 connections) >>> # 4. flatten the result into one raw stream >>> # 5. extract the first item's content >>> # >>> # Note: no point in sorting after the filter since async fetching doesn't guarantee >>> # order >>> @coroutine ... def run(reactor): ... stream = yield ( ... AsyncPipe('fetch', conf=fetch_conf, connections=4) # 1 ... .filter(conf={'rule': filter_rule}) # 2 ... .xpathfetchpage(conf=xpath_conf) # 3 ... .output) # 4 ... ... print(next(stream)['content']) # 5 >>> >>> try: ... react(run) ... except SystemExit: ... pass Here's how iteration works (): CookbookCookbook Please see the cookbook or ipython notebook for more examples. NotesNotes InstallationInstallation (You are using a virtualenv, right?) At the command line, install riko using either pip (recommended) pip install riko or easy_install easy_install riko Please see the installation doc for more details. Design PrinciplesDesign Principles The primary data structures in riko are the item and stream. An item is just a python dictionary, and a stream is an iterator of items. You can create a stream manually with something as simple as [{'content': 'hello world'}]. You manipulate streams in riko via pipes. A pipe is simply a function that accepts either a stream or item, and returns a stream. pipes are composable: you can use the output of one pipe as the input to another pipe. riko pipes come in two flavors; operators and processors. operators operate on an entire stream at once and are unable to handle individual items. Example operators include count, pipefilter, and reverse. >>> from riko.modules.reverse import pipe >>> >>> stream = [{'title': 'riko pt. 1'}, {'title': 'riko pt. 2'}] >>> next(pipe(stream)) {'title': 'riko pt. 2'} processors process individual items and can be parallelized across threads or processes. Example processors include fetchsitefeed, hash, pipeitembuilder, and piperegex. >>> from riko.modules.hash import pipe >>> >>> item = {'title': 'riko pt. 1'} >>> stream = pipe(item, field='title') >>> next(stream) {'title': 'riko pt. 1', 'hash': 2853617420} Some processors, e.g., pipetokenizer, return multiple results. >>> from riko.modules.tokenizer import pipe >>> >>> item = {'title': 'riko pt. 1'} >>> tokenizer_conf = {'delimiter': ' '} >>> stream = pipe(item, conf=tokenizer_conf, field='title') >>> next(stream) {'tokenizer': [{'content': 'riko'}, {'content': 'pt.'}, {'content': '1'}], 'title': 'riko pt. 1'} >>> # In this case, if we just want the result, we can `emit` it instead >>> stream = pipe(item, conf=tokenizer_conf, field='title', emit=True) >>> next(stream) {'content': 'riko'} operators are split into sub-types of aggregators and composers. aggregators, e.g., count, combine all items of an input stream into a new stream with a single item; while composers, e.g., filter, create a new stream containing some or all items of an input stream. >>> from riko.modules.count import pipe >>> >>> stream = [{'title': 'riko pt. 1'}, {'title': 'riko pt. 2'}] >>> next(pipe(stream)) {'count': 2} In case you are confused from the "Word Count" example up top, count can return multiple items if you pass in the count_key config option. >>> counted = pipe(stream, conf={'count_key': 'title'}) >>> next(counted) {'riko pt. 1': 1} >>> next(counted) {'riko pt. 2': 1} processors are split into sub-types of source and transformer. sources, e.g., itembuilder, can create a stream while transformers, e.g. hash can only transform items in a stream. >>> from riko.modules.itembuilder import pipe >>> >>> attrs = {'key': 'title', 'value': 'riko pt. 1'} >>> next(pipe(conf={'attrs': attrs})) {'title': 'riko pt. 1'} The following table summaries these observations: If you are unsure of the type of pipe you have, check its metadata. >>> from riko.modules import fetchpage, count >>> >>> fetchpage.async_pipe.__dict__ {'type': 'processor', 'name': 'fetchpage', 'sub_type': 'source'} >>> count.pipe.__dict__ {'type': 'operator', 'name': 'count', 'sub_type': 'aggregator'} The SyncPipe and AsyncPipe classes (among other things) perform this check for you to allow for convenient method chaining and transparent parallelization. >>> from riko.collections import SyncPipe >>> >>> attrs = [ ... {'key': 'title', 'value': 'riko pt. 1'}, ... {'key': 'content', 'value': "Let's talk about riko!"}] >>> flow = SyncPipe('itembuilder', conf={'attrs': attrs}).hash() >>> flow.list[0] {'title': 'riko pt. 1', 'content': "Let's talk about riko!", 'hash': 1346301218} Please see the cookbook for advanced examples including how to wire in vales from other pipes or accept user input. NotesNotes Command-line InterfaceCommand-line Interface riko provides a command, runpipe, to execute workflows. A workflow is simply a file containing a function named pipe that creates a flow and processes the resulting stream. CLI UsageCLI Usage usage: runpipe [pipeid] description: Runs a riko pipe - positional arguments: - pipeid The pipe to run (default: reads from stdin). - optional arguments: - CLI SetupCLI Setup flow.py from __future__ import print_function from riko.collections import SyncPipe conf1 = {'attrs': [{'value': '', 'key': 'content'}]} conf2 = {'rule': [{'find': 'com', 'replace': 'co.uk'}]} def pipe(test=False): kwargs = {'conf': conf1, 'test': test} flow = SyncPipe('itembuilder', **kwargs).strreplace(conf=conf2) stream = flow.output for i in stream: print(i) CLI ExamplesCLI Examples Now to execute flow.py, type the command runpipe flow. You should then see the following output in your terminal: runpipe will also search the examples directory for workflows. Type runpipe demo and you should see the following output: Deadline to clear up health law eligibility near 682 ScriptsScripts riko comes with a built in task manager manage. SetupSetup pip install riko[develop] ExamplesExamples Run python linter and nose tests manage lint manage test ContributingContributing Please mimic the coding style/conventions used in this repo. If you add new classes or functions, please add the appropriate doc blocks with examples. Also, make sure the python linter and nose tests pass. Please see the contributing doc for more details. CreditsCredits Shoutout to pipe2py for heavily inspiring riko. riko started out as a fork of pipe2py, but has since diverged so much that little (if any) of the original code-base remains. More InfoMore Info Project StructureProject Structure ┌── benchmarks │ ├── __init__.py │ └── parallel.py ├── bin │ └── run ├── data/* ├── docs │ ├── AUTHORS.rst │ ├── CHANGES.rst │ ├── COOKBOOK.rst │ ├── FAQ.rst │ ├── INSTALLATION.rst │ └── TODO.rst ├── examples/* ├── helpers/* ├── riko │ ├── __init__.py │ ├── lib │ │ ├── __init__.py │ │ ├── autorss.py │ │ ├── collections.py │ │ ├── dotdict.py │ │ ├── log.py │ │ ├── tags.py │ │ └── py │ ├── modules/* │ └── twisted │ ├── __init__.py │ ├── collections.py │ └── py ├── tests │ ├── __init__.py │ ├── standard.rc │ └── test_examples.py ├── CONTRIBUTING.rst ├── dev-requirements.txt ├── LICENSE ├── Makefile ├── manage.py ├── MANIFEST.in ├── optional-requirements.txt ├── py2-requirements.txt ├── README.rst ├── requirements.txt ├── setup.cfg ├── setup.py └── tox.ini LicenseLicense riko is distributed under the MIT License.
https://reposhub.com/python/miscellaneous/nerevu-riko.html
CC-MAIN-2020-45
refinedweb
2,100
59.6
Maximally localized Wannier functions¶ This page describes how to construct the Wannier orbitals using the class Wannier. The page is organized as follows: - Introduction: A short summary of the basic theory. - The Wannier class : A description of how the Wannier class is used, and the methods defined within. Introduction¶ The point of Wannier functions is the transform the extended Bloch eigenstates of a DFT calculation, into a smaller set of states designed to facilitate the analysis of e.g. chemical bonding. This is achieved by designing the Wannier functions to be localized in real space instead of energy (which would be the eigen states). The standard Wannier transformation is a unitary rotation of the Bloch states. This implies that the Wannier functions (WF) span the same Hilbert space as the Bloch states, i.e. they have the same eigenvalue spectrum, and the original Bloch states can all be exactly reproduced from a linear combination of the WF. For maximally localized Wannier functions (MLWF), the unitary transformation is chosen such that the spread of the resulting WF is minimized. The standard choice is to make a unitary transformation of the occupied bands only, thus resulting in as many WF as there are occupied bands. If you make a rotation using more bands, the localization will be improved, but the number of wannier functions increase, thus making orbital based analysis harder. The class defined here allows for construction of partly occupied MLWF. In this scheme the transformation is still a unitary rotation for the lowest states (the fixed space), but it uses a dynamically optimized linear combination of the remaining orbitals (the active space) to improve localization. This implies that e.g. the eigenvalues of the Bloch states contained in the fixed space can be exactly reproduced by the resulting WF, whereas the largest eigenvalues of the WF will not necessarily correspond to any “real” eigenvalues (this is irrelevant, as the fixed space is usually chosen large enough, i.e. high enough above the fermilevel, that the remaining DFT eigenvalues are meaningless anyway). For the theory behind this method see the paper “Partly Occupied Wannier Functions” Thygesen, Hansen and Jacobsen, Phys. Rev. Lett, Vol. 94, 26405 (2005). The Wannier class¶ Usual invocation: from ase.dft import Wannier wan = Wannier(nwannier=18, calc=GPAW('save.gpw'), fixedstates=15) wan.localize() # Optimize rotation to give maximal localization wan.save('file.pickle') # Save localization and rotation matrix # Re-load using saved wannier data wan = Wannier(nwannier=18, calc=calc, fixedstates=15, file='file.pickle') # Write a cube file wan.write_cube(index=5, fname='wannierfunction5.cube') For examples of how to use the Wannier class, see the Partly occupied Wannier Functions tutorial. - class ase.dft.wannier. Wannier(nwannier, calc, file=None, nbands=None, fixedenergy=None, fixedstates=None, spin=0, initialwannier=’random’, seed=None, verbose=False)[source]¶ Maximally localized Wannier Functions Find the set of maximally localized Wannier functions using the spread functional of Marzari and Vanderbilt (PRB 56, 1997 page 12847). Required arguments: nwannier: The number of Wannier functions you wish to construct. - This must be at least half the number of electrons in the system and at most equal to the number of bands in the calculation. calc: A converged DFT calculator class. - If filearg. is not provided, the calculator must provide the method get_wannier_localization_matrix, and contain the wavefunctions (save files with only the density is not enough). If the localization matrix is read from file, this is not needed, unless get_functionor write_cubeis called. Optional arguments: nbands: Bands to include in localization. - The number of bands considered by Wannier can be smaller than the number of bands in the calculator. This is useful if the highest bands of the DFT calculation are not well converged. spin: The spin channel to be considered. - The Wannier code treats each spin channel independently. fixedenergy/ fixedstates: Fixed part of Heilbert space. - Determine the fixed part of Hilbert space by either a maximal energy or a number of bands (possibly a list for multiple k-points). Default is None meaning that the number of fixed states is equated to nwannier. file: Read localization and rotation matrices from this file. initialwannier: Initial guess for Wannier rotation matrix. - Can be ‘bloch’ to start from the Bloch states, ‘random’ to be randomized, or a list passed to calc.get_initial_wannier. seed: Seed for random initialwannier. verbose: True / False level of verbosity. get_function(index, repeat=None)[source]¶ Get Wannier function on grid. Returns an array with the funcion values of the indicated Wannier function on a grid with the size of the repeated unit cell. For a calculation using k-points the relevant unit cell for eg. visualization of the Wannier orbitals is not the original unit cell, but rather a larger unit cell defined by repeating the original unit cell by the number of k-points in each direction. Note that for a \(\Gamma\)-point calculation the large unit cell coinsides with the original unit cell. The large unitcell also defines the periodicity of the Wannier orbitals. indexcan be either a single WF or a coordinate vector in terms of the WFs. get_functional_value()[source]¶ Calculate the value of the spread functional. Tr[|ZI|^2]=sum(I)sum(n) w_i|Z_(i)_nn|^2, where w_i are weights. get_hamiltonian(k=0)[source]¶ Get Hamiltonian at existing k-vector of index k dag H(k) = V diag(eps ) V k k k get_hamiltonian_kpoint(kpt_c)[source]¶ Get Hamiltonian at some new arbitrary k-vector _ ik.R H(k) = >_ e H(R) R Warning: This method moves all Wannier functions to cell (0, 0, 0) get_hopping(R)[source]¶ Returns the matrix H(R)_nm=<0,n|H|R,m>. 1 _ -ik.R H(R) = <0,n|H|R,m> = --- >_ e H(k) Nk k where R is the cell-distance (in units of the basis vectors of the small cell) and n,m are indices of the Wannier functions. get_pdos(w, energies, width)[source]¶ Projected density of states (PDOS). Returns the (PDOS) for Wannier function w. The calculation is performed over the energy grid specified in energies. The PDOS is produced as a sum of Gaussians centered at the points of the energy grid and with the specified width. get_radii()[source]¶ Calculate the spread of the Wannier functions. -- / L \ 2 2 radius**2 = - > | --- | ln |Z| --d \ 2pi / initialize(file=None, initialwannier=’random’, seed=None)[source]¶ Re-initialize current rotation matrix. Keywords are identical to those of the constructor. localize(step=0.25, tolerance=1e-08, updaterot=True, updatecoeff=True)[source]¶ Optimize rotation to give maximal localization max_spread(directions=[0, 1, 2])[source]¶ Returns the index of the most delocalized Wannier function together with the value of the spread functional translate(w, R)[source]¶ Translate the w’th Wannier function The distance vector R = [n1, n2, n3], is in units of the basis vectors of the small cell. translate_all_to_cell(cell=[0, 0, 0])[source]¶ Translate all Wannier functions to specified cell. Move all Wannier orbitals to a specific unit cell. There exists an arbitrariness in the positions of the Wannier orbitals relative to the unit cell. This method can move all orbitals to the unit cell specified by cell. For a \(\Gamma\)-point calculation, this has no effect. For a k-point calculation the periodicity of the orbitals are given by the large unit cell defined by repeating the original unitcell by the number of k-points in each direction. In this case it is useful to move the orbitals away from the boundaries of the large cell before plotting them. For a bulk calculation with, say 10x10x10 k points, one could move the orbitals to the cell [2,2,2]. In this way the pbc boundary conditions will not be noticed. In Dacapo, the inialwannier keyword can be a list as described below: Setup an initial set of Wannier orbitals. initialwannier can set up a starting guess for the Wannier functions. This is important to speed up convergence in particular for large systems For transition elements with d electrons you will always find 5 highly localized d-orbitals centered at the atom. Placing 5 d-like orbitals with a radius of 0.4 Angstroms and center at atom no. 7, and 3 p-like orbitals with a radius of 0.4 Angstroms and center at atom no. 27 looks like this:initialwannier = [[[7],2,0.4],[[27],1,0.4]] Placing only the l=2, m=-2 and m=-1 orbitals at atom no. 7 looks like this:initialwannier = [[[7],2,-2,0.4],[[7],2,-1,0.4]] I.e. if you do not specify the m quantum number all allowed values are used. Instead of placing an orbital at an atom, you can place it at a specified position. For example the following:initialwannier = [[[0.5,0.5,0.5],0,0.5]] places an s orbital with radius 0.5 Angstroms at the position (0.5, 0.5, 0.5) in scaled coordinates of the unit cell. Note For calculations using k-points, make sure that the \(\Gamma\)-point is included in the k-point grid. The Wannier module does not support k-point reduction by symmetry, so you must use the usesymm=False keyword in the calc, and shift all k-points by a small amount (but not less than 2e-5 in) in e.g. the x direction, before performing the calculation. If this is not done the symmetry program will still use time-reversal symmetry to reduce the number of k-points by a factor 2. The shift can be performed like this: from ase.dft.kpoints import monkhorst_pack kpts = monkhorst_pack((15, 9, 9)) + [2e-5, 0, 0]
https://wiki.fysik.dtu.dk/ase/dev/ase/dft/wannier.html
CC-MAIN-2018-09
refinedweb
1,610
56.25
The QExpressionEvaluator class computes the results of arithmetic, logical and string based expressions. More... #include <QExpressionEvaluator> Inherits QObject. The QExpressionEvaluator class computes the results of arithmetic, logical and string based expressions. Most interestingly, the expression evaluator has the ability to use values from the Qtopia valuespace in its expressions and signal when the resulting expression changes through termsChanged(). It takes as input through setExpression() an expression such as "2 + 2" and calculates the result. Here is an example of basic usage of the expression evaluator. QExpressionEvaluator ee; ee.setExpression("2 + 2"); if(!ee.isValid()) { // check if syntax/semantics correct. qWarning("Syntax or semantic error in expression."); } else { if(!ee.evaluate()) { // evaluate the expression qWarning("Run-time error when evaluating expression"); // run-time error - type coercion or divide by zero. } else { QVariant result = ee.result(); // retrieve the result int x = result.toInt(); // x == 4 } } The expression evaluator functionally operates in 2 phases. The first phase is the setup phase, where the specified expression is tokenized, parsed, semantically checked and byte code generated. The isValid() function returns whether this entire setup phase is successful ie. the specified expression is syntactually and semantically valid. The second phase is the evaluation phase, where the generated bytecode from the first phase is executed to compute the result of the expression. The evaluate() function uses a virtual machine to execute the bytecode and store the resulting value. Run-time errors occur when an expression attempts to divide-by-zero or if an expression evaluator term cannot be coerced to a required type. The return value of evaluate() indicates whether there were any run-time errors. If evaluate() returns true, result() can then be called to retreive the calcuated result of the expression as a QVariant. You should cast the variant to the data type you expect. The expression evaluator supports 5 data types: int, real, string and bool. real numbers are represented either using the C++ double data type, or by using fixed point calculations. C++ double is the default, but you probably want to use the fixed point format for user visible applications of the expression evaluator, such as a desktop calculator. This can be set using the setFloatingPointFormat() function. Table is in highest to lowest precedence. Operators in the expression evaluator work with operands of the same type ie. the '+' operator can only add two integer or two real numbers. However, a user may still mix data types and the operands will be coerced to the correct type for the operator. Consider the expression: 2 + "2" The '+' operator adds two number operands, but the RHS operand is a string. As the LHS is an integer, the expression evaluator tries to coerce the RHS string to an integer to meet the requirements of the '+' operator. In this case, the coercion would succeed and "2" would simply become an integer 2. The result of the expression would then be the integer 4. If operands cannot be coerced to the required types for an operator, then for static coercion the setup phase fails and isValid() returns false and for run-time coercion evaluate() returns false. Run-time coercion failures can occur for 2 reasons: a term, eg. a key in the valuespace, does not return a value that can be coerced to the required type, or a return value of one side of the expression cannot be coerced to the required type. eg. 2 + ("2" . "@/value/in/valuespace") would fail at run-time because the RHS of '+' is a string, calculated at runtime, that cannot be coerced to an integer. Below are the data type requirements of the expression evaluator's operators. The expression evaluator has the ability to use values from the Qtopia valuespace in its expressions. 2 + @/Value/Space/Key The above code would add 2 and the value for /Value/Space/Key in the valuespace. The '@' character uniquely identifies the subsequent characters as a valuespace key to the expression evaluator. In the above example, /Value/Space/Key must return data that can be converted to an integer. If conversion fails, a run-time error will occur and evaluate() will return false. If a value in the valuespace changes, expressions which use that value will emit the termsChanged() signal. Controls the floating point format used by the expression evaluator. Constructs a QExpressionEvaluator. parent is passed to the QObject constructor. Constructs a QExpressionEvaluator. expr is passed to setExpression(). parent is passed to the QObject constructor. Destroys the QExpressionEvaluator. Clears the set expression and any associated data structures. The expression becomes invalid ie. isValid() returns false. Evaluates the expression specified through setExpression(). isValid() must return true before you call this function, otherwise it will abort(). Returns true if the expression was successfully evaluated, or false if a run-time error occured. A run-time error can occur due to a coercion error or divide by zero. If this function returns true, the result of the evaluation can be retrieved using result(). Returns the current expression data the evaluator is operating on. See also setExpression(). Returns the current floating point format. See also setFloatingPointFormat(). Returns true if this expression is valid, otherwise false. An expression is valid if it is not empty, it is syntactually and semantically correct, and a previous call to evaluate() did not result in a run-time error. You must not call evaluate() unless this function returns true. Returns the result of the last call to evaluate() as a QVariant. Returns an empty QVariant if evaluate() has not yet been called. Sets the expression for the evaluator to be expr expr is parsed and semantically checked immediat Returns true on success; otherwise returns false. You should call isValid() after this function to determine whether the setup phase was completed successfully. See also expression(). Sets the floating point format to be used by the expression evaluator to fmt. The default is QExpressionEvaluator::Double, but setting QExpressionEvaluator::FixedPoint may give results appropriate for user level applications. See also floatingPointFormat(). Emitted when a pluggable term in the expression changes.
https://doc.qt.io/archives/qtopia4.3/qexpressionevaluator.html
CC-MAIN-2019-18
refinedweb
1,002
50.23
23 April 2013 09:01 [Source: ICIS news] SINGAPORE (ICIS)--CNOOC Energy Technology & Services (CNOOC EnerTech) plans to build a 50,000 tonne/year butyl rubber plant at Putian in Fujian province, a company source said on Tuesday. “We are currently doing environmental assessment and feasibility research, which may last a year,” said the source. ?xml:namespace> The company also plans to build a 100,000 tonne/year isobutene unit and related supporting facilities at the site, the source said. The rubber plant will need 80,000-90,000 tonnes/year of methyl tertiary butyl ether (MTBE) as feedstock, most of which will come from the spot market, market sources said. CNOOC EnerTech is a part of China National Offshore Oil Corp (CNOOC).CNOOC EnerTech is a part of China National Offshore Oil Corp (CNO
http://www.icis.com/Articles/2013/04/23/9661519/chinas-cnooc-enertech-to-build-new-butyl-rubber-plant-in-fujian.html
CC-MAIN-2014-42
refinedweb
135
59.13
Few days ago I went into searching for a good way to make a simple computer vision system. OpenCV library is something I need but it proved hard to learn with Python especially after OpenCV 2.4.3 update which have very slim Python related documentation. So I now understand that there was a bunch of changes in OpenCV, for exaxmple import cv is now import cv2 And there is bunch of modules that is missing. I mean, yes there are examples of the new python-opencv syntax but it's very narrow and proven to be hard to understand. For example: Example in official documentation for Python code cv2.cvtColor(src, code[, dst[, dstCn]]) I know what this code means and how to use it, at least I think i know. But writing source and color code does nothing just give me : Traceback (most recent call last): File "C:\FILEFOLDER\tut.py", line 11, in <module> cv.cvtColor('proba.jpg', 'CV_RGB2GRAY') TypeError: an integer is required Or if i try to write code like variable: Traceback (most recent call last): File "C:\FILEFOLDER\tut.py", line 11, in <module> cv.cvtColor('proba.jpg', CV_RGB2GRAY) NameError: name 'CV_RGB2GRAY' is not defined So is there any Python related reference document/tutorial/book/guide for newest OpenCV with the ground up explanations that does not confuse newbie like me with unwanted code examples for C++ or Java? answered 2012-11-17 14:25:04 -0500 Python documentation is a little patchy, but in my opinion worth persisting with. Sometimes the C++ description is very helpful as it says the type of array required. The main problem with your code examples is that OpenCV Python functions which process images take as input Numpy arrays. This means you have to read the image from .jpg into an array, and then pass it to the function. The result from cvtColor is another Numpy array. Example: import numpy as np import cv2 im=cv2.imread('c:/temp/i1.jpg',cv2.cv.CV_LOAD_IMAGE_COLOR) type(im) #Shows Numpy array im.shape #Numpy array object shape gives image size cv2.imshow('Colour',im) im_gray=cv2.cvtColor(im,cv2.COLOR_BGR2GRAY) cv2.imshow('Gray',im_gray) #show image on screen cv2.imwrite('c:/temp/i1g.jpg',im_gray) #write to file im_gray[...]=0 #Use Numpy broadcasting cv2.imshow('Turned black',im_gray) If you unpack the OpenCV source there is a directory of samples called opencv\samples\python2 These are all using the cv2 interface. answered 2012-11-15 21:34:26 -0500 I sympathise with your confusion at the state of the official documentation, but your example is an issue with your Python syntax, not with OpenCV or its documentation. Importing like so: import cv will not add symbols in the cv module to the local namespace. You can either reference the cv module every time you want to use a symbol from it (e.g.: cv.cvtColor and cv.CV_RGB2GRAY) or import the symbols you need into the local namespace (e.g.: from cv import cvtColor, CV_RGB2GRAY) or just import everything: from cv import *. I don't know of any better source of documentation, sorry. Asked: 2012-11-14 09:55:54 -0500 Seen: 2,905 times Last updated: Nov 17 '12 How to get dct of an image in python using opencv How to use cv.boxFilter() in python Problems installing opencv on mac with python Error when trying to draw line or rectangle Android async initialization problem Visual Studio 2012 with OpenCV (debugging, lack of OpenCV VC11 libraries) how can i deal with these outputs python 2 cameras under usb hub
http://answers.opencv.org/question/4186/python-and-opencv-243/
CC-MAIN-2014-41
refinedweb
601
64.2
Everything you need to know to write, debug, deploy and monitor Azure Functions Step by step guide using a light weight approach 1. Introduction TimeSpan(someInterval)); } }); } The code that captures some data is now to be moved to multiple Azure function apps. They will be triggered by timers. In this article, I want to share all lessons learned. I will show the complete process of how to go from zero to deployment and even beyond. The goals are as follow: - First, this approach will be as light weight as possible. NO massive Visual Studio 2017 installation is required. - During development, since you’ll need to know how to debug and log messages, we’ll cover that. After the Azure function apps are deployed to the Azure Cloud, we certainly want to monitor log messages so that we can determine how they’re running or not running. We’ll cover that as well. - In real-world situations like in my cases, we need to write and run multiple Azure function apps in production. These function apps need to share some common code such as Entity Framework data access, models, helper utilities, etc. - We’ll cover how to do Dependency Injection. Some assumptions: - From this article, you will learn how to implement Azure function apps and run locally. But to get the maximum benefits when it comes to deployment on Azure, you should already have an Azure subscription. You should be familiar with portal.azure.com already. - I will only show Azure function apps in C#. These functions are timer-triggered. 2. Set up NodeJS and npm packages Everything above sounds perfect? Well, since we know nothing is perfect, so is this approach. The drawback, if you so consider, is that we need to install NodeJS (since we only do C# here). For me, it’s not a problem because I already have Node installed for many other purposes. Anyway, you can install from Then we need to install the npm pckage azure-functions-core-tools. This package will be required later. If we don’t do it now, Visual Studio Code will remind us later. For now, let’s just install and get it out of the way. $ npm install -g azure-functions-core-tools@latest 3. Install .NET Core and Visual Studio Code - Download the .NET Core SDK (2.1 at the time of this writing). Be sure to choose the SDK and NOT the Runtime, because we don’t want to just run the apps, we want to build the apps. You might already have this installed, in which case, this step can be ignored. Make sure when you type dotneton a Terminal, the command is recognized. .NET Downloads for Linux, macOS, and Windows Free downloads for building and running .NET applications on Linux, macOS, and Windows. Get downloads for the latest… - NO Visual Studio 2017 is needed. But we will need to install Visual Studio Code (hereinafter referred to as Code). Code is much more lighter weight than Visual Studio 2017 (which takes up more than 20 GB easily with only a few modules installed) and Code is also a a lot more stable. It does not hang every now and then like Visual Studio 2017. So Code is what we will use. If you don’t already have Code installed, the link is below. You might already have this installed, in which case, this step can be ignored. Download Visual Studio Code - Mac, Linux, Windows Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows. Download Visual Studio… code.visualstudio.com - Install the Azure Functions extensionin Visual Studio Code. In case you don’t know about Extensions, look for the 5th menu item in the most left gutter panel of Code. A by product of this installation is Azure Account extensionis also installed. - There are a couple ways to create an Azure Function: using the Command Line Interface (CLI) or directly from Code. I normally prefer CLI everything, but in this case, let’s do from Code. - First, let’s create a new Project. - Select a folder, choose C#. You should see a .csprojfile created. Open this file and make sure the target framework is 2.1. If you don’t see 2.1, you might see problem with deploying later on in the process. I think because at the time of this writing, 2.1 is the default on Azure. So anything other than that doesn’t work. I experienced that, but the error message doesn’t help. <TargetFramework>netcoreapp2.1</TargetFramework> - Next let’s create a couple of function apps. Use the next icon. - Select the same folder, choose TimerTrigger. For the function name, just call them FunctionApp1and FunctionApp2. Type any namespace you want. For this example, I name ExampleAzFuncsas the namespace. - Specify any timer interval you want. I specify 0 */1 * * * *(that’s 1 minute). To learn about the syntax, refer to - You might see multiple warnings from Code. If you see the one below, just click Install. - If you see - That means you have not installed NodeJS and the npm package azure-functions-core-toolsas discussed in 2 above, now is the time to do. You can download node from. After Node is installed, run the following command: $ npm install -g azure-functions-core-tools@latest - If you see For any of triggers other than HttpTrigger, AzureWebJobStorage is required (We picked TimerTrigger). Skip for Now. Just close the box. We’ll deal with this soon. - If you get the warning There are unresolved dependencies. Please execute the restore command to continuejust go ahead and click Restore. You might also get these warning at various times, especially after adding a nuget package. Just click Restoreeach time. 4. Restructure the folder hierarchy At this point you should see in your Code Explorer panel a folder hierarchy similar to this - You want to restructure by adding 2 folders at the top level. Name these folders FunctionApp1and FunctionApp2. Move FunctionApp1.csand FunctionApp2.csinside each of them respectively. In addition, in both FunctionApp1and FunctionApp2folders, create a file in each named function.json. At the same level with FunctionApp1and FunctionApp2folders, create a folder named SharedCode. The folder hierarchy at this point should look like: - Copy the following code to the function.jsonfile. Change the name accordingly. { "bindings": [{ "name": "FunctionApp1or2", "type": "timerTrigger", "direction": "in", "runOnStartup": true, "schedule": "*/1 * * * * *" }] } - Right now, there’s nothing in the SharedCodefolder. But this is where we will place all the shared code. 5. AzureWebJobStorage The reason we skip the above configuration of the AzureWebJobStorage is we don’t want to point to an environment on the Azure cloud, not just yet. Since we’re still getting started and still in development, we can emulate the AzureWebJobStorage locally. There are 2 options: a. Standalone Storage Emulator Both are easy to use. Azurite is advantageous because it’s cross-platform. For me, I choose Azurite. Regardless of whether you choose the Standalone Storage Emulator or Azurite, locate the file local.settings.json and add the value UseDevelopmentStorage=true for the key AzureWebJobsStorage { "IsEncrypted": false, "Values": { "AzureWebJobsStorage": "UseDevelopmentStorage=true", "FUNCTIONS_WORKER_RUNTIME": "dotnet" } } Now open up the Terminal and you can run $ func start --build Depending on the interval you specify, every 1 or 5 second, you should see the some output like (of course you must have changed from the default log messages earlier) FunctionApp1 function executed at … Some Troubleshooting tips a. Missing value for AzureWebJobsStorage If you see the error above, make sure the line "AzureWebJobsStorage": "UseDevelopmentStorage=true”, is in the local.settings.json file. b. Emulator or Azurite not running If you see the error above, make sure the Storage Emulator or Azurite is running 6. Logging You saw the line of code log.LogInformation above. ILogger is injected to the Run method, which makes it very convenient public static void Run([TimerTrigger("0 */2 * * * *")]TimerInfo myTimer, ILogger log) { log.LogInformation("..."); } If you play with Code Intellisense, you’ll see other methods for logging such as log.LogCritical, log.LogDebug, log.LogError, log.LogWarning, etc. To control the log level, locate the host.json file and add the following lines in bold: { "version": "2.0", "logging": { "logLevel": { "default": "Error" } } } 7. Logging in other classes’ methods Chances are nobody will write all the code in this single Run() method, because that will be such a monolithic way of programming. So if we add more classes and want to log messages in their methods, how would we need to do? We need to inject something like ILogger (as seen in the Run method). 8. Dependency Injection We will revisit on how to log messages in other classes’ methods. For now we will need to do Dependency Injection in Azure Function. We will use Autofac, but because we’re doing Azure Function, we need to use Azure Function Autofac. Open up the Terminal and run the command: $ dotnet add package AzureFunctions.Autofac --version 3.0.5 Now add a new file inside the SharedCode folder and call it something like AutofacConfig.cs with the following content: using System; using Microsoft.Azure.WebJobs.Host.Config; using Microsoft.Extensions.DependencyInjection; using Autofac; using AzureFunctions.Autofac.Configuration; using Microsoft.Extensions.Logging; namespace ExampleAzFuncs { public class AutofacConfig { public AutofacConfig(string functionName) { DependencyInjection.Initialize(builder => { builder.Register(ctx => new ServiceCollection() .AddLogging() .BuildServiceProvider() .GetService<ILoggerFactory>()) .As<ILoggerFactory>(); }, functionName); } } } Now let’s say we need to write some ServiceHelper class. From this point on, it is assumed that any code that’s common to all the function apps will be placed in the SharedCode folder. Let’s write the interface called IServiceHelper and this implementation class ServiceHelper. Create 2 new files called IServiceHelper.cs and ServiceHelper.cs with the following contents respectively: //IServiceHelper.cs namespace ExampleAzFuncs { public interface IServiceHelper { string Greet(string message); } } and //ServiceHelper.cs namespace ExampleAzFuncs { public class ServiceHelper : IServiceHelper { public string Greet(string message) { //We'll add logging later return "Hello "+ message; } } } As you can see, there’s no logging code in ServiceHelper yet. Now we need to register with Autofac, so let’s revise the AutofacConfig constructor above: public AutofacConfig(string functionName) { DependencyInjection.Initialize(builder => { builder.RegisterType<ServiceHelper>().As<IServiceHelper>(); builder.Register(ctx => new ServiceCollection() .AddLogging() .BuildServiceProvider() .GetService<ILoggerFactory>()) .As<ILoggerFactory>(); }, functionName); } Next, install the following nuget package from the Terminal $ dotnet add package Microsoft.Extensions.Logging.Console --version 2.1.1 (Above should be all in one line) Inject ILoggerFactory to the constructor of ServiceHelper and start logging. //ServiceHelper.cs using AzureFunctions.Autofac; using AzureFunctions.Autofac.Configuration; using Microsoft.Extensions.Logging; namespace ExampleAzFuncs { [DependencyInjectionConfig(typeof(AutofacConfig))] public class ServiceHelper : IServiceHelper { private ILogger _logger; public ServiceHelper([Inject] ILoggerFactory logFactory){ _logger = logFactory.AddConsole(LogLevel.Information) .CreateLogger<ServiceHelper>(); } public string Greet(string message) { _logger.LogInformation($"[{System.DateTime.Now}] Message is {message}"); return "Hello "+ message; } } } Update 11–5–2018: The above logging code does not cause messages to be streamed from Azure once it’s running in production. Replace with the following: Don’t forget to add the package $ dotnet add package Microsoft.Extensions.Logging.AzureAppServices — version 2.1.1 End of update 11–5–2018 Inject IServiceHelper to the Run method of the Azure Function: using System; using Microsoft.Azure.WebJobs; using Microsoft.Azure.WebJobs.Host; using Microsoft.Extensions.Logging; using AzureFunctions.Autofac; using AzureFunctions.Autofac.Configuration;namespace ExampleAzFuncs { [DependencyInjectionConfig(typeof(AutofacConfig))] public static class FunctionApp1 { [FunctionName("FunctionApp1")] public static void Run( [TimerTrigger("0 */1 * * * *")]TimerInfo myTimer, ILogger log, [Inject] IServiceHelper serviceHelper) { serviceHelper.Greet("Azure Function"); log.LogInformation($"C# Timer trigger function executed at: {DateTime.Now}"); } } } The result would look something like 9. Debug locally Logging messages is great for troubleshooting but sometime debug is more preferable. Debugging an Azure Function in Code could not be easier (but as a side note took me hours to figure out). Simply cursor to the line where you want to place the breakpoint, then hit F9. To run, hit F5. However, if inside the Run method, we need to make some asynchronous calls, that means we have to mark the calls with await, then Run has to be marked with async. Doing so, then we will no longer be able to set breakpoints and debug. 10. Deploy to Azure My preference is to use the Continuous Deployment approach to deploy all of my Azure App Services and Azure Functions. But we’ll do directly for now. - Click on the up arrow in blue. Create a New Function App, type in the name for the Azure Function. I typed ExampleAzFuncs. - Create a New Resource Groupor select an existing one. - Create a New Storage Accountor select an existing one. If you remember, during developement when we run locally, we tell the configuration in local.settings.json "AzureWebJobsStorage": "UseDevelopmentStorage=true", Azurite or the Storage Emulator took care of providing the storage. Now when we deploy to Azure, we need real Azure WebJobs Storage. By using the extension, we can easily configure it on Azure. Everything should go smoothly. If you get the following error Could not zip a non-exist file path, chances are you didn’t specify 2.1 for the target framework as mentioned above. 11. Logging in Production To view logging messages, right click on your Function app and select Start/Stop Streaming Logs. 12. Conclusion The article might seem long, but that’s because I’m too verbose. But as you can see, it’s not that conceptually hard. If you like, please clap.
https://kevinle.medium.com/everything-you-need-to-know-to-write-debug-deploy-and-monitor-azure-functions-be6b8f541e8a
CC-MAIN-2021-04
refinedweb
2,232
51.04
Hi Forum, I am new to Jboss and J2EE so please ignore my ignorance. I have a EAR file containing EJB having a remote interface.Now i have to call this remote interface from another WAR file(this WAR is not contained in the EAR contaning EJB).Both EAR and WAR are deployed on the same JBoss Server. I have tried to call using the JNDI lookup like FiboHome home = (FiboHome) PortableRemoteObject.narrow(ctx.lookup("java:/comp/env/ejb/Fibo"),FiboHome.class); but while calling Remote Method system is throwing exception javax.naming.NameNotFoundException: ejb not bound Is this the right way to call Remote Interface from outside EAR? If Yes,what's wrong if no ,What is the right Way ? Thanks in Advance -Newbie The java:comp/env namespace is a component local one. Unless you have deployed a j2ee client that sets up a java:comp/env namespace you need to know the full jndi name of the remote ejb home to lookup. For more on j2ee clients see:
https://developer.jboss.org/thread/120896
CC-MAIN-2018-13
refinedweb
171
66.13
Teaming C | FORTRAN omp_get_num_threads Definition omp_get_num_threads returns the number of threads in the current OpenMP region. If this function is called outside a parallel region, only the master thread is present hence the value returned is 1. Although spellings are close, do not confuse this function with omp_get_thread_num. Copy Feedback int omp_get_num_threads(); Returned value The number of threads contained in the current region. Example Copy Feedback #include <stdio.h> #include <stdlib.h> #include <omp.h> /** * @brief Illustrates how to get the number of threads. * @details This code prints the number of threads at two specific locations: * 1) Outside an OpenMP parallel region * 2) Inside an OpenMP parallel region **/ int main(int argc, char* argv[]) { // Tell OpenMP to use 4 threads in parallel regions omp_set_num_threads(4); // 1) Outside the OpenMP parallel region printf("Outside the OpenMP parallel region, we are %d threads.\n", omp_get_num_threads()); // Create the OpenMP parallel region, which will contain 4 threads #pragma omp parallel { // 2) Inside the OpenMP parallel region printf("Inside the OpenMP parallel region, we are %d threads.\n", omp_get_num_threads()); } return EXIT_SUCCESS; }
https://www.rookiehpc.com/openmp/docs/omp_get_num_threads.php
CC-MAIN-2019-43
refinedweb
176
56.05
Wei Liu writes ("Re: [PATCH 10/12] tools/libfsimage: Add `xen' to .h names and principal .so name"): > On Fri, Oct 12, 2018 at 04:12:13PM +0100, Ian Jackson wrote: > > `fsimage' is rather general. And we do not expect this library to be > > very useful out of tree because of its unstable ABI. > > > > So add the word `xen'. This will avoid naming conflicts with anyone > > else's fsimage library. > > > > Signed-off-by: Ian Jackson <ian.jackson@xxxxxxxxxxxxx> > > Acked-by: Wei Liu <wei.liu2@xxxxxxxxxx> > > I think we will need another upgrade note for 4.12. Sure, if you think so. Juergen, something like: * The fsimage library used by pygrub, which does not have a stable ABI, and the corresponding python module, have been renamed to `xenfsimage' (to reduce namespace pollution). Any out-of-tree users of this library will have to be updated..
https://old-list-archives.xen.org/archives/html/xen-devel/2018-10/msg01099.html
CC-MAIN-2021-49
refinedweb
144
77.43