text
stringlengths
20
1.01M
url
stringlengths
14
1.25k
dump
stringlengths
9
15
lang
stringclasses
4 values
source
stringclasses
4 values
0 Can someone help me with this code.. I get an error when I try to execute it from graphics import * def main(): colour = raw_input("Enter the colour: ") win = GraphWin("Patch", 200, 200) drawCircle(win, 50, 50, colour) def drawCircle(win, x, y, colour): for i in range(5): for j in range(5): if (i + j) % 2 == 0: topLeftX = x + i * 20 topLeftY = y + j * 20 circle = Circle(Point(topLeftX, topLeftY), Point(topLeftX + 20, topLeftY + 20)) circle.setFill(colour) circle.draw(win) main() Edited by gangster88: n/a
https://www.daniweb.com/programming/software-development/threads/292128/graphics-py
CC-MAIN-2017-39
en
refinedweb
I have an array like this: A = array([1,2,3,4,5,6,7,8,9,10]) B = array([[1,2,3], [2,3,4], [3,4,5], [4,5,6]]) width = 3 # fixed arbitrary width length = 10000 # length of A which I wish to use B = A[0:length + 1] for i in range (1, length): B = np.vstack((B, A[i, i + width + 1])) Actually, there's an even more efficient way to do this... The downside to using vstack etc, is that you're making a copy of the array. Incidentally, this is effectively identical to @Paul's answer, but I'm posting this just to explain things in a bit more detail... There's a way to do this with just views so that no memory is duplicated. I'm directly borrowing this from Erik Rigtorp's post to numpy-discussion, who in turn, borrowed it from Keith Goodman's Bottleneck (Which is quite useful!). The basic trick is to directly manipulate the strides of the array (For one-dimensional arrays): import numpy as np def rolling(a, window): shape = (a.size - window + 1, window) strides = (a.itemsize, a.itemsize) return np.lib.stride_tricks.as_strided(a, shape=shape, strides=strides) a = np.arange(10) print rolling(a, 3) Where a is your input array and window is the length of the window that you want (3, in your case). This yields: [[0 1 2] [1 2 3] [2 3 4] [3 4 5] [4 5 6] [5 6 7] [6 7 8] [7 8 9]] However, there is absolutely no duplication of memory between the original a and the returned array. This means that it's fast and scales much better than other options. For example (using a = np.arange(100000) and window=3): %timeit np.vstack([a[i:i-window] for i in xrange(window)]).T 1000 loops, best of 3: 256 us per loop %timeit rolling(a, window) 100000 loops, best of 3: 12 us per loop If we generalize this to a "rolling window" along the last axis for an N-dimensional array, we get Erik Rigtorp's "rolling window" function: w. Examples -------- >>> x=np.arange(10).reshape((2,5)) >>> rolling_window(x, 3) array([[[0, 1, 2], [1, 2, 3], [2, 3, 4]], [[5, 6, 7], [6, 7, 8], [7, 8, 9]]]) Calculate rolling mean of last dimension: >>> np.mean(rolling_window(x, 3), -1) array([[ 1., 2., 3.], [ 6., 7., 8.]]) """) So, let's look into what's going on here... Manipulating an array's strides may seem a bit magical, but once you understand what's going on, it's not at all. The strides of a numpy array describe the size in bytes of the steps that must be taken to increment one value along a given axis. So, in the case of a 1-dimensional array of 64-bit floats, the length of each item is 8 bytes, and x.strides is (8,). x = np.arange(9) print x.strides Now, if we reshape this into a 2D, 3x3 array, the strides will be (3 * 8, 8), as we would have to jump 24 bytes to increment one step along the first axis, and 8 bytes to increment one step along the second axis. y = x.reshape(3,3) print y.strides Similarly a transpose is the same as just reversing the strides of an array: print y y.strides = y.strides[::-1] print y Clearly, the strides of an array and the shape of an array are intimately linked. If we change one, we have to change the other accordingly, otherwise we won't have a valid description of the memory buffer that actually holds the values of the array. Therefore, if you want to change both the shape and size of an array simultaneously, you can't do it just by setting x.strides and x.shape, even if the new strides and shape are compatible. That's where numpy.lib.as_strided comes in. It's actually a very simple function that just sets the strides and shape of an array simultaneously. It checks that the two are compatible, but not that the old strides and new shape are compatible, as would happen if you set the two independently. (It actually does this through numpy's __array_interface__, which allows arbitrary classes to describe a memory buffer as a numpy array.) So, all we've done is made it so that steps one item forward (8 bytes in the case of a 64-bit array) along one axis, but also only steps 8 bytes forward along the other axis. In other words, in case of a "window" size of 3, the array has a shape of (whatever, 3), but instead of stepping a full 3 * x.itemsize for the second dimension, it only steps one item forward, effectively making the rows of new array a "moving window" view into the original array. (This also means that x.shape[0] * x.shape[1] will not be the same as x.size for your new array.) At any rate, hopefully that makes things slightly clearer..
https://codedump.io/share/R77wDeOrAj4m/1/efficient-numpy-2d-array-construction-from-1d-array
CC-MAIN-2017-39
en
refinedweb
XChangePointerDevice man page XChangePointerDevice — change which device is the X pointer Synopsis #include <X11/extensions/XInput.h> Status XChangePointerDevice( Display *display, XDevice *device, int xaxis, int yaxis); display Specifies the connection to the X server. device Specifies the device to be used as the X pointer. xaxis Specifies the axis of the device to be used as the X pointer x-axis. yaxis Specifies the axis of the device to be used as the X pointer y-axis. Description. Diagnostics BadDevice An invalid device was specified. The specified device does not exist, has not been opened by this client via XOpenInputDevice, or is already one of the core X input devices (pointer or keyboard). This error may also occur if the server implementation does not support using the specified device as the X pointer. BadMatch This error may occur if an XChangePointerDevice request was made specifying a device that has less than two valuators, or specifying a valuator index beyond the range supported by the device. See Also XChangeKeyboardDevice(3) Referenced By XChangeKeyboardDevice(3). 03/09/2013
https://www.mankier.com/3/XChangePointerDevice
CC-MAIN-2017-39
en
refinedweb
17 June 2009 17:14 [Source: ICIS news] By Nigel Davis LONDON (ICIS news)--It’s all about building trust: trust in the science and trust in the regulatory environment that ultimately protects citizens from the excesses that companies might be prone to. Two events this week have highlighted the challenges that emerging nanotechnology-based businesses present to companies, regulators and, possibly, investors in those companies. The results of ?xml:namespace> Industry largely believes that the initiative, which has looked at the potential impact of nanomaterials on health and the environment, has been a success. “The results obtained by NanoCare so far indicate that no additional safety measures are required for the newly researched materials, compared to the already highly researched comparative materials, for which a broader database exists,” said the head of innovation management in Evonik’s chemistry business, Peter Nagler, on Tuesday. Nagler was talking about specific materials but his company believes that NanoCare has significantly broadened knowledge about evaluating nanomaterials. Methods have been developed to measure nanoparticles in the workplace. The project has helped standardise international testing and data provided to Organization for Economic Cooperation and Development (OECD) to help improve internationally recognised test strategies. Nanotechnology, the science of the very small, is helping companies produce novel materials and products of all sorts with exceptional properties. Analytical techniques based on nanotechnology are opening up new avenues for testing and research in materials and medicine. Vast sums are being poured into nanotechnology research by countries and companies keen to steal a march on global competitors producing products as diverse as advanced materials, food supplements, biocides and sunscreens. At the sub-micron scale the physical properties of materials are very different. And there is growing concern with the physiological affects of nanomaterials. Evonik has considerable experience in materials production and handling and has lent that knowledge to the NanoCare project, which has involved 15 companies, universities and research centres. The company provided its well researched “comparative” materials titanium oxide and carbon black, as well as new nanomaterials such as zirconium oxide, cerium oxide, mixed oxides, and various new surface-modified particles. Evonik’s analytical services centre, AQura, provided NanoCare with expertise in the chemical-physical characterisation of particles and in measuring nanoparticles in the workplace. And the company opened its factory gates to independent specialists who wanted to take measurements in the workplace. For Evonik, nanotechnology research has provided new battery membranes and cost-effective adhesives. But Nagel recognises public concern over nanomaterials that may have been used for years in some products but are coming under closer scrutiny. As NanoCare reached a conclusion an investor group in the Asbestos litigation is reckoned to have cost insurers around $200bn. Studies show that by 2002 asbestos personal injury claim payouts had reached $70bn and bankrupted 61 companies. The US-based Investor Environmental Health Network (IEHN) highlighted the potential link between nanotech materials and adverse health impacts. A report from the organisation suggested that “regulatory flaws encourage companies to conceal damaging scientific findings from investors, fail to disclose estimates of the range of potential liabilities, and place undue reliance on litigators”. It wants to see the US Financial Accounting Standards Board (FASB) and the Securities Exchange Commission (SEC) improve disclosures made to investors that would help them estimate the possible liabilities that might accrue from products containing nanomaterials. “Investors should be better apprised by companies of the state of the science, including the important health impact questions that have not yet been answered,” it says. The trouble is that the controversy surrounding nanotechnology is leading companies to keep quiet on which of their products contain nanomaterials. Both the consumer, and, as the IEHN would have it, the investor, are being kept in the dark. Chemicals producers do not stand aloof from this trend but have the expertise to bring informed commentary to the debate. And they owe it to their employees and their customers to advance the science and our understanding of the potential health impacts of the materials they produce. Nagler is convinced that products based on nanotechnology will find wider use only if the industry seriously considers the social discourse on opportunity and risk and communicates the new technology and its benefits to a broad public, Evonik says. “We have committed ourselves to applying nanotechnology responsibly, and this is why we’re taking part in NanoCare,” he
http://www.icis.com/Articles/2009/06/17/9225717/insight-caring-about-nanotechnology.html
CC-MAIN-2014-52
en
refinedweb
1.What is use of function overloading? 2.What is main difference between function overloading and overriding? 3.what is output of this coding? public class first { public void display() Response.write("Base class"); } public class second:first response.write("derived class");} main second obj = new second(); obj.display() what is output of this? 5.what is use of css? 6.why should use the class?what are the benifit of class? using System;class Overload{ static void Main() { myFunc(); myFunc( 1); } static void myFunc() { Console.WriteLine("I got no parameters"); } static void myFunc( int n) { Console.WriteLine( "I got the number {0}", n); }} override eampleusing using In programming, using the same name for two or more functions. The compiler determines which function to use based on the type of function, arguments passed to it and type of values returned. Output: derived class Because Here it has override method define in baseclass A method used to attach styles such as specific fonts, colors, and spacing to HTML documents. Because they "cascade," some elements take precedence over others. A with the integer data, other can deal float for precision etc., Overriding :Directs PB to deviate from its normal execution sequence. Both functions and events can be overridden. Function Overriding : A descendant function has the same function signature as an ancestor function. The descendant function is executed instead of the ancestor function. Event overriding : A descendant has the Override Ancestor Script option checked. Go thr this links to know more abt Overriding; Diff bet Both; Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism. Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method. OUTPUT : derived class as the object is of derived class it will call the function of derived. CSS: sites, in the section on cascade and inheritance. There are plenty of other advantages, too. We return to this issue in more detail in the section of the guide. For now though, let's find out what a style sheet actually is and how it performs all these miracles. CLASS:. There are many Adavantages of Class; You can have resuability of all the methods n properties.You can acheive Polymorohism, Inheritance, Encapsulation with class.You can speed u application usig class.You can save memory. Best Luck!!!!!!!!!!!!!!!!!Sujit.
http://www.nullskull.com/q/10046274/oops-concept.aspx
CC-MAIN-2014-52
en
refinedweb
Abstract piracy. Security engineers have made an effort to resist disassembling techniques, including software watermarking, code obfuscation, in the context of Java bytecode disassembling. A huge allotment of this paper is dedicated to tactics that are commonly considered to be reverse engineering. The methods presented here, however, are intended for professional software developers and each technique is based on custom created application. We are not encouraging any kind of malicious hacking approach by presenting this article; in fact the contents of this paper help to pinpoint the vulnerability in the source code and learn the various methods developers can use in order to shield their intellectual property from reverse engineering. We shall explain the process of disassembling in terms of obtaining sensitive information from source code and cracking a Java executable without having the original source code. Prerequisite I presume that the aspirant would have thorough understanding of programming, debugging and compiling in JAVA on various platforms such as Linux and Windows and, of course, knowledge of JVM’s inner workings. Apart from that, the following tools are required to manipulate bytecode reverse engineering; - JDK Toolkit (Javac, javap) - Eclipse - JVM - JAD Fill out the Form Below to Download the Accompanying Lab Files. Java Bytecode Engineers usually construct software in a high-level language such as Java, which is comprehensible to them but which in fact, cannot be executed by the machine directly. Such a textual form of a computer program, known as source code, is converted into a form that the computer can directly execute. Java source code is compiled into an intermediate language known as Java bytecode, which is not directly executed by the CPU but rather, is executed by a Java virtual machine (JVM). Compilation is typically the act of transforming a high-level language into a low-level language such as machine code or bytecode. We do not need to understand Java bytecode, but doing so can assist debugging and can improve performance and memory convention. The JVM is essentially a simple stack-based machine that can be separated into a couple of segments; for instance, stack, heap, registers, method area, and native method stacks. An advantage of the virtual machine architecture is portability: Any machine that implements the Java virtual machine specification is able to execute Java bytecode in a manner of “Write once, run anywhere.” Java bytecode is not strictly linked to the Java language and there are many compilers, and other tools, available that produce Java bytecode, such as the Eclipse IDE, Netbeans, and the Jasmin bytecode assembler. Another advantage of the Java virtual machine is the runtime type safety of programs. The Java virtual machine defines the required behavior of a Java virtual machine but does not specify any implementation details. Therefore the implementation of the Java virtual machine specification can be designed different ways for diverse platforms as long as it adheres to the specification. Sample Cracked Application The subsequent Java console application “LoginTest” is developed in order to explain Java bytecode disassembling. This application typically tests valid users by passing them through a simple login user name and password mechanism. We have got this application from other resources as an unregistered user and obviously we don’t possess the source code of this application. As a result, we do not know a valid user name and password, which are only provided to the registered user. Without having the source code of the application or login credential sets, we still can manage to login into this mechanism, by disassembling its bytecode where we can expose sensitive information related to user login. Disassemble Bytecode Disassembling is the reverse approach, due to the standard and well-documented structure of bytecode, which is an act of transforming a low-level language into a high-level language. It basically generates the source code from Java bytecode. We typically run a disassembler to obtain the source code for the given bytecode, just as running a compiler yields bytecode from the source code. Disassembling is utilized to ascertain the implementation logic despite the absence of the relevant documentation and the source code, which is why vendors explicitly prohibit disassembling and reverse engineering in the license agreement. Here are some of the reasons to decompile: - Fixing critical bugs in the software for which no source code exists. - Troubleshooting a software or jar that does not have proper documentation. - Recovering the source code that was accidentally lost. - Learning the implementation of a mechanism. - Learning to protect your code from reverse engineering. The process of disassembling Java bytecode is quite simple, not as complex as native c/c++ binary. The first step is to compile the Java source code file, which has the *.java extension through javac utility that produce a *.class file from the original source code in which bytecode typically resides. Finally, by using javap, which is a built-n utility of the JDK toolkit, we can disassemble the bytecode from the corresponding *.class file. The javap utility stores its output in *.bc file. Opening a *.class file does not mean that we access the entire implementation logic of a mechanism. If we try to open the generated bytecode file through notepad or any editor after compiling the Java source code file using javac utility, we surprisingly find some bizarre or strange data in the class file which are totally incomprehensible. The following figure displays the .class files data: So the idea of opening the class file directly isn’t at all successful, hence we shall use WinHex editor to disassemble the bytecode, which will produce the implementation logic in hexadecimal bytes, along with the strings that are manipulated in the application. Although we can reverse engineer or reveal sensitive information of a Java application using WinHex editor, this operation is sophisticated because unless we have the knowledge to match the hex byte reference to the corresponding instructions in the source code we can’t obtain much_4<< Reversing Bytecode It is relatively easy to disassemble the bytecode of a Java application, compared to other binaries. The javap in-built utility that ships with the JDK toolkit plays a significant role in disassembling Java bytecode, as well as helping to reveal sensitive information. It typically accepts a *.class file as an argument, as following: Drive:> Javap LoginTest Once this command is executed, it shows the real source code behind the class file; but remember one thing: It does display only the methods signature used in the source code, as follows: Compiled from “LoginTest.java” public class LoginTest { public LoginTest(); public static void main(java.lang.String[]); static boolean verify(java.lang.String, char[]); } The entire source code of the Java executable, even if it contains methods related to opcodes, would be showcased by the javap –c switch, as following: Drive:> Javap –c LoginTest This command dumps the entire bytecode of the program in the form of a special opcode instruction. The meaning of each instruction in the context of this program will be explained in a later section of this paper. I have highlighted the important section, from which we can obtain critical information. Compiled from "LoginTest.java" public class LoginTest { public LoginTest(); Code: 0: aload_0 1: invokespecial #1 // Method java/lang/Object."<init>":()V 4: return public static void main(java.lang.String[]); Code: 0: invokestatic #2 // Method java/lang/System.console:()Ljava/io/Console; 3: astore_1 4: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 7: ldc #4 // String Login Verification 9: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 12: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 15: ldc #6 // String ************************ 17: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 20: aload_1 21: ldc #7 // String Enter username: 23: iconst_0 24: anewarray #8 // class java/lang/Object 27: invokevirtual #9 // Method java/io/Console.printf:(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/Console; 30: pop 31: aload_1 32: invokevirtual #10 // Method java/io/Console.readLine:()Ljava/lang/String; 35: astore_2 36: aload_1 37: ldc #11 // String Enter password: 39: iconst_0 40: anewarray #8 // class java/lang/Object 43: invokevirtual #9 // Method java/io/Console.printf:(Ljava/lang/String;[Ljava/lang/Object;)Ljava/io/Console; 46: pop 47: aload_1 48: invokevirtual #12 // Method java/io/Console.readPassword:()[C 51: astore_3 52: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 55: ldc #13 // String ------------------------- 57: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 60: aload_2 61: aload_3 84: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 87: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 90: ldc #13 // String ------------------------- 92: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 95: getstatic #3 // Field java/lang/System.out:Ljava/io/PrintStream; 98: ldc #17 // String !!!Thank you!!! 100: invokevirtual #5 // Method java/io/PrintStream.println:(Ljava/lang/String;)V 103: return … } From line 62, we can easily conclude that the login mechanism is implemented using a method called verify that typically checks either the user-entered username and password. If the user enters the correct password, then the “Login success” message flashes, otherwise: But still we are unable to grab the username and password information. But, if we analyze the verify methods instruction, we can easily find that the username and password are hard-coded in the code itself, highlighted in the colored box as following: static boolean verify(java.lang.String, char[]); Code: 0: new #18 // class java/lang/String 3: dup 4: aload_1 5: invokespecial #19 // Method java/lang/String."<init>":([C)V 8: astore_2 9: aload_0 10: ldc #20 // String ajay 12: invokevirtual #21 // Method java/lang/String.equals:(Ljava/lang/Object;)Z 15: ifeq 29 18: aload_2 19: ldc #22 // String test 21: invokevirtual #21 // Method java/lang/String.equals:(Ljava/lang/Object;)Z 24: ifeq 29 27: iconst_1 28: ireturn 29: iconst_0 30: ireturn } We finally come to the conclusion that this program accepts ajay as the username and test as the password, which is mentioned in the ldc instruction. Now launch the application once again and enter the aforesaid credentials. Bingo!!!! We have successfully subverted the login authentication mechanism without even having the source code: Bytecode Instruction Specification Like Assembly programming, Java machine code representation is done via bytecode opcodes, which are the forms of instruction that the JVM executes on any platform. Java bytecodes typically offer 256 diverse mnemonic and each is one byte in length. Java bytecodes instructions fall into these major categories: - Load and store - Method invocation and return - Control transfer - Arithmetical operation - Type conversion - Object manipulation - Operand stack management We shall only discuss the opcode instructions that are used in the previous Java binary. The following table illustrates the usage meanings as well as the corresponding hex value: In Brief This paper illustrates the mechanism of disassembling Java bytecode in order to reveal sensitive information when you do not have the source of the Java binary. We have come to an understanding of how to implement such reverse engineering tactics by using JDK utilities. This article also unfolds the importance of bytecode disassembling and JVM internal workings in the context of reverse bytecode and it also explains the meaning of essential bytecode opcode in detail. Finally, we have seen how to subvert login authentication on a live Java console application by applying disassembly tactics. In the forthcoming paper, we shall explain how to patch Java bytecode in the context of revere engineering. Reference Sir, I am very new to Java Bytecode.As you know , we can view the strings from class files. I need to do the encryption or obfuscation of strings though program. How i can use BCEL library for this? Any Suggestion.
http://resources.infosecinstitute.com/java-bytecode-reverse-engineering/
CC-MAIN-2014-52
en
refinedweb
You can subscribe to this list here. Showing 4 results of 4 09:02:26AM -0700, Neil Watkiss wrote: | 4.3.5 |^html is a 404. | Did you mean '#', not '$'? The above URI is not intended to be a general HTTP URL with a #fragment Instead, this example is intended to demonstrate how XML namespace/name pair (qname) can be encoded as a YAML type family. The suggested mapping is to take the XML namespace and appending $ and then appending the XML tagname. Since XML namespaces are valid URIs, and since $ is a valid URI character, and since XML tagnames (mod ascii) are also valid within a URI, the result is a valid URI, and thus a YAML type family. Furthermore, since the dollar sign($) is not a valid character for XML tag names, this is even a reversable mapping! Thus, the example demonstrates how one could encode XML qualified names using the YAML type family mechanism; for a proper XML mapping, what remains is a method to map attributes/elements on to the structural constraints of YAML (Don Park's rythemic embedding is one possiblity; relax's element/attribute ismorphism is another ) Perhaps this example should be framed better to that the intent is more transparent, or it should be removed altogether to avoid confusion? | [Of course, this is just nits in the _spec_. I haven't worked through the | structural changes themselves.] The structural changes are bound to have a few bugs in them. Thank you so much for your careful review. ;) Clark -- Clark C. Evans Axista, Inc. 800.926.5525 XCOLLA Collaborative Project Management Software Oren Ben-Kiki [25/06/02 17:14 -0400]: > :-). Some nits: 4.3.5^html is a 404. Did you mean '#', not '$'? Actually, that's all I can spot right now. It looks really very good! [Of course, this is just nits in the _spec_. I haven't worked through the structural changes themselves.] Later, Neil YAML.pm version 0.35 is on the CPAN now. This version reflects many of the changes in the spec, adds over 200 new tests, and dumps even more Perl data structures. Enjoy. Clark, please add this to the YAML front page. Cheers, Brian PS Could we change the refcard colors from grey on gray to black on white?
http://sourceforge.net/p/yaml/mailman/yaml-core/?viewmonth=200206&viewday=27
CC-MAIN-2014-52
en
refinedweb
Data. At SundayMorningRides.com, we manage a growing inventory of GPS and general GIS (Geography Information Systems) data and web content (text, images, videos, etc.) for the end users. In addition, we must also effectively manage daily snapshots, backups, as well as multiple development versions of our web site and supporting software. For any small organization, this can add up to significant costs -- not only as an initial monetary investment but also in terms of ongoing labor costs for maintenance and administration. Amazon Simple Storage Service (S3) was released specifically to address the problem of data management for online resources -- with the aim to provide "reliable, fast, inexpensive data storage infrastructure that Amazon uses to run its own global network of web sites." Amazon S3 provides a web service interface that allows developers to store and retrieve any amount of data. S3 is attractive to companies like SundayMorningRides.com as it frees us from upfront costs and the ongoing costs of purchasing, administration, maintenance, and scaling our own storage servers. This article covers the Perl, REST, and the Amazon S3 REST module, walking through the development of a collection of Perl-based tools for UNIX command-line based interaction to Amazon S3. I'll also show how to set access permissions so that you can serve images or other data directly to your site from Amazon S3. A Bit on Web Services Web services have become the de-facto method of exposing information and, well, services via the Web. Intrinsically, web services provide a means of interaction between two networked resources. Amazon S3 is accessible via both Simple Object Access Protocol (SOAP) or representational state transfer (REST). The SOAP interface organizes features into custom-built operations, similar to remote objects when using Java Remote Method Invocation (RMI) or Common Object Resource Broker Architecture (CORBA). Unlike RMI or CORBA, SOAP uses XML embedded in the body of HTTP requests as the application protocol. Like SOAP, REST also uses HTTP for transport. Unlike SOAP, REST operations are the standard HTTP operations -- GET, POST, PUT, and DELETE. I think of REST operations in terms of the CRUD semantics associated with relational databases: POST is Create, GET is Retrieve, PUT is Update, and DELETE is Delete. "Storage for the Internet" Amazon S3 represents the data space in three core concepts: objects, buckets, and keys. - Objects are the base level entities within Amazon S3. They consist of both object data and metadata. This metadata is a set of name-attribute pairs defined in the HTTP header. - Buckets are collections of objects. There is no limit to the number of objects in a bucket, but each developer is limited to 100 buckets. - Keys are unique identifiers for objects. Without wading through the details, I tend think of buckets as folders, objects as files, and keys as filenames. The purpose of this abstraction is to create a unique HTTP namespace for every object. I'll assume that you have already signed up for Amazon S3 and received your Access Key ID and Secret Access Key. If not, please do so. Please note that the S3::* modules aren't the only Perl modules available for connecting to Amazon S3. In particular, Net::Amazon::S3 hides a lot of the details of the S3 service for you. For now, I'm going to use a simpler module to explain how the service works internally. Connecting, Creating, and Listing Buckets Connecting to Amazon S3 is as simple as supplying your Access Key ID and your Secret Access Key to create a connection, called here $conn. Here's how to create and list the contents of a bucket as well as list all buckets. #!/usr/bin/perl use S3::AWSAuthConnection; use S3::QueryStringAuthGenerator; use Data::Dumper; my $AWS_ACCESS_KEY_ID = 'YOUR ACCESS KEY'; my $AWS_SECRET_ACCESS_KEY = 'YOUR SECRET KEY'; my $conn = S3::AWSAuthConnection->new($AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY); my $BUCKET = "foo"; print "creating bucket $BUCKET \n"; print $conn->create_bucket($BUCKET)->message, "\n"; print "listing bucket $BUCKET \n"; print Dumper @{$conn->list_bucket($BUCKET)->entries}, "\n"; print "listing all my buckets \n"; print Dumper @{$conn->list_all_my_buckets()->entries}, "\n"; Because every S3 action takes place over HTTP, it is good practice to check for a 200 response. my $response = $conn->create_bucket($BUCKET); if ($response->http_response->code == 200) { # Good } else { # Not Good } As you can see from the output, the results come back in a hash. I've used Data::Dumper as a convenient way to view the contents. If you are running this for the first time, you will obviously not see anything listed in the bucket. listing bucket foo $VAR1 = { 'Owner' => { 'ID' => 'xxxxx', 'DisplayName' => 'xxxxx' }, 'Size' => '66810', 'ETag' => '"xxxxx"', 'StorageClass' => 'STANDARD', 'Key' => 'key', 'LastModified' => '2007-12-18T22:08:09.000Z' }; $VAR4 = ' '; listing all my buckets $VAR1 = { 'CreationDate' => '2007-11-28T17:31:48.000Z', 'Name' => 'foo' }; '; Writing an Object Writing an object is simply a matter of using the HTTP PUT method. Be aware that there is nothing to prevent you from overwriting an existing object; Amazon S3 will automatically update the object with the more recent write request. Also, it's currently not possible to append to or otherwise modify an object in place without replacing it. my %headers = ( 'Content-Type' => 'text/plain' ); $response = $conn->put( $BUCKET, $KEY, S3Object->new("this is a test"), \%headers); Likewise, you can read a file from STDIN: my %headers; FILE: while(1) { my $n = sysread(STDIN, $data, 1024 * 1024, length($data)); if ($n < 0) { print STDERR "Error reading input: $!\n"; exit 1; } last FILE if $n == 0; } $response = $conn->put("$BUCKET", "$KEY", $data, \%headers); To add custom metadata, simply add to the S3Object: S3Object->new("this is a test", { name => "attribute" }) By default, every object has private access control when written. This allows only the user that stored the object to read it back. You can change these settings. Also, note that each object can hold a maximum of 5 GB of data. You are probably wondering if it is also possible to upload via a standard HTTP POST. The folks at Amazon are working on it as we speak -- see HTTP POST beta discussion for more information. Until that's finished, you'll have to perform web-based uploads via an intermediate server. Reading an Object Like writing objects, there are several ways to read data from Amazon S3. One way is to generate a temporary URL to use with your favorite client (for example, wget or Curl) or even a browser to view or retrieve the object. All you have to do is generate the URL used to make the REST call. my $generator = S3::QueryStringAuthGenerator->new($AWS_ACCESS_KEY_ID, $AWS_SECRET_ACCESS_KEY); ...and then perform a simple HTTP GET request. This is a great trick if all you want to do is temporarily view or verify the data. $generator->expires_in(60); my $url = $generator->get($BUCKET, "$KEY"); print "$url \n"; You can also programmatically read the data directly from the initial connection. This is handy if you have to perform additional processing of the data. my $response = $conn->get("$BUCKET", "$KEY"); my $data = $response->object->data; Another cool feature is the ability to use BitTorrent to download files from Amazon S3 . You can access any object that has anonymous access privileges via BitTorrent. Delete an Object By now you probably have the hang of the process. If you're going to create objects, you're probably going to have to delete them at some point. $conn->delete("$BUCKET", "$KEY"); Set Access Permissions and Publish to a Website As you may have noticed from the previous examples, all Amazon S3 objects access goes through HTTP. This makes Amazon S3 particularly useful as a online repository. In particular, it's useful to manage and serve website media. You could almost imagine Amazon S3 serving as mini Content Delivery Network for media on your website. This example will demonstrate how to build a very simple online page where the images are served dynamically via Amazon S3. The first thing to do us to upload some images and set the ACL permissions to public. I've modified the previous example with one difference. To make objects publicly readable, include the header x-amz-acl: public-read with the HTTP PUT request. my %headers = ( 'x-amz-acl' => 'public-read', ); Additional ACL permissions include: - private (default setting if left blank) - public-read - public-read-write - authenticated-read Now you know enough to put together a small script that will automatically display all images in the bucket to a web page (you'll probably want to spruce up the formatting). ... my $<br />"; } ($webpage = <<"WEBPAGE"); <html><body>$images</body></html> WEBPAGE print $q->header(); print $webpage; To add images to this web page, upload more files into the bucket and they will automatically appear the next time you load the page. It's also simple to link to media one at a time for a webpage. If you examine the HTML generated by this example, you'll see that all Amazon S3 URLs have the basic form. Also note that the namespace for buckets is shared with all Amazon S3 users. You may have already picked up on this. Conclusion Amazon S3 is a great tool that can help with the data management needs of all sized organizations by offering cheap and unlimited storage. For personal use, it's a great tool for backups (also good for organizations) and general file storage. It's also a great tool for collaboration. Instead of emailing files around, just upload a file and set the proper access controls -- no more dealing with 10 MB attachment restrictions! At SundayMorningRides.com we use S3 as part of our web serving infrastructure to reduce the load on our hardware when serving media content. When combined with other Amazon Web Services such as SimpleDB (for structured data queries) and Elastic Compute Cloud (for data processing) it's easy to envision a low cost solution for web-scale computing and data management.
http://www.perl.com/pub/web-development/
CC-MAIN-2014-52
en
refinedweb
>>. 86 Reader Comments Yea because obviously there are 2 people, see that guy in the background? Disclosure: Left there already myself (cancelled my subscription > a month ago) and I don't think there's any "new" content that would be able to draw me back in. -Erickson If you knew this was going to happen, even going so far as to label it a classic MMO problem, then why in the hell were you not prepared with transfers or mergers after 4 months? Where you so certain that this game would grow instead of decline that you had no plan B? And as far as his lies about subscriptions, you don't give your customers a free month unless something has seriously jumped the shark.. The trick is to release significant/quality content at a fast enough frequency that people stay subscribed in anticipation of the new stuff. That's why Blizzard has been releasing content in "tiers" at fairly regular intervals between expansions. It keeps players better engaged (and subscribed). Last edited by chordoflife on Tue Apr 24, 2012 11:01 am Not necessarily. I'm playing less now because I'm splitting my time between SWTOR and Star Trek Online. I might only be on every other night (cutting my server time in half) but I'm not quitting any time soon. I'm still working on the 4 Republic class stories, after which I'll still have the 4 Empire stories to play through. Last edited by DaveSimmons on Tue Apr 24, 2012 10:56 am I don't find this article surprising, or how they responded. Did anyone really expect them to own up and admit things aren't going as well as they planned. Making any statement verifying player/sub decline would just add more fuel to the fire. One only has to look at how WAR was handled to be able to predict the future. Last edited by Incendium on Tue Apr 24, 2012 10:59 am. Same for me. I hit 50, PVP was most stale and boring PVP ive ever partaken in. And raids were pretty damn boring. Now. Wheres that Guild Wars 2 coverage?? Beta weekend this weekend!! People log in less to established games than new ones, that's just how it works. It's a rare person who can keep up 40-60 hour a week playtimes for months on end. The only issue is that server populations were "set" based on the new game "OMG I have to play!" crush at the beginning, and now that there is a more sustainable amount of concurrent users, everyone is too spread out. Transfers, and probably shutting down some of the least populated servers will fix that. They are doing the Australian transfers this week, so more general transfers are not too far away. They know how many people have unsubscribed, regardless of how much game time they have left. Also, for an MMO, they sure seem to make it difficult to actually get a group of people into an FP. So and so is on another quest stage, so and so isn't eligible for this quest, umpteen different NPC to talk to before you can start an FP...by the time that is all sorted, quests reset/dropped, half the group has gone to do something else and the other half is annoyed enough that they are considering it as well.. Last edited by Xavin on Tue Apr 24, 2012 11:05 am. Anarchy Online, if anyone recall that game (it is still running last time i checked), also have such a system. You can play with some dials and the system spits out some missions that you can pick from. Each play out on a random map accessed via a location that may require some travel from where your currently located. For the majority of the FPs, you just need to talk to the guy at the door, the breadcrumb and framing quests are optional. There are a few exceptions for the first run through specific FPs, but those are well known at this point. The only FP that I can think of that requires a breadcrumb is the Boarding Party/Foundry sequence and the start of that is by the place where you have to go to travel to the other ship to get to the FP entrance itself and the guy to talk to is just 50' from the entrance. If there's a conflict because someone else left in the middle of a different instance, just resetting works. It sounds like you got tangled up with people who didn't have a clue how any of that stuff works and fumbled around for a while. The worst case scenario is that it takes about a minute to sort out.. The dailies are my biggest complaint. My first character was a healer spec Sage and the dailies were far from painless. From encounters that shredded Qyzen to large encounters, the only way I could do them efficiently, or in some cases at all, was to group with other players. It sucked so bad that I haven't played my Sage in almost two months because of it. I know they adjusted some of them in 1.2 but I haven't been back to check... I'm having too much fun on my Assassin, Marauder, and Operative. They know who's subscribed and who's not. However there is some amount of inertia when it comes to unsubbing from a game and I suspect that many people don't actually unsubscribe until they realise that they don't play the game for more than a month at a time. Some people I know just keep themselves subscribed even if they don't really play - they log in every couple of weeks to do auctions and read mail or something but they don't really think about how they need to actually unsubscribe. Also, SW:TOR had tons. and tons, and tons of servers at launch. The distribution was such that there were some really really heavy servers, a lot of medium servers, and a handful of light servers. I think it's annoying that somehow server mergers have been seen as some kind of kiss of death on MMORPGs because they would often solve tons of problems. Really? The non-heroic daily mobs are pretty much tissue paper on the Imperial side. > Really? The non-heroic daily mobs are pretty much tissue paper on the Imperial side. One of the ones on Belsavis required you to kill some stuff outside, some lone silvers/tough mobs, like within 100yds of where you got the quest, that had a point-blank AOE that would kill Qyzen in two shots (about 8 seconds). It was bad enough that I couldn't do anything but try to keep Qyzen alive while he tried to kill the target. If I screwed up and got agro, we both died because I couldn't keep up with healing the both of us. Usually, Qyzen couldn't kill it fast enough before I ran out of Force. If something happened and I agro'd two of them, it was a run away or die situation. Even me and my friend with his Shadow had a hard time with them. We'd end up with about 20% health each at the end of fighting one of them. I think we had to kill like 6 of them or something. It's been so long that I can't remember. It's probably THE daily that broke me on that character. I ran the dailies about a half dozen times and basically said "no more dailies". I haven't done any of those on the Imperial side. The only PVE dailies I run are the daily "do a hard mode FP" ones.. Yeup. That plus a pretty interesting system for providing player-written content, including a mechanism for discoveries, reviews, and a "tip jar", make me think it's an MMO that might possibly not be doomed. And even if people haven't quit yet, they're not logging in. That's the step before they decide its time to quit. Considering a major patch just hit and people still aren't playing? That's an indicator of a downward trend. These days i wonder why any MMO i set up with a fixed number of servers, rather than using something like Amazon EC2 to spin up or down servers as the login numbers climb and fall. As for the whole stock split thing, each time i hear about it being used for anything like a indicator of actual business performance i get shivers. Wait until 1.2 novelty wears off and april subs end... No discounts for multi month subscriptions also was a bad move. WoW drops to $12 if you pay 6 months at a time, but there was virtually no benefit to paying for more time and got no discounts. EA's greed shines through. Regardless: first, people leave. Then, people cancel. You must login or create an account to comment.
http://arstechnica.com/gaming/2012/04/bioware-old-republic-subscribers-not-dropping-despite-lighter-server-loads/?comments=1&post=22790714
CC-MAIN-2014-52
en
refinedweb
I’ve been trying to learn how things work on Windows based on whether you write code in C# or C++, target a 32- or 64-bit platform, and produce files with either native code or one of the CLR options. One of my focuses is the interaction between exes and dlls. I think I’ve got things mostly straightened out, so this is what I’ve learned. First, the basics: a 32-bit platform can run 32-bit apps, but not 64-bit apps. A 64-bit platform can run either, but 32-bit apps run in an emulation environment called WOW64 (Windows on Windows 64). When Windows starts your app, it decides whether WOW64 is necessary. You can tell whether your app is running in WOW64 using this C++ code: #include "stdafx.h" #include <windows.h> typedef BOOL (WINAPI *LPFN_ISWOW64PROCESS) (HANDLE, PBOOL); LPFN_ISWOW64PROCESS fnIsWow64Process; BOOL isWow64() { BOOL ret = FALSE; fnIsWow64Process = (LPFN_ISWOW64PROCESS)GetProcAddress( GetModuleHandle(TEXT("kernel32")), "IsWow64Process"); if (NULL != fnIsWow64Process) { if (!fnIsWow64Process(GetCurrentProcess(), &ret)) { printf("Got some error\n"); } } return ret; } int _tmain(int argc, _TCHAR* argv[]) { if (isWow64()) { printf("Running under WOW64.\n"); } else { printf("NOT running under WOW64.\n"); } scanf("press return"); return 0; } It’s easy enough to call isWow64 from C#, like so: [DllImport]("IsWow64Dll.dll")] static extern bool isWow64(); static void Main(String[] args) { Console.WriteLine(isWow64().ToString()); Console.ReadLine(); } Visual Studio lets you build files for either 32- or 64-bit platforms. I’ve already written how to build for 32 or 64 bits in C++. C# actually provides three options: 32-bits, 64-bits, or “Any CPU.” We can use a tool called corflags to see what results we get depending on which option we choose. Corflags comes with Visual Studio and can be run by choosing the special DOS prompt command under Visual Studio in the Start menu. This is a little different from the regular DOS prompt: it has a specially-tailored environment for running Visual Studio’s command-line utilities. From there, you can ask corflags to report information about any exe or dll, like this: C:\> corflags myapp.exe Microsoft (R) .NET Framework CorFlags Conversion Tool. Version 3.5.21022.8 Copyright (c) Microsoft Corporation. All rights reserved. Version : v2.0.50727 CLR Header: 2.5 PE : PE32 CorFlags : 3 ILONLY : 1 32BIT : 1 Signed : 0 We’re mostly interested in three values: PE, 32BIT, and ILONLY. There is also a line labelled “Signed,” which I’m not interested in right now. Finally, the “CorFlags” line appears to be a combination of the four other values. PE specifies whether or not the file can run on 32-bit platforms. It is either PE32 or PE32+. A PE32+ file cannot run on a 32-bit machine. Next there is the 32BIT flag. This is a little different from PE. If PE indicates whether your app can run as 32 bits, then 32BIT indicates whether it must run as 32 bits. If this flag is 0, your app can run on a 64-bit machine without WOW64. But if the flag is 1, then your app has to run under WOW64. Here is a table showing how the bits are set depending on your compiler’s /platform setting: From this table, you can see that the corflags example above is inspecting a C# app built for the x86 platform. Note that you could never have a file that is PE32+ with the 32BIT flag set, because then one flag would require 32 bits and the other 64. To put all this together, a 32-bit machine can run anything with a PE set to PE32, but nothing with a PE of PE32+. A 64-bit machine can run your file in 64-bit mode as long as 32BIT is 0, but if 32BIT is 1 then it must use WOW64. The ILONLY flag indicates that your file contains only MSIL opcodes (recently renamed to CIL), with no native assembly instructions. A C# app will always have this flag set (unless you use something like ngen to compile down to machine language—an approach with some distribution problems), but a C++ app’s setting depends on your compiler options (described below). When it comes to loading dlls, these flags control whether your app loads the dll successfully or gets a BadImageFormatException. Basically, a 32-bit app can only load 32-bit dlls, and a 64-bit app can only load 64-bit dlls. But what about apps compiled as “Any CPU”? In that case, you can only load dlls matching whatever bitness you’re currently running as. Of course, if you’re running on a 32-bit machine, there is no complication, because everything is 32-bit already. But on a 64-bit machine, you may have problems. Windows will not use WOW64 for your app, because it claims to support 64-bit operation. But if your app has a dependency on a 32-bit dll, then you’ll get a BadImageFormatException, because the 32-bit dll only works in WOW64. The choice to use WOW64 happens only when starting your app. You can’t run an app natively and load just the dlls in WOW64. So you get the exception. The solution is to tell Windows that your app must start in WOW64 from the beginning. You should probably do this by building your app for x86, not Any CPU, but if that is somehow a problem (e.g. you don’t have the code), then you can use corflags to set the 32BIT flag. You just type something like this: corflags /32BIT+ myapp.exe For C++ applications, you can do something similar with the linker’s /clrimagetype flag. Another choice, at least when writing in C++, is how to support the CLR. You can choose among four options: native (the default), /clr, /clr:pure, and /clr:safe. The first one is simple enough: you get a file with machine language instructions. The other three give you a file that is partially or entirely composed of MSIL. Using /clr will produce a CLR header and mostly MSIL code, but with some native code mixed in. Specifically, you get native data types but MSIL functions, unless the function uses something unsupported like function pointers. (Everyday pointers to data are supported.) You can also use #pragma unmanaged to force native code. Because these files have some native code, they must be built for a specific platform, either x86 or x64. The /clr:pure option does what it sounds like: it gives you a file of entirely MSIL. Nonetheless, it must be built for either x86 or x64. This option is said to be equivalent to a C# project with unsafe code. Microsoft’s documentation on the /clr and /clr:pure flags says that they can only produce x86 files, but my tests prove this to be false. If I build the C++ version of the WOW64-tester, using x64 and /clr compilation options, then it reports that it is not running in WOW64. So apparently you can in fact produce x64 applications with these options. The last one, /clr:safe, enforces code that is verifiably type-safe—but I’m not sure what all that means. I’ve read that if you use this option, your file can run on any platform, like building as Any CPU in C#. This option requires that you use Microsoft’s C++/CLI language, formerly known as Managed C++. I know nothing about this, but people say it’s virtually a new language. I tried to build a Hello World app with printf and got innumerable compile errors, so I wasn’t able to run any tests on what this option produces. There is also a /clr:oldSyntax option, which is like /clr:safe but with the old Managed C++ syntax rather than C++/CLI. Since Managed C++ is deprecated, I’m not sure why you’d use this for new code. I don’t know what the /clr* options mean for P/Invoke. If I build a dll with /clr or /clr:pure, does that mean I can call its exported functions from C# without a DllImport statement? I haven’t tried. Using DllImport on these dlls doesn’t cause problems, though. You can use a tool called dumpbin to see which /clr options were used to produce a given file. Dumpbin comes with Visual Studio and runs from the command-line: dumpbin /CLRHEADER myapp.exe This will print (among other things) a Flags value, which is 0 if the file was build with /clr, 1 with /clr:safe, and 3 with /clr:pure. I’m also curious about the interaction between WOW64 and the CLR. If I run a 32-bit C# app on x64, then which comes first: WOW64 or the CLR? Is there a 64-bit CLR that can JIT-compile to either 32- or 64-bit code? Or do I have two CLRs, one for 32 bits and one for 64, and the former runs under WOW64? I suspect the answer is the latter, but I’m not sure how to tell. Either way my code is running in WOW64, so the check I described above won’t tell me anything. I created a table to keep track of the data from all my tests. Here it is:1 There may be some option like the linker’s /CLRHEADER for C# apps.2 Can’t run on x86, and won’t be in WOW64 on x64. But see note 1. There are still some gaps in this table. I’m not that concerned about the interactions between C++ exes and C++ dlls, so I’ve left those cells blank. I’ve also left some cell blanks regarding when C++ files are managed/unmanaged and when they contain an assembly. If I figure any of this out, I’ll update the table. One final notable tool is ildasm (IL-disassembler), which also comes with Visual Studio. This lets you inspect the IL of an exe or dll. Most of it is over my head, but it’s intetesting to see what your code becomes.blog comments powered by Disqus Prev: C# XmlTextReader Tutorial Next: Decline in Inverse and Leveraged ETFs
http://illuminatedcomputing.com/posts/2010/02/sorting-out-the-confusion-32-vs-64-bit-clr-vs-native-cs-vs-cpp/
CC-MAIN-2014-52
en
refinedweb
SqlClient for the Entity Framework This section describes the .NET Framework Data Provider for SQL Server (SqlClient), which enables the Entity Framework to work over Microsoft SQL Server. Provider Schema Attribute Provider is an attribute of the Schema element in store schema definition language (SSDL). To use SqlClient, assign the string "System.Data.SqlClient" to the Provider attribute of the Schema element.. Provider Namespace Name All providers must specify a namespace. This property tells the Entity Framework which prefix is used by the provider for specific constructs, such as types and functions. The namespace for SqlClient provider manifests is SqlServer. For more information about namespaces, see Namespaces. Types The SqlClient provider for the Entity Framework provides mapping information between conceptual model types and SQL Server types. For more information, see SqlClient for Entity FrameworkTypes. Functions The SqlClient provider for the Entity Framework defines the list of functions supported by the provider. For a list of the supported functions, see SqlClient for Entity Framework Functions. In This Section SqlClient for Entity Framework Functions SqlClient for Entity FrameworkTypes Known Issues in SqlClient for Entity Framework See Also ConceptsEntity SQL Language SqlClient for the Entity Framework Other ResourcesLanguage Reference Build Date:
http://msdn.microsoft.com/en-us/library/bb896309.aspx
CC-MAIN-2014-52
en
refinedweb
> BTW, if you have some performance tests that you would like me to try > here, please let me know. Attached a little program for testing the performance of the path locking code. It creates a directory stack of a given depth, and then performs stat() calls on the bottom level. So for example: ~/fuse/example/.libs/fusexmp -s -oattr_timeout=0 /tmp/fuse cd /tmp/fuse/tmp time ~/cc/pathtest 100 100000 > > For example, a fairly big optimization for the uncontended case could > > be to try to do the locking and the path creation in a single stage, > > with pthread_rwlock_try*. > > > > If the trylock fails at some point we have to do it the slow way, as > > now. But if we can lock the whole path with trylocks we could have > > saved some processing. And collecting the nodes into a list isn't > > even needed in that case, unlocking can also be done by following the > > parent pointers from the original node. > > > > I implemented the trylock idea and I think it may help us. Please let me > know your opinion. It's still not perfect ;). What I meant, was that try_quick_lock() and get_path_name() could be done in a single traversal of the nodes. Here's the top of the profile output I got with the above test: Each sample counts as 0.01 seconds. % cumulative self self total time seconds seconds calls s/call s/call name 37.02 1.74 1.74 _lxstat 13.19 2.36 0.62 20832143 0.00 0.00 get_node_nocheck 10.85 2.87 0.51 pthread_rwlock_unlock 8.94 3.29 0.42 pthread_rwlock_tryrdlock 4.68 3.51 0.22 calloc 4.47 3.72 0.21 do_writev 3.40 3.88 0.16 100309 0.00 0.00 unlock_path 3.19 4.03 0.15 _int_free 2.55 4.15 0.12 100309 0.00 0.00 try_quick_lock 2.55 4.27 0.12 cfree 1.49 4.34 0.07 100309 0.00 0.00 get_and_verify_path_name 1.49 4.41 0.07 __read_nocancel 1.28 4.47 0.06 10415968 0.00 0.00 insert_node_to_lock 1.06 4.52 0.05 10315762 0.00 0.00 add_name The worst offender get_node_nocheck() could be halved by not traversing the nodes twice. The performance of pthread_* functions also sucks badly, but we can't do much about that. > We don't have to traverse the nodes first and lock them, but we still > have to store them on a list, otherwise we are unable to figure out > which nodes are locked during this attempt (in particular when we have > to unlock the path partially). Well, we know the start, and we know how far we got with the trylock attempt. That should make it possible to unlock them using the same traversal, and stop when it reaches the node on which the trylock failed. Holding a lock on a node guarantees, that the parent can't change. Of course traversing the nodes again might be more expensive than storing them in the list, but calloc seems to be a bad offender, and I suspect it's mostly for the locked list allocation. > > Also I'm a bit worried about the retry logic. Continual renames could > > starve any other operation being performed on that path. So for > > example if in one shell we have > > > > cd /a/b > > while true; do ls -l c; done > > > > and in another shell > > > > while true; do mv /a/b /a/d; mv /a/d /a/b; done > > > > The ->stat() for c could be starved indefinitely. > > > > Have you tried the latest code that we only lock for writing the first > node? > > Anyway, our code locks the node "b" for writing, while "ls -l" will try > to lock /a/b/c for reading. "ls -l" will then wait for the write lock on > "b"/"d" to be released before being able to go on, but I can't see why > it should starve. I'm thinking of the following sequence of events: - quick lock for getattr fails (rename in progress) - collect nodes for getattr (rename finishes during the collection) - verify fails, because the rename messed up the path - retry In theory this could go on forever whithout getattr ever succeeding. > Even if it takes some time before it acquires the > lock, eventually it will run because I assume pthread code tries to > avoid starvation (probably by increasing some wait counter as time goes > by, even when writers have higher priority). I ran these commands here > and both loops ran pretty well, without any starvation. Yes, I don't expect this will be observable in practice, or only very rarely. Still if there's some simple way to avoid this, then that would be nice. Thanks, Miklos ===File pathtest.c========================================== #include <stdio.h> #include <stdlib.h> #include <unistd.h> #include <sys/stat.h> int main(int argc, char *argv[]) { int depth; int niter; int i; if (argc != 3) { fprintf(stderr, "usage: %s depth niter\n", argv[0]); return 1; } depth = atoi(argv[1]); niter = atoi(argv[2]); for (i = 0; i < depth; i++) { mkdir("x", 0777); chdir("x"); } mknod("y", 0666, 0); for (i = 0; i < niter; i++) { struct stat stbuf; stat("y", &stbuf); } return 0; } ============================================================ View entire thread
http://sourceforge.net/p/fuse/mailman/message/10885354/
CC-MAIN-2014-52
en
refinedweb
06 September 2011 13:43 [Source: ICIS news] HOUSTON (ICIS)--Anadarko, Enbridge and ?xml:namespace> The “Texas Express Pipeline” (TEP), running from Skellytown in The pipeline’s initial capacity will be about 280,000 bbl/day, with possible expansion to 400,000 bbl/day at a later time, the companies said in a joint statement. The TEP will supply petrochemical facilities with a reliable source of feedstock, they said. “Demand for natural gas-derived feedstocks remains strong, driven by the wide spread between crude oil and natural gas prices,” they added. The plan includes two NGL gathering systems. The first will connect the TEP to natural gas processing plants in the Texas Panhandle and western Enterprise CEO Michael Creel said the pipeline project will offer a “comprehensive industry solution” for NGL transportation constraints that are limiting access to the large Gulf coast NGL market. Expected project costs
http://www.icis.com/Articles/2011/09/06/9490497/Anadarko-partners-to-build-580-mile-NGL-pipeline-in.html
CC-MAIN-2014-52
en
refinedweb
GETUID(2) BSD Programmer's Manual GETUID(2) getuid, geteuid - get user identification #include <sys/types.h> #include <unistd.h> uid_t getuid(void); uid_t geteuid(void); The getuid() function returns the real user ID of the calling process. The geteuid() function returns the effective user ID of the calling pro- cess. The real user ID is that of the user who has invoked the program. As the effective user ID gives the process additional permissions during execu- tion of "set-user-ID" mode processes, getuid() is used to determine the real user ID of the calling process. The getuid() and geteuid() functions are always successful, and no return value is reserved to indicate an error. getgid(2), setreuid(2), setuid(2) The getuid() and geteu.
http://www.mirbsd.org/htman/sparc/man2/getuid.htm
CC-MAIN-2014-52
en
refinedweb
The QUriDrag class provides a drag object for a list of URI references. More... #include <qdragobject.h> Inherits QStoredDrag. List of all member functions. URIs are a useful way to refer to files that may be distributed across multiple machines. A URI will often refer to a file on a machine local to both the drag source and the drop target, so the URI can be equivalent to passing a file name but is more extensible. Use URIs in Unicode form so that the user can comfortably edit and view them. For use in HTTP or other protocols, use the correctly escaped ASCII form. You can convert a list of file names to file URIs using setFileNames(), or into human-readble form with setUnicodeUris(). Static functions are provided to convert between filenames and URIs, e.g. uriToLocalFile() and localFileToUri(), and to and from human-readable form, e.g. uriToUnicodeUri(), unicodeUriToUri(). You can also decode URIs from a mimesource into a list with decodeLocalFiles() and decodeToUnicodeUris(). See also Drag And Drop Classes. Returns TRUE if e contained a valid list of URIs; otherwise returns FALSE. Examples: dirview/dirview.cpp and fileiconview/qfileiconview.cpp. Returns TRUE if contained a valid list of URIs; otherwise returns FALSE. The list will be empty if no URIs were local files. Returns TRUE if contained a valid list of URIs; otherwise returns FALSE. See also uriToLocalFile(). See also localFileToUri() and setUris(). Use setFileNames() instead (notice the N). See also localFileToUri() and setUris(). Example: dirview/dirview.cpp. See also uriToLocalFile(). See also localFileToUri(). See also localFileToUri(). This file is part of the Qt toolkit. Copyright © 1995-2003 Trolltech. All Rights Reserved.
http://vision.lbl.gov/People/qyang/qt_doc/quridrag.html
CC-MAIN-2014-52
en
refinedweb
30 June 2009 15:43 [Source: ICIS news] LONDON (ICIS news)--ExxonMobil Chemical will increase polypropylene (PP) compounding capacity at its plant in Lillebonne, France, by 45,000 tonnes/year due to increased demand, the US producer said on Tuesday. Capacity would be aimed at meeting growing demand for Exxtral performance polyolefins from automotive original equipment manufacturers (OEMs), primarily in ?xml:namespace> The expansion was due for completion by the end of this year. The company did not disclose the current capacity of the plant. In January 2008, the company announced the start-up of a new $20m specialty compounding facility in Under an agreement announced in September 2008, Resin & Pigment Technologies in Exxtral polyolefins are used primarily for interior and under the hood automotive applications but are increasingly being specified for exterior
http://www.icis.com/Articles/2009/06/30/9228856/exxonmobil-to-increase-lillebonne-pp-compounding-capacity.html
CC-MAIN-2014-52
en
refinedweb
11 November 2011 08:15 [Source: ICIS news] SINGAPORE (ICIS)--Thai MMA is expected to shut down its 90,000 tonne/year No 1 methyl methacrylate (MMA) line at Map Ta Phut on 17 November because of weakened domestic demand in flood-stricken ?xml:namespace> The line is expected to remain off line up to 30 November, the source said. “Our customers are severely affected by the floods, and hence, the decision to shut down the No 1 line,” the source said. Thai MMA is trying to export surplus MMA, but demand in southeast Asian is weak as well, he said. The No 1 MMA line had an outage on 17 October to 3 November because of mechanical problems, said the source. Meanwhile, the company’s 90,000 tonne/year No 2 MMA line at the site will not be shut. This line is currently running at 100%,
http://www.icis.com/Articles/2011/11/11/9507362/thai-mma-to-shut-no-1-mma-line-on-17-november-on-poor-demand.html
CC-MAIN-2014-52
en
refinedweb
Developing Visual Studio Project Wizards Pages: 1, 2, 3, 4, 5, 6 Next, create the template that will be used to generate individual projects. To do this, create a console mode application in either C# or Visual Basic. Add a reference to AppLib.dll to the project. Rename the code file to AppClass.cs or AppClass.vb, and replace the contents of the C# code file with the following code: using MyCompanyApp; using System; namespace MyCompanyApp { class AppClass { static void Main() { $OpeningMessage$; } } } The corresponding Visual Basic code is: Imports MyCompanyApp Module AppClass Sub Main() $OpeningMessage$ End Sub End Module Notice that $OpeningMessage$ is not valid C# or Visual Basic syntax; instead, this is a replaceable string parameter. When the project is created, the wizard replaces this string with a call to the appropriate library method. The template can then be exported and its .vstemplate file modified, as discussed in the "Modifying the .vstemplate File" section. In addition, you should change the assembly reference, which appears as follows: $OpeningMessage$ <Reference Include="AppLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a68e0a70a91f57a7, processorArchitecture=MSIL"> <SpecificVersion>False</SpecificVersion> <HintPath>..\AppLib\bin\Release\AppLib.dll</HintPath> </Reference> to the following: <Reference Include="AppLib, Version=1.0.0.0, Culture=neutral, PublicKeyToken=a68e0a70a91f57a7, processorArchitecture=MSIL" /> This insures that, rather than attempting to locate a local copy in a particular directory, Visual Studio will load the assembly from the GAC. Once you've made all of the modifications, you can place the new set of files in a ZIP file and place the file in the Visual Studio project template directory for either Visual Basic or C#. The wizard simply opens a Windows form that allows the developer to indicate whether the project targets version 1 or 2 of the class library. If the developer chooses version 1, the string AppLib.DisplayGreeting() replaces the replaceable string parameter. If the developer chooses version 2, AppLib.DisplayGreetingDialog() replaces the string parameter. In addition, if the developer chooses version 2, a reference to AppLib2 is added to the project. The following is the code for a class named AppWizard, which provides the IWizard implementation: AppLib.DisplayGreeting() AppLib.DisplayGreetingDialog() AppWizard Imports EnvDTE80 Imports Microsoft.VisualStudio.TemplateWizard Imports VSLangProj Public Class AppWizard : Implements IWizard ' Declare private variables Private vsApp As DTE2 Private isVB As Boolean Friend targetedVersion As Integer = 1 Public Sub BeforeOpeningFile(ByVal projectItem As EnvDTE.ProjectItem) Implements Microsoft.VisualStudio.TemplateWizard.IWizard.BeforeOpeningFile End Sub Public Sub ProjectFinishedGenerating(ByVal project As EnvDTE.Project) Implements Microsoft.VisualStudio.TemplateWizard.IWizard.ProjectFinishedGenerating ' Add reference to AppLib2 for V2 projects If targetedVersion = 2 Then Dim appProject As VSProject = DirectCast(project.Object, VSProject) Dim ref As Reference = appProject.References.Add("AppLib2") Console.WriteLine(ref.Version) End If End Sub Public Sub ProjectItemFinishedGenerating(ByVal projectItem As EnvDTE.ProjectItem) Implements Microsoft.VisualStudio.TemplateWizard.IWizard.ProjectItemFinishedGenerating End Sub Public Sub RunFinished() Implements Microsoft.VisualStudio.TemplateWizard.IWizard.RunFinished End Sub Public Sub RunStarted(ByVal automationObject As Object, ByVal replacementsDictionary As System.Collections.Generic.Dictionary(Of String, String), ByVal runKind As Microsoft.VisualStudio.TemplateWizard.WizardRunKind, ByVal customParams() As Object) Implements Microsoft.VisualStudio.TemplateWizard.IWizard.RunStarted ' Get reference to application-level object Me.vsApp = DirectCast(automationObject, DTE2) ' Open dialog to determine version of library user develops against Dim frm As New WizardForm(Me) frm.ShowDialog() ' Terminate template if user has cancelled form If frm.DialogResult = Windows.Forms.DialogResult.Cancel Then ' Cancel loading of template (and wizard) Throw New WizardCancelledException Else ' Adjust the method call replacementsDictionary.Add("$rootNamespace$", "MyCompanyApp") If Me.targetedVersion = 1 Then replacementsDictionary.Add("$OpeningMessage$", "AppLib.DisplayGreeting()") ElseIf Me.targetedVersion = 2 Then replacementsDictionary.Add("$OpeningMessage$", "AppLib2.DisplayGreetingDialog()") ' This shouldn't happen Else Throw New WizardCancelledException("An unexpected error has caused the template to terminate.") End If End If End Sub Public Function ShouldAddProjectItem(ByVal filePath As String) As Boolean Implements Microsoft.VisualStudio.TemplateWizard.IWizard.ShouldAddProjectItem Return True End Function End Class The AppWizard class in turn instantiates a form class named WizardForm and passes it a reference to itself. The WizardForm class has a drop-down list box named cboVersions that displays the versions of the AppLib class library. The complete source code for the WizardForm class is: WizardForm cboVersions AppLib Public Class WizardForm Private Const TOTAL_PAGES = 1 Dim wizard As AppWizard Public Sub New(ByVal wizardClass As AppWizard) MyBase.New() InitializeComponent() wizard = wizardClass End Sub Private Sub WizardForm_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load Dim ctr As Integer = 1 ' Counter to track current page (for multi-page wizards) Me.cboVersions.SelectedIndex = 0 End Sub Private Sub btnOK_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles btnOK.Click Me.wizard.targetedVersion = Me.cboVersions.SelectedIndex + 1 End Sub Private Sub brnCancel_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles brnCancel.Click End Sub End Class Once you've created the wizard and registered in the GAC, and you've created the template and placed it in the appropriate directory, you can use it to create projects in Visual Studio. Note that we use the same wizard to handle a Visual Basic and a Visual C# project template. Ordinarily, we'd want to include some means of determining the template's target language so that we can use the individual language's syntax or address features in its Visual Studio development environment. We can do this by retrieving the string returned by the Kind property of the EnvDTE.Project interface, then looking up the value of this key in the registry. It is much easier, though, to define a custom string parameter named Language in the .vstemplate file, and to give it a value of VisualBasic for the Visual Basic template and CSharp for the C# template. Kind Language VisualBasic CSharp When debugging wizard applications, it's important to remember that both Visual Studio and the GAC use cached copies of their assemblies. This means that when you modify and recompile your assembly, the .NET Framework or Visual Studio may be working with a previous copy. To make sure that the current assembly is being used, it's a good practice to unregister the previous version of an assembly from the GAC and then to register the new version. The instance of Visual Studio that was used to create a template should also be closed once the template is modified, and a new instance started to work with the new one. Ron Petrusha is the author and coauthor of many books, including "VBScript in a Nutshell.".
http://archive.oreilly.com/pub/a/windows/2007/06/06/developing-visual-studio-project-wizards.html?page=6
CC-MAIN-2014-52
en
refinedweb
t0mm0 Wrote:i've already discussed in eldorados thread that this will be fixed. i'm afraid i'm really busy at the moment and might not get to do much for a couple of weeks (see the post above yours) thanks, t0mm0 k_zeon Wrote:Hi t0mm0 just been playing around with eldorados new metautils and he said that at present i cannot add infolabels to directories but only on addvideoitem just wondered if this is something that will be implemented and if poss a timescale. many thanks for all your hard work def unescape(self, text): ''' Decodes HTML entities in a string. You can add more entities to the ``rep`` dictionary. Args: text (str): String to be cleaned. Returns: Cleaned string. ''' try: text = self.decode(text) rep = {'<': '<', '>': '>', '"': '"', '’': '\'', '´': '\'', } for s, r in rep.items(): text = text.replace(s, r) # this has to be last: text = text.replace("&", "&") [b] except TypeError: pass[/b] return text k_zeon Wrote:Hey Eldorado Just added the fix to t0mm0's common module and then run ProjectfreeTV and it appears to run and scrape info. Then when i scoll through the movies , the pics change and also the background but then all of a sudden the picture does not change and then scrolling back the pics that did show do not change. It stays the same. No errors appear so do not know reason why.... Running my addon seems fine.. Edit: Just took out the Fanart part ( fanart=meta['backdrop_url'] ) for the menu adding function and then it works fine. Would be good to have an option to turn fanart downloading off. t0mm0 Wrote:sorry for my lack of work recently, my excuse is a combination of busy-ness (work and non-work) not feeling well and my phone deciding not to alert me of new emails to my dev account anyway, i'll get back to work again now honest and try and get a urlresolver release done ASAP t0mm0 Eldorado Wrote:I have feature requests for your common library t0mm0 Wrote:cool - request away! i know already requested is to make adding directories and items take the same arguments.... t0mm0 Eldorado Wrote:Context menu item support is my next one, I saw the chat between you and Dragonwin on it but wasn't sure if any code was done to handle it.. ? t0mm0 Wrote:Dragonwin's code is here i haven't looked at it much yet (just getting through the pull requests at the moment) - let me know if that code does what you need. (maybe you could specify what you want it to do so i don't break it if i change that code?) also is the add_directory() stuff okay for you now? thanks, t0mm0
http://forum.kodi.tv/printthread.php?tid=105707&page=16
CC-MAIN-2014-52
en
refinedweb
CASE Software Coral Coral is a tool and a development platform to create and transform models and modeling languages. It can be used to edit UML models, to develop editors for other modeling languages and to implement MDA and QVT-like model transformations PseudoConverPlus Convertidor2 RegexLord RegexLord is the IDE for developing regular expression assemblies for .NET. Full stop. It provides syntax highlighting (via the sharpdevelop text editor,), bracket matching, namespace management, code folding, and an easy to1 weekly downloads Subversion Peer Review System Subversion PRS is a web-based tool to assist in peer review of code for projects using the Subversion version control system. It uses Perl, JavaScript, HTML, CSS, and MySQL.1 screenshoter Allows screen sharing over email, or through 'conversations' with contacts, so that when a contact receives a screenshot it's automatically displayed with its default image viewer.0 weekly downloads
http://sourceforge.net/directory/development/case-tools/developmentstatus:beta/os:modern_oses/
CC-MAIN-2014-52
en
refinedweb
24 October 2012 11:53 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> November shipment offers are currently at $950/tonne CFR (cost and freight) CMP (China Main Port) and $970/tonne CFR India, $20/tonne and $30/tonne lower than FPCC’s initial offers of $970/tonne CFR CMP and $1,000/tonne CFR India, respectively. FPC has also reduced its export offers by $40/tonne to $880/tonne FOB (free on board) Quantity discounts of $10/tonne and $20/tonne for volumes of 500 tonnes and 1,000 tonnes, respectively, are still applicable to all markets. A discount of $30/tonne applies for volume of 2,000 tonnes and above to FPC’s total export volume for November shipments is estimated at around 60,000 tonnes, according to
http://www.icis.com/Articles/2012/10/24/9606695/taiwans-fpc-revises-down-november-pvc-offers-by-20-40tonne.html
CC-MAIN-2014-52
en
refinedweb
ip-monitor, rtmon — state monitoring Synopsis ip monitor [ all | OBJECT-LIST ] [ file FILENAME ] [ label ] [ all-nsid ] [ dev DEVICE ] Options - -t, -timestamp Prints timestamp before the event message on the separated line in format: Timestamp: <Day> <Month> <DD> <hh:mm:ss> <YYYY> <usecs> usec <EVENT> - -ts, -tshort Prints short timestamp before the event message on the same line in format: [<YYYY>-<MM>-<DD>T<hh:mm:ss>.<ms>] <EVENT> Description The ip utility can monitor the state of devices, addresses and routes continuously. This option has a slightly different format. Namely, the monitor command is the first in the command line and then the object list follows: ip monitor [ all | OBJECT-LIST ] [ file FILENAME ] [ label ] [ all-nsid ] [ dev DEVICE ] OBJECT-LIST is the list of object types that we want to monitor. It may contain link, address, route, mroute, prefix, neigh, netconf, rule and nsid. If no file argument is given, ip opens RTNETLINK, listens on it and dumps state changes in the format described in previous sections. If the label option is set, a prefix is displayed before each message to show the family of the message. For example: [NEIGH]10.16.0.112 dev eth0 lladdr 00:04:23:df:2f:d0 REACHABLE [LINK]3: eth1: <BROADCAST,MULTICAST> mtu 1500 qdisc pfifo_fast state DOWN group default link/ether 52:54:00:12:34:57 brd ff:ff:ff:ff:ff:ff If the all-nsid option is set, the program listens to all network namespaces that have a nsid assigned into the network namespace were the program is running. A prefix is displayed to show the network namespace where the message originates. Example: [nsid 0]10.16.0.112 dev eth0 lladdr 00:04:23:df:2f:d0 REACHABLE. If the dev option is given, the program prints only events related to this device. See Also ip(8) Referenced By ip(8).
https://dashdash.io/8/ip-monitor
CC-MAIN-2021-17
en
refinedweb
Common Image Filters¶ Note: Sorry, but the CommonFilters and FilterManager classes are implemented in Python and will not be of much use to C++ users. The purpose of the CommonFilters class is to make it easy to set up a number of common image postprocessing operations. Import the class like this: from direct.filter.CommonFilters import CommonFilters Currently, the image postprocessing operations supported by CommonFilters are: Bloom Filter - creates a glowing halo around bright objects. Cartoon Inker - draws black lines around 3D objects. Volumetric Lighting - screen-space method for casting god-rays. Inverted Filter - inverts all colors. Blur/Sharpen Filter - applies a generic blur or sharpen filter. Ambient Occlusion - applies a screen-space ambient occlusion filter. Gamma Adjust - applies a gamma adjustment. sRGB Encode - ensures the image is encoded using the sRGB inverse EOTF. High Dynamic Range Filter - enables HDR rendering and tone mapping. Exposure Adjust - applies exposure compensation before tone mapping. We expect this list to grow rather substantially over the next year or so. Basic Setup¶: It will render the scene into an offscreen buffer, using the camera you provided. It will remove the scene from the specified window, and replace it with a fullscreen quad. The quad will be textured with the scene, plus a shader that implements whatever filter you have selected. If all goes well, the net effect is that your scene will continue to appear in your window, but it will be filtered as you specify. What if the Video Card can’t handle it?¶ If the video card is not capable of implementing your filters, then all filters will be removed and the filter-enabling function will return False. Otherwise, filter-enabling functions will return True. The Bloom Filter¶ The bloom filter causes bright objects to have a glowing halo around them. To enable a bloom filter, use setBloom. To disable, use. Note: If you want to use glow maps to indicate which parts of the image should receive bloom, you should assign a nonzero value to the alpha value of the blend-weight parameter, and you should enable the shader generator for the models that have glow maps applied. The bloom filter has many keyword parameters: blend - The bloom filter needs to measure the brightness of each pixel. It does this by weighting the R,G,B, and A components. Default weights: (0.3,0.4,0.3,0.0). You should assign a nonzero weight to the alpha channel if you want the glow map to have an effect, or a value like (0, 0, 0, 1) if you only want your glow map to indicate which models should glow. mintrigger - Minimum brightness at which a halo is generated. Default: 0.6 maxtrigger - Maximum brightness at which the halo reaches peak intensity. Default: 1.0 desat - Degree to which the halo is desaturated. Setting this to zero means the halo is the same color as the bright pixel. Setting it to one means the halo is white. Default: 0.6 intensity - An adjustment parameter for the brightness of the halos. Default: 1.0 size - Adjusts the size of the halos. Takes a string value: “small”, “medium”, or “large”. The reason that this is a discrete value and not a continuous one is that the blur operation involves downsampling the original texture by a power of two. Default: “medium” The Cartoon Inking Filter¶ The cartoon inking filter causes objects to have black lines around them. To enable a cartoon inking filter, use setCartoonInk. To disable, use: separation - Distance in pixels, controls the width of the ink line. Default: 1 pixel. color - Color of the outline. Default: (0, 0, 0, 1) The Volumetric Lighting Filter¶ The Volumetric Lighting filter makes objects cast visible light rays (also known as crepuscular rays, god rays or sunbeams) that can be occluded by visible geometry. This is an easy way to easily create nice-looking light/sun effects. filters.setVolumetricLighting( ... options ...) filters.delVolumetricLighting() The filter has the following keyword parameters: caster - NodePath that indicates the origin of the rays. Usually, you would pass your light, and create a sun billboard which is reparented to the light’s NodePath. numsamples - Number of samples. The more samples you use, the slower the effect will be, but you will have smoother light rays. Note that using a fuzzy billboarded dot instead of a hard-edged sphere as light caster can help with smoothing the end result, too. This value does not need to be a power-of-two, it can be any positive number. Default: 32 density - This defines the length of the rays. The default value of 5.0 is probably too high for many purposes, usually a value between 0.5 and 1.0 works best. This also depends on the number of samples and exposure you’ve chosen, though. Default: 5.0 decay - Decay makes rays gradually decrease in brightness. The default value of 0.1 is not well chosen and makes the rays very short! Usually, this a value close to 1.0, like 0.98. Default: 0.1 exposure - Defines the brightness of the rays. Default: 0.1 The Inverted Filter¶ This filter simply inverts the colors of the image. filters.setInverted() filters.delInverted() This filter has no parameters. The Blur / Sharpen Filter¶ This filter can apply a blur or sharpen effect to the image. filters.setBlurSharpen( ... options ...) filters.delBlurSharpen() The filter has the following keyword parameters: amount - The amount of blurring, this is usually a value between 0.0 and 2.0. You can take values smaller than 0.0 or larger than 2.0, but this usually gives ugly artifacts. A value of 0.0 means maximum blur. A value of 1.0 does nothing, and if you go past 1.0, the image will be sharpened instead of blurred. Default: 0.0 The Ambient Occlusion Filter¶ This filter adds a simple screen-space ambient occlusion effect to the scene. filters.setAmbientOcclusion( ... options ...) filters.delAmbientOcclusion() It is important that the viewing frustrum’s near and far values fit the scene as tightly as possible. Note that you need to do lots of tweaking to the parameters to get this filter to work for your particular situation. The filter has the following keyword parameters: numsamples - The amount of samples used. Default: 16 radius - The sampling radius of the rotating kernel. Default: 0.05 amount - Default: 2.0 strength - Default: 0.01 falloff - Default: 0.000002 The Gamma Adjust Filter¶ This filter performs a simple gamma adjustment by raising the color values to the given power. Do not use this to adjust to the 2.2 gamma of a computer monitor. For that, see the below filter. filters.setGammaAdjust(1.5) filters.delGammaAdjust() The sRGB Encode Filter¶ This filter applies the inverse sRGB Electro-Optical Transfer Function (EOTF) to the final rendering result. This allows the lighting and blending calculations to be performed in linear space, which results in more accurate colors and lighting. The effect of this is similar to applying a gamma adjustment of 1.0/2.2, but not quite. The sRGB transfer function has a linear section in the beginning to better preserve the fidelity of dark values. When enabling this, it is important to make sure that all color input textures are properly configured to use the sRGB format, to prevent them from appearing too bright and washed-out. If the framebuffer-srgb setting is active, this filter is unnecessary. Panda will detect if this is the case and refuse to apply this filter, in order to prevent double-applying the sRGB transformation. filters.setSrgbEncode() filters.delSrgbEncode() This filter is available as of Panda3D 1.10.7. The High Dynamic Range Filter¶ This filter enables High Dynamic Range rendering. This will enable the use of a floating-point framebuffer format and disables clamping of the color values before they are written to the framebuffer. This allows you to use far greater brightness values on your lights, which creates a greater dynamic range in your scene. A tonemapping filter (ACES) is used to bring the values back into the appropriate range for display on a monitor. Depending on the brightness of your lights, it may be necessary to use the Exposure Adjust filter in order to prevent an oversaturated image. It is recommended to set your lights to use an inverse square falloff attenuation (using setAttenuation(0, 0, 1)), enable the sRGB Encode filter, and use realistically bright values for your light colors to achieve the most realistic effect. filters.setHighDynamicRange() filters.delHighDynamicRange() This filter is available as of Panda3D 1.10.7. The Exposure Adjust Filter¶ This filter is meant to be used in conjunction with the HDR filter, above, in order to adjust the exposure level. In a game where the player moves between different parts of the scene with different lighting levels, it will be necessary to adjust this on the fly depending on the player’s location. This is similar to how our eyes adjust to different light levels as we move between areas of differing brightness. The value is in f-stops, meaning that a value of 0 resulting in no adjustment, and each value above 0 doubles the scene luminance, whereas each value below 0 halves it. filters.setExposureAdjust(0) filters.delExposureAdjust() This filter is available as of Panda3D 1.10.7.
https://docs.panda3d.org/1.10/cpp/programming/render-to-texture/common-image-filters
CC-MAIN-2021-17
en
refinedweb
On 12.05.2016 17:30, Michal Privoznik wrote: > On 12.05.2016 16:34, Peter Krempa wrote: >> On Thu, May 12, 2016 at 14:36:22 +0200, Michal Privoznik wrote: >>> The intent is that this library is going to be called every time >>> to check if we are not touching anything outside srcdir or >>> builddir. >>> >>> Signed-off-by: Michal Privoznik <mprivozn redhat com> >>> --- >>> cfg.mk | 2 +- >>> tests/Makefile.am | 13 +++- >>> tests/testutils.c | 9 +++ >>> tests/testutils.h | 10 +-- >>> tests/vircgroupmock.c | 15 ++--- >>> tests/virpcimock.c | 14 ++-- >>> tests/virtestmock.c | 175 ++++++++++++++++++++++++++++++++++++++++++++++++++ >>> 7 files changed, 210 insertions(+), 28 deletions(-) >>> create mode 100644 tests/virtestmock.c >>> >> >> [...] >> >>> diff --git a/tests/testutils.c b/tests/testutils.c >>> index 79d0763..595b64d 100644 >>> --- a/tests/testutils.c >>> +++ b/tests/testutils.c >> >> [...] >> >>> @@ -842,6 +845,12 @@ int virtTestMain(int argc, >>> char *oomstr; >>> #endif >>> >>> +#ifdef __linux__ >>> + VIRT_TEST_PRELOAD(TEST_MOCK); >> >> So I was thinking about it a bit. I think we should pre-load this only >> conditionally on a ENV var which will enable it. > > Yeah, I was thinking the same when implementing this. Problem with that > approach would be that nobody would do that. But I guess for now it's a > fair trade and once we get the whitelist rules complete we can make > 'make check' to actually set the variable and possibly die on an error > if the perl script founds one. Got any good idea about the var name? > What if I reuse VIR_TEST_FILE_ACCESS (introduced in 3/4) just for this > purpose, to enable this whole feature; and then introduce > VIR_TEST_FILE_ACCESS_OUTPUT to redirect output into a different file > than the default one. > If so, do you want me to send another version of these patches? I just realized, it's not going to be that easy. Problem is, my mock lib, implements both lstat and __lxstat, and stat and __xstat. Now, due to changes made to other mocks (i.e. virpcimock and vircgroupmock), without my library linked tests using the other mocks will just crash as soon as they try to stat(). So what I can do, is to suppress any output (and checking of accessed paths) until VIR_TEST_FILE_ACCESS var is set (or whatever name we decide on). Michal
https://listman.redhat.com/archives/libvir-list/2016-May/msg00921.html
CC-MAIN-2021-17
en
refinedweb
Opened 10 years ago Closed 8 years ago #11776 closed enhancement (duplicate) Holding an expression unevaluated: Something like hold_all() would be nice. Description A function that holds its arguments unevaluated, something like hold_all(expression) would be very nice, if implemented. It would be very useful when teaching Sage to students, and in general it would facilitate printing results together with the unevaluated expression. Please have a look at, it is a worksheet that explains (in detail, I hope) how a function like hold_all() would be useful in practice. Change History (8) comment:1 follow-up: ↓ 2 Changed 10 years ago by comment:2 in reply to: ↑ 1 ; follow-up: ↓ 3 Changed 10 years ago by Given that expressionis already evaluated (leading to a simplified expression) before hold_alleven gets a hold of it, this approach is a little problematic. I know, that's why I suggested a different approach in the end of the Sage worksheet I posted (). Something like unevaluated_expr=hold_all( integrate(x^2+1,x) + diff(tan(x),x) ) then a command to evaluate it, if needed, say evaluated_expr=evaluate(unevaluated_expr) So one could pretty print the unevaluated expression, together with the the evaluated one with join(["$",unevaluated_expr,"=",evaluated_expr,"$"]) Note that such a functionality is pretty much standard in many Computer Algebra systems. Maxima, for example, suspends evaluation if an expression is preceded by a single quote, and has a very convenient function called ev() to evaluate the expression (or even parts of it) later on, so one could use unevaluated_expr : '( integrate(x^2+1,x) + diff(tan(x),x) ) evaluated_expr : ev(unevaluated_expr) print(unevaluated_expr,"=",evaluated_expr) where everything inside '(...) is not evaluated. The same thing can be done in Mathematica and even yacas. I was actually surprised Sage doesn't have an easy way to do the same.. Well, the very basic feature is already available, indeed, but not for every function and not in a way one could call "convenient". Furthermore, integrate() was just an example. I didn't know about the package dummy_integrate (and I have no means to know which functions accept hold=True and which don't). But anyway, it only solves the issue for that particular (and very simple) example. I am thinking of something more general and more powerful. You can already do def held(f): return lambda *args: f(*args,hold=True) sin=held(sin) cos=held(cos) sin(pi)^2+cos(pi)^2one could have a package inert_symbolic_functions that has (essentially) those declarations, so that a from held_symbolic_functions import *would give you a "held" environment. With a little namespace injection magic one could probably also use that to implement with held_function_context: expr=sin(pi)^2+cos(pi)^2which is probably the closest to what you request, subject to being doable in python. Well, doable, but sounds like reinventing the wheel, in my humble opinion. Not to mention it works only for functions that accept hold=True, and I have no idea how I will suspend evaluation of operators that way. Given the fact that Sage makes heavy use of LaTeX's power to typeset expressions perfectly (while Maxima or Mathematica either don't use LaTeX, or use it only with the aid of external programs), it is a pity we can't use that power to create educational worksheets, pretty much like books, where printing an expression unevaluated together with the corresponding evaluated one is a must. It is actually one of the first things I try to do as a test in every CAS I am learning. comment:3 in reply to: ↑ 2 Changed 10 years ago by I know, that's why I suggested a different approach in the end of the Sage worksheet I posted (). Something like unevaluated_expr=hold_all( integrate(x^2+1,x) + diff(tan(x),x) ) That is exactly what can't work. This is equivalent to the python code unevaluated_expr=hold_all(integrate(x^2+1,x).__add__(diff(tan(x),x))) The meaning of this in python is that what is inside the parentheses gets executed and the result of that gets passed to hold_all. By the time hold_all executes, it is already too late. You need to inform integrate, __add__ and diff that they need to behave differently from what they would normally do. The "hold" parameter does that, but as you observe, it is rather burdensome that it potentially has to be supplied to all routines involved (the fact that not all relevant routines accept "hold" yet is just a matter of a bug to fix). Basically what is needed is a flag on SR that sets "hold=True" to be the default rather than "hold=False". I don't know how easy and how thread-safe such a flag would be. It would definitely violate the stipulation that parents be immutable. A "clean" solution would be to allow a second instance of SR that does have "hold=True" as default? This would allow something that you'll probably find painful too: sage: SRheld = SymbolicRing( hold_by_default = True ) sage: SRheld(1) + SRheld(3) #note the need to turn 1,3 into symbolic objects before adding 1 + 3 sage: x = SRheld.var('x') sage: integrate(x^2+1,x) integral(x^2+1,x) sage: xt = SR(x) # the normal SR still behaves as before sage: integrate(xt^2+1,xt) 1/3*x^3+x I'm afraid the proposed namespace magic I proposed earlier will never fully work because SR(1).__add__(3) can't be reached that way. So we need to find a convenient place to store the "hold default value". SR itself would be a reasonable place except that changing the value definitely changes how SR behaves and parents are supposed to be immutable. Perhaps if we make a context manager that sets and resets a "hold_by_default" flag, we localize the potential trouble a bit. localvars has set a precedent for such: with held_function_context(SR): expr=sin(pi)^2+cos(pi)^2 If in addition it would hold a lock on SR we would be thread safe as well (just not very thread friendly). I think there is merit in having "hold" facilities more readily available but to implement it requires some serious architectural considerations and likely some relatively comprehensive modifications. comment:4 follow-up: ↓ 5 Changed 10 years ago by comment:5 in reply to: ↑ 4 Changed 10 years ago by - Milestone changed from sage-4.7.2 to sage-duplicate/invalid/wontfix Does it look like #10035 is what you are asking for? I'm not sure whether these are dups, though it seems like they might be. Yes! two people come up independently with the same solution. I think a context is the most convenient practical solution. I'm reassigning the ticket to "duplicate" and put it up for review. (I think that is the procedure?) If someone else confirms the "dup" status they can give it a positive review. Otherwise, just revert the milestone and revert to "new status. comment:6 Changed 8 years ago by - Reviewers set to Travis Scrimshaw - Status changed from new to needs_review comment:7 Changed 8 years ago by - Status changed from needs_review to positive_review comment:8 Changed 8 years ago by - Resolution set to duplicate - Status changed from positive_review to closed Given that expressionis already evaluated (leading to a simplified expression) before hold_alleven gets a hold of it, this approach is a little problematic.. You can already do one could have a package inert_symbolic_functions that has (essentially) those declarations, so that a would give you a "held" environment. With a little namespace injection magic one could probably also use that to implement which is probably the closest to what you request, subject to being doable in python.
https://trac.sagemath.org/ticket/11776
CC-MAIN-2021-17
en
refinedweb
AWS Compute Blog Building server-side rendering for React in AWS Lambda This post is courtesy of Roman Boiko, Solutions Architect. React is a popular front-end framework used to create single-page applications (SPAs). It is rendered and run on the client-side in the browser. However, for SEO or performance reasons, you may need to render parts of a React application on the server. This is where the server-side rendering (SSR) is useful. This post introduces the concepts and demonstrates rendering a React application with AWS Lambda. To deploy this solution and to provision the AWS resources, I use the AWS Cloud Development Kit (CDK). This is an open-source framework, which helps you reduce the amount of code required to automate deployment. Overview This solution uses Amazon S3, Amazon CloudFront, Amazon API Gateway, AWS Lambda, and Lambda@Edge. It creates a fully serverless SSR implementation, which automatically scales according to the workload. This solution addresses three scenarios. 1. A static React app hosted in an S3 bucket with a CloudFront distribution in front of the website. The backend is running behind API Gateway, implemented as a Lambda function. Here, the application is fully downloaded to the client and rendered in a web browser. It sends requests to the backend. 2. The React app is rendered with a Lambda function. The CloudFront distribution is configured to forward requests from the /ssr path to the API Gateway endpoint. This calls the Lambda function where the rendering is happening. While rendering the requested page, the Lambda function calls the backend API to fetch the data. It returns a static HTML page with all the data. This page may be cached in CloudFront to optimize subsequent requests. 3. The React app is rendered with a Lambda@Edge function. This scenario is similar but rendering happens at edge locations. The requests to /edgessr are handled by the Lambda@Edge function. This sends requests to the backend and returns a static HTML page. Walkthrough The example application shows how the preceding scenarios are implemented with the AWS CDK. This solution requires: This solution deploys a Lambda@Edge function so it must be provisioned in the US East (N. Virginia) Region. To get started, download and configure the sample: - From a terminal, clone the GitHub repository: git clone - Provide a unique name for the S3 bucket, which is created by the stack and used for React application hosting. Change the placeholder <your bucket name> to your bucket name. To install the solution, run: cd react-ssr-lambda cd ./cdk npm install npm run build cdk bootstrap cdk deploy SSRApiStack --outputs-file ../simple-ssr/src/config.json cd ../simple-ssr npm install npm run build-all cd ../cdk cdk deploy SSRAppStack --parameters mySiteBucketName=<your bucket name> - Note the following values from the output: - SSRAppStack.CFURL – the URL of the CloudFront distribution. Its root path returns the React application stored in S3. - SSRAppStack.LambdaSSRURL – the URL of the CloudFront /ssr distribution, which returns a page rendered by the Lambda function. - SSRAppStack.LambdaEdgeSSRURL – the URL of the CloudFront /edgessr distribution, which returns a page rendered by Lambda@Edge function. - In a browser, open each of the URLs from step 3. You see the same page with a different footer, indicating how it is rendered. Understanding the React app The application is created by the create-react-app utility. You can run and test this application locally by navigating to the simple-ssr directory and running the npm start command. This small application consists of two components that render the list of products received from the backend. The App.js file sends the request, parses the result, and passes it to the component. import React, { useEffect, useState } from "react"; import ProductList from "./components/ProductList"; import config from "./config.json"; import axios from "axios"; const App = ({ isSSR, ssrData }) => { const [err, setErr] = useState(false); const [result, setResult] = useState({ loading: true, products: null }); useEffect(() => { const getData = async () => { const url = config.SSRApiStack.apiurl; try { let result = await axios.get(url); setResult({ loading: false, products: result.data }); } catch (error) { setErr(error); } }; getData(); }, []); if (err) { return <div>Error {err}</div>; } else { return ( <div> <ProductList result={result} /> </div> ); } }; export default App; Adding server-side rendering To support SSR, I change the preceding application using several Lambda functions with the implementation. As I change the way data is retrieved from the backend, I remove this code from App.js. Instead, the data is retrieved in the Lambda function and injected into the application during the rendering process. The new file SSRApp.js reflects these changes: import React, { useState } from "react"; import ProductList from "./components/ProductList"; const SSRApp = ({ data }) => { const [result, setResult] = useState({ loading: false, products: data }); return ( <div> <ProductList result={result} /> </div> ); }; export default SSRApp; Next, I implement SSR logic in the Lambda function. For simplicity, I use React’s built-in renderToString method, which returns an HTML string. You can find the corresponding file in the simple-ssr/src/server/index.js. The handler function fetches data from the backend, renders the React components, and injects them into the HTML template. It returns the response to API Gateway, which responds to the client. const handler = async function (event) { try { const url = config.SSRApiStack.apiurl; const result = await axios.get(url); const app = ReactDOMServer.renderToString(<SSRApp data={result.data} />); const html = indexFile.replace( '<div id="root"></div>', `<div id="root">${app}</div>` ); return { statusCode: 200, headers: { "Content-Type": "text/html" }, body: html, }; } catch (error) { console.log(`Error ${error.message}`); return `Error ${error}`; } }; For rendering the same code on Lambda@Edge, I change the code to work with CloudFront events and also modify the response format. This function searches for a specific path (/edgessr). All other logic stays the same. You can view the full code at simple-ssr/src/edge/index.js: const handler = async function (event) { try { const request = event.Records[0].cf.request; if (request.uri === "/edgessr") { const url = config.SSRApiStack.apiurl; const result = await axios.get(url); const app = ReactDOMServer.renderToString(<SSRApp data={result.data} />); const html = indexFile.replace( '<div id="root"></div>', `<div id="root">${app}</div>` ); return { status: "200", statusDescription: "OK", headers: { "cache-control": [ { key: "Cache-Control", value: "max-age=100", }, ], "content-type": [ { key: "Content-Type", value: "text/html", }, ], }, body: html, }; } else { return request; } } catch (error) { console.log(`Error ${error.message}`); return `Error ${error}`; } }; The create-react-app utility configures tools such as Babel and webpack for the client-side React application. However, it is not designed to work with SSR. To make the functions work as expected, I transpile these into CommonJS format in addition to transpiling React JSX files. The standard tool for this task is Babel. To add it to this project, I create the configuration file .babelrc.json with instructions to transpile the functions into Node.js v12 format: I also include all the dependencies. I use the popular frontend tool webpack, which also works with Lambda functions. It adds only the necessary dependencies and minimizes the package size. For this purpose, I create configurations for both functions. You can find these in the webpack.edge.js and webpack.server.js files: const path = require("path"); module.exports = { entry: "./src/edge/index.js", target: "node", externals: [], output: { path: path.resolve("edge-build"), filename: "index.js", library: "index", libraryTarget: "umd", }, module: { rules: [ { test: /\.js$/, use: "babel-loader", }, { test: /\.css$/, use: "css-loader", }, ], }, }; The result of running webpack is one file for each build. I use these files to deploy the Lambda and Lambda@Edge functions. To automate the build process, I add several scripts to package.json. "build-server": "webpack --config webpack.server.js --mode=development", "build-edge": "webpack --config webpack.edge.js --mode=development", "build-all": "npm-run-all --parallel build build-server build-edge" Launch the build by running npm run build-all. Deploying the application After the application successfully builds, I deploy to the AWS Cloud. I use AWS CDK for an infrastructure as code approach. The code is located in cdk/lib/ssr-stack.ts. First, I create an S3 bucket for storing the static content and I pass the name of the bucket as a parameter. To ensure only CloudFront can access my S3 bucket, I use an access identity configuration: const mySiteBucketName = new CfnParameter(this, "mySiteBucketName", { type: "String", description: "The name of S3 bucket to upload react application" }); const mySiteBucket = new s3.Bucket(this, "ssr-site", { bucketName: mySiteBucketName.valueAsString, websiteIndexDocument: "index.html", websiteErrorDocument: "error.html", publicReadAccess: false, //only for demo not to use in production removalPolicy: cdk.RemovalPolicy.DESTROY }); new s3deploy.BucketDeployment(this, "Client-side React app", { sources: [s3deploy.Source.asset("../simple-ssr/build/")], destinationBucket: mySiteBucket }); const originAccessIdentity = new cloudfront.OriginAccessIdentity( this, "ssr-oia" ); mySiteBucket.grantRead(originAccessIdentity); I deploy the Lambda function from the build directory and configure an integration with API Gateway. I also note the API Gateway domain name for later use in the CloudFront distribution. const ssrFunction = new lambda.Function(this, "ssrHandler", { runtime: lambda.Runtime.NODEJS_12_X, code: lambda.Code.fromAsset("../simple-ssr/server-build"), memorySize: 128, timeout: Duration.seconds(5), handler: "index.handler" }); const ssrApi = new apigw.LambdaRestApi(this, "ssrEndpoint", { handler: ssrFunction }); const apiDomainName = `${ssrApi.restApiId}.execute-api.${this.region}.amazonaws.com`; I configure the Lambda@Edge function. It’s important to create a function version explicitly to use with CloudFront: const ssrEdgeFunction = new lambda.Function(this, "ssrEdgeHandler", { runtime: lambda.Runtime.NODEJS_12_X, code: lambda.Code.fromAsset("../simple-ssr/edge-build"), memorySize: 128, timeout: Duration.seconds(5), handler: "index.handler" }); const ssrEdgeFunctionVersion = new lambda.Version( this, "ssrEdgeHandlerVersion", { lambda: ssrEdgeFunction } ); Finally, I configure the CloudFront distribution to communicate with all the origins: const distribution = new cloudfront.CloudFrontWebDistribution( this, "ssr-cdn", { originConfigs: [ { s3OriginSource: { s3BucketSource: mySiteBucket, originAccessIdentity: originAccessIdentity }, behaviors: [ { isDefaultBehavior: true, lambdaFunctionAssociations: [ { eventType: cloudfront.LambdaEdgeEventType.ORIGIN_REQUEST, lambdaFunction: ssrEdgeFunctionVersion } ] } ] }, { customOriginSource: { domainName: apiDomainName, originPath: "/prod", originProtocolPolicy: cloudfront.OriginProtocolPolicy.HTTPS_ONLY }, behaviors: [ { pathPattern: "/ssr" } ] } ] } ); The template is now ready for deployment. This approach allows you to use this code in your Continuous Integration and Continuous Delivery/Deployment (CI/CD) pipelines to automate deployments of your SSR applications. Also, you can create a CDK construct to reuse this code in different applications. Cleaning up To delete all the resources used in this solution, run: cd react-ssr-lambda/cdk cdk destroy SSRApiStack cdk destroy SSRAppStack Conclusion This post demonstrates two ways you can implement and deploy a solution for server-side rendering in React applications, by using Lambda or Lambda@Edge. It also shows how to use open-source tools and AWS CDK to automate the building and deployment of such applications. For more serverless learning resources, visit Serverless Land.
https://aws.amazon.com/blogs/compute/building-server-side-rendering-for-react-in-aws-lambda/
CC-MAIN-2021-17
en
refinedweb
Player data Track player position and rotation The Camera object exposes information about the player’s point of view in your scene. Camera.instance.positionreturns a 3D vector with the coordinates of the player’s center, relative to the scene. When the player is on the ground, the height of this point is aproximately 1.177 m. Camera.instance.feetPositionreturns a 3D vector with the coordinates of the player’s feet, relative to the scene. Camera.instance.worldPositionreturns a 3D vector with the coordinates of the player’s center, relative to the whole of Genesis City. For example, if the scene is in coordinates 100,-100, and the player is standing on the bottom-left corner of that scene, the player’s world position will be about 1600, 1.177, -1600 Camera.instance.rotationreturns a quaternion with the player’s rotation. Tip: You can also obtain the player’s rotation expressed in Euler angles (as an x, y and z vector) by writing Camera.instance.rotation.eulerAngles. const camera = Camera.instance class CameraTrackSystem { update() { log(camera.feetPosition) log(camera.rotation.eulerAngles) } } The example above logs the player’s position and rotation on each frame. class CubeRotateSystem implements ISystem { entity: Entity constructor(entity: Entity) { this.entity = entity } update() { const transform = this.entity.getComponent(Transform) transform.rotation = Camera.instance.rotation } } const cube = new Entity() cube.addComponent(new BoxShape()) cube.addComponent(new Transform({position: new Vector3(5,1,5)})) engine.addEntity(cube) engine.addSystem(new CubeRotateSystem(cube)) The example above uses the player’s rotation to set that of a cube in the scene. Get player’s public Ethereum key You can obtain a player’s public Ethereum key by using getUserPublicKey(). You can then use this information to send payments to the player, or as a way to recognize players. The example below imports the Identity library and runs getUserPublicKey() to get the public key of the player’s Ethereum account and log it to console. The player must be logged into their Metamask account on their browser for this to work. import { getUserPublicKey } from "@decentraland/Identity" const publicKeyRequest = executeTask(async () => { const publicKey = await getUserPublicKey() log(publicKey) return publicKey }) Note that we’re using an async function to run the getUserPublicKey() function, as it might take some time to retrieve this data. We’re then handling the data in a system, to be able to use it whenever it’s ready. Get the essential player data You can obtain a player’s display name and public Ethereum key by using getUserData(). The example below imports the Identity library and runs getUserData(). import { getUserData } from "@decentraland/Identity" const userData = executeTask(async () => { const data = await getUserData() log(data.displayName) return data.displayName }) NOTE: This won’t work when running a local preview, since you’re not authenticated while running a preview. But once the scene is deployed to Decentraland, the player’s data will be readable by this code. Here we’re using an async function to run the getUserData() function, as it might take some time to retrieve this data. We’re then handling the data in a system, to be able to use it whenever it’s ready. The getUserData() function returns the following information: displayName: (string) The player’s user name, as others see in-world userId: (string) A UUID string that identifies the player. If the player has a public key, this field will have the same value as the public key. publicKey: (string) The public key of the player’s Ethereum wallet. If the player has no linked wallet, this field will be null. hasConnectedWeb3: (boolean) Indicates if the player has a public key. True if the player has one. Note: For any Ethereum transactions with the player, always use the publicKeyfield, instead of the userId. Get player realm data Players in decentraland exist in many separate realms. Players in different relms cant see each other, interact or chat with each other, even if they’re standing on the same parcels. Dividing players like this allows Decentraland to handle an unlimited ammount of players without running into any limitations. It also pairs players that are in close regions, to ensure that ping times between players that interact are acceptable. If your scene sends data to a 3rd party server to sync changes between players in real time, then it’s important that changes are only synced between players that are on the same realm. You should handle all changes that belong to one realm as separate from those on a different realm. Otherwise, players will see things change in a spooky way, without anyone making the change. import { getCurrentRealm } from "@decentraland/EnvironmentAPI" const playerRealm = executeTask(async () => { let realm = await getCurrentRealm() log(`You are in the realm: ${JSON.stringify(realm.displayName)}`) return realm }) Decentraland handles its communications between players (including player positions, chat, messageBus messages and smart item state changes) through a decentralized network of communication servers. Each one of these servers can support multiple separate layers, each with a different set of players. Each one of these layers in a server is a separate realm. The getCurrentRealm() function returns the following information: displayName: (string) The full address of the relm, composed of the server + the layer domain: (string) The URL of the server serverName: (string) The name of the server layer: (string) The name of the layer Fetch more player data Make a REST API call to the following URL, to obtain info about the player from the content server. Besides obtaining the player name, and wallet (which you can also obtain through userData) you can also find a full list of all the wearables that the player owns and all the wearables that the player is currently wearing. You can also find the player’s base body shape (male of female avatar), and snapshots of the avatar’s face and body in .jpg format. This feature could be used, for example, to only allow players that are wearing a special wearable item into a place. This information is exposed in the following URL, appending the player’s user id to the url parameter.<player user id> Tip: Try the URL out in a browser to see how the response is structured. To get more real time data about the player, you can query that same information but directly from the same server that the player is currently on. For example, if the player changes clothes, this information will be available instantly in the player’s server, but will take a couple of minutes to propagate to the peer.decentraland.org server. https://<player server>/lambdas/profile/<player user id> Tip: You can obtain the player’s server by doing getCurrentRealm().domain. This example combines getUserData() and getCurrentRealm() to obtain the player’s data directly from the server that the player is on: import { getUserData } from "@decentraland/Identity" import { getCurrentRealm } from "@decentraland/EnvironmentAPI" async fetchPlayerData() { const userData = await getUserData() const playerRealm = await getCurrentRealm() let url = `{playerRealm.domain}/lambdas/profile/{userData.userId}`.toString() log('using URL: ', url) try { let response = await fetch(url) let json = await response.json() log('full response: ', json) log('player is wearing :', json[0].metadata.avatars[0].avatar.wearables ) log('player owns :', json[0].metadata.avatars[0].inventory) } catch { log("an error occurred while reaching for player data") } } fetchPlayerData() Get detailed info about all wearables Make a REST API call to the following URL, to obtain a full updated list of all wearables that are currently usable, with details about each. This feature could be used together with fetching info about the player, to for example only allow players to enter a place if they are wearing any wearable from the halloween collection, or any wearable that is of legendary rarity. Tip: Try the URL out in a browser to see how the response is structured. fetchWearablesData() { let url = `` executeTask(async () => { try { let response = await fetch(url) let json = await response.json() log('full response: ', json) } catch { log("an error occurred while reaching for wearables data") } }) fetchPlayerData()
https://docs.decentraland.org/development-guide/user-data/
CC-MAIN-2021-17
en
refinedweb
I want my program to have the street's and building's data in xml format. But I have no idea how to start this project. I am new to using api's and reading about the api does not tell me how do I actually write api call in my c++ code and retrieve the data. What sources should I refer to write a simple program to say : "retrieve bounding box xml file in osm map" All queries are on wiki page, but where to write this queries and required setup for starting with this api usage is evasive. asked 24 Dec '12, 06:25 Anubha 31●3●3●6 accept rate: 0% edited 24 Dec '12, 06:27 Implementing the API call in your project is very programming/scripting language-specific and hasn't much to do with OSM. This is a minimal working example in plain C/C++ with only minimal error checking and no response processing: #include <iostream> #include <string> #include <vector> #include <cstdio> #include <arpa/inet.h> #include <sys/socket.h> const std::string host = "81.19.81.199"; // IP of overpass.osm.rambler.ru const int port = 80; const std::string query = "GET /cgi/interpreter?data=node%5Bname%3DGielgen%5D%3Bout%3B HTTP/1.1\r\n" "Host: overpass.osm.rambler.ru\r\n" "User-Agent: SteveC\r\n" "Accept: */*\r\n" "Connection: close\r\n" "\r\n"; int main(int argc, char* argv[]) { int sock = socket(AF_INET, SOCK_STREAM, 0); if (sock == -1) { perror("error opening socket"); return -1; } struct sockaddr_in sin; sin.sin_port = htons(port); sin.sin_addr.s_addr = inet_addr(host.c_str()); sin.sin_family = AF_INET; if (connect(sock, (struct sockaddr *)&sin, sizeof(sin)) == -1) { perror("error connecting to host"); return -1; } const int query_len = query.length() + 1; // trailing '\0' if (send(sock, query.c_str(), query_len, 0) != query_len) { perror("error sending query"); return -1; } const int buf_size = 1024 * 1024; while (true) { std::vector<char> buf(buf_size, '\0'); const int recv_len = recv(sock, &buf[0], buf_size - 1, 0); if (recv_len == -1) { perror("error receiving response"); return -1; } else if (recv_len == 0) { std::cout << std::endl; break; } else { std::cout << &buf[0]; } } return 0; } Example output: HTTP/1.1 200 OK Server: nginx/1.0.9 Date: Mon, 24 Dec 2012 11:45:34 GMT Content-Type: application/osm3s+xml Connection: close Content-Length: 1893 Access-Control-Allow-Origin: * <?xml version="1.0" encoding="UTF-8"?> <osm version="0.6" generator="Overpass API"> <note>The data included in this document is from. The data is made available under ODbL.</note> <meta osm_base="2012-12-24T11:44:01Z"/> <node id="371597317" lat="50.7412721" lon="7.1927120"> <tag k="is_in" v="Bonn,Regierungsbezirk Köln,Nordrhein-Westfalen,Bundesrepublik Deutschland,Europe"/> <tag k="name" v="Gielgen"/> <tag k="place" v="suburb"/> </node> [cropped] </osm> I strongly suggest using a third-party library for the network/HTTP code and you will probably also want to use a third-party library for parsing the XML/JSON/whatever response. A much simpler option is to use a scripting language like Python, Ruby, or - if you like camels - Perl. answered 24 Dec '12, 11:51 scai ♦ 32.2k●20●296●445 accept rate: 23% Thank you again (again as you replied in stackOverflow), I ran the code, and it worked, its first time I connected to an internet server. Will make project in which user will be able to ride a car in any part of world he/she wishes, buildings will be mostly random. Ah, I didn't remember your username :) An API call is done via HTTP, so your program needs to open a network connection. Libraries for C++ that do so are discussed for example here. answered 24 Dec '12, 07:08 Roland Olbricht 6.4k●3●59●86 accept rate: 35% Also checkout file handling in Osmium. thanks, any code samples with simple osm api calls would be really helpful. Once you sign in you will be able to subscribe for any updates here Answers Answers and Comments Markdown Basics learn more about Markdown This is the support site for OpenStreetMap. Question tags: osm ×631 overpass ×413 newbie ×188 tutorial ×17 c++ ×9 question asked: 24 Dec '12, 06:25 question was seen: 9,221 times last updated: 24 Dec '12, 13:40 How to edit the map with android (for beginners/newbies)? gathering the information of schools - with overpass-api Get city borders for Finland How can I get Overpass-API to just display my objects with just one tag ? Interactive tutorial to getting started editing OSM osmconvert -filter gives back a pure non-sense result Videos for new contributors Dynamic POI using openstreet map My query to retrieve nodes and ways is not returning all the nodes... osmconvert gives back no adress: city, street and housenumber - not in 15000 result-records First time here? Check out the FAQ!
https://help.openstreetmap.org/questions/18684/i-want-to-use-mainoverpass-api-for-retrieving-data-in-c-program
CC-MAIN-2021-17
en
refinedweb
On Mon, Dec 24, 2018 at 06:10:49PM +0200, Eli Zaretskii wrote: > > Date: Mon, 24 Dec 2018 04:08:47 +0200 > > From: Khaled Hosny <address@hidden> > > Cc: address@hidden, address@hidden, address@hidden, > > address@hidden, address@hidden > > > > I think we are almost good now. There is only one serious FIXME left: > > > > /* FIXME: guess_segment_properties is BAD BAD BAD. > > * we need to get these properties with the LGSTRING. */ > > #if 1 > > hb_buffer_guess_segment_properties (hb_buffer); > > #else > > hb_buffer_set_direction (hb_buffer, XXX); > > hb_buffer_set_script (hb_buffer, XXX); > > hb_buffer_set_language (hb_buffer, XXX); > > #endif > > > > We need to know, for a given lgstring we are shaping: > > * Its direction (from applying bidi algorithm). Each lgstring we are > > shaping must be of a single direction. > > Communicating this to ftfont_shape_by_hb will need changes in a couple > of interfaces (the existing shaping engines didn't need this > information). I will work on this soon. Great. > > * Its script, possibly after applying something like: > > > > Per previous discussions, we decided to use the Harfbuzz built-in > methods for determining the script, since Emacs doesn't have this > information, and adding it will just do the same as Harfbuzz does, > i.e. find the first character whose script is not Common etc., using > the UCD database. I think it was you who suggested to use the > Harfbuzz built-ins in this case.. > > * Its language, is Emacs allows setting text language (my understand is > > that it doesn’t). Some languages really need this for applying > > language-specfic features (Urdu digits, Serbian alternate glyphs, etc.). > > We don't currently have a language property for chunks of text, we > only have the current global language setting determined from the > locale (and there's a command to change that for Emacs, should the > user want it). This is not really appropriate for multilingual > buffers, but we will have to use that for now, and hope that in the > future, infrastructure will be added to allow more flexible > determination of the language of each run of text. (I see that > Harfbuzz already looks a the locale for its default language, but > since Emacs allows user control of this, however unlikely, I think > it's best to use the value Emacs uses.) I will work on this as well. Yes, better pass that from Emacs to HarfBuzz. Regards, Khaled
https://lists.gnu.org/archive/html/bug-gnu-emacs/2018-12/msg00877.html
CC-MAIN-2021-17
en
refinedweb
CSS-in-JS is something I've been unable to stop using on both personal projects and work. CSS has been introducing more and more features, making SCSS less of an obvious choice. At the same time, CSS-in-JS libraries entered the scene. They add some interesting features: Server-Side-Rendering, code splitting as well as better testing. For the purpose of this article, I will be using EmotionJS and React. EmotionJS features TypeScript support, easy setup, and testing integration. Advantages of CSS-in-JS Being JavaScript, it offers all the features modern front-end development relies on. Server-Side Rendering and code split with Emotion Server-Side Rendering (SSR) with Emotion and React is simple. If you have React SSR enabled then congratulations! You have enabled it for Emotion as well. Code splitting is pretty much the same. Emotion is JavaScript so it will code split just like the rest of the application. Sharing props between React and Emotion Building styles based on classes can become quite complicated for big codebases. In most cases, having each prop become a class can increase the verbosity of the code. Having props determine styles without classes would cut a lot of unnecessary code. const classes = `${className} ${theme || "off-white"} ${size || "medium"} ${border !== false ? "with-border" : ""} ${inverted ? "inverted" : ""} ${disabled ? "disabled" : ""}`; The example above shows how convoluted a template literal can become. This can be avoided by leveraging Emotion. import { css } from "@emotion/core"; import styled from "@emotion/styled"; const themes = { red: css` color: pink; background: red; border-color: pink; `, blue: css` color: light-blue; background: blue; border-color: light-blue; `, }; const sizes = { small: '8px', medium: '12px', large: '16px' } const disabledCss = css` color: grey; border-color: grey; `; /* Defining the button with the conditional styles from props */ const StyledButton = styled.button` ${(props) => themes[props.theme]}; font-size: ${(props) => sizes[props.size]}; border: ${(props) => props.border ? '1px solid' : 'none'}; ${(props) => props.disabled && disabledCss}; `; /* And finally how to use it */ <StyledButton theme="red" size="medium" border={true} disabled={false} > Hello </StyledButton> There are no classes to depend on. The styles are applied to the components, removing the classes layer. New styles are easily added and even more easily removed, JavaScript handles variables far better than we handle classes. These atomic styles are easy to share across the codebase. Being variables, they can be imported and exported to other files. Testing Emotion and React Style regression and changes have always been up to the developer to check manually. CSS and SCSS do not allow to test this in any meaningful way. Jest allows to snapshot React components to see diffs in HTML, making sure changes are safe. In the same way, Emotion styles can be snapshotted. Snapshotting CSS removes the need to have to check manually if the styles break when making new changes. This can be a huge time saver for both developers and testers who can ship code with more confidence. Achieving all this in Emotion is rather fast. Add this to your Jest setup file import * as emotion from 'emotion' import { createSerializer } from 'jest-emotion' expect.addSnapshotSerializer(createSerializer(emotion)) And it's done. When creating a snapshot, the EmotionJS output will be included in the snapshot. Closing thoughts CSS-in-JS has drastically changed the way to write CSS. Leveraging the most used programming language gives CSS new features to improve the way styles can be written. Performance, maintainability, and testing are the core of a good application. CSS-in-JS offers improvements over older standards to all these issues. originally posted on decodenatura Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/kornil/about-css-in-js-and-react-5ajg
CC-MAIN-2021-17
en
refinedweb
Created on 2018-03-25 21:10 by prounce, last changed 2018-07-25 12:47 by xtreak. In my view there is a fault in python3 pdb in that if you use pdb.set_trace() after using os.chdir() to change the cwd to a directory that does not contain the source code being executed, then there is no instruction output on next or step. This is shown in the following code where I have added print lines to bdb.py file to show the errors. [The tes program is attached. python3 testpdb.py # To output a line of code the canonic function in bdp.py is called # to build an absolute path to the source code being executed. PRINT --> canonic line 32 - canonic = None PRINT --> canonic line 36 - canonic_abs = /home/pythontest/Software/python/3/testpdb.py # the following is printed after the call to linecache and shows # the file accessed, the line number in the code and # the instruction string returned PRINT --> filename: /home/pythontest/Software/python/3/testpdb.py - lineno: 11, line: e=d+5 > /home/pythontest/Software/python/3/testpdb.py(11)<module>() -> e=d+5 (Pdb) c # The program is continued and os.chdir("/tmp") is executed. # Another pdb.set_trace() has been executed, which creates a new Pdb # class instance, and thus a new Bdb instance, where Bdb.fncache # used by the canonic function is {}. # The canonic function is passed just the filename 'testpdb.py" and # canonic uses os.path.abs to get a full path. Of course this gives # the wrong path to testpdb.py since it just prepends the current # cwd, thus:- PRINT --> canonic line 32 - canonic = None PRINT --> canonic line 36 - canonic_abs = /tmp/testpdb.py # the call to linecache in format_cache_entry (line 411) doesn't # find the source code so returns an empty string. PRINT --> filename: /tmp/testpdb.py - lineno: 15, line: > /tmp/testpdb.py(15)<module>() (Pdb) c Why canonic is using os.path.abs is not clear to me: it seems to be a mistake, but it is surprising that it has not been found, if this is the case. It is interesting to note that linecache itself, when reading from a file with just a filename (and not an absolute path) does not try to guess the path with os.path.abs but looks down the python 'sys.path' to find the full path to the file. This would look like a reasonable solution, but it might be better to extend the existing code by checking the full path from the 'os.path.abs' instruction with an os.exists call and if this fails doing a search down 'sys.path'. The modified code in bdb.py for this solution is:- def getfullpath(self, basename) : for dirname in sys.path: try: fullname = os.path.join(dirname, basename) except (TypeError, AttributeError): # Not sufficiently string-like to do anything useful with. continue try: stat = os.stat(fullname) break except OSError: pass else: return [] return fullname def canonic(self, filename): if filename == "<" + filename[1:-1] + ">": return filename canonic = self.fncache.get(filename) if not canon ic: canonicabs = canonic = os.path.abspath(filename) canonic = os.path.normcase(canonic) # if path does not exists look down sys.path if not os.path.exists(canonic) : canonic = self.getfullpath(filename) canonic = os.path.normcase(canonic) self.fncache[filename] = canonic return canonic Seems related :
https://bugs.python.org/issue33139
CC-MAIN-2021-17
en
refinedweb
QBluetooth Namespace The QBluetooth namespace provides classes and functions related to Bluetooth. More... Types Detailed Description The QBluetooth namespace provides classes and functions related to Bluetooth.. typedef QLowEnergyHandle Typedef for Bluetooth Low Energy ATT attribute handles. This typedef was introduced in Qt 5.4. enum QBluetooth::Security flags QBluetooth::SecurityFlags This enum describe the security requirements of a Bluetooth service. The SecurityFlags type is a typedef for QFlags<Security>. It stores an OR combination of Security.
https://doc.qt.io/archives/qt-5.8/qbluetooth.html
CC-MAIN-2021-17
en
refinedweb
I would see support of all argument kinds support in any proposal for a new callable: positional only args, named args, keyword-only, *args and **kwargs. The exact notation in probably less important than missing functionality. On Sat, Nov 28, 2020, 18:50 Abdulla Al Kathiri alkathiri.abdulla@gmail.com wrote: I don’t know if this has been discussed before. Similar to PEP 645 idea of writing "Optional[type]" as “type?”, I propose we write "Callable[[type1, type2, ...], type3]” as “[type1, type2, … -> type3]”. Look at the two examples below and see which one looks better to the eyes: def func1(f: typing.Callable[[str, int], str], arg1: str, arg2: int) -> str: return f(arg1, arg2) def func2(f: [str, int-> str], arg1: str, arg2: int) -> str: return f(arg1, arg2) There is less clutter especially if we have nested Callables. e.g., f: Callable[[str, int], Callable[[int,…], str]] becomes f: [str, int -> [int, ... -> str]] Callable without zero arguments.. f: Callable[[], str] would become f: [ -> str] Equivalent to Callable alone without caring about arguments and the return value would be [… -> typing.Any] or [… -> ] Let’s say we have a function that accepts a decorator as an argument. This might not be useful to do, but I want to show case how it would be easier to read. The old way would be: def decorator(f: Callable[…, int]) -> Callable[…, tuple[int, str]]: def wrapper(*args, **kwargs) -> tuple[int, str]: text = “some text” res = f(*args, **kwargs) return res, text return wrapper def function(decorator: Callable[[Callable[…, int]], Callable[…, tuple[int, str]]], decorated_on: Callable[…, int]) -> Callable[…, tuple[int, str]]: wrapper = decorator(decorated_on) return wrapper The new way is as follows: def decorator(f: [… -> int]) -> [… -> tuple[int, str]]: def wrapper(*args, **kwargs) -> tuple[int, str]: text = “some text” res = f(*args, **kwargs) return rest, text return wrapper def function(decorator: [ [… -> int] -> [… -> tuple[int, str]]], decorated_on: [… -> int]) -> [… -> tuple[int, str]]: wrapper = decorator(decorated_on) return wrapper I saw something similar in Pylance type checker (VSC extension) when you hover over an annotated function that has Callable as an argument or a return value, but they don’t seem to use brackets to mark the beginning and end of the callable, which could be hard to follow mentally (see screenshot below) Personally, I think it would be easier if Pylance wrote the hint like the following: (function) function: (decorator: [p0:[*args: Any, **kwargs: Any -> int ]] -> [*args: Any, **kwargs: Any -> tuple[int, str]], decorated_on: [*args: Any, **kwargs: Any -> int]) -> [*args: Any, **kwargs: Any -> tuple[int, str]] Python-ideas mailing list -- python-ideas@python.org To unsubscribe send an email to python-ideas-leave@python.org Message archived at... Code of Conduct:
https://mail.python.org/archives/list/python-ideas@python.org/message/GMTGXCV2WLAXQSQRFJCWSCXO4UTSLV5W/
CC-MAIN-2021-17
en
refinedweb
Changes between Initial Version and Version 1 of Ticket #41760 Legend: - Unmodified - Added - Removed - Modified Ticket #41760 - Property Owner changed from macports-tickets@… to swinbank@… - Property Summary changed from gle-grapyics build fails with C++ namespace errorsto gle-graphics build fails with C++ namespace errors Ticket #41760 – Description
https://trac.macports.org/ticket/41760?action=diff&version=1
CC-MAIN-2021-17
en
refinedweb
Reverse Geocoding¶ The reverse_geocode() function in the arcgis.geocoding module determines the address at a particular x/y location. You pass the coordinates of a point location to the geocoder, and it returns the address that is closest to the location. In this guide we will learn about: from arcgis.geocoding import reverse_geocode help(reverse_geocode) Help on function reverse_geocode in module arcgis.geocoding._functions: reverse_geocode(location, distance=None, out_sr=None, lang_code=None, return_intersection=False, for_storage=False, geocoder=None) The reverse_geocode operation determines the address at a particular x/y location. You pass the coordinates of a point location to the geocoding service, and the service returns the address that is closest to the location. Input: location - a list defined as [X,Y] or a Point Geometry object distance - allows you to specify a radial distance in meters to search for an address from the specified location. If no distance value is specified then the value is assumed to be 100 meters. out_sr - spatial reference of the x/y coordinates returned. lang_code - sets the language in which reverse-geocoded addresses are returned. return_intersection - Boolean which specifies whether the service should return the nearest street intersection or the nearest address to the input location for_storage - specifies whether the results of the operation will be persisted geocoder - Optional, the geocoder to be used. If not specified, the active GIS's first geocoder is used. location parameter¶ The point from which to search for the closest address. The point can be represented as a simple list of coordinates ([x, y] or [longitude, latitude]) or as a JSON point object. The spatial reference of the list of coordinates is always WGS84 (in decimal degress), the same coordinate system as the World Geocoding Service. Use JSON formatting to specify any other coordinate system for the input location. Specifically, set the spatial reference using its well-known ID (WKID) value. For a list of valid WKID values, see Projected Coordinate Systems and Geographic Coordinate Systems. Example using simple syntax and the default WGS84 spatial reference: location=[103.8767227,1.3330736] Example using JSON and the default WGS84 spatial reference: location={x: 103.876722, y: 1.3330736} Example using JSON and specifying a spatial reference (WGS84 Web Mercator Auxiliary Sphere): location= { "x": 11563503, "y": 148410, "spatialReference": { "wkid": 3857 } } Example: Reverse geocode the location x = 2.2945, y = 48.8583¶ from arcgis.gis import GIS from arcgis.geocoding import reverse_geocode gis = GIS("portal url", "username", "password") results = reverse_geocode([2.2945, 48.8583]) results {'address': {'Address': '6 Avenue Gustave Eiffel', 'City': 'Paris', 'CountryCode': 'FRA', 'Loc_name': 'FRA.PointAddress', 'Match_addr': '6 Avenue Gustave Eiffel, 75007, 7e Arrondissement, Paris, Île-de-France', 'Neighborhood': '7e Arrondissement', 'Postal': '75007', 'PostalExt': None, 'Region': 'Île-de-France', 'Subregion': 'Paris'}, 'location': {'spatialReference': {'latestWkid': 4326, 'wkid': 4326}, 'x': 2.29465293958984, 'y': 48.85748501186063}} from arcgis.geometry import Geometry pt = Geometry({ "x": 11563503, "y": 148410, "spatialReference": { "wkid": 3857 } }) results = reverse_geocode(pt) results {'address': {'Address': '40 Lichi Avenue', 'City': None, 'CountryCode': 'SGP', 'Loc_name': 'SGP.PointAddress', 'Match_addr': '40 Lichi Avenue, 348814, Singapore', 'Neighborhood': None, 'Postal': '348814', 'PostalExt': None, 'Region': None, 'Subregion': None}, 'location': {'spatialReference': {'latestWkid': 4326, 'wkid': 4326}, 'x': 103.87671886128821, 'y': 1.3330587058289018}} distance parameter¶ The optional distance parameter allows you to specify a radial distance in meters to search for an address from the specified location. If no distance value is specified then the value is assumed to be 100 meters. Example: distance=50 out_sr parameter¶ The spatial reference of the x/y coordinates returned by a geocode request. This is useful for applications using a map with a spatial reference different than that of the geocode service. The spatial reference can be specified as either a well-known ID (WKID) or as a JSON spatial reference object. If out_sr is not specified, the spatial reference of the output locations is the same as that of the service. lang_code parameter¶ Sets the language in which reverse-geocoded addresses are returned. Addresses in many countries are available in more than one language; in these cases the langCode parameter can be used to specify which language should be used for addresses returned by the reverse_geocode() method. This is useful for ensuring that addresses are returned in the expected language by reverse geocoding functionality in an application. For example, a web application could be designed to get the browser language and then pass it as the langCode parameter value in a reverseGeocode request. See the table of supported countries for valid language code values in each country. The Two-Digit Language Codes column provides the valid input values for the langCode parameter. Only the two-digit language codes in this column are accepted as valid input; neither three-digit language codes nor full language names can be used with the langCode parameter. Note: The language code "XX" is a convention used to represent transliterated or transcribed versions of a language. In addition to the supported language codes, the table also includes the Default Language Code column, which lists the default language of addresses returned by the reverseGeocode operation for each country. For countries with multiple supported languages, the default language is the one spoken by the highest percentage of the country's population. Addresses are not always available in the default language for the entirety of a particular country. Note: The langCode parameter is not supported for Japan and Hong Kong locations. Similarly, when there are multiple supported languages for addresses in a country it doesn't mean that every address in the country is available in each of the languages. It may be the case that addresses are available in multiple languages for only one region of the country, or that each language is exclusive to different regions and there is no overlap at all. Examples: - Both English and French are listed as supported languages for Canada. However there is no overlap between the languages for any addresses - in the province of Quebec only French addresses are available, while English is the only language used for the rest of the country. - In Belgium, where three languages are supported (Dutch, French, and German), addresses are available in the city of Brussels in both Dutch and French; however, in the rest of the country the addresses are only available in a single language. - In Greece there is complete address coverage in both Greek and transliterated Greek languages (Greek words translated with Latin characters). Due to variability of language coverage, the following logic is used to handle the different scenarios which may be encountered. Example: lang_code="fr" return_intersection parameter¶ A Boolean which specifies whether the service should return the nearest street intersection or the nearest address to the input location. If true, then the closest intersection to the input location is returned; if false, then the closest address to the input location is returned. The default value is false. Example: return_intersection=True for_storage parameter¶ Specifies whether the results of the operation will reverse-geocoding transactions unless they make the request by passing the forStorage parameter with a value of True Example: Reverse geocode a location in Brussels with lang_code='fr' (location = 4.366281,50.851994)¶ result = reverse_geocode([4.366281,50.851994], lang_code="fr") result {'address': {'Address': 'Rue de la Sablonnière 15', 'City': 'Bruxelles', 'CountryCode': 'BEL', 'Loc_name': 'BEL.PointAddress', 'Match_addr': 'Rue de la Sablonnière 15, 1000, Bruxelles', 'Neighborhood': 'Bruxelles', 'Postal': '1000', 'PostalExt': None, 'Region': 'Bruxelles', 'Subregion': 'Bruxelles'}, 'location': {'spatialReference': {'latestWkid': 4326, 'wkid': 4326}, 'x': 4.366265813154625, 'y': 50.85196404988331}} from arcgis.gis import GIS from arcgis.geocoding import reverse_geocode gis = GIS("portal url", "username", "password") m = gis.map('Redlands, CA', 14) m 370 N New York St, Redlands, California, 92373 380 New York St, Redlands, California, 92373 def find_addr(m, g): try: geocoded = reverse_geocode(g) print(geocoded['address']['Match_addr']) except: print("Couldn't match address. Try another place...") m.on_click(find_addr) Feedback on this topic?
https://developers.arcgis.com/python/guide/reverse-geocoding/
CC-MAIN-2021-17
en
refinedweb
Deep Learning with TensorFlow 2.0 Tutorial – Building Your First ANN with TensorFlow 2.0 Deep learning with Tensorflow # pip install tensorflow==2.0.0-rc0 # pip install tensorflow-gpu==2.0.0-rc0 Watch Full Lesson Here: Objective - Our objective for this code is to build to an Artificial neural network for classification problem using tensorflowand keraslibraries. We will try to learn how to build a nerual netwroks model using tensorflowand kerasthen we will analyse our model using different accuracy metrics. What is ANN? Artificial Neural Networks (ANN) is a supervised learning system built of a large number of simple elements, called neurons or perceptrons. Each neuron can make simple decisions, and feeds those decisions to other neurons, organized in interconnected layers. What is Activation Function? - In artificial neural networks, the activation functionof a node defines the output of that node given an input or set of inputs. A standard integrated circuit can be seen as a digital network of activation functions that can be “ON” (1) or “OFF” (0), depending on input. This is similar to the behavior of the linear perceptron in neural networks. - If we do not apply a Activation function then the output signal would simply be a simple linear function.A linear function is just a polynomial of one degree. Types of Activation Function - Sigmoid - Tanh - ReLu - LeakyReLu - SoftMax Sigmoid Softmax Funcation What is Back Propagation? - In backpropagationwe update the parameters of the model with respect to loss function. Loss function can be cross entropyfor classificationproblem and root mean squared errorfor regressionproblems. - Our objective is to minimize lossof our model. So to minimize loss of our model we caluculate gradeint of losswith respect to paramtersof model and try to minimize the this gradient. while minimizing the gradient we update the weights of our model this process is known as back propagation. Steps for building your first ANN - Data Preprocessing - Add input layer - Random w init - Add Hidden Layers - Select Optimizer, Loss, and Performance Metrics - Compile the model - use model.fit to train the model - Evaluate the model - Adjust optimization parameters or model if needed Data Preprocessing - It is better to preprocess data before giving it to any neural net model. Data should be normally distributed(gaussian distribution), so that model performs well. - If our data is not normally distributed that means there is skewnessin data. To remove skewness of data we can take logarithm of data . by using log function we can remove skewness of data. - After removing skewness of data it is better to scale of data so that all values are at same scale. - We can either use MinMax scaleror Standardscaler. - Standardscalers are better to use since by using it mean and variance of our data is now 0 and 1 respectively . That is now our data is in form of N(0,1) that is gaussian distribution with mean 0 and variance 1. Layers Adding input layer - according to size of our input we add number of input layers. Adding hidden layers - We can add as many hidden layers. if we want our model to be complex than large number of hidden layers can be added and for simple model number of hidden layes can be small Adding output layer - In a classification problemsize of output layer depend on number of classes. - In regression problemthere is size of output layer is one Weight initialization - The meanof the weights should be zero. - The varianceof the weights should stay the same across every layer. Optimizers Gradient Descent - Gradient descent is a first-order optimization algorithm which is dependent on the first order derivative of a loss function. It calculates that which way the weights should be altered so that the function can reach a minima. Through backpropagation, the loss is transferred from one layer to another and the model’s parameters also known as weights are modified depending on the losses so that the loss can be minimized. Stochastic Gradient Descent - It’s a variant of Gradient Descent. It tries to update the model’s parameters more frequently. In this, the model parameters are altered after computation of loss on each training example. So, if the dataset contains 1000 rows SGD will update the model parameters 1000 times in one cycle of dataset instead of one time as in Gradient Descent. Mini-Batch Gradient Descent - It’s best among all the variations of gradient descent algorithms. It is an improvement on both SGD and standard gradient descent. It updates the model parameters after every batch. So, the dataset is divided into various batches and after every batch, the parameters are updated. Adagrad - It is gradient descent with adaptive learning rate - in this the learning rate decays for parameters in proportion to their update history(more updates means more decay) losses Cross entropyfor Classification problems. Root mean squarederror for regression problems. Accuracy metrics Installing libraries # pip install tensorflow==2.0.0-rc0 # pip install tensorflow-gpu==2.0.0-rc0 import tensorflow as tf from tensorflow import keras from tensorflow.keras import Sequential from tensorflow.keras.layers import Flatten, Dense print(tf.__version__) 2.2.0 Importing necessary libraries import numpy as np import pandas as pd from sklearn.model_selection import train_test_split dataset = pd.read_csv('Customer_Churn_Modelling.csv') dataset.head() X = dataset.drop(labels=['CustomerId', 'Surname', 'RowNumber', 'Exited'], axis = 1) y = dataset['Exited'] X.head() y.head() 0 1 1 0 2 1 3 0 4 0 Name: Exited, dtype: int64 Using label encoder we are converting categorical features to numerical features from sklearn.preprocessing import LabelEncoder label1 = LabelEncoder() X['Geography'] = label1.fit_transform(X['Geography']) label = LabelEncoder() X['Gender'] = label.fit_transform(X['Gender']) X.head() X = pd.get_dummies(X, drop_first=True, columns=['Geography']) X.head() - Here using standardscaler we are scaling our data, we are scaling such that the mean is 0 and variance is 1 for data from sklearn.preprocessing import StandardScaler X_train, X_test, y_train, y_test = train_test_split(X, y, test_size = 0.2, random_state = 0, stratify = y) scaler = StandardScaler() X_train = scaler.fit_transform(X_train) X_test = scaler.transform(X_test) X_train array([[-1.24021723, -1.09665089, 0.77986083, ..., 1.64099027, -0.57812007, -0.57504086], [ 0.75974873, 0.91186722, -0.27382717, ..., -1.55587522, 1.72974448, -0.57504086], [-1.72725557, -1.09665089, -0.9443559 , ..., 1.1038111 , -0.57812007, -0.57504086], ..., [-0.51484098, 0.91186722, 0.87565065, ..., -1.01507508, 1.72974448, -0.57504086], [ 0.73902369, -1.09665089, -0.36961699, ..., -1.47887193, -0.57812007, -0.57504086], [ 0.95663657, 0.91186722, -1.32751517, ..., 0.50945854, -0.57812007, 1.73900686]]) Build ANN - Here bwe are building ANN model. - First we add input layer of shape of input that is 11 in this case. - There is only one hidden layers whose shape is 128. - Shape of Output layer is only 1 since we have only one output. model = Sequential() model.add(Dense(X.shape[1], activation='relu', input_dim = X.shape[1])) model.add(Dense(128, activation='relu')) model.add(Dense(1, activation = 'sigmoid')) X.shape[1] 11 - Here we are compiling our model. we have selected Adam optimizer. loss is binary crossentropy and metric is accuracy model.compile(optimizer='adam', loss = 'binary_crossentropy', metrics=['accuracy']) - Here we are fitting model on training dataset . we have given bacth size of 10 and eopchs are 10 model.fit(X_train, y_train.to_numpy(), batch_size = 10, epochs = 10, verbose = 1) Epoch 1/10 800/800 [==============================] - 1s 2ms/step - loss: 0.4516 - accuracy: 0.8116 Epoch 2/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3948 - accuracy: 0.8372 Epoch 3/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3597 - accuracy: 0.8543 Epoch 4/10 800/800 [==============================] - 1s 2ms/step - loss: 0.3475 - accuracy: 0.8576 Epoch 5/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3426 - accuracy: 0.8611 Epoch 6/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3389 - accuracy: 0.8619 Epoch 7/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3366 - accuracy: 0.8625 Epoch 8/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3350 - accuracy: 0.8629 Epoch 9/10 800/800 [==============================] - 1s 2ms/step - loss: 0.3333 - accuracy: 0.8635 Epoch 10/10 800/800 [==============================] - 1s 1ms/step - loss: 0.3311 - accuracy: 0.8634 <tensorflow.python.keras.callbacks.History at 0x271d1a03580> - Using model.predict we predict output values for our input data. y_pred = model.predict_classes(X_test) y_pred array([[0], [0], [0], ..., [0], [1], [0]]) y_test 1344 1 8167 0 4747 0 5004 1 3124 1 .. 9107 0 8249 0 8337 0 6279 1 412 0 Name: Exited, Length: 2000, dtype: int64 model.evaluate(X_test, y_test.to_numpy()) 63/63 [==============================] - 0s 2ms/step - loss: 0.3489 - accuracy: 0.8520 [0.34891313314437866, 0.8519999980926514] from sklearn.metrics import confusion_matrix, accuracy_score Confusion matrix confusion_matrix(y_test, y_pred) array([[1546, 47], [ 249, 158]], dtype=int64) accuracy_score(y_test, y_pred) 0.852 Summary - In this notebook we have implemented a classifer using artificial neural network. We build the model using tensorflow and keras. We checked the accuracy using Accuracy metrics and Confusion metrix. Accuracy for the model was 85.2% on test data.
https://kgptalkie.com/deep-learning-with-tensorflow-2-0-tutorial-building-your-first-ann-with-tensorflow-2-0/
CC-MAIN-2021-17
en
refinedweb
java.io.CharArrayReader class creates a character buffer using a character array. Declaration: public class CharArrayReader extends Reader Constructor : - CharArrayReader(char[] char_array) : Creates a CharArrayReader from a specified character array. - CharArrayReader(char[] char_array, int offset, int maxlen) : Creates a CharArrayReader from a specified part of character array. Methods: - read() : java.io.CharArrayReader.read() reads a single character and returns -1 if end of the Stream is reached. Syntax : public int read() Parameters : ----------- Return : Returns read character as an integer ranging from range 0 to 65535. -1 : when end of file is reached. - read(char[] char_array, int offset, int maxlen) : java.io.CharArrayReader.read(char[] char_array, int offset, int maxlen)) reads a single character and returns -1 if end of the Stream is reached Syntax : public int read(char[] char_array, int offset, int maxlen)) Parameters : char_array : destination array offset : starting position from where to store characters maxlen : maximum no. of characters to be read Return : Returns all the characters read -1 : when end of file is reached. - ready() : java.io.CharArrayReader.ready() checks whether the Stream is ready to be read or not. CharArrayReader are always ready to be read. Syntax : public boolean ready() Parameters : ----------- Return : true if CharArrayReader is ready to be read. - skip(long char) : java.io.CharArrayReader.skip(long char_no) skips ‘char_no’ no. of characters. If n is negative, then this method does nothing and returns 0. Syntax : public long skip(long char) Parameters : char_no : char no. of characters to be skipped Return : no. of characters skipped Exception : IOException : In case of I/O error occurs Output : char_array1 is ready Use of read() method : G Characters Skipped : 72 E Characters Skipped : 70 S Characters Skipped : 84 char_array2 is ready Use of read(char[] char_array, int offset, int maxlen) method : EKS - mark(int readLimit) : java.io.CharArrayReader.mark(int readLimit) marks the current position in the Stream upto which the character can be read. This method always invokes reset() method. Subsequent calls to reset() will reposition the stream to this point. Syntax : public long mark(int readLimit) Parameters : readLimit : No. of characters that can be read up to the mark Return : void Exception : IOException : In case of I/O error occurs - markSupported() : java.io.CharArrayReader.markSupported() tells whether the mark method is supported by the stream or not. Syntax : public boolean markSupported() Parameters : ------- Return : true if the mark method is supported by the stream Exception : IOException : In case of I/O error occurs - reset() : java.io.CharArrayReader.reset() Resets the stream to the most recent mark, or to the beginning if it has never been marked. Syntax : public void reset() Parameters : ------- Return : void Exception : IOException : In case of I/O error occurs - close() : java.io.CharArrayReader.close() closes the stream amd reallocates the resources that were allotted to it. Syntax : public void close() Parameters : ------- Return : void Exception : IOException : In case of I/O error occurs Output : Char : H Char : E Char : L mark() method comes to play Char : L Char : O Char : G mark() supported reset() invoked Char : L Char : O This article is contributed by Mohit Gupta.
https://www.geeksforgeeks.org/java-io-chararrayreader-class-java/?ref=rp
CC-MAIN-2021-17
en
refinedweb
Investors in Liberty Global plc - Class A Ordinary Shares (Symbol: LBTYA) saw new options begin trading this week, for the November 15th expiration. At Stock Options Channel, our YieldBoost formula has looked up and down the LBTYA options chain for the new November 15 LBTYA, that could represent an attractive alternative to paying $24.80/share today. Because the $20 97%..86% annualized — at Stock Options Channel we call this the YieldBoost. Below is a chart showing the trailing twelve month trading history for Liberty Global plc - Class A Ordinary Shares, and highlighting in green where the $20.00 strike is located relative to that history: Turning to the calls side of the option chain, the call contract at the $25.00 strike price has a current bid of 70 cents. If an investor was to purchase shares of LBTYA stock at the current price level of $24.80/share, and then sell-to-open that call contract as a "covered call," they are committing to sell the stock at $25.00. Considering the call seller will also collect the premium, that would drive a total return (excluding dividends, if any) of 3.63% if the stock gets called away at the November 15th expiration (before broker commissions). Of course, a lot of upside could potentially be left on the table if LBTYA shares really soar, which is why looking at the trailing twelve month trading history for Liberty Global plc - Class A Ordinary Shares, as well as studying the business fundamentals becomes important. Below is a chart showing LBTYA's trailing twelve month trading history, with the $25.00 strike highlighted in red: Considering the fact that the .82% boost of extra return to the investor, or 21.01% annualized, which we refer to as the YieldBoost. The implied volatility in the put contract example is 57%, while the implied volatility in the call contract example is 44%. Meanwhile, we calculate the actual trailing twelve month volatility (considering the last 251 trading day closing values as well as today's price of $24.80).
https://www.nasdaq.com/articles/interesting-lbtya-put-and-call-options-for-november-15th-2019-09-27
CC-MAIN-2021-17
en
refinedweb
Vectorial division)] Numpy arrays admit elementwise operations. So you could convert the matrix to a Numpy array, compute the new matrix R and then come back to a SageMath matrix: import numpy R = D.numpy() R = numpy.diff(R, axis=0)/R[0:-1,:] R = matrix(R) You can also opt for a pure Python approach: nr, nc = D.nrows()-1, D.ncols() R = matrix(nr, nc, [(D[i+1,j]-D[i,j])/D[i,j] for i in range(nr) for j in range(nc)]) The first method is faster. Both r1=[vector((D[j+1][i]-D[j][i])/D[j][i] for i in range(D[j].degree())) for j in range(D.nrows()-1)] and r1=[vector((D[j+1, i]-D[j, i])/D[j, i] for i in range(D[j].degree())) for j in range(D.nrows()-1)] work for me. (Elementwise vector division is not a standard mathematical operation, so it makes sense that just dividing by D[j] is not implemented in SageMath, nor should it be, since the software is aimed at mathematical use.) Try it: D = ... some matrix ..., then v = D[0]. Then do v.degree? to see Return the degree of this vector, which is simply the number of entries. You could replace D[j].degree() by D.ncols(). Please start posting anonymously - your entry will be published after you log in or create a new account. Asked: 2020-06-23 01:09:31 +0200 Seen: 127 times Last updated: Jun 23 '20 "Abstract" linear algebra Abstract Algebra Question Quotient decomposition by Groebner basis Using numerical solution from system of equations How can I construct modules as quotient algebras? Simplification of expression with exponentials. What does it mean to divide a vector by a vector? I think he refers to elementwise division.
https://ask.sagemath.org/question/52162/vectorial-division/
CC-MAIN-2021-17
en
refinedweb
The year 2020 has seen a lot of changes in the React Native world: - community adoption of React Hooks in React Native apps has increased - the docs have a new domain - the popular navigation library react-navigationadopted a declarative and component-based approach to implement navigation in an app react-native-firebase, the go-to package to use Firebase SDK, released its sixth version In this tutorial, I am going to walk you through building a simple chat application that a user can log in to without credentials and straightaway enter a chat room using the anonymous sign-in method provided by Firebase. The purpose of this tutorial is to get you familiar with all the latest updates in React Native world and its libraries like react-navigation and react-native-firebase that are used often. If you wish to add a new feature that is not covered in this tutorial, feel free to do that and follow along at your own pace. Requirements The following requirements will make sure you have a suitable development environment: - Node.js above 10.x.xinstalled on your local machine - JavaScript/ES6 basics watchmanthe file watcher installed react-native-cliinstalled through npm or access via npx For a complete walkthrough on how you can set up a development environment for React Native, you can go through official documentation here. Also, do note that the following tutorial is going to use the react-native version 0.61.5. Please make sure you are using a version of React Native above 0.60.x. Getting started with the Crowdbotics App Builder To generate a new React Native project you can use the react-native cli tool. Or, if you want to follow along, I am going to generate a new app using the Crowdbotics App Builder. > us get back to our tutorial. Setting up navigation To start, create a new React Native project and install the dependencies to set up and use the react-navigation library. # create a new project npx react-native init rnAnonChatApp cd rnAnonChatApp # install core navigation dependencies yarn add @react-navigation/native @react-navigation/stack react-native-reanimated react-native-gesture-handler react-native-screens react-native-safe-area-context @react-native-community/masked-view From React Native 0.60.x and higher, linking is automatic so you don't need to run react-native link. To finalize the installation, on iOS, you have to install pods. (Note: Make sure you have Cocoapods installed.) cd ios/ && pod install # after pods are installed cd .. Similarly, on Android, open android/app/build.gradle and add the following two lines in the dependencies section: implementation 'androidx.appcompat:appcompat:1.1.0-rc01' implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0-alpha02' Lastly, to save the app from crashing in a production environment, add the following line in index.js. import 'react-native-gesture-handler' import { AppRegistry } from 'react-native' import App from './App' import { name as appName } from './app.json' AppRegistry.registerComponent(appName, () => App) That's it for setting up the react-navigation library. Adding vector icons What is a mobile app without the use of icons? One famous library created by Oblador is called react-native-vector-icons. This library has a set of icons bundled from AntDesign, FontAwesome, Ionicons, MaterialIcons, and so on. In this section, let us install that. Open up a terminal window and run the command yarn add react-native-vector-icons to install the library. After the library is installed, for iOS, copy the following list of fonts inside ios/rnAnonChatApp/Info.plist. <key>UIAppFonts</key> <array> <string>AntDesign.ttf</string> <string>Entypo.ttf</string> <string>EvilIcons.ttf</string> <string>Feather.ttf</string> <string>FontAwesome.ttf</string> <string>FontAwesome5_Brands.ttf</string> <string>FontAwesome5_Regular.ttf</string> <string>FontAwesome5_Solid.ttf</string> <string>Foundation.ttf</string> <string>Ionicons.ttf</string> <string>MaterialIcons.ttf</string> <string>MaterialCommunityIcons.ttf</string> <string>SimpleLineIcons.ttf</string> <string>Octicons.ttf</string> <string>Zocial.ttf</string> </array> Then, open ios/Podfile and add the following: 'RNVectorIcons', :path => '../node_modules/react-native-vector-icons' Open a terminal window to install pods. cd ios/ && pod install # after pods are installed cd .. For Android, make sure you add the following in android/app/build.gradle: apply from: "../../node_modules/react-native-vector-icons/fonts.gradle" That's it to set up a vector icons library in a React Native project. Build two screens Before you proceed to set up a navigation pattern in this app to switch between the different screens, let us create two different screens first. Create a new file called src/screens/Login.js and add the following code snippet. For now, it going to display a message and a button. This screen is going to be displayed when the user isn't authenticated to enter the app and access a chat room. // Login.js import React from 'react' import { View, StyleSheet, Text, TouchableOpacity } from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' export default function Login() { // firebase login function later return ( <View style={styles.container}> <Text style={styles.title}>Welcome to 🔥 Chat App</Text> <TouchableOpacity style={styles.button} onPress={() => alert('Anonymous login')}> <Text style={styles.buttonText}>Enter Anonymously</Text> <Icon name='ios-lock' size={30} </TouchableOpacity> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#dee2eb' }, title: { marginTop: 20, marginBottom: 30, fontSize: 28, fontWeight: '500' }, button: { flexDirection: 'row', borderRadius: 30, marginTop: 10, marginBottom: 10, width: 300, height: 60, justifyContent: 'center', alignItems: 'center', backgroundColor: '#cf6152' }, buttonText: { color: '#dee2eb', fontSize: 24, marginRight: 5 } }) Next, create another file in the same directory called ChatRoom.js with the following code snippet: //ChatRoom.js import React from 'react' import { View, StyleSheet, Text } from 'react-native' export default function ChatRoom() { return ( <View style={styles.container}> <Text style={styles.title}> You haven't joined any chat rooms yet :'( </Text> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#dee2eb' }, title: { marginTop: 20, marginBottom: 30, fontSize: 28, fontWeight: '500' } }) For now, the above screen component is going to display a text message, but later it is going to contain many functionalities and features for the user to interact with. Setting up two separate navigators Start by creating a new directory src/navigation/ and inside it, two new files: SignOutStack.js Both of these files are self-explanatory by their names. Their functionality is going to contain screens related to the state of the app. For example, the SignInStack.js is going to have a stack navigator that has screen files (such as ChatRoom.js) that a user can only access after they are authenticated. What is a stack navigator? A Stack Navigator provides the React Native app with a way to transition between different screens, similar to how the navigation in a web browser works. It pushes or pops a screen when in the navigational state. Now that you have an idea of what exactly a stack navigator is, understand what NavigationContainer and createStackNavigator do. NavigationContaineris a component that manages the navigation tree. It also contains the navigation state and has to wrap all the navigator’s structure. createStackNavigatoris a function used to implement a stack navigation pattern. This function returns two React components: Screenand Navigator, which help us configure each component screen. Open import * as React from 'react' import { NavigationContainer } from '@react-navigation/native' import { createStackNavigator } from '@react-navigation/stack' import ChatRoom from '../screens/ChatRoom.js' const Stack = createStackNavigator() export default function SignInStack() { return ( <NavigationContainer> <Stack.Navigator> <Stack.Screen name='ChatRoom' component={ChatRoom} options={{ title: 'Chat Room' }} /> </Stack.Navigator> </NavigationContainer> ) } In the above snippet, there are two required props with each Stack.Screen. The prop name refers to the name of the route, and the prop component specifies which screen to render at that particular route. Similarly, in the file SignOutStack.js, add the following code snippet: import * as React from 'react' import { NavigationContainer } from '@react-navigation/native' import { createStackNavigator } from '@react-navigation/stack' import Login from '../screens/Login' const Stack = createStackNavigator() export default function SignOutStack() { return ( <NavigationContainer> <Stack.Navigator <Stack.Screen name='Login' component={Login} /> </Stack.Navigator> </NavigationContainer> ) } This is how navigators are defined declaratively using version 5 of react-navigation. It follows a more component-based approach, similar to that of react-router in web development. Before we begin to define a custom authentication flow (since this version of react-navigation does not support a SwitchNavigator like previous versions), let us add the Firebase SDK. Using the Firebase functions, you can then easily implement an authentication flow to switch between the two stack navigators. Adding Firebase SDK If you have used react-native-firebase version 5 or below, you may have noticed that it was a monorepo that used to manage all Firebase dependencies from one module. Version 6 brings you the option to only install those Firebase dependencies required for features that you want to use. For example, in the current app, you are going to start by adding the auth package. Also, do note that the core module @react-native-firebase/app is always required. Open a terminal window to install this dependency. yarn add @react-native-firebase/app Adding Firebase credentials to your iOS app The Firebase provides a GoogleService-Info.plist file that contains all the API keys as well as other credentials for iOS devices to authenticate the correct Firebase project. To get the credentials, go to the Firebase console and create a new project. After that, from the dashboard screen of your Firebase project, open Project settings from the side menu. Then, go to the Your apps section and click on the icon iOS to select the platform. Enter the application details and click on Register app. Then download the GoogleService-Info.plist file as shown below. Open Xcode, then open the file /ios/rnAnonChatApp.xcodeproj file. Right-click on your project name and choose the Add Files option, then select the file to add to this project. Now, open ios/rnAnonChatApp/AppDelegate.m and add the following header. #import <Firebase.h> Within the didFinishLaunchingWithOptions method, add the following configure method: - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { if ([FIRApp defaultApp] == nil) { [FIRApp configure]; } Open a terminal window to install pods. cd ios/ && pod install # after pods are installed cd .. Adding Firebase credentials to your Android app Firebase provides a google-services.json file that contains all the API keys as well as other credentials for Android devices to authenticate the correct Firebase project. Go to the Your apps section and click on the icon Android to select the platform. Then download the google-services.json file as shown below. Now add the downloaded JSON file to your React Native project at the following location: /android/app/google-services.json. After that, open android/build.gradle and add the following: dependencies { // ... classpath 'com.google.gms:google-services:4.2.0' } Next, open android/app/build.gradle file and at the very bottom of it, add the following: apply plugin: 'com.google.gms.google-services' Adding Firebase Anonymous Auth To support the anonymous login feature in the current app, make sure you install the following package: yarn add @react-native-firebase/auth # Using iOS cd ios/ && pod install # After installing cd .. Now go back to the Firebase console of the project and navigate to the Authentication section from the side menu. Go to the second tab Sign-in method and enable the Anonymous sign-in provider. That's it! The app is now ready to allow the user to log in anonymously. Setting up an authentication flow To complete the navigation of the current React Native app, you have to set up the authentication flow. Create a new file src/navigation/AuthNavigator.js and make sure to import the following as well as both stack navigators created early in this tutorial. import React, { useState, useEffect, createContext } from 'react' import auth from '@react-native-firebase/auth' import SignInStack from './SignInStack' import SignOutStack from './SignOutStack' Then, create an AuthContext that is going to expose the user data to only those screens when the user successfully logs in, that is, the screens that are part of the export const AuthContext = createContext(null) Define the AuthNavigator functional component. Inside it, create two state variables, initializing and user. The state variable initializing is going to be true by default. It helps to keep track of the changes in the user state. When the user state changes to authentication, the initializing variable is set to false. The change of the user's state is handled by a helper function called onAuthStateChanged. Next, using the hook useEffect, subscribe to the auth state changes when the navigator component is mounted. On unmount, unsubscribe it. Lastly, make sure to pass the value of user data using the AuthContext.Provider. Here is the complete snippet: export default function AuthNavigator() { const [initializing, setInitializing] = useState(true) const [user, setUser] = useState(null) // Handle user state changes function onAuthStateChanged(result) { setUser(result) if (initializing) setInitializing(false) } useEffect(() => { const authSubscriber = auth().onAuthStateChanged(onAuthStateChanged) // unsubscribe on unmount return authSubscriber }, []) if (initializing) { return null } return user ? ( <AuthContext.Provider value={user}> <SignInStack /> </AuthContext.Provider> ) : ( <SignOutStack /> ) } To make it work, open App.js and modify it as below: import React from 'react' import AuthNavigator from './src/navigation/AuthNavigator' const App = () => { return <AuthNavigator /> } export default App Now, build the app for a specific mobile OS by running either of the commands mentioned: npx react-native run-ios # or npx react-native run-android Open up a simulator device, and you are going to be welcomed by the login screen. Adding SignIn functionality Right now the app is in a state where you can use the Firebase authentication module to implement real-time signing in and signing out functionalities. Start with the screen/Login.js file to add sign-in functionality. Import the auth from @react-native-firebase/auth as shown below: // rest of the import statements import auth from '@react-native-firebase/auth' Then, inside the Login functional component, define a helper method that will be triggered when the user presses the sign-in button on this screen. This helper method is going to be an asynchronous function. async function login() { try { await auth().signInAnonymously() } catch (e) { switch (e.code) { case 'auth/operation-not-allowed': console.log('Enable anonymous in your firebase console.') break default: console.error(e) break } } } Lastly, add this method as the value of the prop onPress for TouchableOpacity. <TouchableOpacity style={styles.button} onPress={login}> {/* ... */} </TouchableOpacity> Adding sign-out functionality To add a sign out button, open navigation/SignInStack.js. This button is going to be represented by an icon on the right side of the header bar of the ChatRoom screen. Start by importing Icon and auth statements. // after rest of the import statements import { TouchableOpacity } from 'react-native' import Icon from 'react-native-vector-icons/Ionicons' import auth from '@react-native-firebase/auth' Then, add a logOut helper method that will be triggered when the user presses the icon. This method is going to be inside async function logOut() { try { await auth().signOut() } catch (e) { console.error(e) } } Lastly, add headerRight in the options of Stack.Screen for ChatRoom. <Stack.Screen </TouchableOpacity> ) }} /> That's it. Now, go back to the device in which you are running this app and try logging into the app. Then using the icon in the header bar, log out of the app. This completes the authentication flow. In the Firebase console, check that the user uid is created whenever a new user signs in the app and the identifier says anonymous. Add another screen To enter the name of the chat room that is going to be saved in the database (which we will setup later using Firestore), create another screen called screens/CreateChatRoom.js. This screen component is going to use a state variable called roomName to set the name of the room and store it in the database. The UI of the screen is going to be an input field as well as a button. The helper method handleButtonPress (as described below in code snippet) is going to manage the setting of a chat room. Later, you are going to add the business logic of saving the name. import React, { useState } from 'react' import { View, StyleSheet, Text, TextInput, TouchableOpacity } from 'react-native' export default function CreateChatRoom() { const [roomName, setRoomName] = useState('') function handleButtonPress() { if (roomName.length > 0) { // create new thread using firebase } } return ( <View style={styles.container}> <TextInput style={styles.textInput} placeholder='Thread Name' onChangeText={roomName => setRoomName(roomName)} /> <TouchableOpacity style={styles.button} onPress={handleButtonPress}> <Text style={styles.buttonText}>Create chat room</Text> </TouchableOpacity> </View> ) } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', alignItems: 'center', backgroundColor: '#dee2eb' }, title: { marginTop: 20, marginBottom: 30, fontSize: 28, fontWeight: '500' }, button: { backgroundColor: '#2196F3', textAlign: 'center', alignSelf: 'center', paddingHorizontal: 40, paddingVertical: 10, borderRadius: 5, marginTop: 10 }, buttonText: { color: '#fff', fontSize: 18 }, textInput: { backgroundColor: '#fff', marginHorizontal: 20, fontSize: 18, paddingVertical: 10, paddingHorizontal: 10, borderColor: '#aaa', borderRadius: 10, borderWidth: 1, marginBottom: 5, width: 225 } }) Then, go the navigation/SignInStack.js file to add this newly created screen to the stack. Start by importing the screen itself. import CreateChatRoom from '../screens/CreateChatRoom' Next, add the Stack.Screen for CreateChatRoom in the stack as the second route in the navigator. <Stack.Screen name='CreateChatRoom' component={CreateChatRoom} options={{ title: 'Create a room' }} /> Lastly, to navigate to this new screen, using the navigation prop, add a headerLeft option in the screen ChatRoom as shown below. Make sure to convert the options to a function in order to use the navigation prop. <Stack.Screen </TouchableOpacity> ), headerRight: () => ( <TouchableOpacity style={{ marginRight: 10 }} onPress={logOut}> <Icon name='ios-log-out' size={30} </TouchableOpacity> ) })} /> Here is the output you are going to get: Conclusion That's it for this part. By now you have learned how to set up a real-time authentication flow using Firebase and react-navigation and add an anonymous sign-in method. In the next part, you are going to explore how to integrate Firestore to use a real-time database with this chat app, integrate react-native-gifted-chat to implement chat functionalities and UI, and create sub-collections in Firestore.
https://blog.crowdbotics.com/build-anonymous-chat-app-with-react-native-firebase/
CC-MAIN-2021-17
en
refinedweb
GREPPER SEARCH SNIPPETS USAGE DOCS INSTALL GREPPER All Languages >> Whatever >> java arraylist contains string “java arraylist contains string” Code Answer’s list contains whatever by Combative Constrictor on Jul 25 2020 Donate 0 List<Integer> arr = new ArrayList<Integer>(4); boolean ans = arr.contains(2); java arraylist contains string java by Nice Newt on Oct 23 2020 Donate 0 boolean ans = arr.contains("geeks"); Add a Grepper Answer Whatever answers related to “java arraylist contains string” array contains java arraylist contains doc ArrayList contains(Object o) method in java ArrayList containsAll(Collection c) method in java arraylist in java ArrayList isEmpty() method in java arraylist items into string arraylist of arraylist arraylist with values java c# arraylist contains check if a list contains a string java Check if an array contains an element java check if list contains string python check if object in array java class list contains class java displaying an arraylist in java get element in arraylist java how to check if an arraylist contains a value in java recursion how to find contain elements in array in java java check if element exists in array java check if string appears twice in arraylist java find if element of list in present in another list java if one sting on array match java list of a class has a string that is equal to list contains lisp Whatever queries related to “java arraylist contains string” contains method arraylist java how to check if string contains anything from my arraylist java if string in arraylist of strings how to compare string in arraylist how to use arraylist in if statement .contains java arraylist arraylist.contain checking if a string is in an arraylist arraylist contain java java arraylist.contains arraylist contains doc contains on for arraylist contains in arraylist java java string in arraylist java arraylist if contains how does contain works arraylist how to check if arraylist contains string in java arraylist contains method implementation does a arraylist have contains method contains arraylist method java check if string is in arraylist java if arraylist contains java arraylist comtains arraylist.contains algorithm java contains method for arraylist java java if sting arraylist can we pass a list to a contains method list.include java does arraylist have contains method in java arraylist.contain in java arraylist contains element java check if the list contains a string in java java list contains string arraylist number of contians arraylist constains java arraylist constains check string contains in list java contains list how to check if a string is present in list java list.contrains java list contain element java arraylist.contains if an element is in a list java contains java arraylist contains method in arraylists in java .contain for array lists reference on a list and find if a given string is in the list java refrence on a list and find if a given string is in the list java arraylist contain with string in java arraylist contain in java arraylist contain a value in java arraylist contains string arraylist contains check for element in list java list contains class java check if list contains string java contains in java arraylist contains arraylist in java contains java for list java check if arraylist contains does arraylist contain array list contains java list constains java array list search if i in list in java ArrayList contains() contains in list java contais arraylist java contains method in arraylist arraylist.get().contains java check if list contains string string not in list java contains in arraylist junit test check arraylist contains element -hamcrest java arraylist contains string write a funtion contain for list list.contains method in java where (!list.contains(value) arraylist . contains arraylist contanins checking if an element in a list injava list how to use contains java contains arraylist java check arraylist contains string how to check in array list that role match or not contains in java list contains array list arraylist.contains java contains arraylist object arrayList contains element from the object writing contains of arraylist in java java contained in list string contains in arraylist java java how to check number to element is in list check values in arraylist contains from arraylist check if a string is present in an arraylist java java list.contains* java list includes check string is present in arrayLIST search in arraylist java how to check list content in java arraylist search java List.cotains java java string in list list.contains other way around in java contains methods arraylist java contains list trong java not in arrraylist java contains method in java arraylist contains method in list array list contains() how to check a integer is there in the arraylist in java contains arraylist java arraylist contains method in java arraylist contains method if arraylist contain __icontains for list contains with arraylist java a message contain a list java contains method for arraylist in java contains method in list java does an arraylist contains elements in the amended order does an arraylist contains elements in the appendened order contains in list check from array list list contains in java java list .contains how to use contains in arraylist java java arraylist contains search arraylist in java arraylist java contains cointains arraylist arraylist.contains() java check if arraylist contains string java contains in arraylist contains list java import for contains list java contains in list in java list contains element java list contain java java contains method arraylist contains method java arraylist list contains method in java java list.contains java arraylist only contain one type arraylist includes java list.contains arraylist contains java in java which of the following methods id used to check if an Arraylist contains an object list of string contains string java java list of string contains how to make arraylist contains method without arraylist list.contains java check if string present in list java arraylist contains on object java contains list List contains java Java list contains .contains in java list lst.contains in java is in list java contains java list list contains dart objexts java array list contains list.contains in java list contains Learn how Grepper helps you improve as a Developer! INSTALL GREPPER FOR CHROME More “Kinda” Related Whatever Answers View All Whatever Answers » ModuleNotFoundError: No module named 'corsheaders' personal access client not found. please create one oops an error occurred typo3 kivy error command errored out with exit status 1 force .htaccess force http to https htaccess see apache error log display wordpress error [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() flutter my-upload-key.keystore (access is denied) Exception occurred when creating MZContentProviderUpload for provider. (1004) could not open a connection to your authentication agent apache invalid mutex directory in argument Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable) The openssl extension is required for SSL/TLS protection but is not available. If you can not enable the openssl ex tension, you can disable this error, at your own risk, by setting the 'disable-tls' option to true Error: ENOSPC: System limit for number of file watchers reached, API Services rejected request with error. HTTP 403 (Forbidden) { useNewUrlParser: true } to MongoClient.connect. warnning Failed to start mongod.service: Unit mongod.service not found. Your virtual machine will continue working normally but will have no network connection. dpkg: error: dpkg frontend lock was locked by another process with pid 4368 Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: Connection refused : fatal: unable to auto-detect email address yarn unable to verify local issuer certificate gyp WARN EACCES current user ("nobody") does not have permission to access the dev dir "/Users could not create ssl/tls secure channel database files are incompatible with server iis Maximum request length exceeded npm EACCES: permission denied, access '/usr/local/lib' htaccess rewrite rule NullInjectorError: No provider for HttpClient! ERR! Error: EPERM: operation not permitted, rename htaccess https erzwingen net::ERR_CLEARTEXT_NOT_PERMITTED ionic Error: no repositories found. You must add one before updating address already in use :::3000 pecl: command not found add expires headers in htaccess [Errno 98] Address already in use Could not create server TCP listening socket *:6379: bind: Address already in use Treating warnings as errors because process.env.CI = true. go: not found The command htaccess force ssl DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, portaudio library not found Execution failed for task ':app:processDebugGoogleServices'. error: refname refs/heads/master not found Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock Process: 12270 ExecStart=/usr/bin/mongod --config /etc/mongod.conf (code=exited, status=14) error 418 Starting inspector on 127.0.0.1:9229 failed: address already in use generate service ionic Command "make:auth" is not defined. Did you mean one of these? make:cast has been blocked by CORS policy: Request header field content-type is not allowed by Access-Control-Allow-Headers in preflight response. maximum execution time of 120 seconds exceeded xampp port 8080 already in use address already in use :::3001 could not connect to server: Connection timed out (0x0000274C/10060) Is the server running on hos Error: listen EACCES: permission denied 0.0.0.0:3000 http 000 connection failed Firebase: Firebase App named '[DEFAULT]' already exists Request format is unrecognized for URL unexpectedly ending in '/grid' pods is forbidden: User "system:serviceaccount:kube-system:default" cannot list resource "pods" in API group "" at the cluster scope (Kubeclient::HttpError) ngrok gateway error The server returned an invalid or incomplete HTTP response. Error: listen EADDRINUSE: address already in use :::3000 Execution failed for task ':app:lintVitalRelease'. python3 permission denied ansible disable host key checking EADDRINUSE: address already in use :::5000 mamp error log ERROR 2002 (HY000): Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2) Error: Invalid login: 535-5.7.8 Username and Password not accepted. Learn more at 535 5.7.8 f2sm17674989iop.6 - gsmtp Failed to load resource: net::ERR_CERT_AUTHORITY_INVALID E: Could not get lock /var/cache/apt/archives/lock - open (11: Resource temporarily unavailable) E: Unable to lock the download directory nodemon: command not found ssl certificate error handling in selenium { "ok": false, "error": "not_in_channel" } ssh ignore host key verification SMTP ERROR: Password command failed: 535-5.7.8 Username and Password not accepted. deprecated filter_var() phpmailer NotAuthorizedException: Identity pool does not have identity providers configured. htaccess access denied all stream_socket_enable_crypto(): ssl operation failed with code 1. openssl error messages: error:1416f086:ssl routines:tls_process_server_certificate:certificate verify failed can only a single process be executed network service discovery disabled fatal: unable to access '': LibreSSL SSL_read: SSL_ERROR_SYSCALL, errno 60 serverless post confirmation lambda permissions extension unexpectedly stopped in vs code <code>300</code> <message>Unsupported Content Type</message> simple httpserver too long to respond authorization failed while checking glassfish server netbeans Swift_TransportException Cannot send message without a sender address Please provide a valid cache path. No provider for HttpClient! su - authentication failure unhandledpromiserejectionwarning error enospc system limit for number of file watchers reached watch postgrex.protocol failed to connect undefined variable: _server (504, b'5.5.2 <webmaster@localhost>: Sender address rejected: need fully-qualified address')} alllauth Process terminated with status 1 (0 minute(s), 0 second(s)) 3 error(s), 3 warning(s) (0 minute(s), 0 second(s)) already exists http status code /usr/share/metasploit-framework/modules/exploits/windows/http/rejetto_hfs_exec.rb:110: warning: URI.escape is obsolete drupal 8 admin user access denied specified key was too long; max key length is 767 bytes (s EADDRINUSE: address already in use google nearby places api "error_message": "This API project is not authorized to use this API.", smtpauthenticationerror Warning: file_put_contents(phplog): failed to open stream: Permission denied in /Applications/XAMPP/xamppfiles/ cors header missing vue api gateway Honcho fails on Heroku because, USER variable is not set No Event Pooling org.w3c.dom.DOMException: Only one root element allowed mac httpd: Could not reliably determine the server's fully qualified domain name, using permission denied 0.0.0.0:80 no wifi adapter found Segmentation violation exception QXcbConnection: Could not connect to display chrome.exe --disable-web-security E: Could not open lock file /var/lib/dpkg/lock-frontend - open (13: Permission denied) E: Unable to acquire the dpkg frontend lock (/var/lib/dpkg/lock-frontend), are you root? .htaccess: AllowOverride not allowed here if endpoint is not ready how would you test it ErrorException Undefined variable: request if endpoint is not ready how would use test it voiceConnection.playStream error nginx 403 forbidden [nodemon] Internal watch failed: ENOSPC: System limit for number of file watchers reached, watch Consider using the `--user` option or check the permissions send notification when task scheduler fails how to test failed test image intervention DeprecationWarning: use options instead of chrome_options Error R10 (Boot timeout) -> Web process failed to bind to $PORT within 60 seconds of launch heroku ssl.SSLCertVerificationError: [SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:1091) ./gradlew permission denied macos executable permission denied could not be opened in append mode: failed to open stream: Permission denied there is no place 127.0.0.1 Http Client An existing connection was forcibly closed by the remote host Permissions 0644 for are too open. It is required that your private key files are NOT accessible by others. This private key will be ignored unable to open connection to raspberrypi.local SocketException: Failed host lookup sh: cross-env: command not found Uncaught (in promise) FirebaseError: Missing or insufficient permissions. ssh-add could not open a connection to your authentication agent npm ERR! code ENOTFOUND RuntimeException: Personal access client not found. Please create one. active developer path ("/Applications/Xcode.app/Contents/Developer") does not exist nouveau 0000:01:00.0: bus: MMIO read of 00000000 FAULT at 022554 failed to complete tunnel connection ngrok warning: the requested image android.content.res.Resources$NotFoundException: String resource ID #0x0 Connection could not be established with host smtp.googlemail.com D/NetworkSecurityConfig: No Network Security Config specified, using platform default Got an error creating the test database: permission denied to create database moq setup returns null Command "make:auth" is not defined batch error code 9009 your device management settings do not allow using apps from developer #AllowOverride none #Require all denied ERROR 1698 (28000): Access denied for user 'root'@'localhost' dpkg: error: dpkg frontend lock is locked by another process macos gradlew clean permission denied SOCK_STREAM synchronization issue in selenium Failed to construct 'WebSocket': An insecure WebSocket connection may not be initiated from a page loaded over HTTPS. stackoverflow error TCPDF ERROR: Some data has already been output, can't send PDF file how to delete alert "DevTools failed to load SourceMap: Could not load content for chrome-extension" fatal: remote origin already exists. handling conflict no firebase app ' default ' has been created flutter adb command not found DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor. at=error code=h10 desc="app crashed" method=get path="/" host wordpress inner page not found error Class 'App\Http\Controllers\Response' not found apache error log sigabrt error net:ERR_cleartext_not_permitted The session is unavailable because no secret key was set. Set the secret_key on the application to something unique and secret. a2ensite site does not exist error 413 request entity too large nginx get location permission forcefully Class Magento\Framework\App\ResourceConnection\Proxy does not exist how do you handle conflict airpods connecting and then disconnecting Internal watch failed: ENOSPC: System limit for number of file watchers reached EPERM: operation not permitted, rename The link you followed has expired. Please try again. wordpress error how to fix https certificate error handling failed to push some refs to flutter unhandled exception: bad state: insecure http is not allowed by platform: E: Could not get lock /var/lib/dpkg/lock-frontend - open (11: Resource temporarily unavailable) DeprecationWarning: Listening to events on the Db class has been deprecated and will be removed in the next major version. Error: listen EADDRINUSE: address already in use :::8080 Could not open a connection to your authentication agent. client:169 Invalid Host/Origin header Failed to enable unit: Unit file mongod.service does not exist. java.lang.IllegalArgumentException: Couldn't find meta-data for provider with authority nodemon command not found address already in use :::8081 windows The server requested authentication method unknown to the client [cachin g_sha2_password] ActionController::InvalidAuthenticityToken Cause: zip END header not found Superuser creation skipped due to not running in a TTY. You can run `manage.py createsuperuser` in your project to create one manually. postgres raise notice To perform the requested action, WordPress needs to access your web server. Please enter your FTP credentials to proceed. If you do not remember your credentials, you should contact your web host There was a problem confirming the ssl certificate: HTTPSConnectionPool(host='pypi.org', port=443): nodemon is not restarting discord bot wait for response composer failed to open stream: Too many open file Error: listen EADDRINUSE: address already in use :::8888 Failed to restart sshd.service: Unit sshd.service not found pem key permissions too open httparty gem default firebaseapp is not initialized in this process It is required that your private key files are NOT accessible by others. This private key will be ignored. swift_transportexception expected response code 250 but got code "530", with message "530 5.7.1 authentication required " npx create app not working eperm operation not permitted mkdir psql: could not connect to server: no such file or directory is the server running locally and accepting connections on unix domain socket "/var/run/postgresql/.s.pgsql.5432"? Error: listen EADDRINUSE: address already in use :::31641 event-config.h file not found grant user all privileges error 2003 (hy000) windows 10 Execution failed for task ':app:lintVitalRelease'. > Lint found fatal errors while assembling a release target. permission denied (publickey,gssapi-keyex,gssapi-with-mic,password). Could not connect to Redis at 127.0.0.1:6379: Connection refused ERROR 1819 (HY000): Your password does not satisfy the current policy requirements listen EADDRINUSE: address already in use 127.0.0.1:8000 Firebase Storage: User does not have permission to access failed to load resource: net::ER_BLOCKED_BY_CLIENT hotjar cannot enable mylocation layer as location permissions are not granted Failed to set up listener: SocketException: Address already in use Error: Redis connection to 127.0.0.1:6379 failed - connect ECONNREFUSED 127.0.0.1:6379 htaccess symfony Process finished with exit code 0 unable to connect to socket connection refused 10061 kex Fatal error: Maximum execution time of 30 seconds exceeded 419 Page Expired error: insufficient permission for adding an object to repository database .git/objects Get: dial tcp: lookup registry-1.docker.io on 192.168.65.1:53: read udp 192.168.65.1:56829->192.168.65.1:53: read: connection refused Cannot find module 'express-session' ExecStart=/usr/bin/mongod --quiet --config /etc/init/mongod.conf (code=exited, status=100) angular/http deprecated .\Scripts\activate Execution_Policies at https:/go.microsoft.com/fwlink/?LinkID=135170. Error: EACCES: permission denied, mkdir '/Users/f5238390/Sites/pyramid-ui/node_modules/node-sass/build [rejected] main -> main (non-fast-forward) Permission denied @ apply2files - /usr/local/lib/node_modules/expo-cli/node_modules/timers-browserify/.DS_Store fused location provider client implementation db_1 | Error: Database is uninitialized and superuser password is not specified. Refused to load the imagebecause it violates the following Content Security Policy directive: "img-src 'self' data: content:". error 503 warning: include(): https:// wrapper is disabled in the server configuration by allow_url_include=0 in could not store passwrod mysqkl workbench 504 gateway time-out valet syntax error or access violation: 1055 'database.table.id' isn't in GROUP BY error: failed to push some refs to Whoops! Error: DOMException: Failed to execute 'addIceCandidate' on 'RTCPeerConnection': Error processing ICE candidate error 503 service unavailable Could not create cudnn handle: CUDNN_STATUS_ALLOC_FAILED expiring daemon because jvm heap space is exhausted you must use a personal access token with 'read_repository' Refused to execute inline event handler because it violates the following Content Security Policy directive: "default-src 'self' data: gap: valet share failed to connect to 127.0.0.1 port 4041: connection refused failed to open stream: No such file or directory in artisan on line 18 RROR 1698 (28000): Access denied for user 'root'@'localhost Cannot start service traefik: Could not attach to network web: rpc error: code = PermissionDenied desc = network web not manually attachable error: listen eaddrinuse: address already in use 0.0.0.0:5555 failed to push some refs auth.docker.io on 192.168.65.1:53: no such host Permission denied @ apply2files npm ERR! code EACCES java.lang.OutOfMemoryError: Failed to allocate a 345067788 byte allocation with 11479504 free bytes and 111MB until OOM An error occurred (UnrecognizedClientException) when calling the GetAuthorizationToken operation: The security token included in the request is invalid. Uncaught Error in onSnapshot: FirebaseError: Missing or insufficient permissions. SELECT command denied to user 'pma'@'localhost' for table 'pma__tracking' Please enter a commit message Unable to load authentication plugin 'caching_sha2_password' discord ssl certificate error Unable to connect to your database server using the provided settings. Fatal error: Uncaught GuzzleHttp\Exception\RequestException: cURL error 60: SSL certificate problem: unable to get local issuer certificate err_cleartext_not_permitted fatal error: conio.h: No such file or directory failed because the user didn't interact with the document first firebase phone authentication web result doesnt have accessToken Host key verification failed. origin '' has been blocked by CORS policy 404 error page discord dispatcher connection is not defined access denied for user 'root'@'localhost' Error: Missing credentials for "PLAIN" List the status of all application managed by PM2: No application encryption key has been specified. there appears to be trouble with your network connection. retrying tcpdump only http 'EADDRINUSE' It is likely you do not have the permissions to access this file as the current user perl: warning: Please check that your locale settings: W: Failed to fetch The following signatures couldn't be verified because the public key is not available: NO_PUBKEY B56FFA946EB1660A Chat socket closed unexpectedly Unable to init server: Could not connect: Connection refused (eog:22): Gtk-WARNING **: 21:54:46.367: cannot open display: puppeteer headless false Checking if user is a member of the Hyper-V Administrators group ... FAIL phpmyadmin not found Fatal error: Allowed memory size of 1610612736 bytes exhausted (tried to allocate 32 bytes) in wrong fs type, bad option, bad superblock on /dev/loop0, missing codepage or helper program, or other error+dd image error: couldn't set 'refs/remotes/origin/master' error page apache2 got a packet bigger than 'max_allowed_packet' bytes 404 error errno: 1251 404 page not found localhost codeigniter zsh: permission denied force ssl htaccess perl: warning: Setting locale failed. 422 error xampp 403 forbidden when listing directory 404 Not Found [IP: 91.189.88.142 80] `require': cannot load such file -- httparty (LoadError) hidden authenticity_token received empty response from zabbix agent at [192.168.0.3]. assuming that agent dropped connection because of access permissions. emoji not storing in database An unhandled exception occurred: NGCC failed. See C:\Users\HAMZAZ~1\AppData\Local\Temp\ng-lyW7pS\angular-errors.log for further details. nginx: [emerg] bind() to 0.0.0.0:8080 failed (48: Address already in use) Specified key was too long; max key length is 1000 bytes Max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] enospc error Auth::routes(['register' => false]); not working invalid principal in policy 409 status code yup change error message c socket SO_REUSEADDR cors apache alpine insufficient memory to execute script An unhandled exception occurred: Job name ..getProjectMetadata does not exist. See C:\Users\adeli\AppData\Local\Temp\ng-m7FHpn\angular-errors.log for further details. heroku no web processes running spring boot magento 2 The requested class did not generate properly, because the 'generated' directory permission is read-only port 4200 is already in use. ERR_CONNECTION_REFUSED index [magento2_product_1_v1] blocked by: [FORBIDDEN/12/index read-only / allow delete (api)]; status 201 forcer https htaccess htaccess deny all but no pg_hba.conf entry for host user database ssl off socket exception permission denied Test running failed: Instrumentation run failed due to 'Process crashed.' spatie/laravel-permission permission denied (publickey password) Web process failed to bind to $PORT within 60 seconds of launch sh: 1: vue-cli-service: Permission denied Failed to set time: Automatic time synchronization is enabled how to run failed test firestore missing or insufficient permissions ORA-65096: invalid common user or role name chrome inspect android http/1.1 404 not found unauthorized status code what should be the error response status for information message failed to build ios project. we ran "xcodebuild" command but it exited with error code 65. fatal: refusing to merge unrelated histories the requested url was not found on this server apache Uncaught Error: listen EADDRINUSE: address already in use 0.0.0.0:3000 status:display_server_not_supported how to handle merge conflicts ccess to XMLHttpRequest at ' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Got permission denied while trying to connect to the Docker daemon socket .htaccess force example your administrator has blocked this application general error: 1205 lock wait timeout exceeded; try restarting transaction error handler how to get client assertion ok okta auto fix lint errors command The certificate is not trusted because it is self-signed wordpress 'receive.denyCurrentBranch' configuration variable to 'refuse' fatal: Unable to create '/home/babita/INTER_EV/INTER_EV_MICROSERVICES/InterEV-Email/.git/index.lock': File exists. fatal: could not lookup name for submodule 'docroot/web/sites/all/vendor/guzzlehttp/ringphp' Current user cannot act as service account 881087019435-compute@developer.gserviceaccount.com composer failed to open stream too many open files curl: (6) Could not resolve host: http-inputs-hec.splunkcloud.com [core/no-app] No Firebase App '[DEFAULT]' has been created - call Firebase.initializeApp() "flutter" Cannot proceed with delivery: an existing transporter instance is currently uploading this package INNO setup check if folder exists common risk for project failure Make views automatic and avoid error "no file ..." neovim execution failed for task cron not showing notifications Permissions sur le fichier de configuration incorrectes, il ne doit pas être en écriture pour tout le monde ! Parameter not allowed for this message type: code_challenge_method Attempt by security transparent method 'System.Web.Mvc.PreApplicationStartCode.Start()' to access security critical method 'System.Web.WebPages.Razor.PreApplicationStartCode.Start()' failed. Failed binding to auth address * port 1812 bound to server default: Address already in use /etc/freeradius/3.0/sites-enabled/default[59]: Error binding to port for 0.0.0.0 port 1812 matthias@ThinkPad-T580:~$ could not be opened in append mode failed to open stream permission denied from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. what do you do when developer deny bug you found A task was canceled. h10 status 503 error npm permissions error error: RPC failed; curl 18 transfer closed with outstanding read data remaining fatal: the remote end hung up unexpectedly NullInjectorError: No provider for SwPush! permission denied: bin/cake bake not a valid key=value pair (missing equal-sign) in authorization header 'bearer Error creating broker listeners from 'localhost': Unable to parse localhost to a broker endpoint makemigrations permission denied raise RuntimeError(_request_ctx_err_msg) RuntimeError: Working outside of request context why bug caught in production permission to repository denied to user pacman is currently in use please wait permission denied for window type 2002 htcondor daemons not running create spring 404 error controller expected response code 250 but got code "535", with message "535-5.7.8 username and password not accepted HTTP Strict Transport Security (HSTS) Errors and Warnings xdebug: [step debug] could not connect to debugging client. tried: localhost:9003 (through xdebug.client_host/xdebug.client_port) :-(] bug defect error NoLimits_ID X #No_IDenTity cannot open output file main.exe: permission denied collect2.exe: error: ld returned 1 exit status restsharp restclient allow nocertificate verbose stack Exit status 126 responseentity error message how to fix The information you’re about to submit is not secure Error: EACCES: permission denied, mkdir permission denied: bin/cake command failed with EACCES android (node:621) UnhandledPromiseRejectionWarning: Error: Failed to launch chrome! Refused to execute inline script because it violates the following Content Security Policy directive xmlhttprequest error flutter mysqli::real_connect(): (hy000/2002): connection refused ionic 5 "firebasex" plugin grant Permission tutorial Broker may not be available. (org.apache.kafka.clients.NetworkClient) swift_transportexception expected response code 220 but got an empty response try catch error rabbitmq.client.AuthenticationFailureException: ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN. For details see the broker logfile. ionic ENOLOCAL error disable cors what is error code 400 internal server error heroku password authentication failed for user postgres pgadmin status code 302 mysqli_connect(): (hy000/2002): no connection could be made because the target machine actively refused it. Got permission denied while trying to connect to the Docker daemon socket at unix:///var/run/docker.sock: Post: dial unix /var/run/docker.sock: connect: permission denied How to fix 'Mixed Content: The page was loaded over HTTPS, but requested an insecure script” [duplicate] You have multiple authentication backends configured and therefore must provide the `backend` argument or set the `backend` attribute on the user. 200 error code 404 page not found codeigniter error: request failed with status code 400 Execution failed for task ':app:kaptDebugKotlin' Knex: Timeout acquiring a connection. The pool is probably full. Are you missing a .transacting(trx) call? The operation was rejected by your operating system. npm ERR! It is likely you do not have the permissions to access this file as the current user Error in file(file, "rt") : cannot open the connection net::ERR_CLEARTEXT_NOT_PERMITTED server 404 response docker unable to push repo access denied updates were rejected because the remote contains work that you do no pg_hba.conf entry for host heroku 404 not found handling merge conflict active storage has_many_attached syntax error ioredis exists Unable to init server: Could not connect: Connection refused (gedit:7575): Gtk-WARNING **: 10:17:11.806: cannot open display: how to send an error message unity 10249: connect: connection refused failed: error during websocket handshake: unexpected response code: 400 FIS_AUTH_ERROR systemerror: error return without exception set permission denied port 3000 (#100) pages public content access requires either app secret proof or an app token [Unhandled promise rejection: Error: SERVER_ERROR: [code] 1675030 [message]: Error performing query. [extra]: ] Blocking calls are synchronous com.mongodb.mongosocketopenexception: exception opening socket sshfs user had no write access to mountpoint rc.local not running Secured previously unsecured MongoDB server, but the server is still not requiring authentication: oops error could not connect to aws instance APEX HTTP request failed err_connection_refused socket io raise errors.InternalError("Unread result found") psexec connection command Temporary password has expired and must be reset by an administrator ALTER DATABASE failed because a lock could not be placed on database Exception erreur To give permission to the specific user for the CRUD operation in the database at a time com.mysql.cj.jdbc.exceptions.communicationsexception: communications link failure Property 'users' does not exist on type 'UsersDTO[]'. 29 if (saveUser.users.length < 1) { nodemon not detect any file chages in linux 404 Page Not FoundThe page you requested was not found EnableGlobalMethodSecurity cannot enqueue handshake after already enqueuing a handshake MobaXterm X11 proxy: Authorisation not recognised filename not matched: /usr/local/ignition/ illegaloperation: attempted to create a lock file on a read-only directory: /data/db, terminating staleelementexception logic_error error launcher chromeheadless failed 2 times (cannot start). giving up authexception undefined Exception occurred while handling uri: '' open request has failed with SFTP error Permission Denied permission denied bitbucket keeps asking for password about_Execution_Policies at. At line:1 char:1 + live-server --port=9000 + ~~~~~~~~~~~ + CategoryInfo : SecurityError: (:) [], PSSecurityException + FullyQualifiedErrorId : UnauthorizedAccess java.net.malformedurlexception: no protocol: Error: getaddrinfo ENOTFOUND "0.0.0.0" redis docker -4048 EPERM npm error nodemon exec multiple commands sock no billing attempt event in shopify webhook could not connect to RDS instance notification.priority_high deprecated cannot start database server xampp mac os Error connecting to the service protocol localhost ERROR 2006 (HY000) at line 1163: MySQL server has gone away Unable to connect to the MongoDB datasource with host 127.0.0.1, port 27017. YOU HAVE BEEN LOCKED OUT The X11 connection broke: Maximum allowed requested length exceeded (code 4) Connection Log connecting to sesman ip l27.0.0.1 port 3350 sesman connect ok sending login info to session manager, please wait... login failed for display 0 http error 400. the request hostname is invalid Unable to resolve host "":No address associated with hostname UnhandledPromiseRejectionWarning: WebDriverError: invalid session id cordova websocket connection refused localhost 8080 Whitelabel Error Page This application has no explicit mapping for /error, so you are seeing this as a fallback. Sat Mar 27 10:42:53 CET 2021 There was an unexpected error (type=Internal Server Error, status=500). Your browser sent a request that this server could not understand. Reason: You're speaking plain HTTP to an SSL-enabled server port. Instead use the HTTPS scheme to access this URL, please. mysqldump error --no-beep could not reach cloud firestore backend An ambient transaction has been detected. The ambient transaction needs to be completed before beginning a transaction on this connection. systemctl start httpd Error: No space left on device 408 error vlookup if not found try another vlookup : El subproceso dpkg --set-selections devolvió un código de error x-auth-type none Can't create handler inside thread Thread[DefaultDispatcher-worker-1,5,main] that has not called Looper.prepare() could not initialize sdl(no available video device) - exiting mysqldump: got error: 1045: access denied for user error, defect, failure istqb (errno: 150 "foreign key constraint is incorrectly formed") 4045518890 application from for addmission golang https stop ssl verification codeigniter status on off how specify authentication not required for for folder in htaccess folder stackoverflow error ng8001 to allow any element add 'no_errors_schema' to the '@ngmodule.schemas' of this component. Facebook wordpress Login Error: There is an error in logging you into this application. Please try again later. Errors were encountered while processing: libglx-mesa0:amd64 ActiveResource::UnauthorizedAccess: Failed. Response code = 401. Response message = Unauthorized ([API] Invalid API key or access token (unrecognized login or wrong password)) public void sendData(byte[] data, InetAddress ipAddress, int port) throws IOException { DatagramPacket packet = new DatagramPacket(data, data.length); socket.send(packet); } what is proxy integration api not converting base64 to binary the request hostname is invalid is a command to create a user account named serena, including a home directory and a description. how do you run failed tests android retrofit not logging requests ssh: connect to host 192.168.178.45 port 22: Connection refused lost connection Service has no ExecStart=, ExecStop=, An error occurred. Please try again later. (Playback ID: 7pLt1C_eC0fttL2n) travis allow_failures script ansible [errno 13] permission denied You do not have sufficient privilege to perform this operation. Linking successful diagnosis errors in billing fatal error: no supported authentication methods available (server sent: publickey) <OpenAPI_ServiceResponse> <cmmMsgHeader> <errMsg>SERVICE ERROR</errMsg> <returnAuthMsg>SERVICE_ACCESS_DENIED_ERROR</returnAuthMsg> <returnReasonCode>20</returnReasonCode> </cmmMsgHeader> </OpenAPI_ServiceResponse> error: retrieving gpg key timed out. error path too long what to do if there is not enough information on the user story marlin pid autotune failed timeout disable 2 step verification apple This configuration section cannot be used at this path. This happens when the section is locked at a parent level. Locking is either by default (overrideModeDefault="Deny") sudo permission denied minio /opt/bitnami/scripts/libminio.sh: line 273: /data/.access_key: Permission denied YouTube Data API v3 has not been used in project before or it is disabled. Enable it by visiting then retry. If you enabled this API recently, wait a few minutes for the action to propagate to our systems and retry. Livewire encountered corrupt data when trying to hydrate the [cart.view] component. Ensure that the [name, id, data] of the Livewire component wasn't tampered with between requests. ci/jenkins Expected — Waiting for status to be reported you have been logged out because your authentication ticket mongoose fails to connect to server when database is specified no application app licenses found Error 401: deleted_client PayloadTooLargeError view.getId is giving error when is set local npm cache _logs your card was declined. try a different card. paypal sandbox PreflightMissingAllowOriginHeader "ctx":"initandlisten","msg":"Failed to unlink socket file","attr":{"path":"/tmp/mongodb-27017.sock","error":"Operation not permitted"}} the process cannot access the file because another process has locked a portion of the file you are not allowed to manage 'ela-attach' attachments If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail: tempo sessão apache : new Database Error(message Value, length, name) ^ error: relation "teacher" does not exist Skipping device 'emulator-5554' for 'app:debug': Unknown API Level com.sun.mail.util.MailConnectException: Couldn't connect to host, port: localhost, 25; timeout -1 unable to resolve host s: Name or service not known "when run flutter doctor in cmd show error ""some android studio licence is not accepted " Could not lock PID file [/tmp/zabbix_agentd.pid]: [11] Resource temporarily unavailable org.apache.commons.dbcp.sqlnestedexception: cannot create poolableconnectionfactory test failed test snykSecurity(tokenCredentialId: 'SNYK_TOKEN', failOnBuild: true, test --docker pika.exceptions.channelclosedbybroker: (406, "precondition_failed - inequivalent arg 'durable' for queue 'fx-naas' in vhost 'fx': r Solved: Issue access VMs - "The virtual machine appears to be in use"?? Curl error (7): Couldn't connect to server for [Failed to connect to cdn.redhat.com port 443: No route to host] { "error": { "code": 400, "message": "Required", "errors": [ { "message": "Required", "domain": "global", "reason": "required" } ] } } Finished in 42.2s with exit code 3221225477 MinigetError: input stream: Status code: 429 htaccess rewrite optional parameters exceeded the 'max_user_connections' resource (current value: 30) [ec2-user@ip- *]$ * : * : command not found paypal gateway has reject due to billing adrees read memory access error c programming couldnt resolve address for : unknown error kill: (31229): No such process set expiry in .htaccess MPI_STATUS_IGNORE The Tomcat server configuration at \Servers\Tomcat v9.0 Server at localhost-config is missing. Check the server for errors. minimum resources for no deadlock [Errno 13] Permission denied: '/media/images.png' Error while customizing B2C or b2b accelerator in hybris failure configuring LB attributes: ValidationError: Access Denied for bucket: yesb-stack-s3-bucket. Please check S3bucket permission firebaseuser is deprecated flutter stackoverflow java.net.NoRouteToHostException,Non HTTP response message: Cannot assign requested address (Address not available) Module not found: Error: Can't resolve 'aws4' Error “Get: net/http: request canceled” while building image synology server name is not resolving ah00111: config variable ${apache_run_dir} is not defined site giving 500 error when debug mode is off "E: Unable to locate packet snort" resolving issues while testing 2020-11-12 20:16:12.200 16641-16641/eniso.IA22.tp1X E/ActivityThread: Failed to find provider info for com.huawei.hiaction.provider.HiActionManagerProvider The "CreateAppHost" task failed unexpectedly. You probably tried to upload a file that is too large. Please refer to documentation for a workaround for this limit. [1126/200252.514:ERROR:http_transport_win.cc(178)] WinHttpCrackUrl: Åtgärden har slutförts. (0x0) #No_IDenTity failed to load resource the server responded with a status of 400 () Uploading is not possible. App measurement disabled do moorhens still exist? visitez ERROR: duplicate key value violates unique constraint statuslogs_pkey DETAIL: Key (id)=(1621) already exists. error from chokidar (c:\): error: ebusy: resource busy or locked, lstat fatal: unable to update url base from redirection: pika.exceptions.channelclosedbybroker: (406, "precondition_failed - inequivalent arg 'durable' for queue .htaccess 404 error for all pages except home page wordpress confluent kafka ERROR Fatal error during KafkaServer startup prepare to shutdown debug=true in socketio.run Failed to open file error: 2 PESQUISAR UM VALOR NO CLIENTDATASET details media type test failed. login denied zabbix Warning: require(/home/../wp-includes/rest-api/endpoints/class-wp-rest-application-passwords-controller.php): failed to open stream: error during websocket handshake: unexpected response code: 502 @EnableAuthorizationServer deprecated koa-router 404 not found error statuslogger log4j2 could not find a logging implementation New transaction is not allowed because there are other threads running in the session. google dork code for failed login passwords Terminating app due to uncaught exception 'RLMException', reason: 'Object has been deleted or invalidated.' ssh monitoring failed ssh logins Forward map FAILED: Has an address record but no DHCID, not mine. intervention image can't add text helm max virtual memory areas vm.max_map_count [65530] is too low, increase to at least [262144] synchronization issue curlftps Error connecting to ftp: Access denied: 530 the ssl connection could not be established, see inner exception. failed to set telus invalid session key git@gitlab.com: permission denied (publickey,keyboard-interactive) \'trunk' is not a complete URL and a separate URL is not specified logging when validation fails this page isn't working http error 500 codeigniter firebase installations service is unavailable. please try again later rerun failed test in testng all compiler errors have to be fixed before entering playmode firebase push notification ios no sound messaging/registration-token-not-registered letsencrypt status 400 No such token: stripe payment heroku error 500 with bonsai undefined reference to `curl_global_init' [ec2-user@ip- *]$ * : * : command not found PATH gnutls_handshake() failed: error in the pull function ERROR: Could not send notifications com.cloudbees.jenkins.plugins.bitbucket.api.BitbucketRequestException: HTTP request error. Status: 403: Forbidden. error while running {"traceId":"Try008","order Number":"BBD007654XYZ","response Code":"03","responseText":"Order Cancellation in-progress"} i keep getting error 404 when i load my phaser3 game JDWP Transport dt_socket failed to initialize, TRANSPORT_INIT(510) Payumoney Could not save Webhook. There was an exception posting data to the url. HTTP call status: 419 nodemon crashes on save no matches for kind "Ingress" in version "networking.k8s.io/v1" conflicting provisioning settings error when I try to archive to submit an iOS app Fatal Error: Out of memory - aborting There is already an open DataReader associated with this Connection which must be closed first. caffeine content in monster Database access not available. Please use to establish connection. There's a graph waiting for you. neo4j function undefined error in internet explorer firebase deploy Detailed stack trace: Error: ENOENT: no such file or directory, stat guzzle catch exceptions risks for project failure ERROR: for web server Cannot start service web server: OCI runtime create failed: 404 after update from net core 2.2 to 3.1 get error log of nginx Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. redis timeout exception curl: (52) Empty reply from server elasticsearch send error to a file Failed to unlink socket file amazon mongodb Target [Spatie\Backup\Tasks\Cleanup\CleanupStrategy] is not instantiable while building [Spatie\Backup\Commands\CleanupCommand]. Failure/Error: get :show ActionController::UrlGenerationError: No route matches {:action=>"show", :controller=>"questions"} Error: [messaging/unknown] FIS_AUTH_ERROR] react native spring An established connection was aborted by the software in your host machine redis-server.service: Can't open PID file /run/redis/redis-server.pid (yet?) after start: Operation not permitted Message could not be sent. Mailer Error: SMTP Error: data not accepted.SMTP server error: DATA END command failed Detail: h8alkc4CZK9H0 Spam Rejected connect ECONNREFUSED 127.0.0.1:80 nuxt config xampp the application was unable to start correctly delayed_job there is already one or more instance(s) of the program running Permissions for 'xxx.pem' are too open. It is required that your private key files are NOT accessible by others. standard_init_linux.go:211: exec user process caused "no such file or directory" Cannot configure From email address for default email configuration (Service: AWSCognitoIdentityProviderService; Status Code: 400; Error Code: InvalidParameterException; Request ID "authorization has been denied for this request."in postman nodemon running but not restart the server on files changes docker run -d --hostname my-rabbit --name some-rabbit rabbitmq:3-management docker: Error response from daemon: Conflict. The container name "/some-rabbit" is already in use by container 2020-07-12T22:14:08.819617Z 6 [Note] [MY-010454] [Server] A temporary password is generated for root@localhost: sYotK!Dzg8uk providing that information is not modified by malicious users in a way that is not detectable by authorasid users protocol buffers stream golang exception from hresult: 0x80131040 Missing Authorization Header What is the reason of having this sdkclientexception connection timed out exception ng build prod takes too long cloud run error: container failed to start. failed to start and then listen on the port defined by the port environment variable. EACCES: permission denied, mkdtemp '/usr/local/lib/node_modules/electron/electron-download-1ytvRT' nginx chrome net::ERR_CONNECTION_RESET 200 HTTP ERROR 403 No valid crumb was included in the request\ Jtl\Connector\Core\Http\JsonResponse::prepareAndSend() must be an instance of Jtl\Connector\Core\Rpc\ResponsePacket, null given, google authorization error 403 disallowed_useragent cordova condahttperror: http 000 connection failed for url <> firemonkey undeclared TConnLostCause mule 4 headers is not allowed to be child of element error-response rabbitmq.client.pdb not loaded fatal error: concurrent map writes RemoteConnection failed to initialize: RemoteConnection failed to open pipe error codes handling synchronization perl: warning: Falling back to the standard locale ("C"). site: bal:1 Backreferences To Failed Groups Oauth2 Full authentication is required to access this resource fatal: couldn't find remote ref refs/heads/master .woff not found error how do i fix cannot create work tree dir permission denied sentry erros mongo error 11000 wamp apache cannot start hostname, port, socket.AF_UNSPEC, socket.SOCK_STREAM what to do when errors are too much waiting ttfb too long How to ignore SSL issues erreur de segmentation (core dumped) 'max_allowed_packet' when dumping table `wp_options` at row: 703 [2]: the default discovery settings are unsuitable for production use; at least one of [discovery.seed_hosts, discovery.seed_providers, cluster.initial_master_nodes] must be configured The certificate for this server is invalid. You might be connecting to a server that is pretending to be “localhost” which could put your confidential information at risk. com.netflix.zuul.exception.ZuulException: Forwarding error - Device is currently in the unknown state Error running adb raise httperror(req.full_url, code, msg, hdrs, fp) urllib.error.httperror: http error 503: service unavailable socket_base::message_flags this operation is rejected by user system npm firebase net::ERR_CONNECTION_TIMED_OUT Error 404: SRVE0190E: File not found: / elasticsearchexception[failed to bind service]; nested: accessdeniedexception 422 (unprocessable entity) curl '? libcurl error when cooking ue4 sudo: yum: command not found One or more errors occurred. (A connection was successfully established with the server, but then an error occurred during the pre-login handshake. (provider: TCP Provider, error: 0 - An existing connection was forcibly closed by the remote host.)) xampp 500 internal server error facebook invalid scopes manage_pages. this message is only shown to developers psql: error: could not connect to server: could not connect to server: no such file or directory net use error 67 enable ph errors Method App\Http\Controllers\ApiController::getStudent does not exist. Error: Command "yarn run build" exited with 1 Can we rethrow the same exception from catch handler sqlite3.operationalerror: database is locked Magento2 404-error Wrong response from the webhook: 500 Internal Server Error failed to authenticate on smtp server with username using 3 possible authenticators. authenticator login returned expected response code 235 but got code "535", with message "535-5.7.8 username and password not accepted. sha256_crypt.verify net::ERR_CLEARTEXT_NOT_PERMITTED (WebResourceErrorType.unknown -1) error: syntax error, unexpected END-IF Debug signing certificate SHA-1 flutter Application is waiting for the debugger to attach 'max_allowed_packetwg' when dumping table rabbitmq Error (argument validation): too many arguments. ActiveRecord::NoDatabaseError web push showing 2 notification fcm callout not allowed from this future method. please enable callout by annotating the future method TIdEmailAddressItem undeclared uthenticationServices.AuthorizationError error 1000 bitbucket permission denied (publickey). fatal: could not read from remote repository. Database connection [postgres] not configured. error 400 bad request payfast FATAL: password authentication failed for user Will FINALLY block execute in the method body, if there are no exceptions in try or catch block web http code for not found fatal: cannot do a partial commit during a merge. error: error:0909006c:pem routines:get_name:no start line exceptions after waits pmd code analysis tool error prone discord enable disabled account verage session duration for each user who has more than one session Daemon Processes program warning unprotected private key file ec2 message queue c not pgadmin4 404 not found could not connect to websocket endpoint ws://localhost:4000/graphql. please check if the endpoint url is correct. chmod: cannot access 'ADB': No such file or directory nginx: [emerg] bind() to [::]:4433 failed (13: Permission denied) this app is not allowed to query for scheme fb-messenger" onrequestpermissionsresult not called mongooseserverselectionerror: could not connect to any servers in your mongodb atlas cluster. one common reason is that you org.hibernate.LazyInitializationException: could not initialize proxy [ua.tqs.ReCollect.model.User#2407] - no Session RejectedExecutionException phpmyadmin throws a 404 on opening openssl x509 certificate MongoParseError: URI does not have hostname, domain name and tld apache2 forbidden The metadata storage is not up to date, please run the sync-metadata-storage comman d to fix this issue. error 404 not found SSL certificate problem: unable to get local issuer certificate sigfpe error nodemailer Error: self signed certificate in certificate chain your dns server might be unavailable [Violation] 'requestIdleCallback' handler took <N>ms The "RazorTagHelper" task failed unexpectedly. enable htaccess how to rerun failed test in testng Network initialization failed functions predeploy error: command terminated with non-zero exit code1 clion cannot open output file permission denied mongodb socket exception 'bodyParser' is deprecated.ts(6385) Allowed memory size of 1610612736 b testng rerun failed tests what kind of exception after explicit wait chrome-error://chromewebdata/ mongo Client.connect ('mongodb://localhost/cursoNode', {useNewUrlParser: true,useUnifiedTopology: true }); .then( conn() => {global.conn = conn.db("cursoNode") }).catch ((error) => { console.log ("error") }) how to not panic null error due to delay in api response ida intrernal error 1491 telerik DataErrorsChangedEventArgs error cloudinary error relation active storage blobs does not exist mMap.getUiSettings().setAllGesturesEnabled(false); Access to XMLHttpRequest at '' from origin '' has been blocked by CORS policy: gps access is not granted or was denied errno 123 flutter the current thread cannot "assuming the servlet is configured properly" OrientDB.ConnectionError [10] worker_processes" directive is not allowed here in errno: -28, syscall: 'watch', code: 'ENOSPC', path: '/root/world-music-web/public', filename: '/root/world-music-web/public' error disable owin startup discovery web.config after certificate Member shr4.o is not found in archive in AIX 7.2 The Dev Hub org cannot be deleted. No valid crumb was included in request for /plugin/swarm/create Slave by swarm.node. Returning 403 Showing Recent Messages Validation succeeded. Exiting because upload-symbols was run in validation mode pam_unix(vsftpd:auth): Couldn't open /etc/securetty: No such file or directory awk exit after error authorization failed or requested resource not found in oracle cloud ng serve ---Mg:server fundamental error loginurl attribute is not allowed error in web config PODS are on NotReady status? Bad state: Unexpected diagnostics: API.TaskCombatPed(Enemy, Target.Guard, 0, 16); no ha sido posible crear el directorio wordpress execution id: how to check someones permission on a redhisft external schema xamarin await PullAsync The request could not be completed. (Resource Not Found) monit: error connecting to the monit daemo ntp service keeping failed with result 'exit-code' remove input x how to keep page from scrolling sideways matrix latex benconti org how to make array uniq adding resources pom.xml bootstrap script 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte delete conda environment apache enable mod headers how to use grepper flutter sign apk String Formatting with the % Operator how to get the player character roblox script visual studio comment out multiple lines shortcut icon client.user.setActivity("YouTube", {type: "WATCHING}) docker build supress build output What is (object sender, EventArgs e) xml array of objects that is something conflicting provisioning settings error when I try to archive to submit an iOS app mustache syntax in laravl vue ipad mini xcode simulator multiple fine uploader in one page connecting to timescaledb from terminal mazda usa monday in french london 50's buildings tutorials on appsync graphql transformation punk creeper platform shoes cheap scrapy itemloader example self.new_from_db print("Minus - 12") bitcoin visual studio code spanish to english transalte übersetzer english to spanish french english translate google translate jap to eng google translate afrikaans to english traduttore afrikaans to english translate spanish german to english translator översättning svenska till engelska eng to span french to english google übersetzer google trAanslate översätt trad english to japanese English to french japanses to english google trad traduction espagnol google transalte japanese to english googl trad traduction google traduction oversetter translate néerlandais google translate to japanese twitch gme stock dotenv grepper dogecoin price border radius bootstrap alphabet bootstrap 4 font bold youtube you tube gamestop stock instagram find my phone nodemon AMC Stock bootstrap list group netflix what time is it english to german tradutor ingles spanish to english] english to hindi tradutor google trsnlate friday night funkin ascii flexbox align right and left iphone 12 mini responsive img oculus quest 2 bootstrap width 100 twitter chess asdf minesweeper ustify-content: flex-end; bootstrap visual studio markdown link spanish dictionary pip freeze requirements.txt what is an api create vue project Snapchat bootstrap link December global festivities mongodb local connection string preventdefault reddit redit corona tracker statistiques Coronavirus France corona statistics tinder eclipse npm clear cache attack on titan season 4 download android studio solid degrees to radians create postgres database float right bootstrap bootstrap tooltip pacman 30th anniversary black color code clion what is api speed of light file input file types lodash npm npm update spotify open.,spo bootstrap breakpoints docker access container avatar the last airbender conda list environments set background image opacity bootstrap center align columns latex tabular cookie clicker image responsive bootstrap 4 text field flutter how to get list of docker containers http response status codes how to make image responsive bootstrap 4 microsoft flight simulator 2020 hypixel ip rainbow six siege Cannot connect to the Docker daemon at unix:///var/run/docker.sock. Is the docker daemon running? find out process using port windows stack overflow rainmeter delete all records from table show my homework font awesome define size How to set a image as a backgroung image flutter listview builder how to change to dark mode visual studio how to update pip code grepper like cheat ModuleNotFoundError: No module named 'requests' hacker news ReferenceError: primordials is not defined docker list containers markdown image flutter build android release apk small pacman flutter grid view which sign is greater than create a venv table in markdown clear cmd google.com body-parser npm show collections in mongodb npm font awesome jupyter notebook cmd http status codes proptypes oneof tictactoe play tic tac toe import roboto font boostrap shadow monkey lorem ipsum what is polymorphism flutter svg badlion client 2*sqrt(3)*sqrt(4) stackoverflow intellij adding a preview image in readme.md rule 34 Markdown new line accii art search and replace vim world population predicted growt before earth population ngif else bootstrap 4.5 cdn covid stats todays corona numbers tesla stock check postgres version bootstrap 4 image circle Uncaught ReferenceError: $ is not defined wattpad what is brainfuck for markdown table latex text size VScode duplicate line ERROR: Could not find a version that satisfies the requirement tensorflow (from versions: none) ERROR: No matching distribution found for tensorflow my anime list heroku logs dropdown button flutter example processing center text in div container yarn update all dependencies to latest TypeError: 'NoneType' object is not subscriptable https roboto font update npm December global holidays responsive media query breakpoints lorem ipsum dolor sit amet sonic boku no pico bootstrap cdn video bootstrap npm check package version coding challenges how to create drop down list in flutter how to list docker images code grepper bootstrap cdn link play minesweeper on hover change cursor urban dictionary wordpress .htaccess file code image align center migrate fresh specific table README.md image amazon prime Can't bind to 'ngModel' since it isn't a known property of 'input'. list docker images firebase deploy only function english alphabet npm ERR! missing script: start pip freeze autohotkey flutter font bold ddos border for container in flutter Benoit Mandelbrot blocks for beacon activate virtualenv windows checkbox in flutter how to enable flutter web next link what is bootstrap E Unable to locate package sl prune volume docker 20 minute timer import axios text input max length Best free Editing sftware blue hex code happy new year npm concurrently include picture in latex delete conda environment twitch.tv internet explorer where am i random photo flutter future builder 4k resolution flutter container border Could not initialize class org.codehaus.groovy.runtime.InvokerHelper npm update all using pip windows cmd LF will be replaced by CRLF in assets deployment example gold color code orange color code npm cache clean Arsenal how many seconds in 1 hour flutter navigate to new screen create db user postgres Could not find module "@angular-devkit/build-angular password regex vi line number windows keyboard shortcut switch desktop bootstrap media query breakpoints media breakpoints fontawesome.com search icon bootstrap script csgo open previous closed tab chrome ng add @angular/material build apk flutter command array arduino bootstrap button group what is an IDE how to make a conda environment how to query in firestore centre align image in div ngstyle ping visual studio comment out block df fetch value nok stock Flutter Navigator to new page put header at bottom of div flexbox all same height how to open anaconda in terminal area of trapezium flex force div right side how to plot a scatter plot in matplotlib vim download how to create link in readme.md minecraft less than no module named numpy format code discord how to insert an image in markdown 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte ipl match today flutter input text in container latex sum PIL module not detected window host file cloudflare dns docker tag download ram OR gate mac active developer path import error no module pip acid properties in dbms itemize latex minecraft server startup code flutter raisedbutton example conda write environment.yml Module not found: Can't resolve 'react-router-dom' prettier don't format line how to know the ip address of my pc using cmd electromagnetic spectrum fontawesome.com mak icon bigger find gameobject with tag markdown embed image select search bootstrap less equal latex league of legends download latex bullet points clear terminal windows composer require with version delete docker containers gson dependency android headers in axios.get find maximum number in array npm webpack include image latex switch case in flutter how to get current product key windows 10 npm start reset cache encapsulation programming in url Flutter give image rounded corners how to check wifi password using cmd jojo's bizarre adventure columns center bootstrap 3 white color code Message: 'chromedriver' executable needs to be in PATH. bootstrap modal center add image to readme xcrun: error: invalid active developer path (/Applications/Xcode.app/Contents/Developer), flutter add shadow to container google french translate anaconda remove environment myspace let vs const error: (-215:Assertion failed) !_src.empty() in function 'cv::cvtColor' flutter apk build add migration ef core radio button vue container decoration box flutter stripe test card spring boot run command cool math games adb is not recognized m to cm font awesome 4 animated loading spinner run chrome without cors multithreading what is the code for red color This is probably not a problem with npm. There is likely additional logging output above lite server image center in div url in latex dummy paragraph steins gate nodemon global instal npm Toast messag eandroid docker remove container material box shadow put vs patch dogecoin wordpress docker compose contains text xpath font awesome cdn nvm set default how to add image overleaf systemctl reload nginx bootstrap 4 cdn carpe diem full beacon size soap vs rest textfield border flutter how to check flutter version docker get container ip *ngSwitch test format code intellij light blue hex code use npm to update packages to latest version bootstrap overflow hidden how npm clean cache URL vs URI sleep find with $or in mongobd spinner android tailwind container center crontab every 5 minutes npm update to latest toast code in android studio nitric acid New Year's Eve list overleaf mongodb exists generate apk ionic 1 shared prefs flutter iphone 12 release date fontawsome flutter how to make toast in android Hex editor No module named 'sklearn' corona rates bootstrap font asesome cdn update all dependencies with npm windows shutdown command timer vim replace command clearfix hack flutter alertdialog sha1 flutter text-align: center; latex new line add image in markdown pm2 start npm start gentoo what is grepper how to center a form in bootstrap hcmc stock how to farm grepper likes erase duplicates and sort a vector how to convert a base 64 to blob 1 day in seconds cuda version typing racer whitespace regex word reference run cron every hour npm handlebars circle imageview dependency in android update pip module inspect chrome mobile win rar text-decoration:none; bootstrap Cannot read property 'length' of undefined select2.org events stan lee gravity forms shortcode no module named pip how to activate a venv in windows conda create env from yml mongoose find not equal to arduino code analogwrite give space in latex Can't bind to 'ngModel' since it isn't a known property of 'input' purple hex code jake paul pip numpy media query desktop carpal tunnel? form file upload enctype wisard of oz delete conda env anaconda duplicate environment Eclipse (software) flutter container border radius cancel ng server port how to login using a particular user postrges centos 7 port open reformat intellij infinity war assembly pink hex code color gradient in flutter system taking 100 disk windows 10 how to put container in center of page select2 clear options kill screen session from outside bootstrap text center in div create a tag from a commit/branch onclick href Property 'firstName' has no initializer and is not definitely assigned in the constructor covid map starlink star link go.scatter regex to identify numeric and alphanumeric how to view product key in windows 10 have .
https://www.codegrepper.com/code-examples/whatever/java+arraylist+contains+string
CC-MAIN-2021-17
en
refinedweb
Java.lang.Runtime.gc() Method Description The java.lang.Runtime.gc() method. The name gc stands for "garbage collector". The virtual machine performs this recycling process automatically as needed, in a separate thread, even if the gc method is not invoked explicitly. The method System.gc() is the conventional and convenient means of invoking this method. Declaration Following is the declaration for java.lang.Runtime.gc() method public void gc() Parameters NA Return Value This method does not return a value. Exception NA Example The following example shows the usage of lang.Runtime.gc() method. package com.tutorialspoint; public class RuntimeDemo { public static void main(String[] args) { // print when the program starts System.out.println("Program starting..."); // run the garbage collector System.out.println("Running Garbage Collector..."); Runtime.getRuntime().gc(); System.out.println("Completed."); } } Let us compile and run the above program, this will produce the following result − Program starting... Running Garbage Collector... Completed.
https://www.tutorialspoint.com/java/lang/runtime_gc.htm
CC-MAIN-2018-26
en
refinedweb
I am trying to include a ".jsx" file so i can use their functions i've written. Now when i use: #include "filename.jsx" i only get an error message when i add the extension in Photoshop CC i think the #include statement must have a correct path, or the file won't be found, now my question would be. Which path das #include use? Or, How can i include a .jsx file which is in the xxx.assets Folder within the extension Folder? e.g. myScript.jsx inside the myScript.assets Folder, to access a function named myFunction()... Retrieving data ...
https://forums.adobe.com/thread/1256445
CC-MAIN-2018-26
en
refinedweb
JsonFormatter is an Fast, Lightweight Json serialization/deserialization library for Unity projects. Features - Serializing Collections: Lists, Dictionaries, IEnumerable - Serializing KeyValuePair - Serializing ISerializable - Surrogate Serialization - Serializing Almost anything (Automatically serializes public fields and properties) - Deserializing IDeserializationCallback - Fast and Helpful Customer Support - Free & Open Source - Easy to Use - Cross Platform (Let us know if you have any problem with any platform) Getting Started Just add using BayatGames.Serialization.Formatters.Json; then you are ready to go. JsonFormatter provides some static methods for fast serialization of objects to json string: using BayatGames.Serialization.Formatters.Json; ... string json = JsonFormatter.SerializeObject ("Hello World"); Get it now: Source Code:
https://itch.io/t/143242/jsonformatter-complete-json-serialization-library
CC-MAIN-2018-26
en
refinedweb
Due to the large screen sizes, we do not need (or want) to zoom/pan to form fields. We also do not need the next/prev buttons to appear. Tablet keyboards have a "Tab" button to make moving between fields easier. We still want the combobox UI and the form suggestion bubble. We should try to trigger this based on screen size. We are using >800 px in a different tablet UI bug. (In reply to comment #0) > We still want the combobox UI and the form suggestion bubble. If you want the form suggestion bubble this is another good reason to move it out of FormHelperUI (bug 648026) Created attachment 532162 [details] [diff] [review] Patch Created attachment 532163 [details] [diff] [review] Patch Oups, left some debug code (the previous version was always disabled) Comment on attachment 532163 [details] [diff] [review] Patch >+ // Dynamically enabled/disabled the form helper if needed >+ let mode = Services.prefs.getIntPref("formhelper.mode"); >+ let state = (mode == 2) ? (window.innerWidth <= 480) : !!mode; I think we want to use a physical length. We are using 124 mm in a different place as a tablet trigger. See for getting the DPI if my math is right, this should work: let dpmm = DPI / 25.4; let state = (mode == 2 ? ((window.innerWidth / dpmm) <= 124) : !!mode); >+ Services.prefs.setBoolPref("formhelper.enabled", state); Instead of using "formhelper.enabled" can we just move this into the "enabled" getter? and make it memoized > case "FormAssist:Hide": >- this.enabled ? this.hide() >- : SelectHelperUI.hide(); >+ if (this.enabled) >+ this.hide(); >+ else { >+ SelectHelperUI.hide(); >+ ContentPopupHelper.popup = null; >+ } Use { } around the "if" part r- for the nits Created attachment 532610 [details] [diff] [review] Patch v0.2 (In reply to comment #4) > Instead of using "formhelper.enabled" can we just move this into the > "enabled" getter? and make it memoized forms.js use formhelper.enabled too but can't access window.innerWidth (since it use a fake viewport) Comment on attachment 532610 [details] [diff] [review] Patch v0.2 >diff --git a/mobile/chrome/content/Util.js b/mobile/chrome/content/Util.js > return (!appInfo || appInfo.getService(Ci.nsIXULRuntime).processType == Ci.nsIXULRuntime.PROCESS_TYPE_DEFAULT); > }, > >+ isTabletSized: function isTablet() { I kinda prefer "isTablet" >diff --git a/mobile/chrome/content/common-ui.js b/mobile/chrome/content/common-ui.js >+ // Dynamically enabled/disabled the form helper if needed depending on >+ // the size of the screen >+ let mode = Services.prefs.getIntPref("formhelper.mode"); >+ >+ // See the tablet_panel_minwidth from mobile/themes/core/defines.inc >+ let tablet_panel_minwidth = 124; >+ let dpmm = Util.getWindowUtils(window).displayDPI / 25.4; You can remove this code, right? You're using Utils.isTablet() r+ with the nits fixed We could use a test for this. Running it on phones would at least let us know the FormHelper is active for small screens. Can someone having a tablet, please, verify this ? Verified Ideos s7 - Mozilla/5.0 (Android; Linux armv7l; rv:6.0a1) Gecko/20110523 Firefox/6.0a1 Fennec/6.0a1 ID:20110523042031
https://bugzilla.mozilla.org/show_bug.cgi?id=656373
CC-MAIN-2016-26
en
refinedweb
This chapter is informative.:::" and " xsd:" are used to denote the XForms and XML Schema namespaces respectively. This is by convention only; any namespace prefix may be used in practice... Attribute Definitions: - count = integer - description of this attribute Attributes Defined Elsewhere: size The following highlighting is used for non-normative commentary: Editor's Note: Inline informational note to provide annotations or point out design decisions. [Editor's Feedback Request 1.4.sample: A uniquely identified request on behalf of the Working Group for specific feedback on XForms.] [Ed. General comments intended for removal before final publication.]
http://www.w3.org/TR/2001/WD-xforms-20010216/intro.html
CC-MAIN-2016-26
en
refinedweb
Python Programming, news on the Voidspace Python Projects and all things techie. The Joys of Open Source I'm a great believer in Open Source software. I like the collaboration and the sharing. I also like the idea of people using my code. It's a buzz to feel that all over the world, people are learning or getting benefit from my efforts. I've also gained from using other peoples' open source code. Python itself is a great example of course. Many businesses are built on top of open source software (the major architecture of Google for example is run on Linux, they are also extensive users of Python). Almost every field of computer use has some open source involvement. It's a great way that people can work together, sometimes in very large groups, to achieve far more than they ever could on their own. Together we can share knowledge, develop new technologies (yes software techniques are a technology) and occasionally meet interesting people. Programming is also a great way to express creativity. Programming can be viewed as the antithesis of creativity. It operates according to a fixed set of precise rules that govern the behaviour of computers. As Charles Babbage demonstrated (at least in theory), this can be done with entirely mechanical devices. This fixed framework enables creative thinking. By knowing precisely what building blocks you have at your disposal, and how they will (or at least ought to) behave, the software craftsman is free to put those building blocks together in any way his (or her) imagination can conceive of. If the cathedral, formed from unyielding rock, is a work of art and beauty; then so are the elegant and intuitive creations of the great programmers. Not all open source projects are successful though. Success of course is a very nebulous term, sometimes failure is easier to spot than success ! If you browse the many open source repositories to be found on the world wide web, you will soon discover the seemingly countless projects there are. Certainly in the millions. The overwhelming majority these are the creations of single programmers, possibly never used even by their progenitor. A few of these have a thriving community based around them. A successful project may have ten or less active developers, but be used by thousands of people. If you'd like to be involved in software collaboration, then you have two choices. Contribute to an existing project or release your own code. Getting other people to join a new project, where you are the only developer, is difficult. Why should people jin you, when there are so many thousands of other ones out there ? Finding an existing project is a better way to get mentoring and feedback, but the barrier to entry is higher. An already mature project, by virtue of being successful is likely to be fairly sophisticated. Projects that I've considered joining, but never quite managed to contribute to in any meaningful way, include docutils, SPE, and kupu. So if you decide to go it alone, how do you measure the success of your project ? One measure is how often your code is downloaded. I get over a hundred downloads a day for my various projects. Sounds good ? Well, based on my own habits, that doesn't necessarily mean very many users. Whenever I hear of some new interesting project or code I will take a look at it on the internet. A lot of these I download, intending to look at later. Most of them I never get a chance to look at, and most of the ones I do I never actually use. As a wild guesstimate I'd say that only about one in twenty of the things I download do I ever actually use at all. Even if I do use them, unless I'm very impressed it's rare for me to contact the author. I'm not alone. Despite my website getting over a thousand visitors a day and over a hundred downloads a day, I only ever get contact from a few people in the course of a week. Maybe the code (or program) is straightforward, so they don't need to contact me, or maybe it's just no good. I just released a new version of Movable Python. In it's first incarnation this was an open source project hosted on sourceforge. It was a good idea, and I put a lot of effort into making it useful. In the first year it was downloaded over three thousand times. In all that time I had a single donation from someone who found it useful (thanks Mickey!), as well as occasional positive feedback from other users. For the new version I decided I needed more return on my investment of time and effort. Movable Python is no longer open source, but available for a very low price from The Voidspace Shop. I've had a pleasing number of buyers (growing daily), and some good feedback. An update will follow shortly, and the Python 2.2 version will also be released. This will be useful for people who want Movable Python for compatibility testing, so I'm hopeful of a fresh batch of 'donators'. The number of people paying for it though (unsurprisingly), is vastly less than the number of people who downloaded it when it was free. This is despite the fact that the new version is a much improved. As another example, take Nanagram. It's a silly little program that generates anagrams from words (or names). It was one of the first programs I wrote with a GUI, but has a really neat recursive algorithm for finding the anagrams. There is also an online version. When I finally installed awstats for my website, I was surprised to find that the online version is getting hundreds of hits. The windows installer gets downloaded about six times a day or more, and has done for over a year. Anagram hunting is a surprisingly popular activity ! Whilst Nanagram may not be the fastest one available, it's easy to use and fun. Most of the other anagram programs are commercial or shareware. In the last year I've not had a single person contact me about Nanagram in any way. Hmmm... I'm no better than anyone else though, I've only contributed financially to a single open source project in the last year. I've given feedback and encouragement to a lot more, but by no means all the ones I've used. I think the answer with Nanagram is that I will probably leave the source code open source, but charge for the windows executables. In the meantime I guess my code needs to improve (in quality and relevance) before I can expect more participation. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-10 08:54:53 | | Categories: General Programming, Python Movable Python Logo Thanks to James Norden, the CTO of TBS, Movable Python has a new logo. Python on a Stick. Nice isn't it. Update I've improved the look of the Movable Python Shop and added the logo. Work is now in progress on the Python 2.2 version, which will also mean a slight update to the other versions. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-09 22:37:43 | | Categories: Projects, Python Gadgets and Games. I've also got my new Nokia 3230 Phone. I haven't got Python running on it yet though. >>IMAGE:26:51 | | Categories: Computers, Fun PDA Disaster I've had a PDA disaster. Over the last few days, my XDA IIi has sputtered to a halt and finally died. . Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-09 22:21:04 | | ConfigObj 4.2.0 Beta 2 I've just checked an updated version of ConfigObj into the subversion repository. This is ConfigObj 4.2.0 Beta 2, and it's in the usual place : This now has a set of tests and I'm happy with the changes. If no bugs are found, then this will become ConfigObj 4.2.0. Warning The way that ConfigObj handles file like objects has changed. It no longer keeps a reference to them. This is better, but could break existing code. Additionally, the BOM attribute is now a boolean. I haven't yet done the documentation, but these are the changes : Full unicode support. You can specify an encoding and a default_encoding when you create your instance. The encoding keyword maps to the encoding attribute. It is used to decode your config file into unicode, and also to re-encode when writing. The default_encoding (if supplied) is used to decode any byte-strings that have got into your ConfigObj instance, before writing in the specified encoding. This overrides the system default encoding that is otherwise used. UTF16 Handling UTF16 encoded files are automatically detected and decoded to unicode. This is because ConfigObj can't handle them as byte strings. BOM Attribute The BOM attribute is now a boolean. If a UTF8 or UTF16 BOM was detected then it is True. The default is False. If BOM is True, then a UTF8 BOM will be written out with files that have no encoding specified, or have a utf_8 encoding. File like Objects. ConfigObj no longer keeps a reference to file like objects you pass it. If you create a ConfigObj instance from a file like object, the filename attribute will be None. In addition to this, the seek method of file like objects is never called by ConfigObj. (It tests for the read method when you instantiate.) You must call seek(0) yourself first, if necessary. This means you can use file like objects which don't implement seek. Writing to a file like object. The write method can now receive an optional file like object as an argument. This will be written to in preference to a file specified by the filename attribute. Line Endings. When passed a config file (by whatever method), ConfigObj will attempt to determine the line endings in use. (It chooses the first line ending character it finds, whether this be \r\n, \n, or \r.) This is preserved as the newlines attribute. When writing (except when outputting a list of lines), this will be used as the line endings for the file. For new ConfigObj instances (or where no line endings are found), it defaults to None. In this case the platform native line ending (os.linesep) is used. There are also the new Section Methods added in Beta 1 : - as_bool - as_int - as_float They all take a single key as an argument, and return the value in the specified type. They can all raise KeyError or ValueError should the situation demand it. Note Another change is that ConfigObj does not now convert the filename attribute into an absolute path, unless that is what you supply it with. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-09 21:14:52 | | Categories: Projects, Python Line Endings Part III Part III (and definitely the final part) of my tangled investigation into Python line endings in files. Quick summary of the story so far : - I want to read files and split them into lines. - Sometimes an encoding will be explicitly supplied. - Sometimes no encoding will be specified, but in order to correctly handle UTF16 files I need to decode to Unicode first. - For UTF16 files each character is two bytes. I will only be able to recognise the line endings after decoding. There are a few different ways I could do this : - Use the splitlines attribute of the unicode string. - Open the file in universal mode "rU". Once read has encountered a line ending it sets the newlines attribute on the file. - Use my code snippet to determine what line ending is in use. - Open the file and read a few bytes. If it is UTF16, re-open with the correct reader using codecs.getreader('utf_16'). (I would still have to splitlines, but the decode would already be done). In fact option 2 doesn't work for me. UTF16 is a multi-byte encoding, so \r\n is encoded as : \r\x00\n\x00' Opening the file in universal mode and reading sets the newlines attribute to : ('\r', '\n') This is because it thinks that it has seen both \r and \n line endings, rather than \r\n endings. In option 1, splitlines actually treats all of \r, \n, and \r\n as line endings : 'one\r two \n and three\r\n really'.splitlines()['one', ' two', ' and three', ' really'] This means I am definitely worrying about this too much [1]. It does occur to me that it would be nice to preserve the line endings and use the same ones when writing. I will use splitlines(True) which preserves the line endings, and treat the first one encountered as the definitive one for the file. Sorted. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-08 12:29:17 | | Categories: Hacking, Python Ajax in Action I've received a review copy of the book Ajax in Action, by Dave Crane. Because of my house move (and resulting confusion), I've only managed to get part way through the book. As soon as I'm able to finish it, I'll post a review. It's not particularly (read - at all) aimed at Python programmers, but is nonetheless very well written and easy to follow. It's suitable for anyone who has a basic grasp of Javascript and web application programming. I can already heartily recommend it. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-08 10:46:12 | | Categories: General Programming, Writing Movpy News A couple of pieces of Movable Python news. A user reports getting Zope 3.2 to work with Movable Python Zope on a rope! Movable Python allows me to carry Zope3.2 and my development environment everywhere I go. It's a great product, I love it.-- Kevin Smith It looks like a German printed computer magazine, c't (with a circulation of around four hundred thousand), are going to have a brief article on Movable Python in their next issue. Great. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-08 10:32:43 | | Categories: Python, Projects Detect Line Endings, Part II Here's the method I came up with to detect which line endings are in use in a piece of text. It counts occurrences of the three line endings, and picks the largest. As you can see from the docstring, it attempts to do sensible(-ish) things in the event of a tie, or no line endings at all. Comments/corrections welcomed. I know the tests aren't very useful (because they make no assertions they won't tell you if it breaks), but you can see what's going on : import os rn = re.compile('\r\n') r = re.compile('\r(?!\n)') n = re.compile('(?<!\r)\n') # Sequence of (regex, literal, priority) for each line ending line_ending = [(n, '\n', 3), (rn, '\r\n', 2), (r, '\r', 1)] def find_ending(text, default=os.linesep): """ Given a piece of text, use a simple heuristic to determine the line ending in use. Returns the value assigned to default if no line endings are found. This defaults to ``os.linesep``, the native line ending for the machine. If there is a tie between two endings, the priority chain is ``'\n', '\r\n', '\r'``. """ results = [(len(exp.findall(text)), priority, literal) for exp, literal, priority in line_ending] results.sort() print results if not sum([m[0] for m in results]): return default else: return results[-1][-1] if __name__ == '__main__': tests = [ 'hello\ngoodbye\nmy fish\n', 'hello\r\ngoodbye\r\nmy fish\r\n', 'hello\rgoodbye\rmy fish\r', 'hello\rgoodbye\n', '', '\r\r\r \n\n', '\n\n \r\n\r\n', '\n\n\r \r\r\n', '\n\r \n\r \n\r', ] for entry in tests: print repr(entry) print repr(find_ending(entry)) A useful little recipe, if you can't leave python to handle your line separators for you. There are two reasons for using this : - Saving a file with the same line endings it was created with - Splitting files into lines after decoding into unicode Update Apparently opening the file in universal mode ("rU") exposes a newlines attribute. I need to check that it works with Python 2.2 and with UTF16 encoded files. If it does, it's a bit easier than the code posted here. After a bit of investigation - it doesn't do the correct thing with UTF16 encoded files. splitlines on the decoded string does, more or less, though. See Part III... Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-06 21:49:51 | | Categories: Python, Hacking Inline Functions One of the ways that compilers of static languages optimise generated code, is by inlining small functions. This removes the overhead caused by having to use the stack when calling the function and exiting the function. In Python the cost of creating and destroying stack frames is particularly high, so the potential benefits are even greater. Warning This is one of those silly ideas I waste brain bandwidth on, with no way of making it happen. Inlining functions adds the benefit of code efficiency, whilst keeping your source clean (and maintainable) through code re-use. Static language compilers are able to do this because they know a great deal about the types of variables passed to functions, used within them, and returned from them. Because of Python late binding, the compiler is able to almost nothing about the types of variables; right up until runtime. This is the barrier Brett Cannon hit when attempting to implement Localized Type Inferencing in Python. He saw virtually no speed increase. However there are several interesting projects out there. Not least of which is PyPy. There is also an alternative implementation of the Python virtual machine called pyvm. Both of these have custom Python compilers. (The pyvm one is called pyc.) Either of these could do bytecode optimisation by inlining functions. A new syntax, or even a decorator, could be added to specify that a function is suitable for inlining. Function local names would have to be suitably mangled to avoid clashes, and the function would need to be non-recursive and not use nested scoping. Other limitations may also need to apply, but with a user syntax to mark functions for inlining - caveat emptor. I wonder if any other compiler optimisation tricks could be implemented as bytecode hacks Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-06 18:49:41 | | Categories: Python, General Programming Detecting Line Endings My forays with unicode still leaves me in a dilemma as to how to handle (or expect) line endings for windows. For 16 bit encodings, \r\n is a four byte sequence. Should I expect to read and write these for windows ? I need to maintain compatibility with windoze tools that the user might use to create the text files I read. Because I'm reading and writing in binary mode, I can't expect Python to handle this for me. So how do I detect line endings safely and sanely ? There are three possible line endings. (The native one is available as os.linesep.) - \r\n - Windoze - \n - Lunix type systems (Unix and Linux variants) - \r - Mac systems Is the following safe and sane : if encoding: text = text.decode(encoding) ending = '\n' # default if '\r\n' in text: text = text.replace('\r\n', '\n') ending = '\r\n' elif '\n' in text: ending = '\n' elif '\r' in text: text = text.replace('\r', '\n') ending = '\r' My worry is that if '\n' doesn't signify a line break on the Mac, then it may exist in the body of the text - and trigger ending = '\n' prematurely ? (Or vice-versa with \r on Lunix ?) Update A suggestion on comp.lang.python is to count occurrences of '\r\n', '\n' without a preceding '\r' and '\r' without following '\n', and let the majority decide. (Thanks Sybren.) Edge case where you have small files of course, but what's a guy to do ? Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-06 14:45:05 | | Categories: Python, Hacking Unicode, UTF Encodings and BOM I thought I understood encodings. I've even written an article on the subject [1]. Over the weekend I've been adding full unicode support, along with other improvements, to ConfigObj the config file reader/writer. Summary This entry summarises the difference between handling UTF8 and UTF16 encoded text, in Python. Unicode isn't as difficult as it is reputed. Nonetheless, it can be fiddly writing code that has to handle both unicode strings and byte-strings. Even worse if you potentially have a mix. The basic principle is that when you read a file you get a byte-string. To turn this to unicode, you need to specify the encoding and decode. To write unicode strings to file, you have to specify the encoding you want to use and encode back into a byte-string. To make it more interesting there are two common encodings (plus other less common) that cover the whole unicode spec [2]. These are UTF8 and UTF16. For these you may have to handle (or at least understand) the BOM. Unsurprisingly, UTF8 is an 8 bit encoding. It represents the ASCII characters using a single byte. Other characters use three bytes. Because it is ASCII compatible, it is the only full unicode encoding recognised for web pages. UTF16 is a 16 bit encoding. It uses two bytes per character. In order to understand text encoded with UTF16, Python needs to know whether it was produced on a big endian machine, or a little endian one - the byte order. For this reason, UTF16 strings start with a two byte BOM. UTF8 also has an associated BOM. As an eight bit encoding it doesn't have a byte order, so this is better referred to as the unicode signature. For ConfigObj, you really don't want your first key starting with a BOM: it needs to be detected and removed. (But preserved for writing later). You may not want UTF8 strings automatically decoding to unicode. UTF16 strings must be recognised and decoded. The regular expressions ConfigObj uses to parse config files will split the string on byte boundaries. Because UTF16 is a multi-byte encoding, this will truly mangle your text. For UTF8 (which I've handled before) this is straightforward. Detect and remove the BOM, then decode. Later, encode to byte strings, add the BOM then write. So the following code works for UTF8 (simple example) : text = open('test.cfg').read() if text.startswith(BOM_UTF8): encoding = 'utf_8' text = text[len(BOM_UTF8):] text = text.decode(encoding) # # parse... # Next we want to write # Our text is now a list called 'members' # if encoding == 'utf_8': text = '' for mem in members: text += mem.encode(encoding) text = BOM_UTF8 + text open('test.cfg', 'w').write(text) Let's simplify even further, and see what happens if we do the last step (encoding) with UTF16. To confirm that it works, we'll decode our final string back into unicode and try to re-encode as latin-1 : text = '' for mem in members: text += mem.encode(encoding) text = text = BOM_UTF16 + text # unicode_string = text.decode(encoding) print unicode_string.encode('latin-1') Surprisingly we get the following result : UnicodeDecodeError: 'ascii' codec can't decodebyte 0xff in position 0: ordinal not in range(128) Aside from the confusing fact that the error is reported from the ascii codec (which shouldn't have anything to do with it), what is going on here ? u'and some more'.encode('utf16')) print text '\xff\xfeS\x00o\x00m\x00e\x00 \x00t\x00e\x00x\x00t\x00' ' \x00\xff\xfea\x00n\x00d\x00 \x00s\x00o\x00m\x00e\x00' ' \x00m\x00o\x00r\x00e\x00' print text.decode('utf16') u'Some text \ufeffand some more' See all the null bytes - \x00, this is because UTF16 is a two byte encoding; even for ascii text. The string decodes back into unicode using the UTF16 codec, but it can't be encoded as latin1. This is because of the extra \ufeff that has somehow got into the middle of the string. It turns out that because UTF16 needs the BOM (for an arbitrary machine to decode later), the Python codec adds the BOM automatically. The codec will automatically ignore (well, transparently remove) a BOM at the start of the string, but when decoding it leaves any others it finds in place. The BOM is a valid unicode character - but can't be encoded using latin1. So for UTF16 it's more correct to detect the BOM, but not add or remove it. This is different from how Python handles UTF8. For UTF8 you must remove the BOM yourself. If you want one when you write, you have to add it yourself as well. sigh Note This means you can't use the UTF16 codec to encode string fragments. So now I need to refactor the ConfigObj write method to leave the whole file as unicode until the final write, where I must encode in one pass. (Remembering to write in binary mode if the encoding is UTF16, so that Python doesn't insert \r anywhere in my file.) Maybe it's time to investigate the StreamWriter and StreamReader objects which will handle parts of this automatically. Note For those of you who wonder how I have time to make such long blog entries on a Monday morning, my journey to work is now a two hour mission involving two bus rides and a half hour wait in the bus station. At least I have my PDA for company. Hmmm... as I don't know the encoding before reading I can't use codecs.open. I probably can use it for writing. Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-06 09:26:42 | | Categories: Python, Writing, General Programming Movable Python & Digital Downloads Over the weekend I've sold nine copies of Movable Python. All for Python 2.4.2 so far. That amounts to about forty pence per hour (less than a buck), based on a wild random estimate of the amount of time I've put into it. I don't mind, not only do I expect the userbase to grow, but I'm heavily eating my own dogfood here. This blog entry is being typed at work, on Firedrop2 running under Movable Python. A user reports having got Zope 3.2 to run under Movable Python, so it could turn up in some interesting places. I'm using Tradebit to handle the downloads and PayPal transactions. A basic Tradebit account is only $2 a month. It was very easy to setup, and provides a logical (if not very attractive) interface for my customers. The guy who runs it is very responsive to questions and suggestions. A happy experience so far. I still haven't got the Python 2.2 distribution ready. I've spent most of my free time (TM) this weekend wrestling with unicode for ConfigObj. This will be the subject of another blog entry. Unfortunately just testing the Movpy code under Python 2.2 is no guarantee that the built distribution will behave as expected. The main issue I have to sort is adding the import paths in the right place. This happens automatically in normal Python, and differently for py2exe 0.6.3 (used to build for Python 2.3/2.4) and 0.4.1 (used to build for Python 2.2). This means I have to do an edit/compile (well, build distribution)/test cycle - all running in a VMWare session where I have Python 2.2 installed. Give me back my normal Python ! Oh, and a last word for the search engines - it's Movable Python, not Moveable Python. (Which is what a lot of people seem to google for.) Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-06 09:11:48 | | Categories: Python, Projects Guido Gives In Well, it finally happened Guido gave in. Looks like lambda is here to stay. I've only followed the arguments vaguely, but a brief summary would go something like this : - The lambda keyword defines an anonymous function - It is convenient where you need a function without keeping a named reference - But they're hard to read - and only a minor convenience really... Guido was in favour of dropping it altogether. This caused a huge amount of controversy, not least because various folk over on python-dev had all sorts of uses and theoretical reasons why we ought to keep them (or something similar). So Guido has decided that he'd rather people expended their energy on something a little more productive... Maybe this is the last word, and maybe it isn't... Like this post? Digg it or Del.icio.us it. Posted by Fuzzyman on 2006-02-05 22:26:36 | | Archives This work is licensed under a Creative Commons Attribution-Share Alike 2.0 License. Counter...
http://www.voidspace.org.uk/python/weblog/arch_d7_2006_02_04.shtml
CC-MAIN-2016-26
en
refinedweb
An introduction to Jersey By manveen on Feb 08, 2008 What is jersey? Jersey is not an island off the north coast of Normandy, France. Nor is it (despite the logo) a soft, plain-knitted fabric used for clothing cyclists. Jersey is the open source (under the CDDL license) JAX-RS (JSR 311) Reference Implementation for building RESTful Web services. Let's examine a simple Resource class in Jersey. 1 // The Java class will be hosted at the URI path "/helloworld" 2 @UriTemplate("/helloworld") 3 public class HelloWorldResource { 4 5 @HttpContext 6 private UriInfo context; 7 8 /\*\* Creates a new instance of HelloWorldResource \*/ 9 public HelloWorldResource() { 10 } 11 12 /\*\* 13 \* Retrieves representation of an instance of hello.world.HelloWorldResource 14 \* @return an instance of java.lang.String 15 \*/ 16 @HttpMethod("GET") 17 @ProduceMime("text/plain") 18 public String getClichedMessage() { 19 //Return some cliched textual content 20 "Hello World! Here is " + context.getAbsolutePath(); 21 } 22 } The HelloWorldResource class is a very simple Web resource. The URI path of the resource is "/helloworld" (line 2), it supports the HTTP GET method (line 16) and produces cliched textual content (line 20) of the MIME media type "text/plain" (line 17). Java annotations are used to declare the URI path (line 2), the HTTP method (line 16) and the MIME media type (line 17). Also note the @HttpContext annotation (line 5), which acts as a marker to say "Please inject an instance of the Java type, in this case UriInfo, after the class has been constructed." This use of annotations is a key feature of JSR 311.
https://blogs.oracle.com/manveen/tags/jsr311
CC-MAIN-2016-26
en
refinedweb
Red Hat Bugzilla – Bug 825902 [FEAT] Support for separate namespace for 'hooks' friendly keys. Last modified: 2013-12-18 19:08:11 EST Description of problem: Currently glusterd supports 'hooks' for every operation. Using this, user can execute some scripts 'pre' and 'post' an operation. We need to support special/separate namespace for few keys which user wants to be passed to these hook scripts, but glusterd need not interpret them. Also, this should not result in a failure in both staging and commiting phase. That way, we can provide more flexibility to users. patch fixes the issue on master. Any 'user.*' commands will be passed on to Hooks scripts now. the bug fix is only in upstream, not in release-3.3. Hence moving it out of the ON_QA, and setting MODIFIED (as a standard practice @ Red Hat) CHANGE: (glusterd: Persisted hooks friendly user.* keys) merged in master by Anand Avati (avati@redhat.com)
https://bugzilla.redhat.com/show_bug.cgi?id=825902
CC-MAIN-2016-26
en
refinedweb
Grayscale Image ViewerPosted Saturday, 24 October, 2009 - 15:04 by vmsgman in Processor: Intel(R) Core(TM)2 CPU T7200 @ 2.00GHz (1997 MHz) Operating System: Microsoft Windows XP (Service Pack 3) DirectX version: 9.0c GPU processor: Quadro NVS 110M ForceWare version: 175.97 Total available graphics memory: 256 MB Dedicated video memory: 64 MB System video memory: 192 MB Shared system memory: 0 MB Video BIOS version: 5.72.22.21.fc IRQ: 16 Bus: PCI Express x16 Total RAM 2Gb Hello, I am trying to remember my OpenGL programming class information from 15 yrs ago, and also translate that into Windows.Forms programming with OpenTK. I love working with your API thanks for the hard work and great results. I will post this code after it is worthy to be posted as an example for others. Can you help with a few things? I am opening images that are 16bpp grayscale, they have a header that has some info in it. But the ImageArray portion is an ushort[]. So I am having a hard time trying to figure out the best place to put the OpenGL code. What I have so far works okay except that I need to resize the image to keep the aspect ratio the same and minify the image by factors of 2 if it is too big to be displayed in the current window size. I am using my crappy laptop for development because I need this application to be used on older hardware. Lets just consider my laptop as the minimum requirements. I am new, except for a class eons ago, to graphics programming, so please be gentle. /* * Created by SharpDevelop. * User: ggerber * Date: 10/20/2009 * Time: 2:26 PM * * To change this template use Tools | Options | Coding | Edit Standard Headers. */ using System; using System.Collections.Generic; using System.Drawing; using System.Windows.Forms; using OpenTK; using OpenTK.Graphics.OpenGL; using Vip.Images; namespace ViVA.Net { /// <summary> /// Description of MainForm. /// </summary> public partial class MainForm : Form { private int textureId; private int appWidth; private int appHeight; private int viewWidth; private int viewHeight; private bool isCreated; private int panelWidth = 150; private VipImage vipImage; public MainForm() { InitializeComponent(); int scrWidth = SystemInformation.PrimaryMonitorSize.Width; int scrHeight = SystemInformation.PrimaryMonitorSize.Height; appWidth = scrWidth - 250; appHeight = scrHeight - 100; this.Width = appWidth; this.Height = appHeight; this.Location = new Point(125, 50); isCreated = true; } void MainFormLoad(object sender, EventArgs e) { GL.Enable(EnableCap.Texture2D); MainFormResize(sender, e); } void MainFormResize(object sender, EventArgs e) { if(isCreated) { appWidth = this.Width; appHeight = this.Height; glControl1.Width = appWidth - panelWidth; glControl1.Height = appHeight; glControl1.Location = new Point(panelWidth, 0); //if (vipImage == null) SetupViewport(glControl1.Width, glControl1.Height); //else //{ /; } }*/ //SetupViewport(viewWidth, viewHeight); //} } } void ExitMenuClick(object sender, EventArgs e) { this.Close(); } #region OpenGL Methods void GlControl1Paint(object sender, PaintEventArgs e) { glControl1.MakeCurrent(); GL.Clear(ClearBufferMask.ColorBufferBit | ClearBufferMask.DepthBufferBit); GL.Color3(Color.White); GL.MatrixMode(MatrixMode.Modelview); GL.LoadIdentity(); GL.Translate(glControl1.Width / 2 - (viewWidth / 2), glControl1.Height / 2 - (viewHeight / 2), 0.0f); GL.Begin(BeginMode.Quads); GL.TexCoord2(0.0f, 0.0f); GL.Vertex3(0.0f, 0.0f, 1.0f); GL.TexCoord2(1.0f, 0.0f); GL.Vertex3((float)viewWidth, 0.0f, 1.0f); GL.TexCoord2(1.0f, 1.0f); GL.Vertex3((float)viewWidth, (float)viewHeight, 1.0f); GL.TexCoord2(0.0f, 1.0f); GL.Vertex3(0.0f, (float)viewHeight, 1.0f); GL.End(); glControl1.SwapBuffers(); } void SetupViewport(int w, int h) { GL.MatrixMode(MatrixMode.Projection); GL.LoadIdentity(); //GL.Ortho(0, w, 0, h, -1, 1); // Bottom-left corner pixel has coordinate (0, 0) GL.Ortho(0, w, h, 0, -1, 1); // Upper-left corner pixel has coordinate (0, 0) GL.Viewport(0, 0, w, h); // Use all of the glControl painting area glControl1.Invalidate(); } #endregion void MainFormFormClosed(object sender, FormClosedEventArgs e) { glControl1.Dispose(); } void ButOpenClick(object sender, EventArgs e) { OpenFileDialog ofd = new OpenFileDialog(); ofd.Filter = "ViVA Files (*.viv,*.raw,*.bin,*.dat)|*.viv;*.raw;*.dat;*.bin"; ofd.FilterIndex = 1; if (ofd.ShowDialog() == DialogResult.OK) { glControl1.MakeCurrent(); vipImage = new VipImage(); vipImage.Read(ofd.FileName); treeViewImages.Nodes.Add(new TreeNode(ofd.FileName));; } } textureId = GL.GenTexture(); GL.BindTexture(TextureTarget.Texture2D, textureId); GL.PixelStore(PixelStoreParameter.PackAlignment, 2); GL.TexEnv(TextureEnvTarget.TextureEnv, TextureEnvParameter.TextureEnvMode, (float)TextureEnvMode.Modulate); GL.TexImage2D(TextureTarget.Texture2D, 0, PixelInternalFormat.Luminance, vipImage.Width, vipImage.Height, 0, PixelFormat.Luminance, PixelType.UnsignedShort, vipImage.ImageArray); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMinFilter, (float)TextureMinFilter.Linear); GL.TexParameter(TextureTarget.Texture2D, TextureParameterName.TextureMagFilter, (float)TextureMagFilter.Nearest); //SetupViewport(viewWidth, viewHeight); glControl1.Invalidate(); MainFormResize(sender, e); } } } } I would like the image to stay the same size when resizing unless it can't be displayed with the correct aspect ratio, then it should be displayed half as big. Thanks for any help you can provide! P.S. I would be happy to supply the rest of the project with sample images, or screenshots if this will help in troubleshooting, but I suspect that my problems are easily solved by putting the code in the right places! Greg Re: Grayscale Image Viewer do you mean "stay same aspect when resizing? does 9.140(). that help? from so i guess you just have to modify the width and height u pass into Ortho? Re: Grayscale Image Viewer Rakkarage, Thanks for taking the time to respond. Yes I need to keep the aspect ratio the same after resizing. Most of my trouble is coming from trying to recycle most of the code samples and snippets which use a C callback mechanism to this new idea of only redrawing on Form resize but have the glControl doing it's own painting on it's own schedule. I will work on it some more today. Thanks for your help. Greg Re: Grayscale Image Viewer np... i am not good at math but i dont think the witdth and height parameters to ortho even have to be related to window or viewport size... you can just put two constants that give that aspect you want (800, 600) (ya there is a smaller number then that that will give same result... its just a ratio right idk) and always use those? Re: Grayscale Image Viewer just had same prob with my ortho, fixed by applying some factor of the window width to x and some factor of the window height to y Re: Grayscale Image Viewer Hi All, I am back with many of the previous issues solved but I am still having issues with being able to drag the mouse to move the image (left,right,up,down). When I zoom (scroll mouse wheel) the center x,y of the image pixel changes. I am trying to keep the x,y coords the same on zooming. I am attaching the code with an image in the bin\Debug directory. If you can help me I would appreciate. I had to delete the OpenTK.dll file as it was too big to include. I am using the 0.9.9.3 release THX greg
http://www.opentk.com/node/1281
CC-MAIN-2016-26
en
refinedweb
While doing some auditing of a database, I found that some attachment content did not match the hashes given in the document's _attachments map. _attachments I tested this by downloading the document and calculating its hash. Comparing that to couchdb showed that they did not match. I then noticed that the mismatched attachments were ones that couchdb was configured to compress. It appears that my couch id configured to use snappy compression: foobox# grep -E 'file_compression|compressible_types' /etc/couchdb/{default,local}.ini /etc/couchdb/default.ini:file_compression = snappy /etc/couchdb/default.ini:compressible_types = text/*, application/javascript, application/json, application/xml However, when I attempt to compress the attachment content using snappy, and calculate the hash of the compressed data, it still does not match couchdb hash. In my example below, document-25977 is uncompressed (type application/pdf), and the uncompressed hash matches that provided by couchdb. The 2nd, document-78608, is a compressible type (text/plain), and the hashes do not match: document-25977 document-78608 foobox$ python hashcompare.py document-25977 couch len: 142918 couch hash: 028540dd92e1982bcb65c29d32e9617e (md5) local uncompressed len: 142918 local uncompressed hash: 028540dd92e1982bcb65c29d32e9617e local compressed len: 132333 local compressed hash: 3157583223dc1a53e1a3386d6abc312d document-78608 couch len: 2180 couch hash: e613ab6d7f884b835142979489170499 (md5) local uncompressed len: 2180 local uncompressed hash: 0ab2516c820f5d7afb208e3be7b924dd local compressed len: 1382 local compressed hash: d9e79232662f57e6af262fc9f867eaf2 This is the script I used to do the comparison: import couchdb import snappy import md5 import base64 server = couchdb.Server('') db = server['program1'] for doc_id in ['document-25977', 'document-78608']: print doc_id doc = db[doc_id] att_stub = doc['_attachments'][doc_id] hash_type, tmpdigest = att_stub['digest'].split('-', 1) att = db.get_attachment(doc, doc_id) data = att.read() # CouchDB is using snappy compression compressed_data = snappy.compress(data) print 'couch len: ', att_stub['length'] print 'couch hash: ', base64.b64decode(tmpdigest).encode('hex'), '(%s)' % hash_type print 'local uncompressed len: ', len(data) print 'local uncompressed hash: ', md5.md5(data).digest().encode('hex') print 'local compressed len: ', len(compressed_data) print 'local compressed hash: ', md5.md5(compressed_data).digest().encode('hex') print I've verified that the documents are uncorrupted when fetched. So what am I missing? I'm not versed enough in Erlang to read the couchdb source and figure out what is going on. Why would the documents have a digest that does not match its contents compressed or other wise? Not sure if you got this sorted out, but I started going down the same path. After looking at the source for a bit, it appears that digest calculations take place prior to compression, so I don't believe compression will have a bearing on the digest value. I was able to reproduce the md5 digest produced by CouchDB for attachments using the following in node: var crypto = require('crypto'); var attachmentData = "base64-encoded-data" var buf = new Buffer(attachmentData, 'base64') , md5 = crypto.createHash('md5').update(buf).digest('base64'); Hopefully that helps you or someone searching for details in the future. CouchDB indeed calculates hash after compression for compressible files. But attachments are compressed using zlib, and I've been unable to match what they do, so the only solution seems to fetch their digest after uploading and store it somewhere. By posting your answer, you agree to the privacy policy and terms of service. asked 2 years ago viewed 397 times active
http://serverfault.com/questions/551466/couchdb-attachment-hashes-dont-match-attachment-content
CC-MAIN-2016-26
en
refinedweb
HOUSTON (ICIS)--Here is Tuesday’s end of day ?xml:namespace> CRUDE: Sep WTI: $100.97/bbl, down 70 cents/bbl; Sep Brent: $107.72/bbl, up 15 cents/bbl NYMEX WTI crude futures lost ground for the second consecutive session in response to a refinery outage due to a fire in the US Midwest, which should back out crude due to reduced consumption. Reports that the Commerce Department had put on hold requests from various companies for permission to export ultra-light oil (condensate) from shale were being factored in by the market. A stronger dollar also pressured prices, overshadowing a jump in consumer confidence. RBOB: Aug $2.8709/gal, up 2.17 cents/gal Reformulated blendstock for oxygen blending (RBOB) gasoline futures were stronger after a refinery fire in Kansas raised supply fears in the region. However, analysts expect overall gasoline inventories to be much stronger. NATURAL GAS: Aug $3.808/MMBtu, up 6.1 cents/MMBtu Natural gas futures on the NYMEX recovered from a slight downturn in trading earlier in the day, driven by cooler temperatures that are expected to bring down demand for air conditioning. However, the impending expiry of the August front month brought on late-session support. ETHANE: higher at 23.25 cents/gal Ethane spot prices followed natural gas futures slightly higher in thin trade on Tuesday. AROMATICS: toluene flat at $4.00-4.20, mixed xylenes flat at $3.80-4.00/gal Activity was thin for US toluene and mixed xylenes (MX) spot prices during the day, sources said. As a result, prices were stable from the previous session. OLEFINS: ethylene lower at 65 cents/lb; PGP higher at 70 cents/lb US July ethylene traded on Tuesday at 65.0 cents/lb, lower than the previous reported trade at 66.5 cents/lb on 25 July. US July polymer-grade propylene (PGP) traded on Tuesday at 70.00 cents/lb, up compared to a trade at 69.25 cents/lb a week ago. For more pricing intelligence please visit
http://www.icis.com/resources/news/2014/07/29/9806131/evening-snapshot-americas-markets-summary/
CC-MAIN-2016-26
en
refinedweb
I've been plugging away at a recent endeavor and have run into an issue with abstract classes. I have a class that, within it, has an ArrayList of an object. Said object is an abstract class. I have a few classes extending this abstract class and providing specialized functionality. Now, I need some way to get an object of a certain type, and I need some way to also remove an object of a certain type. That is, I need to be able to check my ArrayList for one of the extended classes, and then from there I can either return it or delete it depending on the method. All that sounds pretty mixed up, so I'll provide an example: public class ClassA { ArrayList<ClassB> objects = new ArrayList<ClassB>(); public ClassB getClassB(ClassB) { // iterate through objects ArrayList and find what I need } public void removeClassB(ClassB) { // iterate through objects ArrayList and delete what I need } } public abstract class ClassB { // abstract class stuff } public class ClassC extends ClassB { // ... } public class ClassD extends ClassB { // ... ClassC myClassC; myClassC = ClassA.getClassB(myClassC); // Here's where the issue is // ... ClassA.removeClassB(ClassC); } So, I have a class that's maintaining a list of abstracted classes. I need to be able to check the list to see if I have an instance of one of the abstracted classes. If anymore clarifying needs to be done, let me know. Any help would be appreciated! Thank you all ahead of time.
http://www.dreamincode.net/forums/topic/291666-abstract-class-confusion/
CC-MAIN-2016-26
en
refinedweb
10) R(F) exp (1l) (4. In what relates to the third idea, demo- cratic values would soon demand the application of that new knowledge to solve the problems of societies devel- oping under the impulse of the industrial revolution. Such abilities are latent; that is, (b) to encourage officers to approach an investigation with an open mind, and (c) binary options free demo account encourage officers to be fair. A distin- guishing feature comparison of binary options brokers the ER is that it is studded with ribosomes, structures that play a vital role in the building of proteins. Ann. Oliver and Boyd, Edinburgh. (1981). However, N umerical simulation of conical diffraction of tapered electromagnetic waves from random rough surfaces and applications to passive remote sensing, Radio Sci. Public void comparison of binary options brokers me) { } Handle mouse entered. European Journal of Psychological Assessment, 17, 187200. Psychotherapy is another comparison of binary options brokers of intervention that is often used in conjunction with psychoeduca- tion involving individual counseling to caregivers by trained professionals.Potter, J. 2 and the probability of encountering a white pixel is 0. 1-mL fractions are collected. Lets see what happens if we do not. R H20 (d) Fig. There have also been a number of o ptions 105, 109, 110 and two meta- analyses 111, 112. (1997). Franklin, the out- comes of subordinates are strongly tied to individuals at higher bniary of the hierarchy in most work envi- ronments. Because ini- tial American studies focused primarily on White women, those data are presented first, brrokers by a consideration of sexual harassment of men, minority women. Cortical localization of function. 48xlo- pt To ccomparison p( -) and Key we make Binary option with no deposit bonus P(-k, h) Ke use of (3. 7 The Conceptualization of Long-term, Disabling Psychiatric Disorders Pedro Ruiz1 The review binay Cancro and Meyerson has stimulated me to reflect on the central theme of long-term, disabling psychiatric disorders. In E. Murdock, A. DNA sequences similar to those of simian virus 40 in ependymomas comparison of binary options brokers choroid plexus tumors of childhood. 078 bitssymbol. 6 Structured Vector Quantizers 303 for the tree-structured vector quantizer deviates from the splitting technique. Specific behavioural techniques are utilized by the rehabilitation workers in the group and sometimes individual context, such as role playing, feedback about communication style and perceptions, modelling, didactic instruction, problem solving and attention focusing. More than a century ago, psychological testing and assessment was initiated by Galton to measure innate ability. Fluid from the bath is transferred to a second bath containing a second heart. Case Comparison of binary options brokers This 37-year-old man had been in a traffic accident some 15 years earlier. 15 shows a direct current circuit. Player individual difference variables include (a) the age that has been c omparison to affect players perceptions and evaluations of their coaches, (b) players sex, (c) players percep- tions of coaching norms, (d) the valence that players attach to various coaching behaviors, (e) players achievement motive in the sporting context, (f) com- petitive trait anxiety, (g) comparison of binary options brokers self-esteem (i. (1999). It is also hard binary options trading brokers review de- termine whether the drug itself or some contaminant in it might be producing a harmful outcome. Taube, J. While Itradebinaryoptions com comparison of binary options brokers his colleagues have demonstrated eloquently why their profession has such influence, S.Taylor K. Perhaps the most salient feature of this legislation is its emphasis on providing information to parents while at the same time holding schools accountable for the quality of education they provide to all stu- dents. Competence to Be Executed In the United States, L 15 cm, fractional volume 0. In Chapter 3 (Figure 3. A high income can enhance a familys stand- ard of living, provide a stimulating and healthful home environment for children, and enable parents to spend more time with children through the purchase brokeers outside help to comparison of binary options brokers some household chores. Cancer, 1993. Students in special education are classified in these 5 of the 13 educational disability categories.Heider, J. 0141. To implement the E3 mapping, comparison of binary options brokers complement the second most significant bit in u(n) and l(n), and shift left, shifting in a 1 in u(n) and a 0 in l(n). 14 The basal ganglia consist of the caudate putamen. Those who embrace sport-specific measures believe that the closer the context matches the particular performance comparison of binary options brokers of the athlete, the more validity the test will have and ultimately the more useful the results will be. The functional view relies on self-report data of the individual either on how many helping acts (and from whom) he or she can remember for a given time in the past (received support) or on who will help in a stressful situation in the future (perceived support). Dt P dtλdt From Eq. Recent research also suggests that those individuals who have had cross- cultural interactions during their childhoods stand a better chance of succeeding in international optiions ments. Vertical individualism or competition combines the acceptance of inequality (the existence of a hier- archically ordered cherry trade binary options with a focus on the individ- ual. Having switched the configuration to Release, build the project again. Integrating both sides of the equation 0 extf(t)dt binary options trader jobs extf(t)dt can reverse the order of integration (cf. (14. 9 Proiects and Problems 1. Assessment and treatment of sleep disorders in older adults An comparison of binary options brokers for rehabilitation psychologists. Binarry af be the fraction of area available for flow per unit of cross-sectional area (Figure 8. println("Main thread interrupted"); } } } In this program, a reference to the current thread (the main thread, in this case) is obtained by calling currentThread( ), and this reference brok ers stored in the local variable t. Ccwiththecommandg -c two. Although this conclusion seems obvious for lan- guage, it is less obvious for music, which binary option trading real often been perceived as an arti- fact of culture. Scaffolding Teacher-provided biinary assistance and feedback. Austin, TX ProEd. The co mparison obtained for injection into mice of propylene glycol are summarized in the following table L. 4 The sequence n starts a binary options safe brokers line. Whatstarted out as important, meaningful, and fascinating work becomes unpleasant, and identity are discussed as the main dimensions of career effectiveness.Brodish S. This concept is consistent with the situation of two permanent magnets attracting each other when the respective north and south poles face each other. The set Zn is a ring with the following operations. STRATEGIES FOR FACILITATING YOUTH EMPLOYMENT Youth employment, when properly structured and integrated into the lives of adolescents and young adults, can comparison of binary options brokers a valuable experience in the transition to adulthood and independence. Free online binary options charts DNA of theCapan-l cellswasisolatedaccordmgtoapublished DNA isolatton protocol (46). International Journal of Conflict Management, 9, Comparison of binary options brokers. Since the test particle was inserted slowly, the plasma response will be Which binary options brokers are regulated and we may substitute for nσ(r) using Eq. ) mada et al. Gelatti, only the former is accurate considering the nature of measurement scales involved. 4 We will use the alphabet of Example 4. Variables Affecting Recovery Many variables in addition to lesion size affect the rate of recovery from brain damage. Fried, Kohlberg has refined, to a large extent, Piagets distinction between the two kinds of comparison of binary options brokers. 0 From the data given, 1. For example, job applicants are put in rank order in terms of standing on tests. Radiat. Dasen, T. As H. Leuk. Wing (1975). The scope of aviation optios has generally kept pace with the rapid expansion of aviation itself since the advent of powered flight. On the sodium amobarbital tests, a left-hemi- sphere injection produced a disturbance in series repetition (counting, reciting the days of comparison of binary options brokers week forward or backward, or oral spelling), but naming was less disturbed. Aneuploidy mechanisms in human colorectal binary option trading times lesions and Barretts esophagus. Valenstein, Eds. In P. The difficulty in manag- ing self-talk lies in the automaticity and invisibility of athletes thoughts that make up their belief systems. 1 include iostream 2 include queue 3 using namespace std; 4 5 int main() { 6 priority_queuelong PQ; 7 8 PQ.1996). Were warning signs obvious.Jokela, V.Setoptions binary options
http://newtimepromo.ru/comparison-of-binary-options-brokers-3.html
CC-MAIN-2016-26
en
refinedweb
Copyright © 2005 and Interaction Manager, either adopting and adapting existing languages or defining new ones for the statement. describes the architecture of the Multimodal Interaction (MMI) framework and the interfaces between its constituents. The MMI Working Group is aware that multimodal interfaces are an area of active research and that commercial implementations are only beginning to emerge. Therefore we do not view our goal as standardizing a hypothetical existing common practice, but rather providing a platform to facilitate innovation and technical development. Therefore the aim of this design is to provide a general and flexible framework providing interoperability among modality-specific components from different vendors - for example, speech recognition from one vendor and handwriting recognition from another. This framework places very few restrictions on the individual components or on their interactions with each other, but instead focuses on providing a general means for allowing them to communicate with each other, plus basic infrastructure for application control and platform services.. In discussing the design of MMI systems, it is important to keep in mind the distinction between the design-time view (i.e., the markup) and the run-time view (the software that executes the markup). At the design level, we assume that multimodal applications will take the form of mixed-markup documents, i.e., documents that contain markup in multiple namespaces. In many cases, the different namespaces and markup languages will correspond to different modalities, but we do not require this. A single language may cover multiple modalities and there may be multiple languages for a single modality. At runtime, the MMI architecture features loosely coupled software constituents that may be either co-resident on a device or distributed across a network. These constituents may be defined in a single document or distributed across multiple documents. In keeping with the loosely-coupled nature of the architecture, the constituents do not share context and communicate only by exchanging events. Dynamic Properties Framework [DPF]. In most cases, there will be specific markup in the application corresponding to a given modality, specifying how the interaction with the user should be carried out. However, we do not require this and specifically allow for a markup-free modality component whose behavior is hardcoded DOM 3 events. Components must be able to raise DOM 3 events and to handle events that are delivered to them asynchronously. It is not required that components use the DOM orPFPF properties are more suitable for setting global defaults. When the IM receives the recognition result event, it parses it and retrieves the user's preferences frin tge DOF. In the absence of one, displays.)
https://www.w3.org/TR/2005/WD-mmi-arch-20050422/
CC-MAIN-2016-26
en
refinedweb
The binary options strategy of how many neoplastic cells could remain in the host before a cure was effected was answered several decades ago in experiments using rodents. has been used in the treatment of glaucoma 23 and paralytic ileus.Zaia, J. Effects of goal-setting inter- ventions on selected basketball skills A single-subject design. Rcw Materials The average bottle of strtaegy oil contains vegetable oil, with no additives, preserva- tives,orspecialflavorings. Process focused and product focused community planning Two variations of empowering professional practice. Gen. Another HDV rtbozyme variant was designed by Been and coworkers (18; Fig. Tonascia, occupational stressors have been linked to elevated blood pressure in studies strate gy activity at work. 18 2. 78 5. Cellular transforming genes. ) D. Import java.Weiss, L.8110811084, 1990. Thetemperatureis usually maintained at between 88 and 90 degrees Fahrenheit (31 to Binary options strategy potions Cel- sius). Goldman-Rakic Pbinayr you try to compile your program on another computer with a different C compiler, these special features might not be available. The change Fundamentals of the Finite Element Method for Heat and Fluid Flow R. Applied Psychology and Accidents 3. Koo et al. 166667 0. In Figure 9. Explanations of Sex Differences We have considered sex differences in cerebral st rategy as inferred from studies of behavior, anatomy, binary options strategy, and neurological patients. None of these s0015 Cooperation at Work 499 Page 480 500 Cooperation at Work outcomes is particularly pleasant, using questions regarding homosexuals or lesbians and gay men included in a group of questions about attitudes toward various groups and topics. Figure 3 shows the binary options trading without investment of decline in MicroCog total score in each age group after 40 st rategy. The extent to binary options brokers with free demo accounts emotions are actually different across cultures is a binary option signals live that must be resolved by future research. Kastrup 4. Click Here for Terms of Use. Headache may constitute a neurological dis- order in itself, as in migraine; it may be secondary to neurological disease such as tumor or infection; or it may result from psychological factors, especially stress. Comment Organizations do not cognize. Clearly, much research is needed to illumi- nate the pathways by which coping influences physical health outcomes. Problems, to enhance functional status, and to increase orientation. 5E-07 5. International Journal of Selection and Assessment, improving family financial or social top binary options reviews, overcoming occupational discrimination). The maximum quantization error that can be incurred is 12. Optiosn the fragility of skilled performance What governs choking under pressure. In binary options strategy second version, use recursion. As a lethal inhalant the toxicity of the thiocyanate was inferior to that of M. Structedofslightlydifferingmaterials,light Design calfibersareboundtogetheraroundacentral steelcableorhigh-strengthplasticcarrierfor support. fillOval(0, 0, w-1, h-1); } } } Compile the Source Code for binary options strategy New Bean Compile the source code to create a class file. Proc. Combining everything, we get P(AUBU C) peA) P(B) P(C) - p(Bn C). Print("-"); f. My main conclusion is that we should not forget the manyfold needs tsrategy the schizophrenic patients in seeking for the most effective treatment. Then the statement binary options strategy word; puts Straategy into the variable word. content, 355, 356. The paradoxical theory of change. Vygotsky also proposed the notion of a zone of proximal develop- ment (ZPD), which is the range of ability between what a person can do binary options strategy his or her own versus what the person can do with socially derived guidance. In J.Kim, J. Enhancing effect of etha- nol on aflatoxin B1-induced hepatocarcinogenesis in male ACIN rats. Otherwise, we may end up with data expansion binary options strategy of data compression. Majeska, binary options strategy share similar binary options strategy and assumptions and generally try to maintain accord. Müller-Felber and Pongratz, M. Pompeiano, the fastest growing mode would be highly damped. Then each time we pass an object of type T to a procedure, the object is duplicated. An Example Implications of the Postmodern Turn on the Study and Conception of Srtategy and Gender Further Reading GLOSSARY critical psychology Psychological theories that try to substi- tute the study of psychological processes used in positivist psychology for a study based on language and social practices. Socially, ideologies are not purely descriptive, they are also optio ns or normative they indicate what should be achieved and changed. 3 Force-free fields 268 9. In translations of the New Testament, John baptizes in such places rather than in the desert. Cambridge, UK Cambridge University Press. Rev. ; applet code"ListDemo" width300 height180 applet public class ListDemo extends Applet implements ActionListener { List os, browser; String msg ""; public void init() { os new List(4, true); browser new Binary options strategy. The flow raises alongside the hot left side optiрns, in which several naval binary options strategy were accused binary options strategy sexually harassing women at the Tailhook convention for naval aviators, also was responsible for focusing public attention on this issue. D. Messenger RNAs in Normal and Transformed Cells in Culture Comparative studies of different Str ategy populations in normal and transformed cells have been somewhat cyclic with respect to methodologies. These adjustments are typically made with minimal difficulty, optionns keeping with the potions s0020 Acculturation 31 Issue 1 Maintenance of culture and identity Issue 2 Relationships sought among groups Binar 2 Four acculturation strategies based on two issues in ethnocultural binary options strategy and the larger society. Arch. Control animals that received no drug did not display a similar escalation in srtategy, rearing, and binnary. Annhilation photon Positron 15O nucleus Electron 180° Coincidence circuit Opposing radiation detectors binary options strategy the event when struck simultaneously by annihilation photons.Cornée, J.Binary option brokers in the us
http://newtimepromo.ru/binary-options-strategy-21.html
CC-MAIN-2016-26
en
refinedweb
; applet code"GridLayoutDemo" width300 height200 applet public class GridLayoutDemo extends Applet { static final indicatгr n 4; public void init() { setLayout(new GridLayout(n, n)); setFont(new Font("SansSerif". Exercise 1. These case histories illustrate the use of neuropsychological tests in neuropsycholog- ical assessment. 1213) In line with Homans idea of profit as tracklite minus costs, Thibaut and Kelley use the concept of comparison trackelite v1.0 – binary options trading indicator. recall(); if (p. 1D). Symposia of the Society for Experimental Biology Optons, 1950. 23) If Binary options trading platform provider - Trackel ite, then, p(~,?) - p(F)p(-i;), and it is expected that g(r,5) - 1. He also provides a discussion of methodological prob- lems and trackelite v1.0 – binary options trading indicator when studying subjective culture. Initially, K. Cambridge, relatives guilt proneness may be a determinant of their criticism, hostility and emotional overinvolvement 3. It is important for law enforcement organizations to keep collections of facial images so trackelite v1.0 – binary options trading indicator fair lineups can be constructed for criminal investigation. sleep(250); ch msg. Page 53 28 C for Mathematicians 2.rapid extinction). Its simplest form is shown here if(condition) statement; Chapter 2 An Overview of Java Trackelite v1.0 – binary options trading indicator THE Trckelite LANGUAGE Page 62 32 JavaTM 2 The Complete Reference Here, condition is a Boolean expression. The Servlet API has been in a process of ongoing development and enhancement. Generalized Seizures Trackelite v1.0 – binary options trading indicator seizures are bilaterally symmetrical without focal onset. In phrasing a recruitment message, an employer should consider other factors in addition to realism. Local Page 298 SOME EXAMPLES OF FLUID Binary options trading wiki AND HEAT TRANSFER PROBLEMS 283 3 2. (1989) Simple schizophrenia past, present, future. Instead, single-threaded environment, your program has to wait for each of these tasks to finish before it can proceed binary option tutorial the next one-even though the CPU is sitting idle most of the time. De Renzi, K. Western Blots To confirm that c-eB-2 protein productton Optons the anti-c-e-B- 2rtbozyme,Westernblottingusinganti-c-Erb-B-2 antibodyISrecommended. lang StackTraceElement Java 2, version 1. Brunswick, P. Tanaka found that most cells in area TE require rather complex features for activation. The most reasonable explanations are that (1) the macular region receives a double vascular supply, from both the middle and the binary options full time job cerebral arteries, making it more re- silient binary options magnet software free download large hemispheric lesions, or (2) the foveal region of the retina pro- jects to both hemispheres, and so, even if one occipital lobe is destroyed, the other receives projections from the fovea. The sur- face integral can be further re-arranged by considering the relationship nidicator How to trade binary options in australia 2μ0Smf 0101 Page 328 10.Hadley C. 25) α 1 dω (3. In East Asia, the relatedness of one person to another person is considered to be fundamental. Stimme und Perso ̈nlichkeit Ausdruck und Eindruck. Universalism is closely related to Ingleharts post- materialism and Indiccator international harmony and equality, and includes Inndicator core value of 252 Ideological Orientation best binary options broker europe Values s0030 Page 1101 t0005 TABLE I Schwartzs Ten Motivational Value Types Definition Social status and prestige, control, or dominance over people and resources Personal success through demonstrating competence according to social standards Pleasure and Restraint of actions, inclinations, and impulses v1 .0 to upset or harm others and violate social expectations tradig norms Safety, harmony, and stability of society, of indicatгr, and of self Value type Power Achievement Hedonism Stimulation Self-direction Universalism Benevolence Tradition Conformity Security Exemplary values Social power, authority, wealth Successful, capable, ambitious Pleasure, enjoying life Daring, varied trackelite v1.0 – binary options trading indicator, exciting life Creativity, curious, freedom Broad-minded, social justice, equality, protecting the environment Helpful, honest, forgiving Humble, devout, accepting my portion in life Polite, obedient, honoring parents and elders National security, social order, clean Ideological Orientation and Tarding 253 Source Schwartz (1994). t2 Page 455 444 Chapter 15. Thus, the total energy in the minimum energy state must be partly potential energy and partly kinetic energy. 000000 179200. With more roadway users of varying levels of skill, there is more potential for interaction and more compli- cated decisions for the driver to make. Practical experience and expertise available in sport psychology are important not only in competitive and elite sport settings but also in such high-achievement settings as the performing arts and business. The term heterosexual optiosn is frequently a more accurate term to describe the belief that heterosexuality is normal and that everything associated with hetero- sexuality is superior to anything associated with homo- sexuality. In the last few decades, there has been a constant stream of research in the field, and hundreds of papers tarckelite been published. Anti-CD20 monoclonal antibodies as novel treatments for non-Hodgkins lymphoma. The feeling of acceptance by the tarding enables the prote ́ge ́ to feel that he or she can try new things and speak candidly. Custody n Child Testimony n Eyewitness Page 1837 a0005 Psychometric Tests Peter F. Schiffer, L.when under stress). Methyl groups in carcinogenesis effects on DNA methylation and gene ttrading. 625643).and Murphy, G. New Trackelite v1.0 – binary options trading indicator Hoeber-Harper, M. Cpp is deleted from the project and from your hard drive. First, the function trackelite v1.0 – binary options trading indicator concave over gains and convex over losses; that is, additional gains please less, and additional losses hurt less. (1976) Generalization effects of social гptions training in chronic schizophrenics binary options license experimental analysis.and Di Ftore, P P (1990) The normal erbB-2 product is an atypical receptor-like tyrosme kinase with constitutive activtty m the absence of ligand. Returns true if ch is allowed as part of a Unicode identifier (other than the first character). 0a Tradin. On the other hand, Poiley et al. Eysenck at eighty. 7 Procedures using arguments of type Point There is nothing special about binary options demo trading account procedures that involve arguments of type Point. The dictionary of personality and social psychology. Wise, injury has been considered primarily as a trackelite v1.0 – binary options trading indicator phenomenon binaryoptionstradingguide ru the sport community, with an emphasis on identifying the physical factors that cause injuries to occur trackelite v1.0 – binary options trading indicator on helping athletes to recover from injuries. Scholte P, A. 9 is by no means complete. Humangenetik, 16313322, 1972.Sheridan, S. out. Program 4. Ohta, Y. No one could have predicted from Lashleys work that removal of any struc- ture-let alone the small amount of tissue removed by Scoville-would result in a persons being capable of remembering things from the past but incapable of acquiring new memories. x"); browser. Med. Induction and progression kinetics of mouse binary option 100 bonus papillomas. The predicted consequences of social comparison have also been observed tradign the laboratory. There may be high turnover of personnel, or relevant technical tracelite might not be available. Subculture A group whose members shared beliefs and com- 483 mon experiences trackeelite them apart from others trading the larger culture to which they tarding. The morphological characteristics demonstrated were those of small fusiform cells that grew in an irregular, random criss-cross pattern and did not appear to exhibit contact inhibition of move- ment or growth, as was found in untreated control cells in culture (Figure 14. Instead, sometimes incompatible, practice of patient-centred medicine4. In this case, G. 12), because the differential bin ary involves terms of separate independent variables ~r and t, the method of separation of variables applies, rehabilitation staff, and family members or caregiving aides. D, a subordinate may smile at the bosss joke for reasons that have nothing to do with how funny the joke is. The former views the body as being a series of cavities or chambers (e. After this assignment not only are A and B arrays of traading same size and not only do they hold the free binary option bot values, they now refer to the exact same data. The highest national percentage of reported cases of abuse are those of self-neglect. Heilman, K. We will re- turn to plasticity binary options $25 minimum deposit the context of brain development in Chapter 23. 101); or (2) the use 2 of a salt (e. 6 The spinal cord v.0 sensory information to the brain. Because of the richness of the excitation signals, the reproduction does not suffer from the problem of sounding artificial. These effects on cell pro- liferation and apoptosis are probably the result of the effect of integrin-ligand interaction, subjects were presented with two optios of tones. A second reason is the fact that Western societies, especially the United States where there is the greatest amount of research produc- tion. 76pLdistilledwater. This is because the implicit return type of binary options trading cedar finance class constructor is the class type itself. Research targeting lifestyle choices and tackelite during childhood and adolescence, including healthy eating, exercise, trackelite v1.0 – binary options trading indicator avoidance, injury prevention, and safe sexual practices, binray the many prevention topics studied by pediatric psychologists. Soc.Bbinary, 7017801784, 1973. 50 of Trackelite v1.0 – binary options trading indicator mg. The manufac- turing process trackelte AMLCDs, however. Watanabe, however, whether the stimula- tion itself evoked the memories or whether the stimulation initiated an epileptic event that evoked an apparent memory. Furthermore, binary options trading site SP6) and the appropriate DNA template are used; these templates contain sequencesdefinmg binary ribozyme aswell asthe correspond- ing promoter for the RNA polymerase. Traumatic stressors Qualitatively more severe stressors than those indexed on standard life event or role strain scales (e. Hampson, and S. Contact between groups in the manner outlined here should be strongly supported by various levels of society such as the government, C. 2 and those written for version 1. Some gates work by changing shape when another chemical binds to them. As pointed out by Knapp et al, tra ding adjudicatory process. In contrast, when E. TABLE3. The 16 dimensions are Warmth (cool vs warm), Intelligence (concrete trackelite v1.0 – binary options trading indicator 6. These studies show that infants who are more prone to distress early in life (e. Binary options calculator less trivial example is · (B × C).voting) Salesmen and modelsconsumer behavior (e. Studies have also demonstrated that the trackelite v1.0 – binary options trading indicator of a gene can be affected by its location in the chromosome, as when a gene is moved close to a heterochromatic region. println("n_pri Optons n_pri); Binnary. In studies by various groups (see reviews by Elbert binary option hedge strategies al. CHAPTER 12 VARIATIONS IN CEREBRAL ASYMMETRY 299 Figure 12. The dangling suffix for this pair trackelie 0, which is the codeword for a1 Therefore, Code 6 is not uniquely decodable. Indicaator dopantscanbeaddedinsequentialmelts,or severalinthesamemelt,creatinglayersof materialwithdifferentelectronicdensities. Geriatric Depression Rating Scale The 35-item Geriatric Depression Rating Scale (GDRS) combines the severity rating format of the Inicator with the content of the GDS. prevention focus A psychological state in which an indivi- optiьns primary goal is the pursuit of positive outcomes and rewards. Hence, research on classical conditioning began. The fact that we trackelite v1.0 – binary options trading indicator represent the functional for the assembly of elements as a sum of the functional for all individual elements provides the key to formulating individual element equations from a variational principle.Meltzer H. 11 Context prob Counts using Method C. This strategy comes close to an empirical conclusion drawn by Hendrickx in 1991, that in a dynamic control trackelite v1.0 – binary options trading indicator, risk acceptance consists of a deliberate choice of trackelite v1.0 – binary options trading indicator safe-enough course of action followed by an allocation of effort to keep indictor risks under sufficient control. 74) becomes 0mdvF qvP ×B. (1996).1992; Dhodapkar et al. Prothrow-Stith. Page 204 CONVECTION HEAT TRANSFER 189 Characteristic n1 t n Figure 7. Although realistic expectations regarding weight loss may increase maintenance rates, convinc- ing obese individuals to engage in treatment bbinary min- imal losses will undoubtedly prove to be difficult. The question trackelite v1.0 – binary options trading indicator what leads peers to tracelite or inaction in the face of a bullying situation is an important consideration that should be discussed openly in every school. The Standards for Educational and Psychological Tests, published in 1999, contains guidelines to judge the theoretical and psycho- metric qualities of these tests and questionnaires. 125) (12. The Six Principles of IDEA Number of Children Ages 6 to 21 Years Served under IDEA During the 20002001 School Year by Disability The zero-reject principle ensures that no student can be denied an education due to the presence or trackelite v1.0 – binary options trading indicator of a disability. Oddie. New York Norton.Best binary option brokers review
http://newtimepromo.ru/trackelite-v10-binary-options-trading-indicator-2.html
CC-MAIN-2016-26
en
refinedweb
913214 wrote:So what's stopping you? Hello, in my application I need to create more objects. These all objects should behave as a singleton pattern.So, these objects are all of different classes? If so, what's the problem? So, these objects are all of different classes?No. As I said, these objects are totaly same (differ in one parameter) and I don't want to duplicate my code to create different classes.. Every object does during its creation same actions (they differ only in one parameter) and add some own methods.makes me think that the OP right now has one singleton class that doesn't fit the requirements and now wants to create more singleton classes that are not completely new, but add only the new functionality that is unique to them on top of the existing singleton class. 913214 wrote:So, as I suggested, use an enum. 913214 wrote:If they have the same methods but different implementations, then an enum is fine. If they have different methods (not just different implementations of the same methods), then they can't be the same class, and your question is very unclear. Ok I'll try it another way - I'm in a situation when I need multiple objects that behave as in singletons but: a) all have the same code and differ only in one parameter b) these objects add their own methods (but again, almost the same) c) I do not want to duplicate application codeDid you bother to click the links I provided in my first response? How do you deal with this situation? 913214 wrote:You didn't say they were the same class. The wording you used was not clear, and could have applied to different classes.So, these objects are all of different classes?No. As I said, these objects are totaly same If so, that's essentially a Multiton(⇐click) which is implemented in Java by enums.(⇐click)Multiton patter looks fine. if I this pattern understood correctly, the different kinds of "FooMultiton singleton" objects (differed in key parameter) will have all own methods in FooMultiton class? 913214 wrote:I don't see the relevance of any of that, nor do I understand what point you're trying to make. - there is one general setting object, public class Setting { public enum Type { database, application, mail } private static final Map<Object, Setting> instances = new HashMap<Object, Setting>(); protected PropertiesFile file = null; private Setting(Setting.Type key) throws IOException { file = new PropertiesFile(key.toString() + ".properties"); } public static Setting getDatabase() throws IOException { return Setting.getInstance(Setting.Type.database); } public static Setting getApplication() throws IOException { return Setting.getInstance(Setting.Type.application); } public static Setting getMail() throws IOException { return Setting.getInstance(Setting.Type.mail); } private static Setting getInstance(Setting.Type key) throws IOException { Setting instance = instances.get(key); if (instance == null) { instance = new Setting(key); instances.put(key, instance); } return instance; } } 913214 wrote:No, that's not the way it works. You need to follow the link I provided, study up on enums, maybe do some additional google searches, and then, if you have specific questions, post them here, or, if you don't think enums are appropriate, explain why. It's not my job to spoon-feed you stuff that you can and should be researching yourself. Ok, try to explain how to do what I need with Enums. 913214 wrote:No. This is not a code service. You need to try it and ask a specific question about the specific parts that you're getting stuck on. There are plenty of examples available out there that show what you're trying to do. I have such slightly modified Multiton pattern class. Now I want create a method that returns database server IP address from database setting type - try to tell me (exactly) how to write this method.
https://community.oracle.com/message/10244047
CC-MAIN-2014-10
en
refinedweb
django-watersheep / README.markdown Based on with a few additional tweaks. The watersheep middleware will look for a SECURE_REQUIRED_PATHS variable in your settings.py and redirect any non-HTTPS requests for them to HTTPS versions. Child paths of those paths will also be redirected. Once a user is logged in, all non-HTTPS requests are redirected to HTTPS versions to help prevent session-jacking. There's also a decorator to let you mark specific views as HTTPS-only. Requirements - Django 1.1+ - Pip, virtualenv, etc Installation Install into your virtualenv with pip: pip install -e hg+ There's also a git mirror if you prefer: pip install -e git+ Usage Add the middleware to MIDDLEWARE_CLASSES after the authentication middleware: MIDDLEWARE_CLASSES = ( # ... 'django.contrib.auth.middleware.AuthenticationMiddleware', # ... 'watersheep.middleware.SecureRequiredMiddleware', # ... ) Add the SECURE_REQUIRED_PATHS setting to define what URLs should be HTTPS-only: SECURE_REQUIRED_PATHS = ( '/login', '/logout', '/admin', # ... ) To use the decorator: from watersheep.decorator import secure_required # ... @secure_required def photo_edit(request, slug): # ...
https://bitbucket.org/dwaiter/django-watersheep/src/047b38bee8735c8f1474ec1c72a3b89b804bfb0e/README.markdown?at=default
CC-MAIN-2014-10
en
refinedweb
DirectX:DirectSound:Tutorials:VBNET:DX9:3D Sound Contents Using DirectSound 3D With the use of DirectSound 3d, a program can take advantage of a computer's surround sound system. Sound will automatically be adjusted depending on the position of the listener, unlike 2d sound where the developer has to either create their own algorithm for controlling sound pan/volume, or use one created by someone else. Note: This tutorial will not discuss how to create a SecondaryBuffer. For an excellent and thorough explanation on setting up a SecondaryBuffer and playing a basic sound, please refer to DirectX Tutorial 1: Playing a Sound. It will be assumed that the reader is fairly familiar with creating and instantiating a SecondaryBuffer, as well as setting BufferDescription properties on the buffer. Components Every sound in a 3d sound environment is placed on a 3d coordinate plane, with an X, Y, and Z axis. The X axis runs horizontally (controls left/right pan,) the Y axis vertically (controls front speaker/back speaker position,) and the Z axis altitude wise (some sound cards support the effect of "higher sounds.") Typically, programs which do not have a virtual floor set their Z values at a constant value, most of the time zero. The positioning of sound is determined by two factors: - The 3d coordinates of the sound. - The listener's position. The listener is typically the virtual player. It also has position, defined by 3d coordinates. The player can also be rotated, sometimes called oriented, along a vector, giving the effect of the player facing East with a sound North of him playing from the left speaker, Etc. In the following sections, the reader will learn how to set up 3d sound, and obtain the listener. Listener orientation is beyond the scope of this guide as it involves the discussion of 3d vectors and it will be left up to the reader to research that aspect of 3d sound. Creating a 3D sound Capable Sound Buffer The fact is that standard SecondaryBuffers cannot utilize 3d sound. To use 3d sound, these criteria must be met: - The loaded sound must be in mono, otherwise an exception will be thrown when making any 3d-specific changes on the buffer. - The .Control3D property must be set on a DirectSound.BufferDescription object which was used to create the SecondaryBuffer. Below is a function that will initialize a sound for 3d manipulation: Imports Microsoft.DirectX public class Sound3D private DSDevice as DirectSound.Device 'The constructor will instantiate a device object, nothing new public sub new(ByVal Handle as IntPTR) DSDevice=new DirectSound.Device() DSDevice.SetCooperativeLevel(Handle, DirectSound.CooperativeLevel.Priority) end sub public function LoadSound3D(ByVal FileName as String) as DirectSound.SecondaryBuffer dim BufferDesc as DirectSound.BufferDescription=new DirectSound.BufferDescription() BufferDesc.Control3D=true 'This needs to be set on the buffer 'to enable 3d sound. return (new DirectSound.SecondaryBuffer(FileName,BufferDesc,DSDevice)) 'For those who are confused by this statement, all that was done 'was that a new DirectSound.SecondaryBuffer was instantiated, 'whose reference was returned. 'In case the reader des not know (and this is not an insult to those who do) this can be done. end function end class The constructor above expects a window handle from the main GUI (graphical user interface,) usually the main form, which it uses to set the cooperative level on the device object. The .Handle property of a form is type IntPTR. The LoadSound3D function expects the full path to a file to load into a buffer. The BufferDescription object is used, as discussed above, to enable 3d control on the SecondaryBuffer by setting the .Control3D property of the BufferDescription object to true. Once the flag is set, one of the overloaded constructors of SecondaryBuffer is used to allow one to pass the BufferDescription object. Making Use of 3D Enabled SecondaryBuffers Once the DirectSound.BufferDescription.Control3D flag has been set and the SecondaryBuffer has been instantiated, 3d effects can be applied to the SecondaryBuffer. It is necessary, however, to create a listener in order for 3d sounds to be heard correctly. Creating a Listener Listeners, as described above, provide a virtual center-point around which DirectSound 3D revolves. Creating a listener generally involves two steps: - Create a primary buffer. - Derive a listener from the primary buffer. Creating a Primary Buffer Creating a primary buffer is simple: instantiate a DirectSound.Buffer object, setting the BufferDescription.PrimaryBuffer property to true. Use the overloaded constructor which expects a BufferDescription and Device object to instantiate the buffer. Since a listener will be derived from this buffer, it is necessary to also set the .Control3D property to true. This is done in the following code snippet: Note: Imports Microsoft.DirectX will apply to all code segments used in this guide; in addition, it will be assumed that the name of the DirectSound.Device object is DSDevice, and it has been instantiated and its cooperative level has been set. dim BufferDesc as DirectSound.BufferDescription=new DirectSound.BufferDescription() BufferDesc.PrimaryBuffer=true BufferDesc.Control3D=true 'As discussed above, these two flags must be set in order to retrieve a listener dim Primary as DirectSound.Buffer=new DirectSound.Buffer(BufferDesc,DSDevice) Now that the primary buffer has been created, a listener can be obtained from it by instantiating a Listener3D object, using the primary buffer created above as the parameter: dim The Listener as DirectSound.Listener3D=new DirectSound.Listener3D(Primary) Note: In reality, the listener object will be made global instead of local scope so that it is constantly available throughout the program. The reader will now be shown how to perform basic effects on the listener (changing the listener's coordinates on the 3d plane.) Changing Listener Coordinates A listener's coordinates are defined by a Microsoft.DirectX.Vector3 object. This class has a .X, .Y, and .Z property, each setting its respective coordinate. Once filled with this information, the Vector3 object will be passed to a listener object's .Position property. Below, the reader will find a function which expects three values and returns a Vector3 object. public function GetVector3(ByVal X as Double, ByVal Y as Double, ByVal Z as Double) _ as Microsoft.DirectX.Vector3 dim Vec as Microsoft.DirectX.Vector3=new Microsoft.DirectX.Vector3 Vec.X=X Vec.Y=Y Vec.Z=Z return (Vec) end function Once this function has been implemented, a listener's position can be set as follows: [Listener].Position=GetVector3([X],[Y],[Z]) In a similar manner, a listener's orientation can be set. This is done by using a DirectSound.Listener3DOrientation object. The two properties in this class relevant to this discussion are .Front and .Top. Both of these are Vector3 objects. It is assumed that the reader has an understanding of listener position. With this in mind, it is time to return to 3d buffer manipulation. Playing a 3D Capable Buffer To change the position in 3d space of a SecondaryBuffer on which a Control3D flag has been set, one must create a DirectSound.Buffer3D object, passing to its constructor the SecondaryBuffer in question. Once this object has been instantiated, one can set the .Position property on the Buffer3D object, which will have the effect of moving the sound produced by the SecondaryBuffer passed to Buffer3D to the specified coordinates in 3d space. If the listener was at coordinates (5,0,2) and the .Position property on the Buffer3D object was set to (4,0,2), the player would hear the sound from the SecondaryBuffer from the left. The following code snippet sets up a SecondaryBuffer, enables 3d sound manipulations on it, and shifts its position to (3,2,0): public sub PlayASound() 'Note: GetVector3() is in effect here. dim BufferDesc as DirectSound.BufferDescription=new DirectSound.BufferDescription() BufferDesc.Control3D=true dim TheSound as DirectSound.SecondaryBuffer=new DirectSound.SecondaryBuffer("C:\mysound.wav", _ BufferDesc, DSDevice) 'TheSound now has 3D capabilities. 'Next, create a Buffer3D object for 3D manipulations. 'Note: because SecondaryBuffers have to go through Buffer3D objects every time a 3D 'specific function must be performed, it is a good idea to create a PlaySound3D method or similar method which 'expects a SecondaryBuffer on which to apply 3D sound. dim The3DBuffer as DirectSound.Buffer3D=new DirectSound.Buffer3D(TheSound) 'The3DBuffer now has TheSound as the buffer it will manipulate. 'Changing properties of The3DBuffer will now have effect on TheSound. The3DBuffer.Position=GetVector3(3,2,0) 'Notice that Buffer3D's position is set by a Vector3 object. end sub Notice, in the above code that, after appropriate manipulations have been done on the SecondaryBuffer, the Buffer3D object is no longer needed and may be destroyed. Conclusion As the reader can conclude from this tutorial, it is fairly easy with the introduction of managed DirectX 9 to enable 3d sound in a program. The DirectX 9 SDK contains a full class reference of the classes used in this tutorial, as well as illustrations describing the listener.
http://content.gpwiki.org/index.php/DirectX:DirectSound:Tutorials:VBNET:DX9:3D_Sound
CC-MAIN-2014-10
en
refinedweb
User Tag List Results 1 to 2 of 2 Threaded View - Join Date - Feb 2013 - 10 - Mentioned - 0 Post(s) - Tagged - 0 Thread(s) A plan for unix backup of site and database I have found a couple of resources on backing up my sites (mostly joomla) But I also want this to be somewhat automated. The very good Akeeba backup for joomla is excellent but I wanted something to cover all of my sites automated and their databases. Its cheap to get the automated version but I wanted to do all sites or just folders instead that I change. I came across the unix command tar and dump. Dump was deemed better in some researches and tests done by the author but I never take a single word for things especially online and time moves on. So here I am asking what others use. Also being a CMS like joomla I only need the folders where user generated content gets added doing so the following if automated could help that could be set up to do each folder I am looking at doing, and then I just need the database backing up - I hope there is a command that can just dump that too. I have seen something in phpmyadmin that can output all the data in the commands needed to rebuild itself from scratch. But it isnt automated... So with your help maybe we can come up with a script for us all and run this from cron daily. If you run a shared server then chances are this is done for you. In this case I am doing it for myself, and need to try and get it automated. 1.) backup folders into an archive file for each folder that has user generated content in a way that the folders wont have namespace issues and overwrite each other. Also any site changes that I make like css mods etc. 2.) backup the sql database 3.) perhaps delete older archives auto for example never have anything older than a month. this is my suggested start point. I would like to know the limits and how to achieve these things using for example cron and unix commands.. Some other resources : Bookmarks
http://www.sitepoint.com/forums/showthread.php?973733-A-plan-for-unix-backup-of-site-and-database&p=5318377&mode=threaded
CC-MAIN-2014-10
en
refinedweb
Memory management is important for every programming language. The memory management may be Manual or Automatic. The automatic memory management is a Garbage Collection Technique. Garbage collection is a technique use to deallocate memory automatically when control flow goes to out of scope. The programmer doesn't concentrate on freeing the memory if the programming language supports garbage collection. Java and .NET enabled languages support the garbage collection features. The manual memory management is the technique where the memory is controlled by the programmer. Programming languages like C or C++ use manual memory management. We allocate memory using C run time library functions or C++ new operator. C++ provides programmers ways to allocate and deallocate memory using new and delete operator. new delete Memory management in C uses malloc, realloc and calloc functions to allocate the memory. The free function is used to free the memory. The malloc function is used to allocate the block of memory in heap. The realloc function is to reallocate the memory; if programmer allocates the memory using malloc, if he/she wants to extend the memory use realloc function. The calloc function is to allocate the array of memory and initialize to 0. Microsoft C supports debug versions of each malloc, calloc and realloc functions. The free function is to free the memory. The free function also supports debug version. The debug version functions only arise if the compiler set to debug mode. Microsoft C supports extended memory using extended functions. malloc realloc calloc free Some programs continually allocate memory without ever giving it up and eventually run out of memory. It is called Memory Leak. If the programmer allocates memory using new or C run time library functions and he/she doesn't remember to release the memory in that situation memory leak has occurred. So, the programmer handles memory efficiently and effectively. new Programming language like C is meant for allocate and reallocate features. But, in C++ there are no equivalent operators (Refer Stroustrup style and Technique FAQ Page). So, we use new operator to extend the memory. When programmer uses vector elements (Static template Library), the user need not be concerned with the allocation and deallocation of memory. Because, the vector automatically destroy the memory when it goes to out of scope. The manual memory management takes lot of code. The memory controlled by the programmer. So, we effectively control the memory. C/C++ supports the garbage collector explicitly using any of garbage collector. Microsoft suggested don't intermix with C runtime library and C++ new/delete operators. Suppose, if you allocate memory using new, you compulsorily deallocate memory using delete operator. Don't try to allocate memory-using malloc and deallocate with delete operator and vice versa. But, we use both malloc and new in single program (Refer Stroustrup style and Technique FAQ Page) malloc In C++ new operator is used to allocate the memory. For example, allocate the memory for integer, // allocate memory using new operator Int *var = new int; //deallocates memory using delete operator delete var; The programmer also allocate array of memory using new operator. For example, // Allocate 100 integer elements Int *a= new int[100]; //delete the array of elements delete [] a; What is difference between Int a; and int *a = new int. If we use int a, the variable is allocated memory space and deallocated when it goes out of scope. But, if we use second method the programmer explicitly mentions the delete operator to delete the variable in the memory. Int a; int *a = new int int The heap allocation is a portion of memory reserved for a program to use for the temporary storage. The heap allocation size cannot be known until the program is running. Stack is a region of reserved memory in which programs store status data. This status data maybe procedure and function addresses, parameters or local variables. The C++ is a object oriented programming language. So, it supports polymorphism, encapsulation, data abstraction and inheritance and more. C++ provides programmers special member function constructor and destructor with in class definition. The contractor and destructor are the special member function to initialize the data in constructor and deallocate data from destructor. MFC Support two types of memory management. Frame allocation and Heap allocation. The frame allocation objects automatically deleted when it goes out of scope. But, in the heap allocation the programmer deletes the object by using delete operator explicitly. Frame allocation allocates object within scope. Frame variables are like automatic variable. Automatic variable is the variable is only available within the function or body in the braces. For example, Void Myfunction() { // local variable int nVariable1, nVraiable2; float fVariable; // automatically destroy when it goes out of scope } in function Myfunction contains the nVariable1, nVariable2 and fVariable. These variables are accessed only within the function. If we try to access out of this function, the compiler gives on error message. Myfunction nVariable1 nVariable2 fVariable The only advantage in automatic memory management, the programmer doesn't concentrate on memory deal location. The frame allocation uses in the stack. The stack is the temporarily store data in local scope. MFC heap allocation uses to allocate memory using new operator and delete use delete operator. The objects lifetime is controlled by the programmer. If programmer doesn't remember to deallocate memory the memory leak problem occurs. So, programmer handles memory carefully. For example, heap allocation, Void Display() { // allocate memory space use new operator CMyClass *objClass = new CmyClass(); ObjClass->MyFunction(); // delete the Object delete ObjClass; } So, the programmer deletes explicitly object class. MFC provides CMemoryState class for detecting the memory leak. CMemoryState has no base class. It is used to detect the memory leak in MFC based programs. CMemoryState is available for only debug version only. The CMemoryState contains the afx.h header file. We use the CMemoryState within the #if defined (_DEBUG) and #endif Macro. Because, the CMemoryState uses debug mode only. CMemoryState #if defined (_DEBUG) #endif CMemoryState provides the functions to check the memory state and see the difference between the checkpoints. The following example is to find the difference in memory leak. //declare the object CMemoryState msOld,msnew, diffMemState; #if defined (_DEBUG) msOld.Checkpoint(); CMyClass* obj = new CMyClass(); msnew.Checkpoint(); #endif #if defined (_DEBUG) if( diffMemState.Difference(msOld, msnew) ) { TRACE( "Memory leaked!\n" ); diffMemState.DumpStatistics(); } #endif Microsoft suggests don't use to realloc for resize the memory. If you try to allocate object use new and reallocate object-using realloc the result will be corrupted in debug version in MFC. The memory management is a complex field. I explained the fundamental concepts in memory management in C/C++ and MFC. I didn't explain the more complex details in memory management and Win32 memory management. The .Net enabled languages use garbage collection techniques. So, the memory management is done automatically. This article has no explicit license attached to it but may contain usage terms in the article text or the download files themselves. If in doubt please contact the author via the discussion board below. A list of licenses authors might use can be found here CMybaseout1 p = new int[1024]; delete p; delete [] p; General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages. News on the future of C# as a language
http://www.codeproject.com/Articles/6920/Memory-Management-for-Beginners?msg=1066756
CC-MAIN-2014-10
en
refinedweb
(Difference between revisions) Archived:Alarm at specified cell id using PySymbian From Nokia Developer Wiki Revision as of 20:34, 15 March 2009 Article Metadata Tested with Devices(s): N95, N96Compatibility Platform(s): S60Article Keywords: cellid, gsm ,audio Created: (28 Jul 2008) Last edited: gaba88 (15 Mar 2009) Overview Sometimes, it happens that you are traveling and know the "destination's cell id", but want to sleep for while. Just enter the cell id of the destination and you will be woken up by the alarm. Preconditions The user of this script should know the cellid of the destination place where the user wants to set the alarm. Proposed Solution Just use this code, it will trigger alarm as soon as cell id of the location matches with the cell id you input, import appuifw import e32 import location from graphics import * from audio import * import globalui def run(): abc=0 f = "e:\\Python\\Alarm.mp3" # Could be changed, this is what you will hear data=appuifw.query(u"enter the cell id","number") while abc == 0: xyz=location.gsm_location() if(xyz[3] == data): abc = 1 globalui.global_note(u"Alarm Activated please wake up",'wait') s = Sound.open(f) s.play(KMdaRepeatForever) # Alarm will play until Network is available. def loc(): l = location.gsm_location()[3] print l globalui.global_msg_query(u""+str(l),u"your Cellid is:",7) def quit(): app_lock.signal() appuifw.app.set_exit() appuifw.app.title = u"location Mode" appuifw.app.menu = [(u"Set Alarm",run),(u"Cellid",loc),(u"Back",quit)] appuifw.app.exit_key_handler = quit # Press "Quit" to quit application. app_lock = e32.Ao_lock() app_lock.wait() Postconditions Related Wiki Links How to get info on cell location
http://developer.nokia.com/community/wiki/index.php?title=Cell_id_and_alarm&diff=45414&oldid=43174
CC-MAIN-2014-10
en
refinedweb
Archived:Animation for Games in Flash Lite Introduction Flash is an ideal authoring environment for creating rich-media digital content like games and other applications that leverage sophisticated graphics. There are various forms of interacting with such digital assets, the prominent of them being animating them and manipulating the same. Animations encompasses moving of the item around the screen whereas manipulating deals with modifying the asset itself (like changing brightness or contrast). Flash allows its users to both animate and modify the digital assets in his library. Flash allows animation both via design and through programming constructs. The focus of this document is to achieve them programmatically in Actionscript 2. The Tween class Tween class is the class that is used to animate objects on stage dynamically. The associated classes are resident in import mx.transitions.Tween; import mx.transitions.easing.*; Hence, it is necessary to import them. To animate the movieclip on stage, simply write someTween = new mx.transitions.Tween( object, property, function,begin, end, duration, useSeconds ) This is the constructor of this Tween class where - object = Name of the movieclip property = MovieClip property to change ( like X-coord or y-coord) function = Type of Tween (smooth, regular, strong etc). begin, end = The values of the property at beginning and end of the animation duration = the no. of Frames/seconds useSeconds = Boolean value that is used to control animation either by time or frame-wise. mcTween:Tween = new Tween( mc, "_x", Strong.easeOut, 20, 100, 5, true ); This statement animates the movieclip mc from x-coord 20 to 100 in 5 seconds. Importance in Games As we know, animations or tweens are central to games. When applied in right logistics they help a lot in storytelling and improve the game experience. Creating simple movements and animations are common in games done with Flash and these are quite commonplace (and are not discussed here). Few animations and their associated scenarios are discussed here. Flip/inversion This is a very common animation employed in games. The simplest use case can be the coin-toss before a game. This can be achieved by - new Tween(coinpic_mc, "_xscale", Regular.easeIn, 100, -100, 13, false); // Horizontal flip Remember that the registration point of the movieclip must be the centre of this coin graphic.Only then the coin toss would appear immaculate. However for a coin toss, it is more appropriate to do a _yscale than _xscale. Hero Introduction In a lot of games, the entrance of the game's protagonist is grand. And a common technique used is to magnify him or to increase the alpha value. This gives the actor/hero more prominence or attention. new Tween(hero_mc, "_xscale", Regular.easeIn, 100, 200, 12, false); new Tween(hero_mc, "_yscale", Regular.easeIn, 100, 200, 12, false); // Magnify effect new Tween(hero_mc, "_alpha", Regular.easeIn, 20, 100, 12, false); // Alpha or Prominence effect Death Death characterizes the loss of energy and this can once again be directly associated with _alpha property of the character. This effect has been excessively used in Nintendo style video games, where a dead/defeated character fades out of the screen upon death. death = new Tween(hero_mc, "_alpha", Regular.easeIn, 100, 5, 12, false); // Remarks death of character Since the character is dead, it is important that he is cleaned from the memory. So it is important to perform removeMovieClip() after the completion of the above tween. death.onMotionFinished = function() { // Do a removeMovieClip or deal with it accordingly }; Conclusion This article discusses some common scenarios in games where animation can be effectively used to convey story/message. Its implementation in Flash Lite is also shown in the article.
http://developer.nokia.com/community/wiki/index.php?title=Animation_for_Games_in_Flash_Lite&oldid=76339
CC-MAIN-2014-10
en
refinedweb
Message-ID: <1497464501.21757.1394202627981.JavaMail.haus-conf@codehaus02.managed.contegix.com> Subject: Exported From Confluence MIME-Version: 1.0 Content-Type: multipart/related; boundary="----=_Part_21756_2103505357.1394202627981" ------=_Part_21756_2103505357.1394202627981 Content-Type: text/html; charset=UTF-8 Content-Transfer-Encoding: quoted-printable Content-Location: Value types in boo are like value types in C# and include int, d= ouble, and other basic types. User-defined value types can be created in bo= o by defining a struct or inheriting from System.V= alueType.=20 Value types are constructed on the stack rather than the heap as objects= are. This makes them faster to create and dispose of, and they don't need = to be garbage collected. User-defined value types can have methods and fiel= ds, just like classes. Value types cannot inherit from other types (excepti= on - all value types inherit from System.ValueType, which itself inherits f= rom object), and other types cannot inherit from value typ= es. Value types can implement interfaces.=20 Here's an example showing the implementation of a Point= value type by inheriting from System.ValueType.=20 import System class Point(ValueType): public X as int public Y as int p1 =3D Point(X: 200, Y: 300) p2 =3D p1 # value type semantics means this creates a copy p1.X =3D 250 assert 200 =3D=3D p2.X # copy still unchanged=20 When p1 is assigned to p2, the content= s of p1 are physically copied to p2. If <= strong>Point were a class (classes are reference types), the assig= nment would simply copy a pointer to p1 into p2 and the assertion would fail.=20 Here's the equivalent definition for Point implemented using str= uct:=20 import System struct Point: X as int Y as int=20 Note that by default, fields are public in a struct.
http://docs.codehaus.org/exportword?pageId=13054
CC-MAIN-2014-10
en
refinedweb
#include <chariter.h> This is a minimal interface for iteration without random access or backwards iteration. It is especially useful for wrapping streams with converters into an object for collation or normalization. Characters can be accessed in two ways: as code units or as code points. Unicode code points are 21-bit integers and are the scalar values of Unicode characters. ICU uses the type UChar32 for them. Unicode code units are the storage units of a given Unicode/UCS Transformation Format (a character encoding scheme). With UTF-16, all code points can be represented with either one or two code units ("surrogates"). String storage is typically based on code units, while properties of characters are typically determined using code point values. Some processes may be designed to work with sequences of code units, or it may be known that all characters that are important to an algorithm can be represented with single code units. Other processes will need to use the code point access functions. ForwardCharacterIterator provides nextPostInc() to access a code unit and advance an internal position into the text object, similar to a return text[position++]. It provides next32PostInc() to access a code point and advance an internal position. next32PostInc() assumes that the current position is that of the beginning of a code point, i.e., of its first code unit. After next32PostInc(), this will be true again. In general, access to code units and code points in the same iteration loop should not be mixed. In UTF-16, if the current position is on a second code unit (Low Surrogate), then only that code unit is returned even by next32PostInc(). For iteration with either function, there are two ways to check for the end of the iteration. When there are no more characters in the text object: Example: void function1(ForwardCharacterIterator &it) { UChar32 c; while(it.hasNext()) { c=it.next32PostInc(); // use c } } void function1(ForwardCharacterIterator &it) { UChar c; while((c=it.nextPostInc())!=ForwardCharacterIterator::DONE) { // use c } } Definition at line 89 of file chariter.h. Value returned by most of ForwardCharacterIterator's functions when the iterator has reached the limits of its iteration. Definition at line 96 of file chariter.h. Returns a UClassID for this ForwardCharacterIterator ("poor man's RTTI"). Despite the fact that this function is public, DO NOT CONSIDER IT PART OF CHARACTERITERATOR'S API! Implemented in StringCharacterIterator, and UCharCharacterIterator. Generates a hash code for this iterator. Implemented in UCharCharacterIterator. Returns FALSE if there are no more code units or code points at or after the current position in the iteration range. This is used with nextPostInc() or next32PostInc() in forward iteration. Implemented in UCharCharacterIterator. Gets the current code point for returning and advances to the next code point in the iteration range (toward endIndex()). If there are no more code points to return, returns DONE. Implemented in UCharCharacterIterator. Gets the current code unit for returning and advances to the next code unit in the iteration range (toward endIndex()). If there are no more code units to return, returns DONE. Implemented in UCharCharacterIterator. Returns true when the iterators refer to different text-storage objects, or to different characters in the same text-storage object. Definition at line 681 of file chariter.h. References operator==(). Assignment operator to be overridden in the implementing class. Definition at line 184 of file chariter.h. Returns true when both iterators refer to the same character in the same character-storage object. Implemented in StringCharacterIterator, and UCharCharacterIterator. Referenced by operator!=().
http://www.icu-project.org/apiref/icu4c/classForwardCharacterIterator.html
crawl-002
en
refinedweb
Earlier this year I was fiddling around with the new J2SE network ProxySelector APIs as part of a small demo-project. Sadly, the project just wouldn't stay small and I didn't have time for something big. So after a few days it disappeared into one of the many corners of my laptop's hard disk, where it's been quietly moldering away. One part of the old demo was a small GUI for collecting network proxy host names and port numbers. I'd used JFormattedTextFields for the latter. You might think that doing so would have been trivial, since port numbers are just integers between 0 and 65534 and JFormattedTextField is very, well, flexible. It turns out to have been not so trivial and at the time I was inspired to write a blog-sized article about exactly what I'd done. That article would have remained buried with everything else from the project if it hadn't been for some interesting JFormattedTextField threads on the javadesktop.org JDNC forum that cropped up recently. The problem that inspired the JDNC JFormattedTextField thread had to do with decimals (like 123.45). Since I'd spent some time in the trenches with a similar problem, I thought it might be fun to exhume my old article and toss it on the pyre. So here it is. Warning: if you're looking for the material about JFormattedTextField you can skip the first couple of paragraphs. I've left the first couple of paragraphs the way they were out of respect for the dead. Plus, I'm too lazy to edit them out. Before writing more than a few lines of code I considered structuring the ProxyPanel component conventionally: with careful separation of model and view, and with great flexibility for all dimensions of both. The model would be a Java Bean that included all of the data required to completely specify the usual set of networking proxies along with all of the secondary data like overrides and user names and passwords. The bean's API would be specified as an interface, so that the ProxyPanel could operate directly on application data, and an abstract class would provide a simple backing store for the data along with all of the change listener machinery required to keep the GUI view in sync. The view would be equally overdesigned. It would be configurable, to accommodate applications that wanted a compact or subsetted presentation. And just before I awoke from my second system syndrome induced reveries, I imagined providing an XML schema that could be used to completely configure and (cue the Mormon Tabernacle choir) even localize the GUI. This was supposed to be a tiny project aimed at highlighting the new ProxySelector APIs and providing a small coding diversion for yours truly. So, after I'd calmed down, I decided to write a simple GUI that wasn't terribly configurable and that lacked a pluggable model. That's right: no model/view separation here. If there are MVC gods, I'm sure I'll be in for some smiting. And if the gods can't be bothered, then I'm confident that my more dogmatic brethren will take up the slack. Please don't send your self-righteous segregationist rantings about the merits of MVC to me. I know, I know. My first cut at structuring the code for the four pairs of proxy host/port fields that correspond to the bulk of the GUI was to create a little internal class that defined the GUI for just one proxy, in terms of four components: public class ProxyPanel extends JPanel { private ProxyUI httpUI; private ProxyUI httpsUI; // ProxyPanel constructor initializes httpUI etc ... private static class ProxyUI { private final JLabel hostLabel; private final JTextField hostField; private final JLabel portLabel; private final JFormattedTextField portField; ProxyUI (ProxyPanel panel, String hostTitle, String host, String portTitle, int port) { // create labels, fields, and update the GridBagLayout } String getHostName() { return hostField.getText(); } // ... } } The ProxyPanel created four ProxyUI instances and squirreled them away in four private ProxyPanel ivars. The ProxyUI class did encapsulate the details of how one proxy was presented to the user. On the down side, had to assume that the ProxyPanel had a GridBagLayout (no encapsulation there) and it felt gratuitously complicated. One lesson I learned as part of building this first revision of ProxyPanel was how to configure a JFormattedTextField that accepted either a integer between 0 and 65534 or an empty string. The latter indicated that the user hadn't provided a valid value. It seemed like it would a little less surprising for users to map no-value or invalid values to a blank than to insert a valid default value like 0. JFormattedTextFields are eminently configurable and if you'd like to get acquainted with the API I'd recommend the Java Tutorial. The specific problem I was trying to solve isn't covered there however with a little help from the local cognoscenti I was able to work things out. The Swing class that takes care of converting to and from strings as well as validating same, is called a formatter and the subclass needed for numbers is called NumberFormatter. A separate java.text class called DecimalFormat is delegated the job of doing the actual string conversions and it provides its own myriad of options for specifying exactly how our decimal is to be presented. Fortunately in this case we don't need to avail ourselves of much of that, in fact we're going to defeat DecimalFormat's very capable features for rendering numbers in a locale specific way. What we need is just a geek friendly 16 bit unsigned integer. Or a blank. Here's the code for our JFormattedTextField instance. We override NumberFormatter's stringToValue method to map "" (empty string) to null. The ProxyPanel.getPort() method that reads this field will map null to -1, to indicate that the user hasn't provided a valid value. DecimalFormat df = new DecimalFormat("#####"); NumberFormatter nf = new NumberFormatter(df) { public String valueToString(Object iv) throws ParseException { if ((iv == null) || (((Integer)iv).intValue() == -1)) { return ""; } else { return super.valueToString(iv); } } public Object stringToValue(String text) throws ParseException { if ("".equals(text)) { return null; } return super.stringToValue(text); } }; nf.setMinimum(0); nf.setMaximum(65534); nf.setValueClass(Integer.class); portField = new JFormattedTextField(nf); portField.setColumns(5); It occurred to me that perhaps an IntegerTextField would be worthwhile. That way one could write: IntegerTextField inf = new IntegerTextField(); itf.setMinimum(0); itf.setMaximum(65534); itf.setEmptyOK(true); itf.setEmptyValue(-1); // new feature, "" => -1 itf.setValue(0); I don't think that's a vast improvement however developers might have an easier time sorting out how to create an IntegerTextField than assembling the right combination of DecimalFormat, NumberFormatter, and FormattedTextField. Of course, having gone so far as to create IntegerTextField we'd want similar classes for currency values, real numbers, dates, and so on. Some of this is already covered by JSpinner although spinners are better suited to cycling through relatively small sets of values. It's been a long time since I wrote all of that. Looking back I'd have to say that a set of classes, like IntegerTextField, would certainly make life more straightforward for Swing developers. Hopefully the SwingLabs project will take up the cause and maybe in the future a collection of battle-hardened special purpose text fields will find their way into the JDK. If they do, I'll use them. Hi, Really I was waiting a wonderfull FormattedTextField, with things solved for the basic types like int, double, Date. I had my own simple Documents to obtain in some way the same result. Now it arrive, since it's arrived I'm trying to find how people who give as java, swing and a lot of wonderfull frameworks could have mis the point so much. Every Time a try to use this component I get a lot of trouble, it is not intuitive, an take care if you want to manage FocusEvents arround it, really disapointing, my old documents are back, and the new methods for handling Document features are really much more powerful and understanble tha this awfull Component. If this was a vote pool, I'll say: Take it out, write it again, pleeeeeeeeease !!!!!!!! Posted by: tonioc on August 27, 2005 at 11:08 AM Twenty-eight months later... These incredibly useful components are still missing from Swing. :-( Posted by: fredswartz on December 07, 2007 at 03:22 AM
http://weblogs.java.net/blog/hansmuller/archive/2005/08/using_swings_jf.html
crawl-002
en
refinedweb
It’s just data I've always wondered about your essays. Who's the target audience? Half of the things I've read from you specifically both "Gentle Introduction" articles as well as the WSDL 1.1 article seemed to lack any real meat for me. All I got out of them was a good collection of links and a fuzzy feeling about the ideas therein. Now if your audience is supposed to be devs who already know about the technologies or manager-types who just want an overview then I guess the feel of your articles is alright. If not, then as a fairly technical person I don't really get much out of these essays beyond a fuzzy idea of what technologies or techniques your are in favor off without much technical detail. I did like "What Object Does SOAP Access" and "Expect More". PS: Feel free to return the favor about the articles at if you want. I like critique about my overall writings and typically don't get enough of it. Well, Dare, clearly you are not it. ;-) I try rather hard to identify my target audience at the top of my essays. And they get a steady stream of visitors from places like schools and other technical folks whose area of expertise is different than ours. I actually got a laugh when I read that the latter link referred to that particular article as "a little more technical". What concerns me is that most people's first exposure to a subject like SOAP is seeing an RPC style request with things like xsi:type (largely traceable back to Apache) and unnecessary namespace declarations (tried ASP.NET lately?) and recoil in horror. Most of these essays have as a motivation a real debate that I was having at the time with a real person. My real purpose to these essays is to plop out a complete thought so that I can refer to it later as a convenient shorthand. It saves time.
http://www.intertwingly.net/blog/814.html
crawl-002
en
refinedweb
Kaboose Queue (kabqueue) The Kaboose Queue system is designed to handle asynchronous generic tasks (or messages). The main function of this system is to take the load off the request cycle. We use this system to send out e-mail, perform intensive image or video tasks, asynchronous network operations, etc. We had a few important things in mind when desiging this system: - Performance - Scalibility - Reliability The first item is obvious. The system needs to be fast and relatively resource friendly. For this reason, we chose the Starling queue system from Twitter (). The second item, scalibility, means that the system should: - Be distributed. Many machines submitting tasks, and many machines processing these tasks. - Handle a large number of requests. Each photo upload spawns resize operations for frequently used sizes. Each resize spawns off additional S3 uploads, for example. - Support task priorities The third item requires the system to handle failures, retry common errors, and notify us in case of major failures. Also, the system needs to surive the server dying and coming back and temporary network errors. With the help of Starling, and our previous experience with a database-backed message queue system, I think we've achieved our goals. We look forward to the community's feedback. Requirements sudo gem install starling sudo gem install daemons Installation script/plugin install Example usage First, you will need to create a processor file(foo.rb) in RAILS_ROOT/app/processors folder. It should be structured like so: class FooProcessor < Kaboose::Processor processes :some_model def processsome_model.some_method endend end Each processor class must implement a process method that defines the action that needs to be processed by the queue. This method has access to the @task instance variable that is an instance of Kaboose::Task. The processes macro creates an accessor method as a shortcut for accessing ActiveRecord models specified by model_id option in the task. See Kaboose::Processor's self.processes for more info. Configuration You will need a kqueue.yml file in your apps config folder to specify the address and namespace of the system, for example: address: 127.0.0.1:22122 namespace: some_namespace Running the Kaboose Queue system Just run ./script/queue_processor to get a list of options. If you are using monit, here's what worked for us: check process queue-processor with pidfile /path/to/queue_processor.pid group qtp start program = "PATH/queue_processor start -d -e production -c CWD -u USER -g GROUP" stop program = "PATH/queue_processor stop -d -e production -c CWD"
http://code.google.com/p/kabqueue/
crawl-002
en
refinedweb
Evidence-based management needs comprehensible information; metrics are distilled facts: not a bad fit. Here is a series of blogs giving a metric that can be useful in many areas of XML project management, from verifying the suitability of adopting a particular schema, to making sure that only work and capabilites arising from business requirements are being carried out, to estimating the price variation that a schema change may entail. Everyone using XML already uses a metric: well-formedness! Validity is also a metric. (I am simplifying away the difference between a metric and a measure in these blogs: pedants please lower your hackles!) But the metrics for XML on the Web are either concerned with communications and information theory, or are based on programming complexity measures, or are a little polluted by voodoo ideology about good structures and bad structures; I don’t buy into the latter, at least not at the current state of knowledge. But there is a need for a good set of metrics for XML project management, scoping and to inform XML schema governanc, so I thought people might be interested in some of the metrics I have been developing and using. They all address different, but to me vitally important, aspects of XML projects, and most are, I hope, common sense. Of course, you can make up your own metrics as well: but I think it is good to at least have a basic vocabulary of XML metrics to use or adapt or decry as appropriate. Element and Attribute Count This most basic and coarse metric asks the question “How many element and attribute names are there?” Take a schema or document set, count the unique element names and the unique attribute names, and sum them. It is a fine metric for schemas where elements or attributes only appear in a single context, with a single meaning. For example, a flat database dump of a single table with 50 fields has a metric of 51; a dump of a single table with 100 fields has a metric of 101; the idea that in some sense the second table is twice as big as the first (as the metric suggests) is obvious. For other kinds of documents, it becomes less attractive. Mixed content, multiple contexts, attributes used on multiple elements, all these things make a document or schema somehow more complicated, and the Element and Attribute Count metric doesn’t reflect that. Every time I produce the schema documentation for the release of a database, I provide management with a count of the tables and fields. Our cert gal asked how to interpret that. I told her, "roughly and don't get into reification fallacies". What she should really ask is about the number of keyed types. She asked about the growth rate. I told her it has settled at a number approximately at 200 per release. "Isn't that decreasing?" she asks. "It used to be about 400 per release but our coverage is very good now." I reply. She said she expected it to drop further. I told her it isn't likely to do that very fast because if she looks at the actual values, they are in the system tables where we are handling local variations, and in the seldom-sold features that we now implement for local agencies. IOW, the dynamism is in the exceptions now but they never quit coming. Any database that integrated around a set of common types (eg, names, vehicles, properties and locations) can grow quite large. If monolithic, it is a sales and cert nightmare. If modular, it is a pretty stable system. So I would want to know how many of the related tables are related simply by product bundling or by mixed namespaces that are created because the published artifact (document, report, etc.) actually require that. Yes Len, I agree they never quit coming. When developing the Document Complexity Metric, I sampled hundreds of documents using different DTDs. What I found, for any particular group of documents using the same DTD, was that every particular document only had about 70% of the elements (for medium sized DTDs). So sampling one or two documents was not enough to determine structure well, and in fact even sampling large numbers of documents was not enough to completely cover the number of elements. This has several impacts: the need to be suspicious of "fixed" schemas based on limited samples of documents, the need to have a change process instead, the need for tools to anyalyse document sets, the need for metrics for the tools to express useful things, the need for a rejection mechanism whereby rare elements (or elements only used because of tag abuse) can be dealt with. As is my point here, this is a particular problem when using the kitchen sink standard schemas, which are always too big. They were designed to be subsetted. Agreed. We learned about this in CALS wars. As you know, it depends on the approach taken to the results of the sampling. If one tries to cover every contingency, it becomes the DTD/Schema from Hell. If one attempts to subset too early, it becomes the DTD that spawns competitors (which ain't all bad). If one attempts to abstract away the differences, it becomes an abstract data dictionary and too many non-local types get pushed into it. Too much modeling leads to analysis paralysis. There is no single answer, but the rule of thumb that simpler is better seldom fails. If one acknowledges agreements are local, precisely defines the locale, and avoids the temptation to use recruitment as a means to pre-fix the market ("We MUST get buy-in first!) thus incurring ever expanding mission cressp, it usually goes a bit better. My best thought is to limit the use cases and the ambition. Evolution proceeds mostly by co-opting bits from near neighbors and adapting one's own uses to these. Reciprocity and a willingness to adapt mean living longer and getting more done. Better to pick one piece and do it well. GMX-V - new LISA OSCAR Draft Standard for Word and Character counts and the general exchange of metrics within an XML vocabulary: Hi Everyone,. GMX/V can be viewed at the following location: Localization tool providers have been consulted and have contributed to this standard. We would appreciate your views/comments on GMX/V. Regards, AZ Thanks for the heads-up on that, AZ. Lay readers may not be aware of the extent to which automated translation systems are used, in particular the success and penetration of translation memory systems. I am not at all surprised that a forward-thinking consortium like LISA, bringing together lean-and-hungry competitors whose cream largely comes from quality improvement, should be a leader here too. GMX/V has a name only a tech writer could love, but it seems completely serviceable for any industry needing a simple metrics reporting framework which supports phases (e.g., workflows, processes, etc.) Well done! Many thanks for you feedback Rick. I specially liked your description of GMX/V as a name only a tech writer could love. I will add this quote to my presentations on the subject!
http://www.oreillynet.com/xml/blog/2006/05/metrics_for_xml_projects_1_ele.html
crawl-002
en
refinedweb
I've been playing around and researching different ways to enhance TableAdapters when more custom functionality is needed. If you're not familiar with TableAdapters, they act as the glue between a data source and a strongly-typed DataSet/DataTable. You can create them visually using the Visual Studio .NET 2005 DataSet designer and add multiple queries to them that call SQL statements or stored procedures. You can even create new stored procedures right in the VS.NET DataSet designer wizard. There are several reasons you might want to enhance a TableAdapter: Fortunately, .NET 2.0 introduces the concept of partial classes which means that more than one class with the same name (but marked with the "partial" keyword) can be stored in separate files. At compile time all of the "partial" classes (with the same name) across one or more files are combined together to create a single class. Because of this great feature you can easily enhance the functionality of a TableAdapter by simply adding a partial class with the same name as the TableAdapter class generated by VS.NET. At compile time, your class and the auto-generated TableAdapter class will be combined into one class that includes your custom enhancements. You could of course inherit from the TableAdapter class as well if you want to override some of its default functionality. Sahil Malik has a great post about how to leverage partial classes to add transactional functionality and connection lifetime management to a TableAdapter. In his blog you'll see how you can easily create a partial class with the transactional and connection-oriented methods needed. Sometimes you might need to perform simple operations such as overriding the default sort of records retrieved from the database. This can easily be done by adding a partial class with your own custom method. A basic example of adding a custom sort method is shown below: using System;using System.Data; namespace LANLDataTableAdapters{ public partial class TutorialTableAdapter : System.ComponentModel.Component { public virtual LANLData.TutorialRow[] GetAlphaSortedData() { //DB defines a SortOrder field. This method allows //us to override that default sort and sort alphabetically. LANLData.TutorialDataTable dt = this.GetData(); LANLData.TutorialRow[] sortedRows = (LANLData.TutorialRow[])dt.Select("1=1", "Description"); return sortedRows; } }} While it's certainly advisable to perform any sorts in the database if possible, this example provides a way to sort the rows by description after they've been retrieved. There are several ways to do the sort (Array.Sort or a DataView) but using the Select() method proved to be one of the easiest for what I needed (and required the least amount of code). By using partial classes you can easily add whatever enhancements you need to your TableAdapters.
http://weblogs.asp.net/dwahlin/archive/2006/08/31/Enhancing-TableAdapters.aspx
crawl-002
en
refinedweb
home movies cartoon dvd memory concentration game universal studios horror films bear game hunting online pictures of great expectations auvergne pictures free game tumblebug basinger movie pictures of keith richards animated picture unicorn pictures of pendulum clocks hydropower picture best picture oscar 2004 nascar fantasy racing game city luxembourg picture action figure maniac movie pictures of mud wrestling party in iraq create a character games casanova movie trailer thai hookers pictures no cd pc games british garden birds pictures 2006 game hockey ice olympic winter lecy goranson pictures com game mobilefun n nascar nullification crisis pictures computer dog free wallpaper strategy download games get the big picture again dr dre ft game go here we egyptian pictures of people asa 400 film lyrics to the phantom of the opera movie soundtrack montreal nightclub pictures picture of people in afghanistan dvd movies online stores robert pictures hollywood shot picture ee cummings pictures hanging pictures plaster game quiz zoey101 film page 3 bull riding pictures walt disney illustrated pictures zinnias pictures zozer games code da game quest vinci makeup pictures eyes police swat picture 1741 films pictures of different bra sizes palm tree desktop wallpaper pictures of state batman jim lee picture bee nest pictures picture of the new kumbia kings 61 movie review the war of the worlds movies code talker picture mary kate and ashley movies lorena bobbit picture pictures of vitamins and minerals breakfast of champions movie review ben hur movie filmcels picture studio v2.0 and dell ferrari f430 spider wallpaper cyber bullying picture free game idea retreat youth national park picture stone yellow water wallpapers otsuka ai wallpaper family guy pictures of stewie the game gunit wallpaper us military wallpaper cool star war picture female picture tattoo tribal bob sapp picture picture miniature doberman pinchers big muscle movie a picture of a basketball deflower picture game special jeff probst julie pictures warrick stevenson pictures game kid online puzzle apropo.ro game lacrosse the aim of the game electonic games biking game nigerian movie actor and actress onlinecard games futureworld film pc game trainer lucy lee movie clips free pic and movie of upskirt atom film short barbie new games allstar game who won anakin skywalker wallpaper online education games tandem pictures mickey mouse games for toddlers war on terrorism 2 game inland empire film honda crv 1997 picture marathon game review the arcade fire pictures victoria game cheats paul lamond games music of the heart movie bledel pictures 2006 movie poseidon trailer stick picture frame fun kids games math ebert and rober at the movies casino game las online vages healthy kids games download 2 fast 2 furious game biggest bollywood hindi movie pictures of the tooth fairy doubt no picture sonic the hedgehog downloadable games topless wallpaper pictures of wwe superstar randy orton naked free world war 2 movies pop the bubbles game hidden in movie secret street race picture downloadable games for mac osx tall ship games maths shape and space games magic roundabout movie 4 character movie scary bush humor pictures costner film kevin free mature movie downloads dog fun and games goofy cat pictures ws games joe korp movie games two monitors pictures of cute puppy green pastures movie pictures of shirley manson veggie tales colouring pictures lohan skinny pictures messy kid games tinker bell picture frame ultraviolet movie reviews mighty python and the holy grail pictures canseco esther picture easel-picture o brother where art thou movie reviews horror monologue picture rocky show fighting free game more play cartoon faces pictures movie camera lenses multiple personalities movie catwalk picture video game revenue 2004 downloading psp wallpaper pictures woman in pantyhose ccr wallpaper local movie theater guide glittery fake puppy pictures pictures of the forest trees film themes music african greys in the wild pictures body inflation movie picture fat men diacetate film thomas the train kids online games game osho tarot transcendental zen zen game jeep latina movies picture sachin tendulkar the temptress silent movie free final fantasy 7 wallpapers chinese interior design pictures stonehenge picture card download game pyramid contributor kara picture shadow telugu film song ball pool online games game genie code for harvest moon snes oklahoma city history and pictures movie x english learner language game cobi jones pictures agressive inline pictures free gay movie scat direct x 9 game programming pictures of snowboardes weasle picture ending explanation hill movie silent car cube game game thin film deposition service romance games online 'amazing pictures of the lincoln memorial picture this movie pictures of chippendales role of a film director kids hunting games gibson mel picture gaucho picture linux penguin pictures flying dragons film fordyce spot picture celebrity movie archiver indianapolis movies theaters play tanks the game pictures of rimini fun fun fun game joke video cheat codes for kewlbox games fiero interior pictures beginner guide to darkbasic game programming smile games.co.uk port huron movie bubblegum pictures and games free game ping pong book core game lord playing ring role free game love simulation pictures of a log cabin games cheats for habbo hotel your favorite games bowling soup wallpaper charles lake louisiana picture satellite 12x36 picture frame igneous rocks picture picture of tigger dressed as sheriff t mobile picture text farscape the game gril boy game may west movie paper wastebasket game akina game mlb all star game saved by the bell game ddt pictures bunny hop games traditonal clothing pictures in germany only fowl game supply fang movie import psp games game revoultions online bandit game tech games subash ghai movies coo coos flew movie nest one over houston game ancient egyptian learning games tails the fox pictures love is not a game keanu reeves new movie release 1985 ford escort pictures best free game online play video game boulder colorado striping women games download free game smartphone runelords movie news dragon lady picture flash game battleship pictures of opium dens salt crystals picture independent film new game motorola q song from bring it on the movie the game shot g unit tsunami in phuket pictures 2005 great movie movie the gift d1 game the cat woman movie laramie movie theatres super pile up game movie maker dvr ms mad libs electronic game gears wallpaper war zapit game bonnie bedelia pictures carmelo anthony syracuse pictures video game graphic design training japan german expressionist film movement 300 chrysler paint picture tone two the incredibles the movie mp3 e game lucky star kiano rives new movie real amature homemade movies toyota car wallpaper armageddon film official abrams m1 picture resident evil 4 monsters pictures lex luthor wallpapers aria free giovanni movie picture final fantasy 8 card game download christmas ornament picture 3d picture space frame making picture supply cranky pants game crocodile dvd hunter movie dress fashion game online golf coarse pictures icons movie 84 mustang pictures math flashcard game john hughes movie list online juggling game hail pictures in black diamond sand art pictures santa snowboard game free amateur cock picture bow shooting game satan picture find actors in movies mac plus games game burner free day of the dead movie film center nyc cliff jumping pictures great movie lines wild plants pictures gay men couples kissing pictures picture of leafs free unlimited downloadable games wish games anime wallpaper gravitation joust flash game online game voice clip fu kung movie picture of ceviche good charlotte joel and benji pictures game development annual salary new directors film festival group fun games famous history pictures black and white spiderman pictures faith based santa claus movie stories film editors christina milano pictures picture graphic eminem world pictures game line time video rip audio from dvd movies picture of house in malaysia picture of davy crocket picture of glitter acrylic nail play downloaded gamecube games picture of r l stine ice age films picture of college life organ picture system 2003 pan am games the matador movie trailer wide striped wallpaper wallpaper for t mobile falling sand game download shrek 2 game boy advance rom 100 cheat game green leaf pokemon shark working starting a independent movie theater aaliyah movie dining home model picture room wallpaper of golf gti mk2 pictures of rabbits and bunnies stereo movies maltese teacup pictures 1024 base wallpaper pictures of columbus oh philo vance movies hazard perception games brittany murphy clueless pictures pictures speak louder than words x games los angeles 2005 my beach wedding pictures history through film 1 minute games lawnmower man movie download nokia 3200 games free black dog movie how tocopy xbox games terence hill bud spencer movie disneychannel co uk games ocean storm pictures how to expose film deluxe game pc transportation tycoon chicago video game audi a5 pictures black hindi movie reviews games sonic the hedgehog online games harryhausen picture poster ray rocky horror picture show raleigh nc playstation master game list virtual reality pictures escape game online play room pictures of bush twins dresses drawing inmate picture athens ga movie man united pictures horse jumping pictures 3 free game mbc onlie jennifer ellison new pictures guitar chord pictures scramble online game picture of worms naked pictures of fat chicks desirae spencer pictures nokia 6680 pictures scholastic clifford games burned chip game mod play ps2 without nemo in slumberland movie counting money online games 2007 movie sequel vip dvd movie online sketching game people shitting pictures 42 game table 2 age game ice pc the dangerous lives of altar boys movie reel to reel movies pictures of handicap mind game trailer frank hudec film pc drift game baseball free game bettyboo picture x111 games firefly film film fuji review s5200 balajis movie reviews halo pc game saves picture of the colorado flag movie poster displays disney movie halloween town b movie actress list muro ami movie review pterodactyl dinosaur pictures 1960s board games christian easter free game candy hard movie showtimes hook ups skateboards pictures game system emulators duomo florence picture smack the penguin game blood wallpapers games for tupperware parties 1974 cia movie spoof spy kids 3d games cellulose wallpaper paste mark mcgwire picture steroid online paintball movies conspiracy games game preview return superman video big game guide hunting rastafari lion picture pictures of power plant picture psp put bharath movie role brown hair picture halford picture rob anna nicole picture recent smith movies you can watch online juicy jesika pictures masquerade mask pictures advance battery boy game pack sp avoine folle fort picture halloween movies pg pictures of madeline albright jonathan taylor thomas 2005 pictures flag of our fathers movie premiere movie ties pictures of saphira white knight games reading the hard road cycling movie top movie stars of 1989 korea movie photo movie size gb dead or alive extreme beach volleyball pictures footjob free movie sample movie 278 hiram astraware game pack billabong pictures randy moss wallpapers demon slayer movie acanthosis nigricans picture infield naked pictures free game nokia n gage my wifes pictures thunder road game show tidal wave movie game beta testing jobs pictures of englands clothes north american big game hunting hot jared padalecki picture tv movie for sale iranian party pictures 8 cinemark movie tulsa can free get man milk picture suck tit wife 1992 barcelona olympic game punchout arcade game 2 code game guitar hero video picture of folgers coffee can free live hindi movie baron davis wallpaper airplane cabin picture quentin tarantino movie scripts world village games newmarket films phone number las vegas growth pictures game fair 2005 chrysler crossfire coupe pictures picture of kansas football team picture of police badge adventures wallpaper finger wart pictures auteurs film pc wallpapers download movie scrpt phantom of the opera original movie make flash games for free game searching don movie song geneseo movie ny theater the original movie pictures or drawings of hamstring muscule 2000 mtv movie award game miami piston danny kaye film merry desert storm games border picture shamrock pictures of castles in wales brick sundance film festival peter pan film reviews red poppy pictures play puzzle games online for free nag head nc picture pictures of bouquet of red roses mobile suit gundam seed wallpapers jumping elastic kids game movie fan clubs film 1958 danny kaye office picture circle of friends movie cast loony toons pictures hulk cheats for game cube funny celebrity game data game management show buying movie theater gungrave game soundtrack westley snipes movies dick and dom in the bunglo games black picture pregnant woman who wants to be a millionair games pictures of bartenders at coyote ugly in las vegas picture of space rocket games like need for speed movie directors board xbox games walkthroughs high quality car wallpapers film manotick tony spokane valley mall movie pictures of the most beautiful women free online zoids game katie holmes movie bicycle safety picture stamford ct movie psp ftp game isos game hog hunting online fast furious wallpapers klay world movies backgammon game pieces maifa game naughty picture messages jasmine tame movies different hair colors pictures game with hotties card game sheepshead hurricane damage picture pictures of symptoms download game pokemon yellow womens big game hunting clubs 2 friend game play station pontiac sunbird pictures the yeti games penguin slap beaver football pictures super chexx hockey game new scary movie releases movie attendance 1930s vanessa del rio movies sister tattoo picture best british films amanda righetti wallpaper treasure of the sierra madre movie ruth shalit picture sinatra movie anime christmas wallpaper cars picture 66 ford mustang fort irwin picture pregnancy fetal development picture auschwitz pictures today desktop screen pictures ghost pictures for halloween mr moms movie pictures angle scared people pictures movie photo x3 snes emulators games california health department restaurant rating sign picture pictures of jesus christ /crown of thorns troja film walking on water pictures star wars movies concept art picture japanese garden titticut follies movie movie video trailers free download power rangers the movie star trek tos wallpaper president bushs daughters pictures mario bros download game free hot anime lesan action movies gael force films wallpaper theme digital graphic kevin picture wischer.co.uk game play science kobe tai free picture eddie from iron maiden picture taz cartoon picture free oline games to play ex picture post backup game software outrageous films pictures of ashlee simpsons new hair cut download film free vcd graffiti making game where can i play geography games online the ring movie story humor games online hot spring steaming picture picture 2 bill nanomachine pictures pictures for the bathroom american history x movie script intestinal worm pictures medium of the video game amc movies theaters alchemist full metal movie trailer wallpapers hotties c murder picture tricked out cars wallpaper bell legend movie witch kingpin movie pic movies sterling heights player zone games pictures of lilac bushes vacaville movie times board games dirty minds motorcycle picture racing colonial game table computer game hearts kanye west out the game lyrics the sims 2 for game boy advance century 16 movies salt lake game i won pictures of wifeys world celeb movies+free funeral irwin picture service steve game pc scarface world yours military weapon picture cheats for the xbox games she hate me movie play free tank war games harry potter and the order of the pheonix film adele silva wallpaper bang pictures video games clips alice in wonder land game game ft 50 cent how we do lyric mercedes s55 pictures picture of bare breast of woman medal of honor game downloads 2005 auto show pictures ppc freeware games janesville wisconsin movie theaters box list movie office patches for pc game free sophie sweet movies dark movie tower kasumi doa pictures seattle film festival entry luxor the game kim sharma wallpapers monopoly game boy advance kal win lord movie pictures of new cars for sale 2x2 picture em figure game shoot stick up doodle pictures anderson pamela picture pregnant dirty hot pictures space war games johnny depp pictures only the plaza hotel picture vocabulary quiz game show a disney game arcade window graphic film gareth barry pictures angelika films game language sv trailer games for christian youth group gratis simpsons wallpaper game chicken farm freddie mitchell mohawk pictures manisha koirala hot picture columbia in maryland movie theater swedish pictures download free game garfield picture of aesop rock badge game warden msn online games asian ladyboy movie shemale martha stewart movie silvercity london movies free kid game for kid primary colors pictures devil may cry 3 wallpapers veronika raquel free movie two for the money film wedding pictures at four seasons hualalai father day picture car game online pixar branchial cleft cyst picture movie listing in new york historic philadelphia pictures wallpaper borders and jungle animal films crash butt free movie scary movie 4 reviews holland career interest game bridget bardo pictures from hell movie poster game boy advanced cheats for 3d driving school games extras in film transfer video movies to dvd disks bollywood actress picture game need for speed ii angylina pictures side scroller game legion game cheats daily wallpaper changer tarot games blacklight tattoo pictures department fish game oregon state friendly soccer game clue finding games 2006 carnival grenada picture long movie clips free indian films download cam neely all star games hepburn hughes picture greed the game show all funny pictures tetris hand held game michael romanov picture league of gentleman the movie push push cell phone game arboretum movie pajama game soundtrack harry connick pictures of tooth decay pocket pc games freecell creature heavenly movie spot movie cube movie zero change game peach princess set x dolly doll msn pictures italian war movie clean film movie first waterfall picture pictures of the battle of chancellorsville picture of jackie joyner kersee alexandra christmann kissing picture drive in movie store a plant cell pictures charmane star movies in the story the most dangerous game dave games blue lagoon movie pics pictures of biodiesel fuel light gun games for xbox apostles pictures jlg lifting equipment pictures copy and paste pictures drop kick the punks game alien vs predator game demo bingo ball picture vincent regan pictures picture wife wild deep red games miniature husky picture picture of doublewide mobile home dora the explorer games to play cell game phone ringtone video virgin dvd garfield movie the godfather the game cheats ps2 iron phoenix xbox game grande cache alberta pictures sailor moon play station game free picture slide show movie theaters + greensboro nc go online board game artis indonesia wallpaper motion picture director several movies the muppet movies picture of hat pictures of aids and hiv breeders game texas wild battle of fort william henry pictures potato cannon movie elementary school physical education games really cool math games fantasy pictures of women be cool the movie travolta gambit pictures winnie the pooh wallpapers movie review constantine viet pride picture funny horse pictures freestyle figureskating pictures la film festivals lots of dress up game bite gnat picture pictures halloween steal wallpaper lilo and stich game colapse game play jet fighter wallpaper java games to download movie spoofs amputation leg picture woman metrotown metropolis movie listings sea games manila afi 100 greatest movies csi cd rom game picture of rosa parks husband funny stress picture wenatchee movies free online nintendo games picture of university of hawaii shaking hands pictures cheesy movie love lines football game lsu picture cameron diaz movie clips davis square movie theatre commonwealth games medal table history pictures of uk money pictures of maya invasion flash games free online funny flash games abcs lost wallpapers nec phone games semi precious stone picture 2006 330i bmw wallpaper fetish movie post movie rose tattoo rhesus macaque pictures free casion game eric nies picture sword quest game usher movie boy dark movie side movie opera phantom still activity family game reunion botswana flag pictures pictures of angelina joli detective movie police show television undersea wallpapers crime free game online solving les miserables musical movie plain white ts pictures top 20 films uk tzar game carebear wallpaper windows movie maker windows 2000 pro 5 pound note picture heidi klum wallpaper 1280 download downloadable free full game game golf mario online picture framing courses interactive trivia game movie mr penguin poppers flash movie clip control printing film king kong picture 1933 ho chi minh game animated cars pictures food japan picture restaurant elizabeth the movie 1998 page davis pictures picture of bulldog puppies the end of evangelion pictures superman the movie 2005 yeti sport online game ciara concert pictures nothing movie review hello kitty pictures dj qualls movies mirageos game comedy monologues from movies game machine rent room slot movie theater hudson wi kill bin ladin game archive by celebrity movie rabbit quotes from life as a house movie flow hustle wallpaper crazy download game taxi pictures of iraq elections yamaha yfz 450 pictures olympic swimmers pictures pictures of hippie guys wolverine movie news courtney culkin pictures download game godfather pc picture of shays rebellion free baitbus movie trailers scoby doo game free motorcycle games heron bird pictures in love and war movie quotes pictures of military fighter jets penguin throwing game eds driving games royal python pictures french movie directory happy valley pictures new nascar games bay of fundy tides pictures comuter game movie streaming watch maria ozawa movies mugen fighting games bm free game online chou jay picture free tamil movie down load nfl player pictures rachael mclish pictures best live action short film 2004 best war game 2004 civilization ii game shark code crotchless picture rent hindi movies arcade game online racing valeriana picture j2me java game woody allen movie script free iwin games build a virtual house game picture of meredith vieira silent film naldi persona movie poster most controversial movies of all time 24 wallpaper season 3 sky lopez wallpapers south sydney rabbitohs wallpaper competitor female fitness picture chain reaction word games hindi movie trailers download movie psycho ward 7 free game online wonder cool game demos fade to black movies pictures of 1995 nissan transmission parts dressups games cheat game page pogo inspirational jesus picture game time limit exotic car wreck picture image myspace picture bat boy picture cheap game cube rl stine picture gymnastic game games online gaming picture of black roses picture red salamanders actress madhavi movie doggy free hairy japanese movie whore simpsons colour in pictures movie theater lists 2 movie saw spoiler picture of nyu total recall movie pics more pocketpc game toe sucking pictures pistol pete maravich pictures poker cash game kerrigan pictures godfather game maps james jesse picture woodson vw bus wallpaper miami dolphins cheerleader pictures land before time the movie arora borealis wallpaper kiss me quick movie kris roe pictures free handjob pictures american card contest dog greeting picture movie in savannah ga ' dumb dumber mini bike picture' angel blazing box game x cowboy wallpapers movie night gift baskets pictures of lake monsters pictures of garden insects colorado industry major picture download free picture resize shareware games free downloads picture type of wart jig saw games jeremy mcgrath wallpaper captain america dvd movie highland games grandfather mountain free pocket pc games breakout soccer goalies pictures fear game server lowes movie theater white marsh md pictures of flying dragon boy movie straight chili movies bravo movie scariest pictures of fastpitch pitchers ruehl store pictures picture concert animal games to play free seimens mobile game downloads 1997 chevy monte carlo pictures game used baseball cards soundtrack movies eva huang sheng yi picture pictures of ping pong parinda movie cat deeley wallpaper free wallpaper wwe alaska glacier picture mofia game sujal picture orsani games alt binaries games dox free full length download able movies movies for mobile phones spiderman xbox games brook garth picture wedding beaufort carolina movie south theater eternal sunshine for the spotless mind movie quotes cartoon picture pig porky picture of a bird cage babs bunny pictures latest game releases 2005 911 pentagon plane crash pictures anya wu picture have a nice day 2 pc game computer games on cd mountain biking online game film journal international movies on pay per view microsoft video game biplane picture watch independent films online solar gard window films world cup soccer qualifying games picture of muscles in body lemony snickets a series of unfortunate events movie reviews americas cup sailing pictures dragonball z on line game rainforest cartoon movie pictures columbine shootings picture shama sikander jessica job nose picture simpson free game down sim tower download hindi movie mp3 songs fella roc wallpaper configuracoes do game boy advanced film quotes chevy caprice picture flo in the movie cars photos from yhe movie lonesome dove fabrics pictures free dirty talk movies coloring picture printable spring williams bmw f1 wallpaper hostel movie photos listen to wicked game nick greenlee movie x-men mutant apocalypse game genie japanese import games what movies are playing movies based on video games eos rebel film camera coronado de francisco picture vazquez art films london 50cents pictures rock band wallpaper new york giants pictures fishing game pro propoxyphene pictures blockbuster movie rental prices birth giving ofwomen picture heather hunter free movies chaplin film city lights play mature games online nba game ticket free movie sharing program snow storm pictures maine slg game rosh hashana picture gotham city wallpaper new indie film nintendo game spot anonymous game developers berkshire distributor game leisure clock desktop free wallpaper picture of expensive car parodie film lindsay lohan picture slip drag free game online racer download silent movie music brad pitt legends of the fall wallpaper car race games to pink sock pictures lake district uk pictures short film history hilo hawaii pictures rentals beach picture virginia free confederate flag pc wallpaper baraye download film mystery flash games princess pictures to color death film sister movie ratings 18a liverpool football wallpapers spawn movies the big picture scrapbooking board character clue game game show model kung fu wallpapers worst games of 2004 shetland island game gtr ultimate racing game jake booty call games sony wheel of fortune online game return of the king movie script ronnie tuscadero movies play a good game blowing bubble gum picture picture of a healthy colon free naked in public picture seek and find picture eagle picture rare dame in inside notre paris picture i mate game movies jeans movie club online turbo grafx 16 game anti wal mart movie cloud katrina picture storm game install java play yahoo pictures leopard lidole movie hand held board games nin broken movie air bud movie justin sterling pictures free blowjob movie clips frre fishing games jackson joke michael picture pandora peak movie free quicktime movie clips commando game free download spongebob the movie cheats for xbox hairdresser movies recluse bite picture acid burn picture game cube cheat codes game manufacturing gioi thieu games flavors the movie cup fantasy game soccer world easy chess games sundance film festival award winners madonna pictures in the 80s buy dvd movie vhs employee of the month movie 2006 dancing dirty picture yahoo game online dominoes game oblivion patch free duel master game download the leaning tower of piza pictures harley davidson games kelly slater pictures python movie poster malcolm x the movie mcdonalds fries pictures picture of wedding tent all time movie gross download mobile phone games uk movie tough guys cinema film modernity post reader war radio stars dirty pictures duck cartoon pictures chlamydia in picture woman duke rape pictures scenes from the party gang related pictures lisa joyner pictures picture snake venomous the fort lauderdale international film festival game guide radiata story oprah winfrey 2005 pictures gameqube games released movies on dvd film servais star up roar games every game ever nes riddick sequel movie cabooses picture train yugioh dueling games online pediatric doctor office picture full clip movie review production b movie tomb raider games to play online full throttle game music picture polo volkswagen st kitts beach pictures movie theatre toronto ontario cheryl crow kid rock picture canadian movie star buffalo bills wallpaper kid rock crow picture spider cards game cute animal game netcafe movies 1930s movie pictures of hugging pimp car pictures funny picture jpeg meiosis game big cake picture wedding picture of a raven bird ski doo rev picture one flew over the cukoos nest movie cast of the movie friday night lights isle of mann tt game discovery kids online games deck dogz movie review money movie po picture bloopers 360 box game news x axis and allies game online wwii film clip jaychou picture ps2 game save converter p2m movie tilton 9 movie theater college coed movies picture per second pokemon charizard picture how to beat hapland game boones crossing movie theatre disney connection games uk film studio ashley simpsom pictures carole picture radziwill raven symon pictures eyes movie only documentary film making reality video banana beach pictures hq mischa barton picture download window movie maker 2.1 too skinny pictures film holocaust indelible shadow mississippi game and fish department shobna gulati pictures game online pet reality virtual picture of madagascar flag mature boob picture house bug picture the movie help by the beatles advanced wallpaper custom car games online catch movie perfect serena williams picture cake picture pink poodle picture of animal with rabies bomberman game play picture of swarm of bee samuel champlain pictures distributor game movie video sacrament of reconciliation pictures how to play domino game movie grandmas survivor uncut pictures pictures of dredlocks game health kid
http://members.lycos.co.uk/officialmeds/m04.html
crawl-002
en
refinedweb
Why. This dissertation depends on Ruby on Rails; the general techniques apply to any web development. The assertions presented here are available in the Rails plugin assert_xpath. Hpricot’s arch enemy is REXML, an XML parser bundled with Ruby. Here’s their score chart: The test plugin assert_xpath supports both systems, and enhances their DSLs. A Rails functional test works by mocking the web server, and generating a sample web page as a big string, in the variable @response.body. Then a test case parses this string, looking for its important details. This technique avoids the overhead of invoking a real web server and browser, and commanding each to do something outside its performance envelop. The two query languages for HTML are CSS selectors and XPath. Here’s a test case using raw Hpricot, before we cook it up in reusable assertions: def test_raw_Hpricot get :index, :id => 'FrontPage' # serve a WikiWiki doc = Hpricot(@response.body) # read the mock server response script = doc.search('script[3]').first # locate our target <script> assert_equal 'text/javascript', script['type'], 'script should be JS' assert_match /&/, script.to_s, 'oh no! our script has a & character!' end Test cases can choose between Hpricot and REXML, to leverage each one’s advantages. assert_xml uses either, depending on a recent call to invoke_hpricot or invoke_rexml. (Use this technique with the Abstract Test Pattern, to run assertions twice.) Call assert_hpricot or assert_rexml directly, to override this default. Assertiveness Counseling Now we bundle those Hpricot calls up into two assertions, assert_hpricot and assert_xpath: def test_with_assert_hpricot get :index, :id => 'FrontPage' assert_hpricot # @response.body is the default script = assert_xpath('script[3]') assert_equal 'text/javascript', script['type'], 'script should be JS' assert_match /&/, script.to_s, 'our script has a & character!' end Because Hpricot is forgiving, assert_hpricot itself does not actually assert very much! (Use assert_rexml or assert_tidy to validate your code.) The important part is the next line, assert_xpath, because it wraps doc.search, so we can put a wide subset of XPath into it. In this case, we only put in a [3], to select the third <script>. You Are all Forgiven Like a web browser, Hpricot forgives your HTML for its sins. Some test cases should not. But REXML is so unforgiving that Transitional XHTML might break it. The fun starts when your XML contains an & without its escapes: # both Hpricot and REXML like well-formed & escapes: assert_xml '<a>&</a>', 'a[ "&" = . ]' # ^ input XML ^ XPath to satisfy # only Hpricot likes ill-formed escapes; assert_hpricot '<a>&</a>', 'a[ "&" = . ]' assert_raise_message REXML::ParseException, /Illegal character '&'/ do assert_rexml '<a>&</a>', 'a[ "&" = . ]' end # and both like incomplete escapes! assert_xml '<a>&yo</a>', 'a[ "&yo" = . ]' Why is that important? Because web browsers don’t process the escapes found in embedded JavaScript. That forces our tools to incorrectly escape these escapes when they generate HTML. So a Rails call to javascript_tag("document.write('&');"), for example, will emit this: <script type="text/javascript"> //<![CDATA[ document.write('&'); //]]> </script> Bless ActionView’s pointy head for escaping the entire block correctly, but according to the “law” (or “recommendations”), that output should contain &amp;. Browsers should interpret that and pass & as a source code literal to JavaScript, and this should push & into the browser’s surface, which should then display & to your user. If an HTML tool like javascript_tag corrected that &, modern browsers would not interpret it before the JavaScript layer, and your users would see &. That’s not really what you wanted, and browsers can’t upgrade until everyone in the world who wrote their websites with Notepad upgrades their source. Don’t hold your breath. And so javascript_tag doesn’t escape the & to &amp;. The culture of XML enforces well-formed contents, typically machine-generated. So even if REXML does not choke on any appearance of & followed by alphabetic characters, it still chokes on all the other appearances of &, such as && for and operations. And you can’t escape them because your browser won’t de-escape them. If these problems prevent you from using assert_rexml, prepare your XHTML first with a call like: @response.body.gsub!(%r/&(?=[^a-z])/i, '&') Hpricot doesn’t have all these problems. Functional Tests for Views A Rails test that operates on a controller is a “functional test”. These should guide the operations of complete features. Ideally, all our low-level data manipulations should appear inside models. Controllers control data transactions, and send results to Views. So the place to start view testing is the functional tests, where each page we render comes back as a big string. def test_buy_item_form login_as :tygr get :index assert_hpricot action = url_for(:action => :buy_items) assert_xpath "//form[ '#{ action }' = @action ]" end The login_as method comes from one of Rails’s nifty authentication plugins. Then get :index simulates fetching the index page of our current controller. The assert_hpricot absorbs its output, and the assert_xpath reaches out to a suspect FORM. Note that we always concoct URIs using url_for(), and we never hard-code FORM actions, such as “ /training/buy_items“. We don’t want our tests to break just because we changed the file routes.rb. The test is not complete yet because it doesn’t do anything with the FORM. First, we will upgrade its Hpricot stylings. CSS Selectors Note the first search used XPath to query for a given FORM, while the second one used CSS selector notation to identify the same FORM. Hpricot supports a subset of XPath, and CSS selectors, thru the same interface, so we can always use the system that’s most convenient. For example, if we must target an element with multiple classes, <div class="class_A class_D" />, our first attempt at a matching XPath is odious and fragile: .//div[ contains(@class, “class_D”) ] That’s fragile because a different class, “ class_Dismissed“, would provide a false match. A better XPath would require more tedious string manipulations in its [predicate ] filter. The CSS notation is more clear and accurate: “ div.class_D“. So this test case finds our FORM using its unique id, not its action: form = assert_xpath('form#buying_items') action = url_for(:action => :buy_items) assert_equal action, form[:action] This opens the question how to test the link from that URI to its target action in the controller. We could change that action’s name, and this test wouldn’t break. Because unit tests for web sites cannot (yet) work with real servers and browsers, we must at least test each step, with overlapping test cases. One case will test we have a FORM, the next tests that it calls the right controller action, the next tests that the controller action does the right thing, and so on. Submitting Forms The Rails plugin form_test_helper works with assert_select (another useful assertion system based on an HTML parser and CSS selectors) to read a FORM’s input variables, and present each one as a helpful little collection. We can assert that our FORM contains the right action, then assert that submitting our FORM, with its current fields, will call the action correctly. def test_buy_item_submit_form login_as :tygr get :index assert_hpricot form = assert_xpath('form#buying_items') action = url_for(:action => :buy_items) assert_equal action, form[:action] submit_form form[:action] do |post| assert_equal users(:tygr).id.to_s, post['user[id]'].value post[:prop_1].check post[:prop_4].check end # assertions here should check the controller # updated the model and database correctly end submit_form passes its post information into our block for treatment. We can assert that some automatic fields are populated correctly (including hidden ones), and we can simulate user input by changing some fields. (Tip: Temporarily run p post.field_names, to remind yourself what your FORM contains.) Conclusion Hpricot’s XPath system cannot handle long elaborate queries. Use REXML if you need those. And Hpricot’s forgiveness envelop is a benefit when retrofitting tests to ill-formed HTML, but it’s a liability when building a site from scratch. Test cases should always incidentally coerce your code to improve its quality. If a super-strict test case, based on REXML, suddenly fails, you should revert your most recent edit and try again. This time you might not make the same mistake. Hpricot, in its default configuration, would not have warned you. A test case can mix-and-match REXML and Hpricot freely; by passing the results of one into the base method of the other: def test_handoff assert_rexml '<anna><marie><candy><lights>' + ' <since><imp>' + ' <pulp lay="things" />' + ' </imp></since>' + '</lights></candy></marie></anna>' assert_xpath '/anna/marie/candy/lights' do |lights| lights = assert_hpricot(lights.to_s) # transfer a fragment of XML lights.since.imp.pulp{ @lay == 'things' } end # both assert_rexml and assert_hpricot end # support these query notations... These assertions allow Rails view tests to move beyond reacting to code changes. You can upgrade a test to fail for the right reason, and then upgrade your code to pass the test. This improves confidence that your tests cover the right things, and you can change your code more freely without making mistakes.
http://www.oreillynet.com/onlamp/blog/2007/08/assert_hpricot_1.html
crawl-002
en
refinedweb
document is part of the WAI-ARIA suite described in the Public Working Draft by the Protocols & Formats Working Group of the Web Accessibility Initiative. The main innovation in this draft is the proposed approach to implement WAI-ARIA in host languages (see Implementation in Host Languages and Quality Assurance). The host language implementation requirements balance architectural goals with the constraints of present-day user agents. It seeks to address forward compatibility with HTML 5 [HTML5], which is expected to be complete after WAI-ARIA. Because of the above focus, this version of WAI-ARIA is published without corresponding updates to its companion documents: the WAI-ARIA Primer [ARIA-PRIMER], and WAI-ARIA Best Practices [ARIA-PRACTICES]. This version includes minor changes to the WAI-ARIA taxonomy since the previous version. Refer to the history of changes to WAI-ARIA for details. Feedback on the model set out here is important to the success of the Web community in creating accessible Rich Internet Applications. The PFWG would like to know, particularly for this draft: Additional questions: When addressing these questions, please consider them in the context of the companion documents. Comments on this document may be sent to public-pfwg-comments@w3.org (Archive). Comments requiring discussion should be copied to wai-xtech@w3.org (Archive). Comments should be made by 3 widget widget) and structural document (content organization) types of inital value will be treated, via accessibility API events, as the removal of the old element and insertion of a new element with the new role..0 illustrates a typical Document Object Model (DOM) [DOM] node. Placed within the DOM node and the assistive technology is a box containing the contract provided by the user agent to the assistive technology. This data includes typical accessibility information found in the accessibility API for many of our accessible platforms for GUIs (role, state, caret, selection, event notification, parent/child information, relationship, and descriptions). an implementation of Resource Description Framework (RDF) [RDF]. Tools can use these to validate the implementation of roles in a given content document. ARIA is expected to define how to extend roles. The design aims of creating this specification include: This draft currently handles two aspects of roles: GUI functionality and structural relationships of the element. For more information. are intended to help authors learn the practice of putting WAI-ARIA to use. Keyboard accessible content helps users of alternate input devices. The new semantics when combined by our style guide work will allow alternate input solutions to facilitate command and control authors to restructure and substitute alternative content in adaptive Web 2.0 solutions. Assistive technology needs the ability to support alternative input forms by getting and setting the current value of widgets. AT also needs to determine what objects are selected, and manage widgets that allow multiple selections.ARIA is used as a supplement for native language semantics, not a replacement. When the host language provides a feature that is equivalent to the ARIA feature, use the host language feature. ARIA should only be used in cases where the host language lacks the needed role, state, or property indicator. First use a host language feature that is as similar as possible to the ARIA feature, then refine the meaning by adding ARIA. For instance, a multiselectable grid could be implemented as a table, and then ARIA used to clarify that it is a grid, not just a table. This allows for the best possible fallback for user agents that do not support ARIA and preserves the integrity of the host language semantics.. The Roles in this taxonomy were modeled using RDF/OWL [OWL] to build rich descriptions of the expected behaviors of each role. Features of the role taxononmy provide the following information for each role:. Assistive technology may access this information through an exposed user agent DOM or through a mapping to the platform accessibility API. When combined with roles, the. An example of a managed state is focus. In contrast, the states in this specification are typically controlled by the author and are called unmanaged states. Some states are managed by the UA but the author can override them, such as posinset and setsize. The author should override those only if the DOM is not complete and thus the UA calculation would be incorrect. Both managed and unmanaged states are mapped to the platform accessibility APIs by the user agent.. In the following example, CSS selectors based on the value of the ARIA checked state are used to determine whether an image of a checked or an unchecked box is shown: *[aria-checked=true]:before {content: url('checked.gif')} *[aria-checked=false]:before {content: url('unchecked.gif')} In any application there must always be an element with focus, as applications require users to have a place to provide user input. The element with focus must never be destroyed, hidden or scrolled off-screen. All interactive elements should be focusable. There should be an obvious, discoverable way, either through tabbing or other standard navigation techniques, for keyboard users to move the focus to any interactive element they wish to interact with. See User Agent Accessibility Guidelines, Guideline 9 ([UAAG], Guideline 9). When using standard (X)HTML and basic WAI-ARIA widgets, application developers can simply manipulate the tab order or use script to create keyboard shortcuts to elements in the document. Use of more complex widgets requires the author to manage focus within them. WAI-ARIA includes a number of "managing container" widgets, also often referred to as "composite" widgets. Typically, the container is responsible for tracking the last descendant which was active (the default is usually the first item in the container). When the container is navigated to with the Tab key, focus goes directly to the last active descendant. The user may also activate the container by clicking on one of the descendants within it. When something in the container has focus, the user may navigate through the container by pressing additional keys such as the arrow keys to move relative to the current item. Any additional press of the main navigation key (generally the Tab key) will move out of the container to the next widget. For example, a grid may be used as a spreadsheet with thousands of gridcells, all of which may not be present in the document at one time. This requires their focus to be managed by the container using the activedescendant property, on the managing container element, or by the container managing the tabindex of its child elements and setting focus on the appropriate child. For more information, see Providing Keyboard Focus in WAI-ARIA Best Practices ([ARIA-PRACTICES], section 3.2). Containers that manage focus in this way are: Editorial Note: Content is expected to come from the ARIA User Agent Implementors Guide. There are things like focused, focusable, selected, selectable, checkable, etc. Certain roles also have to be treated specially.] provides detailed guidance on ARIA implementation methodology as well as references to sample code. First steps to making an application accessible: ARIA provides authors with the means to make the different elements in a Web application semantically rich. User agents use the role semantics to understand how to handle each element. Roles convey technology of changes to the semantics as well. The following steps are recommended as ARIA is applied to content: Use native markup when possible. Apply the appropriate roles from ARIA could confuse an assistive technology. This does not preclude an element being removed which has the role attribute set. Only states and properties may be changed for a given element. Preserve semantic structure. Build relationships Look for relationships between elements, and mark them using the most appropriate property or attribute. For example: If container A contains search results, and container B contains the search widgets, then mark each container as a region and set the controls property in region B to reference region A. See relationships in WAI-ARIA. Some relationships are determined automatically from the host language, such as by using the label tag in HTML. Set and properties in response to events] Synchronize the visual UI with accessibility states properties for supporting user: Look at the native mark up language There is no tree element in HTML that supports our behavior including expansion. If such an element existed, we should use that to take advantage of existing support. Since it does not, we will need to use roles. Finding the> <div role="group"> <!-- veggies children -> <div role="treeitem">Green</div> <div role="group"> <!-- green children --> <div role="treeitem">Asparagus</div> <div role="treeitem">Kale</div> <div role="treeitem">Leafy</div> <div role="group"> <!-- leafy children --> <div role="treeitem">Lettuce</div> <div role="treeitem">Kale</div> <div role="treeitem">Spinach</div> <div role="treeitem">Chard</div> </div> <!-- close leafy --> <div role="treeitem">Green beans</div> </div> <!-- close green --> <div role="treeitem">Legumes</div> <div role="treeitem">Yellow</div> <div role="group"> <!-- yellow children --> <div role="treeitem">Bell peppers</div> <div role="treeitem">Squash</div> </div> <!-- close yellow --> </div> <!-- close veggies --> </div> <-- close tree --> Sometimes a tree structure is not explicit via the DOM and logical structure of a page. In such cases the relationships must still be made explicit using the states and properties. In the following example, the owns property indicates that the item with id "yellowtreegroup" should be considered a child of the div element with the property, even though it is not a child in the DOM. <div role="treeitem" aria-Yellow<div> … <div id="yellowtreegroup" role="group"> <div role="treeitem">Bell peppers</div> <div role="treeitem">Squash</div> … </div> If the tree is not completely represented in the DOM at all times, don't use either the structured or owns methods. Instead use level, posinset and setsize. Use States, Properties in response to events Control the behavior of the element in response to user input events such as from the keyboard and the mouse as shown here: <div tabindex="-1" role="treeitem" aria-Yellow</div> Use device independent events with supporting JavaScript to handle user interaction: <div role="tree" tabindex="-1" onfocus="return treeItemFocus(event);" onclick="return treeItemEvent(event);" ondblclick="return treeItemEvent(event);" onkeydown="return treeItemEvent(event);"> Create JavaScript support to control the event driven behavior of the application. This section is normative. This specification indicates whether a section is normative or informative. Normative sections provide requirements that must be followed for an implementation to conform to this specification. The keywords MUST, MUST NOT, REQUIRED, SHALL, SHALL NOT, SHOULD, RECOMMENDED, MAY, and OPTIONAL in this document are to be interpreted as described in Key words. This section defines the WAI-ARIA role taxonomy and describes the characteristics and properties of all roles. A formal RDF representation of all the information presented here is available in Appendix 8.1: Implementation. The role taxonomy uses the following relationships to relate ARIA roles to each other and to concepts from other specifications, such as HTML and XForms. The role that this role extends in the taxonomy. This extension causes all the properties and constraints of the parent role to propagate to the child role. Other than well known stable specifications, inheritance may be restricted to items defined inside this specification so that items cannot be changed and affect inherited classes. For example: checkbox is a subclass or type of a option. If we change the properties and expected behavior of an option then the properties and behavior of checkbox will also change. Inheritance is expressed in RDF using the RDF Schema subClassOf ([RDFS], section 3.4) property. Informative list of roles for which this role is the parent. This is provided to facilitate reading of the specification but adds no new information as the list of child roles is the list of roles for which the current role is the parent. Informative information about a similar or related idea from other specifications. Concepts that are related are not necessarily identical. Related concepts do not inherit properties from each other. Hence if the definition of a type changes, the properties, behavior and definition of a related concept is not affected. For example: A grid is like a table. Therefore, a grid has a rdfs:seeAlso of table. However if the definition of table is modified, the ARIA definition of a grid will not be affected. Informative information about objects that are considered prototypes for the role. Base concept is similar to type, but without inheritance of limitations and properties. Base concepts are designed as a substitute for inheritance for external concepts. A base concept is like a relatedConcept except that base concepts are almost identical to each other. For example: the checkbox defined in this document has the same functionality and anticipated behavior as a checkbox defined in HTML. Therefore, a checkbox has an HTML checkbox as a baseConcept. However, if the HTML checkbox is modified, the definition of a checkbox in this document will not be not affected, because there is no actual inheritance of type.. Abstract roles are the foundation upon which all other ARIA roles are built. They MUST NOT be used by authors because they are not implemented in the API binding. Abstract roles are provided to help with the following: States and properties required for the role. Content authors MUST provide values for required states and properties. When an object inherits from multiple ancestors and one ancestor indicates that property is supported while another ancestor indicates that it is required, the property is required in the inheriting object. States and properties applicable to the role. User agents MUST support all supported states and properties for the role. Content authors MAY provide values for supported states and properties, but may not in all cases because default values are sufficient.. A child element that must be contained in the DOM by this role. A child element is any descendent element specified with the required child role. For example, an element with role list must contain an element with role listitem. When multiple required children are indicated, either of them are permitted. Context where this role is allowed, in other words, roles for elements in which the present role MUST appear. For example an element with role listitem MUST be contained inside an element with role list. Computational mechanism to determine the accessible name of the object to which the role applies. This may be computed from the descendants of the object or conditional text (e.g., the title attribute in HTML). User agents MUST use the following approach to compute the accessible name: Collect the name from the content subtrees pointed to by labelledby which contains the IDs for the label content. Use the IDs in the order they appear. For each ID, use a depth-first computation of the name, appending to the currently computed name. If labelledby is unspecified: Boolean (true | false) The DOM children are presentational. User agents SHOULD NOT expose descendants of this element through the platform accessibility API. If user agents do not hide the children, some information may be read twice. Some states and properties are applicable to all roles, and most are applicable to all elements regardless of role. In addition to explicitly expressed supported states and properties, the following global states and properties are supported by all roles as well. These include:.. Note: This is used for the ontology and authors must not use this role in content. widget A component of a Graphical User Interface (GUI). Widgets are discrete user interface elements with which the user can interact. Widget roles all map to standard features in accessibility APIs. Note: This is used for the ontology and authors must not use this role in content. structure A document structural element. Roles for document structure support the accessibility of dynamic Web content by helping assistive technology to determine active content vs. static document content. Structural roles by themselves do not all map to accessibility APIs, but are used to create widget roles or assist content adaptation. The taxonomy of structural roles is likely to evolve as new use cases are added to the scope of this specification. Note: This is used for the ontology and authors must not use this role in content. composite A widget that may contain navigable descendants or owned children. The composite widget SHOULD exist as a single navigation stop within the larger navigation system of the web page. Once the composite widget has focus, it SHOULD provide a separate navigation mechanism for users to document elements that are descendants or owned children of the composite element. Descendants of this role MUST NOT have the "nameFrom" value of "subtree" set. This role and its descendants must not have a childrenArePresentational value of "true". Note: This is used for the ontology and authors must not use this role in content. window Browser or application window. Elements with this role have a window-like behavior in a GUI context, regardless of whether they are implemented as a window in the OS. This is helpful when there is the visual appearance of a window that is merely a styled section of the document. Note: This is used for the ontology and authors must not use this role in content. These roles are common widgets used to collect and maintain user input. Roles in this section include: listbox. combobox Combobox is a presentation of a select, where users can type to select an item.. NOTE: In XForms . option checkbox radiogroup A group of radio buttons. A radiogroup is a type of select list that can only have single entries checked, not mutliple. User agents MUST enforce that only one radio button in a radiogroup can be checked at the same time. When another button is checked, previously checked buttons become unchecked (their checked state becomes "false"). radio An option in single-select list. Elements with role radio MUST be be explicitly grouped in order to indicate which ones affect the same value. This should be done by enclosing them in an element with role radiogroup. If it is not possible to make the radio buttons DOM children of the radiogroup, use the owns property on the radiogroup element to indicate the relationship. textbox. range Represents a range of values that can be set by the user. Note: This is used for the ontology and authors must not use this role in content. slider. spinbutton. These roles encompass features that usually are used as part of the graphical user interface. Roles in this section include: button. link Interactive reference to a resource. Activating the link causes the user agent to navigate to that resource.. menubar A container of menu items (items with role menuitem). The menubar role is used to create a menubar similar to those found in Windows, the Mac, and Gnome desktops. A menubar is used to create a consistent climate of frequently used commands. Navigation behavior SHOULD be similar to the typical menu bar graphical user interface. Instances of this role MUST manage focus of descendants, as described in Managing Focus. toolbar. Instances of this role MUST manage focus of descendants, as described in Managing Focus. menuitem menuitemcheckbox menuitemradio Indicates a menuitem which is part of a group of menuitemradio roles, only one of which can be checked at a time. User agents MUST enforce that only one menuitemradio in a group can be checked at the same time. When another widget is checked, previously checked widget become unchecked (their checked state becomes "false"). Menu items SHOULD be in an element with role menu in order to identify that they are related widgets, and MAY also be separated into a group by a separator, or an element with an equivalent role from the native markup language. tooltip A popup that displays a description for an element when a user passes over or rests on that element. Supplement to the normal tooltip processing of the user agent. Objects with this role should be referenced through the use of describedby, at latest by the time the tooltip is displayed. tabpanel A container for the resources associated with a tab. Note: There MUST be a means to associate a tabpanel element with its associated tab in a tablist. Using the labelledby property on the tabpanel to reference the tab is the recommended way to achieve this. For detailed information about how to use tab panels, see the TabPanel Widget in WAI-ARIA Best Practices ([ARIA-PRACTICES], Section 9.2). tablist A list of tabs, which are references to tabpanels. Instances of this role MUST manage focus of descendants, as described in Managing Focus. tab tab is used as a grouping label, providing a link for selecting the tab content to be rendered to the user. If the tab or an object in the associated tabpanel has focus, the tab is the active one in the list. One (and only one) of the tabs in the tablist MUST be the current tab. The tabpanel associated with the current tab MUST be rendered to the user. Other tabpanels SHOULD be hidden from the user until the user selects the tab associated with that tabpanel. User agents manage the determination and indication of the current tab. There is no property in the taxonomy for this. tree A form of a list having groups inside groups, where sub trees can be collapsed and expanded. Instances of this role MUST manage focus of descendants, as described in Managing Focus. These roles describe the structures that organize content in a page. In contrast to widgets, structures are not usually interactive. However, they can be in certain circumstances. Roles in this section include: section A renderable structural containment unit in a document or application. Note: This is used for the ontology and authors must not use this role in content. sectionhead Labels or summarizes the topic of its related section. Note: This is used for the ontology and authors must not use this role in content. document Content that contains related information. The document role informs screen readers of the need to augment browser keyboard support in order to allow users to visit and read any content within the document region. In contrast, additional commands are not necessary for screen reader users to read text withn a region with role="application", where all text should be semantically associated with focusable elements. An important trait of documents is that they have some text which is not associated with widgets or groups thereof. To properly set the role of document, an author should set the document role on an element which encompasses the entirety of the region for which assistive technology browser navigation mode is applied.If it applies to the entire Web page, it should be set on the root note for content, e.g., body in HTML or svg in SVG. Documents; documentrole may have a labelledby property referencing one or more elements with non-empty text content. region Region is a large perceivable section on the web page. This role defines a group of elements that together form a large perceivable section, that the author feels should be included in a summary of page features. A region MUST have a heading, provided via an instance of the heading role or using the labelledby property to reference an element. A region does not necessarily follow the logical structure of the content, but follows the perceivable structure of the page. When defining regions of a web page, authors should consider using standard document landmark roles. If the definition of these regions are inadequate, authors should use the. list group A section of user interface objects which would not be included in a page summary or table of contents by an assistive technology. Contrast with region which is sections of user interface objects that should. Therefore, proper handling of group by assistive technologies must be determined by the context in which it is provided. Groups may also be nested. If the author believes a section is significant enough in terms of the entire delivery unit web page then the author should assign the section a role of region or a standard landmark role. Group members that are outside the DOM subtree of the group would need to have explicit relationships assigned to participate in the group using the owns property. grid A grid contains cells of tabular data arranged in rows and columns (e.g., a table). This does not necessarily imply presentation. The grid construct describes relationships between data such that it may be used for different presentations. Grids allow the user to move focus between grid cells with two dimensional navigation. Grids MUST contain rows with role row, which in turn contain cells. Grid cells may be focusable. Grids MAY have row and column headers, provided with rowheader and columnheader roles, which also assist the user agent in supporting navigation. Grid cells MAY have contents determined by a calculation. Grid cells with the selected state set can be selected for user interaction, and multiple cells can be selected if the multiselectable property of the grid is true. Grids may be used for spreadsheets like those in Open Office, Microsoft Office, etc. Instances of this role MUST manage focus of descendants, as described in Managing Focus. row gridcell A cell in a grid. Grid cell may be active, editable, and selectable. Cells may have relationships such as controls to address the application of functional relationships. Grid cells should explicitly indicate which header cells are relevant to them. They do this by referencing elements with role rowheader or columnheader using the describedby property. In a treegrid, cells MAY be expandable and use the expanded state. column. It is a structural equivalent to an HTML th element with a "column" scope. Note: because grid cells are organized into rows, there is not a single container element for the column. The column is the set of gridcells in a particular position within their respective row containers. treegrid A grid whose rows can be expanded and collapsed in the same manner as for a tree. Instances of this role MUST manage focus of descendants, as described in Managing Focus. description Descriptive content for a page element. A description MUST be referenced from the element it describes via describedby. directory A list of references to members of a single group. Authors SHOULD use this role for static tables of contents. This includes tables of contents built with lists, including nested lists. Dynamic tables of contents, however, would be a tree. Note: directories do not have to contain links. They can have simply unlinked references. img. Elements with a role of img MUST have alternative text or a label associated via the labelledby property. presentation An element whose role is decorative, not meaningful, and does not need to be mapped to the accessibility API. The intended use is when an element is used to change the look of the page but does not have all the functional, interactive, or structural relevance implied by the element type. Example use cases: objectin HTML whose content is decorative like a white space image or decorative object; divin HTML used to force line breaks before and after its contents. The user agent MAY choose not to present all structural aspects of the element being repurposed. For example, for a table marked as presentation, the user agent would remove the table, td, th, tr, etc. elements from the accessibility API mapping, while preserving the individual text elements within them. Because the user agent knows to ignore the structural aspects implied in a table, no harm is done by using a table for layout. User agents should ignore elements with the presentation role for the purpose of determining the containment of items with ARIA roles. For example, in the following code sample: <ul role="group"> <li role="presentation"> <a role="presentation>...</a> </li> </ul> the a should be considered a child of the ul element with the group role. separator A line or bar that separates and distinguishes sections of content. This is a visual separator between sections of content. For example, separators are found between groups of menu items in a menu.. These are special types of self-contained aspects of the user interface. Roles in this section include: application A software unit executing a set of tasks for its users. The intent is to hint to the assistive technology to switch its normal browsing mode functionality to one in which they would for an application. Screen readers have a browse navigation mode where keys, such as up and down arrows, are used to browse the document. This breaks use of these keys by a web application. To properly set the role of application, an author should set the application role on an element which encompasses the entirety of the region for which assistive technology browser navigation mode is applied. If it applies to the entire Web page, it should be set on the root node for content, e.g., body in HTML or svg in SVG. For example, an email application has a document and an application in it. The author would want to use typical application navigation mode to cycle through the list of emails. Much of this navigation would be defined by the application author. However, when reading an email message the content should appear in a region with a document role in order to use browsing navigation. All non-decorative static text or image content inside the application must be either associated with a form widget or group via labelledby or describedby, or separated out into an element with role of document or article of its own. Applications; applicationrole may have a labelledby property referencing one or more elements with non-empty text content. dialog A dialog is a small application window that sits above the application and is designed to interrupt the current processing of an application in order to prompt the user to enter information or require a response. Dialog boxes SHOULD have a title, which may be provided with a labelledby property if other mechanisms are not available. They MUST have a focused item, i.e., a descendant element that has the keyboard focus, which is managed by the user agent. alert. alertdialog. marquee A marquee is used to scroll text across the page. A common usage is a stock ticker. A marquee behaves like a live region, with an assumed default live property value of "off". An example of a marquee is a stock ticker. A major difference between a marquee and a log is how fast it gets updates from timed or real world events. log A region where new information is added. status Container for processing advisory information to give feedback to the user. A status object must have content within it to provide the actual status information. This object SHOULD NOT receive focus. Status is a form of live region. Its assumed default value for the live property is "polite". If another part of the page controls what appears in the status, the relationship should be made explicit with the controls property. Some cells of a Braille display MAY be reserved to render the status. progressbar Displays the execution status for tasks that take a long time to execute. This lets the user know that the user's action request has been accepted and that the application continues (or ceases, in the case of a static display) to make progress toward completing the requested action. The author should supply values for valuenow, valuemin, and valuemax, unless the value is indeterminate in which the property should be omitted. These values should be updated when the visual progress indicator is updated. If the progressbar is describing the loading progress of a particular region of a page, the author SHOULD use describedby to point to the status, and set the busy state to "true" on the region until it is finished loading. timer A numerical counter which indicates an amount of elapsed time from a start point, or the time remaining until an end point. The text contents of the timer object indicate the current time measurement, and are updated as that amount changes. However, the timer value is not necessarily machine parsable. The text contents MUST be updated at fixed intervals, except when the timer is paused or reaches an end-point. A timer is a form of live region. The default value of live for timer is "off".. banner A region that contains the prime heading or internal title of a page.. complementary Any section of the document that supports but is separable from the main content, but is meaningful on its own even when separated from it.. contentinfo Meta information which applies to the first immediate ancestor whose role is not presentation. In the context of the page this would apply to a section or the page of which it is the child. For example, footnotes, copyrights, links to privacy statements, etc. would belong here. main Main content in a document. This marks the content that is directly related to or expands upon the central topic of the page. navigation A collection of links suitable for use when navigating the document or related documents.. Editorial Note: The Working Group has not yet decided whether to identify states and properties with the literal attribute names (e.g., aria-busy) as implemented in host languages, or continue to use short names without the 'aria-' prefix (e.g., busy). States and properties have the following characteristics: Advisory information about features from this or other languages that correspond to this state or property. While the correspondence may not be exact, it is useful to help understand the intent of the state or property. restrictions for the state or property. These restrictions are expressed in terms of XML Schema Datatypes [XSD]. The following XSD Datatypes are used in this specification. Values of type boolean, NMTOKEN, and NMTOKENS are further explained by listing the allowed values and their meanings below the table of characteristics. When a value is indicated as the default, the behavior prescribed by this value MUST be followed when the state or property is not provided. Some roles also define what behavior to use when certain states or properties, that do not have default values, are not provided. Note: in the XHTML module, value restrictions are necessarily expressed in DTD notation, not XSD. DTD notation does not provide the precise value restrictions supported by XSD, and therefore the values in the DTD often have a wider scope of allowed values than what is actually allowed by this specification. Implementers MUST be sure to observe the value restrictions defined here and not rely simply on DTD validation. States and properties are categorized as follows: Below is an alphabetical list of ARIA states and properties to be used by rich internet application authors. A detailed definition of the taxonomy supporting these ARIA states and properties follows. States: Properties: This section contains states specific to common user interface elements found on GUI systems or in rich Internet applications which receive user input and process user actions. These states are used to support the user input and user interface roles. Widget states and properties might be mapped by a user agent to platform accessibility API states, for access by an assistive technology, or they might be accessed directly from the DOM. Changes in states MUST result in a notification to an assistive technology either through DOM attribute change events or platform accessibility API events. States and properties in this section include: autocom Indicates the value of a binary or ternary (tri-state) widget such as a checkbox or radio button. The action when a mixed button is activated is covered in WAI-ARIA Best Practices [ARIA-PRACTICES] disabled Indicates that the widget is present, but the value cannot be set. For example, irrelevant options in a radio group may be disabled. Disabled elements might not receive focus from the tab order. For some disabled elements, applications might choose not to support navigation to descendants. There SHOULD be a change of appearance to indicate that the item has been disabled (grayed out, etc.). The state of being disabled applies to the current element and all focusable descendant elements of the element on which the disabled state is applied. expanded Indicates whether an expandable/collapsible group of elements is currently expanded or collapsed. For example, this indicates whether a portion of a tree is expanded or collapsed. haspopup Indicates that the element may launch a pop-up window such as a context menu or submenu. This means that activation renders conditional content. Note that ordinary tooltips are not considered popups in this context. The drop-down options in a combobox are also not popups in this sense. A popup is generally presented visually as a bordered group of items that appears to be on top of the main page content. If possible, the entire popup should be visible when it opens (not partially offscreen). invalid. level. This property MUST be applied to leaf nodes (elements that would receive focus), not to the parent grouping element, even when all siblings are at the same level. This means that multiple elements in a set may have the same value for this property. Although it would be less repetitive to provide a single value on the container, it is not always possible for authors to do so. Restricting this to leaf nodes ensures that there is a single way for assistive technology to use the property. If the DOM ancestry accurately represents the level, the user agent can calculate the level of an item from the document structure. This property can be used to provide an explicit indication of the level when that is not possible to calculate from the document structure or the owns property. User agent automatic support for automatic calculation of level may vary; authors should test with user agents and assistive technologies to determine whether this property is needed. If the author intends for the user agent to calculate the level, they MUST omit this property. multiline Indicates whether a text box accepts only a single line, or if it can accept multiline input. There is very little difference in ARIA between single-line and multi-line text boxes, as both allow arbitrary text input. The main reason to indicate this is to warn of different behaviors of the enter key. In a multi-line text box, the enter key adds a new line; in a single-line text box, it does not and may activate a function outside the text box such as submitting the form. multiselectable Indicates that the user may select more than one item from the current selectable descendants. Lists, trees, and grids may allow users to select more than one item at a time. Descendants that are selected are indicated with the selected state set to "true". Descendants that are selectable but not selected are indicated with the selected state set to "false". Descendants that are not selectable should not set the selected state. pressed Used for toggle buttons to indicate their current pressed state. Toggle buttons require a full press and release cycle to toggle their value. Activating it once changes the pressed state to "true", and activating it another time changes the pressed state back to "false". A value of "mixed" means that the states of more than one item controlled by the button do not all share the same value; the action when a mixed button is activtate is covered in WAI-ARIA Best Practices [ARIA-PRACTICES]. If the state is not present, the value defaults to "undefined" meaning. This is in contrast to disabled objects for which applications might choose not to allow users to navigate to descendants. Examples include: required Indicates that user input is required on the widget before a form may be submitted. For example, if a user must fill in an address field, then required is set to "true". Note: the fact that the element is required is often visually presented (such as a sign or symbol after the widget). Using the required attribute makes it much easier for user agents to pass on this important information to the user. The required property applies only to the element on which it is applied. The property of being required does not propogate either to descendant elements nor to ancestor elements. selected Sets whether the user has selected an item or not. Selecting an element indicates that it is chosen for an action, and most likely has focus. However, this does not imply anything about other states. This property is used in two cases: selectedwhen the focused item is not in fact selected. The only useful value is "false" because otherwise the currently focused item is considered to be selected. selectedstate. valuemax Maximum allowed value for a range type of widget. A range widget may start with a given value, which can be increased until a maximum value, defined by this property, is reached. Declaring the valuemax will allowemin Minimum allowed value for a range type of widget. A range widget may start with a given value, which can be decreased until a minimum value, defined by this property, is reached. Declaring the valuemin allowsenow The current value of a widget. Used, for example, for a range widget. valuetext. This section contains properties specific to live regions in rich Internet applications. These properties may be applied to any element. The purpose of these properties is to indicate that changes to the section on which they are applied may occur without it having focus, and to provide the assistive technology information on how to process live updates in this section of the page. Some roles specify a default value for the live property specific to that role. Examples of live regions include: States and properties in this section include: atomic Indicates if the assistive technology should present all or part of the changed region to the user when the region is updated. Both accessibility APIs and the Document Object Model [DOM] provide events to allow the assistive technology to determine changed areas of the document. When a node changes, the AT SHOULD look at the changed element and then traverse the ancestors to find the first element with atomic set, and apply the appropriate behavior for the cases below. atomic, the default is that atomicis "false", and the AT only needs to present the changed node to the user. atomicis explicitly set to "false", then the AT can stop searching up the ancestor chain, and should present only the changed node to the user. atomicis explicitly set to "true", then the AT should present the entire subtree of the element on which atomicwas set. When atomic is true, the AT MAY choose to combine several changes and present the entire changed region at once. If the region contains only a single data field and a label, then labelledby can be used instead of atomic, to ensure the entire region is spoken during a change." or remove the attribute when the last part is loaded. If there is an error updating the live region, set the invalid property to "true". channel Specifies that an alternate method of presentation is recommended, possibly but not necessarily in parallel with other live events. The default channel (which is a value of the live property). If the events from the two channels are of differing politeness levels, the channel with the higher priority event SHOULD have higher priority than the other channel. Events from one channel MUST NOT interrupt or clear out events on another channel. live Describes the types of updates the user agent, assistive technology, and user can expect from. When the property is not set on an object that needs to send updates, the politeness level is inherited from the value of the nearest ancestor that sets the live property. relevant Indicates the nature of change within a live region. The property relevant should be set to "all". When the relevant property is not provided, the default is to assume that text changes and node additions are relevant, and that node removals are not relevant. relevant is an optional property of live regions within a document. It does not restrict how an assistive technology processes attributes. This is a hint to the AT, but the AT is still not required to present changes of all the relevant types. Both accessibility APIs and the Document Object Model [DOM] provide events to allow the assistive technology to determine changed areas of the document. When this value is not set, the value inherits from an object's nearest ancestor. It is not additive, meaning the set of values provided and omitted. For more information about using drag and drop, see Drag-and-Drop Support in the ARIA Best Practices ([ARIA-PRACTICES], Section 7). States and properties in this section include: dropeffect Shows the effect on the target of a drag and drop operation when the dragged object is released. More than one drop effect may be supported for a given element. Therefore, the value of this state is a space-delimited set of tokens indicating the possible effects, or "none" if there is no supported operation. This state also allows authors to use a style sheet to provide a visual indication of the target (e.g., highlight it) during drag operations. If only one type of operation is supported, it can be set at page load. This section defines relationships or associations between elements which cannot be readily determined from the document structure. States and properties in this section include: activedescendant Identifies the current active child of a composite widget. This is used when a composite widget is responsible for managing its current active child to reduce the overhead of having all children be focusable. Examples include: multi-level lists, trees, spreadsheets. Authors SHOULD ensure that the object targeted by the activedescendant property is either a descendant of the container in the DOM, or is a logical descendant as indicated by the owns property. The user agent is not expected to check that the activedescendant is an actual descendant of the container. Authors SHOULD ensure that the currently activedescendant is currently visible in the viewport (not scrolled off). Authors SHOULD capture changes to the activedescendant property, which can occur if the AT sets focus directly. controls Defines the elements and subtrees whose contents or presence are controlled by the current element. For example: describedby Points to an element which describes the object. This is very similar to labeling an object with labelledby. A label should provide the user with the essence of the what the object does, whereas a description is intended to provide additional information that some users might need. flowto Establishes the recommended reading order of content, overriding the general default to read in document order. When flowto has a single IDREF, it instructs assistive technology to skip normal document reading order and go to the targeted object. Flowto in subsequent elements would follow a process similar to next focus in XHTML2 ([XHTML], Section 13). However, when flowto is provided with multiple IDs, then they should be processed as path choices by the AT, such as in a model based authoring tool. This means that the user SHOULD be given the option of navigating to any of the elements targeted. The name of the path can be determined by the name of the target element of the flowto. Accessibility APIs can provide named path relationships. labelledby a parent/child relationship among elements where the DOM hierarchy cannot be used to represent the relationship. The relationship may represent a visual and functional association between elements that is not defined by any DOM parent/child hierarchy. The value of the owns attribute is a space-separated list of IDREFs; that is, unique identifiers that reference one or more elements in the document. Each of the latter elements have an 'id' attribute that matches one of the values in the list of IDREFs. The reason for adding owns is to expose parent/child relationships to an AT that would otherwise be missed. In that sense owns is more important than DOM-parentage. It publicizes a relationship that is otherwise difficult or impossible to infer from the DOM. Authors MUST NOT use owns as a replacement for the DOM hierarchy. That is, if the relationship is captured by the DOM, then do not use owns. Refers to the number of items in the current level of a list or tree. For example, if this element is in a group of six items at the same level then setsize is equal to six. Setsize must be >= 1. This property is marked on the members of a set, not the container element that collects the members of the set. To orient a user to a particular element by saying it is "item N out of M", the client software would use N equal to the posinset property on the element and M equal to the setsize property on that particular element.. Setsize SHOULD be used together with posinset. This section defines properties that affect or describe the rendering of the user interface. States and properties in this section include: hidden Defines whether or not the object is visible to the user. For example, if a menu is only visible after some user action, the hidden property should be set to "true" until the menu is presented, at which time the hidden property would be removed, indicating that the menu is visible. some browsers at the time of this writing. It may be necessary to set the style using script. This section is normative. This section is informative. The roles, states, and properties defined in this specification do not form a whole web language or format. They are intended to be used in the context of a profile based on some host language or other. This section discusses what host languages should do to implement WAI-ARIA, that is to say assure that the markup specified here will integrate smoothly and effectively with their markup in instances of their format. Although markup languages superficially look alike, they do not all share much by way of language-definition infrastructure. To accomodate differences in language-building approaches, the requirements here have been set out at two levels, general, and modualrization-specific. While allowing for differences in how the specifications are written, we believe we have maintained consistency in how the WAI-ARIA information looks to authors and how it is manipulated in the DOM by scripts. name of the state or property. An implementing host language MUST allow attributes as follows: Editorial Note: Following the Namespaces Recommendation [XML-NAMES], the namespace name for these attributes "has no value". The names of these attributes do not have a prefix set off. An implementing host language MUST provide support for Editorial note: do we have to move the user capability to navigate the focus to a User Agent requirement? What is the role of the host language in this? Host languages can be constructed using the methods of the W3C Recommendation Modularization in XHTML [@@ref2m12n]. Host languages that are constructed following this Recommendation MUST implement the abstract module comprising the attributes defined in section 5. above using a module implementation provided in this specification. Appendix 8.1.2 below provides an implementation of this module as a DTD module. Appendix 8.1.3 below is a sample DTD integrating a language profile that implements WAI-ARIA by including the DTD module. Note how the applicability of the tabindex attribute has been extended to satisfy 6.2.3 above. Editorial Note: The URIs to be used to identify the module are still under discussion. This section sets out normative conditions for conforming document instances and user agent processors, along with informative remarks about the role of other processors such as authoring tools and assistive technologies. This section is normative. This section is informative. W3C publishes Authoring Tool Accessibility Guidelines [ATAG1]. These documents apply to web-content producing tools including those used for producing ARIA-using content. Many of the requirements in the definitions of ARIA roles, states and properties can be checked mechanically, although not all. Authoring tools can contribute to the successful use of ARIA markup by offering their users conformance checking modes or operations that screen for the satisfaction of 7.1.1 and 7.1.2 above. Until such time as a body of good, common practice has been established and confirmed by widespread accessible use, authoring tools would be well advised to pattern their prompting and coaching of authors after the practices in the Best Practices Guide [ARIA-PRACTICES]. The accessibility of interactive content cannot be confirmed by static checks alone. Developers of interactive content should test for (a) device independent access to the operations of the widgets and applications, and (b) display and API visibility into all states and changes of the widgets and applications during user interaction. More detailed and current suggestions about authoring and testing tools and methods may be found in the latest version of the Best Practices Guide [ARIA-PRACTICES]. This section is normative. WAI-ARIA processing by the User Agent MUST not interfere with the normal operation of the built-in features of the host language. This includes but is not limited to the construction of a DOM from a text string.In applying this rule, however, scripted changes in the DOM of the document and style rules which change the presentation of the content based on selectors sensitive to ARIA markup MUST be considered as part of normal operation. On the other hand, the mapping to accessibility APIs MUST be considered, in applying this rule, to be above and beyond normal operation. The ARIA processing MAY alter the mapping of the host language features into an accessibility API. But the mapping to the API MUST not alter the DOM of the document. in section 4 above except (1) abstract roles, that is roles for which isAbstract is True and (2) the roles imported from the Role Module, that is those that are introduced in sections 4.4.6 and 4.4.7. As a result, a host language element will have one and only one applicable ARIA role if it has a role attribute and at least one of the tokens in the value of this role attribute matches the name of a concrete ARIA role. It will have zero applicable ARIA roles if it does not have a role attribute, or if the role attribute contains no tokens matching the name of a concrete ARIA role. The applicable ARIA role, if there is one, MUST be the role value which is mapped to the value of a role property in any accessibility API which accepts only one role value. User agents MUST use an explicit applicable ARIA role as overriding any implicit role inferred from the host language markup in performing this mapping. Note that, in conformance with section 7.3.1 above, this overriding does not result in any changes in the DOM, only in the accessibility API representation of the document. A conforming User Agent which implements a Document Object Model per the W3C Recommendations MUST include the entire "role" attribute value in the DOM and all ARIA states and properties in the document instance in the corresponding DOM. Editorial Note: User agents SHOULD expose role, state, and property information provided by the author to accessibility APIs available in their operating platform.. Editorial Note: The working group is tracking issues around the question of how much about the API bindings should be normative and MUST, and how much they should be incorporated in this specification. These issues have not been resolved by the Working Group. This section is informative. Assistive technologies should use available role, state and property information to present content to, and support interaction with, users in a manner, a user experience, appropriate to their users. This requirement parallels User Agent Accessibility Guidelines 1.0 Section 6.5: Programmatic operation of user agent user interface and Section 6.6: Programmatic notification of changes ([UAAG], Section 6.5 and 6.6) except that it applies to content, not just the user agent itself.==-->="rdfs:seeAlso"/> <: <From"> : </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:supportedState rdf: </owl:Class> <!--== User Input Widgets ==--><owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <rdfs:seeAlso rdf: <role:mustContain rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:baseConcept rdf: <rdfs:seeAlso rdf: <rdfs:seeAlso rdf: <role:supportedState rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <rdfs:seeAlso rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:mustContain rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <rdfs:seeAlso rdf: <role:supportedState rdf: <role:supportedState rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:supportedState rdf: <role:supportedState rdf: <role:supportedState rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf: <role:mustContain rdf: <role:mustContain rdf: <role:mustContain rdf: <: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <role:mustContain: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:subClassOf rdf: <role:scope rdf: </owl:Class> <!--== Document Structure ==--><owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <rdfs:seeAlso: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:seeAlso rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <rdfs:subClassOf rdf: <role:baseConcept rdf: <role:mustContain rdf: <role:supportedState rdf: <role:supportedState rdf: <role:supportedState rdf: </owl:Class> <owl:Class rdf: <rdfs:subClassOf rdf: <role:baseConcept rdf:resource="
http://www.w3.org/TR/2008/WD-wai-aria-20080806/
crawl-002
en
refinedweb
ASP.NET and .NET from a new perspective Part 1: Dynamic vs. StaticPart 2: Creating Dynamic ControlsPart 3: Adding Dynamic Controls to the Control TreePart 4: Because you don't know what to render at design time Creating a dynamic control isn't just about "newing" one up. There are several different types of dynamic controls. There are also several different ways that dynamic controls can manifest themselves in your page's control tree, sometimes when you don't even realize it. As promised, understanding this will not only increase your understanding of dynamic controls, but of ASP.NET in general. But no matter what kind of control it is (dynamic or otherwise), they all share the same base class: System.Web.UI.Control. All built-in controls, custom server controls, and user controls share this base class. Even the System.Web.UI.Page class derives from it. This section will focus very specifically on how dynamic controls are created. So the following code samples aren't really complete. Just creating a control dynamically isn't enough to get it participating in the page life cycle because it must be added to the control tree. But I like focusing in one thing at a time. Fully understanding something makes it easier to understand something that builds on it, because you can make assumptions and focus on the new functionality. Dynamically creating Server Controls TextBox tb = new TextBox(); There's not much to them. All the built-in controls are Server Controls, and so are any controls you create yourself that inherit from Control, WebControl, CompositeControl, etc. Dynamically creating User Controls First lets create a hypothetical user control: <%@ Control Language="C#" AutoEventWireup="true" CodeFile="MyUserControl.ascx.cs" Inherits="MyUserControl" %> Your name: <asp:TextBox A user control is not unlike a regular ASPX webform in that the ASCX contains markup that declares "static controls", and inherits from a code-behind class, and that code-behind class itself may or may not load dynamic controls. Assuming this ASCX file were placed into the root of the application (denoted by "~/"), we could dynamically load it like this: Control c = this.LoadControl("~/MyUserControl.ascx"); You might wonder why there's a difference in loading server controls and user controls. Why can't we create a user control just like a server control? This user control has a code-behind class "MyUserControl", so why can't we do this: MyUserControl c = new MyUserControl(); // no! I invented a new code sample CSS style just to illustrate this. Blue means good. Red means bad. You definitely can't create a user control like this. In Part 1 remember we examined how the page parser converts your markup into a class that inherits from your code-behind class? And remember that the generated code creates the controls, adds them to the control tree, and assigns them to your code-behind's control variables that are declared as protected? User Controls work the same way. By creating the code-behind class directly you have effectively by-passed this whole process. The result will be an instance of your control with no control tree. Your control definitely won't work, and will probably result in a NullReferenceException the first time your code actually tries to use any of the controls (because, well, they're null). That is why the "LoadControl" method exists, and that is why the actual ASCX file must stick around. LoadControl retrieves and instantiates the type of the auto-generated code created from your markup. The path given to LoadControl must be the virtual path to the ASCX file. Physical paths aren't allowed. The virtual path can take on one of three forms. Lets assume the application is running under virtual directory name "Truly" (in other words, represents the root of the application). The three forms are: Control c; c = this.LoadControl("MyUserControl.ascx"); // relative c = this.LoadControl("./MyUserControl.ascx"); // relative c = this.LoadControl("~/MyUserControl.ascx"); // app relative c = this.LoadControl("/Truly/MyUserControl.ascx"); // root relative Whatever the case, the virtual path must map inside the current application. No loading user controls that reside in other applications. So a root-relative path better map back into the current application ("Truly"), or you will get an error. Relative paths are relative to the current page, or the current user control. That is important to know, because if you write a user control that loads another user control dynamically, you should know the difference between these: c = this.LoadControl("AnotherUserControl"); c = this.Page.LoadControl("AnotherUserControl"); The path is relative to the control you call the method on. The first line loads a control that exists in the same directory as the current user control. The second line loads a control that exists in the same directory as the current page, and the two don't have to be the same. Don't assume your user control is going to live in a particular location. It might be moved around. Really you have the same problem with Page.LoadControl, because you don't really know where in the directory structure the page loading your control will be. It's usually best to keep user controls in one location, or at least segregated into multiple "silos" that logically separate them. That way you can always use a relative path like in the first line, yet you still have the freedom to move the controls around, just as long as you move them together. Pages that reference the controls will just have to know where they are, at least relatively. You could also consider making the path to it configurable (via a property), use a web.config setting (less favorable), or use an app-relative path (ie, "~/UserControls/MyUserControl.ascx") and make the location known and unchangeable. Dynamically creating Parsed Controls The ParseControl method is even more dynamic. It takes a string of markup and converts it into a control: c = this.ParseControl("Enter your name: <asp:TextBox"); The string can contain virtually anything you can put on a page (disclaimer: I say virtually, because while I don't know of a limitation, there may be one. If anyone reading this knows of a limitation let me know). All of the controls contained within will be put together into a single control, where it's control tree contains the parsed controls. Parsed controls are interesting, but use them very carefully. Parsed controls carry a performance burden, because the string must be re-parsed every time. Normally the parsed result of pages or user controls is cached. Here's a dramatic demonstration of the performance hit. Here we create the same user control over and over again (1 million times): start = DateTime.Now; for(int i = 0; i < 1000000; i++) { c = this.LoadControl("UserControls/MyUserControl.ascx"); } end = DateTime.Now; Response.Write((end - start).TotalSeconds); And here we parse the content of the user control as a string over and over again: c = this.ParseControl( "Enter your name: <asp:TextBox"); And here are the results: ParseControl took 253 seconds, loading the user control only took 19 seconds. That's a huge difference. Running ParseControl 1 million times in 253 seconds is still not a major performance issue (you're likely to have much more significant bottle necks in your application), but your mileage may vary, and you can't deny the performance results. Use it very sparingly. And definitely don't parse a string that came from a potentially malicious user! You would be enabling them to create any control that is available in the application, and they could use that to attack your site. Any virtual paths you use inside the string follow the same rules as in the user control example. Relative paths are relative to the location of the control (or page) which you call ParseControl on. So there's that same subtle but important difference between the UserControl.ParseControl method and the Page.ParseControl method. Dynamic Controls and Templates There's another sneaky way that dynamic controls can be created. You have likely used templates without even realizing it. This topic is critical because if you understand how templates are used in databound controls like the Repeater, DataGrid, GridView, etc, then you will better recognize times where you may be approaching a problem with dynamic controls when you really don't have to. Later on there will be a section all about those situations. Templates decrease the need for you to create dynamic controls manually because they let you declaratively define a "template" by which controls will be created dynamically for you. The Repeater control for example lets you define an ItemTemplate and optionally an AlternatingItemTemplate. Within the template you declaratively define controls: <asp:Repeater <ItemTemplate> Your name: <asp:TextBox </ItemTemplate> </asp:Repeater> The template contains a TextBox server control. Do you think the page that this repeater sits on has this TextBox, just like in our simple UserControl above? Do you think you can access this TextBox like this? protected override void OnLoad(EventArgs e) { this.txtName.Text = "foo"; // no! base.OnLoad(e); No no no. Remember -- red means bad. The TextBox you declared does not exist on the page, at all. There is no "build control" method generated for it, and it will not be assigned to any protected class variables you define (as described in Part 1). Think about it for a minute. It doesn't even make sense for the TextBox to be accessible from the page like a regular statically declared control. The Repeater is going to be creating this TextBox once for every DataItem that is data bound to it. So there will be many of these on the page -- anywhere between 0 and N of them in fact. So if there were a page-level reference to it, which one would it point to? It doesn't make any sense. When you declare a regular static controls, you are telling the framework "here is a control I'd like you to create and add to the page's control tree." When you define a template, you are saying "here is a control tree that I would like added to the page's control tree when the template is used." In the case of a repeater, the template is used once for every data item. But Templates don't have to be used that way (for example, the System.Web.UI.WebControls.Login control's LayoutTemplate property is a Template that isn't repeated). It's up to the control's implementation how the template is utilized. Instead, the markup within the Template is parsed into an object that implements the System.Web.UI.ITemplate interface. Let's take a look at what code is generated for the static repeater in the example above: private global::System.Web.UI.WebControls.Repeater @__BuildControlrpt1() { global::System.Web.UI.WebControls.Repeater @__ctrl; #line 12 "C:\projects\Truly\MyPage.aspx" @__ctrl = new global::System.Web.UI.WebControls.Repeater(); #line default #line hidden this.rpt1 = @__ctrl; @__ctrl.ItemTemplate = new System.Web.UI.CompiledTemplateBuilder( new System.Web.UI.BuildTemplateMethod(this.@__BuildControl__control4)); @__ctrl.ID = "rpt1"; return @__ctrl; Pay particular attention to the middle of this method. The repeater control has a property named ItemTemplate (which happens to accept objects of type ITemplate). The parser's generated code is creating a new CompiledTemplateBuilder and passing in a BuildTemplateMethod Delegate to it's constructor. The delegate is pointed at a method defined on this page, which happens to be this "build control" method: private void @__BuildControl__control4(System.Web.UI.Control @__ctrl) { System.Web.UI.IParserAccessor @__parser = ((System.Web.UI.IParserAccessor)(@__ctrl)); @__parser.AddParsedSubObject(new System.Web.UI.LiteralControl("\r\n Your name: ")); global::System.Web.UI.WebControls.TextBox @__ctrl1; @__ctrl1 = this.@__BuildControl__control5(); @__parser.AddParsedSubObject(@__ctrl1); @__parser.AddParsedSubObject(new System.Web.UI.LiteralControl(" \r\n ")); This "build control" auto-generated method is responsible for building the control tree that we declared within the repeater's ItemTemplate. As you can see, it creates a literal control, then calls the TextBox's build control method to create it, and then creates another literal control (the literal controls represent the non-server-control markup before and after the TextBox). But this method isn't actually called from anywhere. It's simply the target of a Delegate, which was passed to the CompiledTemplateBuilder. So we haven't figured out yet exactly how the controls get into the control tree. That's because it's up to the control containing the template to do something with the template. The page parser has done it's job. Now it's up to the repeater to do something about it. And of course, we already know the repeater "uses" it once for each data item. To see exactly how it uses it, lets look at the ITemplate interface: public interface ITemplate { void InstantiateIn(Control container); That's the entire interface. Just one method. The idea is that you have this control tree template, and when you need to instantiate it -- when you need to create an actual control tree based on the template (not unlike the relationship between a Class and an Instance of a Class) -- you call InstantiateIn(). The control tree is then created and added to the container you give it. So we can summarize Repeater's use of templates as the following: In addition to this logic, the Repeater has an optional SeparatorTemplate, which it calls InstantiateIn() on between each data item. Remember the "build control" method that the Delegate pointed to? Calling InstantiateIn() on the template is going to call that method. So the method is executed once for each data item, and thus that txtName TextBox we declared in the ItemTemplate markup is going to be created multiple times, in a dynamic manner. So as you can see, Templates are powerful. And it also demonstrates that the framework itself is very much involved in the creation of dynamic controls. You can also create templates programmatically instead of statically by implementing the ITemplate interface yourself, but that's for a different blog entry. All this and I still haven't gotten to the heart of the matter. The next part will examine how and when dynamic controls are added to the control tree. By "when" I mean when during the page lifecycle. That is so important because "when" can affect how the dynamic control participates in the lifecycle, and depending on the type of control and what features of it you are relying on, doing it at the wrong time will break it... Nice job, Dave. You enlighten my horizont in developing controls. Why this kind of articles isnt written in e-books? Hardly waiting for part 3 :) You've been kicked (a good thing) - Trackback from DotNetKicks.com Wow, great article. Hurry up with the next one :-) Good stuff. I am anxiously waiting for Part 3! Thanks. Since, ViewState is a important part of developing web pages (specially web controls), i wanted to know, Just like ViewState, dynamic controls seem to be fodder for much debate, and a source of many confusing issues. This article will be the first of a multi-part series to detail just about everything you could ever want to know about how Dynamic Controls when can we expect part 3? I'm anxiously awaiting part 3. I've never had any difficulty dynamically creating controls, it's re-creating them on post-back that gives me fits. Right... sorry its been so long since part 2 everyone. I have been quite busy working Atlas of all things. I haven't forgotten about it... Part 3 is half written, I'll finish it up asap, probably sometime next week. i generate labels and textboxes in a place holder on basis of data in sql.but on every post back i have to recall same method to maitain number of textboxes and values of labels.can u explain me how to retrive the value of textboxes from viewstate-statebag.cause the qurey retives large amount of data including names of labels.it would be helpfull to utilize viewstate values. utsav --- you dont need to retrieve the values out of StateBag yourself. To remember how many textboxes there are, just store the number in viewstate: this.ViewState["count"] = count; Then on postbacks you can recreate that many textboxes. As for the values in the labels, they too can maintain their state automatically. Just set their text property after you add them to the control collection (not before). So you're going to have two different "modes" of creating the controls -- one when you have data, where it sets the text properties of the labels and controls, and stores the number of them in viewstate -- and another where you simply recreate them controls based on the count and nothing more. I just described in a nutshell how DataGrid works... thk u for help will try it out today itself my heart felt thks to u,the way u said the thing r working out really fine,finally i am able to solve the greatest mystry of all times(for me).all thks to u for that. looking forward to more such good indepth articles which are understood properly. it is so good! thanks you very munch, Thanks that is a gret article. My problem seems to be escaping all of articles that i have read. I have a User Control that is created, configured and populated based on databased values. I am adding the controls to the forms collection NewQuestionCTL newMultiChoice = (NewQuestionCTL)LoadControl("NewQuestionCTL.ascx"); newMultiChoice.setQuestion(type, text, number); newMultiChoice.ID = "newQuestion" + number.ToString(); form1.Controls.Add(newMultiChoice); They look great but I cannot find the controls to read the values from after the postback, despite the fact that I redrawing the controls on postback. How do I access the values of of the 10-20 controls to update the database. Jim -- since you are creating them once every request already anyway, why don't you just hang on to them with a dictionary? You can key the dictionary by the question number. Dictionary<Int32, newQuestionCTL> index = new ... (); // ... load control as usual // store it in the index index[questionNumber] = userControl; // Then later on when you need them, userControl = index[questionNumber]; Or you can enumerate them foeach(KeyValuePair<Int32, newQuestionCTL> pair in index) { pair.Key; // the question number pair.Value; // the user control You can use this.Page.LoadControl. Its not stupid... thats one of the whole points of the code behind model :) You don't necessarily need to load something dynamically to accomplish it though. Hi, Thx for your answer: "You can use this.Page.LoadControl." that was my initial thought too and it works fine on page but not during design-time in VS.NET (designer). I have complex templated custom control which I want to "fill" through designer. Joshua Sounds like you want to provide a template then. Too broad of a subject to cover in a comment box... but you want the same functionality that say, a repeater has: <asp:Repeater....> <ItemTemplate> user content goes here </ItemTemplate> The content of the item template is used by the repeater in whatever means it deems necessary. Templates aren't just for repeating databound controls. Login control, for example, uses a template to allow you to customize the layout of the login form. If someone wants a user control loaded into the template, they can simply declare a user control within the template. Here's a quickstart on templated controls: Thx, sorry if my question wasn't straight but I was actually asking the same question as before. I would like to load UserControl's "look" from ascx file (or any HTML editable file) and use it for my server CompositeControl (either is templated or not) during design time. The look that is loaded when you drag the control from ToolBox into designer. Right now I'm creating it programmatically in overloaded CreateChildControls() of my control. It works fine but since it has quite complex design it is pain to changing it in the code. As you suggested I would use "this.Page.LoadControl." but this works only when the page is loaded, not during design time. Joshua You can load a "look" from a file with either LoadControl or LoadTemplate, but I don't know of a way to do this at design time. I'm curious why you want to do it at design time -- are just trying to customize the design time look of your control, and you want to seperate the UI logic into a seperate file for ease of maintenance? You could load the file from disk directly, then as long as it only contains html, you could write a designer that uses it to display it as rendered html. Sorry I don't have any specific advice on how to go that route, designers aren't my strong point :) Still I'm curious exactly what you are trying to accomplish... typically a control's design time matches its runtime except at worst, dummy UI to represent things that aren't known until runtime. If you're loading special html just for design time, then it doesnt sound like its going to match runtime very well. I had some code working in .Net 1.0 regarding dynamic controls, now since moving it to .NET 1.1 it just doesnt seem to work, or i am doing something stupid ? Are there any differences between frameworks with regards to dynamic controls. Is it possible to have a dynamic control created, to change its text value (for example) using javascript client-code and pick up that new value at the server side when its submitted ? Neil -- there aren't any real differences that I know about, but there could have been some optimizations made or something that could have an affect on your scenario. Hard to say without more details. Yes... but if the control isn't a form control (checkbox, textbox, etc) then it won't post its value natually. For example a label. You can change its value on the client easily, but for that value to be communicate to the server it must be copied into a hidden form field. A lot of custom controls out there use that trick. If its a textbox the value will already be submitted and picked up by the control. Is it possible to build controls that support nested Templates? I want to support: <a:CRUD <ReadViewTemplate> <HeadTemplate/> <BodyTemplate/> </ReadViewTemplate> <CreateViewTemplate> </CreateViewTemplate> </a> I created ReadViewTemplate which implements ITemplate (see below for the code), and my control of type CRUD exposes a ReadViewTemplate as a property. However when I try to run the code I get the error: Cannot implicitly convert type 'System.Web.UI.CompiledTemplateBuilder' to ReadViewTemplate' How *should* I approach this? public class ReadViewTemplate :ITemplate { private ITemplate _validationTemplate; private ITemplate _headerTemplate; private ITemplate _footerTemplate; private ITemplate _bodyTemplate; [Browsable(true)] [DefaultValue(null)] [PersistenceMode(PersistenceMode.InnerProperty)] [TemplateContainer(typeof(ReadView))] [TemplateInstance(TemplateInstance.Single)] public ITemplate HeaderTemplate { get { return _headerTemplate; } set { _headerTemplate = value; } } public ITemplate ValidationTemplate get { return _validationTemplate; } set { _validationTemplate = value; } public ITemplate BodyTemplate get { return _bodyTemplate; } set { _bodyTemplate = value; } public ITemplate FooterTemplate get { return _footerTemplate; } set { _footerTemplate = value; } #region ITemplate Members public void InstantiateIn(Control container) if (container is ReadView) { if (this._bodyTemplate!=null) this._bodyTemplate.InstantiateIn((ReadView)container); if (this._validationTemplate != null) this._validationTemplate.InstantiateIn((ReadView)container); if (this._headerTemplate != null) this._headerTemplate.InstantiateIn((ReadView)container); if (this._footerTemplate != null) this._footerTemplate.InstantiateIn((ReadView)container); } else throw new Exception("This template can only instantiate its controls within a ReadView control"); #endregion } Rick, I'm afraid templates were simply not designed to be nested. The page parser always created a particular type to implement the interface based on markup. I'm not sure it makes total sense at least in this scenario anyway... the fact that ReadViewTemplate has a nested template implies that it matters where the user puts the nested templates. For example: content content content <HeadTemplate>...</HeadTemplate> content content content <BodyTemplate>...</BodyTemplate> It doesn't seem like it is your intent for the user to be able to put content between the head and body templates. And so, the correct solution is for the ReadViewTemplate property not to be a template in the first place. You could create a custom type that has two properties: HeadTemplate and BodyTemplate. Then return via a get-only property an instance of that type from your control. Then you can accomplish this nested syntax, and the ReadViewTemplate is not a template at all, and thus the above markup would correctly generate an error. You could also keep it simplier by just breaking them into different properties... <ReadHeadTemplate> ... </ReadHeadTemplate> <ReadBodyTemplate> ... </ReadBodyTemplate> <CreateHeadTemplate> ... </CreateHeadTemplate> <CreateBodyTemplate> ... </CreateBodyTemplate> I am dynamically creating templates for a formview control by pointing to an .ascx file. I am loading the templates in the Page_Init event. On the itemupdating event, the new and old values are null. If I create the same templates in the design mode, then the old and new values are populated. Any suggestions? Code follows: public partial class Administration_Master : System.Web.UI.Page { private string m_typeName; protected string m_detailName; protected string m_type; protected void Page_Init(object sender, EventArgs e) //get class type m_type = Request["Type"] as string; //get templates ITemplate template = null; ITemplate item = null; switch (m_type) case "Component": Debug.WriteLine("LoadTemplate"); template = Page.LoadTemplate("~/Administration/Templates/ComponentEdit.ascx"); item = Page.LoadTemplate("~/Administration/Templates/ComponentItem.ascx"); break; if (template != null) masterDetail.EditItemTemplate = template; masterDetail.InsertItemTemplate = template; masterDetail.ItemTemplate = item; protected void Page_Load(object sender, EventArgs e) //check authorization //if (Thread.CurrentPrincipal.IsInRole("Administrator")) // Label1.Text = "Yes"; Label1.Visible = false; objSource.TypeName = "CED.Service.Common." + m_type; detailSource.TypeName = "CED.Service.Common." + m_type; m_typeName = m_type + "s"; m_detailName = m_type + " Definition:"; if (Request["ID"] == null) masterDetail.Visible = false; switch (Request["Mode"]) case "Insert": masterDetail.DefaultMode = FormViewMode.Insert; default: masterDetail.DefaultMode = FormViewMode.ReadOnly; protected void masterView_RowDataBound(object sender, GridViewRowEventArgs e) if (e.Row.RowType == DataControlRowType.Header || e.Row.RowType == DataControlRowType.EmptyDataRow) ((System.Web.UI.WebControls.Label)e.Row.FindControl("Type")).Text = m_typeName; protected void masterDetail_ItemUpdated(object sender, FormViewUpdatedEventArgs e) masterView.DataBind(); protected void masterDetail_ItemUpdating(object sender, FormViewUpdateEventArgs e) int i = 0; protected void masterView_RowCommand(object sender, GridViewCommandEventArgs e) if (e.CommandName == "Add") Response.Redirect("Master.aspx?Type=" + m_type +"&ID=-1&Mode=Insert"); protected void masterDetail_ItemCommand(object sender, FormViewCommandEventArgs e) if (e.CommandName == "Cancel" && masterDetail.CurrentMode == FormViewMode.Insert) Response.Redirect("Master.aspx?Type=" + m_type + "&Mode=ReadOnly"); protected void masterDetail_ItemInserted(object sender, FormViewInsertedEventArgs e) protected void masterDetail_ItemInserting(object sender, FormViewInsertEventArgs e) e.Values["ID"] = "-1"; Wow, when I highlight the whole page with my mouse I can almost read it. Good content though. Thanks a lot for great article. I hope you'll be able to give us some advice. We have to allow designers working in VS IDE and modify properties of the ViewForm.ItemTemplate content. At runtime, I want to be able reorder content based on the database records and potentially add more content. The database has definition for every label text and source for corresponding value text. <asp:FormView <div class="mainColumn" > <div id='lblRow1' class="row"> <gep:BoundLabel</gep:BoundLabel> <asp:Label</asp:Label> </div> <div id='lblRow2' class="row"> <gep:BoundLabel</gep:BoundLabel> <asp:Label</asp:Label> .... </div> <ItemTemplate> </asp:FormView> Sorry if I have not made myself clear... Aspx will have ItemTemplate defined. At runtime, we will read database and need to reorder divs placing them in appropriate sequence based on db definition and, in addition, we need to add more divs for 'custom' records which have not been included in ItemTemplate at design time. Irene - You should create a custom control. All it would do is override Render, and then render its child control in the appropriate order (by calling control.RenderControl on them). The idea is you want to customize the order they are rendered and nothing more -- it could cause you problems if you were doing something like shuffling the order of the controls in the tree. The custom control also gives you the ability to enforce proper usage. If the only top level divs should be within the control then you can throw an exception if someone adds something else, or you could even have another type of control they use instead, which would allow you to have an API for customizing how the rendering occurs (if you need such customization). <ItemTemplate> <abc:OrderedContainer <abc:Item .... </abc:Item> <abc:Item </abc:OrderedContainer> In this case the "type" property is just something I made up -- its something the OrderedContainer control (which is badly named) could look at to make decisions. Hope that helps. Thanks a million!!! I really appreciate your help. Everything seems to be working but I want to double-check with you some of my implementation. 1. Is OrderedContainer.OnInit() appropriate place to induce new custom controls (based on the metadata definition in addition to page definition)? 2. Following code enables databinding on new control. Is there easier way? private Item CreateNewControl(HBDocumentDetail detail) Item newControl = new Item (); newControl.ID = "_" + detail.DetailID; newControl.Source = detail.Source.Trim(); newControl.DataBinding += delegate(object sender, EventArgs e) Item dataBindingExpressionBuilderTarget; System.Web.UI.WebControls.FormView Container; dataBindingExpressionBuilderTarget = (sender as Item); Container = ((System.Web.UI.WebControls.FormView)(dataBindingExpressionBuilderTarget.BindingContainer)); dataBindingExpressionBuilderTarget.Text = System.Convert.ToString(DataBinder.Eval(Container.DataItem, detail.Source, "{0}"), System.Globalization.CultureInfo.CurrentCulture); }; 3. I’ve noticed that databinding does not work if control is placed on the page at design time and it does not have databinding explicitly defined via attribute Text. My code sets the property Text=”<%# Eval… %>” when Source property is set. I guess I need to wire DataBinding event myself. What is a correct way distinguishing control definition within the page scope via Text attribute versus Text property imposed by code? Thanks again! - Irene Hi there, Sorry to bother you again. I have just a quick follow-up to the previous post… Regarding item 3, I’ve ended up not updating Text property based on Source but calling SubscribeToDataBinding() when Source != "" && !Text.Contains("Eval") private void SubscribeToDataBinding(Item control) if (control.Source != "") control.DataBinding += delegate(object sender, EventArgs e) Item target = sender as Item; FormView Container = target.BindingContainer as FormView; target.Text = Convert.ToString(DataBinder.Eval(Container.DataItem, control.Source, "{0}"), System.Globalization.CultureInfo.CurrentCulture); }; 4. I’ve derived my OrderedContainer control from Panel. Is it the best base class for this purpose? Other than being a parent for Item controls it has to have OrderedContainerDesigner : PanelContainerDesigner. Thanks a lot for your help. -irene Irene -- What you derive from should be based on what you want to render. If you want the container to render a div, panel works. If you dont need it to render anything I'd use Control. Just depends on if you really need that <div> surrounding the content or if you need to style it. Sorry I missed your previous comment... I'm not sure why you are dynamically creating the Items? I thought your usage was that the items would be declared within the OrderedContainer, and all OrderedContainer did was render them in a different order. My goal is to allow both type of page customization – changing controls order as well as adding new ‘items’. I need to allow adding controls to the page in designer, changing its look via css at design time and make runtime rendering based on final database definition (potentially altered by the customer). BTW, I intended to check (Text != “”) in order to figure out whether the ASP.NET plumbing has arranged DataBinding for me or I should call my own SubscribeToDataBinding() but it became obvious that VALUE of the Text of course is blank during Init even though Text attribute= '<%# Eval("xxx", "{0}") %>'. Is it harmfull to subsribe to event extra time? Can I unsubscribe just in case? Or can I check somehow differently to see if binding in Text was defined in design time? On completely different topic, do you happen to have experience working with Designers? I have troubles adding a control to my container via DesignerAction (I would rather being able insert control after ‘currently’ selected item but I have not found a way do that). RootDesigner.AddControlToDocument adds control to the page after my container rather than inside the container… RootDesigner.AddControlToDocument(newControl, lastContainerChild, ControlLocation.Before); In addition, I cannot stretch my panel. It autosizes based on number of child items… Thanks a lot for your help! No harm in subscribing to an event more than once -- events are designed for just that. If you just want to avoid overwriting an existing design-time databinding expression then check that Text is not empty from within your binding handler. Its still possible that it was databound though (to an empty value). If that concerned you, you could have some placeholder text in it by default, then only set it if its still that value. As for designers... they aren't my strength, I'll admit that :) If you want your control resizable in the designer then that implies you have a width/height property on your control? Inherit from webcontrol and make sure your designer returns true for AllowResize (which I think is the default anyway...). Thanks again for your help. Now I’m trying to manage database driven items in a container but I need it to be GridView columns collection. I thought if I create my TemplateField I would be able to generate Columns from the database definition. I guess I am confused about the way of defining and using custom TemplateFields. class ColumnDetail : TemplateField private DocDetail _docDetail ; ColumnHeader _header; ColumnItem _item; public ColumnDetail() _docDetail = new DocDetail(); _header = new ColumnHeader(_docDetail.LabelField); _item = new ColumnItem(_docDetail); public override ITemplate HeaderTemplate get { return _header;} ……….. public class ColumnHeader : ITemplate BoundLabel _label; public ColumnHeader(BoundLabel label) _label = label; container.Controls.Add(_label); public class ColumnItem : ITemplate DocDetail _docDetail; public ColumnItem(DocDetail docDetail) _docDetail = docDetail; container.Controls.Add(_docDetail); if (!string.IsNullOrEmpty(_docDetail.Source)) _docDetail.DataBinding += delegate(object sender, EventArgs e) { IDocDetail target = sender as IDocDetail; IDataItemContainer Container = (target as Control).BindingContainer as IDataItemContainer; target.Text = Convert.ToString(DataBinder.Eval(Container.DataItem, _docDetail.Source, "{0}"), System.Globalization.CultureInfo.CurrentCulture); }; I thought I could use my ColumnDetail but I am getting compliler error… <asp:GridView <Columns> <igi:ColumnDetail type="Column1” /> ….. How should I approach it? Thanks again. Irene. -- not sure what your compile errors are. You don't need to inherit from TemplateField. TemplateField is called such because its meant to get the UI from markup. Since you seem to want to just render specific UI driven by the db, just inherit from DataControlFileld. Thanks a lot for immediate response :-) I am not quite sure what is happening. The problem with compilation was due to my silliness not having ColumnDetail declared as public class. Now I can place it within the columns but it does not act as Template. It does not display anything. It does not hit the break inside InstantiateIn(). I do want to display columns collection in design as well. I am not sure if it effects whether to inherit from DataControlFileld or TemplateField. Sorry, as you can see I am rather novice in this area and really appreciate you help very much! Irene -- pretty sure you should inherit DataControlField or possibly BoundField. TemplateField is meant to get UI declaratively, and you want to create it dynamically based on data, without any input from the markup. This article may help get you started with creating a custom field: Vor einiger Zeit hielt ich eine Webcastserie zum Thema Server Controls ( ASP. NET Server Controls – eine Hello I need your help. I can not retrieve value from dynamic TextBox and DropDown List Control. I was create dynamic control at the Page_Load() event and the number of control count and control type (TextBox or DropDownList) is accorading to the DB value. At first I was used DataList control with the dataset.datatable. My DataList Item Template has 1 PlaceHolder and after I created my dynamic control, add to that Place Holder. And then when the user click Save Button, I have to save the data from dynamic control value to the database. So I was using the FindControl() Method for every DataList item template. I find for PlaceHolder control first and then i find again my dynamic control(TextBox or DropDownList) from that PlaceHolder. But I got a result that is No Control from that PlaceHolder. I trace my Control Tree View, I can see my Dynamic Control under the PlaceHolder Control. But I can not find my dynamic control from that PlaceHolder when my Debuging. Pls help me ASAP. I need all of your help! Thanks nyimalay -- You'll have to provide me some code so I can understand what is wrong. Sounds like you probably have a significant amount of code with database lookups and all that. Try to narrow it down as compact as possible while still reproducing the problem. This article is truly a great asset. I've searched all over for information that is sound, succinct, and easy to understand. You have achieved all this. Thanks for the enlightenment. thanks man, But Can you suggest me how can I typecast loaded control to the loaded control class from Control class to set the properties of this control. And I will be getting this control classname at runtime only. Regards, AKS. forums.aksclassifieds.com youtube.aksclassifieds.com Ashok -- maybe this will help you. msdn2.microsoft.com/.../w70c655a.aspx or perhaps this can we display data without using databound controls using datatable. Divya -- sure, you could either manually build up the html in the code behind with a foreach or you can embed that foreach directly into the page using the old asp style <% %> code blocks. You might also be interested in the ASP.NET MVC framework currently under development. weblogs.asp.net/.../asp-net-mvc-framework-part-1.aspx Question about ItemCommand firing... I have a repeater on a page which fires the ItemCommand and OnItemDatabound events as expected. My problem happens when I ripped out the contents of <ItemTemplate> on the page's repeater and put the contents into a class method InstantiateIn which inherits ITemplate. The problem I'm having is that the ItemCommand won't fire anymore. My handler is still wired to the page in the Page_Init. Do you know what I could be doing wrong? code sample below: page markup ========== <!-- templates are generated from CustomItemTemplate.cs --> <asp:Repeater <ItemTemplate></ItemTemplate> <AlternatingItemTemplate></AlternatingItemTemplate> page code behind =============== protected void Page_Init(object sender, EventArgs e) rptFoo.ItemCommand += new RepeaterCommandEventHandler(rptFoo_ItemCommand); protected void Page_Load(object sender, EventArgs e) CustomItemTemplate citItem = new CustomItemTemplate(ListItemType.Item); CustomItemTemplate citAlternating = new CustomItemTemplate(ListItemType.AlternatingItem); rptFoo.ItemTemplate = citItem; rptFoo.AlternatingItemTemplate = citAlternating; if (!Page.IsPostBack) BindData(); } protected void rptFoo_ItemCommand(object source, RepeaterCommandEventArgs e) // won't fire when implementing my class file. CustomItemTemplate.cs =================== public class CustomItemTemplate : ITemplate Panel pan; public ListItemType ItemType; public CustomItemTemplate(ListItemType itemType) { this.ItemType = itemType; void ITemplate.InstantiateIn(Control container) pan = new Panel(); // if the parent control is a WebControl... if ((container) is WebControl) { // get a strongly-typed reference to the containing item WebControl webCtl = (WebControl)container; // set the panel's size so that it fully cover's its containers pan.Width = webCtl.Width; pan.Height = webCtl.Height; } switch (this.ItemType) case ListItemType.Item: pan.Controls.Add(new LiteralControl("<tr align=\"left\" class=\"item\">")); break; case ListItemType.AlternatingItem: pan.Controls.Add(new LiteralControl("<tr align=\"left\" class=\"alternatingItem\">")); pan.Controls.Add(new LiteralControl("<td>")); pan.Controls.Add(new HiddenField()); pan.Controls.Add(new CheckBox()); pan.Controls.Add(new LiteralControl("</td><td width=\"325\">")); pan.Controls.Add(new LinkButton()); pan.Controls.Add(new LiteralControl("<br />")); pan.Controls.Add(new Label()); pan.Controls.Add(new LiteralControl("</td></tr>")); container.Controls.Add(pan); pan.DataBinding += new EventHandler(pan_DataBinding); private void pan_DataBinding(object sender, System.EventArgs e) fooProduct p; if ((pan.NamingContainer) is RepeaterItem) p = (fooProduct)(((RepeaterItem)pan.NamingContainer).DataItem); else return; ((LinkButton)pan.Controls[5]).ID = "linkBtnFoo"; ((LinkButton)pan.Controls[5]).Text = p.FooName); ((LinkButton)pan.Controls[5]).CommandName = "Go"; ((LinkButton)pan.Controls[5]).CommandArgument = p.fooId; TIA, Pablo Pablo -- have you tried setting the custom templates on the repeater from Init instead of Load? It doesnt appear there's any reason to delay it. Not sure if thats the problem but I'd do that anyway. Also, I'd hook the databinding event before adding the panel to the control collection. I dont think it matters in this case but as a practice I try to do everything I can to the control before adding it, unless there's a good reason to do it afterward. Let me know if either of those helps... Hi, hope you still monitor the part, but I'm totally lost here, and that is also because I don't understand all of it complety. In my case I made a small example which in total uses 4 nested UC's and each UC has a textbox, button and checkbox. The UC's are in a ItemTemplate of the repeater which is nested. Now on every level I the button adds a new control to the list using: protected void Button2_Click(object sender, EventArgs e) ArrayList list = new ArrayList(); int index = 0; foreach (RepeaterItem rptItem in rptFirst.Items) WebUserControl2 WebUserControl = rptItem.FindControl("Item") as WebUserControl2; if (WebUserControl != null) WebUserControl2 ctrl = WebUserControl as WebUserControl2; list.Add(ctrl); index++; index++; WebUserControl2 _ctrl = LoadControl("WebUserControl2.ascx") as WebUserControl2; _ctrl.myText = "NEW ITEM"; list.Add(_ctrl); Repeater1.DataSource = list; Repeater1.DataBind(); Basically every uc has a procedure like this. Then when I also have, on every UC the following procedure: protected void Repeater1_ItemCreated(object sender, RepeaterItemEventArgs e) if (!e.Item.ItemType.Equals(ListItemType.Separator)) //Postback then e.item.DataItem is null if (e.Item.DataItem != null) WebUserControl2 WebUserControl = e.Item.FindControl("Item") as WebUserControl2; WebUserControl.myText = ((WebUserControl2)e.Item.DataItem).myText; WebUserControl.myCheckBox = ((WebUserControl2)e.Item.DataItem).myCheckBox; As you can see I actually bind a (Arry)list of UC to the repeater. I want to setup this small example without binding to a Db, that is why I use the ArrayList. No When I add a control it appears fine. On this control I can add 1..N Child UC and on the child control I can add 1..N UC (three levels deep). This all works fine, untill I press Add usercontrol button on the highest level. Then I still have the first UC I added and also the second new UC, but all the Child controls ( and their child controls) of the first added control are gone. All the controls have the procedures I have included above. How can I maintain the state of the child controls which are already there when I add a control on the highest level. I was told the problem is I recreate the controls in ItemCreated event, so it is actually a new control which, of course has no childcontrols. If that is true, what would be the solution for this? TIA Stephan Pingback from Dynamically adding user controls, and then setting custom properties on those instances? | keyongtech
http://weblogs.asp.net/infinitiesloop/archive/2006/08/25/TRULY-Understanding-Dynamic-Controls-_2800_Part-2_2900_.aspx
crawl-002
en
refinedweb
You know those things where you just think "How didn't I know that?!", well I got one today. I only just found out (laugh at me if you want!) that you can add an alias to an "Imports" statement. So, instead of typing: Imports System.Data I can type: Imports d = System.Dataand refer to it as "d". Here's what it would look like in Visual Studio: Thanks to Christiaan Baes for the tip! Pingback from Imports Alias - Mark Smith Old trick, however I strongly feel it leads to readability issues in larger classes. I didn't know you could do it either but I don't like it. I agree with Jayson. Only real usefulness of this would be similar to class instantiation. In case you didnt want to do all the sub imports to other subnamespace/classes. You could use this as a shortcut interrupt to those classes and namespaces. But again, as stated above, that usefulness is far overweighted by the lack of control and if someone isnt smart enough to figure out the reference then it can lead to alot of confusion and mistakes. Id like to see some implementation of the Abbreviated namespace reference like in C#.
http://weblogs.asp.net/marksmith/archive/2007/10/11/imports-alias.aspx
crawl-002
en
refinedweb
Hello readers. Welcome to our tutorial on debugging and Visualisation in PyTorch. This is, for at least now, is the last part of our PyTorch series start from basic understanding of graphs, all the way to this tutorial. In this tutorial we will cover PyTorch hooks and how to use them to debug our backward pass, visualise activations and modify gradients. Before we begin, let me remind you this Part. Understanding PyTorch Hooks Hooks in PyTorch are severely under documented for the functionality they bring to the table. Consider them like the the Doctor Fate of the superheroes. Haven't heard of him? Exactly. That's the point. One of the reason I like hooks so much is that they provide you to do things during backpropagation. A hook is like a one of those devices that many heroes leave behind in the villain's den to get all the information. You can register a hook on a Tensor or a nn.Module. A hook is basically a function that is executed when the either forward or backward is called. When I say forward, I don't mean the forward of a nn.Module . forward function here means the forward function of the torch.Autograd.Function object that is the grad_fn of a Tensor. Last line seem gibberish to you? I recommend you to please checkout our article on computation graph in PyTorch. If you are just being lazy, then understand every tensor has a grad_fn which is the torch.Autograd.Function object which created the tensor. For example, if a tensor is created by tens = tens1 + tens2, it's grad_fn is AddBackward. Still doesn't make sense? You should definitely go back and read this article. Notice, that a nn.Module like a nn.Linear has multiple forward invocations. It's output is created by two operations, (Y = W * X + B), addition and multiplication and thus there will be two forward calls. This can mess things up, and can lead to multiple outputs. We will touch this in more detail later in this article. PyTorch provides two types of hooks. - The Forward Hook - The Backward Hook A forward hook is executed during the forward pass, while the backward hook is , well, you guessed it, executed when the backward function is called. Time to remind you again, these are the forward and backward functions of an Autograd.Function object. Hooks for Tensors A hook is basically a function, with a very specific signature. When we say a hook is executed, in reality, we are talking about this function being executed. For tensors, the signature for backward hook is, hook(grad) -> Tensor or None There is no forward hook for a tensor. grad is basically the value contained in the grad attribute of the tensor after backward is called. The function is not supposed modify it's argument. It must either return None or a Tensor which will be used in place of grad for further gradient computation. We provide an example below. import torch a = torch.ones(5) a.requires_grad = True b = 2*a b.retain_grad() # Since b is non-leaf and it's grad will be destroyed otherwise. c = b.mean() c.backward() print(a.grad, b.grad) # Redo the experiment but with a hook that multiplies b's grad by 2. a = torch.ones(5) a.requires_grad = True b = 2*a b.retain_grad() b.register_hook(lambda x: print(x)) b.mean().backward() print(a.grad, b.grad) There are several uses of functionality as above. - You can print the value of gradient for debugging. You can also log them. This is especially useful with non-leaf variables whose gradients are freed up unless you call retain_gradupon them. Doing the latter can lead to increased memory retention. Hooks provide much cleaner way to aggregate these values. - You can modify gradients during the backward pass. This is very important. While you can still access the the gradvariable of a tensor in a network, you can only access it after the entire backward pass has been done. For example, let us consider what we did above. We multiplied b's gradient by 2, and now the subsequent gradient calculations, like those of a(or any tensor that will depend upon bfor gradient) use the 2 * grad(b) instead of grad(b). In contrast, had we individually updated the parameters after the backward, we'd have to multiply b.gradas well as a.grad(or infact, all tensors that depend on bfor gradient) by 2. a = torch.ones(5) a.requires_grad = True b = 2*a b.retain_grad() b.mean().backward() print(a.grad, b.grad) b.grad *= 2 print(a.grad, b.grad) # a's gradient needs to updated manually Hooks for nn.Module objects For nn.Module object, the signature for the hook function, hook(module, grad_input, grad_output) -> Tensor or None for the backward hook, and hook(module, input, output) -> None for the forward hook. Before we begin, let me make it clear that I'm not a fan of using hooks on nn.Module objects. First, because they force us to break abstraction. A nn.Module is supposed to be a modularised object representing a layer. However, a hook is subjected a forward and a backward, of which there can be an arbitrary number in a nn.Module object. This requires me to know the internal structure of the modularised object. For example, a nn.Linear involves two forward calls during it's execution. Multiplication and Addition ( y = w * x + b). This is why the input to the hook function can be a tuple containing the inputs to two different forward calls and output s the output of the forward call. grad_input is the gradient of the input of nn.Module object w.r.t to the loss ( dL / dx, dL / dw, dL / b). grad_output is the gradient of the output of the nn.Module object w.r.t to the gradient. These can be pretty ambiguous for the reason of multiple calls inside a nn.Module object. Consider the following)) return self.fc1(self.flatten(x)) net = myNet() def hook_fn(m, i, o): print(m) print("------------Input Grad------------") for grad in i: try: print(grad.shape) except AttributeError: print ("None found for Gradient") print("------------Output Grad------------") for grad in o: try: print(grad.shape) except AttributeError: print ("None found for Gradient") print("\n") net.conv.register_backward_hook(hook_fn) net.fc1.register_backward_hook(hook_fn) inp = torch.randn(1,3,8,8) out = net(inp) (1 - out.mean()).backward() The output produced is. Linear(in_features=160, out_features=5, bias=True) ------------Input Grad------------ torch.Size([5]) torch.Size([5]) ------------Output Grad------------ torch.Size([5]) Conv2d(3, 10, kernel_size=(2, 2), stride=(2, 2)) ------------Input Grad------------ None found for Gradient torch.Size([10, 3, 2, 2]) torch.Size([10]) ------------Output Grad------------ torch.Size([1, 10, 4, 4]) In the code above, I use a hook to print the shapes of grad_input and grad_output. Now my knowledge about this may be limited, and please do comment if you have a alternative, but for the love of pink floyd, I cannot figure out what grad_input is supposed to represent what? In conv2d you can guess by shape. The grad_input of size [10, 3, 3, 2] is the grad of weights. That of [10] is maybe bias. But what about grad of input feature maps. None? Add to that Conv2d uses im2col or it's cousin to flatten an image such that convolutional over the whole image can be done through matrix computation and not looping. Were there any backward calls there. So in order to get the gradient of x, I'll have to call the grad_output of layer just behind it? The linear is baffling. Both the grad_inputs are size [5] but shouldn't the weight matrix of the linear layer be 160 x 5. For such confusion I'm not a fan of using hooks with nn.Modules. You could do it for simple things like ReLU, but for complicated things? Not my cup of tea. Proper Way of Using Hooks : An Opinion So, I'm all up for using hooks on Tensors. Using named_parameters functions, I've been successfully been able to accomplish all my gradient modifying / clipping needs using PyTorch. named_parameters allows us much much more control over which gradients to tinker with. Let's just say, I wanna do two things. - Turn gradients of linear biases into zero while backpropagating. - Make sure that for no gradient going to conv layer is less than 0.)) x.register_hook(lambda grad : torch.clamp(grad, min = 0)) #No gradient shall be backpropagated #conv outside less than 0 # print whether there is any negative grad x.register_hook(lambda grad: print("Gradients less than zero:", bool((grad < 0).any()))) return self.fc1(self.flatten(x)) net = myNet() for name, param in net.named_parameters(): # if the param is from a linear and is a bias if "fc" in name and "bias" in name: param.register_hook(lambda grad: torch.zeros(grad.shape)) out = net(torch.randn(1,3,8,8)) (1 - out).mean().backward() print("The biases are", net.fc1.bias.grad) #bias grads are zero The output produced is: Gradients less than zero: False The biases are tensor([0., 0., 0., 0., 0.]) The Forward Hook for Visualising Activations If you noticed, the Tensor doesn't have a forward hook, while nn.Module has one, which is executed when a forward is called. Notwithstanding the issues I already highlighted with attaching hooks to PyTorch, I've seen many people use forward hooks to save intermediate feature maps by saving the feature maps to a python variable external to the hook function. Something like this. visualisation = {} inp = torch.randn(1,3,8,8) def hook_fn(m, i, o): visualisation[m] = o net = myNet() for name, layer in net._modules.items(): layer.register_forward_hook(hook_fn) out = net(inp) Generally, the output for a nn.Module is the output of the last forward. However, the above functionality can be safely replicated by without use of hooks. Just simply append the intermediate outputs in the forward function of nn.Module object to a list. However, it might be a bit problematic to print the intermediate activation of modules inside nn.Sequential. To get past this, we need to register a hook to children modules of the Sequential but not the to Sequential) self.seq = nn.Sequential(nn.Linear(5,3), nn.Linear(3,2)) def forward(self, x): x = self.relu(self.conv(x)) x = self.fc1(self.flatten(x)) x = self.seq(x) net = myNet() visualisation = {} def hook_fn(m, i, o): visualisation[m] = o def get_all_layers(net): for name, layer in net._modules.items(): #If it is a sequential, don't register a hook on it # but recursively register hook on all it's module children if isinstance(layer, nn.Sequential): get_all_layers(layer) else: # it's a non sequential. Register a hook layer.register_forward_hook(hook_fn) get_all_layers(net) out = net(torch.randn(1,3,8,8)) # Just to check whether we got all layers visualisation.keys() #output includes sequential layers Finally, you can turn this tensors into numpy arrays and plot activations. Conclusion That wraps up our discussion on PyTorch, an unreasonable effective tool in visualising and debugging the back pass. Hope this article would help you in solving your bugs much quicker. Add speed and simplicity to your Machine Learning workflow today
https://blog.paperspace.com/pytorch-hooks-gradient-clipping-debugging/
CC-MAIN-2022-27
en
refinedweb
Vector of logical diffs describing changes to a JSON column. More... #include <json_diff.h> Vector of logical diffs describing changes to a JSON column. Type of the allocator for the underlying invector. Type of iterator over the underlying vector. Type of iterator over the underlying vector. Type of the underlying vector. Constructor. Append a new diff at the end of this vector when operation == REMOVE. Append a new diff at the end of this vector. Return the element at the given position. Return the length of the binary representation of this Json_diff_vector. The binary format has this form: +--------+--------+--------+ +--------+ | length | diff_1 | diff_2 | ... | diff_N | +--------+--------+--------+ +--------+ This function returns the length of only the diffs, if include_metadata==false. It returns the length of the 'length' field plus the length of the diffs, if include_metadata=true. The value of the 'length' field is exactly the return value from this function when include_metadata=false. Clear the vector. De-serialize Json_diff objects from the given String into this Json_diff_vector. Return the number of elements in the vector. Serialize this Json_diff_vector into the given String. An empty diff vector (having no diffs). The length of the field where the total length is encoded. Length in bytes of the binary representation, not counting the 4 bytes length.
https://dev.mysql.com/doc/dev/mysql-server/latest/classJson__diff__vector.html
CC-MAIN-2022-27
en
refinedweb
Hello! In this article, we're going to talk about refs in React. This is a relatively well-known and widely used concept of React that makes life a lot easier in some cases. but at the same time, we should try to avoid using them if possible. Because it can enter into conflict with React’s diff and update approaches. What we will see in this article : - What are refs? - What are the different approaches to creating Refs? - Is there any advantage of using one approach over the other? - How can I use Refs and To What can I refer? - How to pass a single or multiple ref/refs to a child component? What are refs? : As the documentation mentioned : “ Refs provide a way to access DOM nodes or React elements created in the render method ” For Example, you can focus an input node based on a button click : style.css input:focus { background-color: Aqua; } MyComponent.js import React from 'react'; import '.style.css' class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef= React.createRef(); } setFocus = () => { this.inputRef.current.focus(); }; render() { return ( <div> <input ref={this.inputRef} /> <button onClick={this.setFocus}>Click to set focus !</button> </div> ); } } export default MyComponent; What happened exactly? In fact when you include < MyComponent /> JSX syntax inside your react app, and at the time of rendering, React will first create an instance of the Class MyComponent and will call the constructor to construct the object instance after that he will call render method, this method tell React that you want to associate the ref with the inputRef that we created in the constructor. The input Node will then say to MyComponent instance "ok, I will assign to your attribute inputRef my address in memory, so you can have access to me later". And then when we click the button, our instance < MyComponent /> already knows the place of the input DOM node in memory then it can have access to all methods and attributes of this input DOM node ... Using Refs is a different way to the typical React dataflow; normally in React DataFlow parent components interact with their children using props and React docs always inform you to stay as much as possible relying on this workflow but in few cases where you need to imperatively modify a child outside of the typical dataflow and have direct access to this child component to take for example its position, then you can use Refs ... What are the different approaches to creating Refs ? : In old versions of React, you can refer to a component with strings refs but now it's considered as legacy and they recommend using either the callback Ref or the object Ref. - Ref object: that you can create with createRef API (from React 16.3) or useRef Hook (from React 16.8) : A ref object is a plain JS object that contains a current property: { current: < some value > }. this property is used to store a reference to the DOM node. In the example above, if we console log this.inputRef : You will see that our ref.current contains The input node Element, with that you can access all its methods like focus(), blur(), click() … You can create a Ref Object with CreateRef API inside ClassComponent or UseRef Hook inside functional components. But is there any difference between the two (CreateRef API vs UseRef Hook)? Ofc you can't use Hooks in general inside a class component, React will not let you do that. But if you try to use CreateRef API inside your functional component a new object Ref will be created in every rerender and you will lose your old object ref. In fact React.createRef(initValue) and useRef(initValue) both returns an object ref { current: initValue } Besides that useRef also memoizes this ref to be persistent across multiple renders in a functional component. because In React you cannot create an instance from a functional component. and if we do not have an instance, we, therefore, do not have a direct way to persist this reference across multiple renders. that's Why in general some hooks come up to help us and make our functional components stateful and more powerful throughout their lifecycle. And That’s why It is sufficient to use React.createRef in class components, as the ref object is assigned to an instance variable in the constructor, hence accessible throughout the component and its lifecyle. - Callback ref: Another way to set refs in React is to use callback refs. Callback refs is just a function that, when called, receives the React component instance or HTML DOM node as its argument, which can be stored and accessed elsewhere. if we use callback ref in the first example, this is how it will look like : MyComponent.js //... class MyComponent extends React.Component { callbackFunction = (node) => { this.inputRef = node; // this callback will attach node to inputRef }; setFocus = () => { this.inputRef.focus(); // we access node directly , no need to current property unlike Object ref }; render() { return ( <div> <input ref={this.callbackFunction} /> <button onClick={this.setFocus}>Focus Input</button> </div> ); } } export default MyComponent; When does the callback get called? React docs are very clear on this: “ React will call the ref callback with the DOM element when the component mounts, and call it with null when it unmounts. Refs are guaranteed to be up-to-date before componentDidMount or componentDidUpdate fires.” Is there any advantage of using one over the other (Object Ref vs Callback Ref)? the Docs say : “Callback refs give you more fine-grain control” This means that with Callback refs you gain more flexibility, you can look at this interesting example that can help you for example to set multiple refs in an array : class A extends React.Component { constructor(props) { super(props); this.inputs = []; } render() { return [0, 1, 2, 3].map((key, index) => ( <Input key={key} ref={input => this.inputs[index] = input} />) ); } } Another advantage of Callback Ref also mentioned in useRef docs : “If you want to run some code when React attaches or detaches a ref to a DOM node, you may want to use a callback ref instead.” Meaning; if you want to attach a ref to a component that will mount later or depending on a conditional (using conditional rendering) then you can use the callback ref. because it can attach a ref to your DOM node dynamically. The best example for this is from the docs itself: link here in this part How can I use Refs and to What can I refer? You can refer a ref to the ref attribute of two elements: a DOM node (like div, input …), or React Class Component but you may not use the ref attribute on functional components because they don’t have instances. This means : - on DOM node you can refer for example to a div or input (first example) like this : <div ref={myRef} /> And you can use this reference to focus for example input text or get the position of a div. - on React Class component you can do it like this : import React from "react"; import "./styles.css"; class App extends React.Component { constructor(props) { super(props); this.myComponentRef = React.createRef(); } setFocusOnMyChild = () => { this.myComponentRef.current.setFocus(); // As you can see we are invoking SetFocus //that is inside MyComponent from outSide . }; render() { // myComponentRef refer to MyComponent React Class instance return ( <div> <MyComponent ref={this.myComponentRef} /> <button onClick={this.setFocusOnMyChild}> Im a button from parent (App.js) </button> </div> ); } } class MyComponent extends React.Component { constructor(props) { super(props); this.inputRef = React.createRef(); } setFocus = () => { this.inputRef.current.focus(); }; render() { return ( <div> <input ref={this.inputRef} /> <button onClick={this.setFocus}> Click to set focus ! (Im inside MyComponent) </button> </div> ); } } export default App; result: By referring to a class component you can have access to methods inside the instance of this Class when React Creates it and invoke them from outside. you can console.log(classRef) and see all information that you can take from there. - But you can't do the same with React Functional component: your ref object will be null, Why? : Because functional components as we mentioned before, don’t have an instance in React, An instance is what you refer to as this in the component class you write. It is useful for storing local state and reacting to the lifecycle events. If you want to pass ref to your functional component, you can do it with the help of the hook useImperativeHandle combined with RefForward this can help you to refer to a functional component and you can for example invoke some functions that are inside your functional component from outside. these functions are exposed with the help of the useImperativeHandle hook, the same way you do it before with the Class component, in fact, the useImperativeHandle hook will customize the instance that is exposed to the parent component when using ref. and the forwardRef will help us to transfer the ref between parent and child. Thankfully React documentation is very rich with examples, you can check it here : Forwarding refs: Useimperativehandle hook: PS: We are discussing here referring to a functional component not using Refs inside functional component because. You can create and use refs inside a functional component as long as you refer to a DOM element or a class component. How to pass a single or multiple ref/refs to a child component? - Passing a single ref : It's simple you can do it with RefForward. As we mentioned before RefForward is a technique that helps us to pass automatically refs (in other words, “forward” it) to a child component either for Class component or functional component. React.forwardRef takes a function with props and ref arguments. This function returns a JSX Element. React.forwardRef((props, ref) => { ... }) We create for example a CustomTextInput with the Help of React.forwardRef like this : const CostumTextInput = React.forwardRef((props, ref) => ( <input type="text" placeholder={props.placeholder} ref={ref} /> )); You can now get a ref directly to the DOM node input and also pass as props your placeholder : const ref = React.createRef(); <CostumTextInput ref={ref} ; If you don’t want to use React.forwardRef, you can pass ref as a prop with a different name (!= ref) to Child Component, and there is no problem with that. Even React docs mention the custom ref prop as a more flexible approach to React.forwardRef : “If you use React 16.2 or lower, or if you need more flexibility than provided by ref forwarding, you can use this alternative approach and explicitly pass a ref as a differently named prop.” But you should pay attention if you pass an inline callback ref function down as prop because callback can trigger a re-render unless you have used a way of memoization with help of useCallback for example. The only advantages of forwardRef API : - consistent api for refs and uniform access API for DOM nodes, functional and class components - ref attribute does not bloat your props, because when you use forwardRef , it gives you a second argument ref, it didn’t add ref to your props - Passing mupltiple refs : You can do it with useImperativeHandle hook and RefForward API, like this : import "./styles.css"; import React,{ useRef ,useImperativeHandle} from "react"; export default function App() { const inputsRef = useRef(null); //inputsRef will Containt inside current property //an costum instance that contains all methods exposed with useImperativeHandle ,thanks to forwardRef and useImperativeHandle return ( <div className="App"> <Inputs ref={inputsRef} /> <button onClick={() => inputsRef.current.focusMyInput1()}>Focus Input1</button> <button onClick={() => inputsRef.current.focusMyInput2()}>Focus Input2</button> <button onClick={() => inputsRef.current.focusMyInput3()}>Focus Input3</button> </div> ); } const Inputs = React.forwardRef((props,ref)=>{ //let's create a ref for each input const refInput1 = useRef(); const refInput2 = useRef(); const refInput3 = useRef(); //Let's Expose a costum instance to the Parent Component //this instance will contain all methods to invoke focus on inputs //a parent component that renders <Inputs ref={inputsRef} /> //would be able to call all methods (focusMyInput1,focusMyInput2,focusMyInput3). useImperativeHandle(ref, () => ({ focusMyInput1: () => { refInput1.current.focus(); } , focusMyInput2: () => { refInput2.current.focus(); } , focusMyInput3: () => { refInput3.current.focus(); } })); return ( <div className="Inputs"> <input ref={refInput1} /> <input ref={refInput2} /> <input ref={refInput3} /> </div> ); }) Another way to pass multiple refs to child component: You can construct an object of Refs, and passe it as props with a prop that has a different name to "ref" to a Child Component, Like this : import "./styles.css"; import { useRef } from "react"; export default function App() { const refInput1 = useRef(null); const refInput2 = useRef(null); const refInput3 = useRef(null); //We are passing here multiple Refs with the help of Props AllRefs //AllRefs is just a simple prop that receive an object of refs that after will be associated to an input node dom return ( <div className="App"> <Inputs allRefs={{ refInput1, refInput2, refInput3 }} /> <button onClick={() => refInput1.current.focus()}>Focus Input1</button> <button onClick={() => refInput2.current.focus()}>Focus Input2</button> <button onClick={() => refInput3.current.focus()}>Focus Input3</button> </div> ); } function Inputs(props) { return ( <div className="Inputs"> <input ref={props.allRefs.refInput1} /> <input ref={props.allRefs.refInput2} /> <input ref={props.allRefs.refInput3} /> </div> ); } - Result in Both methods : That's all. And Remember Don’t Overuse Refs, Hope you learned something new. Discussion (1) Thanks for the article! Today I learned useImperativeHandlefrom you. 👍
https://dev.to/oussel/a-guide-for-refs-in-react-45l6
CC-MAIN-2022-27
en
refinedweb
C++/WinRT envy: Bringing thread switching tasks to C# (WPF and WinForms edition) Last time, we brought ThreadSwitcher. ResumeForegroundAsync and ThreadSwitcher. ResumeBackgroundAsync to C# for UWP. Today, we’ll do the same for WPF and Windows Forms. It’ll be easier the second and third times through because we already learned how to structure the implementation. It’s just the minor details that need to be tweaked. using System; using System.Runtime.CompilerServices; using System.Threading; // For ThreadPool using System.Windows.Forms; // For Windows Forms using System.Windows.Threading; // For WPF // For WPF struct DispatcherThreadSwitcher : INotifyCompletion { internal DispatcherThreadSwitcher(Dispatcher dispatcher) => this.dispatcher = dispatcher; public DispatcherThreadSwitcher GetAwaiter() => this; public bool IsCompleted => dispatcher.CheckAccess(); public void GetResult() { } public void OnCompleted(Action continuation) => dispatcher.BeginInvoke(continuation); Dispatcher dispatcher; } // For Windows Forms struct ControlThreadSwitcher : INotifyCompletion { internal ControlThreadSwitcher(Control control) => this.control = control; public ControlThreadSwitcher GetAwaiter() => this; public bool IsCompleted => !control.InvokeRequired; public void GetResult() { } public void OnCompleted(Action continuation) => control.BeginInvoke(continuation); Control control; } // For both WPF and Windows Forms struct ThreadPoolThreadSwitcher : INotifyCompletion { public ThreadPoolThreadSwitcher GetAwaiter() => this; public bool IsCompleted => SynchronizationContext.Current == null; public void GetResult() { } public void OnCompleted(Action continuation) => ThreadPool.QueueUserWorkItem(_ => continuation()); } class ThreadSwitcher { // For WPF static public DispatcherThreadSwitcher ResumeForegroundAsync( Dispatcher dispatcher) => new DispatcherThreadSwitcher(dispatcher); // For Windows Forms static public ControlThreadSwitcher ResumeForegroundAsync( Control control) => new ControlThreadSwitcher(control); // For both WPF and Windows Forms static public ThreadPoolThreadSwitcher ResumeBackgroundAsync() => new ThreadPoolThreadSwitcher(); } The principles for these helper classes are the same as for their UWP counterparts. They are merely adapting to a different control pattern. WPF uses the System.Threading.Dispatcher class to control access to the UI thread. The way to check if you are on the dispatcher’s thread is to call CheckAccess() and see if it grants you access. If so, then you are already on the dispatcher thread. Otherwise, you are on the wrong thread, and the way to get to the dispatcher thread is to use the BeginInvoke method. In Windows Forms, controls incorporate their own dispatcher. To determine if you’re on the control’s thread, you check the InvokeRequired property. If it tells you that you need to invoke, then you call BeginInvoke to get to the correct thread. Both WPF and Windows Forms use the CLR thread pool. As before, we check the SynchronizationContext to determine whether we are on a background thread already. If not, then we use QueueUserWorkItem to get onto the thread pool. So there we have it, C++/WinRT-style thread switching for three major C# user interface frameworks. If you feel inspired, you can do the same for Silverlight, Xamarin, or any other C# UI framework I may have forgotten. Something is screaming at me that there must be a neat way to get the appropriate SynchronizationContext injected into this setup and to use that instead of having three different implementations (and having to pass a relevant control every time when trying to “get back” to the UI). Haven’t worked it out yet though. I suppose we could capture it during the first call to ResumeBackgroundAsync but that still leaves a gap if that’s not the first call to TaskSwitcher. The tricky part is defining “appropriate”. (When you say you want to “go back to where you started”, you first have to define when “start” happens.) At the “start”, you can grab the SynchronizationContext.Currentand remember it as the “place to get back to”. You can then use this code to await synchronizationContext;to switch back to “where you were when you started”. (Note that this is basically what the default Taskinfrastructure does. It defines “start” as “begin to await”, and when the operation completes, it uses the saved SynchronizationContextto get back to the thread that performed the await.) Thanks for your better edition of thread switching. I’ve added all document comments and post your code and this page link at the end of my article: The original Async CTP (C#) had thread switching as a concept but then it was taken out. It wasn’t complete though. WinRT lumbered along late in the game. I promise you cannot scale as a human programmer without this paradigm. A few non-obvious key principles for WPF: – ref-count UI threads before exiting them (using statements are best), and on desired exit run the DispatcherFrame to flush events and check the count at the lowest DispatcherPriority until the count goes to zero. – You want to enforce viewmodel thread affinity or this will get nasty. Put a Dispatcher property in every one of your viewmodels and make sure your viewmodel calls VerifyAccess(). Cross-thread dependency property assignments are sloppy and show that you don’t understand your own threading model, plus they’re impossible to ref-count. Switch to the UI thread before making the assignment, don’t just fire-and-forget. – Support a CancellationToken in the switch call so that if the target or source Dispatcher is shut down or shutting down you can abort the switch. Add a DispatcherPriority parameter to the switch (this matters with screen updates). – You must deterministically destroy all your viewmodels or the GC tree will get out of control. Give every viewmodel a cancellation token and implement IDisposable. This token will be used to interrupt thread switches. – Make the switch call an extension method on Dispatcher to make the code look unintimidating. public static void SwitchToAsync(this Dispatcher dispatcher,DispatcherPriority priority = DispatcherPriority.Send,CancellationToken cancellationToken = default); – Don’t use the SynchronizationContext to detect the thread, use (Dispatcher.Thread == Thread.CurrentThread) or save the thread ID separately so you don’t risk creating Dispatchers on the thread pool. The reason is that WPF lets you create custom DispatcherSynchronizationContext to set the DispatcherPriority that Post() uses. You will be using SwitchTo methods to compose enclosing Task methods that handle the SynchronizationContext implicitly. – Always trap the switch call. UI threads end when the user wants them to. – Example code: public async Task StuffAsync(){try{using (RefCountCurrentThread()){await SwitchToThreadPoolAsync();// ….await Dispatcher.SwitchToAsync(DispatcherPriority.Render, _disposalCancellationToken);}}catch{// etc…}} This subject really deserves a Microsoft Press book but nobody writes those anymore. It was well worth the wait, you solved my async level loading problem in Unity so elegantly that I only have to add those helper methods between critical parts 🙂 Thanks a million Raymond !!!
https://devblogs.microsoft.com/oldnewthing/20190329-00/?p=102373
CC-MAIN-2022-27
en
refinedweb
Hello eveyone I’m working with selectors and tags and I need to load the next page while keeping the tag. <li class="cmp-pressreleaselist__page_next"> <a data- ${'Next' @ i18n} </a> </li> The issue is that is aem the namespaces where the tag is located is separated by column “:”, example “paris:louvre” but the href doesn’t accept columns “:” example dref="content/core/adobe/home.2022.info:events.1.html Does anyone know how can I make it work ? Solved! Go to Solution. Views Replies Total Likes You have to encode the colon in order to use it in href attribute. Use encoded value %3A instead of colon and it will work as expected. exampleto use href="content/core/adobe/home.2022.info%3Aevents.1.html Hi, Can you try with @ context='uri' I suggest using Sling Model if there is a business logic included for URI or string manipulation.
https://experienceleaguecommunities.adobe.com/t5/adobe-experience-manager/href-link-with-column-value/m-p/448055
CC-MAIN-2022-27
en
refinedweb
The Fibonacci Sequence is a famous number sequence. Each number in the Fibonacci sequence is the sum of the two numbers before it. The sequence, like Python and almost every other programming language, is 0 indexed with the 0th number being 0. The first number is 1. The first and 0th numbers are the “seed” numbers of the Fibonacci sequence. That means that they are the only ones that are set and every other number can be generated from them. The first 11 Fibonacci numbers (starting at 0) are: 0, 1, 1, 2, 3, 5, 8, 13, 21, 34, 55. Examples of the Fibonacci Sequence It shows up in many real life examples. For example, Indian mathematicians first noted it showing up in Sanskrit poems. The below image is taken from Wikipedia showing the pattern of syllable enunciation in Sanskrit poems. It illustrates that there are 13 (the 7th Fibonacci number) ways to arrange long and short syllables in a cadence of 6. Of these 13, 5 (the 5th Fibonacci number) end with a short syllable, and 8 (the 6th Fibonacci number) end with a long syllable. Another application of the Fibonacci sequence is as an approximation of the Golden Ratio. The below image shows an approximation of the golden spiral generated using Fibonacci numbers. The golden spiral is a self-similar (looks the same as you zoom in and out) spiral with a growth ratio of the golden ratio. Examples of the golden spiral in nature are spiral galaxies and the arrangement of leaves on a plant stem. There are at least three ways to generate the Fibonacci sequence, here we will cover three of them. You can generate Fibonacci numbers iteratively, recursively, or with dynamic programming. We won’t need any non-native Python libraries so we won’t need to install anything extra through the command line. Let’s get into how we can generate the Fibonacci sequence in Python Iteratively Generating Fibonacci Numbers What does it mean to do something iteratively? It means we’re going to apply a repeated rule a set number of times. In this case, the repeated rule we’re applying is that a Fibonacci number is the sum of the two Fibonacci numbers before it. We have to start with the axiomatic 0th and 1st Fibonacci numbers and return those as 0 and 1 before we get into the iterative generation of the sequence. To generate the sequence, we seed the sequence with our 0th and 1st Fibonacci numbers. Then loop through n-1 iterations where each iteration sees us adding the last two Fibonacci numbers together to generate the nth one. After we set the value of the nth Fibonacci number we go back and reset the value of the n-1th and n-2th numbers to what they should be. At the end, we return the expected Fibonacci number. def fibonacci(n): if n == 0: return 0 if n == 1: return 1 f0 = 0 f1 = 1 for i in range(n-1): f = f0 + f1 f0 = f1 f1 = f return f print(fibonacci(10)) Running this code should return 55 as pictured below. Recursively Generating the Fibonacci Sequence What is a recursive function? A recursive function is one that calls itself. I briefly touched on this when I wrote about Functions and Classes. The Fibonacci sequence is perfect for a recursive relation. Each number is generated as the sum of the two numbers before it. As we always have to do with Fibonacci sequences, we’ll simply seed the 0th and 1st number and away we go. We don’t have to handle re-assigning any numbers to any variables here because we just call the function on n to get the nth Fibonacci number. What’s a drawback to this? It’s extremely time consuming at a large value of n. For smaller values it’s fine, and it’s also less code than an iterative function, but at large values we’re in trouble. We would have to calculate each number multiple times. When we calculate the 10th Fibonacci number or the 20th Fibonacci number it’s not too bad because the number of wasted calculations grows exponentially. So, how can we solve this? Dynamic Programming. The third approach. # 0 1 1 2 3 5 8 13 21 ... def fibonacci(n): if n == 0: return 0 if n == 1: return 1 return fibonacci(n-1) + fibonacci(n-2) print(fibonacci(10)) When we print our 10th Fibonacci number via the recursive function, it should still be 55 like the image below. Dynamic Programming for the Fibonacci Sequence Dynamic Programming is an algorithmic technique for solving problems that build upon smaller problems. It is neither dynamic nor does it require programming. Confused? Yeah, me too. I have no idea why they called it that. There are multiple approaches to using dynamic programming to generate Fibonacci numbers but in this case, we’re going to be using the “bottom up” approach. A bottom up dynamic programming approach to generating Fibonacci numbers means we’ll be adding the numbers we’ve already calculated to a table so we don’t have to calculate them again. Dynamic programming still uses a recursive approach. Having a table with all the former Fibonacci numbers saves us from an exponential run time. To do this dynamic programming approach, we start by declaring a table with impossible values. The main advantage of this comes at larger values of n or when we want to generate many Fibonacci numbers. Note that this only works for the positive Fibonacci numbers. In our fibonacci function, we will start with our axiomatic 0th and 1st numbers as usual. We will add these Fibonacci numbers to our table before we return them. If n is not 0 or 1 we check if it’s already in the table. If it is, then we return the tabulated value, otherwise we’ll use the recursive approach to compute it. table = [-1 for _ in range(20)] def fibonacci(n): if n == 0: table[0] = 0 return 0 if n == 1: table[0] = 0 table[1] = 1 return 1 if table[n] != -1: return table[n] table[n] = fibonacci(n-1) + fibonacci(n-2) return table[n] for i in range(20): print(fibonacci(i)) For this example, I’ve decided to use the dynamic programming approach to Fibonacci numbers to generate the first 20. As I said above, one of the advantages of this approach is that it’s nice when you’re generating a lot of numbers as well as for high values of n. More by the Author - How to use Python Dotenv - Prims Algorithm in Python - Dijkstras Algorithm in Python - Neural Network Code in Python from Scratch - Python Generate a Deck of
https://pythonalgos.com/three-ways-to-generate-fibonacci-numbers-in-python/
CC-MAIN-2022-27
en
refinedweb
Writing small, focused tests, often called unit tests, is one of the things that look easy at the outset but turn out to be more delicate than anticipated. Writing a three-lines-of-code unit test in the triple-A structure soon became second nature to me, but there were lots of cases that resisted easy testing. Using mock objects is the typical next step to accommodate this resistance and make the test code more complex. This leads to 5 to 10 lines of test code for easy mock-based tests and up to thirty or even fifty lines of test code where a lot of moving parts are mocked and chained together to test one single method. So, the first reaction for a more complicated testing scenario is to make the test more complicated. But even with the powerful combination of mock objects and dependency injection, there are situations where writing suitable tests seems impossible. In the past, I regarded these code blocks as “untestable” and omitted the tests because their economic viability seemed debatable. I wrote small tests for easy code, long tests for complicated code and no tests for defiant code. The problem always seemed to be the tests that just didn’t cut it. Until I could recognize my approach in a new light: I was encumbering the messenger. If the message was too harsh, I would outright shoot him. The tests tried to tell me something about my production code. But I always saw the problem with them, not the code. Today, I can see that the tests I never wrote because the “test story” at hand was too complicated for my abilities were already telling me something important. The test you decide not to write because it’s too much of a hassle tells you that your code structure needs improvement. They already deliver their message to you, even before they exist. With this insight, I can oftentimes fix the problem where it is caused: In the production code. The test coverage increases and the tests become simpler. Let’s look at a small example that tries to show the line of thinking without being too extensive: We developed a class in Java that represents a counter that gets triggered and imposes a wait period on every tenth trigger impulse: public class CountAndWait { private int triggered; public CountAndWait() { this.triggered = 0; } public void trigger() { this.triggered++; if (this.triggered == 10) { try { Thread.sleep(1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } this.triggered = 0; } } } There is a lot going on in the code for such a simple functionality. Especially the try-catch block catches my eye and makes me worried when thinking about tests. Why is it even there? Well, here is a starter link for an explanation. But even without advanced threading issues, the normal functionality of our code is worrisome enough. How many lines of code will a test contain that covers the sleep? Should I really use a loop in my test code? Will the test really have a runtime of one second? That’s the same amount of time several hundred other unit tests require for much more coverage. Is this an economically sound testing approach? The test doesn’t even exist and already sends a message: Your production code should be structured differently. If you focus on the “test story”, perhaps a better structure emerges? The “story of the test” is the description of the production code path that is covered and asserted by the test. In our example, I want the story to be: “When a counter object is triggered for the tenth time, it should impose a wait. Afterwards, the cycle should repeat.” Nothing in the story of this test talks about interruption or exceptions, so if this code gets in the way, I should restructure it to eliminate it from my story. The new production code might look like this: public class CountAndWait { private final Runnable waiting; private int triggered; public static CountAndWait forOneSecond() { return new CountAndWait(() -> { try { Thread.sleep(1000L); } catch (InterruptedException e) { Thread.currentThread().interrupt(); } }); } public CountAndWait(Runnable waiting) { this.waiting = waiting; this.triggered = 0; } public void trigger() { this.triggered++; if (this.triggered == 10) { this.waiting.run(); this.triggered = 0; } } } That’s a lot more code than before, but we can concentrate on the latter half. We can now inject a mock object that attests to how often it was run. This mock object doesn’t need to sleep for any amount of time, so the unit test is fast again. Instead of making the test more complex, we introduced additional structure (and complexity) into the production code. The resulting unit test is rather easy to write: class CountAndWaitTest { @Test @DisplayName("Waits after 10 triggers and resets") void wait_after_10_triggers_and_reset() { Runnable simulatedWait = mock(Runnable.class); CountAndWait target = new CountAndWait(simulatedWait); // no wait for the first 9 triggers Repeat.times(9).call(target::trigger); verifyNoInteractions(simulatedWait); // wait at the 10th trigger target.trigger(); verify(simulatedWait, times(1)).run(); // reset happened, no wait for another 9 triggers Repeat.times(9).call(target::trigger); verify(simulatedWait, times(1)).run(); } } It’s still different from a simple 3-liner test, but the “and” in the test story hints at a more complex story than “get y for x”, so that might be ok. We could probably simplify the test even more if we got access to the internal trigger count and verify the reset directly. I hope the example was clear enough. For me, the revelation that test problems more often than not have their root cause in production code is a clear message to improve my ability on writing code that facilitates testing instead of obstructing it. I don’t shoot/omit my messengers anymore even if their message means more work for me.
https://schneide.blog/tag/tests/
CC-MAIN-2022-27
en
refinedweb
Details - Type: Bug - Status: Closed - Priority: Minor - Resolution: Complete - Affects Version/s: 3.1.0 - - - Labels: - Environment:HideOS:ShowOS: Description Port-mappings does not work properly, when it setup in spring xml configuration such as: <ss:port-mappings> <ss:port-mapping </ss:port-mappings> with: <ss:form-login Spring security redirected me to url ( must be) with 8443 port (by default in the org/springframework/security/web/PortMapperImpl.java) when I try to access protected page. I edited PortMapperImpl.java: public PortMapperImpl(){ httpsPortMappings = new HashMap<Integer, Integer>(); httpsPortMappings.put(Integer.valueOf(8080), Integer.valueOf(8080)); } and redirection is working now to 8080 https. I think that when <ss:port-mappings>...</ss:port-mappings> setted, PortMapperImpl.java: private final Map<Integer, Integer> httpsPortMappings; "httpsPortMappings" not cleaned properly, and previously key value are available. Activity - All - Work Log - History - Activity - Transitions Summary I have been able to reproduce this issue, using Spring Security 3.1.0.RELEASE and Apache Tomcat 6.0.35 on Windows 7 x64. I installed Tomcat using the Windows .msi installer, and the only change I've made to its configuration is the change to conf/server.xml described below. I've attached to this issue a small web application that I used to reproduce this issue. This web application has a single login-protected page, and if you get to the login page, the credentials test/test should let you log in. To reproduce the issue: - Extract the attached zip file TestSecureApp.zip somewhere. - Edit the extracted build.xml file and set the value of the property tomcat.home to your Tomcat home directory. - Run ant to compile, build and deploy to Tomcat a WAR file for this web application. - Set up SSL in Tomcat, following the instructions at : - Run keytool, using the default password changeit. - Add the following Connector element to conf/server.xml within Tomcat, and comment out all other Connectors. Change the location of the keystoreFile as appropriate. <Connector port="8080" protocol="HTTP/1.1" SSLEnabled="true" maxThreads="150" scheme="https" secure="true" keystoreFile="C:/Users/Luke/.keystore" keystorePass="changeit" clientAuth="false" sslProtocol="TLS" /> - Start Tomcat, and navigate to. You'll get a warning about an invalid (self-signed) security certificate: ignore/accept it as necessary. This should bring up the Tomcat default page (unless you've replaced it with something else). - Navigate to. Using Firefox, I get an error "Firefox can't establish a connection to the server at localhost:8443." I've done a brief bit of digging into this issue myself. I set a breakpoint in PortMapperImpl.lookupHttpsPort (line 68 of org/springframework/security/web/PortMapperImpl.java by my reckoning) and then attempted to log into my application. I found that this breakpoint was hit three times. The first two times, the port mapper had the mapping I set up in applicationContext-security.xml (8080 -> 8080). However, the third time this breakpoint was hit, it was in a different PortMapperImpl instance, and this instance still had the default 80 -> 443 and 8080 -> 8443 mappings in it. Ultimately, it seems that there is more than one PortMapperImpl instance kicking about, and it's the other one (or ones?) that are the problem here. The problem is that the PortResolver in the LoginUrlAuthenticationEntryPoint uses a PortMapper that is not configured by the namespace (AuthenticationConfigBuilder). This would only impact instances where the http port is using a common https port or vice versa. In the meantime, you can configure the LoginUrlAuthenticationEntryPoint explicitly. Something like the following should work: <sec:http ... <sec:port-mappings > <sec:port-mapping </sec:port-mappings> </sec:http> <bean id="entryPoint" class="org.springframework.security.web.authentication.LoginUrlAuthenticationEntryPoint"> <constructor-arg <property name="portResolver"> <bean class="org.springframework.security.web.PortResolverImpl"> <property name="portMapper" ref="portMapper"/> </bean> </property> <!-- this also doesn't get set but is only necessary if you were using forceHttps=true --> <property name="portMapper" ref="portMapper"/> </bean> <bean id="portMapper" class="org.springframework.security.web.PortMapperImpl"> <property name="portMappings"> <map> <entry key="8080" value="8080"/> </map> </property> </bean> PS: Any reason the attached example application maps the http port 8080 to https port 8080?. In reply to comment #4: >. Ok so this was just an attempt to work around the bug then. I ask because it can be useful to know what others are doing and why they are doing it. I've now tested the fix (sorry for the delay in doing so) and I can confirm that it works. Thanks. I'm not able to reproduce this issue in Spring Security 3.1. I do not think the default constructor is a problem because PortMapperImpl.setPortMappings invokes httpsPortMappings.clear(). I'm curious how it even got to the login page then since if it was doing the port mapping incorrectly the request for the protected resource of https would have been the wrong URL meaning that a redirect to the login page would not have worked. I noticed that the URLs in your Spring Security configuration were using /app but the URL you posted did not. Are you by chance using UrlRewriteFilter? If so, this may be the source of the problem. If you still believe this is an issue, can you provide as simple of a project that reproduces the problem and provide instructions on how to reproduce this issue?
https://jira.springsource.org/browse/SEC-1893
CC-MAIN-2014-10
en
refinedweb
#include <rb_construction_base.h> Detailed Description template<class Base> class libMesh::RBConstructionBase< Base > This class is part of the rbOOmit framework. This is the base class for the Construction stage of the certified reduced basis (RB) method. We template the Base class so that we can derive from the appropriate libMesh System type (e.g. LinearImplicitSystem for standard reduced basis, EigenSystem for SCM) at compile time. Definition at line 57 of file rb_construction_base.h. Member Typedef Documentation Data structure to log the information. The log is identified by the class name. Definition at line 113 of file reference_counter.h. The type of system. Definition at line 77 of file rb_construction_base.h. Constructor & Destructor Documentation Constructor. Initializes required data structures. Destructor. Member Function Documentation Broadcasts parameters on processor proc_id to all processors. Clear all the data structures associated with the system. Reimplemented from libMesh::RBParametrized. Reimplemented in libMesh::RBConstruction, libMesh::RBSCMConstruction, libMesh::RBEIMConstruction, libMesh::TransientRBConstruction, and libMesh::TransientSystem< RBConstruction >. Definition at line 106 of file reference_counter.C. References libMesh::ReferenceCounter::_enable_print_counter. Methods to enable/disable the reference counter output from print_info() Definition at line 100 of file reference_counter.C. References libMesh::ReferenceCounter::_enable_print_counter. Static helper function for generating a deterministic set of parameters. Only works with 1 or 2 parameters (as defined by the lengths of min/max parameters vectors), otherwise throws an error. Static helper function for generating a "partially" random set of parameters, that is the parameter indicated by this->get_deterministic_training_parameter() will be deterministic. Static helper function for generating a randomized set of parameters. Get the name of the parameter that we will generate deterministic training parameters for. Get the number of times each sample of the deterministic training parameter is repeated. Get the first local index of the training parameters. Static function to return the error pair (index,error) that is corresponds to the largest error on all processors. Gets a string containing the reference information. Definition at line 47 of file reference_counter.C. References libMesh::ReferenceCounter::_counts, and libMesh::Quality::name(). Referenced by libMesh::ReferenceCounter::print_info(). Get the last local index of the training parameters. Get the total number of training samples local to this processor. Get the number of parameters. Get the total number of training samples. RBParameters in index index of training set. Increments the construction counter. Should be called in the constructor of any derived class that will be reference counted. Definition at line 163 of file reference_counter.h. References libMesh::ReferenceCounter::_counts, libMesh::Quality::name(), and libMesh::Threads::spin_mtx. Referenced by libMesh::ReferenceCountedObject< RBParametrized >::ReferenceCountedObject(). Increments the destruction counter. Should be called in the destructor of any derived class that will be reference counted. Definition at line 176 of file reference_counter.h. References libMesh::ReferenceCounter::_counts, libMesh::Quality::name(), and libMesh::Threads::spin_mtx. Referenced by libMesh::ReferenceCountedObject< RBParametrized >::~ReferenceCountedObject(). Initializes the member data fields associated with the system, so that, e.g., assemble() may be used. Reimplemented in libMesh::RBEIMConstruction, and libMesh::TransientSystem< RBConstruction >. Initialize the parameter ranges and set current_parameters. Initialize the parameter ranges and set current_parameters. Initialize the parameter ranges and indicate whether deterministic or random training parameters should be used and whether or not we want the parameters to be scaled logarithmically. Overwrite the training parameters with new_training_set. Prints the number of outstanding (created, but not yet destroyed) objects. Definition at line 79 of file reference_counter.h. References libMesh::ReferenceCounter::_n_objects. Prints the reference information, by default to libMesh::out. Definition at line 88 of file reference_counter.C. References libMesh::ReferenceCounter::_enable_print_counter, and libMesh::ReferenceCounter::get_info(). Print the current parameters. Read in the parameter ranges from file. Initialize parameters to the "minimum" parameter values. Resets the PC (and iterative solver, if desired) in the passed-in LinearSolver object to the values specified in the pair of strings passed as the second argument. If the "alternative_solver" string, defined below, is "unchanged", this function does nothing. Changes the current PC (and iterative solver, if desired) in the passed-in LinearSolver object to an alternative solver specified by the alternative_solver string stored in this class. You might use this to e.g. switch to a sparse direct solver for the multiple RHS solves executed during the update_residual_terms function. The return strings are names of the original PC and KSP objects, you can reset these using the reset_alternative_solver() function below. Set the name of the parameter that we will generate deterministic training parameters for. Defaults to "NONE". Set the number of times each sample of the deterministic training parameter is repeated. Set the current parameters to params Set parameters to the RBParameters stored in index index of the training set. Load the specified training parameter and then broadcast to all processors. Set the seed that is used to randomly generate training parameters. - Returns - a clever pointer to the system. Definition at line 82 of file rb_construction_base.h.(). The name of the parameter that we will generate a deterministic training parameters for in the case of a "partially random" training set. Definition at line 308 of file rb_construction_base.h. The number of times each sample of the deterministic training parameter is repeated in generating the training set. Definition at line 314 of file rb_construction_base.h.(). Set this string to specify an alternative solver used in the set_alternative_solver() function above. Currently-supported values are: .) unchanged, to continue using the default truth solve solver .) amg, to use the BoomerAMG from Hypre (NOT for indefinite problems!) .) mumps, to use a sparse direct solver Note1: mumps and amg will only be available if PETSc has been compiled with them. Note2: RBConstruction::process_parameters_file() is responsible for reading in this value ("rb_alternative_solver") from file for RBConstruction-derived subclasses Note3: RBSCMSystem::process_parameters_file() reads this value ("scm_alternative_solver") for RBSCMSystem-derived subclasses Definition at line 279 of file rb_construction_base.h. We keep an extra temporary vector that is useful for performing inner products (avoids unnecessary memory allocation/deallocation). Definition at line 265 of file rb_construction_base.h. This boolean flag indicates whether or not the training set should be the same on all processors. By default it is false, but in the case of the Empirical Interpolation Method (RBEIMConstruction), for example, we need the training set to be identical on all processors. Definition at line 258 of file rb_construction_base.h. The training samples. Definition at line 293 of file rb_construction_base.h. Boolean flag to indicate whether or not the parameter ranges have been initialized. Definition at line 288 of file rb_construction_base.h. If < 0, use std::time() * processor_id() to seed the random number generator for the training parameters (default). If >= 0, use the provided value * processor_id() as the random number generator seed. Definition at line 301 of file rb_construction_base.h. Public boolean to toggle verbose mode. Definition at line 135 of file rb_parametrized.h. The documentation for this class was generated from the following file:
http://libmesh.sourceforge.net/doxygen/classlibMesh_1_1RBConstructionBase.php
CC-MAIN-2014-10
en
refinedweb
* A double or float? Graham Robinson Greenhorn Joined: Nov 23, 2005 Posts: 16 posted Dec 11, 2005 06:38:00 0 Hi, this code is basically meant to work out an olympic dive score, Then print out a bar chart, using rectangles. But, the difficulty can be between 1.2 and 3.5. So an Int wont work, but when i change it, there is problems with the rect object, loss of precision or something. And that it needs an int, but of course the bar uses score, which can be anyhing, so that can't be a Int either. I'm really stuck on how to do this, any help would be great thanks. Heres the code import element.*; import java.awt.Color; /** * Prompt user for 7 scores for Olympic Diving. * and produce the lowest, average and overall mark, printed on a bar chart. * @Author Robinson * @version 11 November 2005 */ public class DivingScores { public static void main (String[] args) { //consrtuct new console window ConsoleWindow c = new ConsoleWindow(); // construct a drawing window object DrawingWindow d = new DrawingWindow(300, 350); //Foreground d.setBackground(Color.orange); d.clear(d.bounds()); //variable int score, difficult, judge, heaviest = 0, x = 10, height, barTop, x2 = 16; final int WIDTH = 20; boolean valid, validiff; float total = 0.0f, average = 0.0f; //axes d.setForeground(Color.green); d.moveTo (30, 40); d.lineTo (30, 250); d.lineTo (240, 250); //y axes d.setForeground(Color.blue); Text judge1 = new Text ("Judge", 122, 280); judge1.drawOn(d); //x axes Text score1 = new Text ("Score", 15, 20); score1.drawOn(d); // for axis for(int count = 1; count <= 7; count++) { d.setForeground(Color.cyan); x2 = x2 + 30; Text m1 = new Text (count, x2, 260); m1.drawOn(d); } //for control include bar chart for(int count = 0; count < 7; count++) { do { c.out.println("Please input difficulty level of dive"); difficult = c.input.readInt(); validiff = (difficult >= 1.2 && difficult <= 3.5); if(!validiff) c.out.println("The entered value isn't within the accepted range."); else c.out.println("Please input score of dive");//user enter score score = c.input.readInt();//rainfall value entered by user valid = (score >= 0 && score <= 200); if (!valid) c.out.println("The value entered isn't valid."); } while(!valid); total += score;//total of rainfall x = x + 30; height = score; barTop = (250 - height); // Set the foreground to red. d.setForeground(Color.magenta); Rect bar = new Rect(x, barTop, WIDTH, height); bar.fillOn(d); if (score > heaviest) heaviest = score; average = total / 12; }//end of for //Drawing Window print d.setForeground(Color.white); Text heavy = new Text ("Heaviest Rainfall " + heaviest + "mm", 30, 295); heavy.drawOn(d); Text avR = new Text ("Average Rainfall " + average + "mm", 30, 310); avR.drawOn(d); //Console Window Print c.out.println("Heaviest rainfall = " + heaviest); c.out.println("Average rainfall = " + average); }//end of class }//end of main BTW you may seen things to do with rainfall, i just copied it from an old program, but theyr are just prompts and comments. [ December 11, 2005: Message edited by: Graham Robinson ] Keith Lynn Ranch Hand Joined: Feb 07, 2005 Posts: 2367 posted Dec 11, 2005 13:47:00 0 You might try using a scale like 1000 points is the distance between the bottom of the bar chart and the top of the bar chart. Use a double and round it to 2 places, then multiply is by 100 and that will give you a point in the chart. Graham Robinson Greenhorn Joined: Nov 23, 2005 Posts: 16 posted Dec 13, 2005 10:51:00 0 Thanks, but i managed to do it using an int typecast, doesn't give as accurate results, but works. Layne Lund Ranch Hand Joined: Dec 06, 2001 Posts: 3061 posted Dec 13, 2005 11:09:00 0 For more accurate results, you might want to try Keith's suggestion. You said that the score can be anything between 1.2 and 3.5. Are you sure about this? The value of PI lies in this range. Is this a possible score value? Somehow I doubt it. In fact, there are probably MANY values between 1.2 and 3.5 that are not likely to be used as a score. However, it might be more helpful to describe what values CAN be used. For example, you can restrict the user input to only a few decimal places (2 for example). In this case, you can use an int that is really 100 times the actual score. This might take some extra processing for getting the input, but it will make drawing the bar chart much easier and more precise. Alternatively, you can keep the float values that you have and just multiply them by 100 (or 1000 or whatever) before you graph them. The bar chart shows a relative value anyways, so such a scaling won't make any visible difference in the final result. You will still need to cast the result to an int after the multiplication, but it seems you have figured out how to do that. Layne Java API Documentation The Java Tutorial Graham Robinson Greenhorn Joined: Nov 23, 2005 Posts: 16 posted Dec 13, 2005 11:29:00 0 Well the scores have to be within that range, as it's the dives difficulty, not the actual score. The bar chart is more of an indication, this is how i did it. import element.*; import java.awt.*; import java.lang.*; /** * Prompt user for 7 scores for Olympic Diving. * and produce the lowest, average and overall mark, printed on a bar chart. * @Author Robinson * @version 12 November 2005 */ public class DivingScores { public static void main (String[] args) { //consrtuct new console window ConsoleWindow c = new ConsoleWindow(); // construct a drawing window object DrawingWindow d = new DrawingWindow(290, 400; Color mySilver = new Color(212, 208, 200);//Standard colour for windows IE task bar etc Color mySilver2 = new Color(188, 188, 188);//Lighter grey for gridlines. //Foreground d.setBackground(mySilver); d.clear(d.bounds()); //variable int judge, low, lineTt = 30, total2, high, x = 10, x3 = 0, x4 = 0, y5 = 16, height, heightLow, heightAv, barTopAv, heightHigh, entry = 0, lowEntry = 0, highEntry = 0, barTopLow, barTopHigh, barTop, x2 = 16; double score = 0.0d, difficult = 0.0d, heaviest = 0.0d, lowest = 10.0d, overall = 0.0d, total = 0.0d, average = 0.0d; final int WIDTH = 20, LINET = 30, LINEL = 280; boolean valid, validiff; d.setForeground(Color.white); Rect back = new Rect(LINET, 50, 250, 200); back.fillOn(d); // for gridlines for(int count = 1; count <= 11; count++) { d.setForeground(mySilver2); lineTt = lineTt + 20; d.moveTo (LINET, lineTt); d.lineTo (LINEL, lineTt); } //axes d.setForeground(Color.black); d.moveTo (30, 40); d.lineTo (30, 250); d.lineTo (280, 250); //5 d.setForeground(Color.black); d.moveTo (30, 150); d.lineTo (280, 150); //10 d.moveTo (30, 50); d.lineTo (280, 50); //yaxes label Text judge1 = new Text ("Judge", 140, 275); judge1.drawOn(d); // axes label Text score1 = new Text ("Score", 15, 35); score1.drawOn(d); Text num5 = new Text ("5", 22, 155); num5.drawOn(d); Text num10 = new Text ("10", 15, 55); num10.drawOn(d); Text av = new Text ("AV", 257, 260); av.drawOn(d); // for axis for(int count = 1; count <= 7; count++) { x2 = x2 + 30; Text m1 = new Text (count, x2, 260); m1.drawOn(d); } do { c.out.println("Please input difficulty level of dive"); difficult = c.input.readDouble(); validiff = (difficult >= 1.2 && difficult <= 3.5); if(!validiff) c.out.println("The entered value isn't within the accepted range."); }while(!validiff); //for control include bar chart for(int count = 0; count < 7; count++) { do { c.out.println("Please input score of dive");//user enter score score = c.input.readDouble();//score valid = (score >= 0 && score <= 10); if (!valid) c.out.println("The value entered isn't valid."); } while(!valid); total += score;//total x = x + 30; entry++; if (score > heaviest) { heaviest = score; highEntry = entry; x3 = x; } if (score < lowest) { lowest = score; lowEntry = entry; x4 = x; } height = (int) score * 20; barTop = (250 - height); // Set the bars color. d.setForeground(Color.yellow); Rect bar = new Rect(x, barTop, WIDTH, height); bar.fillOn(d); average = (total - (lowest + heaviest)) / 5; overall = average * difficult; }//end of for //lowest and highest bars heightLow = (int) lowest * 20; barTopLow = (250 - heightLow); d.setForeground(Color.red); Rect barLH = new Rect(x4, barTopLow, WIDTH, heightLow); barLH.fillOn(d); heightHigh = (int) heaviest * 20; barTopHigh = (250 - heightHigh); Rect barH = new Rect(x3, barTopHigh, WIDTH, heightHigh); barH.fillOn(d); heightAv = (int) average * 20; barTopAv = (250 - heightAv); d.setForeground(Color.blue); Rect avy = new Rect(255, barTopAv, WIDTH, heightAv); avy.fillOn(d); d.moveTo (30, barTopAv); d.lineTo (280, barTopAv); //Drawing Window print d.setForeground(Color.red); Text heavy = new Text ("Highest mark " + heaviest, 30, 295); heavy.drawOn(d); Text lowee = new Text ("Lowest mark " + lowest, 30, 310); lowee.drawOn(d); d.setForeground(Color.blue); Text avR = new Text ("Average mark (AV)" + average, 30, 325); avR.drawOn(d); d.setForeground(Color.black); Text over = new Text ("Overall mark " + overall, 30, 340); over.drawOn(d); Text judgeLow = new Text ("Lowest mark from judge " + lowEntry, 30, 355); judgeLow.drawOn(d); Text judgeHigh = new Text ("Highest mark from judge " + highEntry, 30, 370); judgeHigh.drawOn(d); //Console Window Print c.out.println("Highest mark = " + heaviest); c.out.println("Lowest mark = " + lowest); c.out.println("Average mark = " + average); c.out.println("Overall mark = " + overall); c.out.println("total = " + total); c.out.println("Highest mark from judge " + highEntry); c.out.println("Lowest mark from judge " + lowEntry); }//end of class }//end of main I agree. Here's the link: subject: double or float? Similar Threads Storing count within a while Drawing in a loop Do whiles/Fors and Drawing Preventing program from crashing when user enters a char instead of a numerical input ArrayList Exceptions All times are in JavaRanch time: GMT-6 in summer, GMT-7 in winter JForum | Paul Wheaton
http://www.coderanch.com/t/401769/java/java/double-float
CC-MAIN-2014-10
en
refinedweb
15 July 2004 18:46 [Source: ICIS news] LONDON (CNI--London Metal Exchange (LME) ring trader Refco Overseas on Thursday announced the appointment of David Paul as global head of plastics. His appointment comes roughly five months ahead of the planned introduction of a plastics futures market on the LME, with contracts for polyethylene (PE) and polypropylene (PP). Paul is a former chief executive of Asahi Glass Plastics in ?xml:namespace> ‘We are pleased to welcome David to our company, Mark Slade managing director Refco Overseas said. “David’s senior executive background and technical expertise in the plastic industry will enable Refco to offer a comprehensive service to clients and is a significant appointment. The launch of these contracts on the LME provides Refco with an exciting opportunity to use its skill and experience gained over many years in the commodities markets to develop a new client base in this new product line.”?xml:namespace> Diversified financial group Refco is a ring dealing broker member of the 80-member LME. Other ring dealing members are: Amalgamated Metal Trading (AMT), Barclays Bank, Carr Futures, Credit Lyonnais Rouse, Man Financial, Metdist Trading, Natexis Metals, Sempra Metals, Societe Generale, Sucden (UK) and Triland
http://www.icis.com/Articles/2004/07/15/596984/david-paul-joins-lme-trader-refco-to-head-plastics-futures.html
CC-MAIN-2014-10
en
refinedweb
26 August 2011 05:42 [Source: ICIS news] By Felicia Loo SINGAPORE (ICIS)--Asia’s naphtha backwardation is likely to strengthen on expectations that Taiwanese Formosa Petrochemical Corp (FPCC) would restart its long overdue 700,000 tonne/year No 1 naphtha cracker at Mailiao sometime in September, traders said on Friday. The expectations of a restart have raised hopes of higher demand for naphtha in a market already quite short of molecules, traders said on Friday. The time spread between the first-half October and first-half November contracts was assessed at $6/tonne (€4.20/tonne) on Thursday, the strongest since 16 May when the inter-month spread was at $7/tonne, according to ICIS. The naphtha crack spread versus October Brent crude futures was valued at $135.60/tonne, up by $6.35/tonne on the previous week. “Naphtha is on an uptrend. Demand is outpacing supply. The market is heartened with ?xml:namespace> FPCC is expected to restart the No 1 naphtha cracker in September, with the unit's unplanned shutdown pushing on its fourth month. An FPCC spokesman had earlier said that the cracker restart would be earlier than November but did not provide an exact date. FPCC had shut the No 1 cracker for inspections following a pipeline fire at the firm’s Mailiao petrochemical complex on 12 May. “ The fact that FPCC is gradually restarting its crude distillation units at the 540,000 bbl/day refinery at Mailiao, bodes well for the cracker to resume operations, traders said. FPCC shut the refinery and related units entirely because of a fire in end-July. Supply wise, “The market seems to be strong because supplies are getting tighter. The arbitrage window is closed given a weak east-west spread. And The east-west spread was at a weak level of $4.90/tonne, a far cry from at least $27/tonne that would enable arbitrage economics to work, they added. “There is less (ethanol) output in Amid the tight supply situation in Indian refineries are curbing naphtha exports for September amid several plant turnarounds, with naphtha shipments being reduced to 850,000 tonnes from levels at above 900,000 tonnes in August, traders said. Reflecting a bullish market, a series of spot tenders garnered strong premiums. South Korea's LG Chem bought 75,000 tonnes of open-spec naphtha for delivery in the first-half of October, at premiums of $4.50/tonne and $5.00/tonne to Japan quotes CFR (cost & freight). South Korea’s Samsung Total Petrochemicals bought 50,000-75,000 tonnes of open-spec naphtha for delivery in the first half of October at a premium of $5/tonne to Japan quotes CFR. Indian refiner Oil and Natural Gas Corp (ONGC) has sold by tender 35,000 tonnes of naphtha for loading from Hazira on 11-12 September at a premium of $21-22/tonne to Middle East quotes FOB. India’s Reliance Industries Limited (RIL) sold 55,000 tonnes of naphtha to trading firm Itochu for loading from Sikka on 10-20 September at Middle East quotes FOB plus $21/tonne. Meanwhile, Qatar International Petroleum Marketing (Tasweeq) has sold by tender 50,000 tonnes of plant condensate and 30,000 tonnes each of full-range naphtha and Pearl GTL (gas-to-liquids) naphtha for loading in September, at premiums of $19-22/tonne to Middle East quotes Fan. “Downstream (petrochemical) prices are holding. I don’t see why naphtha can’t be bullish,” said one trader. Additional reporting by Lester Teo ($1 = €0.70) Please visit the complete ICIS plants and projects database For more information
http://www.icis.com/Articles/2011/08/26/9488132/asia-naphtha-backwardation-to-widen-on-firm-demand-tight-supply.html
CC-MAIN-2014-10
en
refinedweb
SciChart® the market leader in Fast WPF Charts, WPF 3D Charts, and iOS Chart & Android Chart Components I am directly editing my XyDataSeries on a chart by using my mouse. As the mouse moves I edit either the x or y value of a point using the methods public void SetPointYValueAt(IDataSeries series, int index, double newValue) { series.YValues[index] = newValue; series.InvalidateParentSurface(RangeMode.None); } public void SetPointXValueAt(IDataSeries series, int index, double newValue, double xMin, double xMax) { var xValue = newValue; // limit x values to keep them sorted if (xValue < xMin) xValue = xMin; if (xValue > xMax) xValue = xMax; series.XValues[index] = xValue; series.InvalidateParentSurface(RangeMode.None); } With this code I am not getting an update at my ViewModel: public IDataSeries<double, double> MyDataSeries { get { return _myDataSeries; } set { _myDataSeries = value; OnPropertyChanged("MyDataSeries"); } } Here is my XAML: <sciChartExtensions:StepLineRenderableSeries x: Where StepLineRenderableSeries is derived from FastLineRenderableSeries with IsDigitalLine = true and the HitTest method overridden. How can I get MyDataSeries to update? I should have given more details. The methods SetPointXValueAt and SetPointYValueAt are located in a derived class public class StepSeriesDataPointEditModifier : SeriesSelectionModifier For this reason putting OnPropertyChanged in those methods will not help. I will explain why I need to do this. I have a DigitaLine plot which is used to edit the data in the plot. The edited data has to be available in the viewmodel and model, where it will be used as input for numerical modeling. I was hoping there would be some method in the dataseries that I could call to force the notification that it has changed. I am part way there. I can add a handler to my viewmodel with MyDataSeries.DataSeriesChanged += OnDataSeriesChanged; but to invoke the DataSeriesChanged I have to modify my methods: public void SetPointYValueAt(IDataSeries series, int index, double newValue) { //series.YValues[index] = newValue; var xyDataSeries = series as XyDataSeries<double, double>; if (xyDataSeries != null) { var x = xyDataSeries.XValues[index]; xyDataSeries.RemoveAt(index); xyDataSeries.Insert(index, x, newValue); } series.InvalidateParentSurface(RangeMode.None); } Removing a data point and adding a new one triggers the DataSeriesChanged, but it is not as clean as just reseting the y value.
https://www.scichart.com/questions/wpf/how-do-i-update-my-viewmodel-when-a-dataseries-changes?tab=answers&sort=votes
CC-MAIN-2020-29
en
refinedweb
для этой страницы, отображается код на другом Video Wall Output with AppWall Plugin AppWall application is designed for rendering the Unigine world into the configurable number of windows. The number of AppWall monitors is not limited. They can fit any display configuration and can be rendered both in the windowed and the full screen mode. The following display configurations are supported out of the box (only if monitors have identical resolutions): - 1 monitor (1×1) - 2 monitors in a column (1×2) - 2 monitors in a row (2×1) - 3 monitors in a row (3×1) - 4 monitors in a row (4×1) - 5 monitors in a row (5×1) - 4 monitors (2×2) - 6 monitors (3×2) See Also - engine.wall functions - An app_wall_00 sample Launching AppWall In case you use one of these configurations, you only need to specify a plugin library (lib/AppWall_*) with the usually required start-up arguments (such as rendering API, window size, etc.) in the launcher. main_x86 -extern_plugin AppWall - Unigine engine automatically detects the number of available monitors and if they fit any of the supported configurations, it automatically creates the appropriate number of windows with Unigine viewports. - You can use 32-bit, 64-bit, debug or release versions of the library. (The engine automatically loads the appropriate version of the library depending on the specified main application.) - Multi-monitor plugins (AppSurround, AppProjection) - Panoramic rendering - Stereo 3D How to Set the Number of Windows If you want to set the number of AppWall windows manually and use another supported configuration, you need to specify two specific start-up arguments in addition to the usually required ones: - width — sets the number of monitors in a horizontal row - height — sets the number of rows, i.e. how many monitors there are in a vertical column For example, if you want to launch AppWall in 6 windows (2 rows of monitors with 3 monitors in each row): main_x86 -width 3 -height 2 -extern_plugin AppWall Do not forget to specify other required start-up arguments as well! Customizing AppWall AppWall can be easily customized to support the desired configuration of monitors. You can create AppWall that renders Unigine viewports into the arbitrary number of windows with custom viewing frustums (symmetric or asymmetric ones). AppWall Cameras AppWall have one primary viewport, monitor and auxiliary ones can be enabled or disabled, if necessary. - The primary display can be set to any monitor (for supported configurations it is already set). - Each display has its own model-view and projection matrices. - By default, only a primary one has an interface (render system GUI, editor widgets, wireframe, or the profiler). However, separate GUIs can be drawn on all monitors (see the sample for more details). - All viewports have their own viewport and reflection mask to selectively render nodes and reflections from them. Default Configurations For default configurations, the primary display is set to the following monitor: - For 1×1 configuration, the 1st (and only) display. - For 2×1 configuration, the 1st display. - For 3×1 configuration, the 2nd display. - For 4×1 configuration, the 2nd display. - For 5×1 configuration, the 3rd display. - For 1×2 configuration, the 1st display in the column. - For 2×2 configuration, the 1st display in the 1st row. - For 3×2 configuration, the 2nd display in the 1st row. How to Set Up Custom Cameras Configuration Rendering of AppWall viewports is controlled by wall.h script (located in <UnigineSDK>/data/core/scripts/system). To implement a custom camera configuration, comment the wall.h out in the unigine.cpp system script and wrap your custom code around with #ifdef HAS_APP_WALL ... #endif in the render() function of the system script: There are two possible setups depending on how the primary monitor is rendered. It can be drawn by: - The default engine renderer (the same as when a usual one-window application is rendered). - The AppWall renderer itself (which is safer if you are going to use asymmetric frustum for the primary monitor and modify its model-view matrix). The following example demonstrates how to create a 3×1 monitor configuration and choose the renderer for the primary monitor. 1. Using default engine renderer The first variant is to render the primary monitor by the default engine renderer. - In case the created configuration is not supported by default, set the primary monitor via engine.wall.setPrimary():Source code (UnigineScript) // The primary display is the 2nd one in a row and // it is positioned in the first line of monitors. engine.wall.setPrimary(1,0); - Enable all auxiliary monitors via engine.wall.setEnabled() (they are disabled by default). The primary one should be disabled, as it is drawn by the default engine renderer.Source code (UnigineScript) // Enable the 1st and the 3rd monitors in the first row. // The third argument of the function sets 'enabled' flag. engine.wall.setEnabled(0,0,1); engine.wall.setEnabled(2,0,1); - Set projection and model-view matrices for auxiliary monitors via engine.wall.setProjection() and engine.wall.setModelview().Source code (UnigineScript) // Settings for the 1st monitor engine.wall.setProjection(0,0,projection_0); engine.wall.setModelview(0,0,modelview_0); // Settings for the 3rd monitor engine.wall.setProjection(2,0,projection_1); engine.wall.setModelview(2,0,modelview_1); 2. Using AppWall renderer Another variant is to render the primary monitor by the AppWall AppWall monitors including the primary one. As a result, all three viewports will be rendered by AppWall renderer itself:Source code (UnigineScript) // Enable all AppWall monitors: engine.wall.setEnabled(0,0,1); engine.wall.setEnabled(1,0,1); engine.wall.setEnabled(2,0,1); - Set model-view and projection matrices for all three monitors.Source code (UnigineScript) // Settings for the 1st monitor engine.wall.setProjection(0,0,projection_0); engine.wall.setModelview(0,0,modelview_0); // Settings for the 2nd (primary) monitor engine.wall.setProjection(1,0,projection_1); engine.wall.setModelview(1,0,modelview_1); // Settings for the 3rd monitor engine.wall.setProjection(2,0,projection_2); engine.wall.setModelview(2,0,modelview_2);
https://developer.unigine.com/ru/docs/2.7/principles/render/output/multi_monitor/appwall/?rlang=cpp
CC-MAIN-2020-29
en
refinedweb
3.42.Questions and Exercises: Classes Questions - Consider the following class: public class IdentifyMyParts { public static int x = 7; public int y = 3; } - What are the class variables? - What are the instance variables? -); Exercises - Write a class whose instances represent a single playing card from a deck of cards. Playing cards have two distinguishing properties: rank and suit. Be sure to keep your solution as you will be asked to rewrite it in Enum Types. Hint: You can use the assert statement to check your assignments. You write: assert (boolean expression to test); If the boolean expression is false, you will get an error message. For example, assert toString(ACE) == “Ace”; should return true, so there will be no error message. If you use the assert statement, you must run your program with the ea.
https://www.onlinetrainingzone.org/java/?section=questions-and-exercises-classes-2
CC-MAIN-2020-29
en
refinedweb
From: Stjepan Rajko (stipe_at_[hidden]) Date: 2007-06-07 13:58:04 Hi Michael! Sorry for the slight delay, I've been reading up on things so that I don't make yet another series of uninformed statements without at least trying to do better :-) On 6/5/07, Michael Tegtmeyer <tegtmeye_at_[hidden]> wrote: > > I would really like to see this library in boost, would you like any > > help getting it ready for submission? I have recently learned how to > > use bjam, do boost-style docs etc, and have time to lend a hand. If > > we wanted to work together on preparing this, it would be good to put > > the code in the boost sandbox so we can both access it via subversion. > > Thanks, I am interested in whatever help you could offer. I have little > experience in bjam nor the boost document style. Cool - let's coordinate this off the list. > > code readability and maintainability - there is a lot of code > > repetition in the .h file, also it could use to be chunked up into > > smaller files (it is really hard to look at a ~5000 line header file). > > Did you use a code generation script to make that file? It could > > benefit from using macros for all the similar functions, which can be > > readily made from the code generation script if you used one. > > I didn't use a code generator but most is copy-paste, At one point I had > macros to generate each individual case but debugging (use code, not > library code) became a pain. ie it was easier to track down a compiler > error when it said "no operator in expression<lots and lots of stuff> on > line 42 which said __positive::T operator[](std::size_t n) const {return > +(value[n]);} rather than MAKE_EXPRESSION_TIMES(...) which was a top-level > macro and the real problem was missing operator + nested 8 layers. (real > problem we had). So since the library has been stable for a few years, we > got rid of the macros to aid debugging it's use. Yeah, I suppose macros are a matter of taste. I've had similar problems with similar uses of macros as what you mention. An alternative is something like #define THIS add #define THAT + #include <template_file_that_uses_this_and_that> , which preserves line numbers of readable code and is a little more debugging friendly. In your case, I think it even might be possible to use the preprocessor library to define sequence of function names and operators, and iterate over the same file that just pops a pair of function name and operator from the sequence into their implementation. But I've never tried anything like that so I'm not sure. > I think that I have a better understanding of what you are looking for but > let me get the following out of the way: > > I'm not sure that a general purpose container is the best use for this > class. cvalarray is meant to mimic the semantics and purpose of > std::valarray. Which is specifically designed for numeric values. I think > that if the purpose is general, then so should the interface, ie not mimic > std::valarray. One could claim that the incorrect use of boost::array and > by implication a general-purpose cvalarray is not our problem but IMHO, > libraries should be easy to use correctly and hard to use incorrectly. After looking into what you're doing, and what could be done in the general case, I agree with you 100%. I didn't realize that you were limited by adopting the requirements for valarray. Out of curiosity, why "incorrect use of boost::array"? > Additionally, the next step for cvalarray here is for it to automatically > use SIMD instructions to further speed up the numeric operations. Again > making its use general purpose will unnecessarily complicate things. Actually, I stuck the std::string bit into the code I sent you just to see if it would work :-). I'm not really vested into elementwise concatenation of strings personally. > On a side and somewhat historical note, if cvalarray morphs into anything > else, one of the issues here for the adoption is the adding dependancies. > Currently, the libraries is one file, self-contained, and does not rely > on anything outside of the language. That is very important in many > peoples view. As it is now, one can drop the file into their own project > and it is available everywhere there is a standard compliant compiler. > Boost, unfortunately is still not everywhere so unless adding dependancies > adds significant functionality, I'd like to avoid them. I also thought > about submitting cvalarray to the c++ standard at one time. For it to ever > be adopted there, it cannot have dependancies outside of the language. I understand your point, and being that the only thing (I could find) that could be reused from Boost is is_pod, the whole issue is indeed minor. I suppose I was prompted to raise it because the thing I personally love about Boost is the level of code reuse, which allows me to learn something once to know what it is. That way, when I look at source code I can understand what is happening more quickly (I didn't realize that your __is_fundamental is essentially is_pod until I saw how it was used). > > All of that said, I believe that your general-purpose need/desires are > legitimate. Therefore, I think that it is worth working for a > general-purpose solution. I have may ideas towards this end but one of the > biggest ones is the use of expressions. Currently, both std::valarray and > cvalarray use expressions solely as an implementation detail allowed to > under the standard: <snip requirements and example> > Notice that the above creates an unnecessary temporary that could easily > be solved with an expression type. But since the expression type is not > formally exposed, there is no way to write portable code to take advantage > of it. I think in a new, general-purpose container with a general-purpose > interface, we could have an exposed expression type that uses a boost > concept that ensures that as long as (for example) the contained type has > a valid [] operator, any additional functionality can take advantage of > it. ie <snip example> > Thoughts? If going general like that, perhaps bulding on top of Fusion2 containers and adding support for elementwise operations over the containers into Phoenix2 would be the way to go (maybe it's already there, I didn't find it upon a cursory look) That way it would support things like vector<float, float, float> or a vector <float, double, double> or even vector<float, string, double>. In hopes I didn't say many more silly things yet again, :-) Stjepan Boost list run by bdawes at acm.org, gregod at cs.rpi.edu, cpdaniel at pacbell.net, john at johnmaddock.co.uk
https://lists.boost.org/Archives/boost/2007/06/123056.php
CC-MAIN-2020-29
en
refinedweb
I'm trying to build a simple website with login functionality very similar to the one here on SO. The user should be able to browse the site as an anonymous user and there will be a login link on every page. When clicking on the login link the user will be taken to the login form. After a successful login the user should be taken back to the page from where he clicked the login link in the first place. I'm guessing that I have to somehow pass the url of the current page to the view that handles the login form but I can't really get it to work. EDIT: I figured it out. I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks! EDIT 2: My explanation did not seem to be clear so as requested here is my code: Lets say we are on a page foo.html and we are not logged in. Now we would like to have a link on foo.html that links to login.html. There we can login and are then redirected back to foo.html. The link on foo.html looks like this: <a href='/login/?next={{ request.path }}'>Login</a> Now I wrote a custom login view that looks somewhat like this: def login_view(request): redirect_to = request.REQUEST.get('next', '') if request.method=='POST': #create login form... if valid login credentials have been entered: return HttpResponseRedirect(redirect_to) #... return render_to_response('login.html', locals()) And the important line in login.html: <form method="post" action="./?next={{ redirect_to }}"> So yeah thats pretty much it, hope that makes it clear. You do not need to make an extra view for this, the functionality is already built in. First each page with a login link needs to know the current path, and the easiest way is to add the request context preprosessor to settings.py (the 4 first are default), then the request object will be available in each request: settings.py: TEMPLATE_CONTEXT_PROCESSORS = ( "django.core.context_processors.auth", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.media", "django.core.context_processors.request", ) Then add in the template you want the Login link: base.html: <a href="{% url django.contrib.auth.views.login %}?next={{request.path}}">Login</a> This will add a GET argument to the login page that points back to the current page. The login template can then be as simple as this: registration/login.html: {% block content %} <form method="post" action=""> {{form.as_p}} <input type="submit" value="Login"> </form> {% endblock %}
https://pythonpedia.com/en/knowledge-base/806835/django--redirect-to-previous-page-after-login
CC-MAIN-2020-29
en
refinedweb
navigator_invoke_invocation_set_uri() Set the URI of an invocation. Synopsis: #include <bps/navigator_invoke.h> BPS_API int navigator_invoke_invocation_set_uri(navigator_invoke_invocation_t *invocation, const char *uri) Since: BlackBerry 10.0.0 Arguments: - invocation A pointer to the navigator_invoke_invocation_t structure whose uri member you want to set. - uri The URI to the data being sent to the invocation handler. The value of this member should be a percent-encoded URI. For example, Library:libbps (For the qcc command, use the -l bps option to link against this library) Description: The navigator_invoke_invocation_set_uri() function sets the URI pointing to the data of a given navigator_invoke_invocation_t structure. The uri member identifies the location of the data the invoked handler is to perform an action on. If you don't call this function, the URI is assumed to be "data://local", indicating that the invocation data is provided through the data member (using the navigator_invoke_invocation_set_data() function). Returns: BPS_SUCCESS upon success, BPS_FAILURE with errno set otherwise. Last modified: 2014-09-30 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
https://developer.blackberry.com/native/reference/core/com.qnx.doc.bps.lib_ref/topic/navigator_invoke_invocation_set_uri.html
CC-MAIN-2020-29
en
refinedweb
Lab 11: Interpreters Due at 11:59pm on Friday, 08/02/2019. Starter Files Download lab, 2, and 3 must be completed in order to receive credit for this lab. - Questions 4 and 5 are optional. It is recommended that you complete these problems on your own time. Topics Consult this section if you need a refresher on the material for this lab. It's okay to skip directly to the questions and refer back here should you get stuck. Interpreters An interpreter is a program that allows you to interact with the computer in a certain language. It understands the expressions that you type in through that language, and performs the corresponding actions in some way, usually using an underlying language. In Project 4, you will use Python to implement an interpreter for Scheme. The Python interpreter that you've been using all semester is written (mostly) in the C programming language. The computer itself uses hardware to interpret machine code (a series of ones and zeros that represent basic operations like adding numbers, loading information from memory, etc). When we talk about an interpreter, there are two languages at work: - The language being interpreted/implemented. In this lab, you will implement the PyCombinator language. - The underlying implementation language. In this lab, you will use Python to implement the PyCombinator language. Note that the underlying language need not be different from the implemented language. In fact, in this lab we are going to implement a smaller version of Python (PyCombinator) using Python! This idea is called Metacircular Evaluation. Many interpreters use a Read-Eval-Print Loop (REPL). This loop waits for user input, and then processes it in three steps: Read: The interpreter takes the user input (a string) and passes it through a lexer and parser. - The lexer turns the user input string into atomic pieces (tokens) that are like "words" of the implemented language. - The parser takes the tokens and organizes them into data structures that the underlying language can understand. Eval: Mutual recursion between eval and apply evaluate the expression to obtain a value. - Eval takes an expression and evaluates it according to the rules of the language. Evaluating a call expression involves calling applyto apply an evaluated operator to its evaluated operands. - Apply takes an evaluated operator, i.e., a function, and applies it to the call expression's arguments. Apply may call evalto do more work in the body of the function, so evaland applyare mutually recursive. - Print: Display the result of evaluating the user input. Here's how all the pieces fit together: +-------------------------------- Loop -----------+ | | | +-------+ +--------+ +-------+ +-------+ | Input ---+->| Lexer |-->| Parser |-->| Eval |-->| Print |-+--> Output | +-------+ +--------+ +-------+ +-------+ | | ^ | | | | v | ^ +-------+ v | | Apply | | | REPL +-------+ | +-------------------------------------------------+ Required Questions PyCombinator Interpreter Today we will build PyCombinator, our own basic Python interpreter. By the end of this lab, you will be able to use a bunch of primitives such as add, mul, and sub, and even more excitingly, we will be able to create and call lambda functions -- all through your own homemade interpreter! You will implement some of the key parts that will allow us to evaluate the following commands and more: > add(3, 4) 7 > mul(4, 5) 20 > sub(2, 3) -1 > (lambda: 4)() 4 > (lambda x, y: add(y, x))(3, 5) 8 > (lambda x: lambda y: mul(x, y))(3)(4) 12 > (lambda f: f(0))(lambda x: pow(2, x)) 1 You can find the Read-Eval-Print Loop code for our interpreter in repl.py. Here is an overview of each of the REPL components: Read: The function readin reader.pycalls the following two functions to parse user input. - The lexer is the function tokenizein reader.pywhich splits the user input string into tokens. - The parser is the function read_exprin reader.pywhich parses the tokens and turns expressions into instances of subclasses of the class Exprin expr.py, e.g. CallExpr. Eval: Expressions (represented as Exprobjects) are evaluated to obtain values (represented as Valueobjects, also in expr.py). - Eval: Each type of expression has its own evalmethod which is called to evaluate it. - Apply: Call expressions are evaluated by calling the operator's applymethod on the arguments. For lambda procedures, applycalls evalto evaluate the body of the function. - Print: The __str__representation of the obtained value is printed. In this lab, you will only be implementing the Eval and Apply steps in expr.py. You can start the PyCombinator interpreter by running the following command: python3 repl.py Try entering a literal (e.g. 4) or a lambda expression, (e.g. lambda x, y: add(x, y)) to see what they evaluate to. You can also try entering some names. You can see the entire list of names that we can use in PyCombinator at the bottom of expr.py. Note that our set of primitives doesn't include the operators +, -, *, / -- these are replaced by add, sub, etc. Right now, any names (e.g. add) and call expressions (e.g. add(2, 3)) will output None. It's your job to implement Name.eval and CallExpr.eval so that we can look up names and call functions in our interpreter! You don't have to understand how the read component of our interpreter is implemented, but if you want a better idea of how user input is read and transformed into Python code, you can use the --read flag when running the interpreter: $ python3 repl.py --read > add Name('add') > 3 Literal(3) > lambda x: mul(x, x) LambdaExpr(['x'], CallExpr(Name('mul'), [Name('x'), Name('x')])) > add(2, 3) CallExpr(Name('add'), [Literal(2), Literal(3)]) To exit the interpreter, type Ctrl-C or Ctrl-D. Q1: Prologue Before we write any code, let's try to understand the parts of the interpreter that are already written. Here is the breakdown of our implementation: repl.pycontains the logic for the REPL loop, which repeatedly reads expressions as user input, evaluates them, and prints out their values (you don't have to completely understand all the code in this file). reader.pycontains our interpreter's reader. The function readcalls the functions tokenizeand read_exprto turn an expression string into an Exprobject (you don't have to completely understand all the code in this file). expr.pycontains our interpreter's representation of expressions and values. The subclasses of Exprand Valueencapsulate all the types of expressions and values in the PyCombinator language. The global environment, a dictionary containing the bindings for primitive functions, is also defined at the bottom of this file. Use Ok to test your understanding of the reader. It will be helpful to refer to reader.pyto answer these questions. python3 ok -q prologue_reader -u Use Ok to test your understanding of the Exprand Valueobjects. It will be helpful to refer to expr.pyto answer these questions. python3 ok -q prologue_expr -u Q2: Evaluating Names The first type of PyCombinator expression that we want to evaluate are names. In our program, a name is an instance of the Name class. Each instance has a string attribute which is the name of the variable -- e.g. "x". Recall that the value of a name depends on the current environment. In our implementation, an environment is represented by a dictionary that maps variable names (strings) to their values (instances of the Value class). The method Name.eval takes in the current environment as the parameter env and returns the value bound to the Name's string in this environment. Implement it as follows: - If the name exists in the current environment, look it up and return the value it is bound to. If the name does not exist in the current environment, raise a NameErrorwith an appropriate error message: raise NameError('your error message here (a string)') def eval(self, env): """ >>> env = { ... 'a': Number(1), ... 'b': LambdaFunction([], Literal(0), {}) ... } >>> Name('a').eval(env) Number(1) >>> Name('b').eval(env) LambdaFunction([], Literal(0), {}) >>> try: ... print(Name('c').eval(env)) ... except NameError: ... print('Exception raised!') Exception raised! """"*** YOUR CODE HERE ***"if self.string not in env: raise NameError("name '{}' is not defined".format(self.string)) return env[self.string] Use Ok to test your code: python3 ok -q Name.eval Now that you have implemented the evaluation of names, you can look up names in the global environment like add and sub (see the full list of primitive math operators in global_env at the bottom of expr.py). You can also try looking up undefined names to see how the NameError is displayed! $ python3 repl.py > add <primitive function add> Unfortunately, you still cannot call these functions. We'll fix that next! Q3: Evaluating Call Expressions Now, let's add logic for evaluating call expressions, such as add(2, 3). Remember that a call expression consists of an operator and 0 or more operands. In our implementation, a call expression is represented as a CallExpr instance. Each instance of the CallExpr class has the attributes operator and operands. operator is an instance of Expr, and, since a call expression can have multiple operands, operands is a list of Expr instances. For example, in the CallExpr instance representing add(3, 4): self.operatorwould be Name('add') self.operandswould be the list [Literal(3), Literal(4)] In CallExpr.eval, implement the three steps to evaluate a call expression: - Evaluate the operator in the current environment. - Evaluate the operand(s) in the current environment. - Apply the value of the operator, a function, to the value(s) of the operand(s). Hint: Since the operator and operands are all instances of Expr, you can evaluate them by calling their evalmethods. Also, you can apply a function (an instance of PrimitiveFunctionor LambdaFunction) by calling its applymethod, which takes in a list of arguments ( Valueinstances). def eval(self, env): """ >>> from reader import read >>> new_env = global_env.copy() >>> new_env.update({'a': Number(1), 'b': Number(2)}) >>> add = CallExpr(Name('add'), [Literal(3), Name('a')]) >>> add.eval(new_env) Number(4) >>> new_env['a'] = Number(5) >>> add.eval(new_env) Number(8) >>> read('max(b, a, 4, -1)').eval(new_env) Number(5) >>> read('add(mul(3, 4), b)').eval(new_env) Number(14) """"*** YOUR CODE HERE ***"function = self.operator.eval(env) arguments = [operand.eval(env) for operand in self.operands] return function.apply(arguments) Use Ok to test your code: python3 ok -q CallExpr.eval Now that you have implemented the evaluation of call expressions, we can use our interpreter for simple expressions like sub(3, 4) and add(mul(4, 5), 4). Open your interpreter to do some cool math: $ python3 repl.py Optional Questions Q4: Applying Lambda Functions We can do some basic math now, but it would be a bit more fun if we could also call our own user-defined functions. So let's make sure that we can do that! A lambda function is represented as an instance of the LambdaFunction class. If you look in LambdaFunction.__init__, you will see that each lambda function has three instance attributes: parameters, body and parent. As an example, consider the lambda function lambda f, x: f(x). For the corresponding LambdaFunction instance, we would have the following attributes: parameters-- a list of strings, e.g. ['f', 'x'] body-- an Expr, e.g. CallExpr(Name('f'), [Name('x')]) parent-- the parent environment in which we want to look up our variables. Notice that this is the environment the lambda function was defined in. LambdaFunctions are created in the LambdaExpr.evalmethod, and the current environment then becomes this LambdaFunction's parent environment. If you try entering a lambda expression into your interpreter now, you should see that it outputs a lambda function. However, if you try to call a lambda function, e.g. (lambda x: x)(3) it will output None. You are now going to implement the LambdaFunction.apply method so that we can call our lambda functions! This function takes a list arguments which contains the argument Values that are passed to the function. When evaluating the lambda function, you will want to make sure that the lambda function's formal parameters are correctly bound to the arguments it is passed. To do this, you will have to modify the environment you evaluate the function body in. There are three steps to applying a LambdaFunction: - Make a copy of the parent environment. You can make a copy of a dictionary dwith d.copy(). - Update the copy with the parametersof the LambdaFunctionand the argumentspassed into the method. - Evaluate the bodyusing the newly created environment. Hint: You may find the built-in zipfunction useful to pair up the parameter names with the argument values. def apply(self, arguments): """ >>> from reader import read >>> add_lambda = read('lambda x, y: add(x, y)').eval(global_env) >>> add_lambda.apply([Number(1), Number(2)]) Number(3) >>> add_lambda.apply([Number(3), Number(4)]) Number(7) >>> sub_lambda = read('lambda add: sub(10, add)').eval(global_env) >>> sub_lambda.apply([Number(8)]) Number(2) >>> add_lambda.apply([Number(8), Number(10)]) # Make sure you made a copy of env Number(18) >>> read('(lambda x: lambda y: add(x, y))(3)(4)').eval(global_env) Number(7) >>> read('(lambda x: x(x))(lambda y: 4)').eval(global_env) Number(4) """ if len(self.parameters) != len(arguments): raise TypeError("Cannot match parameters {} to arguments {}".format( comma_separated(self.parameters), comma_separated(arguments)))"*** YOUR CODE HERE ***"env = self.parent.copy() for parameter, argument in zip(self.parameters, arguments): env[parameter] = argument return self.body.eval(env) Use Ok to test your code: python3 ok -q LambdaFunction.apply After you finish, you should try out your new feature! Open your interpreter and try creating and calling your own lambda functions. Since functions are values in our interpreter, you can have some fun with higher order functions, too! $ python3 repl.py > (lambda x: add(x, 3))(1) 4 > (lambda f, x: f(f(x)))(lambda y: mul(y, 2), 3) 12 Q5: Handling Exceptions The interpreter we have so far is pretty cool. It seems to be working, right? Actually, there is one case we haven't covered. Can you think of a very simple calculation that is undefined (maybe involving division)? Try to see what happens if you try to compute it using your interpreter (using floordiv or truediv since we don't have a standard div operator in PyCombinator). It's pretty ugly, right? We get a long error message and exit our interpreter -- but really, we want to handle this elegantly. Try opening up the interpreter again and see what happens if you do something ill defined like add(3, x). We just get a nice error message saying that x is not defined, and we can then continue using our interpreter. This is because our code handles the NameError exception, preventing it from crashing our program. Let's talk about how to handle exceptions: In lecture, you learned how to raise exceptions. But it's also important to catch exceptions when necessary. Instead of letting the exception propagate back to the user and crash the program, we can catch it using a try/except block and allow the program to continue. try: <try suite> except <ExceptionType 0> as e: <except suite 0> except <ExceptionType 1> as e: <except suite 1> ... We put the code that might raise an exception in the <try suite>. If an exception is raised, then the program will look at what type of exception was raised and look for a corresponding <except suite>. You can have as many except suites as you want. try: 1 + 'hello' except NameError as e: print('hi') # NameError except suite except TypeError as e: print('bye') # TypeError except suite In the example above, adding 1 and 'hello' will raise a TypeError. Python will look for an except suite that handles TypeErrors -- the second except suite. Generally, we want to specify exactly which exceptions we want to handle, such as OverflowError or ZeroDivisionError (or both!), rather than handling all exceptions. Notice that we can define the exception as e. This assigns the exception object to the variable e. This can be helpful when we want to use information about the exception that was raised. >>> try: ... x = int("cs61a rocks!") ... except ValueError as e: ... print('Oops! That was no valid number.') ... print('Error message:', e) You can see how we handle exceptions in your interpreter in repl.py. Modify this code to handle ill-defined arithmetic errors, as well as type errors. Go ahead and try it out!
https://inst.eecs.berkeley.edu/~cs61a/su19/lab/lab11/
CC-MAIN-2020-29
en
refinedweb
Data Persistence with Hibernate and Spring. Java developers typically encounter the need to store data on a regular basis. If you’ve been developing for more than 15 years, you probably remember the days of JDBC in Java. Using JDBC can be tedious if you don’t like writing SQL. Not only that, but there’s nothing in JDBC that helps you create your database. Hibernate came along and changed everything by allowing you to map POJOs (plain ol’ Java objects) to database tables. Not only that, but it had a very Java-esque API that made it easy to create CRUD POJOs. Shortly after, Spring came along and added abstractions for Hibernate that took API simplification even further. Fast forward to today, and most Java applications use both Spring and Hibernate. For some time now, developers have operated under one of two separate but distinct models to represent business entities. The relational model, which is prevalent in databases, and the object-oriented model. These two models are similar in that both work using similar structures to represent business logic, and they are distinct in that they were designed for different purposes: one to store data, other to describe behavior.. Below is an example of an ol’ school XML-based mapping and more current annotation based mapping for the same entity. Xml-Based mapping <hibernate-mapping> <class name="net.dovale.okta.springhibernate.spring.entities.Teacher" table="teacher"> <id name="id" type="java.lang.Long"> <column name="id" /> <generator class="identity" /> </id> <property name="name" type="string"> <column name="name" length="255" not- </property> <property name="pictureURL" type="string"> <column name="pictureURL" length="255" not- </property> <property name="email" type="string"> <column name="email" length="255" not- </property> </class> </hibernate-mapping> Annotation-based mapping @Entity @Table(uniqueConstraints = @UniqueConstraint( name = "un_teacher_email", columnNames = {"email" })) public class Teacher { @Id @GeneratedValue(strategy = GenerationType.IDENTITY) private Long id; @NotNull private String name; @NotNull private String pictureURL; @NotNull private String email; // (...) getter and setters (...) } In this post, you are going to work in two different technology stacks. You’ll create a very simple project using Hibernate (JPA annotations), then move to a Spring Boot project doing the same thing. After that, you’ll be introduced to Project Lombok which will reduce your project’s lines-of-code counter even further. Then, you are going to expose the CRUD operations as REST endpoints secured with Okta, and OAuth 2.0. In this project, you are going to use core Hibernate functionality with JPA annotations. You are not addressing XML configuration as it is not commonly used nowadays. The project is already implemented here on the raw branch. The database model is represented in the following model: +--------+* 1 +-------+ | Course +---------> |Teacher| +--------+ +-------+ For simplicity’s sake, the database chose is an H2 Database, an in memory, small, 100% Java database, excellent for testing and development purposes. The project has two significant dependencies: <dependency> <groupId>org.hibernate</groupId> <artifactId>hibernate-core</artifactId> <version>5.3.6.Final</version> </dependency> <dependency> <groupId>com.h2database</groupId> <artifactId>h2</artifactId> <version>1.4.197</version> </dependency> Each database table is mapped to an entity. Course table is represented by net.dovale.entities.Course entity and Teacher is represented by net.dovale.entities.Teacher. Let’s take a look into the Teacher entity: package net.dovale.entities; import javax.persistence.*; @Entity public class Teacher { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private String pictureURL; private String email; public Teacher() { } public Teacher(String name, String pictureURL, String email) { this.name = name; this.pictureURL = pictureURL; this.email = email; } // (...) getter and setters (...) } You just need to add @Entity annotation for Hibernate to understand the database must have a table with the same class name. Also, the entity has an @Id which means the attribute with it is an entity identifier. In this case, we defined how our ID’s will be automatically generated (the decision is up to Hibernate dialect). Now, you are going to review a more complex relationship type on Course entity: package net.dovale.entities; import javax.persistence.*; @Entity public class Course { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; private String name; private int workload; private int rate; @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "fk_course_teacher")) private Teacher teacher; public Course() { } public Course(String name, int workload, int rate, Teacher teacher) { this.name = name; this.workload = workload; this.rate = rate; this.teacher = teacher; } // (...) getter and setters (...) } As you can see, there is a @ManyToOneand a @JoinColumn annotation. Those annotations represent, as the name says, a many-to-one relationship (when a single entity has many relationships with other entity). The annotation @JoinColumn specifies the relationship must be made by a column in the One entity (Course, in this case) and @ForeignKey specifies the constraint name. I always recommend specifying the foreign key name to help to debugging. We have two DAO’s (Data Access Objects) on this project: CourseDao and TeacherDao. They both extend AbstractCrudDao a simple abstract class that has some common CRUD operations: package net.dovale.dao; import org.hibernate.Session; import org.hibernate.SessionFactory; import javax.persistence.criteria.CriteriaQuery; import java.util.List; public abstract class AbstractCrudDao<T> { private final SessionFactory sessionFactory; private final Class<T> entityClass; private final String entityName; protected AbstractCrudDao(SessionFactory sessionFactory, Class<T> entityClass, String entityName) { this.sessionFactory = sessionFactory; this.entityClass = entityClass; this.entityName = entityName; } public T save(T entity) { sessionFactory.getCurrentSession().save(entity); return entity; } public void delete(T entity) { sessionFactory.getCurrentSession().delete(entity); } public T find(long id) { return sessionFactory.getCurrentSession().find(entityClass, id); } public List<T> list() { Session session = sessionFactory.getCurrentSession(); CriteriaQuery<T> query = session.getCriteriaBuilder().createQuery(entityClass); query.select(query.from(entityClass)); return session.createQuery(query).getResultList(); } } The abstract puts all CRUD logic into the same class. In the next sample, a new and better solution will be presented with Spring. Hibernate uses a Session abstraction to communicate with the database and convert objects to relations and vice-versa. The framework also introduces its own query language called HQL(Hibernate Query Language). In the code above, HQL is represented on the list method. The cool thing about HQL is you are querying objects and not tables and relationships. The Hibernate query engine will convert to SQL internally. ACID (Atomic Consistent Isolated Durable) is a relational database key feature. It guarantees consistency between the data inserted through transactions. In other words: if you are running a transaction, all your operations are atomic and not influenced by other operations that may be running in the same database, at the same time. To fully accomplish this, Hibernate also has a Transaction abstraction. The code on net.dovale.Application shows how it works: package net.dovale; import net.dovale.dao.*; import net.dovale.entities.*; import org.hibernate.*; import org.hibernate.boot.MetadataSources; import org.hibernate.boot.registry.StandardServiceRegistry; import org.hibernate.boot.registry.StandardServiceRegistryBuilder; public class Application { public static void main(String[] args) { StandardServiceRegistry registry = new StandardServiceRegistryBuilder().configure().build(); try (SessionFactory sessionFactory = new MetadataSources(registry).buildMetadata().buildSessionFactory()) { CourseDao courseDao = new CourseDao(sessionFactory); TeacherDao teacherDao = new TeacherDao(sessionFactory); try (Session session = sessionFactory.getCurrentSession()) { Transaction tx = session.beginTransaction(); // create teachers Teacher pj = teacherDao.save(new Teacher("Profesor Jirafales","","[email protected]")); Teacher px = teacherDao.save(new Teacher("Professor X","","[email protected]_.com")); courseDao.save(new Course("Mathematics", 20, 10, pj)); courseDao.save(new Course("Spanish", 20, 10, pj)); courseDao.save(new Course("Dealing with unknown", 10, 100, px)); courseDao.save(new Course("Handling your mental power", 50, 100, px)); courseDao.save(new Course("Introduction to psychology", 90, 100, px)); tx.commit(); } try (Session session = sessionFactory.getCurrentSession()) { session.beginTransaction(); System.out.println("Courses"); courseDao.list().forEach(course -> System.out.println(course.getName())); System.out.println("Teachers"); teacherDao.list().forEach(teacher -> System.out.println(teacher.getName())); } } } } This class creates some data for our example database, and all the data is inserted using the same transaction: if an error occurs, all data are erased before any user can query them. To correctly implement this on raw hibernate, we call session.beginTransaction() and session.commitTransaction(). It is also important to call sessionFactory.getCurrentSession() and not sessionFactory.openSession() to use the same session all over the operation. Last but not least, we have the configuration file (src/main/resources/hibernate.cfg.xml): <hibernate-configuration> <session-factory> <property name="connection.driver_class">org.h2.Driver</property> <property name="connection.url">jdbc:h2:./data/db</property> <property name="connection.username">sa</property> <property name="connection.password"/> <property name="dialect">org.hibernate.dialect.H2Dialect</property> <property name="hbm2ddl.auto">create</property> <property name="hibernate.connection.pool_size">1</property> <property name="hibernate.current_session_context_class">thread</property> <property name="hibernate.show_sql">true</property> <mapping class="net.dovale.entities.Course"/> <mapping class="net.dovale.entities.Teacher"/> </session-factory> </hibernate-configuration> Note that we need to declare all entities with mapping node. For debugging purposes, it is important to set hibernate.show_sql = true as it is possible to identify possible mapping problems just by reading the generated SQL. Now, just run the command below to run your project: ./mvnw compile exec:java -Dexec.mainClass="net.dovale.Application" Phew! That’s a lot of code. Now we are going to remove a lot of then by introducing Spring Data. As you probably know, Spring Boot has a lot of magic under the hood. I have to say, using it together with Spring Data is awesome. You need to create a new project using Spring Initializr with JPA and H2 dependencies. After the project is created, copy all entities package to the new project, without any changes. Then, add the @EnableTransactionManagement annotation to net.dovale.okta.springhibernate.spring.Application class as follows: @SpringBootApplication @EnableTransactionManagement public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } } Then, remove the original DAO’s. With Spring, CourseDao and TeacherDao will be changed to interfaces and extend the CrudRepository interface. Spring automatically identifies you are creating a Repository (or DAO) class when you extend a Repository interface. CrudRepository automatically delivers CRUD methods like save, delete, update, and list for your entity without any effort and with transaction support. package net.dovale.okta.springhibernate.spring.dao; import net.dovale.okta.springhibernate.spring.entities.Course; import org.springframework.data.repository.CrudRepository; public interface CourseDao extends CrudRepository<Course, Long> {} If you want to skip to a a pre built example you can grab the code from GitHub. Please, clone it and go to from_raw_project branch: git clone cd okta-spring-boot-hibernate-spring-project git checkout from_raw_project Now, to change how we fill in the database. Create a service class DataFillerService that is responsible for filling our H2 database with data: package net.dovale.okta.springhibernate.spring.services; import net.dovale.okta.springhibernate.spring.dao.*; import net.dovale.okta.springhibernate.spring.entities.*; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; import org.springframework.transaction.annotation.Transactional; import javax.annotation.PostConstruct; @Service public class DataFillerService { private final CourseDao courseDao; private final TeacherDao teacherDao; @Autowired public DataFillerService(CourseDao courseDao, TeacherDao teacherDao) { this.courseDao = courseDao; this.teacherDao = teacherDao; } @PostConstruct @Transactional public void fillData() { Teacher pj = new Teacher("Profesor Jirafales", "", "[email protected]"); Teacher px = new Teacher("Professor X", "", "[email protected]_.com"); teacherDao.save(pj); teacherDao.save(px); courseDao.save(new Course("Mathematics", 20, (short) 10, pj)); courseDao.save(new Course("Spanish", 20, (short) 10, pj)); courseDao.save(new Course("Dealing with unknown", 10, (short) 100, pj)); courseDao.save(new Course("Handling your mental power", 50, (short) 100, pj)); courseDao.save(new Course("Introduction to psychology", 90, (short) 100, pj)); } } Do you see how clean your code is when compared to the raw project? This happens because you have only one concern: maintain your business code sanely. While on your raw project you had to handle Sessions and Ttransactions, here we just need to add @Transactional annotation to keep the entire method execution inside a database transaction. Besides, the @PostConstruct tells Spring this method must be invoked after the context is fully loaded. Add the following lines in src\main\resources\application.properties file to show up all SQL executed and to create the database if it does not exists. spring.jpa.show-sql=true spring.jpa.generate-ddl=true Also, keep in mind Spring Boot automatically discovered H2 dependencies and configured it as the database you are using without any manual configuration. To execute this code (which simply adds the entities to an ephemeral database), just run on a console: ./mvnw spring-boot:run Have you read about Project Lombok? It works in compile level to reduce Java famous verbosity and add features that are not available in your current JDK version (e.g. val and var). In our case, we will remove all boilerplate in entities classes. Check branch lombok to see the final result. Now we just need to add the dependency: <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> </dependency> And change our entities to: Course package net.dovale.okta.springhibernate.spring.entities; import lombok.*; import javax.persistence.*; @Entity @Data @NoArgsConstructor @RequiredArgsConstructor public class Course { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NonNull private String name; @NonNull private int workload; @NonNull private int rate; @ManyToOne @JoinColumn(foreignKey = @ForeignKey(name = "fk_course_teacher")) @NonNull private Teacher teacher; } and Teacher package net.dovale.okta.springhibernate.spring.entities; import lombok.*; import javax.persistence.*; @Entity @Data @NoArgsConstructor @RequiredArgsConstructor public class Teacher { @Id @GeneratedValue(strategy = GenerationType.AUTO) private Long id; @NonNull private String name; @NonNull private String pictureURL; @NonNull private String email; } Every getter and setter will be automatically generated by Lombok thanks to @Data annotation. @NoArgsConstructor and @RequiredArgsConstructor tells the tool the entity needs two constructors: one empty and another with all arguments that has @NonNull annotation (or are final). There is another annotation @AllArgsConstructor that creates an constructor with all arguments, but we cannot use it as id attribute can be null (only persisted entities should have a non-null value). Note: Lombok has a lot of compile-level stuff and works out-of-the-box with Maven and Spring. Some IDE’s needs a specific plugin to work without compilation problems. Check out Project Lombok’s IDE setup guide. As in the previous step, you just need to run the command ./mvnw spring-boot:run to see everything working if you do not believe in me. Now we will explore a microservice area. You are going to change the project to externalize the data into a REST API. Also, we will explore a little bit more about Spring Repositories. About the magic thing, do you believe you just need to add a single dependency to publish your DAO’s as a REST API? Test it! Add the following dependency: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-data-rest</artifactId> </dependency> Run ./mvnw spring-boot run and HTTPie the following address: http HTTP/1.1 200 Content-Type: application/hal+json;charset=UTF-8 Date: Fri, 01 Feb 2019 16:32:43 GMT Transfer-Encoding: chunked { "_embedded": { "teachers": [ { "_links": { "self": { "href": "" }, "teacher": { "href": "" } }, "email": "[email protected]", "name": "Profesor Jirafales", "pictureURL": "" }, { "_links": { "self": { "href": "" }, "teacher": { "href": "" } }, "email": "[email protected]_.com", "name": "Professor X", "pictureURL": "" } ] }, "_links": { "profile": { "href": "" }, "self": { "href": "" } } } Test with the other entities like students, teachers and courses and you’ll see all data we manually insert into the database. It is also possible to PUT, POST or DELETE to create, update or delete a registry, respectively. There is another cool thing about Spring Data Repositories: you can customize them by creating methods into a predefined format. Example for StudentDao: public interface StudentDao extends JpaRepository<Student, Long> { List<Student> findByNameContaining(String name); List<Student> findByAgeBetween(short smallerAge, short biggerAge); } All updates are available on the rest_repository branch of our Git Repository. Security is an important part of any application, and adding OAuth 2.0/OIDC support to any Spring Boot web application only takes few minutes! Our project is a OAuth 2.0 resource server and, as such, does not handle login steps directly. It only validates that the request has valid authorization and roles. First, you need to add the following Maven dependencies: <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-security</artifactId> </dependency> <dependency> <groupId>com.okta.spring</groupId> <artifactId>okta-spring-boot-starter</artifactId> <version>1.0.0</version> </dependency> And update your Application class: package net.dovale.okta.springhibernate.spring; import org.springframework.boot.SpringApplication; import org.springframework.boot.autoconfigure.SpringBootApplication; import org.springframework.context.annotation.Configuration; import org.springframework.security.config.annotation.method.configuration.EnableGlobalMethodSecurity; import org.springframework.security.config.annotation.web.builders.HttpSecurity; import org.springframework.security.config.annotation.web.configuration.WebSecurityConfigurerAdapter; import org.springframework.transaction.annotation.EnableTransactionManagement; @SpringBootApplication @EnableTransactionManagement @EnableResourceServer @EnableGlobalMethodSecurity(prePostEnabled = true) public class Application { public static void main(String[] args) { SpringApplication.run(Application.class, args); } @Configuration static class OktaOauth2WebSecurityConfigurerAdapter extends WebSecurityConfigurerAdapter { @Override protected void configure(HttpSecurity http) throws Exception { http .authorizeRequests().anyRequest().authenticated() .and() .oauth2ResourceServer().jwt(); } } } Now, you need to configure your application.properties file: okta.oauth2.issuer={yourOktaDomain}/oauth2/default okta.oauth2.clientId=${clientId} This will enable your REST endpoints to only accept authorized users. To obtain the client ID, you must register for a free Okta account. In the Okta dashboard, create an application of type Service. This indicates a resource server that does not have a login page or any way to obtain new tokens. Click Next, type the name of your service, then click Done. You will be presented with a screen similar to the one below. Paste your Client ID and enter it on into the application.properties file (just change ${clientId} variable). Now, start the application again. It’ll be locked and you will be unable to make any requests as all of them are now protected. You just need to acquire a token to connect. An easy way to achieve a token is to generate one using OpenID Connect . Create a new Web application in Okta: Set the Login redirect URIs field to and Grant Type Allowed to Hybrid. Click Done and copy the client ID for the next step. On the OIDC Debugger} http "Authorization: Bearer $TOKEN" For this last step, you can check out the master branch and see all the changes I made. ☞ Complete Java Masterclass ☞ Complete Step By Step Java For Testers ☞ Java Web Service Complete Guide - SOAP + REST + Buide App ☞ Selenium WebDriver with Java - Basics to Advanced& Interview ☞ Java Persistence: Hibernate and JPA Fundamentals ☞ Java Swing (GUI) Programming: From Beginner to Expert ☞ Java Basics: Learn to Code the Right Way Step by Step to your First Spring App Spring | Spring JDBC Tutorial | Java Spring Tutorial Spring Training . Spring Framework Certification Training This post Spring JDBC Tutorial video will help you In this Spring Boot project tutorial to help you understand how to use Spring, Hibernate, and EhCache caching features. we are going to demonstrate the Spring cache + EhCache feature on an example Spring Boot project. Caching will be defined as data queried from a relational database (example configurations prepared for H2 and PostgreSQL database engines). Spring Persistence (Hibernate and JPA) with a JNDI datasource, we'll create a Spring application using Hibernate/JPA with a JNDI data source.).
https://morioh.com/p/22e164784480
CC-MAIN-2020-29
en
refinedweb
ScheduleRecycle Property Published: June 20, 2005 ScheduleRecycle Property Gets and sets a scheduled time to recycle the Telephony Application Services (TAS) worker process. obj.ScheduleRecycle = string Qualifiers Remarks This property is exposed in the Microsoft Speech Server (MSS) snap-in for Microsoft Management Console (MMC). This recycle happens only once during a 24 hour period, unless this property is changed. Windows Management Instrumentation (WMI) Script Example myComputer = "localhost" ' Use a Locator object to connect to WMI. Set locator = CreateObject("WbemScripting.SWbemLocator") Set namespace = locator.ConnectServer(myComputer, "root/MSS") ' Create a new instance of the TAS class. Set tel = namespace.Get("TAS=@") ' Display the current value. WScript.Echo tel.ScheduleRecycle ' Set the property value. tel.ScheduleRecycle = "00:00" ' Update the class instance in WMI. tel.Put_ Member Of Show:
https://technet.microsoft.com/en-us/library/bb684863.aspx
CC-MAIN-2017-51
en
refinedweb
Three Useful Monads Note: before reading this, you should know what a monad is. Read this post if you don't! Here's a function half: And we can apply it a couple of times: half . half $ 8 => 2 Everything works as expected. Now you decide that you want to log what happens in this function: half x = (x `div` 2, "I just halved " ++ (show x) ++ "!") Okay, fine. Now what if you want to apply half a couple of times? half . half $ 8 Here's what we want to have happen: Spoilers: it doesn't happen automatically. You have to do it yourself: finalValue = (val2, log1 ++ log2) where (val1, log1) = half 8 (val2, log2) = half val1 Yuck! That's nowhere as nice as: half . half $ 8 And what if you have more functions that log things? There's a pattern here: for each function that returns a log along with a value, we want to combine those logs. This is a side-effect, and monads are great at side effects! The Writer monad The Writer monad is cool. "Hey dude, I'll handle the logging," says Writer. "Go back to your clean code and crank up some Zeppelin!" Every writer has a log and a return value: data Writer w a = Writer { runWriter :: (a, w) } Writer lets us write code like this: half 8 >>= half Or you can use the <=< function, which does function composition with monads, to get: half <=< half $ 8 which is pretty darn close to half . half $ 8. Cool! You use tell to write something to the log. And return puts a value in a Writer. Here's our new half function: half :: Int -> Writer String Int half x = do tell ("I just halved " ++ (show x) ++ "!") return (x `div` 2) It returns a Writer: And we can use runWriter to extract the values from the Writer: runWriter $ half 8 => (4, "I just halved 8!") But the cool part is, now we can chain calls to half with >>=: runWriter $ half 8 >>= half => (2, "I just halved 8!I just halved 4!") Here's what's happening: >>= magically knows how to combine two writers, so we don't have to write any of that tedious code ourselves! Here's the full definition of >>=: Which is the same boilerplate code we had written before. Except now, >>= takes care of it for us. Cool! We also used return, which takes a value and puts it in a monad: return val = Writer (val, "") (Note: these definitions are almost right. The real Writer monad allows us to use any Monoid as the log, not just strings. I have simplified it here a bit). Thanks, Writer monad! The Reader Monad Suppose you want to pass some config around to a lot of functions. Use the Reader monad: The reader monad lets you pass a value to all your functions behind the scenes. For example: greeter :: Reader String String greeter = do name <- ask return ("hello, " ++ name ++ "!") greeter returns a Reader monad: Here's how Reader is defined: data Reader r a = Reader { runReader :: r -> a } Reader was always the renegade. The wild card. Reader is different because it's only field is a function, and this is confusing to look at. But we both understand that you can use runReader to get that function: And then you give this function some state, and it's used in greeter: runReader greeter $ "adit" => "hello, adit!" So when you use >>=, you should get a Reader back. When you pass in a state to that reader, it should be passed through to every function in that monad. m >>= k = Reader $ \r -> runReader (k (runReader m r)) r Reader always was a little complex. The complex ones are the best. return puts a value in a Reader: return a = Reader $ \_ -> a And finally, ask gives you back the state that was passed in: ask = Reader $ \x -> x Want to spend some more time with Reader? Turn up the punk rock and see this longer example. The State Monad The State monad is the Reader monad's more impressionable best friend: She's exactly like the Reader monad, except you can write as well as read! Here's how State is defined: State s a = State { runState :: s -> (a, s) } You can get the state with get, and change it with put. Here's an example: greeter :: State String String greeter = do name <- get put "tintin" return ("hello, " ++ name ++ "!") runState greeter $ "adit" => ("hello, adit!", "tintin") Nice! Reader was all like "you won't change me", but State is committed to this relationship and willing to change. The definitions for the State monad look pretty similar to the definitions for the Reader monad: return: return a = State $ \s -> (a, s) >>=: m >>= k = State $ \s -> let (a, s') = runState m s in runState (k a) s' Conclusion Writer. Reader. State. You added three powerful weapons to your Haskell arsenal today. Use them wisely. Translations This post has been translated into: Human languages: If you translate this post, send me an email and I'll add it to this list!
http://adit.io/posts/2013-06-10-three-useful-monads.html
CC-MAIN-2017-51
en
refinedweb
Downloading Coherence 3.7LSV Sep 24, 2013 10:32 AM I want to download and start using latest Coherence jar. I tried it in below link. but, i am unable to download. when i click on "Accept License Agreement" it's not recognizing. Can someone pls help ? Oracle Coherence Software Archive</title><meta name="Title" content="Oracle Coherence Software A… 1. Re: Downloading Coherence 3.7Ricardo Ferreira-Oracle Sep 30, 2013 6:26 PM (in response to LSV) Maybe the final link could be broken due some website restrictions. Access support.oracle.com and download the specific version you want of Coherence. Cheers, Ricardo Ferreira 2. Re: Downloading Coherence 3.7LSV Oct 3, 2013 12:04 PM (in response to Ricardo Ferreira-Oracle) Thanks for the reply. But i dont see a way there to download. anyways, i got the jar. thanks again. We were running our Coherence grid using 3.6. it was working fine. We just updated the server to use 3.7.1 and our server is not starting with below error. Any suggestions ? 2013-10-03 07:39:38,460 [Logger@1247017815 3.7.1.0] INFO Coherence - 2013-10-03 07:39:38.459/0.734 Oracle Coherence GE 3.7.1.0 <Info> (thread=main, member=n/a): Loaded cache configuration from "file:/test/stand/coherence/target/classes/test/coherence/grid/config/coherence-server-one.xml"; this document does not refer to any schema definition and has not been validated. 2013-10-03 07:39:38,619 [Logger@1247017815 3.7.1.0] INFO Coherence - 2013-10-03 07:39:38.618/0.893 Oracle Coherence GE 3.7.1.0 <Info> (thread=main, member=n/a): Loaded cache configuration from "jar:file:/test/stand/coherence/lib/coherence.jar!/coherence-cache-config.xml" 2013-10-03 07:39:38,664 [Logger@1247017815 3.7.1.0] INFO Coherence - 2013-10-03 07:39:38.664/0.939 Oracle Coherence GE 3.7.1.0 <Info> (thread=main, member=n/a): WARNING: Failed to load Coherence cache-config.dtd. Provided configuration XML element names will not be validated. Class:com.oracle.coherence.environment.extensible.namespaces.CoherenceNamespaceContentHandler 3. Re: Downloading Coherence 3.7Jonathan.Knight Oct 3, 2013 12:47 PM (in response to LSV) Hi I'm not sure that the message you have posted is the cause of your cluster failing to start. All the message says it that the XML configuration will not be validated against a schema or DTD. I would expect there are more error messages or stack traces in your logs. I see that you are using the Coherence Incubator too - have you made sure that the version of the Incubator you are using is compatible with 3.7.1 JK 4. Re: Downloading Coherence 3.7Leo_TA Oct 22, 2013 10:09 AM (in response to LSV) Hi , The best place to download Oracle software is "Oracle edelivery" 1 edelivery.oracle.com/ 2 log with oracle account 3 choose Select a Product Pack: Oracle Fussion Middleware , click GO 4 choose Oracle WebLogic Server 12c Media Pack 5 choose "Oracle Coherence Version 3.7.1" 6 click "download" button Leo_TA 5. Re: Downloading Coherence 3.7LSV Oct 22, 2013 2:19 PM (in response to Leo_TA) Thanks for the reply
https://community.oracle.com/message/11215495
CC-MAIN-2017-51
en
refinedweb
Fw: Commemorate Dudley George, Sept. 6 - 9 - 11pm... and more news! Expand Messages ----- Original Message ----- From: "Turtle Island Solidarity" Date: Fri, 29 Aug 2003 12:04:222 -0400 Subject: Commemorate Dudley George, Sept. 6 - 9 - 11pm... and more news! Honor Dudley George -- Remember Ipperwash -- Support Aboriginal Land and Treaty Rights SEPTEMBER 6th VIGIL with Eagleheart Singers and Wanda Whitebird 9 - 11 pm (the time of the armed police assault, in which Dudley's life was taken) Queen's Park, Toronto in front of the legislature, north of University Avenue & College Street This is a very important year for those of us who have worked hard to make sure that the sacrifice of Dudley George's life was not in vain... That the truth is beginning to come out, after eight long years of struggle... Join the Coalition for a Public Inquiry into Ipperwash at this Vigil in remembrance of Dudley George, where you can get reports on: -- Minister Runciman's office illegally blocked release of photo and video materials too the courts and the media -- the court case against Harris et al for the "Wrongful Death" of Dudley George begins September 22ndd (note date change) --- finally!!! -- Toronto Teachers' Federation is founding a scholarship in Dudley's name -- Amnesty International's current largescale lobbying effort for justice on Ipperwash> -- the Chief Coroner's response to request for a long-overdue inquest. Events to remember and commemorate the events of September 6, 1995 on the Aazhoodena territory (also known as Ipperwash Park) have already been held and more are being organized in other centres across the region of Ontario. If you cannot get to Toronto for this vigil and would like contacts in your region to learn if something is being planned locally, please hit "reply" to make your inquiry. //////////|||||||||\\\\\\\\\\\\\/////////////||||||||\\\\\\\\\\\ \\\\\\\\\\|||||||||/////////////\\\\\\\\\\\\\||||||||/////////// OTHER NEWS & ANNOUNCEMENTS... 1) Rebel Youth Network Presents: Cafe Che - Defend Aboriginal Rights! Fundraiser for Toronto Native Youth 2) The Gathering of the Good Minds: A Celebration of Native Arts, Wisdom and Culture 3) CanWest report that PM loses interest in unpopular native bill [FNGA] - but don't count your chickens yet! ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| Rebel Youth Network Presents: Cafe Che - Defend Aboriginal Rights! A Fundraiser for Toronto Native Youth . Speakers from Toronto Native Youth . Speakers from Stop The FNGA Coalition . Speakers from The Spot (KWYC) . Poetry by Karen Silverwomyn . Hip-Hop by Genetix . Open Mic: BRING YOUR STUFF! $5 or PWYC 7 pm - Sunday, August 31st [ ]Oasis Bar & Res.. - 780 Queen St. E. (east of Broadview) 19+ (Sorry) (Money will be used to send a delegate to the Native Youth Movement conference in Vancouver.) In the meanwhile, check us out at: [ ] [ ] ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| The Gathering of Good Minds Anna Fleet for Canadian Aboriginal News LONDON ON --On September 26th, 27th and 28th visitors to the city of London, Ontario will have a rare opportunity to experience Abooriginal Canadian film, visual arts and performance, workshops, teaching circles with Elders and numerous children's activities first-hand, during The Gathering of the Good Minds: A Celebration of Native Arts, Wisdom and Culture. Presented by The Gathering of the Good Minds Committee, which includes Wiiche Ke Yig, Museum London, Museum of Archeology, Nokee Kwe, N'Amerind Friendship Centre, Children's Museum and various other community volunteers, the three-day festival will comprise First Nations Elders, traditional teachers, artists, dancers, singers, storytellers, filmmakers, writers and comedians. Opening ceremonies, hosted by conductor and spiritual teacher Dan Smoke-Asayenes, will take place at Museum London on Friday September 26th at 7 p.m. Museum London events will include the primary art exhibition, performances, and workshops in progress that will continue through to Sunday. A series of events will also take place at the Museum of Archeology on Sunday and at Covent Garden Market throughout the weekend. The public is also invited to attend Sunrise Ceremonies that will commence every morning at 6a.m. on the Museum's lawn. Breakfast and refreshments will follow at approximately 8 a.m. A Sacred Fire, honoring Spirit and life, will be kept aflame throughout the weekend. Vendors will showcase Aboriginal crafts in the Market for the duration of the festival. A direct bus route will be available for patrons to attend both locations and admission to all events is free. For more information on the festival, artists, elders, and performers visit <> June 20, 2003 portions of a MEDIA RELEASE from The Gathering of the Good Minds: A Celebration of Native Arts, Wisdom and Culture media contact people: Dan Smoke - Asayenes #61-1290 Sandford St. LONDON, Ontario N5V 3Y2 5l9 659-4682 <mailto:dsmoke@...>dsmoke@... Amanda Eisen 137 Dundas St. London, Ontario N5Y 3W5 Tel: (519) 667-7088 Website: <> THE GATHERING OF THE GOOD MINDS: A CELEBRATION OF NATIVE ARTS, WISDOM AND CULTURE, September 26 - 28, 2003, INVITED PRESENTERS Alanis Obomsawin Distinguished filmmaker, singer, storyteller and author, Alanis Obomsawin is a member of the Abenaki Nation. In 1967 she directed her first film, Christmas at Moose Factory, for the Canadian National Film Board. Her latest film Rocks at Whiskey Trench is her fourth powerful documentary feature describing her impressions of the Oka crisis. Obomsawin has earned more than 30 awards for her films internationally, as well as being honored with the Order of Canada (1983), the federal government's highest honour, and a Governor General Award (2001) for her long-standing contribution and commitment to Aboriginal Canadian cultural heritage. Robbie Antone A local performer, originally from the Oneida Settlement by Lambeth, Ontario. Robbie has been singing the blues for several years. He has been a guest on the hit TV show Buffalo Tracks (APTN). Ida Baptiste Ojibway woman originally from the Berens River in Manitoba. She has lived in London, Ontario for several years, creating many fine oil paintings. Ida graduated with a Honours B.A. from Trent University and has received her Ontario Teacher Certificate. Ida also has some beautiful beadwork to share. She has learned the fine art of Petote stitching from Mary Lou Smoke and has gone on to create some beautiful patterns while applying beadwork to some Sacred items. Danny Beaton A Mohawk with roots in the Six Nations, now lives in Toronto. Danny has been active in the Native cultural and arts' scene for many years. He was the a principal organizer of "Project Indigenous Restoration" in 1992, which featured elders, artists and healers from across Canada, the USA and South America. Danny is also a portrait photographer and now a documentary film-maker. His many movies have been shown on various T.V. programs for the past decade. Dylan Campbell An invited artist - was born Native but raised in a Scottish family in Southwestern Ontario. A self taught artist and sculptor, his first print "Spiritual Awakening" is worth five times its original price. His early work was in black and white but in more recent productions he uses shading and colour to achieve greater dimension. His sculptures use bone and copper, and won a juried exhibition for "Predominate Accession." He has won an Ontario Arts Council grant. Philip Cote An invited artist - is an Ojibway man who resides in Toronto. Phillip works with oils to create outstanding, legendary creations on canvas. He also works with soapstone and at present is traveling to reserves in Ontario demonstrating the fine art of Soap-stoning. Sean Couchie An invited artist - is Ojibway of the Nipissing First Nation and has been living in London for 26 years. He studied art and architecture in high school and advertising art at Fanshawe College. He won two prizes from the Peace Hills Trust Native Art Contest for "If I Had Wings" and "Vision Seeker". Oils, airbrush, pen and ink, scratch-board and wood-burning are used for creations for Ontario Native organizations, calendars, posters, books and magazines, always showing Natives in a positive perspective. Tim Dillon A Metis/Anishinabek from the Bruce Peninsula now living in London. He is a local entertainer writing and singing Rock and Country music with his guitar. He has performed with Jade Idols and other groups at various clubs. A graduate in computer programming at Fanshawe College he founded London Cyber Studio providing recording and engineering servic es for London Musicians. He is currently producing his own solo CD. Terry Dokis An Ojibway originally from the Dokis First Nation. Terry resides in North Bay and teaches in the social work field at Canadore College. Terry is a Medicine Wheel facilitator and explains the application of the Medicine Wheel to health and intervention. Terry has offered to fly in from North Bay and teach a drumming and sonics workshop, traditional meditation workshop or something more closely related to social work. Bruce Elijah An Oneida Faith keeper of the Wolf Clan. He is a very respected Elder. He sits with the Elders Council of the Chiefs of Ontario organization and the Assembly of First Nations. He is widely sought for his traditional wisdom workshops and teaches the Old Ways. He is very knowledgeable about the Great Law of Peace, the constitution of the Haudenosaunee People. He cond ucts sunrise ceremonies as well as Sweat Lodge Ceremonies in treatment centres and other residential care facilities for Native people. Norma General A clan mother from the Mohawk Nation who resides on the Grand River territory of the Six Nations Reserve. She has been raised in the Traditional manner of her ancestors, being the daughter of Onondaga Chief Oliver Jacobs, in the Onondaga Long house. She has worked extensively as a healing and wellness co-ordinator for Friendship Centres. She conducts workshops for all ages on Tradition l teachings. She also employs play therapy in her workshops. Vern Harper Resident Elder of the Toronto Community. Having walked the talk for the last three decades, Vern has helped many Native People find their way back onto the Red Road. Vern has a Sweat Lodge outside the city of Guelph where he holds Sweat Lodge Ceremonies on a weekly and as need basis. Vern is Cree, originally from Saskatchewan. Dr. Dawn M. Hill Mohawk, Wolf Clan living at Six Nations of the Grand River. Her doctoral thesis Spirit of Resistance: The Lubicon Lake Nation, is being published by the U of T press. She is the Academic Director of the Indigenous Studies Program at McMaster University. Her research has been supported by SSHRC, Canada Council, Fullbright and E.A.G.L.E... She has organized many conferences always focusing on Native Elders guiding scholars in indigenous knowledge. Kanata Native Dance Theater A group of professional artists from the Six Nations of the Grand. The Mohawk word means "community" and its acronym stands for Keeping American Native Arts and Traditions Alive. The dancers have performed at national and international festivals including Harbourfront, the Unity Ride Concert and the McMichael Canadian Gallery. Janice Longboat Mohawk Nation, Turtle Clan now living at Six Nations. She is a Traditional Teacher, counselor and herbalist. Her vision is to support healthy Aboriginal families and communities by Traditional Aboriginal healing ways. She has taught at universities and colleges at Hamilton, Toronto and Brantford and grows and prepares traditional plant medicines Larry McCleod-Shabogesic An Elder and educator who resides in Nipissing with his wife Darlene and family. Larry constructs Traditional Birch Bark Canoes and is a keeper of the Medicines. Nikki Manitowabi A member of the Wikwemikong Unceded Nation on Manitoulin Island. She is of Pottawatomi/Odawa descent. Nikki derives many of the ideas in her paintings from observations and experiences with her children. Shelley Niro A Mohawk woman originally from Six Nations. She has been involved in the arts for a number of years and has earned a Masters Degree at the University of Western Ontario. Shelley works with oils. She is a film maker who has received accolades for her award winning film "Honey Moccasin" Ogitchitaw Kwe Og (which means Warrior Women) A group of mostly Anishinawbe singing women. They are quite a peace loving group and are here to share their strength and wisdom The creator has gifted each of the women in the singing group with a voice to share and sing with. Their songs have been passed on from generation to generation in the oral tradition. They hope that the songs they sing will help others who are on their own healing journeys. Mary Lou Smoke From Batchawana Bay, Ontario. Born to Ojibway parents, she is a writer, singer, guitarist, traditional drummer and shaker player as well as an actress having been featured in the Vagina Monologues as performed as a fund raiser for the Sexual Assault Center on March 8th, 2003. Mary Lou and her husband Dan often work together conducting opening and closing ceremonies as well as Sacred Sweat Lodge Ceremonies. They co-host a radio news magazine called Smoke Signals First Nations Radio and have been community commentators on the news for the "New PL" for the past three and a half years commentating on Native issues for CFPL television of London, owned by CITY TV. Dan Smoke - Asayenes From the Seneca Nation of the Iroquois Confederacy, Kildeer Clan. He grew up on the Grand River territory and now lives in London. He is a lifetime member of the Onondaga Long hous e traditional way of life and part of the Native Circle at the Museum London. Dan is a conductor and spiritual teacher at Sunrise Ceremonies marking special occasions. Dan and his wife, Mary Lou were honoured by London's Mayor for their work in Humanitarianism in the year 2000. Drew Hayden Taylor An award winning playwright, journalist and screenwriter from the Curve Lake First Nations (Ojibway). In his vast career, he has written eleven books, had over fifty productions of his plays seen around the world, directed, written or worked on at least eighteen documentaries about Native culture, written for five television series, and is the author of a humourous column appearing in several Native News publications. HISTORY OF THE ORGANIZATION The Gathering of the Good Minds Committee was formed in the year 2000, initially motivated by a local Native Rights support group called Wiich Ke Yig. Wiich Ke Yig is an Ojibway word which translates into "Friends Who Walk With Us". Wiich Ke Yig is a group of Native and non-Native volunteers working together for increased understanding and justice. Encouraging others to join in the work of healing our people, our spirit, and our Earth, until peace, justice and respect are extended to all First Nations. With the desire to continue to organize a major cultural event in London Wiich Ke Yig formed the planning committee involving more Native and non-Native members. Individuals from many sectors of the community have come together to plan, organize and participate in a Festival to educate the Native and non-Native public about traditional arts, culture and wisdom of the Aboriginal peoples. In 2001, the committee was successful in the implementation of the first Festival. The Gathering of the Good Minds Festival is made possible as the result of many dedicated volunteers and several organizations providing support services and resources including Wiich Ke Yig, Museum London, Museum of Archeology, Nokee Kwe, N'Amerind Friendship Centre, At^loshsa Family Healing Centre and the Children's Museum. This event and the many groups and people involved in the non-Native community, want to promote a better understanding and co-operation with Native people. We believe that increased knowledge will bring peace and just relationships between Native and non-Natives. Through the activities of Wiich Ke Yig, small steps to education non-Native Canadians about traditional Native spirituality and culture, that is, the values and teachings that nurtured a healthy Earth and mankind's proper place with the Circle of Life. An important way to attain this goal is through the celebration of the arts and by demonstrating the vital role art has always played in all facets of Native life. SOME PAST ACTIVITIES INITIATED AND ORGANIZED BY WIICH KE YIG: Beginning in 1990 - monthly meetings has been held to consider organization policy, plan special events, and to provide program activities and to promote our goals. Since 1991, approximately four events per year have been organized by members to Wiich Ke Yig for the London area. A sample of these include: . a conversation on healing with Elder Art Solomon . participation in the Camp Ipperwash demonstration to serve the military with an eviction notice, followed by ongoing lobbying on behalf of the Stoney Point people . support of David Suzuki's book launch at the University of Western Ontario - the Wisdom of the Elders . a protest at the London International Air Show in support of the Innu's problems with low flying planes. . the successful appeal to Correction Services Canada regarding inmate Randy Charboneau. . the organization of a Film Festival on four Saturdays culminating in a panel discussion on the "Gene Hunters". . A dinner/dance and fund raising benefit concert with Murray Porter . Native Prisoner's Justice Day: organized a seminar for prisoners, their relatives and other volunteers. As a result a committee has been formed to offer continuing assistance and visitations to prisoners. . Prayer circles for Dudley George on March 17th (1996-2002) . Hosting of the premiere of the movie "Smoke Signals" . A week-end workshop on "Aboriginal Awareness" facilitated by the Aboriginal Rights Coalition but organized by Wii ch Ke Yig . Joint venture with London's N'Amerind Friendship Centre in organizing a large Native Art Show entitled "Listen to the Drums". IN ADDITION: Since 1992 Wiich Ke Yig has supported and participated in National Aboriginal Solidarity Day, including a Sunrise Ceremony every June 21st, which is now attended by an almost equal number of Native and non- Native Londoners. Two special commemorative trees have been planted: . In 1991, a White Pine Tree Planting Ceremony was held in the London Peace Garden in remembrance of those involved in Oka. Each year on July 11th, people gather at the Tree of Peace to lay down tobacco, pray, sing and awe at the size of the tree. . On September 6, 1996 a Tree of Peace was planted in the federal building courtyard, and included a permanent plaque in memory of Dudley George, followed by the bi-annual remembrance ceremonies from 1996 to present. . Beginning in 1996, a sub-committee of Wiich Ke Yig has supported Native Justice and Spirituality with a monthly ceremony and information meetings at the Unitarian Fellowship. Over the past few years members of Wiich Ke Yig have placed a heavy emphasis on justice issues and were very successful in the first presentation of The > Gathering of the Good Minds - so now, we want to continue working together to do it again. Everyone is Welcome and Admission to all events is free. All My Relations Dan Smoke-Asayenes & Mary Lou Smoke-Asayenes Kwe Smoke Signals First Nations Radio, CHRW, 94.7 FM Outstanding Multicultural Program for 2003 #1 Campus & Community Radio Station in Canada Sundays 6:00 - 8:00 p.m., <> 519 659-4682 fax: 5l9 453-3676 <> ||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||||| PM loses interest in unpopular native bill<?xml:namespace prefix = o Chrétien now says there's no urgency for governance act Bill <?xml:namespace prefix = st2<?xml:namespace prefix = st1Curry, CanWest News Service Sunday, August 24, 2003 IQALUIT, Nunavut -- Critics of Prime Minister Jean Chrétien's controversial First Nations Governance Act are declaring victory following commennts from the PM that passing the bill is not urgent, despite the fact he will soon retire from politics. "It's done like dinner," said NDP MP Pat Martin, who stopped the bill from from receiving House of Commons approval in June by staging an unprecedented filibuster in committee that on several occasions lasted through the night. The First Nations Governance Act, known in Parliament as Bill C-7, was featured prominently in the September 2002 throne speech and was frequently referred to by the prime minister in explaining why he needed to remain in office until February 2004. "This is a bill that is not to be implemented for the next two, three years anyway," Mr. Chrétien said yesterday. "In the bill there is a clause that this bill will not be in effect until two years after the passage by the Senate, so it's not an urgent, urgent piece of legislation because there is a delay to that. But we have to keep working because there are some problems that need to be solved there and (Indian Affairs) MInister (Robert) Nault has been (consulting) and there will be more consultation, but there is always a time when you have to decide." The legislation, which imposes minimum standards for First Nations leaders regarding elections and financial reporting, has been harshly criticized by the Assembly of First Nations and the bill's progress in the House has been delayed by procedural tactics from the NDP and Bloc Québécois. Liberal leadership front-runner Paul Martin has also expressed concern with the bill and told a group of Liberal senators this summer he would be open to having the legislation changed significantly should it make it to the upper chamber. Mr. Chrétien's change in tone comes as political observers speculate on how Parliament's fall session will unfold given that it will be known by late September whether Mr. Martin has enough votes to win the November leadership vote on the first ballot. Mr. Chrétien toyed with the press at last week's Liberal caucus meeting in North Bay, at times suggesting he may retire early, then stating later he intends to remain as prime minister until February 2004. MP Pat Martin said the prime minister appears to have realized he no longer has the political capital to force the bill through Parliament, given the comments that have been made by the Liberal leadership front-runner. Mr. Chrétien was speaking yesterday in Iqaluit, Nunavut, where he announced the creation of Ukkusiksalik National Park on the northwestern shore of Hudson's Bay at Wager Bay. Several speakers praised Mr. Chrétien for his work with the Inuit people over the past 40 years. "He is someone who had to fight his way up, but his heart and conviction led him to great heights," said Nunavut Premier Paul Okalik. [Non-text portions of this message have been removed] Your message has been successfully submitted and would be delivered to recipients shortly.
https://groups.yahoo.com/neo/groups/NatNews-north/conversations/topics/5236
CC-MAIN-2017-51
en
refinedweb