text
stringlengths
454
608k
url
stringlengths
17
896
dump
stringclasses
91 values
source
stringclasses
1 value
word_count
int64
101
114k
flesch_reading_ease
float64
50
104
The best answers to the question “What does "static" mean in C?” in the category Dev. QUESTION: I’ve seen the word static used in different places in C code; is this like a static function/class in C# (where the implementation is shared across objects)? ANSWER: There is one more use not covered here, and that is as part of an array type declaration as an argument to a function: int someFunction(char arg[static 10]) { ... } In this context, this specifies that arguments passed to this function must be an array of type char with at least 10 elements in it. For more info see my question here. ANSWER: - A static variable inside a function keeps its value between invocations. - A static global variable or a function is “seen” only in the file it’s declared in (1) is the more foreign topic if you’re a newbie, so here’s an example: #include <stdio.h> void foo() { int a = 10; static int sa = 10; a += 5; sa += 5; printf("a = %d, sa = %d\n", a, sa); } int main() { int i; for (i = 0; i < 10; ++i) foo(); } This prints: a = 15, sa = 15 a = 15, sa = 20 a = 15, sa = 25 a = 15, sa = 30 a = 15, sa = 35 a = 15, sa = 40 a = 15, sa = 45 a = 15, sa = 50 a = 15, sa = 55 a = 15, sa = 60 This is useful for cases where a function needs to keep some state between invocations, and you don’t want to use global variables. Beware, however, this feature should be used very sparingly – it makes your code not thread-safe and harder to understand. (2) Is used widely as an “access control” feature. If you have a .c file implementing some functionality, it usually exposes only a few “public” functions to users. The rest of its functions should be made static, so that the user won’t be able to access them. This is encapsulation, a good practice. Quoting Wikipedia: In the C programming language, static is used with global variables and functions to set their scope to the containing file. In local variables, static is used to store the variable in the statically allocated memory instead of the automatically allocated memory. While the language does not dictate the implementation of either type of memory, statically allocated memory is typically reserved in data segment of the program at compile time, while the automatically allocated memory is normally implemented as a transient call stack. And to answer your second question, it’s not like in C#. In C++, however, static is also used to define class attributes (shared between all objects of the same class) and methods. In C there are no classes, so this feature is irrelevant. ANSWER: Multi-file variable scope example Here I illustrate how static affects the scope of function definitions across multiple files. a.c #include <stdio.h> /* Undefined behavior: already defined in main. Binutils 2.24 gives an error and refuses to link. */ /*int i = 0;*/ /* Works in GCC as an extension: */ /*int i;*/ /* OK: extern. Will use the one in main. */ extern int i; /* OK: only visible to this file. */ static int si = 0; void a() { i++; si++; puts("a()"); printf("i = %d\n", i); printf("si = %d\n", si); puts(""); } main.c #include <stdio.h> int i = 0; static int si = 0; void a(); void m() { i++; si++; puts("m()"); printf("i = %d\n", i); printf("si = %d\n", si); puts(""); } int main() { m(); m(); a(); a(); return 0; } GitHub upstream. Compile and run: gcc -c a.c -o a.o gcc -c main.c -o main.o gcc -o main main.o a.o Output: m() i = 1 si = 1 m() i = 2 si = 2 a() i = 3 si = 1 a() i = 4 si = 2 Interpretation - there are two separate variables for si, one for each file - there is a single shared variable for i As usual, the smaller the scope, the better, so always declare variables static if you can. In C programming, files are often used to represent “classes”, and static variables represent private static members of the class. What standards say about it C99 N1256 draft 6.7.1 “Storage-class specifiers” says that static is a “storage-class specifier”. 6.2.2/3 “Linkages of identifiers” says static implies internal linkage: If the declaration of a file scope identifier for an object or a function contains the storage-class specifier static, the identifier has internal linkage. and 6.2.2/2 says that internal linkage behaves like in our example: In the set of translation units and libraries that constitutes an entire program, each declaration of a particular identifier with external linkage denotes the same object or function. Within one translation unit, each declaration of an identifier with internal linkage denotes the same object or function. where “translation unit is a source file after preprocessing. How GCC implements it for ELF (Linux)? With the STB_LOCAL binding. If we compile: int i = 0; static int si = 0; and disassemble the symbol table with: readelf -s main.o the output contains: Num: Value Size Type Bind Vis Ndx Name 5: 0000000000000004 4 OBJECT LOCAL DEFAULT 4 si 10: 0000000000000000 4 OBJECT GLOBAL DEFAULT 4 i so the binding is the only significant difference between them. Value is just their offset into the .bss section, so we expect it to differ. STB_LOCAL is documented on the ELF spec at: STB_LOCAL Local symbols are not visible outside the object file containing their definition. Local symbols of the same name may exist in multiple files without interfering with each other which makes it a perfect choice to represent static. Variables without static are STB_GLOBAL, and the spec says: When the link editor combines several relocatable object files, it does not allow multiple definitions of STB_GLOBAL symbols with the same name. which is coherent with the link errors on multiple non static definitions. If we crank up the optimization with -O3, the si symbol is removed entirely from the symbol table: it cannot be used from outside anyways. TODO why keep static variables on the symbol table at all when there is no optimization? Can they be used for anything? Maybe for debugging. See also - analogous for staticfunctions: - compare staticwith extern, which does “the opposite”: How do I use extern to share variables between source files? C++ anonymous namespaces In C++, you might want to use anonymous namespaces instead of static, which achieves a similar effect, but further hides type definitions: Unnamed/anonymous namespaces vs. static functions ANSWER: Short answer … it depends. Static defined local variables do not lose their value between function calls. In other words they are global variables, but scoped to the local function they are defined in. Static global variables are not visible outside of the C file they are defined in. Static functions are not visible outside of the C file they are defined in.
https://rotadev.com/what-does-static-mean-in-c-dev/
CC-MAIN-2022-40
refinedweb
1,157
62.68
This is a discussion on Re: New-bus unit wiring via hints.. - FreeBSD ; On Oct 30, 2007, at 10:48 AM, John Baldwin wrote: >>> That isn't what is happening though. The port marked "1" is at >>> 0x3f8 >>> and happens to be "later" in the namespace than the port marked "2" >>> ... On Oct 30, 2007, at 10:48 AM, John Baldwin wrote: >>> That isn't what is happening though. The port marked "1" is at >>> 0x3f8 >>> and happens to be "later" in the namespace than the port marked "2" >>> which is at 0x2e8. The BIOS may _optionally_ decide to communicate >>> this to the OS via the _UID method, but the _UID is only guaranteed >>> to be a string that it suitable for use in a label in a GUI dialog >>> box. >> >> Doesn't this imply that enumerating on the lexicographical ordering >> of the (optional) _UID method would help us do what firmware writers >> intend? >> >> In other words, we don't need a number. We just need a means to >> determine the relative order and we enumerate in that relative >> order. Isn't that how it is now (and if not shouldn't it be that >> way)? > > No. They are strings that have no implied ordering. Then there's no problem, for if _UID is designed as a user-visible label and there's no ordering then no-one can claim that one is to be before the other and thus that the logical ordering in the AML is in fact the right ordering. This of course means that the user can see COM2 before COM1 in some user-interface. This of course is exactly in accordance with the firmware and as such correct. >>> Even if a PC has non-standard resources for COM1 and COM2, the >>> serial >>> ports will show up as sio2 and sio3. >> >> This is another sio(4) bug that uart(4) doesn't have, yes :-) > > Hmmm, I don't think you parsed what I meant, but maybe you mean that > uart(4) > doesn't have the poorly-implemented "feature" in sio(4) to make sure > that all > non-ISA serial ports start at unit 2 to "reserve" sio0 and sio1 for > COM1 and > COM2? Exactly. > Just look in sio_pci.c for 'device_set_unit()' which the current > wiring patches remove with a vengance by making hints always reserve > a given > (name, unit) tuple. And since hints are shipped by us with default values, what we did is remove the poorly-implemented "feature" from sio(4) only to bank on hints to yield the same result, which makes hints nothing more than a different poorly-implemented "feature" :-) >>> Since you don't care what sio0 >>> means at all why not let other people who _do_ care have it work on >>> their >>> systems? >> >> "I" may not care what sio0 means, but that doesn't mean "I" don't >> care that "my" serial ports aren't numbered starting with 0. > > And you could have an empty hints file and be happy. With the exception of course of having an OS that does the wrong thing OOTB and that requires extensive fiddling to behave correctly, increasing the amount of maintenance and upgrade hassle. >>>> You rightly point out that what it really boils >>>> down to is how devX maps to a port on the back or >>>> front of the machine. This mapping should not >>>> change gratuitously. Device wiring achieves that. >>> >>> But on what basis will you wire things? >> >> Correcting the mapping of device instances to physical/visible >> ports will need to be based on user input. A default mapping, >> based on the self-enumerating ability of hardware/firmware, may >> not get it just right in all cases. But may provide a good and >> reliable starting point that may end up 90+% correct. > > Oof. See, here is where I think we hit a snag. I'm thinking inI'm thinking in > terms of > automated installations to a wide variety of server boxes that don't > have > a GUI with a mouse and monitor hooked up so a user can clicky-clicky > to set > which serial port is sio0. I don't see a snag. But maybe that's because I use uart(4) on my machines and I have a serial consoles no matter how things are enumerated... >>> The only currently reliable >>> way I can see to wire things on x86 for an ISA device (and yes, the >>> COM port on a PC is ISA even if ACPI is what enumerates it rather >>> than >>> PNPBIOS) is I/O resources or the name of the device in the ACPI >>> namespace (ACPI-only). >> >> I disagree. Since the firmware describes the legacy devices present >> in the system, the only reliable way is to trust that information. >> Sure, bugs may exist but 95+% of the FreeBSD code assumes correctness >> of hardware as it is, so why not in this respect? > > You've missed the point of this entirely then. Yes, the firmwareYes, the firmware > is > authoritative, and part of the goal is to fix a long-standing > weakness where > the OS is presented with two different enumerations of hardware: one > supplied > by the user via hints and one supplied by the firmware. The "weakness" you mention is really the OSes own failure by "presenting" itself with hardware information that has no relation to the machine that it runs on, because it's actually fixated by virtue of being part of the OSes source code. It isn't supplied by the user at all. We supply it to ourselves. Don't go blaming the user for that... > The idea is to trust > the firmware's notion of resources since it probably knows better > while > allowing for other non-resource information provided by the user to > be tied > to the correct piece of hardware. Agreed... He, that's what I said previously and you responded to with saying that we hit a snag. I guess we don't then; or do we? I'm confused now :-) >> Anyway, when ACPI describes the hardware, I prefer not to call the >> legacy hardware ISA devices. It's important to make a clear >> distinction >> between enumerating and non-enumerating hardware, because that allows >> you to create mechanisms for dealing with non-enumerating hardware >> (i.e. >> hints) without creating conflicts or ambiguity with enumerating HW. >> We have convoluted this and mistakenly accepted this convolution as a >> property of ISA hardware. >> >> I've been advocating that our bus-abstraction is a good one. Devices >> enumerated by ACPI can be said to be attached to an ACPI bus. At >> least >> it's not more wrong than saying that they are ISA devices when it's >> obvious that there's no ISA bus to be found in modern hardware and >> all >> the legacy hardware is really on the chipsets LPC bus. > > You continue to ignore that ACPI is not just a simple bus, but is a > namespace > that enumerates devices on multiple busses such as ISA/LPC, SMBus > (e.g. an > IPMI SSIF interface can be enumerated via ACPI), etc. It is much more > generic than just an ISA enumerator like PNPBIOS. No, I don't ignore anything. I explicitly and deliberately use the term "abstraction". It's a simplified representation of reality. An "idea". My choice of calling ACPI a bus is probably what confuses you. I'm fully aware that it is much more than a bus, but it still "quacks" like one WRT legacy hardware... >>> For uart console wiring you use I/O resources for >>> wiring even. >> >> Yes, but not "even". Since bus-enumeration hasn't happened yet, >> we can not describe the serial console by name+unit, because we >> have no way of knowing upfront what unit number will be assigned >> to the UART. The only way you can describe the serial console >> is by hardware resources or by firmware-level names (such as is >> the case on powerpc & sparc64). >> >> This is why using hints to "mark" the console is wrong. >> >> Note also that on ia64 (at least) ACPI tables exist that describe >> the serial console (and debug port) and those tables use hardware >> resources. So, the common denominator is I/O resources (even for >> OFW-based machines) and as it is, it's really the only thing you >> need (module hardware type) to make a low-level console work. >> >> The only correct way to identify hardware for use as low-level >> console is by it's location in I/O space (module hardware type). >> This is what uart(4) does and it's one of the reasons uart(4) >> works on all platforms even though low-level console support is >> highly machine dependent. It's the right way of doing it and >> as such it just works. >> >> Do not mistake low-level console identification with bus-enumeration >> device wiring or it being similar to hints. >> >> To re-iterate: >> We should reserve hints for describing non-enumerating hardware >> (which means device.hints should be non-existent OOTB) and we >> should add other mechanisms to wire devices to hardware, making >> use of the fact that underneath it mechanisms exist to enumerate >> the hardware (incl. hints for non-enumerating hardware). In the >> future we can replace hints with a more flexible and expressive >> means to describe hardware so that it better meets the needs of >> embedded environments and without it impacting device wiring. > > So what do you want: 'wire.sio.0.*?' Or do you want XML or some > binary > registery like Windows that can't be modified by the user w/o first > booting > the OS (which is real handy when it gets corrupted). What I want is something that is appropriate. If we want to wire hardware to devices, then we need to be able to uniquely identify a device in hardware. A path if you will that mentions busses, bridges devices and functions therein. Look at ACPI, EFI and OFW for example. Such an identification is the keying entity. Data that corresponds to that key can be complex or compound so that you can actually specify which driver you want to use above and beyond simply wiring it to a unit number. This also also allows us to add other pieces of information. I'm not going to give concrete examples, because I foresee that the discussion will then be about how my "solution" sucks rather than it being treated for what it is: an illustration -- something to explain what I said and in no way complete or even usable. Ok, what the heck. For better or for worse: \begin{/boot/hardware.conf} # Lines starting with '#' are comments [pci0.0.18.0] # First function: standard UART # We use this for remote GDB driver="sio" unit=2 dbgport="9600,n,8,1" [pci0.0.18.1] # Second function: standard but memory-mapped UART # doesn't work with sio(4) -- needs uart(4) # We use this one as console. driver="uart" unit=3 console="115200,n,8,1" \end{/boot/hardware.conf} Don't get confused about marking the hardware as console or debug port and how we do the same in hints. It isn't the same. Hints mark the driver instance as console or debug port. Here I mark the *hardware* as console or debug port, even if we don't wish to wire it to a driver instance (although we do in the example) Fundamentally different! > Right now the current "solution" results in various places (like my > employer) > just turning off the ACPI support for sio(4) because hints are more > reliable > for us than ACPI when it comes to enumerating serial ports in _real_ > _world_ > _x86_ server-class machines. Use uart(4)? -- Marcel Moolenaar xcllnt@mac.com _______________________________________________ freebsd-current@freebsd.org mailing list To unsubscribe, send any mail to "freebsd-current-unsubscribe@freebsd.org"
http://fixunix.com/freebsd/287900-re-new-bus-unit-wiring-via-hints.html
CC-MAIN-2014-52
refinedweb
1,961
69.72
u.equals(x) happens when 'u' gets through all the prevs to the room we wanted and needed to visit. u = u.prev; is assigning the previous room to our variable 'u'. 'x' is a room we needed to... u.equals(x) happens when 'u' gets through all the prevs to the room we wanted and needed to visit. u = u.prev; is assigning the previous room to our variable 'u'. 'x' is a room we needed to... Ok, I will post the code and sorry for my absence from the topic but I had some problems. So, this function gives the error: public void run(Vertex x) { this.roomNumber = 0; ... Well, I have found my mistake. The problem was in function Relax: I didn't add back the vertex which weight was the smallest of all. Thank you for your reply though. //EDIT: Though now I have... Hello once again. I wrote a program which uses Dijkstra's algorithm to give us the best weight path through an labyrinth (though every room has 2, 3 or 4 neighbours). Each room has it's weight. We... So: 1. I got it from a friend. 2. constant 53 is: number of small letters + big letters + space. 3. 96 is the code of "`" before "a" in the ASCII code. 4. l is the size of the dictionary. I... I think my hash function has some issue. It should give me numbers 1-7 and for "g" it gives me 0. public static int hash(String key, int l) { int value = 0; for(int j =... That's right. So in BSTs i should just compare strings? No rehash needed? I need to use a Hashtable with an independent connecting which will store Binary Search Trees (words are to be stored in an lexicographical order). I mean: e.g. I get a word with a hashcode 1, so i save it in the BST with the number 1. If i get another word (it's different than the 1st), but it has the same hashcode, I want to save it in the BST... How should i rehash the words with the same hashcode? Creating another rehash method or using hash again(if hash - how?)? I have modified the constructor. Trying to fill the array with the instances. DHT(int n) { bst = new BST[n]; for(int i = 0; i < n; i++) ... return bst[k].insert(x, k); variables: x, k, bst array. x = a k = n bst[1 - n] = null line 236 public static class DHT { Well, i Can't find such a variable. Though when i was trying to debug, i found that the program has some problems with the DHT constructor. This is what it displayed: Not able to submit breakpoint... Exception in thread "main" java.lang.NullPointerException at JavaApplication18$DHT.insert(JavaApplication18.java:244) at JavaApplication18.main(JavaApplication18.java:18) The problem is clearly in the insert method of the BST/DHT class. It crashes at the beginning, while passing the variables from DHT insert to BST insert. It doesn't even print anything when I add a... I have corrected the code. Now it has no compiler errors. I have added to the code in main: while(!"#".equals(s)) { int p = hash(s, n); System.out.println(s + " " + n... Well, I did as you told me, but it didn't tell me a thing. When I printed the variables i didn't get any null value. They were good. I did the whole function with the arguments given on the paper and... Hello. I have a problem with my code. I have implemented BST Tree as well as DHT but my code doesn't work. Here it is: import java.util.Scanner; public class JavaApplication18 { ...
http://www.javaprogrammingforums.com/search.php?s=df99ed3357f94e7be7e0429bad61f99c&searchid=246466
CC-MAIN-2016-36
refinedweb
625
86.2
Ultimate Guide to Red Hat Summit 2018 Labs: Hands-on with Linux Containers Ultimate Guide to Red Hat Summit 2018 Labs: Hands-on with Linux Containers Whether you were already going to Red Hat Summit or just got interested, this article will give you some valuable insight into what to expect. Join the DZone community and get the full member experience.Join For Free This. Our. Linux Container Internals: Part 1 and Part 2 Have you ever wondered how Linux containers work? How they really work, deep down inside? Do you have questions like: - How does sVirt/SELinux, SECCOMP, namespaces, and isolation really work? - How does the Docker Daemon work? - How does Kubernetes talk to the Docker Daemon? - How are container images made? In this lab, we'll answer all of these questions and more. If you want a deep technical understanding of containers, this is the lab for you. It's an engineering walk through the deep, dark internals of the container host, what’s packaged in the container image, and how container orchestration work. You'll get the knowledge and confidence it takes to apply your current Linux technical knowledge to containers. Presenters: Scott McCarty, Red Hat; John Osborne, Red Hat; Jamie Duncan, Red Hat A Practical Introduction to Container Security (3rd Ed.) Linux containers provide convenient application packing and run time isolation in multi-tenant environments. However, the security implications of running containerized applications is often taken for granted. For example, today, Inc.; Daniel Walsh, Red Hat; Aaron Weitekamp, Red Hat Containerizing Applications—Existing and New In this hands-on lab, based on highly rated labs from Red Hat Summit 2016 and 2017, you'll learn how to create containerized applications from scratch and from existing applications. Learn how to build and test these applications in a Red Hat OpenShift environment, as well as deploy new containers to Red Hat Enterprise Linux Atomic Host. You'll quickly develop a basic containerized application, migrate a simple popular application to a containerized version, and deploy your new applications to container host platforms. You’ll get a feel for the different container host platforms and learn how to choose the best one for your container needs. And finally, you’ll learn what to consider and what tools you can use when implementing a containerized microservices architecture. Presenters: Langdon White, Red Hat; Scott Collier, Red Hat; Tommy Hughes, Red Hat; Dusty Mabe, Red Hat Develop IoT Solutions with Containers and Serverless Patterns. }}
https://dzone.com/articles/ultimate-guide-to-red-hat-summit-2018-labs-hands-o-1?fromrel=true
CC-MAIN-2019-35
refinedweb
411
54.02
I have a python script that calls a system program and reads the output from a file out.txt out.txt import subprocess, os, sys filename = sys.argv[1] file = open(filename,'r') foo = open('foo','w') foo.write(file.read().rstrip()) foo = open('foo','a') crap = open(os.devnull,'wb') numSolutions = 0 while True: subprocess.call(["minisat", "foo", "out"], stdout=crap,stderr=crap) out = open('out','r') if out.readline().rstrip() == "SAT": numSolutions += 1 clause = out.readline().rstrip() clause = clause.split(" ") print clause clause = map(int,clause) clause = map(lambda x: -x,clause) output = ' '.join(map(lambda x: str(x),clause)) print output foo.write('\n'+output) out.close() else: break print "There are ", numSolutions, " solutions." You need to flush foo so that the external program can see its latest changes. When you write to a file, the data is buffered in the local process and sent to the system in larger blocks. This is done because updating the system file is relatively expensive. In your case, you need to force a flush of the data so that minisat can see it. foo.write('\n'+output) foo.flush()
https://codedump.io/share/AViaFBLIct4E/1/python-refresh-file-from-disk
CC-MAIN-2016-44
refinedweb
189
70.19
25 SOAP Connector APIs Oracle Mobile Cloud Service (MCS) enables you to create connector APIs to connect to SOAP services. You can call these connector APIs from the implementations of your custom APIs. How SOAP Connector APIs Work A SOAP connector API is an intermediary API for calling SOAP endpoints. The connector API takes the form of a configuration that gives your apps a standard way to connect to these SOAP endpoints and take advantage of the security, diagnostics, and other features provided by MCS. The key steps to creating a SOAP connector API are establishing a connection to an external system, examining and selecting a set of possible interactions, and then modeling them into a reusable API. The SOAP Connector API wizard walks you through creating SOAP connector APIs, from specifying the WSDL location of a remote service, setting a port, setting security policies, to testing your endpoints. SOAP Connector API Design Process Here’s the process for designing a SOAP connector API: A SOAP Connector API is created in MCS using the SOAP Connector API wizard and is passed to the Asset catalog (the Asset catalog is a repository in MCS where API information is stored). The connector API is added to the list of connector APIs (using the API display name) on the Connectors Manage page on the Development tab. The WSDL location is passed to the WSDL Parser. The WSDL file describes how the service is called, what the expected parameters are, and what data structures are returned. From the data in the WSDL file a sample body is generated. The WSDL Parser goes to the provided WSDL location to obtain the WSDL file. All the available ports for the connector are extracted by the parser and returned to the Asset catalog, after which, the port can be selected and the connector API configurations, such as the endpoint URI and custom operation names, are provided. The Asset Catalog stores the security policies and the request and response schemas. Here’s how the runtime flow goes: Custom code calls the SOAP Connector API. Information is then passed to the connector implementation. The implementation extracts the JSON payload from the request. The schemas, security policies, and API configuration are passed to the Asset catalog. The implementation sends the JSON payload to the JSON translator to translate it to XML using the schemas that are stored as part of the API configuration. The JSON translator returns the payload in XML format. A SOAP message is constructed from the XML, some HTTP headers (like context-id) and security-related headers are added and the request is sent to the external service. An XML response is sent by the service back to the connector API. Step 3 and Step 4 are repeated. The response is sent to the JSON translator by the connector implementation to translate the XML response to JSON. The translated response is sent to the connector API. The connector API sends the JSON response back to the custom code. Why Use SOAP Connectors Instead of Direct Calls to External Resources? Allows for simplified declarative connection and policy configuration. Allows calls to an external service, along with security policy setup and credentials, to be encapsulated and used consistently across the mobile API. Provides automatic translation of JSON requests to XML and XML responses to JSON, enabling you to interact with SOAP services without having to work expressly with XML. In addition, it provides you with the ability to provide the SOAP envelope itself, giving you the choice of using XML or JSON. Lets you dynamically modify HTTP timeout properties via the user interface without having to bring down the service. This feature is particularly beneficial when the external SOAP service or network connectivity suffers a slowdown. Provides you with extensive diagnostic information as its tightly integrated with the MCS diagnostics framework. Any outbound calls made through connector APIs are logged, which greatly helps with debugging. Allows for tracking and analytics on remote API usage. Lets you define interaction with the service at design time when you test the validity of your endpoints so that the terms of that interaction aren’t dependent on user input at runtime. This protects both the end system and your mobile backend from harm. Provides a consistent design approach among multiple connector types for interacting with external services. With any change in the interface for a service, lets you can handle any necessary updates, testing, and migration in one place. Creating a SOAP Connector API Use the SOAP Connector API wizard to quickly configure your connector API by providing a name and description, specifying a port, setting security policies, and testing it. Creating a connection to an existing SOAP service can be a simple two-step operation: Name your connector API. Provide the WSDL of the external service. Note:A timeout can occur when downloading a large WSDL file or when connecting to a WSDL over high latency networks, which prevents the creation of the SOAP Connector API. To ensure the WSDL is downloaded, set the following environment policies before you create the API: *.*.Network_HttpConnectTimeout *.*.Network_HttpReadTimeout Set these policies in the development environment in which you’re creating the SOAP Connector API. A mobile cloud administrator can export the policies file from the Administration view, edit these values, and import the modified file back to the development environment. These policies affect only the connector APIs during design time. The timeout values that you set while configuring a connector API take effect during runtime. To edit environment policies, see Modifying an Environment Policy. You also have the ability to configure client-side security policies for the service that you’re accessing and testing and checking the results of your connection. As soon as it’s created, your connector API appears in the list of connector APIs. When at least one connector API exists, you’re taken directly to the Connector API landing page when you click Connectors from the side menu. From there, you can select the connector API you want and edit it, publish it, create a new version or update an existing version, deploy it if it has a Published state, or move it to the trash. See Connector Lifecycle. To call a connector API, you can create a custom API and configure the API’s implementation to call the connector. See Calling Connector APIs from Custom Code. Setting the Basic Information for Your SOAP Connector API Before you begin configuring your connector, you must provide some initial basic information like the connector API name, the address to the remote service, and a brief description: Make sure that you’re in the environment where you want to create the SOAP Connector API. Click and selectApplications > APIs from the side menu. The Connectors page appears. If no connector APIs have been created yet, you'll see icons for each of the connector APIs that you can create. If at least one connector API exists, you'll see the a list of all the connector APIs. You can filter the list to see only the connector APIs that you're interested in or click Sort to reorder the list. Click SOAP or New Connector and select SOAP from the drop-down list.Each time you create a SOAP Connector API, the New SOAP Connector API dialog appears. This is where you enter the basic information for your new connector API. Identify your new SOAP Connector API by providing the following: API Display Name: Enter a descriptive name (an API with an easy-to-read name that qualifies the API makes it much simpler to locate in the list of connector APIs). For example, myOrderApi. Note:The names you give to a connector API (the value you enter in the API name field) must be unique among connector APIs. For new connectors, a default version of 1.0 is automatically applied when you save the configuration. API Name: Enter a unique name for your connector API. For example, myorderapi. By default, this name is appended to the base URI as the resource name for the connector API. You can see the base URI below the API Name field. The connector API name must consist only of lowercase alphanumeric characters. It can’t include special characters, wildcards, slashes /, or curly braces {}. A validation error message is displayed if you enter a name that’s already in use. If you enter a different name for the API here, the change will automatically be made to the resource name in the base URI. Other than a new version of this connector API, no other connector API can have the same resource name. WSDL Location: Enter the address of the existing SOAP service that this connector API will call. For example: You can also copy and paste a WSDL address into this field. To ensure the WSDL you’re using is valid within the scope supported by MCS, see Troubleshooting SOAP Connector APIs. Note:When specifying a port in the URL, only standard internet access ports 80 and 443 are supported. Connection to a service can't be made using a custom port. You can save time by verifying that the URL you’re providing is trusted at trustedsource.org, otherwise, even if you’re connector API is configured correctly, the connection will fail. See Common Custom Code Errors. Short Description: Provide a brief description, including the purpose of this API. The character count below this field lets you know many characters you can add. After you've filled in all the required fields, click Create, which displays the General page of the SOAP Connector API dialog. - Set the timeout values: HTTP Read Timeout: The maximum time (in milliseconds) that can be spent on waiting to read the data. If you don’t provide a value, the default value of 20 seconds is applied. HTTP Connection Timeout: The time (in milliseconds) spent connecting to the remote URL. A value of 0mms means an infinite timeout is permitted. The HTTP timeout values must be less than the Network_HttpRequestTimeoutenvironment policy, which has a default value of 40,000 ms. To learn about environment policies, see Environment Policies. Note:If you have a mobile cloud administrator role in addition to your service developer role, you can open the policies.propertiesfile to see the value for the network policies for the current environment from the Administrator view. Otherwise, ask your mobile cloud administrator for the values. Click Save to save your current settings. If you want to stop and come back later to finish the configuration, the click Save and Close. You can always click Cancel at the top of the General, Port, and Security wizard pages to cancel that particular configuration operation. You’ll be taken back to the Connector APIs page. Click Next (>) to go to the next step in configuring your connector API. After the basic information is provided, you can specify the interaction details for your connector. You can always edit your configuration when it's in a Draft state; however, after you publish your connector API, no changes can be made to it. You can make changes by creating a new version of an existing connector API. See Creating a New Version of a Connector. Selecting a Port The services and their associated ports that are available for the WSDL that you provided are listed on the Port page. A port is a set of actions that define the collaboration and interaction with a web service. A service defines the operations and structures of the WSDL and exposes those operations as explicit endpoints. Although a WSDL can contain multiple ports, the SOAP Connector API can only use a single port at a time. If you need to expose more than one port, you must create one SOAP Connector API for each port. On the Port page, you select a single port that lists the available operations for that service. Optionally, you can provide alternate names for those operations to make them more meaningful or easier to read. - Click the Port navigation link at the top of the SOAP Connector API wizard. - Select a port from the service you want in the list. You can select only one port. Filter the list by entering a string in the Filter field and click the magnifying glass . The endpoint field is populated with the service and port endpoint (URL) that are extracted from the WSDL. By default, the original operation name of the SOAP service is used to form the REST resource at which the functionality of the operation would be exposed by the SOAP Connector API. For example, an operation, CreateIncident, of the service, IncidentReportand port, ReportPort, can be mapped to the REST resource: /mobile/connector/myIncidentReportAPI/CreateIncident. This is the resource path to which custom code would send requests to. You could expose it differently if you wanted to, for example as the REST resource: /mobile/connector/myIncidentReportAPI/Create. Note:If you save the connector configuration without explicitly selecting a port, the first available port for the WSDL is selected for you by default. This action ensures your connector configuration is complete and valid for testing purposes. You can always change the port as long as the connector is in Draft state. - (Optional) Rename one or more operations to make them more meaningful. All the operations available in the selected port are listed. Each operation is mapped to the relative base URI that you entered. For example: the operation Create maps to Create resource. Click Next (>) to go to the next step in configuring your connector API. Setting Security Policies and Overriding Properties for SOAP Connector APIs Select one or more security policies that describe the authentication scheme of the service to which you’re connecting. The security policies have properties, called overrides, which you can configure. One reason to override policy configuration properties is to limit the number of policies that you have to maintain: rather than creating multiple policies with slightly varied configurations, you can use the same generic policy and override specific values to meet your requirements. You don’t need to set all the overrides for a policy; however, you should be familiar enough with a security policy to know which overrides to set. - Click the Security navigation link at the top of the SOAP Connector API wizard. - Select one or more security policies from the list of available policies and click the right arrow to move them to the Selected Policies list.For example, you might want to have wss10_message_protection_client_policyfor message protection and wss_username_token_client_policyfor authentication. Although you can move all the policies to the Selected Policies list, it’s unlikely that all policies are required for your connector API. To learn about supported security policy types for SOAP Connector APIs, see Security Policy Types for SOAP Connector APIs . - Select a policy to read its description. - Specify any other overrides, if applicable, to the selected policy if you don't want to use the default values.To override a policy property, enter or select a value other than the default. For descriptions of policy properties, see Security Policy Properties. To set or create a csf-keyproperty, see Setting a CSF Key. To learn about credential keys and certificates, see CSF Keys and Web Service Certificates. - Click Save to save your work or Save and Close to save your work and exit the SOAP Connector API wizard.Before you can test your connection, you must save your configuration. If you proceed to the testing page without saving the API configuration, you'll see a dialog asking you to save it. You can check the Always save before testing option to automatically perform a save operation for you every time you go to the Testing page. - Click Next (>) to go to the next step, testing the connector API. Setting a CSF Key Click Keys in the csf-key field in the Security Overrides section to open the Select or Create a New API Key dialog. Provide an CSF key in one of the following ways: Select an existing key from the Available Keys list (a description of the selected key is displayed below the list). The list displays only the basic credentials keys supported by the given policy property. When you select the key, its name appears in the Key Name field. Click Select to add the key. The other fields in the CSF Key Details pane are used only when creating a key. Create a new CSF credentials key. To create a new key: - Click New Key. - Enter a key name that is descriptive and easy-to-read. Note that after you create the key, you can’t change the key name. - Enter a brief description of the key's purpose. - Enter the user name and the password (the user credentials) for the service to which you are connecting. Repeat the password in the confirmation field. - Click Save to add the key to the Available Keys list. You can create another key by clicking New Key or edit an existing one. Save toggles to Select allowing you to select a key in the list. Click Cancel to quit the task.The key name value will appear as the override value on the Security page. Note that the value of the key that you create pertains only to the environment in which it’s set. Setting a Web Service Certificate Here the steps for setting the overrides for a Web Service certificate. However, for this release, don’t override the values for keystore.sig.csf.key and keystore.enc.csf.key because orakey is the only valid value for all of these certificate keys. - Select a security policy.The properties for the policy are displayed in the Policy Overrides section. - Select an alias from the drop-down list in the field for the certificate key (certificate keys are denoted by the keystoreprefix) and select an alias.Unlike CSF Keys, you can’t modify a Web Service certificate. You can only select a different alias. Only mobile cloud administrators can create a new Web Service Certificate. If you don’t know the alias for the certificate you want, ask your mobile cloud administrator for the alias. Testing a SOAP Connector API Now that you've defined your connector API, you might want to verify your endpoints and ensure that you’re able to receive the expected results from the web service. Testing a connection is also an optional step but can save you time by identifying and fixing problems with your endpoints using the mock JSON body provided before you finalize the connector API. Testing Your Connector Now its time to validate your connector. The Test page lets you test the connection to a service using sample response data. You’ll see a list of all the operations that you defined for the port. - Click the Test navigation link. - Select the operation that you want to test. The base URI is displayed below the operation name. If you provided an alternate name for the operation, that name appears, otherwise the default operation name is shown. - Click Examples to see Request, Response, and Fault payload examples (in JSON format). These examples are generated based on the request and response definitions in the WSDL file and can’t be edited. The request and response examples display a message body. Fault examples may show one or more faults depending on the operation. They display the error messages returned. For example, here is what a sample GETrequest looks like: { "Header": null, "Body": { "GetIncidentById" : { "IncidentId" : 2 } } } } Here is the request in XML: <soapenv:Envelope xmlns: <soapenv:Header/> <soapenv:Body> <beta:GetIncidentById> <beta:IncidentId>2</beta:IncidentId> </beta:GetIncidentById> </soapenv:Body> </soapenv:Envelope> - (Optional) Click Add HTTP Header to add one or more HTTP headers to apply to the operation. You can select a predefined header or a custom header. For each header, select a header name and provide a value. These headers are for testing purposes only and won't be added to your SOAP Connector API configuration. The default format for the request body and the response body is JSON. You can set the format of one or both to XML if you prefer. See Using XML Instead of JSON. - Use the sample JSON body provided to test your connector or create your XML body in the source editor. A JSON sample body that you can edit is generated for you from the operation that you’ve defined. For example: "Body" : { "CreateIncident" : { "Title" : "new title", "EmailAddress" : "jack@oracle.com", "ImageLink" : "" } } For comparison, here's what the body looks like in XML: <soapenv:Envelope xmlns: <soapenv:Body> <beta:CreateIncident> <beta:Title>new title</beta:Title> <beta:EmailAddress>jack@oracle.com</beta:EmailAddress> <beta:ImageLink>something</beta:ImageLink> </beta:CreateIncident> </soapenv:Body> </soapenv:Envelope> Click in the editor and enter your own body (in JSON or XML format) if you prefer. To learn about JSON conventions and the mapping between JSON and XML, see How Does XML Get Translated into JSON? - If you’ve selected a SAML-based security policy, open the Authentication section and enter your mobile user credentials for each method that you test. If you’re using default test credentials (Step 7), you can skip this step. With SAML-based security policies, the identity of the user making the call is propagated to the external service. For other security policies such as HTTP Basic Authentication and username token, the credentials used to authenticate with the external service are provided in the policy overrides as CSF keys. Depending on the operation you’ve defined, you may have to enter specific credentials for each operation or you might be able to use these credentials for all the methods to authenticate your connector with the service. - Click Save as current mobile backend default credentials to save the user name and password you provide as the default. - If you’re in the design phase of creating your connector and you just want to see if your endpoints are valid, click Default API Designer Test Credentials and select a mobile backend that you’re registered with and its version number.Optionally, you can enter your mobile user credentials (user name and password). These default test credentials are persistent across all the methods that you test. They remain valid during the current MCS session. - Click Test Endpoint. Test Endpoint toggles to Cancel Test when you click it. If you want to stop the test for any reason, click Cancel Test. Click Reset to clear the fields and to change the header types and values and test body. - Repeat Steps 1 through 4 for each method. - Click Done when you’ve finished testing your endpoints.You’re returned to the Connector APIs page. Getting the Test Results After the test is run, the results are displayed at the bottom of the Test SOAP Connector API page. The result indicator is the response status: 2xx - indicates a successful connection 3xx - indicates a redirection occurred 4xx - indicates a user error occurred 500 - indicates an internal server error Here's a list of the more common status codes that you'll want to use: Click Request to see the metadata for the transaction, such as header information and the body of the request. Click Response to see the details of the response returned. The response code tells you whether the connection was successful. Test each of your operations and modify them as needed to validate your endpoints. After your connector API is tested, published, and deployed, you can go to the Connectors page to see analytical information about it, such as how often the connector is being called and what apps are using the connector. See Managing a Connector. Getting Diagnostic Information You can view the response code and returned data to determine if your endpoints are valid. A response status other than 2xx doesn't necessarily mean the test failed. If the operation was supposed to return a null response, a response should show a 4xx code. By examining multiple messages, you can more easily determine where issues occur. For every message that you send, MCS tags it with a correlation ID. A correlation ID associates your request with other logging data. The correlation ID include an Execution Context ID (ECID) that’s unique for each request. With the ECID and the Relationship ID (RID), you can use the log files to correlate messages across Oracle Fusion Middleware components.. Depending on your MCS access permissions, you or your mobile cloud administrator can view the client and server HTTP error codes for your API's endpoints on the Request History page allowing you to see the context of the message status when you're trying to trace the cause of an error. Every message sent has a set of attributes such as the time the event occurred, the message ID, the Relationship ID (RID), and the Execution Context ID (ECID). To obtain and understand diagnostic data, see Diagnostics. SOAP Connector API Design Tips When you configure your SOAP Connector API, you want to ensure that you have a well-formed API. You want to make a valid SOAP Connector API but you should create an API that can be used and understood by others as well. Here are some design recommendations to consider when you define a SOAP Connector API: Most important, test your connector using the Test page after it’s created and at every update. When setting the read and connection timeouts for the connector API, you should set them for a shorter duration than the API timeout. See API Timeouts. Provide an HTTPS endpoint wherever possible. When calling SOAP services protected with HTTP Basic Authentication, you should configure the appropriate security policies on the Security page and store credentials in a CSF key instead of providing the credentials from custom code. While writing custom code to call SOAP Connector APIs, make use of the sample request and response payloads available in the Test page of the SOAP Connector API wizard. See Calling Connector APIs from Custom Code. Keep the payload content relevant to the purpose of the connector, that is, don’t bloat the payloads by adding extraneous data. Include only pertinent data in the message body to facilitate quick transmission of the request or response. When you're working with complex WSDLs, refer to How Does XML Get Translated into JSON? for a discussion of JSON translator limitations. Date formats should follow the ISO-8601 International Standard for date and time: YYYY-MM_DD[THH:mm:ss.sss]Z. For example: 2014-10-07T18:35:50.123Z(see Date and Time Formats for a description of the standard). How Does XML Get Translated into JSON? The WSDL file, which describes the service that you want to access, is an XML-based protocol. The WSDL contains the XML schemas that define the structure of the SOAP XML requests and responses. While XML is a standard means of defining SOAP messages, it’s cumbersome and not well-suited to data-interchange. JSON is the preferred format because it’s a lightweight and easy-to-read and write data interchange format (compared to XML). It’s much easier to handle JSON in (Node.js-based) custom code than XML. Here’s a comparison of XML and JSON features: To make the transmission of data via SOAP Connector APIs possible, MCS uses a JSON translator. The JSON translator uses a set of mapping conventions when converting a JSON request into XML prior to passing the information to a remote service and translates the XML response back into JSON to be passed on to the mobile app. MCS provides sample JSON messages that you can use as a template to construct JSON requests and process JSON responses. A sample payload (body), which gets created for you based on the information in the WSDL, is also translated into JSON. If you choose to provide your own XML sample payload, then you should adhere to the mapping conventions of XML to JSON to ensure a successful translation. The next section demonstrates those mapping conventions. XML - JSON Mapping Conventions Oracle Mobile Cloud Service uses a XML - JSON mapping convention that is based on the Badgerfish convention. The following example shows the mapping of XML elements to JSON object properties: The next example shows how XML attributes are mapped to JSON object properties, with property names starting with the @ symbol: When elements have attributes defined in the XML schema, text nodes are mapped to an object property with the property name $. This is true even if at runtime the attributes do not occur: Here you can see how nested XML elements become nested JSON objects: Here's how XML elements with maxOccurs > 1 in their schemas (that is, repeating elements) become JSON arrays: In the SOAP Connector, the Envelope root element is not required in the JSON message body. During the translation to JSON, XML root elements are dropped when converting to JSON. In the reverse direction, a root element is added when converting JSON to XML. This is done because JSON can have multiple top level object properties which would result in multiple root elements which are not valid in XML: This example shows you how the JSON data types (boolean, string and number) are supported. When converting XML to JSON, based on the type defined in the XML schema, the appropriate JSON type is generated: All namespace information ( ns declarations and prefixes) is dropped when converting XML to JSON. On converting the JSON back to XML, the namespace information (obtained from the schema) is added back to the XML: If a property in an XML file has an empty value, the same property in the converted JSON file shows an empty string: In the reverse scenario, if a JSON file contains a null value, for example "City":null, the translation to XML shows an empty value: <City/>. Mapping Limitations The mapping is comprehensive but isn’t quite a one-to-one match. When creating a message body in JSON, there are some conditons that you should be aware of to ensure that the structure of the body is compliant with the JSON-XML mapping convention. The following constructs aren’t handled by the JSON translator.. If you want to use a construct that isn’t supported by the translator, use XML and be sure to wrap your XML in a SOAP envelope. To learn about JSON, see Introducing JSON at. Using XML Instead of JSON Using JSON isn’t required. You might prefer to use XML instead or you might encounter XML schema constructs that aren’t supported by the translator. You can still interact with the connector using XML requests and responses. The response format is determined by the Accept header in custom code, which has a default value of application/json. To set the format of the request body, add the XML request body and set the contentType header in the custom code to application/xml; charset=utf-8. If you want the response in XML format, change the accept header value to application/xml. For example, /** * The following example calls the 'CreateIncident' resource * on a SOAP connector named '/mobile/connector/RightNow'. * The request and response are in XML and not JSON. * */ var options = { contentType: 'appplication/xml;charset=UTF-8', accept: 'application/xml' }; //Here we suppose an XML message has been //stored in the XML variable var body = xml; req.oracleMobile.connectors.RightNow.post('CreateIncident', body, options).then( function(result){ //result.result contains the response XML res.status(result.statusCode, result.result); }, function(error){ res.status(500, error.error); } ); Remember to wrap your XML in a SOAP envelope. Your XML request must contain the entire SOAP envelope (including any SOAP headers): <?xml version="1.0" ?> <SOAP-ENV:Envelope xmlns: <SOAP-ENV:Header> <!-- Add any SOAP headers here --> </SOAP-ENV> <SOAP-ENV:Body> <!-- Add the Body element here --> </SOAP-ENV:Body> </SOAP-ENV:Envelope> If you configured a security policy on the connector that requires a SOAP header to be sent in the message, that header is added automatically to the envelope you provide so you don’t need to include it in your message. You can see an example of an XML request wrapped in a SOAP envelope in Testing Your Connector. Security Policy Types for SOAP Connector APIs You'll need to set a security policy to protect the information you want to send or receive unless the service you’re accessing isn't a secure service or doesn’t support security policies, in which case, you can’t set a security policy for the connector. When determining what policies to set, consider whether connection to the service involves transmitting proprietary or sensitive information. A few reasons for adding security policies are: Ensuring confidentiality by encrypting messages Ensuring the integrity of the data transmitted by using digital signatures Authenticating the source or destination From the Security section, you can select one or more Oracle Web Services Manager (Oracle WSM) security policies, including SAML, Username Token, and HTTP Basic Authentication. Oracle WSM supports a wide range of security standards, including Authentication Policies and Authorization. Ask yourself the following questions to determine what kinds of security policies you need: What are the basic requirements of your security policy? Do you need to authenticate or authorize users? Do you require only message protection, do you need both? If you need only authentication, do you need a specific type of token and where will the token be inserted? If you need both authentication and message protection, will message protection be handled in the transport layer? For a list of supported security policies, see Security Policies for SOAP Connector APIs. For descriptions of security policy properties that you can override, see Security Policy Properties. CSF Keys and Web Service Certificates Depending on the security policy that you selected, you may be able to override a property that sets a CSF key or a Web Service Certificate. In MCS, the Oracle Credential Store Framework (CSF) is used to manage credentials in a secure form. A credential store is a repository of security data (credentials stored as keys) that certify the authority of users and system components. A credential can hold user name and password combinations, tickets, or public key certificates. This data is used during authentication and authorization. CSF lets you store, retrieve, update, and delete credentials (security data) for a web service and other apps. A CSF key is a credentials key. It uses simple authentication (composed of the user name and the password for the system to which you’re connecting) to generate a unique key value. You can select an existing CSF key or create one through the Select or Create a New API Key dialog. To select or create a CSF key, see Setting a CSF Key. keystore.recipient.alias: The alias for this property is used to identify the certificate in the keystore. keystore.sig.csf.key: The alias for this property is mapped to the alias of the key used for signing. If no value is selected, the default value, orakey, is used (for this release, the only valid value for this property is orakey). keystore.enc.csf.key: The alias for this property is mapped to the alias of the private key used for decryption. If no value is selected, the default value, orakey, is used (for this release, the only valid value for this property is orakey). wss11_username_token_with_message_protection_client_policy, you’ll see that you need to set only keystore.recipient.alias. However, if you selected wss10_username_token_with_message_protection_client_policy, you’ll need to set all three properties. Note:It isn’t necessary to set all the overrides for a policy; however, you should be familiar enough with the security policies that you’ve selected to know which overrides to set for each policy. CSF keys, certificates, and their respective values are specific to the environment in which they’re defined. That is, if there are multiple environments, A and B, and you’re working in environment A, then only the CSF keys and certificates for the security policies in use by artifacts in that environment are listed in the CSF Keys dialog. A different set of keys and certificates will be displayed in environment B. It is also possible for keys with the same key name but with different values to exist in multiple environments. A CSF key can be deployed to another environment, however, because CSF keys are unique to an environment, only the key name and description are carried over to the target environment. You won’t be able to use that key in the new environment until it’s been updated with user name and password credentials by the mobile cloud administrator. Editing a SOAP Connector API If you need to change some aspect of a connector API, you can as long as it’s in the Draft state. After you publish an API, the API can’t be changed. - Make sure that you’re in the environment containing the SOAP Connector API that you want to edit. - Click and selectApplications > Connectors from the side menu.Since at least one connector API exists, the Connectors page is displayed. - Select the draft SOAP Connector API that you want to edit and click Open.You can filter the list by version number or status. You can also sort the list alphabetically by name or by last modified date. - Edit the fields for general information, ports, and security policies as needed. Remember you can always click Save and Close to save your current changes and finish the rest of your changes later. - Save your changes if you didn't select the option to always save the configuration before testing when you created the API. - Test your changes.. To create a new version, publish, and deploy your connector API, see Connector Lifecycle.. SOAP Connector APIs System message logs are great sources for getting debugging information. Depending on your role, you or your mobile cloud administrator can go to Administration in the side menu and click Logs to see any system error messages or click Request History to view the client (4xx) and server (5xx) HTTP error codes for the API's endpoints and the outbound connector calls made within a single mobile backend. Sometimes a connection fails because the service URL provided is untrusted. You can add the URL to the list of trusted URLs at trustedsource.org. To learn more about what happens if you provide an untrusted URL and other common errors that can occur when configuring your connector API, see Common Custom Code Errors. Security_TransportSecurityProtocolsenvironment policy. The policy takes a comma-separated list of TLS/SSL protocols, for example: TLSv1, TLSv1.1, TLSv1.2. Any extra space around the protocol names is ignored. You can use the SSLv2Hello protocol to debug connectivity issues with legacy systems that don't support any TLS protocol. Note that this policy can’t be used to enable SSLv3 endpoints. See Environment Policies and Their Values for a description of the policy and the supported values. Be aware that this policy must be manually added to a policies.propertiesfile that you intend to export. Caution:Be aware when setting the policy that older protocols are vulnerable to security exploits. SOAP Connector API Scope To be sure you’re creating a valid SOAP Connector API in MCS, keep in mind the following WSDL constraints:.
https://docs.oracle.com/en/cloud/paas/mobile-cloud/mcsua/soap-connector-apis.html
CC-MAIN-2022-33
refinedweb
6,575
54.02
. An array has a rank that determines the number of indexes associated with each array elements. The rank of an array is also referred as the dimension of the array. An array may be: • Single Dimensional • Multi Dimensional An array with a rank of one is called single-dimensional array, and an array with a rank greater than one is called a multi dimensional array. Each dimension of array has an associated length, which is an integer number greater than or equal to zero. For a dimension of length n, indices can range from 0 to n-l. In C#, array types are categorized under the reference types derived from. the abstract base. Types system. Array. Single Dimensional Array Single-dimensional arrays have a single dimension (ie. are of rank 1). The process of creation of arrays is basically divided into three steps: 1. Declaration of Array 2. Memory Allocation for Array 3. Initialization of Array Declaration of Array To declare an array in C# place a pair of square brackets after the variable type. The syntax is given below : type[] arrayname; For Example: int [ ] a; float[] marks; double] x; int [ ] m, n ; You must note that we do not enter the size of the arrays in the declaration. Memory Allocation for Array After declaring an array, we need to allocate space and define the size. Declaring arrays merely says what kind of values the array will hold. It does not create them. Arrays in C# are objects, and you use the new keyword to create them. When you create an array, you must tell the compiler how many components will be stored in it. Here is given the syntax: arrayname = new type[size]; For Example: a = new int[5]; marks = new float[6]; x = new double[10]; m = int[100]; n = int [50]; It is also possible to combine the two steps, declaration and memory allocation of array, into one as shown below: int[] num= new int [5]; Initialization of Array This step involves placing data into the array. Arrays are automatically assigned the default values associated with their type. For example, if we have an array of numerical type, each element is set to number o. But explicit values can be assigned as and when desired. Individual elements of an array are referenced by the array name and a number that represents their position in the array. The number you use to’ identify them are called subscripts or indexes into the array. Subscripts are consecutive integers, beginning with 0. Thus the array “num” above has components num[0], num[l], num[2], num[3], and num[4]. The initialization process is done using the array subscripts as shown: arrayname[subscript] = value; For Example: num[O] = 5; num[1] = 15; num[2] = 52; num[3]·= 45; num[4] = 157; We can also initialize arrays automatically in the same way as the ordinary variables when they are declared, as shown below: type[] arrayname = { list of values }; the list of variables separated by commas and defined on both ends by curly braces. You must note that no size is given in this syntax. The compiler space for all the elements specified in the list. For Example: int[] num = {5,15,S2,45,57}; You can combine all the steps, namely declaration, memory allocation and initialization of arrays like as: “, int[] num = new int [5]” {5,15,52,4S,S7}; You-can also assign an array object to another. For Example int [] a = { 10, 20, 30}; int [] b; b=a; The above example is valid in C#. Both the array will have same values. Demonstration of array using system; class Number { public static void Main() { int [] num = {10, 20, 30, 40, SO}; int n =. num.Length; II Length is predefined attribute to access the size of array console.write(” Elements of ,array are :”); for(int ;=0; i<n; i++) { console.writeLlne(num[i]); } int sum =0; for(int i=O; i<n; i++) { sum = sum +.num[i]); } Console.writeLine(” The sum of elements :”+sum); } OUTPUT: Elements of array are: 10 20 30 40 50 The sum of elements :150 Note : If you do not initialize an array at the time of declaration, the array members are automatically initilized to the default initial value for the array type. Also, if you declare the array as a field of a type, it will be set to the default value null when you instantiate the type. Multi Dimensional Array C# supports two types of multidimensional arrays: • Rectangular Array • Jagged Array Rectangular Arrays A rectangular array is a single array with more than one dimension, with the dimensions’ sizes fixed the array’s declaration. The following code creates a 2 by 3 multi-dimensional array: int[,] squareArray =new int[2,3]; As with single-dimensional arrays, rectangular· arrays can he filled at the time they are declared. For instance, the code int[,] squareArray = {(l) returns 0, and the expression squareArray.GetupperBound(l) returns 2, because lowerbound is 0 and upperbound is 2 for length 3. System.Array also includes the method GetLength(int i), which returns the number of elements in the ith dimension (again, zero based) .. The following piece of code loops through squareArray and writes out the value of its elements. for(int i = 0; i < squareArray.GetLengthCO); i++) for (int j = 0; j < squareArray.GetLengthCl); j++) console.writeLine(squareArray[i,j]); A foreach loop can also be used to access each of the elements of an array in turn, but using this construction one doesn’t have the same control over the order in which the elements are accessed. Jagged Arrays A jagged array is an array whose elements are arrays. The elements can be different dimensions and sizes.[l] = new int [6]; The code reveals that each of jag[O] and jag[l] holds a reference to a single-dimensional int array. ‘To illustrate how one accesses the integer elements: the termjag[0] [1] provides access to the second element of the first group. & Concept(O); i++) for (int j = 0; j < jag[i].GetLength(O); j++) console.writeLine(jag[i] [j]); or for (int i = 0; i < jag.Length; ‘i++) for (int j = 0; j < jag[i].Length; j++) console.writeLine(jag[i] [j]); The following example builds on arrays myArray, whose elements are arrays. Each one of array elements has a different size. using System; public class Array Test { public static void Main() { II Declare the array of two elements int [][] myArray = new int [2][]; II initilize the elements myArray [0] = new int [5] {I, 3, 5, 7, 9}; myArray [1] = new int [4] {2, 4, 6, 8}; II Display the array elements for (int i = 0; i< myArray.Length; i++) { console.write (“Element( {O}):”, i) for (int j = 0; j < myArray [i].Length; j++) console.write (“{O}”, myArray [i] [j]); console.writeLine (); } } } OUTPUT: Element (0): 1 3 5 7 9 Element (1): 2 4 6 8 Passing Arrays as Parameters You can pass an initialized array to a method. Here we given example of a printArray (myArray); function for both single and multidimensional arrays. Single Dimension In following example, a string array is initialized and passed as a parameter to the printArray method, where its elements are displayed. using System; public class Arrayclass { static void PrintArray (string [] w) { for (int i = 0; i < w.Length; i++) console.write (w[i]); Console.writeline (); } public static void Main () { II Declare and initialize an array string [] weekDays = new string [] {“sun”, “Sat”, “Mon”, “Tue”, “wed”, “Thu”, “Fri”}; 1/ Pass the array as a parameter printArray (weekDays); } } OUTPUT: Sun Sat Mon Tue wed Thu Fri Multi Dimension In this example, a two dimensional array is initialized and passed to the PrintArray method, where its elements are displayed. using system; public class Arrayclass { static void printArray (int [,]w) { II Display the array elements for (int i = 0; i < 4; i++) for (int j = 0; j < 2; j++) console.writeLine (“Element {O}; {1} = {2}”, i, j,w[i ,j]); } public static void Main () { II pass the array as a parameter printArray (new int [,] {{1, 2}, {3, 4}, {5, 6}, {7, 8}}); } } OUTPUT: Element (0, 0) =1 Element (0, 1) = 2 Element (1, 0) = 3 Element (1, 1) = 4 Element (2, 0) = 5 Element (2, 1) = 6 Element (3, 0) = 7 Element (3, 1) = 8
https://ecomputernotes.com/csharp/page/2
CC-MAIN-2022-21
refinedweb
1,388
62.07
Design And Testability In the line of business applications that I build, it’s considered good practice to use a test-first approach; Test-Driven Development, Behavior-Driven Development, or whatever you want to call it. Write a test, verify that it fails for the right reasons, make it pass, refactor the code to ensure it’s up to all required standards. How a person goes about doing the implementation of the tests and the code to fulfill the tests depends largely on the platform, language and testing tools used. Each platform has different needs and different ways of approaching the idea of “testability” in code. Some languages require specific design decisions to enable testable code, while other languages pretty much guarantee that your code will be testable – even if some designs are easier to test than others. Design And Testability In Ruby If I were writing some code in Ruby, I could easily test this: 1: class Foo 2: def bar 3: baz = Baz.new 4: baz.do_something 5: end 6: end </div> </div> There are a number of options for being able to test the behavior of the Foo class’s .bar method. I could use the nature of Ruby’s open-type system and just replace the initializer and do_something method on the Baz class; I could use RSpec and it’s built in mocking syntax; I could use the not-a-mock gem (which is my preference) to stub the methods; etc. We essentially get testability in ruby for “free” – it’s built into the dynamic nature of the language. Other dynamic languages such as Python, etc, also give us testable code by nature of the language. We are not required to do anything special to create code that is “testable”. Now that doesn’t mean all code is easily tested, though. There are still design principles and paradigms that will make your code easier to test, which also tends to lead to code that is easier to understand. The point, though, is that you don’t have to do anything special to isolate the behavior of the Foo class from the implementation of the Baz class in the above example. Design And Testability In C# Looking at the equivalent code in C#, we would say that this code is not “testable” from the perspective of unit tests: 1: public class Foo 2: { 3: public void Bar() 4: { 5: var Baz = new Baz(); 6: Baz.DoSomething(); 7: } 8: } </div> </div> By all the principles, practices, and design standards that we preach in C# / .NET, this code is not testable because of the hard dependency on the Baz object and it’s implementation. There are a significant number of principles that are being violated in these few lines of executable behavior, and we would need to change the code in a very significant way to create something that is “testable”. We would need to introduce an abstraction over Baz – but ensure that the Foo class owns the abstraction so we don’t violate the Dependency Inversion principle. And we would need to introduce Inversion Of Control and some form of Dependency Injection to ensure that Foo is not directly dependent on Baz’s implementation (neither the constructor nor the DoSomething method’s implementation). The resulting code, to be “testable” by all accounts, would look something like this: 1: public class Foo 2: { 3: private doSomething; 4: 5: public Foo(IDoSomething doSomething) 6: { 7: this.doSomething = doSomething; 8: } 9: 10: public void Bar() 11: { 12: doSomething.DoSomething(); 13: } 14: } 15: 16: public interface IDoSomething 17: { 18: void DoSomething(); 19: } 20: 21: public class Baz: IDoSomething 22: { 23: public void DoSomething() 24: { 25: // ... whatever this does... 26: } 27: } </div> </div> (Note: I included the shell of the implementation for Baz in this example – but those extra few lines of code don’t diminish the expansion of the rest of the code. I included it to show the requirement of implementing the interface on the Baz class.) Angels And Demons As a person who dabbles in ruby and that community, I get the sense that we applaud Matz for the open nature of ruby, allowing the great minds of people like David Chelimsky to develop tools like RSpec with it’s built in mocking capabilities. We have the freedom to express the intent of our code without the significant ceremony of the abstraction, dependency inversion, and “testable” code the we say is required in C#. These people are the heroes – the angels – of the ruby community, held in high esteem because they have made the art of “testable” code approachable by anyone that can write code. And they deserve our applause for these efforts, without question. The tools and capabilities in Ruby and RSpec are quite wonderful and I enjoy working with them. Why, then, do we demonize companies with tools like Telerik’s JustMock, Typemock’s various offerings, and Microsoft “Pex and Moles” for providing the same capabilities in C# / .NET? Why do we attack people like Roy Osherove and dismiss his contributions to the community? Have we become so dogmatic about our “principles” and “standards” that we no longer have a sense of pragmatism or exploration and questioning? Has the “alt.net” community become “dogma.net”, “elitist.net”, or “hate.net” as so many others have suggested, for so many years? What value do we truly gain – other than the admiration and awe of the people that wish they were “smart enough” to point out the “flaws” – through this continuous disregard for what is a valid perspective and approach to software development in .NET? (Edit: the above content create a whirlwind of comments that would have been better off on another communication channel. I should not have taken the tone and stance that I did with this section. The LosTechies community should not be a place where I rant and say these types of incendiary things. As such, I’ve decided to moderate the comments from this post and strike out the above section. Please do not comment on this section, on this blog anymore. I’ll remove the comments. Please continue commenting on the rest of the post, though, as I believe it is still valid.) What’s The Point? I honestly ask – why? … or, why not? If I can write this test in rspec: 1: Baz.should_receive(:do_something) </div> </div> or write this test in typemock: 1: var fake = Isolate.Fake.Instance<Baz>(); 2: Isolate.Swap.NextInstance<Baz>().With(Fake); 3: //... run the foo.Bar method, here 4: Isolate.Verify.WasCalledWithAnyArguments(() => fake.DoSomething()); </div> </div> why shouldn’t I write that one in typemock? Why should we applaud the ruby community for it’s contributions and not the .NET community that has given us the same core capabilities. Is it because the capabilities to do this are not “free” in a static language? Is it because we’re afraid of the profiling API that is required to do this in .NET? Is it because we’ve become dogmatic instead of pragmatic? Is it because TypeMock is expensive? or is there a legitimate reason that we have emotional reactions and cry-foul the possibilities that these tools introduce? Searching … I don’t know the answers. I’m asking because I want to find the answers. And yes, I recognized that I still have an attachment to the abstractions and interfaces. I’m not gong to go spend the $ on TypeMock or JustMock today, but at least I’m asking the question in an open and honest manner. I hope the rest of the
https://lostechies.com/derickbailey/2010/09/10/design-and-testability/
CC-MAIN-2018-22
refinedweb
1,266
61.87
Table Of Contents Behaviors¶ New in version 1.8.0. Behavior mixin classes¶ This module implements behaviors that can be mixed in with existing base widgets. The idea behind these classes is to encapsulate properties and events associated with certain types of widgets. Isolating these properties and events in a mixin class allows you to define your own implementation for standard kivy widgets that can act as drop-in replacements. This means you can re-style and re-define widgets as desired without breaking compatibility: as long as they implement the behaviors correctly, they can simply replace the standard widgets. Adding behaviors¶ Say you want to add Button capabilities to an Image, you could do: class IconButton(ButtonBehavior, Image): pass This would give you an Image with the events and properties inherited from ButtonBehavior. For example, the on_press and on_release events would be fired when appropriate: class IconButton(ButtonBehavior, Image): def on_press(self): print("on_press") Or in kv: IconButton: on_press: print('on_press') Naturally, you could also bind to any property changes the behavior class offers: def state_changed(*args): print('state changed') button = IconButton() button.bind(state=state_changed) Note The behavior class must always be _before_ the widget class. If you don’t specify the inheritance in this order, the behavior will not work because the behavior methods are overwritten by the class method listed first. Similarly, if you combine a behavior class with a class which requires the use of the methods also defined by the behavior class, the resulting class may not function properly. For example, when combining the ButtonBehavior with a Slider, both of which use the on_touch_up() method, the resulting class may not work properly. Changed in version 1.9.1: The individual behavior classes, previously in one big behaviors.py file, has been split into a single file for each class under the behaviors module. All the behaviors are still imported in the behaviors module so they are accessible as before (e.g. both from kivy.uix.behaviors import ButtonBehavior and from kivy.uix.behaviors.button import ButtonBehavior work). - class kivy.uix.behaviors. Bases: kivy.event.EventDispatcher Code navigation behavior. Modifies the navigation behavior in TextInput to work like an IDE instead of a word processor. Please see the code navigation behaviors moduledocumentation for more information. New in version 1.9.1. - class kivy.uix.behaviors Deselects a possibly selected node. It is called by the controller when it deselects a node and can also be called from the outside to deselect a node directly. The derived widget should overwrite this method and change the node to its unselected state when this is called - Parameters - node The node to be deselected. Warning This method must be called by the derived widget using super if it is overwritten. - get_index_of_node(node, selectable_nodes)[source]¶ (internal) Returns the index of the node within the selectable_nodes returned by get_selectable_nodes(). - get_selectable_nodes()[source]¶ (internal) Returns a list of the nodes that can be selected. It can be overwritten by the derived widget to return the correct list. This list is used to determine which nodes to select with group selection. E.g. the last element in the list will be selected when home is pressed, pagedown will move (or add to, if shift is held) the selection from the current position by negative page_countnodes starting from the position of the currently selected node in this list and so on. Still, nodes can be selected even if they are not in this list. Note It is safe to dynamically change this list including removing, adding, or re-arranging its elements. Nodes can be selected even if they are not on this list. And selected nodes removed from the list will remain selected until deselect_node()is called. Warning Layouts display their children in the reverse order. That is, the contents of childrenis displayed form right to left, bottom to top. Therefore, internally, the indices of the elements returned by this function are reversed to make it work by default for most layouts so that the final result is consistent e.g. home, although it will select the last element in this list visually, will select the first element when counting from top to bottom and left to right. If this behavior is not desired, a reversed list should be returned instead. Defaults to returning_node’ is the last node selected and is used to find the resulting node. For example, if the key is up, the returned node is one node up from the last node. It can be overwritten by the derived widget. - Parameters - key str, the string used to find the desired node. It can be any of the keyboard keys, as well as the mouse scrollup, scrolldown, scrollright, and scrollleft strings. If letters are typed in quick succession, the letters will be combined before it’s passed in as key and can be used to find nodes that have an associated string that starts with those letters. - last_node The last node that was selected. - last_node_idx The cached index of the last node selected in the Selects a node. It is called by the controller when it selects a node and can be called from the outside to select a node directly. The derived widget should overwrite this method and change the node state to selected when called. - Parameters - node The node to be selected. - Returns bool, True if the node was selected, False otherwise. Warning This method must be called by the derived widget using super if it is overwritten. -, get_selectable_nodes(). The parameters are such that it could be bound directly to the on_key_down event of a keyboard. Therefore, it is safe to be called repeatedly when the key is held down as is done by the keyboard. - Returns bool, True if the keypress was used, False otherwise. - (internal) Processes a touch on the node. This should be called by the derived widget when a node is touched and is to be used for selection. Depending on the keyboard keys pressed and the configuration, it could select or deslect this and other nodes in the selectable nodes list, succession . - class kivy.uix.behaviors.CoverBehavior(**kwargs)[source]¶ Bases: builtins.object The CoverBehavior mixin provides rendering a texture covering full widget size keeping aspect ratio of the original texture. New in version 1.10.0. - cover_pos¶ Position of the aspect ratio aware texture. Gets calculated in CoverBehavior.calculate_cover. cover_posis a ListPropertyand defaults to [0, 0]. - cover_size¶ Size of the aspect ratio aware texture. Gets calculated in CoverBehavior.calculate_cover. cover_sizeis a ListPropertyand defaults to [0, 0]. - reference_size¶ Reference size used for aspect ratio approximation calculation. reference_sizeis a ListPropertyand defaults to []. - class kivy.uix.behaviors.DragBehavior(**kwargs)[source]¶ Bases: builtins.object The DragBehavior mixin provides Drag behavior. When combined with a widget, dragging in the rectangle defined by drag_rectanglewill drag the widget. Please see the drag behaviors moduledocumentation for more information. New in version 1.8.0. - drag_distance¶ Distance to move before dragging the DragBehavior, in pixels. As soon as the distance has been traveled, the DragBehaviorwill start to drag, and no touch event will be dispatched to the children. It is advisable that you base this value on the dpi of your target device’s screen. drag_distanceis a NumericPropertyand defaults to the scroll_distance as defined in the user Config(20 pixels by default). - drag_rect_height¶ Height of the axis aligned bounding rectangle where dragging is allowed. drag_rect_heightis a NumericPropertyand defaults to 100. - drag_rect_width¶ Width of the axis aligned bounding rectangle where dragging is allowed. drag_rect_widthis a NumericPropertyand defaults to 100. - drag_rect_x¶ X position of the axis aligned bounding rectangle where dragging is allowed (in window coordinates). drag_rect_xis a NumericPropertyand defaults to 0. - drag_rect_y¶ Y position of the axis aligned bounding rectangle where dragging is allowed (in window coordinates). drag_rect_Yis a NumericPropertyand defaults to 0. - drag_rectangle¶ Position and size of the axis aligned bounding rectangle where dragging is allowed. drag_rectangleis a ReferenceListPropertyof ( drag_rect_x, drag_rect_y, drag_rect_width, drag_rect_height) properties. - drag_timeout¶ Timeout allowed to trigger the drag_distance, in milliseconds. If the user has not moved drag_distancewithin the timeout, dragging will be disabled, and the touch event will be dispatched to the children. drag_timeoutis a NumericPropertyand defaults to the scroll_timeout as defined in the user Config(55 milliseconds by default). - class kivy.uix.behaviors.EmacsBehavior(**kwargs)[source]¶ Bases: builtins.object A mixin that enables Emacs-style keyboard shortcuts for the TextInputwidget. Please see the Emacs behaviors moduledocumentation for more information. New in version 1.9.1. - key_bindings¶ String name which determines the type of key bindings to use with the TextInput. This allows Emacs key bindings to be enabled/disabled programmatically for widgets that inherit from EmacsBehavior. If the value is not 'emacs', Emacs bindings will be disabled. Use 'default'for switching to the default key bindings of TextInput. key_bindingsis a StringPropertyand defaults to 'emacs'. New in version 1.10.0. - class kivy.uix.behaviors. - class kivy.uix.behaviors.ToggleButtonBehavior(**kwargs)[source]¶ Bases: kivy.uix.behaviors.button.ButtonBehavior This mixin class provides togglebuttonbehavior. Please see the togglebutton behaviors moduledocumentation for more information. New in version 1.8.0. - allow_no_selection¶ This specifies whether the widgets in a group allow no selection i.e. everything to be deselected. New in version 1.9.0. allow_no_selectionis a BooleanPropertyand defaults to True - static get_widgets(groupname)[source]¶ Return a list of the widgets contained in a specific group. If the group doesn’t exist, an empty list will be returned. Note Always release the result of this method! Holding a reference to any of these widgets can prevent them from being garbage collected. If in doubt, do: l = ToggleButtonBehavior.get_widgets('mygroup') # do your job del l Warning It’s possible that some widgets that you have previously deleted are still in the list. The garbage collector might need to release other objects before flushing them. - group¶ Group of the button. If None, no group will be used (the button will be independent). If specified, groupmust be a hashable object, like a string. Only one button in a group can be in a ‘down’ state. groupis a ObjectPropertyand defaults to None. - class kivy.uix.behaviors.TouchRippleBehavior(**kwargs)[source]¶ Bases: builtins.object Touch ripple behavior. Supposed to be used as mixin on widget classes. Ripple behavior does not trigger automatically, concrete implementation needs to call ripple_show()respective ripple_fade()manually. Here we create a Label which renders the touch ripple animation on interaction: class RippleLabel(TouchRippleBehavior, Label): def __init__(self, **kwargs): super(RippleLabel, self).__init__(**kwargs) def on_touch_down(self, touch): collide_point = self.collide_point(touch.x, touch.y) if collide_point: touch.grab(self) self.ripple_show(touch) return True return False def on_touch_up(self, touch): if touch.grab_current is self: touch.ungrab(self) self.ripple_fade() return True return False - ripple_duration_in¶ Animation duration taken to show the overlay. ripple_duration_inis a NumericPropertyand defaults to 0.5. - ripple_duration_out¶ Animation duration taken to fade the overlay. ripple_duration_outis a NumericPropertyand defaults to 0.2. - ripple_fade_from_alpha¶ Alpha channel for ripple color the animation starts with. ripple_fade_from_alphais a NumericPropertyand defaults to 0.5. - ripple_fade_to_alpha¶ Alpha channel for ripple color the animation targets to. ripple_fade_to_alphais a NumericPropertyand defaults to 0.8. - ripple_func_in¶ Animation callback for showing the overlay. ripple_func_inis a StringPropertyand defaults to in_cubic. - ripple_func_out¶ Animation callback for hiding the overlay. ripple_func_outis a StringPropertyand defaults to out_quad. - ripple_rad_default¶ Default radius the animation starts from. ripple_rad_defaultis a NumericPropertyand defaults to 10. - ripple_scale¶ Max scale of the animation overlay calculated from max(width/height) of the decorated widget. ripple_scaleis a NumericPropertyand defaults to 2.0. - class kivy.uix.behaviors.TouchRippleButtonBehavior(**kwargs)[source]¶ Bases: kivy.uix.behaviors.touchripple.TouchRippleBehavior This mixin class provides a similar behavior to ButtonBehaviorbut provides touch ripple animation instead of button pressed/released as visual effect. -. always_releaseis a BooleanPropertyand defaults to False. - last_touch¶ Contains the last relevant touch received by the Button. This can be used in on_press or on_release in order to know which touch dispatched the event. last_touchis a ObjectPropertyand defaults to None. - Button Behavior - Code Navigation Behavior - Compound Selection Behavior - Cover Behavior - Drag Behavior - Emacs Behavior - Focus Behavior - Kivy Namespaces - ToggleButton Behavior - Touch Ripple
https://kivy.org/doc/master/api-kivy.uix.behaviors.html
CC-MAIN-2021-39
refinedweb
1,998
50.73
This is a walkthrough of an app I built using a React/Redux front-end that is pulling data from a Rails API. The frontend is deployed on Digital Ocean, Ubuntu 16.4, and the Rails API is on Heroku. Summary I created a report card comment engine for teachers. Here at the school I currently work at teachers need to write 300+ report card comments for students every semester. It is an immense workload and I thought, maybe a web app could help them out! I devised a pretty simple idea to navigate a database of pre-written comments and compile them together in a master comment that can then be copy-pasted into the educational software PowerShool. I wanted to make it sensical, user friendly and quick. So, a SPA design seemed best. Things I Learned This was built with react, and redux with a Rails api backend. I learned a TON via this project: React lifecycles and state, Redux middleWare, React routes, how to create a rails app of an API backend, wicked new ES6 syntax; it was awesome. Here are some highlights: React Routing I used react-router-dom: npm i --save react-router-dom Took a bit to get my mind around it, but in react-router, a Route is just way to render components based on the url-location. So, the page never refreshes (reminds me of turbolinks), it just renders different components depending on which link was clicked. It doesn’t actually “route” anywhere, pretty slick. So, I used my App.js as a master router, check it out: import {BrowserRouter as Router, Route } from 'react-router-dom' class App extends Component { render() { const isAuthenticated = this.props.session.auth.isAuthenticated; const currentUser = this.props.session.current_user; const userRoutes = ( <div className="App-main-container"> <Route path="/" component={ showHeader } /> <Route exact={true} <Route path="/" component={ showHeader } /> <Route exact={true} { isAuthenticated ? userRoutes : guestRoutes } </div> </Router> ); } } As you can see, I have guest routes, and user routes. Only the user Routes ( which are just component render-ers) get are available when isAuthenticated is true, via this code: { isAuthenticated ? userRoutes : guestRoutes } Now, if a Route’s has the attribute exact={true}, it will only render on it’s exact path, but if not will render as long as part of the path matches it’s path. So, used that feature to create a layout: <Route path="/" component={ showHeader } /> <Route path="/" component={ showFooter } /> The header and footer will always get rendered, because the root path is in every url. I built a bunch of functional components in this file that correspond to each route, like so: <Route exact={true} path="/" component={ showUserHome } /> const showUserHome = () => ( <main> <h1>Welcome, let's rock some comments!</h1> </main> ) So, now I can have any route render any component just by changing the Route path and component. React Component Lifecycles We learned about component lifecycles in the curriculum, and it really seems to be the heart of learning react. I can already tell mastering these component lifecycles if really the key here. Here is where I found some of them useful: Using lifecycle methods for Fetch requests I did a couple fetches from componentDidMount: componentDidMount(){ this.props.dispatch(fetchComments()); } sends an action to dispatch that does the fetch async, using Thunk, like so: export function fetchComments() { return function (dispatch) { dispatch({ type: 'LOADING_COMMENTS' }); return fetch("") .then(response => response.json()) .then(comments => dispatch({ type: 'FETCH_COMMENTS', payload: comments} ) ); }; } This is super useful, as the component is already rendered, the user gets to see stuff, and the fetch is happening quietly in the background. Great for a smooth UX. But, sometimes I wanted the fetch to get started earlier than that, so i used componentWillMount: componentWillMount(){ fetch(`{this.props.userId}/comments`) .then(response => response.json()) .then(response => { console.log("THIS IS THE RESPONSE:", response) this.setState({ comments: response }) }) } I wanted this data before the component actually mounted, so I made a synchonous fetch request before it renders. - what this section is about - why it matters - research or examples - takeaways New Awesome ES6 syntax Javascript is really getting awesome. I love the new syntax. Here are my favorites: Arrow functions These are indespensible in React. You can call a function without loosing your this binding, like so: handleDelete = event => { event.stopPropagation() this.props.deleteTab(event) } Since we aren’t naming a new function, and just immediately invoking it, it doesn’t create a new scope, therefore your ‘this’ stays the same. Spread Operator Again, indispensible in React. I used them a ton in redux when updating state, as we all know, can’t be mutated. Check it out: case "FETCH_COMMENTS": const comments = action.payload.map(comment => comment); let categories = comments.map(comment => comment.categories) categories = [].concat(...categories) let anotherArray = [...new Set(categories)] return {...state, loading: false, comments: [...state.comments, ...comments], categories: [...state.categories, ...anotherArray]}; spread operator all over the place! Here is a cool one: let anotherArray = [...new Set(categories)] This, another ES6 addition, uses the Set object, which let’s you store ‘unique’ values of any type. It will filter your arrays for only unique values, finally! const and let Now, I just never use var. const and let are blocked scoped, which can save you from tons of bugs. This basically means, they can’t bleed into parent scopes. like so: if (true) { let hello = "say Hello"; console.log(hello);//"say Hello" } console.log(hello) // hello is not defined vs var: if (true) { var hello = "say Hello"; console.log(hello); // "say Hello" } console.log(hello) // "say Hello" Let also hoists differently than var: hello = "say hello"; console.log(hello) let hello; // Error: hello is not defined vs var: hello = "say hello"; console.log(hello) var hello; // "say Hello" It also will not allow re-declaration of the same varible name, which can save alot of headaches if you forgot you already used that variable name before the difference between const and let is that const won’t allow any re-assigment. Conclusion This project was super fun, and really made me realize how far I have come. I can now wire up an entire stack with Rails, or with a React front end. Pretty cool. I can’t wait to get out there and build build build! Thank you for reading!
https://nictravis.com/react_redux_final_project
CC-MAIN-2020-16
refinedweb
1,044
56.05
def n = 100 * 1000 def at, bt bt = System.nanoTime() n.times { def sb = new StringBuilder() sb.append('foo') sb.append('bar') sb.append('baz') } at = System.nanoTime() println((at - bt) / n) bt = System.nanoTime() n.times { def sb = new StringBuffer() sb.append('foo') sb.append('bar') sb.append('baz') } at = System.nanoTime() println((at - bt) / n) But the result was against expectation. StringBuffer is more than twice as fast as StringBuilder (Groovy 1.8.6、JVM 1.7.0_04-ea Server VM). It must be worse than or equal to StringBuilder even if the cost of synchronization had been written off by optimization. It means this measurement completely failed. StringBuilder 1947.3 (2.76) StringBuffer 703.1 (1) The failure was more obvious by comparing between StringBuilders: StringBuilder #1 2030.68 (4.85) StringBuilder #2 418.47 (1) The changes of the execution times shows us what the problem was. Some optimizations had been finished in the first time measurement and the second time measurement had started from where the optimizations were finished. Thus, the first time has a disadvantage. And there is an outstanding value in the second time measurement. The value is because of garbage collection and garbage that was collected at this time include garbage which was generated during the first time measurement. Thus, conversely, the second time has a disadvantage at this point. It means right benchmarking is what making measurements to stand on the same start line and thus we need to have finish optimization and memory cleaning before measuring. Solving the problems by yourself is OK, but there is a benchmarking framework for Groovy, GBench. GBench 0.3.0 has got a feature to solve that tiresome problems and get correct results in place of you. The following code is a rewrite using GBench. You can get a simple report that shows only execution time by setting measureCpuTime to false for disabling measurement of CPU time: import gbench.* new BenchmarkBuilder().run(measureCpuTime:false) { 'StringBuilder' { def sb = new StringBuilder() sb.append('foo') sb.append('bar') sb.append('baz') sb.toString() } 'StringBuffer' { def sb = new StringBuffer() sb.append('foo') sb.append('bar') sb.append('baz') sb.toString() } }.prettyPrint() The result of the code was as follows. Why the difference was not so much is because my environment is Server VM and operations of locking were optimized. Jeroen Borgers' article Do Java 6 threading optimizations actually work? is a good reference for optimizations around locking: StringBuilder 244 (1) StringBuffer 265 (1.08) The result of the same code with disabling the optimizations (-XX:-DoEscapeAnalysis -XX:-EliminateLocks -XX:-UseBiasedLocking) was as follows: StringBuilder 242 (1) StringBuffer 310 (1.28)
http://nagaimasato.blogspot.jp/2012_03_01_archive.html
CC-MAIN-2018-22
refinedweb
442
59.19
Fluid Simulation #1 Members - Reputation: 136 Posted 19 February 2012 - 08:14 AM I've found a source-code and therefore seen what the code looks like inside the simulation, but I still don't understand how the lines are related to each function that describes the motion of a fluid in real world. Of course, I can look at how each variable is created in the simulation, but I don't know why the calculations are what they are, as they don't have any resemblance to the real world fluid functions. And since the particles' and grid's variables have so strange abbreviations, the code is just some mumbo jumbo for me. I've read sevelar articles and small e-books about fluid simulations, but none of them really describes how the theory is converted into a working code. Some of the papers that I've read are: An Informal Tutorial on Smoothed Particle Hydrodynamics for Interactive Simulation - Brandon Pelfrey Lagrangian Fluid Dynamics Using Smoothed Particle Hydrodynamics - Micky Kelager Particle-based Viscoelastic Fluid Simulation - Simon Clavet Right now I'm trying to write a 2D fluid simulation using Material Point Method (MPM algorithm), which is very similar to SPH (or that's what I've heard, at least). I have figured out that the MPM uses only two kinds of elements in the simulation: fluid particles and grid cells. The fluid particles are the visual part of the simulation and the grid is used for storing the data about density, pressure (and other physical quantities?) at any given point in space, and that data is gathered and calculated from the nearby fluid particles. The data from the grid cells is then used by the particles later on in the simulation step to calculate their new velocity and direction. That's basically all I know about it right now. The next step is to understand how each line of code is related to the functions that describe a fluid's behaviour in the real world. I want to know where are the code chunks that control the density, pressure, viscosity, elasticity, smoothing, gravity and stiffness of the fluid - or if some of those parts do even exist in the source-code I've found. I find it strange that first of all, very few people are willing to share the source-code of their fluid simulations, and secondly, nobody on the Internet is willing to write a comprehensive tutorial on this subject. I haven't found any source-code that has comments on the lines. If I ever learn the logic behind fluid simulations, I surely will do a video tutorial where I teach everything about how fluids behave and I will describe every line of code and tell why it's written the way it is. So, to put it shortly: I'm asking you to comment the code and describe what happens in each chunk of the code. Here's the 200-line code of the fluid simulation step that I'm studying: The full package can be found here: #2 Members - Reputation: 1867 Posted 19 February 2012 - 08:48 AM And here's some code: Cheers, Mike #3 Members - Reputation: 136 Posted 19 February 2012 - 09:00 AM #4 Members - Reputation: 136 Posted 19 February 2012 - 01:02 PM I find it extremely difficult to read the MPM code as I don't know where the abbreviations come from. I would be very thankful if someone with more skills on fluid simulations could look at the code and tell what 'particle.x', 'particle.u', 'particle.cx', 'particle.px[3]','particle.gx[3]' might be. Same with the nodes' variables: 'd', 'u', 'ax'... It seems like x is a pair for y and u is a pair for v, so once I know what properties these variables store, it would be wise to convert the pairs into 2D vectors. I saw that in the SPH code particles check their neighbors by looping through every other particle, which is quite a slow way. Line 178: // Now look at every other particle int particles_size = particles.size(); for(int j = i + 1; j < particles_size; ++j) { I'm not sure how exactly the neighbor-check is done in MPM, but I can't find a similar line in that. Can anyone find any similarities between the two codes? #5 Members - Reputation: 805 Posted 19 February 2012 - 06:04 PM - These are a nice introduction to fluids and how to simulate them. Very clearly written and easy to read! - Jos Stam's paper on video game smoke. Lots of code in the paper, but you'll have to move it over to some execution environment before it'll run. - Jos Stam, Ronald Fedkiw, and Henrik Wann Jensen's classic paper. After reading these three a time or few, you should be able to teach somebody waiting in the checkout line with you more than they ever wanted to know about fluids. At that point, you should be much more able to look at the code and make sense of it. If you've got a handle on all that already, then I apologize! However, I still suggest that you read these: they do a very good job of putting code with theory. Once you've done that, you can get into fancier techniques. That's where the fun is, so stick with it! - jouley #6 Members - Reputation: 136 Posted 19 February 2012 - 11:46 PM EDIT: So, there's a book and then there's a PDF called 'fluids_notes.pdf'. Is the PDF sufficient enough or do you recommend that I get the book? Did you learn the stuff from the book or the PDF? #7 Members - Reputation: 805 Posted 21 February 2012 - 01:58 PM So, there's a book and then there's a PDF called 'fluids_notes.pdf'. Is the PDF sufficient enough or do you recommend that I get the book? Did you learn the stuff from the book or the PDF? I found the PDF sufficient for my purposes. I haven't looked at the book, so I can't say how much useful material it adds. Best of luck! #8 Members - Reputation: 106 Posted 26 February 2012 - 07:19 PM To solve the Navier Stokes equations; which represent a continuum, one must find a way to discretize it with a mesh or a grid, in which case, it's no longer a continuum. A couple of Astrophysicists back in the 80's figured out a way to treat the fluid as a bunch of particles that behave in a fluid-like way. This is really nice because you don't have to mesh the thing. (Which is a pain.) The key things to know when dealing with SPH is that each property of the fluid is held in the particles: every particle has mass, viscosity, density (weird, I know), velocity, position and any other property which is represented in the equations. Each property is calculated based upon a weighting function. The weighting function for every particle is a function of the difference in the distance from particle p, and every other particle, over a smoothing length. g_p(x,y) ~= f(x',y',. I've annotated the java code where I recognize structures. This fellow didn't explain what they did very well at all. We learn a lesson from this: Comment your code, so that the next poor fool who reads it doesn't feel the need to wet themselves. // forked from zlaper's Liquid simulation //Is this demo using MPM algorithm? //What are the node's m, d, gx, gy, u, v, ax and ay variables? //What are particle's x, y, u, v, dudx, dudy, dvdx, dvdy, cx, cy, px[3], py[3], gx[3] and gy[3] variables? //What are the phases in the liquid simulation? What happens and in what order? What are some of the fluid dynamics functions that are used in each chunk? //Where are the code chunks that control the viscosity, smoothing, elasticity and gravity? If they don't exist, how to add them? // This looks like SPH. // m is mass, d is density, gx and gy... weighting function. // u - velocity in x, v - velocity in y // ax - acceleration in x, ay - acceleration in y // dudx --> du/dx, dudy --> du/dy // cx --> speed of sound in x dim, cy --> speed of sound in y dim // px --> pressure in x, py --> pressure in. package com.jasonpeinko.liquid; import java.util.ArrayList; import com.badlogic.gdx.Gdx; import com.badlogic.gdx.Input; import com.badlogic.gdx.Input.Buttons; import com.badlogic.gdx.graphics.GL10; import com.badlogic.gdx.graphics.Texture; import com.badlogic.gdx.graphics.g2d.SpriteBatch; import com.badlogic.gdx.graphics.glutils.ImmediateModeRenderer; import com.badlogic.gdx.math.Vector2; public class Liquid { boolean mousePressed = false; int mx,my = 0; int mxOld,myOld = 0; Vector2 mVec; private static final float TICK = 1/60.0f; private ArrayList<particle> particles = new ArrayList<particle>(); private int gsizeX = 160; //200 private int gsizeY = 150; //150 private float accum = 0.0f; private Node[][] grid = new Node[gsizeX][gsizeY]; private ArrayList<node> active = new ArrayList<node>(); private Material water = new Material(1.0f, 1.0f, 1.0f, 1.0f, 1.0f, 1.0f); //Only the first parameter is used - Material.m ImmediateModeRenderer renderer; Texture texture; Texture texture2; SpriteBatch batch; public Liquid() { mVec = new Vector2(0,0); init(); } public void init() { int i, j; for (i = 0; i < gsizeX; i++) { //The grid is created for (j = 0; j < gsizeY; j++) { this.grid[i][j] = new Node(); } } Particle p; for (i = 0; i < 100; i++) { //10,000 Particles are spawned for (j = 0; j < 100; j++) { p = new Particle(water, (i) + 4f, (j) + 4f, 0.0f, 0.0f); particles.add(p); } } //System.out.println("Particles: " + particles.size()); //Print the quantity of particles renderer = new ImmediateModeRenderer(); texture = new Texture(Gdx.files.internal("data/water.png")); texture2 = new Texture(Gdx.files.internal("data/node.png")); batch = new SpriteBatch(); } public void render() { //Input mxOld = mx; //The MousePos on the previous frame myOld = my; mx = Gdx.input.getX()/4; //The current MousePos my = Gdx.input.getY()/4; mVec.set(mx-mxOld, my-myOld); //System.out.println(mVec.x + "," + mVec.y); //Print Force vector if (Gdx.input.isButtonPressed(Buttons.LEFT)) { mousePressed = true; } else mousePressed = false; accum += Gdx.graphics.getDeltaTime(); while(accum >= TICK) { accum -= TICK; simulate(TICK); } batch.begin(); //We render stuff for (int i = 0 ; i<grid.length; i++)="" {="" we="" don't="" render="" just="" particles,="" but="" part="" of="" the="" grid="" as="" well="" for="" (=gsizeX){ continue; } if (h<0 || h>=gsizeY){ continue; } grid[g][149-h].affectedByMouse = true; } } // H-L Comment // This is comparing each particle with all of the other particles... actually this is inefficient. // It scales as O(N^2). He/She should have used a linked list. //H-L --> // Pressure is calculated. He/She got it from a model. for (Particle p : particles) { //What happens in this loop? p.cx = (int) (p.x - 0.5F); //We check on which grid-cell (node) the particle is standing on p.cy = (int) (p.y - 0.5F); float x = p.cx - p.x; p.px[0] = (0.5F*x*x + 1.5F*x + 1.125F); p.gx[0] = (x + 1.5F); x += 1.0F; p.px[1] = (-x*x + 0.75F); p.gx[1] = (-2.0F*x); x += 1.0F; p.px[2] = (0.5F*x*x - 1.5F*x + 1.125F); p.gx[2] = (x - 1.5F); float y = p.cy - p.y; p.py[0] = (0.5F*y*y + 1.5F*y + 1.125F); p.gy[0] = (y + 1.5F); y += 1.0F; p.py[1] = (-y*y + 0.75F); p.gy[1] = (-2.0F*y); y += 1.0F; p.py[2] = (0.5F*y*y - 1.5F*y + 1.125F); p.gy[2] = (y - 1.5F); // Wow... ok... speed of sound is dynamically calculated. for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { int cxi = p.cx + i; int cyj = p.cy + j; Node n = grid[cxi][cyj]; if (!n.active) { active.add(n); n.active = true; } float phi = p.px[i]*p.py[j]; n.m += phi*water.m; n.d += phi; float dx = p.gx[i]*p.py[j]; float dy = p.px[i]*p.gy[j]; n.gx += dx; n.gy += dy; } } } for (Particle p : particles) { //What happens in this loop? int cx = (int) p.x; int cy = (int) p.y; int cxi = cx + 1; //Area on a cell? int cyi = cy + 1; float p00 = grid[cx][cy].d; //The node's, on which the particle is standing, data is gathered float x00 = grid[cx][cy].gx; float y00 = grid[cx][cy].gy; float p01 = grid[cx][cyi].d; //Corner of a node? float x01 = grid[cx][cyi].gx; float y01 = grid[cx][cyi].gy; float p10 = grid[cxi][cy].d; //Corner of a node? float x10 = grid[cxi][cy].gx; float y10 = grid[cxi][cy].gy; float p11 = grid[cxi][cyi].d; //Corner of a node? float x11 = grid[cxi][cyi].gx; float y11 = grid[cxi][cyi].gy; float pdx = p10 - p00; float pdy = p01 - p00; float C20 = 3.0F*pdx - x10 - 2.0F*x00; float C02 = 3.0F*pdy - y01 - 2.0F*y00; float C30 = -2.0F*pdx + x10 + x00; float C03 = -2.0F*pdy + y01 + y00; float csum1 = p00 + y00 + C02 + C03; float csum2 = p00 + x00 + C20 + C30; float C21 = 3.0F*p11 - 2.0F*x01 - x11 - 3.0F*csum1 - C20; float C31 = -2.0F*p11 + x01 + x11 + 2.0F*csum1 - C30; float C12 = 3.0F*p11 - 2.0F*y10 - y11 - 3.0F*csum2 - C02; float C13 = -2.0F*p11 + y10 + y11 + 2.0F*csum2 - C03; float C11 = x01 - C13 - C12 - x00; float u = p.x - cx; float u2 = u*u; float u3 = u*u2; float v = p.y - cy; float v2 = v*v; float v3 = v*v2; float density = p00 + x00*u + y00*v + C20*u2 + C02*v2 + C30*u3 + C03*v3 + C21*u2*v + C31*u3*v + C12* u*v2 + C13*u*v3 + C11*u*v; //DENSITY MULTIPLIER: //Higher value = lower density density = density*1.0f; float pressure = density - 1.0F; if (pressure > 2.0F) { pressure = 2.0F; } float fx = 0.0F; float fy = 0.0F; if (p.x < 4.0F) fx += water.m*(4.0F - p.x); else if (p.x > gsizeX - 5) { fx += water.m*(gsizeX - 5 - p.x); } if (p.y < 4.0F) fy += water.m*(4.0F - p.y); else if (p.y > gsizeY - 5) { fy += water.m*(gsizeY - 5 - p.y); } for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Node n = grid[(p.cx + i)][(p.cy + j)]; float phi = p.px[i]*p.py[j]; float gx = p.gx[i]*p.py[j]; float gy = p.px[i]*p.gy[j]; // H-L Poorly labled Force: n.ax += (-(gx*pressure) + fx*phi)*1.4f; //Some interesting parameter of the fluid n.ay += (-(gy*pressure) + fy*phi)*1.4f; } } } // H-L: Nothing magical... finding acceleration. for (Node n : active) { //What happens in this loop? if (n.m > 0.0F) { n.ax /= n.m; n.ay /= n.m; n.ay += 0.03F; //Gravity? >0.06f is negative gravity? } } // H-L: Computes new velocity from acceleration. for (Particle p : particles) { //What happens in this loop? for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Node n = grid[(p.cx + i)][(p.cy + j)]; float phi = p.px[i]*p.py[j]; p.u += phi*n.ax; p.v += phi*n.ay; } } p.v += -0.06f; //-0.06f float mu = water.m*p.u; float mv = water.m*p.v; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Node n = grid[(p.cx + i)][(p.cy + j)]; float phi = p.px[i]*p.py[j]; //Viscosity? n.u += phi*mu*1.0f; //Try multipliers between 0.8 and 1.01 n.v += phi*mv*1.0f; } } } // Computes velocity by dividing momentum by mass. for (Node n : active) { //What happens in this loop? if (n.m > 0.0F) { n.u /= n.m; n.v /= n.m; } } // Positions are calculated then sent to rendering // pipeline. for (Particle p : particles) { //What happens in this loop? float gu = 0.0F; float gv = 0.0F; for (int i = 0; i < 3; i++) { for (int j = 0; j < 3; j++) { Node n = grid[(p.cx + i)][(p.cy + j)]; float phi = p.px[i]*p.py[j]; gu += phi*n.u; gv += phi*n.v; //Mouse interaction if (n.affectedByMouse && mousePressed) { gu +=(0.07f*mVec.x); gv -=(0.07f*mVec.y); } } } p.x += gu; p.y += gv; p.u += 1.0f*(gu - p.u); //Surface Tension? p.v += 1.0f*(gv - p.v); if (p.x < 1.0F) { p.x = (1.0F + (float) Math.random()*0.01F); p.u = 0.0F; } else if (p.x > gsizeX - 2) { p.x = (gsizeX - 2 - (float) Math.random()*0.01F); p.u = 0.0F; } if (p.y < 1.0F) { p.y = (1.0F + (float) Math.random()*0.01F); p.v = 0.0F; } else if (p.y > gsizeY - 2) { p.y = (gsizeY - 2 - (float) Math.random()*0.01F); p.v = 0.0F; } } //end of simulation } } You're brave for taking this on. That should be respected. This is one of the best books that I've ever read on this subject. Liu is one of clearest, most concise authors I've ever read.</grid.length;></node></node></particle></particle> #9 Members - Reputation: 158 Posted 27 February 2012 - 08:10 AM MPM should not be regarded as elf magic and in reality is simpler to implement and faster than SPH. #10 Members - Reputation: 106 Posted 27 February 2012 - 10:25 AM It's not elf magic; you're right, it's merely a useful way to handle PDEs.
http://www.gamedev.net/topic/620575-fluid-simulation/
CC-MAIN-2016-40
refinedweb
2,975
69.18
In short: this is the description of a sample that sends a CardSpace-obtained token to an AJAX service implemented with the new Orcas features. Few posts ago I published a tutorial about using CardSpace with Silver. While talking about it with Kushal Shah from the Workflow team, he suggested that it could be nice if we'd also demonstrate how to use CardSpace with the new RESTful capabilities of WCF: that sounded perfect for my "cardspace+<technology_of_choice>" series, hence I promply jumped on the task. The post below documents the results. Before diving into the code, let's take a moment for understanding what is this all about. The .NET framework 3.5, currently in beta, extends WCF with new capabilities explicitly designed to enable web development scenarios. There's really a lot to say on the subject, however for our context it is enough to say that you can now expose WCF services in ways that makes them extremely easy to consume from web pages. In practice, this mean that you can 1) invoke WCF services via HTTP verbs (POST and GET) and 2) handle messages in web-friendly formats, such as JSON. The macroscopic implication is that you don't need a proxy. Calling a WCF service becames a simple exercise in javascript: you gather the data from whatever UI element you need to, you create "by hand" a web request in AJAX style (with the object XMLHttpRequest or the activeXs Msxml2.XMLHTTP/Microsoft.XMLHTTP) and finally you use the results for updating selcted parts of your page. Those new features can have profound implications on the way in which you develop the backend for a website: you finally have at your disposal an extremely powerful service API, with its expressive model and all its hosting tuning features (think management and throttling), that you can easily use for exposing your asset for web consumption. We can finally stop twisting the arm of web servers for making them work in ways they were not designed for, and we will again able to think in term of content and services without mixing the two in a grey goo difficult to design/maintain. You will hear much more about this from this blog in the near future. In the meanwhile, I wholeheartedly suggest checking out SteveM and Justin blogs. That said: I would like to show you what you need for leveraging CardSpace in this scenario. This is not a "proper" WCF scenario: our client is a browser, hence we can't count on the WS-Security capabilities of wsHttpBinding and all the other cardspace-capable bindings. Since we are working with a web page, we may use the traditional web based cardspace authentication schema: we may impose that before landing on the AJAX enabled page we went through a succesful authentication step. But that would be too easy :-) For the sake of example in our case we assume that the service itself needs to receive a token from cardspace: that may happen when the service we are using needs a token that is different from the one we used for authenticating to the website (example: we authenticated with the web site using a personal card, but the business function offered by the AJAX service we area calling requires a specific managed card from another IP). The prerequisites for this sample are fairly straightforward. You need Orcas beta1, and it helps to have this cardspace sample and the new WCF samples (note: one time installation procedure needed) from the Orcas Beta1 release. Our project will contain a WCF service and a simple web page that will act as client. For making things more realistic we will host the service under IIS: in fact, my service was written taking inspiration from the PostAjaxService sample (thanks Eugene for the help with that). You will need to create an application or reuse an existing one. Note that, since we are playing with CardSpace on a website, we will need to enable HTTPS: if you installed this you can simply deploy the files we are creating in the same directory and you can skip to the next section ("The Project").Otherwise you can take the certificate from that sample (or any other suitable certificate), install it into the LocalMachine store and assign it as the SSL cert of your site via the IIS management console. Writing the service is very easy. You can start with a WCF service library, a class library, whatever you like the most. In the end we are going to write only three files: service.cs, service.svc and web.config. They are going to be very similar to what you find in the PostAjaxService sample, you may even start by modifying it. All our cardspace website samples make use of a helper class for processing the token: we will need to add to our project the file TokenProcessor.cs, from the website\CardSpace\App_Code folder in the cardspace website sample. Let's take a close look to the three files below, with our usual code highlighting style. There's really nothing in this code that gives away that we want to expose this service via AJAX. It looks like a good ol' WCF service. using System; using System.Web; using System.ServiceModel; using System.IdentityModel.Claims; using Microsoft.IdentityModel.TokenProcessor; namespace AService { // Define a service contract. [ServiceContract(Namespace = "")] public interface IMyService { [OperationContract] string EchoString(string s1); } public class MyService : IMyService public string EchoString(string s1) { try { if (s1 == null) return ("Token was null"); //decode from base64 byte[] decode = Convert.FromBase64String(s1); System.Text.Encoding enc = System.Text.Encoding.UTF8; string _tokenstring = enc.GetString(decode); //deserialize in a Token instance Token t = new Token(_tokenstring); //extract & return the givenname claim return (t.Claims[ClaimTypes.GivenName]); } catch (Exception ee) return (ee.ToString()); } } We have a using clause for accessing some cardspace related constructs such as ClaimTypes (System.IdentityModel.Claims) and another for accessing the Token helper class from TokenProcessor.cs (Microsoft.IdentityModel.TokenProcessor). The yellow code declares a minimal ServiceContract, with a single method that accepts a string in input and gives back another string in return. The entire service code is constituted by the implementation fo the method EchoString (all the usual disclaimers about sample code apply). The parameter s1 represents the token string, as we receive it from the client. The token string is actually an encrypted XML element: as such it contains some characters that cannot be posted "as is" via a POST. At first I tried to encodeURI the token string before sending it to the service: that took care of the illegal characters, but somehow I was unable to decrypt the token; apparently the encoding/decoding process was messing up with the encrypted portions of the string. Hence I decided to base64-encode the entire token string before sending it, and everything worked fine. The turquoise code takes care of DEcoding s1 from base64 back to its original form. The green code deserializes the token into an instance of the Token class; the operation decrypts the token and implicitly check the signature integrity, however in a real life application you would make a number of explicit checks on it (like if who signed is actually who you were expecting). The pink code simply extracts the value of the GivenName claim and sends it back. Can a file more uneventful? This is a typical .svc file: it is the mean through which WCF tells to ASP.NET to which class it is supposed to dispatch the calls addressed to this service. Again, no signs of our RESTful intentions <%@ServiceHost language="c"# Debug="true" Service="AService.MyService" %> the web.config is finally where we see some web action: <?xml version="1.0" encoding="utf-8"?> <configuration> <system.serviceModel> <services> <service name="AService.MyService"> <endpoint address="ajaxEndpoint" behaviorConfiguration="AjaxBehavior" binding="webHttpBinding" bindingConfiguration="AjaxBinding" contract="AService.IMyService" /> </service> </services> <bindings> <webHttpBinding> <binding name="AjaxBinding" messageEncoding="Json"> <readerQuotas maxBytesPerRead="999999" /> <security mode="Transport"> <transport clientCredentialType="None" /> </security> </binding> </webHttpBinding> </bindings> <behaviors> <endpointBehaviors> <behavior name="AjaxBehavior"> <enableWebScript /> </behavior> </endpointBehaviors> </behaviors> </system.serviceModel> </configuration> The Services/Service section is the usual one: we define a service called AService.MyService, with endpoint ajaxEndpoint. Well, almost the usual one: the binding type, webHttpBinding, is a new feature in Orcas and it is what enables us to expose the service in webby style. The boxed portion of the file contains the binding configuration: The teal code shows the parameter you need to add in the behavior configuration. That's it for the server! Compile the two *.CS files in a DLL (traditionally it's "service.dll") and deploy it in the \bin folder of your web directory; then copy service.svc and web.config in your web directory. The server is already up and waiting for you to call it! Let's write a quick & dirty client to see how it works The client is a simple static HTM page, that I'll simply call "Client.HTM". We already know that we will need to base64-encode the token string before sending it to the service: for the example I used the handy base64.js from Tyler Akins (thanks Garrett for the hint). Client.htm is pretty big, so I am going to split it in 2 parts: first I am going through the sheer HTML, then I'll go thorugh the javascript. <html xmlns=""> <head> <title>Sample WCF AJAX + CardSpace Client</title> <object type="application/x-informationcard" name="__CardspaceObject" id="Object1"> <param name="tokenType" value="urn:oasis:names:tc:SAML:1.0:assertion" /> <param name="requiredClaims" value="" /> <param name="optionalClaims" value="" /> </object> <script language="javascript" type="text/javascript" src="base64.js"></script> <style type="text/css"> ... </style> </head> <body> <h1> AJAX client page</h1> <h2> Which POST a CardSpace token to a WCF Ajax service</h2> <form name="sampleForm"> <label class="style1" onmousemove="GoGetIt();"> 1) Mouse over here for getting a token via cardspace </label> <label class="style1" onmousemove="makeCall();"> 2) Mouse over here for calling the web service </label> The GivenName claim is: <input type="text" name="result" /> <textarea cols="100" rows="20" id="xmltoken" name="xmlToken"></textarea> </form> </body> </html> In the <head> element we have the usual CardSpace object (shown inside a box). This is a very common configuration in the cases in which the identity selector is summoned via javascript: this is exactly our case, since we want to obtain a token from cardspace and manipulate it via client side code (as opposed to simply performing a POST of a form containing the cardspace Object element, in which case the processing happens immediatly on the server). Note that we won't make that much manipulation on the client, we will just re-encode the token string and send it to the server (more on that in the description of javascript part below). The name of the Object element, shown in grey, will be useful for referring to the element from the script code. The gold code shows the inclusion of the base64.js file. Below we have a form ("sampleForm") which contains our frugal UI. We have a label associated to the function GoGetIt (in yellow): hovering the mouse pointer over this label will call the GoGetIt function, which will take care of obtaining a token from cardspace. The token string will be stored in the textarea named xmlToken (in turquoise). We have another label, associated to the function makeCall (in green): hovering the mouse pointer over this other label will invoke our service by sending the token string obtained in the former step. The results of the call (including errors) will be shown in the input area named "result" (in pink). Let's not take a look to the function GoGetIt: function GoGetIt() var xmltkn = document.getElementById("__CardspaceObject"); var thetextarea = document.getElementById("xmltoken"); thetextarea.value = encode64(xmltkn.value); This is a slight variation of the classical GoGetIt. Assigning the cardspace element to a variable causes the identity selector to show up, and gives back a string containing the token obtained from the card chosen by the user. Once we obtain the token string we base64-encode it and we store it in our text area. Note that I have chosen this course of action for making the process as visible as possible: in a real application you would probably just send the token directly after having base64-encode it, there's normally no reason for showing it in the UI outside didactic purposes. The makeCall function is slightly more complex: function makeCall() //debugger;;}}} xmlHttp.onreadystatechange=function() { if(xmlHttp.readyState==4) { document.sampleForm.result.value=(eval(xmlHttp.responseText)); } } var url = "service.svc/ajaxEndpoint/EchoString"; try var body = '{"s1":"'; body = body + document.getElementById("xmltoken").value + '"}'; xmlHttp.open("POST",url,true); xmlHttp.setRequestHeader("Content-type","application/json"); xmlHttp.send(body); catch(e) alert(e); } All the part before the box is fairly typical AJAX-related code; we create xmlHttp according to the capabilities of the browser that is rendering us, and we make sure that we evaluate the results when they are actually available. Let's concentrate on the code inside the box. The first line creates the URL that refers to our service, following a very intuitive criteria: it starts with service.svc (in grey), the actual resource on the web server; then there is the endpoint name (in green), as defined by the web.config in the service project; finally we have the method name (in yellow), as defined by the servicecontract. The turquoise code shows how we build the body of our web request a' la JSON: we are just assigning the base64-encoded token string to the paramenter s1. NOTE: "s1" is exactly the param name we defined in service.cs, and we have to stick with that. Having the parameter name wrong is a very common mistake and it can drive you crazy for hours before you discover it. The gold code shows how we build the request and perform the call: we establish the HTTP verb we want to use (POST), we set the content type header to "application/json" and we send. That's it. Just copy Client.HTM and base64.js in the virtual directory, and you're almost good to go. Since your code will need to use this SSL certificate for decrypting the incoming token, you have to make sure that the Application Pool user has sufficient privileges over the private key of the certificate. Again, if you are reusing the environment created by the cardspace example you sould be already OK. You can easily do it by 1) finding the file name of the certificate, using the FindPrivateKey utility in the \bin folder of the aforementioned cardspace sample 2) setting the appropriate permissions on it. For example, if you are on Vista the default user will be NETWORKSERVICE: the command line for setting the permissions would look like cacls C:\ProgramData\Microsoft\Crypto\RSA\MachineKeys\[File Name found in step 1] /E /G NETWORKSERVICE:R NOTE: the documentation on MSDN and on other samples omits the "/E" flag, and the result is that you substitute the entire ACLs sometimes with unwanted consequences (SYSTEM and Administrators lose access rights to the file, to name one): the "/E" flag solves the problem. Thanks Rafael for finding it out :-) The moment of the truth :-) let's fire a browser and point it to Client.HTM: Very unimpressive, but exactly what we were expecting to see (including the reassuring green address bar). Let's hover on the first label: Usual CardSpace prompt. Let's click Send. The text area now contains the base64 encoding of our token string. Let's hover on the second label to send it to the web service: And, as expected, we get back the value of the givenname claim as proof that the service correctly received and processed the token. We have seen a basic example of how to expose a WCF service as an AJAX service with the new web capabilities introduced in Orcas. We have also seen how to secure the service via HTTPS and how to collect & send CardSpace tokens to it. If you have questions, do not hesitate to ask. Note for the lazy readers: like the last time, I will probably publish the solution files in some later post... but I won't do it immediately, just for encouraging you to play with it on your own :-) happy exploring! PingBack from Vittorio (once again) has something cool to show us on Vibro.NET . How can you not like a guy who color-codes Microsoft Surface: What WPF Can Do For You [Via: Ashish Shetty ] Where does a Binding find its data?... As promised, here there's a Visual Studio solution for the tutorial I published last week about how to
http://blogs.msdn.com/b/vbertocci/archive/2007/05/30/a-restful-cardspace-sending-tokens-using-the-new-wcf-ajax-services-in-orcas.aspx
CC-MAIN-2013-20
refinedweb
2,804
52.09
Getting notification on NavigationView go back? Can my app get Alerted when the user clicks backin a NavView? I haven't tested this, but perhaps you could check when the topmost view goes off screen (using the on_screenproperty or the wait_modalmethod). This would of course require some custom code when pushing each view onto the navigation view. There's probably a better way to do this with objc_utiland the native UIKit APIs, but I know almost nothing about UIKit. May be you can implement your own navigation view which may not be difficult. Here is an example implementation. The program simple_navigation_view.py builds a navigation view from a sequence of pyui files. The program custom_simple_navigation_view builds the same directly. Note that the second program does not have much additional code and you can customize the pop to your need. @omz Would it be possible for you to add a callback mechanism so that the root_view of a ui.NavigationView() receives a will_close()or a go_back()method call when the user clicks on back ( <in the upper left of the nav view)? ui.View.go_back() could operate like ui.View.layout() -- if the method is present then it gets called at the appropriate time. import ui about = '''Press "Tap me" and then back ("<" in the upper left) numerous times. Desired behavior: Colors remain constant (white, red, white, red) Actual behavior: Colors cycle forward (white, red, white, green)''' colors = 'white red green blue grey'.split() class ColorView(ui.View): def __init__(self): self.index = 0 self.name = 'white' self.add_subview(self.make_button()) frame = (0, -220, *(ui.get_screen_size())) self.add_subview(ui.Label(text=about, frame=frame, number_of_lines=0)) def button_tapped(self, sender): sender.navigation_view.push_view(self.make_button()) def go_back(self): # this NEVER gets called :-( self.index -= 1 def layout(self): self.subviews[0].frame = self.bounds def make_button(self): color = colors[self.index % len(colors)] self.index += 1 return ui.Button(title='Tap me', action=self.button_tapped, bg_color=color, name=color) def will_close(self): # this NEVER gets called :-( self.index -= 1 ui.NavigationView(ColorView()).present() Thanks @dgelessus Your view.on_screenchecking idea worked well at. This is a ui for walking the hierarchy of any json data. It would still be much easier if views displayed in ui.NavigationViews received a will_close()or go_back()callback when the user presses <.
https://forum.omz-software.com/topic/4138/getting-notification-on-navigationview-go-back
CC-MAIN-2021-04
refinedweb
385
53.88
Yesterday Microsoft released a security update for the .NET Framework that fixes the bug I reported last December. I'll write a more detailed analysis (including a proof-of-concept exploit) in a couple of weeks. I decided to take a break from integrating new OpenJDK packages and instead focus on running some test cases and work on stabilization. Contrary to the previous hybrid snapshots, this version should be fairly usable. Feedback is appreciated. Changes: Binaries available here: ikvmbin-hybrid-0.35.2741.zip. I'm getting tired of writing the disclaimers and warnings, but they still apply. The most important change in this snapshot is that there's now a virtual file system for the java.home directory. This has been a long time coming, but the proverbial straw was the fact that the OpenJDK timezone code reads files from the java.home/lib/zi/ directory (IMHO they really should be using resources for these things). Currently the virtual java.home directory is C:\.virtual-ikvm-home\ on Windows and /.virtual-ikvm-home/ on Unix, but this is subject to change (please let me know if you have thoughts on this). The only contents in there so far is the /lib/zi/ directory tree and only a few file operations are supported (notably the ones required by the timezone code), but expect that eventually all (read-only) file system operations will be supported and more virtual files to appear in there. C:\.virtual-ikvm-home\ /.virtual-ikvm-home/ Why a Virtual File System Instead Of a Real Java Home Directory? The main reason is that I want IKVM to behave like a .NET library as much as possible. That means it should be possible to install it into the GAC and support the versioning and side-by-side capabilities of .NET, that's very hard to do when you have to manage real directories. Binaries available here: ikvmbin-hybrid-0.35.2734.zip. Another hybrid snapshot update. Just a reminder again: These snapshots have not been tested extensively and are known to be broken (and are much more broken than the non-hybrid snapshots I used to release). They are only intended to be used for testing and getting a feel of how things are going. If you find a bug specific to this snapshot, please don't file a bug on SourceForge, simply send a message to the ikvm-developers list or to me directly. I'm not going to list everything that's known to be broken, but I will say that Eclipse 3.2 still runs, so at least some parts do work This build also includes several GNU Classpath fixes that I haven't yet checked in, so if you're trying to do a hybrid build from cvs you'll end up with something even more broken than this build. [Update: I checked them in.] Binaries available here: ikvmbin-hybrid-0.35.2728.zip. Wow. Today it's five years ago that I started blogging about IKVM. I'd write more, but I'm having too much fun working on integrating the OpenJDK libraries. In Merging the First OpenJDK Code and Another x64 CLR Bug I briefly mentioned the three different approaches that are available for integrating the OpenJDK classes with IKVM: This triggered a couple of questions in the comments. Morten asked: about your work of [i]ntegrating the whole of OpenJDK and [y]our 3 options. Could you provide more details? From what you write, it sounds like using aspectj to inject annotations could be useful. Codegeneration might also be useful? Yes, that's essentially what option 2 is. The map.xml infrastructure allows me to add methods and fields to existing classes, or allows me to replace method bodies. Albert Strasheim asked: It's too bad that the Sun and Classpath code aren't compatible down to the native methods called by the pure Java code. As Andrew pointed out, it would not have been possible or practical to reverse engineer the Sun native interface. Besides that, the Sun and GNU Classpath libraries have very different goals, so it actually makes a lot of sense for the interfaces to differ. I figured that you'd go the "native methods in C#" route, so I'd be interested to know why you think that the "IKVM specific modifications" route is cleaner and more efficient (efficient in terms of performance or time to implement?). It would seem that implementing the native methods in C# would be the best solution, but that's not always the case. Hopefully that will become clear below. Let's look at some examples and the downsides and cost associated with each of the three options: 1. Use existing native interface In terms of long term development cost, this is easily the best option. Once you understand the ikvmc native method mapping that is used by the class library, it is very easy to find to corresponding native method. Sun is not very likely to change the native method semantics without also modifying the method name or signature. When a new native method is added, the build process will fail due to the fact that the new native method isn't implemented (and hence generates an unverifiable JNI method stub). In terms of runtime performance, this method can be very efficient, but only if the method parameters contains all the required data to work on, or if the data can be easily obtained in another efficient way. This is often not the case, because many of the Sun native methods use JNI reflection to access private fields in the object. Here are two real world examples, one where the native methods works really well and another one where it's not as efficient as I'd like:"); } }} Clearly this is very efficient (and it makes you wonder why it's a native method at all). Here's one that's less efficient: namespace IKVM.NativeCode.java.lang{ public sealed class Class { public static bool isInterface(object thisClass) { return TypeWrapper.FromClass(thisClass).IsInterface; } }} The thisClass parameter is a reference to the java.lang.Class object, but the VM wants to use its internal representation of a class (TypeWrapper), so here I need to use TypeWrapper.FromClass() to get the corresponding TypeWrapper object. Currently that's implemented by using reflection to access a private field in java.lang.Class (that was added through map.xml). thisClass java.lang.Class TypeWrapper TypeWrapper.FromClass() To contrast, here's the equivalent method for use with the GNU Classpath library: namespace IKVM.NativeCode.java.lang{ public sealed class VMClass { public static bool IsInterface(object wrapper) { return ((TypeWrapper)wrapper).IsInterface; } }} Here only a downcast is required, because Class.isInterface() calls VMClass.isInterface(), which reads the vmdata field from Class and passes that to the native IsInterface method. Class.isInterface() VMClass.isInterface() vmdata Class IsInterface 2. Use map.xml tricks This is very powerful, but also much more expensive because it is much less obvious what's going on. In the case of a native method that is implemented, if you can't find it in the C# code, you'll probably eventually find it in map.xml, but when replacing an existing method it's very easy to miss the fact that the method is replaced. I've used method replacement in java.lang.ClassLoader to make bootstrap resource loading work. ClassLoader has two private methods getBootstrapResource() and getBootstrapResources() that are used to load resources from the boot class path. These methods are implemented by parsing the sun.boot.class.path system property and then using internal classes to load from these jars or directories. Obviously that won't do for IKVM, because the boot classes and resources are contained in the core library .NET assembly (currently named IKVM.Hybrid.GNU.Classpath.OpenJDK.dll). So I've had to replace these two methods: java.lang.ClassLoader ClassLoader getBootstrapResource() getBootstrapResources() > These method bodies simply call the real implementations in LangHelper, because it's obviously easier to implement them in Java than in CIL. LangHelper 3. Change the code (i.e. fork a specific source file) In some cases, the changes required are so substantial that the map.xml trickery doesn't work or isn't practical. For an example of that we need to look at how reflection is implemented in OpenJDK. Here's a fragment of java.lang.reflect.Method (not the actual code, but it gets the idea across): java.lang.reflect.Method); }} So the actual method invocation is delegated to an object that implements the MethodAccessor interface. By default Sun's ReflectionFactory returns an object that counts the number of invocations and delegates to another MethodAccessor object that uses JNI to use the VM reflection infrastructure, if the invocation counter crosses a certain value the inner object is replaced by an instance of a dynamically generated class that contains custom generated byte codes to efficiently call the target method (and this generated bytecode is not verifiable, so it won't work as-is on IKVM). In this case I've decided to fork ReflectionFactory and implement my own version that simply returns MethodAccessor instances that reuse the IKVM reflection infrastructure. MethodAccessor ReflectionFactory The cost of forking a source file should be obvious. When improvements are made to the original, you don't automatically inherit these. In this particular case ReflectionFactory is a fairly small and simple class (all of the complexity is in the classes it calls), so the risk seems low. Structural Issues Besides the issues already pointed out, there are also things of a more structural nature. A good example can again be found in java.lang.reflect.Method. Here's its constructor: Method(Class declaringClass, String name, Class[] parameterTypes, Class returnType, Class[] checkedExceptions, int modifiers, int slot, String signature, byte[] annotations, byte[] parameterAnnotations, byte[] annotationDefault){ // ...} Method(Class declaringClass, String name, Class[] parameterTypes, Class returnType, Class[] checkedExceptions, int modifiers, int slot, String signature, byte[] annotations, byte[] parameterAnnotations, byte[] annotationDefault){ // ...} The constructor expects the generics signature and annotations to be passed in. This poses a dillema. On IKVM looking up the custom attributes that contain this data is relatively expensive and in many cases a method object may be constructed while the code is not interested in generics information or annotations at all, so it might be more desireable to lazily get this data. Another problem is that the annotations are passed in as byte arrays that contain the annotation data as it exists in the class file. Code compiled with ikvmc obviously doesn't have a class file. Despite these two issues, I've chosen to not fork Method. At the moment I think that the performance cost of eagerly getting the generics signature and the annotations is an acceptable trade-off for not having to fork Method. Currently, the way annotations are handled is pretty horrible, because I've left the existing annotation mechanisms in place and reuse the stub class generator code to recreate the annotation byte arrays (and the corresponding constant pool entries) on the fly to pass them into the Method constructor. I've got some ideas to change annotation storage in ikvmc compiled code to use a mechanism that's more compatible with this approach and that may ultimately turn out to be more space efficient as well. Method Compatibility One aspect I haven't talked about yet is compatibility. For example, there's code out there that directly uses ReflectionFactory. This is evil, but it's also reality. So I try to weigh the compability impact as well when I'm trying to find the right approach. The.
http://weblog.ikvm.net/default.aspx?date=2007-07-11
CC-MAIN-2019-26
refinedweb
1,942
54.63
This site uses strictly necessary cookies. More Information Hi ! Ik have a drinks class with 2 variables in it : string drinkName, float drinkPrice; Each value is filled in by InputFields and then gets saved in a Drinks list. All working so no problem there. However I wish to add drinks to this list without losing the progress each time I shut down my application. I'm aware of the playerprefs method to save data but are there other ways to do so ? Perhaps better ways I could look into? Thanks in advance Answer by Halichoerus · Oct 18, 2015 at 09:13 AM You can use data serialization and write/read your data to a file, I've recently added save/load for game options and progress and it was pretty easy. I would recommend this tutorial by unity, it explains the basics and gives you a working example you can recreate with little knowledge on the subject. Just skip ahead a bit to get past the player prefabs part. Great thing about doing it this way is you just create your own data class which can contain any serializable data type, which is quite a few. Here's an edited snippet from my project, it's basically just the example from the tutorial I linked. using UnityEngine; using System.Collections; using System; using System.Runtime.Serialization.Formatters.Binary; using System.IO; public class DataSaver : MonoBehaviour { public void SaveData() { MyData data = new Data(); // add relevent data to my new data object e.g data.exampleInt = 5; BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Create(Application.persistentDataPath + "/SomeData"); bf.Serialize(file, data); file.Close(); } public void LoadData() { if (File.Exists(Application.persistentDataPath + "/SomeData")) { BinaryFormatter bf = new BinaryFormatter(); FileStream file = File.Open(Application.persistentDataPath + "/PlayerOptions", FileMode.Open); OptionsData data = (OptionsData)bf.Deserialize(file); file.Close(); // Do stuff with loaded data eg var someNewInt = data.exampleInt; } } } [Serializable] class MyData { // Any serializable data types you want to save/load e.g public int example. Scriptable Object's Data Gets Lost After Re-opening Unity!!! 1 Answer problem updating info to data base 0 Answers Data Management Issue - How to manage retrieved data from mysql? 0 Answers How to upgrade from free to paid version and maintain established player prefrence data? 0 Answers How often to write in database 3 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/1083706/saving-data-5.html
CC-MAIN-2021-49
refinedweb
388
51.14
TLS Session Cache Q: I'm using NSURLConnection to access two HTTPS URLs on the same server. I want to use a unique client identity for each connection. When I access the first URL I get an authentication challenge that allows me to supply the correct client identity, but when I then access the second URL I don't get any authentication challenges. How can I get an authentication challenge for this second connection? A: When you access a URL via HTTPS, you're actually using HTTP over TLS (Transport Layer Security, the evolution of SSL, the Secure Sockets Layer). You don't get a second challenge because the second connection reuses the TLS session established by the first. To understand this problem, you need to understand something about TLS itself, and how it is implemented on OS X and iOS. Opening a TLS session is computationally expensive (because it involves working with large asymmetric keys), so TLS has a mechanism to avoid doing this work for each connection. A TLS connection can either establish a new session or it can attempt to resume an existing session, where resuming an existing session is much cheaper than starting a new one. A TLS client can therefore boost performance by maintaining a cache of existing sessions and reusing them when it's appropriate. The core TLS code on both OS X and iOS, Secure Transport, maintains such a cache. This TLS session cache is implemented independently in each process. In most circumstances the TLS session cache works transparently to speed up TLS connections, but in some cases it can cause problems. In this case, your second connection has reused the TLS session of the first connection, and thus you don't have an opportunity to supply a new client identity for the second connection. Because caching can occur at various levels within the NSURLConnection stack, before trying to work around a TLS session cache problem it's a good idea to confirm that this is actually the root cause. You can do this by exploiting the fact that TLS session cache entries persist for about 10 minutes. Thus, if the problem still occurs when the second connection follows the first connection by 9 minutes, but goes away if the delay is 11 minutes, chances are that the TLS session cache is to blame. Inside the NSURLConnection Framework, there's no direct way to flush the TLS session cache (other than to terminate the process itself), nor is there a way to tell NSURLConnection not to use it (r. 8957312) . The only reasonable workaround is to change your connection in such a way that the second connection doesn't hit (in the sense of a "cache hit") the cache entry created by the first connection. To do this you need to understand the TLS session cache key format used by NSURLConnection or, more accurately, the CFSocketStream that underlies NSURLConnection. If you cannot switch to NSURLSession, please see below. In the absence of a proxy, the TLS session cache key contains the destination IP address, the destination port, and the destination DNS name, for example, {131.39.46.209:47873}devforums.apple.com. Consequently, altering the IP address, the port, or the DNS name will cause a TLS session cache miss, and allow your second connection to receive the TLS authentication challenges. While it's unlikely that you'll be able to alter the IP address component of the TLS session cache key, the port and DNS name components are potential workaround candidates. For example: If your two connections represent very different operations, you might consider configuring your server to listen on two different ports. For example, if the first connection is for enrollment and the second connection is for data transfer, you can have two instances of your server, one for enrollment and one for data transfer, each listening on their own port. Most HTTP servers are easy to configure in this way. If you have control over the DNS namespace of the server, you could configure that namespace to ensure that each connection goes to a unique DNS address. Let's say your server is currently at myapp.example.com. You could configure your DNS server to map all names within that domain ( *.myapp.example.com) to your server. Your clients could then have each connection target a unique name within that namespace, thus avoiding any chance the connection will hit the TLS session cache. For example, your client's first connection might target s464287123.myapp.example.com, its second connection s338233934.myapp.example.com, and so on, all of which are redirected by your DNS server to myapp.example.com. Both of the previous suggestions require you to reconfigure the server in some way. If you have no control over the server, your options are rather limited. One sneaky workaround is to append a dot (".") to the DNS name you're connecting to. If you're not familiar with the details of DNS, a name ending in dot is considered to be a fully qualified domain name (FQDN), whereas names not ending in dot (partially qualified domain names, PQDN) may be resolved by appending some default domain. For example, devforums.apple.com.(note the trailing dot) is an FQDN for DevForums but, when you're at Apple and the default DNS domain is apple.com., you can refer to it via the PQDN of devforums. It turns out that the host name from the URL you give NSURLConnection passes down, unmodified, through many layers of CFNetwork until it eventually forms a component of the Secure Transport TLS session cache key. Thus, if you have a program that first connected to devforums.apple.com.(with a trailing dot) and then connected to devforums.apple.com(without a trailing dot), each connection will get TLS authentication challenges. The obvious drawback of this approach is that it doesn't scale; you can't just keep adding dots! Document Revision History Copyright © 2015 Apple Inc. All Rights Reserved. Terms of Use | Privacy Policy | Updated: 2015-08-19
https://developer.apple.com/library/archive/qa/qa1727/_index.html
CC-MAIN-2022-21
refinedweb
1,012
60.75
Subject: Re: [boost] Seeking advice regarding inline namespaces From: Gavin Lambert (gavinl_at_[hidden]) Date: 2015-11-12 21:43:09 On 13/11/2015 14:26, Louis Dionne wrote: > Ok, thanks a lot for the information. Keeping this in mind, I'll consider > whether the added complexity of versionning Hana's namespace seems to be > worth it (given the nature of Hana as a metaprogramming library). For pure compile-time constructs, probably not. Most of the benefit is in detecting incompatibilities within runtime types. 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/2015/11/226525.php
CC-MAIN-2022-05
refinedweb
106
60.21
Work at SourceForge, help us to make it a better place! We have an immediate need for a Support Technician in our San Francisco or Denver office. Update of /cvsroot/plplot/plplot/bindings/tk In directory sc8-pr-cvs1:/tmp/cvs-serv27298/bindings/tk Modified Files: Makefile.am Log Message: Removed some if/else/endif with_double constructs. Replaced using $(LIB_TAG). This makes code more maintainable and robust, besides a total reduction of 40 lines in the size of the Makefile.am's. The initial plan was to use $(LIB_TAG) wherever it was possible, but Automake does not accept it as part of its variables names :-( View entire thread
http://sourceforge.net/p/plplot/mailman/message/10287062/
CC-MAIN-2014-35
refinedweb
108
58.18
OS2 World Community Forum OS/2, eCS & ArcaOS - Technical => Programming => Topic started by: Ian Manners on January 07, 2013, 04:56:22 pm Title: Paul Smedley's Programming Tips n Tricks Post by: Ian Manners on January 07, 2013, 04:56:22 pm This will be a collection of Tips, hints, and programming tricks gathered from Paul Smedley's posts. As these are Paul's writings, I'm not liable for any damage to your system :o As time permits and also depending on what others may post, there will be other Sticky threads similar to this one with Tips etc from other contributors. For those that are not aware you can get Paul's GCC build environment on DVD - () Paul's GCC build environment is an ideal starting point as it gives you a known good baseline to start from. Yes, it will cost you a small amount of money but you will be supporting someone who has put a lot of effort into both supporting our community, and porting applications that you are probably using somewhere. ========= Paul's Build Environment build txt file from his DVD START ========= Instructions for setup: - Installation is only supported to drive u: - if you want to install it elsewhere, feel free to hack u:\*.cmd and various other scripts that may reference u: drive - unzip buildenv_xxxxxxxx.zip to u:\ - run u:\folder.cmd to create a desktop folder with icons for the various versions of the GCC compiler that are included (3.3.5, 3.4.6, 4.3.5, 4.4.5, 4.5.2, 4.5.3) Building your first command line application: - Launch a GCC command prompt (4.x suggested) - change directory to u:\dev\wget-1.12 - type 'ash ./configure --prefix=/wget' at the command prompt - once configure completes, run 'make' - there will be an error building the doc directory - but we don't care about that :) - once make completes, run 'make install' - wget executables will be found in /wget/bin ========= Paul's Build Environment build txt file from his DVD END ========= Porting software to eCS. In the absolute best case scenario, the process is: 1) extract source 2) run configure using something like: ash ./configure --prefix=/name_of_app --disable-shared --enable-static 2>&1 | tee configure.log --prefix specifies where we want to install the app - default will be /usr or /usr/local --disable-shared tells it not to build shared libraries (in most cases the app won't know how to build shared libraries (ie DLL's) --enable-static forces static libraries to be built 2>&1 | tee configure.log puts the output from configure into a file called configure.log for debugging purposes 3) assuming configure completes: make 2>&1 | tee build.log runs make, with output of the command pipes into build.log 4) If no, errors. make install output will be put into the directory specified as prefix in 2) I'd suggest starting with a simple command line app like wget This serves two purposes, a) ensures your setup works, and b) ensures that nothing has changed. The latest wget v1.14 source will require a minor change to be made in lib/spawn.in.h diff -ur wget-1.14-o/lib/spawn.in.h wget-1.14/lib/spawn.in.h ========= Diff file Start ========= --- wget-1.14-o/lib/spawn.in.h 2012-12-28 19:05:04.000000000 +1030 +++ wget-1.14/lib/spawn.in.h 2012-12-29 15:36:20.000000000 +1030 @@ -32,7 +32,7 @@ /* Get definitions of 'struct sched_param' and 'sigset_t'. But avoid namespace pollution on glibc systems. */ -#if !(defined __GLIBC__ && !defined __UCLIBC__) +#if !(defined __GLIBC__ && !defined __UCLIBC__) && !defined __KLIBC__ # include <sched.h> # include <signal.h> #endif ========= Diff file end ========= SMF 2.0.15 | SMF © 2017 , Simple Machines
http://www.os2world.com/forum/index.php?action=printpage;topic=30.0
CC-MAIN-2018-05
refinedweb
631
64.1
Python caching with redis Contributor - 20 December 2016 - 12min Contributor - 20 December 2016 - 12min Install python package pip install redis Following code shows the basic operations such as saving, fetching & deleting objects. import redis r = redis.StrictRedis(host='localhost', port=6379, db=0) r.set('foo', 'bar') r.get('foo') >>>'bar' r.delete('foo') So far, so good but this is only the beginning. Redis offers multiple functionalities in addition to what python-memcached offers. Let’s take a look at the Redis data-structures and how helpful they are. We can add elements to the Redis list data-structure by appending on left side or the right side. While fetching the list we provide splicing indices just like in python (though both the indices are required in redis). r.rpush('rlist', 1, 2, 3, 4, 5, 6, 7, 8, 9) r.lrange('rlist', 0, -1) >>>['1', '2', '3', '4', '5', '6', '7', '8', '9'] Using Redis lists means while modifying the cache after some operation, we can simply append to or delete from this list instead of the ‘delete old object & create new object with modified data’ approach with python-memcached. Nifty isn’t it? We can restrict the length of this list with LTRIM command. So when used in conjuction with LPUSH command we can add elements to the list and always keep the latest N elements we want. r.lpush('rlist', -1) r.ltrim('rlist', 0, 1) r.lrange('rlist', 0, -1) >>>['-1', '1'] Here we see only the latest two integers are maintained in the cache object and rest are removed. Redis hashes are field-value pairs. Excellent for saving python dictionaries and modifying them in cache without having to recreate object in cache. r.hmset('user', {'username': 'foo', 'birth_year': 1977}) # Fetch all field-value pairs in user key. r.hgetall('user') # Add additional field-value pairs. r.hmset('user', {'user_id': 10}) # Increment values. r.hincrby('user', 'user_id', 1) # Fetch a single key. r.hget('user', 'user_id') >>>11 Just like in python redis Sets are useful for storing unique values, though if maintaining order is required then you’ll have to use Ordered Sets. There are many other redis data-structures available. You can read more about them here. Redis also offers persistent storage. Be careful while using it though, since Redis only saves data after at least five minutes and 100 writes against the data set by default. So you might lose lose the latest minutes of data. Redis also supports values up to 512 MB in size as opposed to 1 MB per key limitation of memcached. Not only is redis the better option for places you might use python-memcached, it enables whole new types of use cases and usage patterns. Hope this little intro to Redis was useful. For any comments/suggestions/questions you can find me at – Skype – vishal.palasgaonkar_tal
https://www.talentica.com/blogs/python-caching-with-redis/
CC-MAIN-2020-40
refinedweb
479
67.04
Matplotlib vs. ggplot: How to Use Both in R Shiny Apps Want to share your content on python-bloggers? click here. Data Science has (unnecessarily) divided the world into two halves – R users and Python users. Irrelevant of the group you belong to, there’s one thing you have to admit – each language individually has libraries far superior to anything available in the alternative. For example, R Shiny is much easier for beginners than anything Python offers. But what about basic data visualization? That’s where this Matplotlib vs. ggplot article comes in. Today we’ll see how R and Python compare in basic data visualization. We’ll compare their standard plotting libraries – Matplotlib and ggplot to see which one is easier to use and which looks better at the end. We’ll also show you how to include Matplotlib charts in R Shiny dashboards, as that’s been a common pain point for Python users. What’s even better, the chart will react to user input. Want to use R and Python together? Here are 2 packages you get you started. Table of contents: - Matplotlib vs. ggplot – Which is Better for Basic Plots? - Matplotlib vs. ggplot – Which is easier to customize? - How to Include ggplot Charts in R Shiny - How to Use Matplotlib Charts in R Shiny - Summary of Matplotlib vs. ggplot Matplotlib vs. ggplot – Which is Better for Basic Plots? There’s no denying that both Matplotlib and ggplot don’t look the best by default. There’s a lot you can change, of course, but we’ll get to that later. The aim of this section is to compare Matplotlib and ggplot in the realm of unstyled visualizations. To keep things simple, we’ll only make a scatter plot of the well-known mtcars dataset, in which X-axis shows miles per gallon and Y-axis shows the corresponding horsepower. Are you new to scatter plots? Here’s our complete guide to get you started. There’s not a lot you have to do to produce this visualization in R ggplot: library(ggplot2) ggplot(data = mtcars, aes(x = mpg, y = hp)) + geom_point() Image 1 – Basic ggplot scatter plot It’s a bit dull by default, but is Matplotlib better? The mtcars dataset isn’t included in Python, so we have to download and parse the dataset from GitHub. After doing so, a simple call to ax.scatter() puts both variables on their respective axes: import pandas as pd import matplotlib.pyplot as plt mtcars = pd.read_csv("", index_col=[0]) fig, ax = plt.subplots(figsize=(13, 8)) ax.scatter(x=mtcars["mpg"], y=mtcars["hp"]) Image 2 – Basic matplotlib scatter plot It would be unfair to call ggplot superior to Matplotlib, for the pure fact that the dataset comes included with R. Python requires an extra step. From the visual point of view, things are highly subjective. Matplotlib figures have a lower resolution by default, so the whole thing looks blurry. Other than that, declaring a winner is near impossible. Do you prefer Matplotlib or ggplot2 default stylings? Let us know in the comment section below. Let’s add some styles to see which one is easier to customize. Matplotlib vs. ggplot – Which is easier to customize? To keep things simple, we’ll modify only a couple of things: - Change the point sizing by the qsecvariable - Change the point color by the cylvariable - Add a custom color palette for three distinct color factors - Change the theme - Remove the legend - Add title In R ggplot, that boils down to adding a couple of lines of code: ggplot(data = mtcars, aes(x = mpg, y = hp)) + geom_point(aes(size = qsec, color = factor(cyl))) + scale_color_manual(values = c("#3C6E71", "#70AE6E", "#BEEE62")) + theme_classic() + theme(legend.position = "none") + labs(title = "Miles per Gallon vs. Horse Power") Image 3 – Customized ggplot scatter plot The chart now actually looks usable, both for reporting and dashboarding purposes. But how difficult it is to produce the same chart in Python? Let’s take a look. For starters, we’ll increase the DPI to get rid of the blurriness, and also remove the top and right lines around the figure. Changing point size and color is a bit trickier to do in Matplotlib, but it’s just a matter of experience and preference. Also, Matplotlib doesn’t place labels on axes by default – consider this as a pro or a con. We’ll add them manually: plt.rcParams["figure.dpi"] = 300 plt.rcParams["axes.spines.top"] = False plt.rcParams["axes.spines.right"] = False fig, ax = plt.subplots(figsize=(13, 8)) ax.scatter( x=mtcars["mpg"], y=mtcars["hp"], s=[s**1.8 for s in mtcars["qsec"].to_numpy()], c=["#3C6E71" if cyl == 4 else "#70AE6E" if cyl == 6 else "#BEEE62" for cyl in mtcars["cyl"].to_numpy()] ) ax.set_title("Miles per Gallon vs. Horse Power", size=18, loc="left") ax.set_xlabel("mpg", size=14) ax.set_ylabel("hp", size=14) Image 4 – Customized matplotlib scatter plot The figures look almost identical, so what’s the verdict? Is it better to use Python’s Matplotlib or R’s ggplot2? Objectively speaking, Python’s Matplotlib requires more code to do the same thing when compared to R’s ggplot2. Further, Python’s code is harder to read, due to bracket notation for variable access and inline conditional statements. So, does ggplot2 take the win here? Well, no. If you’re a Python user it will take you less time to create a chart in Matplotlib than it would to learn a whole new language/library. The same goes the other way. Up next, we’ll see how easy it is to include this chart in an interactive dashboard. How to Include ggplot Charts in R Shiny Shiny is an R package for creating dashboards around your data. It’s built for R programming language, and hence integrates nicely with most of the other R packages – ggplot2 included. We’ll now create a simple R Shiny dashboard that allows you to select columns for the X and Y axis and then updates the figure automatically. If you have more than 30 minutes of R Shiny experience, the code snippet below shouldn’t be difficult to read: library(shiny) library(ggplot2) ui <- fluidPage( tags$h3("Scatter plot generator"), selectInput(inputId = "x", label = "X Axis", choices = names(mtcars), selected = "mpg"), selectInput(inputId = "y", label = "Y Axis", choices = names(mtcars), selected = "hp"), plotOutput(outputId = "scatterPlot") ) server <- function(input, output, session) { data <- reactive({mtcars}) output$scatterPlot <- renderPlot({ ggplot(data = data(), aes_string(x = input$x, y = input$y)) + geom_point(aes(size = qsec, color = factor(cyl))) + scale_color_manual(values = c("#3C6E71", "#70AE6E", "#BEEE62")) + theme_classic() + theme(legend.position = "none") }) } shinyApp(ui = ui, server = server) Image 5 – Shiny dashboard rendering a ggplot chart Put simply, we’re rerendering the chart every time one of the inputs changes. All computations are done in R, and the update is almost instant. Makes sense, since mtcars is a tiny dataset. But how about rendering a Matplotlib chart in R Shiny? Let’s see if it’s even possible. How to Use Matplotlib Charts in R Shiny There are several ways to combine R and Python – reticulate being one of them. However, we won’t use that kind of bridging library today. Instead, we’ll opt for a simpler solution – calling a Python script from R. The mentioned Python script will be responsible for saving a Matplotlib figure in JPG form. In Shiny, the image will be rendered with the renderImage() reactive function. Let’s write the script – generate_scatter_plot.py. It leverages the argparse module to accept arguments when executed from the command line. As you would expect, the script accepts column names for the X and Y axis as command line arguments. The rest of the script should feel familiar, as we explored it in the previous section: import argparse import pandas as pd import matplotlib.pyplot as plt # Tweak matplotlib defaults plt.rcParams["figure.dpi"] = 300 plt.rcParams["axes.spines.top"] = False plt.rcParams["axes.spines.right"] = False # Get and parse the arguments from the command line parser = argparse.ArgumentParser() parser.add_argument("--x", help="X-axis column name", type=str, required=True) parser.add_argument("--y", help="Y-axis column name", type=str, required=True) args = parser.parse_args() # Fetch the dataset mtcars = pd.read_csv("", index_col=[0]) # Create the plot fig, ax = plt.subplots(figsize=(13, 7)) ax.scatter( x=mtcars[args.x], y=mtcars[args.y], s=[s**1.8 for s in mtcars["qsec"].to_numpy()], c=["#3C6E71" if cyl == 4 else "#70AE6E" if cyl == 6 else "#BEEE62" for cyl in mtcars["cyl"].to_numpy()] ) # Save the figure fig.savefig("scatterplot.jpg", bbox_inches="tight") You can run the script from the command line for verification: Image 6 – Running a Python script for chart generation If all went well, it should have saved a scatterplot.jpg to disk: Image 7 – Scatter plot generated by Python and matplotlib Everything looks as it should, but what’s the procedure in R Shiny? Here’s a list of things we have to do: - Replace plotOutput()with imageOutput()– we’re rendering an image afterall - Construct a shell command as a reactive expression – it will run the generate_scatter_plot.pyfile and pass in the command line arguments gathered from the currently selected dropdown values - Use renderImage()reactive function to execute the shell command and load in the image It sounds like a lot, but it doesn’t require much more code than the previous R example. Just remember to specify a full path to the Python executable when constructing a shell command. Here’s the entire code snippet: library(shiny) ui <- fluidPage( tags$head( tags$style(HTML(" #scatterPlot > img { max-width: 800px; } ")) ), tags$h3("Scatter plot generator"), selectInput(inputId = "x", label = "X Axis", choices = names(mtcars), selected = "mpg"), selectInput(inputId = "y", label = "Y Axis", choices = names(mtcars), selected = "hp"), imageOutput(outputId = "scatterPlot") ) server <- function(input, output, session) { # Construct a shell command to run Python script from the user input shell_command <- reactive({ paste0("/Users/dradecic/miniforge3/bin/python generate_scatter_plot.py --x ", input$x, " --y ", input$y) }) # Render the matplotlib plot as an image output$scatterPlot <- renderImage({ # Run the shell command to generate image - saved as "scatterplot.jpg" system(shell_command()) # Show the image list(src = "scatterplot.jpg") }) } Image 8 – Shiny dashboard rendering a matplotlib chart The dashboard takes some extra time to rerender the chart, which is expected. After all, R needs to call a Python script which then constructs and saves the chart to the disk. It’s an extra step, so the refresh isn’t as instant as with ggplot2. Summary of Matplotlib vs. ggplot To conclude, you can definitely use Python’s Matplotlib library in R Shiny dashboards. There are a couple of extra steps involved, but nothing you can’t manage. If you’re a heavy Python user and want to try R Shiny, this could be the fastest way to get started. What do you think of Matplotlib in R Shiny? What do you generally prefer – Matplotlib or ggplot2? Please let us know in the comment section below. Also, don’t hesitate to reach out on Twitter if you use another approach to render Matplotlib charts in Shiny – @appsilon. We’d love to hear your comments. R Shiny and Tableau? Learn to create custom Tableau extensions from R Shiny. The post Matplotlib vs. ggplot: How to Use Both in R Shiny Apps appeared first on Appsilon | Enterprise R Shiny Dashboards. Want to share your content on python-bloggers? click here.
https://python-bloggers.com/2022/09/matplotlib-vs-ggplot-how-to-use-both-in-r-shiny-apps/
CC-MAIN-2022-40
refinedweb
1,907
57.57
The Javadoc Tool was originally designed to generate API documentation from Java source code. Now, it is not only a documentation generator, but an an extensible engine for processing Java source code. This article illustrates how to write programs for the Javadoc Tool. Custom Tags In Java 1.4 support for custom tags was added to the Javadoc Tool. Custom tags are specified with command-line options and can be handled by custom programs called taglets. If you want a one-argument block tag, which can occur anywhere after the main description in a javadoc comment, specify the tag using the “-tag” option. Javadoc will output the tag heading in bold, with the argument indented below it. Here is a javadoc comment that includes the custom tag “@note”: /** * Quark represents a quark. * * @note If you spin a quark, it will spin forever! */ public class Quark { } To generate javadocs for the above, run javadoc like this: javadoc -tag note:a:"Note:" Quark.java The generated javadocs should look like Quark.html. Taglets If you want to customize the handling of a tag, you use a taglet. Taglets are specified with the “-taglet” option and can be used for both the standard taglets and custom taglets. Additionally, taglets can control the formatting of both block tags, which must occur at the beginning of a line, and inline tags, which can occur anywhere in text. To create a taglet: Import the com.sun.javadocpackage and the com.sun.tools.docletspackage. Implement the interface com.sun.tools.doclets.Taglet. Implement the register(Map tagletMap)method. This method will be called when the taglet is loaded by javadoc so that the taglet class can register with javadoc. This is done by adding an instance of the taglet class to the given map, which is a dictionary that javadoc uses to look up taglets by name. Example: public static void register(Map tagletMap) { tagletMap.put("strike", new StrikeTaglet()); } Return the tag name from the getName()method. The tag name is what javadoc will look for in javadoc comments. For example, “note” is returned for the “@note” tag. If you want to customize the format of a standard tag, return its name. For example, return “author” for the “@author” tag. Return truefrom the isInlineTag()method if the tag is an inline tag. Otherwise, return false. Return trueor falseas applicable from inConstructor(), inField(), inMethod(), inOverview(), inPackage(), and inType(). Implement the formatting code in toString(Tag tag)and toString(Tag[] tags). The first method is called by javadoc to format an inline tag. The second method is called by javadoc to format one or more block tags. However, as you will see in the examples below, toString(Tag[] tags)can call toString(Tag tag) to format each tag in the given array. Here are some examples of taglets: AuthorTaglet – Formats “@author” tags as a comma-delimited list. NoteTaglet – Formats “@note” tags in upper case. StrikeTaglet – Formats “{@strike}” inline tags as striken text, like this. To compile the above taglets, include the Java library, tools.jar, in the classpath. To generate javadocs for Quark.java using the taglets, run javadoc like this: javadoc -taglet StrikeTaglet -taglet NoteTaglet -taglet AuthorTaglet Quark.java Alternatively, you could create a file that contains the taglet options, then run javdoc like this: javadoc @taglets.opt Quark.java The generated javadocs should look like Quark2.html. Doclets Doclets are programs that use the Doclet API to customize the output of the javadoc tool. They can be used to augment javadoc generation, to generate other files, or to do something completely different. To create a doclet: Import the package com.sun.javadoc. Extend the class Doclet. Implement the method public static boolean. This method will be called when the doclet is start(RootDoc) started by javadoc. It should generate the output and return true upon successful completion. MetricsDoclet is an example of doclet that generates metrics about the source files that are processed. To compile MetricsDoclet, include the Java library, tools.jar, in your classpath. To run MetricsDoclet, run javadoc like this: javadoc -doclet MetricsDoclet *.java The output of MetricsDoclet should look like metrics.txt. Customizing the Standard Doclet If you want to generate HTML documents that are similar to the documents produced by javadoc, you can extend the standard doclet classes and override methods as necessary to produce the output that you want. The standard doclet classes are in the packages com.sun.tools.doclets.standard and com.sun.tools.doclets.standard.tags in tools.jar. Alternatively, you can make a copy of the standard doclet and modify it. The source code is available from Sun in the Java 2 SDK 1.4 Source Code Release. (See “Resources” for a link.) Command-line Options Doclets can have command-line options. To do so, the doclet must have two methods: public static int optionLength(String option) public static boolean validOptions(String[][] options, DocErrorReporter reporter) The optionLength method is called by javadoc to determine the length of the array that will contain a given option and its arguments. If the given option is one of the doclet options, this method should return one plus the number of arguments that the option takes. For example, for the option "-debug <n>", optionLength should return 2. If the given option is not one of the doclet options, optionLength should return 0. The validOptions method is called by javadoc to validate the doclet options. This method should check the given options and return true if they are valid. If the options are not valid, this method should report any errors via reporter and return false. To retrieve the validated options, call root.options(), where root is the instance of RootDoc that is passed to the start method. OptionsDoclet illustrates using command-line options in a doclet. To compile OptionsDoclet, include the Java library, tools.jar, in your classpath. To run OptionsDoclet, run javadoc like this: javadoc -doclet OptionsDoclet -debug 1 -verbose Quark.java The output of OptionsDoclet should look like options.txt.
https://www.developer.com/java/javadoc-programming/
CC-MAIN-2022-40
refinedweb
1,000
67.76
I just uploaded the source code for this library, used in the Virtual Earth mash-up described in my previous post. You can browse/download it from here. What you will find: - A simple domain model for GeoRSS feeds with support for points, lines and polygons; links and icons GeoRssData geoData = new GeoRssData("Mount Saint Helens", "Trailheads and campsites in the Mount Margaret area of Mt. Saint Helens, WA"); geoData.AddPoint( "Lakes Trailhead", "This is where we started our hike", 46.2913246, -122.2658157 ); polygon = geoData.AddPolygon("Coldwater Lake", "Formed by the 1980 eruption of Mount St. Helens.", ") polygon.Link = "”; … The GeoRssData provides common methods for creating the shapes and passing the information (like coordinates). For example, AddLine and AddPolygon methods come in two versions: one that takes a Point[] and another that takes a string: public GeoRssLineItem AddLine(string itemTitle, string itemDescription, Point[] line); public GeoRssLineItem AddLine(string itemTitle, string itemDescription, string line); The latter is convenient if you persist your information in a single field in a database for example, as I’m doing in LitwareHR. There are also simple validations like point should have 2 coordinates, lines should have an even number of coordinates, strings should be parsed as doubles, etc. - A GeoRSS builder that converts the model into a SyndicationFeed object: SyndicationFeed feed = GeoRssFeedBuilder.GetFeed(geoData) The feed can then be passed to Rss20FeedFormatter. - Unit tests for all with +99% coverage: - A very simple sample demonstrating how to use it (besides the tests which are self explanatory) Final notes: I liked the System.Xml.Linq classes very much. In my original implementation I assembled the Xml elements by hand, concatenating strings, etc. mainly because I couldn’t find a way of programmatically constructing them in the way Virtual Earth likes (e.g. all georss elements have to use the namespace “georss”, the elements must be fully qualified, etc.). Using XElement & XAttribute was straightforward and compact: XNamespace grns = ""; XElement x = new XElement(grns + "point", new XAttribute(XNamespace.Xmlns + "georss", grns.NamespaceName ), 10, 20 ); will serialize as: <georss:point xmlns:georss=””>10 20</georss:point> The model should be fairly simple to extend to include support for other elements (radius, etc). or even the broader set of attributes in the SyndicationFeed class and related cousins. I hope you find it useful. PingBack from In this screencast, I build off of the concepts shown in my previous screencast and show you how to render In this screencast, I build off of the concepts shown in my previous screencast and show you how to render Marc Schweigert builds off of the concepts shown in his previous screencast and shows you how to render Marc Schweigert builds off of the concepts shown in his previous screencast and shows you how to render It’s been a good week for awesome content again here in Virtual Earth land. Marc Schweigert I swear is
https://blogs.msdn.microsoft.com/eugeniop/2008/07/01/simple-georss-utility-library-released/
CC-MAIN-2019-35
refinedweb
481
60.75
Windows Controls: The Track Bar Introduction A track bar is a control used to slide a small bar or pointer, also called a thumb, along a continuous line. In the following dialog box, there is an example of a track bar under Adjust the slider...: To use the track bar, the user can drag the thumb in one of two directions. This changes the position of the thumb. The user can also click a position along the control line to place the thumb at a desired location. Alternatively, when the track bar has focus, the user can use the arrow keys to move the thumb. As far as appearances are concerned, there are two types of track bars, depending on the orientation: horizontal or vertical. Here is an example of a vertical track bar on the left side of Medium: A track bar is configured with a set of values from a minimum to a maximum. Therefore, the user can make a selection included in that range. Optionally, a track bar can be equipped with small marks called ticks. These can visually guide the user for the available positions of the thumb. A track bar can be used as a progress control to help the user monitor an activity. A track bar also allows the user to specify a value that conforms to a range. When equipped with small indicators, also called ticks, a track bar can be used to control exact values that the user can select in a range, preventing the user from setting just any value. Creating a Track Bar To support track bars, the .NET Framework provides the TrackBar class. At design time, to add a track bar to your application, from the Toolbox, you can click the TrackBar button and click the form or a container. The TrackBar class is derived from the Control class. To programmatically create a track bar, declare a variable of type TrackBar, use the new operator to allocate memory for the variable, and add it to the Controls property of its parent. Here is an example of creating a track bar: using System; using System.Drawing; using System.Windows.Forms; public class Exercise : System.Windows.Forms.Form { TrackBar tbrSlider; public Exercise() { InitializeComponent(); } private void InitializeComponent() { tbrSlider = new TrackBar(); Controls.Add(tbrSlider); } } public class Program { static int Main() { System.Windows.Forms.Application.Run(new Exercise()); return 0; } } This would produce:
http://www.functionx.com/vcsharp/controls/trackbar1.htm
CC-MAIN-2017-30
refinedweb
399
64.3
Hi AO's Well i am new to java programming and i was writing a new program in java servlet which is // Hello.java import java.io.*; import javax.servlet.*; public class Hello extends GenericServlet { public void service(ServletRequest request, ServletResponse response) throws ServletException, IOException { response.setContentType("text/html"); PrintWriter pw = response.getWriter(); pw.println("Hello, world!"); pw.close(); } } and while compiling in CMDi got error as follows C:\Program Files\Java\jdk1.6.0_06\bin>javac Hello.java Hello.java:3: package javax.servlet does not exist import javax.servlet.*; ^ Hello.java:5: cannot find symbol symbol: class GenericServlet public class Hello extends GenericServlet { ^ Hello.java:6: cannot find symbol symbol : class ServletRequest location: class Hello public void service(ServletRequest request, ServletResponse response) ^ Hello.java:6: cannot find symbol symbol : class ServletResponse location: class Hello public void service(ServletRequest request, ServletResponse response) ^ Hello.java:7: cannot find symbol symbol : class ServletException location: class Hello throws ServletException, IOException ^ 5 errors C:\Program Files\Java\jdk1.6.0_06\bin> what does this error resembles to Last edited by kingkong; June 8th, 2008 at 09:41 AM. Reason: modification Question is not "Why are you Online" Question is "Why are you Off line" Am I right in thinking that javax.servlet is a Tomcat package (I get the feeling there might be different implementations)? Basically the error you're getting means that the Java compiler can't find the javax.servlet package. This means either: 1. You don't have the package, or 2. Your classpath isn't set up to include the servlet package. If you have the first problem, go to and download. If you have the second problem, find where the servlet package is installed and add it to your classpath. For info on setting the classpath correctly, see. Hope that sorts you out - just bear in mind that I'm not really a Java person, so if there's anything wrong with what I've told you, that's why. Cheers, ac Hi Gothic Type, I got the error i read alot on java site and finally i got the answer for that stupid question i asked i am using JAVA SE which do not have the package of javax.servlet and because of which i got this error i should use Java EE as per i am new to java and still my teacher of the class thought of teaching me javax.servlet , swing , and applets on which i heard should be teached on the later stage after i got my hand properly on the pace of java Thanks a lot for your answer Gothic Forum Rules
http://www.antionline.com/showthread.php?277130-Java-Query&p=939343&viewfull=1
CC-MAIN-2018-05
refinedweb
440
55.74
mbrlen - get number of bytes in a character (restartable) #include <wchar.h> size_t mbrlen(const char *s, size_t n, mbstate_t *ps); If s is not a null pointer, mbrlen() determines the number of bytes constituting the character pointed to by s. It is equivalent to: mbstate_t internal; mbrtowc(NULL, s, n, ps != NULL ? ps : &internal); If ps is a null pointer, the mbrlen()len(). The behaviour of this function is affected by the LC_CTYPE category of the current locale. The mbrlen() function returns the first of the following that applies: - 0 - If the next n or fewer bytes complete the character that corresponds to the null wide-character. - positive - If the next n or fewer bytes complete a valid character; the value returned is stored in errno and the conversion state is undefined. The mbrlen()).
http://pubs.opengroup.org/onlinepubs/007908775/xsh/mbrlen.html
CC-MAIN-2016-50
refinedweb
135
61.06
stepper_at91.c File ReferenceStepper driver interface implementation. More... #include "stepper_at91.h" #include "cfg/cfg_stepper.h" #include <cfg/macros.h> #include <cfg/debug.h> #include <cpu/types.h> #include <cpu/irq.h> #include <io/arm.h> Go to the source code of this file. Detailed DescriptionStepper driver interface implementation. This module use the three timer on the at91 family, to generate a six periodic variable pwm waveform. The pulse width is fix, and could change by setting the STEPPER_DELAY_ON_COMPARE_C define, but you make an attention to do this, becouse the pulse width is not exactly STEPPER_DELAY_ON_COMPARE_C. The pulse width depend also to latency time of cpu to serve an interrupt, this generate an pwm waveform affect to noise. This noise not effect the period but only the pulse width, becouse the raising edge is generate by hardware comply with the our period settings. Note: is most important to set STEPPER_DELAY_ON_COMPARE_C value minor than a interrupt time service, becouse the falling edge must be happen inside to inerrupt service to guarantee a correct functionaly of pwm generator. - Version: - Id - stepper_at91.c 1761 2008-08-29 20:37:03Z bernie Definition in file stepper_at91.c. Function Documentation This function apply to select timer couter all needed settings. Every settings are stored in stepper_timers[]. Definition at line 333 of file stepper_at91.c.
http://doc.bertos.org/2.1/stepper__at91_8c.html
crawl-003
refinedweb
218
52.46
I am fairly new to the programming game, well, in C that is. Anyways, I wrote a small program that should take user input, a single word and run it through a basic encryption algorithm, supplied in the source. The word is translated in decimal form and inserted into the algorithm so that it changes everytime you type something in. Here is the source. --------begenning of code------------- #include <stdio.h> main() { int unenc, enc; printf("Please enter a word that you would like encrypted --> \n"); scanf("%s", &unenc); for ( enc = 2 + 533 + unenc * unenc - 456 * unenc - 65 + 34 ) printf("Your word, encrypted is %s\n", enc); } ------------end of file--------------- Now, I know that my for statement is the issue. I need to know how to use my unenc interger variable in the equation. What is the problem???
http://cboard.cprogramming.com/c-programming/41290-basic-encryption-theory.html
CC-MAIN-2014-23
refinedweb
137
71.65
I’m part of the SAP S/4HANA Regional Implementation Group who assist customers implementing the latest SAP S/4HANA releases. One of the questions we are asked from time to time is how to override the texts – such as field labels, table and column headings – in delivered SAP Fiori apps. In this blog you will learn how to use in-app Extensibility with the Key User tool Adapt UI to override texts. So you want to use a SAP Fiori app in SAP S/4HANA, the app fits with your business process, business role and the task… but all that SAP terminology is getting in the way of user adoption. Your users just don’t think in SAP terms. They need the texts adjusted to fit how they think about their work. You need to override the texts – such as field labels, table and column headings – in the delivered SAP Fiori apps. Typically you might need to do this if: - You need to override SAP standard terminology with industry terms, e.g. change Product to Article - You need to override SAP standard terminology with organization-specific terms, e.g. change Old Material Number to Our Company Reference - You need to add a new language dialect to meet local market standards, e.g. override US English with Australian English. There are 3 main options for adapting texts for SAP delivered Fiori apps: - As an authorized business expert or functional lead, using in-app Extensibility with Key User tools - As a developer, using Classic Extensibility to adapt texts via a Metadata Extension - As a developer, using Classic Extensibility to adapt texts via a SAPUI5 Extension Project It’s worth noting that the 3 approaches for adapting texts can be used together in a complementary way depending on the type of app and the texts to be changed. For example you might use Key User tools to adapt the static texts of an app, and a metadata extension to adjust dynamic texts. IMPORTANT: Regardless of which approaches are used, all changes are made in the Development system and transported through the system landscape to the Production system as per the usual SAP change and transport management process. In this blog you will learn how you can do this using in-app Extensibility with the Key User tool Adapt UI to override texts. Watch for an upcoming blog where you will find out how to use metadata extensions for texts. If you need this urgently then you will find sufficient information in the SAP Help Portal on Creating a MetaData Extension, on Annotation Propagation, and on Adding Translated Text to a MetaData Extension. And of course SAPUI5 Extension Projects have already been covered in many blogs and in official documentation including the localization concept used for i18n.properties files. TIP: You can also enable UI Adaptation in your own custom Fiori apps as explained in UI Adaptation at Runtime: Enable your App. When to Adapt Texts via Key User tools In-app Extensibility via Key User tools enables business experts, functional leads, and other authorized persons to adapt a Fiori app. Certain changes, such as overriding texts, can be made when you are in the Fiori app itself. This approach is called runtime UI Adaptation. If you are authorized, you can access the Adapt UI option in your Fiori Launchpad Me Area. You can change static texts using runtime UI Adaptation in Fiori elements apps, and in freestyle Fiori apps that support flexibility services. In-app Extensibility via Key User tools is the easiest and quickest approach to use when available, e.g. for SAP Fiori apps of application type Fiori elements, and for SAP Fiori apps of application type freestyle Fiori (SAPUI5) apps that support SAPUI5 Flexibility Services. Dynamic texts, such as the count of items at the top of table, are a bit more involved. And freestyle apps don’t always provide full flexibility. Even with Fiori elements apps, not every text is covered by UI Adaptation – at least not yet (which texts are covered has been growing with new releases of SAP S/4HANA and SAP S/4HANA Cloud). Where UI Adaptation cannot be used, in SAP S/4HANA a classic extensibility approach may also be needed, depending on which texts you need to adjust. TIP: Check the App detail in the Fiori Apps Library to find the application type. The Application Type field tells you what framework was used to build the app and you can then quickly determine which extension options are likely to be available. Classic Extensibility can be used as a fallback approach when In-app Extensibility is not available or doesn’t provide access to change all the texts you need to adjust, e.g.: - You might need to use a Metadata Extension to override dynamic texts of a SAP Fiori elements app - You might need to use a SAPUI5 Extension Project to override texts of a freestyle SAPUI5 apps. Options for extending SAP Fiori apps are explained in more detail in the SAP Guided Answer on How to extend a SAP Fiori app in SAP S/4HANA. Prerequisites for Adapting Texts via Key User tools There are 3 prerequisites: - The Adaptation Transport Organizer must be configured - Optionally (and recommended) a workbench transport request can be created and assigned to the user to collate their changes - The user must be authorized to perform UI Adaptation at runtime As an administrator you control in-app extensibility transports via the Adaptation Transport Organizer. You can also use the Fiori app Extensibility Inventory to monitor and act on Key User extensions created by others. You use Transaction S_ATO_SETUP to set up the Adaptation Transport Organizer in the Development system. Here you can control the transports, e.g. assign a namespace or prefix to all changes. More information on Configuring Adaptation Transport Organizer can be found in the SAP Help. TIP: You will also find some additional details in SAP Note 2283716 – S/4HANA Key User Application is not configured The user who will perform the changes is recommended to be assigned to a workbench transport request. You can create a workbench request and assign it to the relevant key user in transaction SE01. NOTE: Alternatively changes can be saved to a Local Object. However if the changes are to be transported, as an administrator you will need to reassign them later to a workbench transport request. Reassigning objects from Local Objects to is more effort, so you are recommended to create a transport request up front. The user id that will perform the changes must be authorized to make UI Adaptations. You authorize a key user by assigning them the security role SAP_UI_FLEX_KEY_USER in the security role maintenance transaction PFCG. Process for Adapting Texts via UI Adaptation at runtime You start by logging on to the Fiori Launchpad in the master language that you want to make your changes. Navigate to the App that you want to change, e.g. using the Home Page tiles, or the App Finder. The following examples are shown using the Fiori app Product Master / Manage Products Once you are in the app, navigate to the screen that holds the texts that you want to change. Open the Me Area and press the Adapt UI icon. Remember you will only see this button if you are authorized to perform UI Adaptation as explained in the prerequisites section. The app will open UI Adaptation mode. TIP: If you need to navigate within the app to get to the text you need to change, simply swap to Navigation mode (click on the Navigation button at the top of the screen). E.g. You might need to select a row to get a button to activate so that you can change the text of the button. Once you have reached the text you need to change, swap back to UI Adaptation mode (click on the UI Adaptation button at the top of the screen) ready to change the texts. Which texts you can change depends on your SAP S/4HANA (or SAP S/4HANA Cloud) version. In SAP S/4HANA 1709 you can change: - Table Headings - Column Headings - Group labels - Field labels TIP: You can also make other changes as well in UI Adaptation mode depending on your SAP S/4HANA version. In SAP S/4HANA 1709 you can: - change the sequence in which buttons are arranged in a toolbar - hide tables - hide thumbnail images - hide header groups - add/hide sections - add/hide groups (within a section) - add/hide fields (within a group or section) - change the order of fields, field groups, and sections While you are in UI Adaptation mode, select and overtype the text you want to change. Once you have finished making your changes press Publish to save those changes. When you publish you will then be asked to assign your changes to your Transport Request. Use the dropdown on the Transport field to find suitable transport requests you can use, and then just press Ok to confirm. TIP: You can also use the option Local Object if your administrator will take charge of reassigning your changes to a transport request. This is more work for the administrator so it’s worth asking them for a transport request before you start. The transport request is a Workbench Request (i.e. cross-client). Technically the transport objects are of object type LRCD (LRepository Client-Dependent content). IMPORTANT: *** DO NOT ATTEMPT to do multiple screens at once *** Each screen has its own set of texts, and each screen may technically be a different app. Fiori navigation is intentionally seamless which means as a user it can be difficult to tell if the current screen is from the same or a different app). Use the Exit button (in the top right hand corner next to the Publish button) to exit UI Adaptation mode between screens. Navigate to the screen and text you need to change, then use the Adapt UI icon in the Me Area to open the current screen in UI Adaptation mode. Repeat the process of overtyping texts. You can make any other UI Adaptation changes at the same time. In the example below as well as changing texts, you can see that the following changes have been made: - added a new field group called Admin Data - moved some fields into the Admin Data field group - hidden a field called Authorization Group - added a field Net Weight. Finish by publishing the screen and save it to your transport request just as you did previously. TIP: If you change your mind or make a mistake, you can always use the Reset button (next to the Publish button) to set the screen back to the original texts. You can use the Reset button at any time to reset the changes of the current screen – even after you have published your changes! Once you are finished all you need to do is let your administrator know that your changes are ready to be transported. IMPORTANT: If you are working in multiple languages, you might need to translate these texts as well. You will notice that after changing the texts that your adapted texts have changed all languages. You can see this by logging in as the same user in a different language (in the examples you can see German). TIP: You can find more on UI Adaptation in the SAP Help Portal in the User Guide for SAP Fiori Launchpad in the section Adapting Fiori Apps at Runtime > Making UI Changes. You will find more on how to translate these texts in this blog Fiori for S/4HANA – Translating Terminology in SAP Fiori apps via Key User tools. Becoming a SAP Fiori for SAP S/4HANA guru You’ll find much more on our SAP Fiori for SAP S/4HANA wiki Brought to you by the S/4HANA RIG Great blog! It might be worth to mention, that you can do the same in SAP S/4HANA Cloud. And event better: You can skip the part “Prerequisites for Adapting Texts via Key User tools” in SAP S/4HANA Cloud, because this is already preconfigured. Just assign the Extensibility catalog to a business role of a user that should do the text adaptations. Best regards, Thomas Hi Jocelyn, This is a very informative post. I had one question. Is it possible to create multiple adaptations of the same UI so that the adaptation which is presented to the user depends on his/her assigned role(s). Best regards, Vimal Hi Vimal, It wasn’t then. With SAP S/4HANA 1909 this should now be possible – and something I am exploring. Hello Jocelyn Dart , I have created custom fields using Custom Fields and Logic App and have added the same in Manage Purchase Contract App. All things have moved correctly to Quality systems. Everything is fine. Now we have created one more custom field and have added this new field to Manage Purchase Contract. But Post moving this Transport, Changes are not reflecting in UI of Quality. We have repeated addition of this new field again using Key User – UI Adaptation and transported this to Quality. But still no luck . Can you please suggest me what might have gone wrong? Thank You Very Much…!!! Hi Pawan Strange…did you check the custom field was enabled for Manage Purchase Contract in the Custom Fields and Logic app? If not, hopefully you raised a SAP Incident. Hello Jocelyn, The blog was very informative.. Can freestyle Fiori apps be extended using In-app extensions and key user tools be used for UI adaptions of freestyle Fiori apps? Best Regards, Chaitra
https://blogs.sap.com/2018/05/12/fiori-for-s4hana-adapting-terminology-in-sap-fiori-apps-via-key-user-tools/
CC-MAIN-2020-50
refinedweb
2,278
58.82
Silverlight – Video & Audio In this chapter, we will see how Silverlight facilities are playing video and audio. The MediaElement is the heart of all video and audio in Silverlight. This allows you to integrate audio and video in your application. The MediaElement class works in a similar way like as Image class. You just point it at the media and it renders audio and video. The main difference is it will be a moving image, but if you point it to the file that contains just audio and no video such as an MP3, it will play that without showing anything on the screen. MediaElement as UI Element MediaElement derives from framework element, which is the base class of all Silverlight user interface elements. This means it offers all the standard properties, so you can modify its opacity, you can set the clip, or transform it and so. Let us have a look at a simple example of MediaElement. Open Microsoft Blend for Visual Studio and create a new Silverlight Application project. Now drag and video or audio file into Blend design surface. It will add a MediaElement to the surface and also add a copy of the video file in your project. You can see it in Solution explorer. You can move it around, change its size, you can do things like applying a rotation etc. Now, it will generate the related XAML for you in MainPage.xaml file like shown" Margin = "51,49,53,53" Source = "/Microsoft Silverlight DEMO.mp4" Stretch = "Fill" RenderTransformOrigin = "0.5,0.5"> <MediaElement.RenderTransform> <CompositeTransform Rotation = "-18.384"/> </MediaElement.RenderTransform> </MediaElement> </Grid> </UserControl> When the above application is compiled and executed, you will see that the video is playing on your web page. Controlling The MediaElement just presents the media. It does not offer any standard player controls. It starts playing automatically and stops when it reaches the end, and there is nothing a user can do to pause or otherwise control it. So in practice most applications will want to provide the user with a bit more control than that. You can disable the automatic playback by setting AutoPlay to False. This means the media player will not play anything until you ask it. <MediaElement x: So when you want to play the video, you can just call the MediaElement Play() method. It also offers stop and pause methods. Let us have a look at the same example again and modify it little bit to allow a bit of control. Attach the MouseLeftButtonDown handler in MediaElementas shown in the XAML code" AutoPlay = "False" MouseLeftButtonDown = "Microsoft_Silverlight_DEMO_mp4_MouseLeftButtonDown" Margin = "51,49,53,53" Source = "/Microsoft Silverlight DEMO.mp4" Stretch = "Fill" RenderTransformOrigin = "0.5,0.5"> </MediaElement> </Grid> </UserControl> Here is the implementation on the MouseLeftButtonDown event handler in which it will check that if the current state of the media element is plating then it will pause the video otherwise it will start playing the video. using System.Windows.Controls; using System.Windows.Input; using System.Windows.Media; namespace MediaElementDemo { public partial class MainPage : UserControl { public MainPage() { InitializeComponent(); } private void Microsoft_Silverlight_DEMO_mp4_MouseLeftButtonDown (object sender, MouseButtonEventArgs e) { if (Microsoft_Silverlight_DEMO_mp4.CurrentState == MediaElementState.Playing) { Microsoft_Silverlight_DEMO_mp4.Pause(); } else { Microsoft_Silverlight_DEMO_mp4.Play(); } } } } When the above code is compiled and executed, you will see the blank web page because we have set the AutoPlay property to False. When you click the web page, it will start the video. When you click the web page again, it will pause the video.
https://turnkey-shop.com/knowledge-base/silverlight-video-audio/
CC-MAIN-2019-43
refinedweb
577
56.86
Hi, the sample program below crashes if compiled with icc sample.cpp -std=c++11 -check=uninit with the Intel C++ compiler v14 on Linux (Suse Linux Enterprise Desktop 11) - it claims that some variable is used without initialization, but the header file looks right to me. Has anyone else encountered this problem? Is it a boost or compiler issue? What can I do if I want to keep both boost and the debug option? Best Regards, Christopher #include <memory> #include <iostream> #include <boost/shared_ptr.hpp> int main(const char* argv[], int argc) { boost::shared_ptr<int> value(new int); *value = 1; std::cout << *value << std::endl; } Link Copied Greetings, the shared pointer code looks good to me. But I see a programming mistake: int main(const char* argv[], int argc) change this to: int main(int argc, const char* argv[]) This is the correct order of arguments of main() function. Hi, you are right, I got that mixed up. Should have written int main() anyway since I do not use argc/argv. But the program aborts in either variant after the 1 is printed to stdout (Run-Time Check Failure: The variable 'r' is being used without being initialized). By the way, my icc is 14.0.4 (gcc version 4.3.0 compatibility), gcc/libc++ version on that machine is 4.3.4, and the boost rpm is boost-devel-1.36.0-12.3.1. Stack trace: #0 0x00002b6f86a7cb55 in raise () in /lib64/libc-2.11.3.so #1 0x00002b6f86a7e131 in abort () in /lib64/libc-2.11.3.so #2 0x0000000000401bd0 in __libirc_get_msg () in a.out #3 0x00007fff89e1ace0 in ?? () #4 0x0000000000401730 in boost::detail::atomic_exchange_and_add (pw=0x606038, dv=-1) at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:43 #5 0x000000000040149f in boost::detail::sp_counted_base::release (this=0x606030) at /usr/include/boost/detail/sp_counted_base_gcc_x86.hpp:143 #6 0x000000000040154f in boost::detail::shared_count::~shared_count (this=0x7fff89e1abc8) at /usr/include/boost/detail/shared_count.hpp:216 #7 0x0000000000401308 in boost::shared_ptr<int>::~shared_ptr (this=0x7fff89e1abc0) at /usr/include/boost/shared_ptr.hpp:164 #8 0x00000000004010e9 in main (argc=1, argv=0x7fff89e1ace8) at sample.cpp:10 Regards, Christopher Hi Christopher, I failed to reproduce your issue on my environment. It just works and will not crash at runtime (also no message about "without initialization"). My boost is as below: boost-1.41.0-11.el6_1.2.x86_64 I may need to build the same boost version to reproduce your issue and see whether this is an issue of Boost or an false positive case from ICC's uninit checking. Also, could you please send me the pre-processed file to me (icc sample.cpp -std=c++11 -check=uninit -E)? I may build your pre-processed file directly. Thanks, Shenghong Hi Shengong, sorry I somehow missed your answer in November. The problem is still troubling us, I will send you the preprocessed file when I have access to it tomorrow morning. We recently stumbled into a related problem with a QT 4.8.6 header (include/QtCore/qatomic_x86_64.h). I do not have a sample program at hand, but the problematic section of the header is the following, and actually looks pretty much the same as in boost: inline bool QBasicAtomicInt::deref() { unsigned char ret; asm volatile("lock\n" "decl %0\n" "setne %1" : "=m" (_q_value), "=qm" (ret) : "m" (_q_value) : "memory"); return ret != 0; } This causes an error "ret is used without being initialized" when used in an object file compiled with --check uninit. If we change the header to initalize ret with zero, no error occurs. Thank you, Christopher Hi Christopher, Thank you for your update. I am kind of clear about the issue now, and reproduce it -DFUNC=foo && ./a.out 1 $ icc temp.cpp -DFUNC=bar && ./a.out 1 $ icc temp.cpp -check=uninit -DFUNC=foo && ./a.out 1 $ icc temp.cpp -check=uninit -DFUNC=bar && ./a.out Run-Time Check Failure: The variable 'ret' is being used in temp.cpp(14,0) without being initialized Aborted (core dumped) $ I'll report it to dev team to see whether it is possible to make this uninit check work for asm code. Thanks, Shenghong Hi Shegong, thank you very much for your effort. I just discovered a similar thread on the forum, "False Positives when Boost::shared_ptr is used with Inspector?", which might be the same or a related issue. Christopher Hi Christopher, The issue is fixed in update 3 compiler, my verification -check=uninit -DFUNC=bar && ./a.out 1 $ Let me know if you still have issues. Thanks, Shenghong
https://community.intel.com/t5/Intel-C-Compiler/Crash-with-boost-shared-ptr-and-check-uninit/td-p/999571
CC-MAIN-2021-10
refinedweb
757
67.65
Eclipse Community Forums - RDF feed Eclipse Community Forums Query field created by the @OrderColumn <![CDATA[I have an entity like this: public class A { @OneToMany @OrderColumn(name = "ORDER") private List<B> bList; ... } I need to fetch from database some B objects ordered by the created ORDER column. If I define a field in B like this: public class B { @Column(name = "ORDER") private Integer order; ... } EclipseLink try to create the "ORDER" column 2 times throwing an exception and doesn't create the B table. I can't fetch A objects because I need to fetch some B objects belonging to different A objects (even no A objects) How can I solve this? Regards Alessandro]]> Alessandro Pacifici 2012-01-12T10:26:10-00:00 Re: Query field created by the @OrderColumn <![CDATA[Hello, If you just want the list to be returned ordered, use the @OrderBy annotation instead. OrderColumn causes the field to be controlled by the collection. Please file a bug though, as the field should not be written twice. Instead, you should get an exception stating that the field is mapped twice (since both the collection and the basic mapping try to write to the field). Best Regards, Chris]]> Chris Delahunt 2012-01-13T14:43:50-00:00
https://www.eclipse.org/forums/feed.php?mode=m&th=275924&basic=1
CC-MAIN-2020-24
refinedweb
209
63.9
Switching Between iOS Apps During a Test Smartphone users use on average 9 apps per day, and 30 apps per month, according to one recent report. If your app is lucky enough to be given such attention, what are the chances that it lives alone, with no integration to the rest of the user's smartphone experience? So many apps today provide value by integrating with other aspects of the mobile phone experience, even if it's just as simple as taking photos using the device's camera. Historically, testing these kinds. So, the test would look like this on a high level: - Launch the Photos app - Navigate to Camera Roll album - Determine how many photos are present, and store that number - Launch your app - Add and save photo by automating your app's UI - Switch back to the Photos app - Navigate to Camera Roll - Determine how many photos are present now - Verify that the number of photos present before has increased by 1 This is all possible to encode into your Appium scripts using two handy commands: mobile: launchApp and mobile: activateApp. We've seen launchApp before, in the Appium Pro article on testing app upgrades.); Simple, no? With Appium we can really pretend we are a user and do all the things a user would do in order to check the appropriate conditions. I won't go into detail in this edition about actually navigating the Photos app UI, nor does The App currently allow you to take photos and save them to the library, so filling out these specific steps will be left as an exercise to the reader. And chances are, you have a different requirement than verifying photo saving. So the thing to take away is the principle of using mobile: launchApp and friends to manage apps on the iOS device during a test. What's nice is that this particular strategy will work not only for simulators but also for real devices! So if you need to have a user login to your app via Facebook, or some other third-party credential authority, you can do so. As always, there's a full example up on GitHub. In this case, though, we just insert some clever Thread.sleeps instead of doing all the craziness with finding the number of photos and so on. Check it out here: import io.appium.java_client.ios.IOSDriver; import java.net.URL; import java.util.HashMap; import org.junit.Test; import org.openqa.selenium.remote.DesiredCapabilities; public class Edition013_iOS_Multi_App { private String APP = ""; private String PHOTOS_BUNDLE_ID = "com.apple.mobileslideshow"; private String BUNDLE_ID = "io.cloudgrey.the-app"; public void testMultiApps() throws Exception {); try { HashMap<String, Object> args = new HashMap<>(); args.put("bundleId", PHOTOS_BUNDLE_ID); driver.executeScript("mobile: launchApp", args); // Here is where we would navigate the Photos UI to get the number of Camera Roll photos Thread.sleep(1000); // Now reactivate our AUT args.put("bundleId", BUNDLE_ID); driver.executeScript("mobile: activateApp", args); // Here is where we would cause the new photo to be taken, edited, and saved Thread.sleep(1000); // Now reactivate the Photos app args.put("bundleId", PHOTOS_BUNDLE_ID); driver.executeScript("mobile: activateApp", args); // Here is where we would get the new number of Camera Roll photos, and assert that it // has increased by the appropriate number Thread.sleep(1000); } finally { driver.quit(); } } }
https://appiumpro.com/editions/13
CC-MAIN-2019-18
refinedweb
551
55.54
I want to refer to the variable of an object of a static nested class from the outer class. Would this work? public class GuiApp { static class book{ static book [] book = new book[1000]; static Boolean overdue; static Boolean checkedOut; static int bookNum; static String personName; static String dueDate; static int month; static int date; static int year; static String dateCheckedOut; } } and later to refer to the variable String personName of book[50] from the outer class for example book.book[50].personName = "Bob"; I'm not sure if I'm understanding this correctly so I want to know if this would work. Before accessing an element of that array : book.book[50].personName = "Bob"; You have to initialize that element : book.book[50] = new GuiApp.book(); I would also advise against using the same name for the class and the array. However, making all the properties of the book class static makes no sense, since it means that all the books would have the same values.
http://m.dlxedu.com/m/askdetail/3/5fb64dd9377bd77d707d5943ba037955.html
CC-MAIN-2018-30
refinedweb
167
62.58
Add simple documentation about union mounting in general and thisimplementation in specific.Signed-off-by: Jan Blunck <jblunck@suse.de>--- Documentation/filesystems/union-mounts.txt | 172 +++++++++++++++++++++++++++++ 1 file changed, 172 insertions(+)--- /dev/null+++ b/Documentation/filesystems/union-mounts.txt@@ -0,0 +1,172 @@+VFS based Union Mounts+----------------------++ 1. What are "Union Mounts"+ 2. The Union Stack+ 3. The White-out Filetype+ 4. Renaming Unions+ 5. Directory Reading+ 6. Known Problems+ 7. References++-------------------------------------------------------------------------------++1. What are "Union Mounts"+==========================++Please note: this is NOT about UnionFS and it is NOT derived work!++Traditionally the mount operation is opaque, which means that the content of+the mount point, the directory where the file system is mounted on, is hidden+by the content of the mounted file system's root directory until the file+system is unmounted again. Unlike the traditional UNIX mount mechanism, that+hides the contents of the mount point, a union mount presents a view as if+both filesystems are merged together. Although only the topmost layer of the+mount stack can be altered, it appears as if transparent file system mounts+allow any file to be created, modified or deleted.++Most people know the concepts and features of union mounts from other+operating systems like Sun's Translucent Filesystem, Plan9 or BSD.++Here are the key features of this implementation:+- completely VFS based+- does not change the namespace stacking+- directory listings have duplicate entries removed+- writable unions: only the topmost file system layer may be writable+- writable unions: new white-out filetype handled inside the kernel++-------------------------------------------------------------------------------++2. The Union Stack+==================++The mounted file systems are organized in the "file system hierarchy" (tree of+vfsmount structures), which keeps track about the stacking of file systems+upon each other. The per-directory view on the file system hierarchy is called+"mount stack" and reflects the order of file systems, which are mounted on a+specific directory.++Union mounts present a single unified view of the contents of two or more file+systems as if they are merged together. Since the information which file+system objects are part of a unified view is not directly available from the+file system hierachy there is a need for a new structure. The file system+objects, which are part of a unified view are ordered in a so-called "union+stack". Only directoties can be part of a unified view.++The link between two layers of the union stack is maintained using the+union_mount structure (#include <linux/union.h>):++struct union_mount {+ atomic_t u_count; /* reference count */+ struct mutex u_mutex;+ struct list_head u_unions; /* list head for d_unions */+ struct hlist_node u_hash; /* list head for seaching */+ struct hlist_node u_rhash; /* list head for reverse seaching */++ struct path u_this; /* this is me */+ struct path u_next; /* this is what I overlay */+};++The union_mount structure holds a reference (dget,mntget) to the next lower+layer of the union stack. Since a dentry can be part of multiple unions+(e.g. with bind mounts) they are tied together via the d_unions field of the+dentry structure.++All union_mount structures are cached in two hash tables, one for lookups of+the next lower layer of the union stack and one for reverse lookups of the+next upper layer of the union stack. The reverse lookup is necessary to+resolve CWD relative path lookups. For calculation of the hash value, the+(dentry,vfsmount) pair is used. The u_this field is used for the hash table+which is used in forward lookups and the u_next field for the reverse lookups.++During every new mount (or mount propagation), a new union_mount structure is+allocated. A reference to the mountpoint's vfsmount and dentry is taken and+stored in the u_next field. In almost the same manner an union_mount+structure is created during the first time lookup of a directory within a+union mount point. In this case the lookup proceeds to all lower layers of the+union. Therefore the complete union stack is constructed during lookups.++The union_mount structures of a dentry are destroyed when the dentry itself is+destroyed. Therefore the dentry cache is indirectly driving the union_mount+cache like this is done for inodes too. Please note that lower layer+union_mount structures are kept in memory until the topmost dentry is+destroyed.++-------------------------------------------------------------------------------++3. Writable Unions: The White-out Filetype and Copy-On-Open+===========================================================++The white-out filetype isn't new. It has been there for quite some time now+but Linux's VFS hasn't used it yet. With the availability of union mount code+inside the VFS the white-out filetype is getting important to support writable+union mounts. For read-only union mounts support neither white-outs nor+copy-on-open is necessary.++The white-out filetype has the same function as negative dentries: they+describe a filename which isn't there. The creation of white-outs needs+lowlevel filesystem support. At the time of writing this, there is white-out+support for tmpfs, ext2 and ext3 available. The VFS is extended to make the+white-out handling transparent to all its users. The white-outs are not+visible by the user-space.++-------------------------------------------------------------------------------++4. Renaming Unions+==================++Rename on union mounts has been handled in a lazy way: it returned -EXDEV.+This works well for dirctories but not for regular files. Even a kernel build+doesn't handle rename errors appropriate. Therefore when renaming regular+files from a lower layer of the union stack it is copied to the topmost+layer. If the file already resides on the topmost layer, the traditional+rename method is used.++-------------------------------------------------------------------------------++5. Directory Reading+====================++As mentioned, union mounts represent a single view of multiple directories as+if they are merged together. This is achieved by reading the contents of every+directory on the union stack and by merging the result. When the directory+listing is read via readdir() or getdents() system call, the union stack is+traversed from the topmost layer of the union stack to the lowermost.++Likewise with regular files, directories are seekable and the position of the+following read is marked by the file position filp->f_pos. When reading from+multiple directories, it is possible that the file position exceeds the inode+size of the first directory. Therefore the file position is rearranged to+select the correct directory in the union stack. This is done by substractiong+the inode size if the file position exceeds it and selecting the next member+of the union stack next.++This worked well with filesystems like ext2 that used flat file directories.+The directory entry offsets are arranged linear and are always smaller than+the inode size of the directory. Modern filesystems have implemented+directories differently and just return special cookies as directory entry+offsets which are unrelated to the position in the directory or the inode+size.++-------------------------------------------------------------------------------++6. Known Problems+=================++- currently it doesn't support seeking/readdir when d_off > i_size is possible+- readdir() is a file operation+- copyup() for other filetypes that reg and dir (e.g. for chown() on devices)++-------------------------------------------------------------------------------++7. References+=============++[1][2][3][4] Blunck <jblunck@suse.de>+Bharata B Rao <bharata@linux.vnet.ibm.com>-- -To unsubscribe from this list: send the line "unsubscribe linux-kernel" inthe body of a message to majordomo@vger.kernel.orgMore majordomo info at read the FAQ at
http://lkml.org/lkml/2007/7/30/181
CC-MAIN-2014-42
refinedweb
1,206
55.84
CodePlexProject Hosting for Open Source Software I am interested in getting started with Orchard, but haven’t had much luck so far with the only tutorial I could find. I could not get past the Creating the Initial Data Migration File step, it gave me a error CS1518 Expected class, delegate, enum, interface, struct, or union Is this tutorial still current? Is version 2.0 coming out soon, Would I be better waiting till version 2.0 before getting my hands dirty? Looking for a bit of guidance Thanks Can you show your code so we can see what is wrong? The tutorial is fine, nothing huge has changed in migrations in recent versions. i have messed with it a lot, i even tried atking out all code except for public class Migrations : DataMigrationImpl {} , but it still gives same error, i was thinging the error was in DataMigrationImpl. Thanks; } } } Are you sure the error is in this file ? This error message often occurs when there is an extra closing bracket or a problem like that. Yes i know, thats why i could not work it out, i opened in VS2010, and it did not show any errors. Look i just went back into the project and tried again and it compiled and ran, but when i added public int UpdateFrom1() { ContentDefinitionManager.AlterPartDefinition("ProductPart", builder => builder.Attachable()); return 2; } it erred again. this is the step that stoped me yesterday. I take it out again, back to where it last ran, and still get the error. Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately. Compiler Error Message: CS1513: } expected Source Error: Line 20: .Column("Sku", DbType.String) Line 21: .Column("Price", DbType.Single) Line 22: ); Line 23: Line 24: Line 20: .Column("Sku", DbType.String) Line 21: .Column("Price", DbType.Single) Line 22: ); Line 23: Line 24: Source File: c:\Sites\Orchard\Modules\SimpleCommerce\Migrations.cs Line: 22 Very strange; try cleaning and rebuilding your solution in VS2010. There shouldn't be anything wrong with the code, and certainly not with core parts of Orchard like DataMigrationImpl (which works for all other modules). Do you have a full source enlistment? Best to get one from Codeplex if not. Yes maybe tomorrow, i will delete the lot and try again, what about version 2.0, is the an ETA, I was thinking of waiting till then? Are you sure you want to delete this post? You will not be able to recover it later. Are you sure you want to delete this thread? You will not be able to recover it later.
http://orchard.codeplex.com/discussions/279205
CC-MAIN-2016-44
refinedweb
450
75.2
Internal Design¶ Overview¶ Dask arrays define a large array with a grid of blocks of smaller arrays. These arrays may be actual arrays or functions that produce arrays. We define a Dask array with the following components: - A Dask graph with a special set of keys designating blocks such as ('x', 0, 0), ('x', 0, 1), ...(See Dask graph documentation for more details) - A sequence of chunk sizes along each dimension called chunks, for example ((5, 5, 5, 5), (8, 8, 8)) - A name to identify which keys in the Dask graph refer to this array, like 'x' - A NumPy dtype Example¶ >>> import dask.array as da >>> x = da.arange(0, 15, chunks=(5,)) >>> x.name 'arange-539766a' >>> x.dask # somewhat simplified {('arange-539766a', 0): (np.arange, 0, 5), ('arange-539766a', 1): (np.arange, 5, 10), ('arange-539766a', 2): (np.arange, 10, 15)} >>> x.chunks ((5, 5, 5),) >>> x.dtype dtype('int64') Keys of the Dask graph¶ By special convention, we refer to each block of the array with a tuple of the form (name, i, j, k), with i, j, k being the indices of the block ranging from 0 to the number of blocks in that dimension. The Dask graph must hold key-value pairs referring to these keys. Moreover, it likely also holds other key-value pairs required to eventually compute the desired values: { ('x', 0, 0): (add, 1, ('y', 0, 0)), ('x', 0, 1): (add, 1, ('y', 0, 1)), ... ('y', 0, 0): (getitem, dataset, (slice(0, 1000), slice(0, 1000))), ('y', 0, 1): (getitem, dataset, (slice(0, 1000), slice(1000, 2000))) ... } The name of an Array object can be found in the name attribute. One can get a nested list of keys with the .__dask_keys__() method. Additionally, one can flatten down this list with dask.array.core.flatten(). This is sometimes useful when building new dictionaries. Chunks¶ We also store the size of each block along each axis. This is composed of a tuple of tuples such that the length of the outer tuple is equal to the number of dimensions of the array, and the lengths of the inner tuples are equal to the number of blocks along each dimension. In the example illustrated above this value is as follows: chunks = ((5, 5, 5, 5), (8, 8, 8)) Note that these numbers do not necessarily need to be regular. We often create regularly sized grids but blocks change shape after complex slicing. Beware that some operations do expect certain symmetries in the block-shapes. For example, matrix multiplication requires that blocks on each side have anti-symmetric shapes. Some ways in which chunks reflects properties of our array: len(x.chunks) == x.ndim: the length of chunks is the number of dimensions tuple(map(sum, x.chunks)) == x.shape: the sum of each internal chunk is the length of that dimension The length of each internal chunk is the number of keys in that dimension. For instance, for chunks == ((a, b), (d, e, f))and name == 'x'our array has tasks with the following keys: ('x', 0, 0), ('x', 0, 1), ('x', 0, 2) ('x', 1, 0), ('x', 1, 1), ('x', 1, 2) Create an Array Object¶ In order to create an da.Array object we need a dictionary with these special keys: dsk = {('x', 0, 0): ...} a name specifying which keys this array refers to: name = 'x' and a chunks tuple: chunks = ((5, 5, 5, 5), (8, 8, 8)) Then, using these elements, one can construct an array: x = da.Array(dsk, name, chunks) In short, dask.array operations update Dask graphs, update dtypes, and track chunk shapes. Example - eye function¶ As an example, lets build the np.eye function for dask.array to make the identity matrix: def eye(n, blocksize): chunks = ((blocksize,) * (n // blocksize), (blocksize,) * (n // blocksize)) name = 'eye' + next(tokens) # unique identifier dsk = {(name, i, j): (np.eye, blocksize) if i == j else (np.zeros, (blocksize, blocksize)) for i in range(n // blocksize) for j in range(n // blocksize)} dtype = np.eye(0).dtype # take dtype default from numpy return dask.array.Array(dsk, name, chunks, dtype)
https://docs.dask.org/en/latest/array-design.html
CC-MAIN-2019-13
refinedweb
686
72.76
Even if a function is defined in the K&R style, I expect that the type conversion for the arguments should happen. However, the output from the test program is: int 9.42 int 2.97005e-12 flt 9.42 flt 9.42 #include <stdio.h> double mult_pi_usual(double v) { return v * 3.14; } double mult_pi_KR(v) double v; { return v * 3.14; } int main() { printf("int %g\n", mult_pi_usual(3)); printf("int %g\n", mult_pi_KR(3)); printf("flt %g\n", mult_pi_usual(3.)); printf("flt %g\n", mult_pi_KR(3.)); } As a declaration, the K&R style does not convey type information for checking at the call point. Consider the fact that a K&R function declaration (e.g. in a header) would be double mult_pi_KR(); and the double v is only visible within the function definition. For consistency across compilation units (not all will have visibility of the complete function definition), the type of the argument is not checked when calling the function. In your example, this means the compiler - at points where the function in CALLED - does not know that mult_pi_KR() accepts a double. So mult_pi_KR(3) does not promote 3 to double. The result of passing an int to a function expecting a double is actually undefined behaviour.
https://codedump.io/share/0987YfTUZb75/1/arguments-type-conversion-if-a-function-is-kampr-style-defined
CC-MAIN-2017-13
refinedweb
210
68.97
Migrating your code from v3 to v4¶ Web3.py follows Semantic Versioning, which means that version 4 introduced backwards-incompatible changes. If your project depends on Web3.py v3, then you’ll probably need to make some changes. Here are the most common required updates: Python 2 to Python 3¶ Only Python 3 is supported in v4. If you are running in Python 2, it’s time to upgrade. We recommend using 2to3 which can make most of your code compatible with Python 3, automatically. The most important update, relevant to Web3.py, is the new bytes type. It is used regularly, throughout the library, whenever dealing with data that is not guaranteed to be text. Many different methods in Web3.py accept text or binary data, like contract methods, transaction details, and cryptographic functions. The following example uses sha3(), but the same pattern applies elsewhere. In v3 & Python 2, you might have calculated the hash of binary data this way: >>> Web3.sha3('I\xe2\x99\xa5SF') '0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e' Or, you might have calculated the hash of text data this way: >>> Web3.sha3(text=u'I♥SF') '0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e' After switching to Python 3, these would instead be executed as: >>> Web3.sha3(b'I\xe2\x99\xa5SF') HexBytes('0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e') >>> Web3.sha3(text='I♥SF') HexBytes('0x50a826df121f4d076a3686d74558f40082a8e70b3469d8e9a16ceb2a79102e5e') Note that the return value is different too: you can treat hexbytes.main.HexBytes like any other bytes value, but the representation on the console shows you the hex encoding of those bytes, for easier visual comparison. It takes a little getting used to, but the new py3 types are much better. We promise. Filters¶ Filters usually don’t work quite the way that people want them to. The first step toward fixing them was to simplify them by removing the polling logic. Now, you must request an update on your filters explicitly. That means that any exceptions during the request will bubble up into your code. In v3, those exceptions (like “filter is not found”) were swallowed silently in the automated polling logic. Here was the invocation for printing out new block hashes as they appear: >>> def new_block_callback(block_hash): ... print "New Block: {0}".format(block_hash) ... >>> new_block_filter = web3.eth.filter('latest') >>> new_block_filter.watch(new_block_callback) In v4, that same logic: >>> new_block_filter = web3.eth.filter('latest') >>> for block_hash in new_block_filter.get_new_entries(): ... print("New Block: {}".format(block_hash)) The caller is responsible for polling the results from get_new_entries(). See Asynchronous Filter Polling for examples of filter-event handling with web3 v4. TestRPCProvider and EthereumTesterProvider¶ These providers are fairly uncommon. If you don’t recognize the names, you can probably skip the section. However, if you were using web3.py for testing contracts, you might have been using TestRPCProvider or EthereumTesterProvider. In v4 there is a new EthereumTesterProvider, and the old v3 implementation has been removed. Web3.py v4 uses eth_tester.main.EthereumTester under the hood, instead of eth-testrpc. While eth-tester is still in beta, many parts are already in better shape than testrpc, so we decided to replace it in v4. If you were using TestRPC, or were explicitly importing EthereumTesterProvider, like: from web3.providers.tester import EthereumTesterProvider, then you will need to update. With v4 you should import with from web3 import EthereumTesterProvider. As before, you’ll need to install Web3.py with the tester extra to get these features, like: $ pip install web3[tester] Changes to base API convenience methods¶ Web3.toDecimal()¶ In v4 Web3.toDecimal() is renamed: toInt() for improved clarity. It does not return a decimal.Decimal, it returns an int. Removed Methods¶ Disambiguating String Inputs¶ There are a number of places where an arbitrary string input might be either a byte-string that has been hex-encoded, or unicode characters in text. These are named hexstr and text in Web3.py. You specify which kind of str you have by using the appropriate keyword argument. See examples in Type Conversions. In v3, some methods accepted a str as the first positional argument. In v4, you must pass strings as one of hexstr or text keyword arguments. Notable methods that no longer accept ambiguous strings: Contracts¶ Personal API¶ w3.personal.signAndSendTransaction is no longer available. Use w3.personal.sendTransaction() instead.
https://web3py.readthedocs.io/en/latest/v4_migration.html
CC-MAIN-2019-09
refinedweb
696
60.11
Adds specific features to the generic definition : PrintTrace is adapted. More... #include <Transfer_FinderProcess.hxx> Adds specific features to the generic definition : PrintTrace is adapted. Sets FinderProcess at initial state, with an initial size. Returns the Model which can be used for context. In the list of mapped items (between 1 and NbMapped), searches for the first mapped item which follows <num0> (not included) and which has an attribute named <name> The considered Attributes are those brought by Finders,i.e. by Input data. While NextItemWithAttribute works on Result data (Binders) Hence, allows such an iteration for (num = FP->NextMappedWithAttribute(name,0); num > 0; num = FP->NextMappedWithAttribute(name,num) { .. process mapped item <num> } Prints statistics on a given output, according mode. Specific printing to trace a Finder (by its method ValueType) Reimplemented from Transfer_ProcessForFinder. Sets an InterfaceModel, which can be used during transfer for instance if a context must be managed, it is in the Model. Returns a TransientMapper for a given Transient Object Either <obj> is already mapped, then its Mapper is returned Or it is not, then a new one is created then returned, BUT it is not mapped here (use Bind or FindElseBind to do this)
https://dev.opencascade.org/doc/occt-7.6.0/refman/html/class_transfer___finder_process.html
CC-MAIN-2022-27
refinedweb
198
54.02
23 Years of Culture Hacking With Perl 99 99 Modern Perl writes "Larry Wall, the creator of Perl, reflects on Perl's history of hacking its culture, from subverting the reductionist culture of Unix to reinventing the ideas of programming language and culture in Perl 6 and the verbal aikido used to encourage honest detractors to become valuable contributors. Perl turned 23 years old last week, and Perl 6 is available." Perl6 (Score:2) The only requirement is that you know how to be nice to all kinds of people (and butterflies) Reading the Perl 6 page - either they are REAL programmers, or they use emacs. Re:Perl6 (Score:4) Mind you, I'd be thrilled to see some nice new stuff in the Perl space. But I work on a software appliance and some of the customers pay tens of thousands of dollars (or more) for it and they do expect a modicum of reliability.... Re:Perl6 (Score:5, Interesting) I've been playing around with Perl 6 a little this week. Rakudo works well enough that I'll be using Perl 6 where I've previously been using Perl. I find it useful to follow the Perl 6 Planet, as it has a bunch of Perl 6 developers' perspectives and musings as they use the langauge. (For example, one guy wrote his blogging engine in Perl 6, and commented on speed differences between a couple Perl 6 implementations.) I'm also helped that Larry Wall has been doing active code review of the Perl 6 code [rosettacode.org] over on Rosetta Code, a site I run; it's nice to have an active source of idiomatic code for understanding the language. Esspweb (Score:1) Yeah, now try hiring for it. (Score:5, Interesting) (Hiring ~4 OO software engineers to do Perl. [newtonsoftware.com] Forgive the inane outsourced hiring-management site. Merry Christmas.) Re: (Score:1) Why bother limiting it by language? We're a perl shop, and don't really require any applicants to know Perl to come in through the door. Bonus points for knowing functional languages, SmallTalk, Scala, whatever. There is ramp-up for people to pick up Perl, but if they're good developers it's a pretty negligible period of time. It takes a lot longer to get people to understand the ideas of functional programming they can incorporate in that makes the code significantly easier to use, write and test. Re: (Score:3) Re:Yeah, now try hiring for it. (Score:4, Interesting) Re:Yeah, now try hiring for it. (Score:4, Insightful) Don't be too hard on the recruiter. All his training puts the highest priorities on "skills", and very specific experiences. He wouldn't know a great coder from a good liar who feels that spreadsheet macros are his limit. A person like that shouldn't have been given the job of screening applicants. It's not his fault, it's the fault of management for delegating this crucial function to someone who lacks the background to judge the technical merits of applicants. What tools he has left for making judgments are weak, but it's all he has, so he uses them. And it's all our faults for focusing far too much on specific languages. We all know that anyone who is good at several programming languages is not going to have a problem picking up a new one. Even programming paradigms are not the big deal they make them out to be. OOP and Functional Programming are not that profound or mysterious. Lot of what is being called functional programming is actually modular programming. But you can't tell any of that to the interviewers. Have to tailor your resume and give yourself a crash course on whatever it is they say they want so you can answer the trivia questions they're using to screen people. I use Perl, but I sure don't have something like all the operators memorized. That's what a reference manual is for, and I have found the Camel book an excellent one. It never ceases to amaze me that so many companies treat the search for talent as little more than a rigged lottery. Head hunting agencies are even worse. They come up with the craziest, completely subjective, off-the-wall reasons for rejecting people, and then complain that they can't find talent. "Learning on the job" is so pre 1980. "Hit the ground running" or "don't let the door hit your ass on the way out" is the way things have been for a long time now. And they don't want competence alone. Many also seek signs that their choice won't leave, and can be pressured to work harder, maybe has something in the closet that shows he understands the "realities" of doing business and so will not make any trouble for management, by, say, doing any whistleblowing. They want a contradiction-- competence at the job, and incompetence at personal finances so that the employee cannot leave without losing everything. Makes the employee more "reliable". Cue the job postings for 5 years of experience in Perl 6. Re: (Score:3) Re: (Score:2) Yeah, I think in hiring that HR need to be focussing on where their skills lie, i.e. not trying ascertain useful technical skills when they lack a sufficient background to do so. I remember my first tech job interview. The HR guy in that case doubted I had the skills to go in to an entry level tech support job, despite my having a a CS degree behind me and a decent background in Unix-likes and Windows systems. Oddly enough after doing tier one for a while I moved on to server, hardware and pro video support Re: (Score:1) Re: (Score:1) Have you considered hiring good developers and then teaching them OO Perl? If your workplace uses Moose [cpan.org], for example, writing good OO Perl 5 is surprisingly easy and effective. The Moose description says bad things about Perl. (Score:2) The implication is that, without Moose, Perl 5 is difficult, inconsistent, and tedious. Is this mistake, "... you can to think more...", indicative of the quality control for Moose? Re: (Score:2) That inference may go too far. Perl 5's default OO is flexible and powerful, but it goes too far in allowing flexibility and it doesn't promote an obvious best way for most projects. As with any abstraction which offers and takes advantage of defaults, Moose reduces complexity and makes it easier to write consistent and concise code. I'm certain many CPAN contributors will welcome an Re: (Score:1) A little unfair. Without using a framework like Moose (or Mouse even), Perl OO is less consistent (TMTOWTDI) and a bit harder. Moose automates and simplifies things like class accessors etc. so one could say Perl OO is also (potentially) more tedious without it. Re: (Score:1) After many years of excellent work, Perl is dying? (Score:2) "There's more than one way to do it." [wikipedia.org] translates to, quoting from Wikipedia, "This makes it easy to write extremely messy programs..." Re: (Score:2) Perl is still alive and well on BSD systems :-) Although FreeBSD purged perl from core a long time ago so that people did not have two versions of perl, base and the version from ports for real work. Re: (Score:1) Re:After many years of excellent work, Perl is dyi (Score:5, Interesting) My experience has been largely: -if working on existing progress, continue in language it is already in -if working on new project, what's the language most comfortable for the most developers available Frequently, the answer continues to be perl, sometimes python, sometimes ruby. Usually, I can't be bothered to care. If it comes down to my call, currently I prefer: -If planning to use across many OS updates, perl5. Nice and stagnant, not screwing around with how it does things, perl6 threatens this. -If not expecting a lot of churn on the runtime but active development across random developers coming and going as available, python as it forces readability. -If expected to work in a barebones as possible generic windows, vbscript, but please no. -If wanting to work with as few prereqs as possible on Windows server 2008r2/7, then powershell. -Have gone along with ruby, but have not personally found the magic situation I personally prefer it for above all other possibilities. Re: (Score:2) I think Ruby beats Python in features only in rare cornercases, which aren't that hard to do Python either. When you already know Python there's not much motivation to learn Ruby. They're too similar. Re: (Score:2) This is my experience as well. However, in my case the definition of project is a bit loose: - Someone wrote a script in perl and left the company. - Someone else needs to make Improvements to this code but they dont know perl. Even though the original code is written in as clear and readable perl as possible, they automatically think perl is hard. This is in fact company policy now. They write a python script and make a system call to it from the perl code. Soon there are two, three... seven python calls in Re:After many years of excellent work, Perl is dyi (Score:5, Interesting) My recent experience is that discussions of Perl quickly turn to discussions of Python, after people make statements like, "If it weren't for CPAN, Perl would be dead." That's not too far from the truth, if you understand that statement to be analogous to "If it weren't for the US dollar, the American economy would be dead." It may only be one thing, but it's a pretty big thing. "There's more than one way to do it." [wikipedia.org] translates to, quoting from Wikipedia, "This makes it easy to write extremely messy programs..." No grasshopper, you fundamentally misunderstand the implications of that statement. Show me a problem in which there isn't more than one way to do it, and I'll show you a problem you haven't grokked properly yet. Perl is a language without ideology. If programming languages were religions, perl would be closer to atheism (sorry Larry) than to anything else. Yes, it sometimes does cast people adrift because they're forced to accept that there is no final arbiter, that sometimes choices do come down to indulging one's biases. The difference here is that we recognise that, and that you have no one to blame for the biases except yourself. For a good programmer, this is one of the paths to enlightenment. To abuse the ideology metaphor a little further, perl is democratic (and borderline anarchic) because it does not criminalise stupidity. Likewise, it doesn't always protect you from yourself. If you really want to do things a certain way, the language probably won't stop you, and might even help you. And if you still don't get the freedom that perl provides, feel free to vacate the green space in front of my domicile. I'm not going to force you off, but I might laugh at you if you stay. Re: (Score:2) Re:Yeah, now try hiring for it. (Score:4, Informative) If you're looking for Perl 6 coders, you might try their IRC channel, #perl6 on Freenode [perl6.org]. Re: (Score:2) Perl software development is a seller's market, and that job ad is rubbish and fails to pique interest. It's a bland description with no indication of benefits or salary on offer. In fact, it's even less detailed than the crap Perl job ads that pimps spam me with me on a daily basis. Lack of detail implies there is little good to say about the job. Is that the impression you want to give? Answer this simple question: Why the bloody hell should I quit my current gig and come and work for you? Then put that an Re: (Score:3, Informative) I've been a build engineer since the mid-80's. My first exposure to Perl was in 1989. The last line of Perl I wrote was in 2005. I spent a year deciding on which direction to go... Python or Ruby. I went with Ruby as my primary scripting language, and have brought Ruby and Rails into 5 companies to build engineering infrastructure. The reason I went with Ruby was due to its simplicity, power, DSL support, and Rails, and both the Ruby and Rails community. In Silicon Valley I found that when working with peop Re: (Score:2) Re: (Score:2) Well, I would say it's not too surprising for a different reason: perl 5's support for OO is ugly and bolted on, so anybody who's a real enthusiast for OO probably isn't using perl. Although perl 6 is designed so that OO isn't ugly and bolted on, perl Re: (Score:1) If Perl 5's default OO is the wrong choice, how is Python's OO the right choice? Syntactic differences aside, they're the same system. Re: (Score:2) If Perl 5's default OO is the wrong choice, how is Python's OO the right choice? Syntactic differences aside, they're the same system. Syntactic sugar is important. Another difference is that in python, ruby, and perl 6 everything is an object, but in perl 5 everything is not an object. I can see various design trade-offs inherent in the everything-is-an-object decision, but, e.g., in ruby one big benefit is that the namespace is clean and the structure of the libraries is very logical and easy to understand. Cf. perl 5, where basically you just have a ton of functions that are thin wrappers for everything in the traditional C/Unix toolbox Re: (Score:2) Blekko's search engine and NoSQL database are written in Perl. We haven't had problems hiring experienced, smart Perl people, and we've also had no trouble getting experienced Python people to learn Perl. Re: (Score:3) Large OO Perl systems tend to be complex, slow sacred cows into which people who should have known better invest their careers. Arguing for total replacement of old VB applications is easy, but there is always great reluctance to rip out Perl messes. Only a desperate or foolish person would want to accept an invitation to someone else's Perl horror show. Once the people responsible for the Perl disaster leave, it will be easy to find people interested in engineering something that isn't rubbish. Ruby? Really? (Score:2) Ruby has all the mindshare these days. I think I've heard of Ruby. Wasn't that popular around 2005? Seriously, all the mindshare? Really? Perl (Score:5, Funny) Re:Perl (Score:5, Funny) Yes, the last 40% was purely gratuitous. Re: (Score:2) That's not a really ofuscated construct. If you know the common 1-character variables, then you know $@, as that is one of the most commonly used ones. I like the sense of humour displayed by the programmer; but his joke is a bit misaimed, as it only reinforces the standard stereotype of Perl. For the non-Perl programmers here: $@ is the variable holding the return code of the most recently called function. This return statement thus returns the boolean negated version of that code. The ; ends the return stat Re: (Score:1) sub check { my $ip = shift; eval{ &lib::function($ip) }; return !$@; } So if $@ is null it returns true. Otherwise false since ! is a condition operator. And they can do false by calling "die" in that lib::function. But yes, that is rather silly. I'm hoping they couldn't control the other code for some reason. Re: (Score:1) I simplified. Of course $@ is set by eval, but that requires a bit more in-depth explanation than I was willing to give. Of course, this being slashdot, there'd have been someone along to provide that anyway. Thanks. Mart Re: (Score:1) The only language that looks the same before and after RSA encryption. In typical programming, when a comment block accompanies some procedure explaining what that does, this comment is a short paragraph and the code - a bulky flowing construct. Perl, on the other hand, is very dense and with many idiosyncrasies. For example: There is another art characterized by terse, overloaded semantics, tenuous connotations. It is called poetry. Not everyone can write poetry. Not everyone ca Re: (Score:1) outside of =()=, I find that code to be pretty simple: $a bitwise xor $b (thus the result contains \0 in each char that is the same) regex looking for null chars in a string thus this returns a list of null chars My guess is that this =()= set of operators causes the $n variable to be the result of the list evaluated in scalar context (resulting in the length of this list). Indeed if you look closely you can see that that is 2 assignment operators and an empty list. You could rewr Re: (Score:2) I'm always struggling with forcing context, but surely this could have been written as ($n) = ($a ^ $b) =~ /\0/g;? By parenthesizing $n you'd force list context, right? Mart Re: (Score:2) Oh bugger. Of course you're right; the object of the given example is to have the final evalution in scalar context, to get the length of the intermediate list. See what I mean about struggling with forcing context? Mart Re: (Score:3) In typical programming, when a comment block accompanies some procedure explaining what that does, this comment is a short paragraph and the code - a bulky flowing construct. Perl, on the other hand, is very dense and with many idiosyncrasies. For example: Yes, but you do not have to write it like this. You can choose a more readable, more explicit way to write this in Perl. I always try to avoid excessive cleverness when I write code; one reason is that I'll forget what it does, and have to figure out all over again. Trying to squeeze as much trickery as you can into a single line of code is just a kid's game. Re: (Score:2) The only language where comic book swear words will beat you at tic-tac-toe. Perl Golf (Score:2) If you don't know what perl golf is, time to treat yourself to some mind blowing perl. Perl golf is a challenge to complete a give set of algorithms in the fewest (key) strokes. Consider the Buroughs Wheeler algorithm, which is what bzip uses. How many keystrokes should that take to write? how about 55? [sourceforge.net] Mind blowing. Also informative as well. I love perl. It has it's problems but I love how it's such a mutable language and how simple the meh (Score:1) Re: (Score:2) Since you're so sure of yourself, you should have no problem explaining what's worse about it, right? I love Perl, but (Score:3, Insightful) The thing that kills me about the Perl culture is that the delusions of what things mean to the non-Perl world. This article is yet another example of that. Larry writes about Camelia representing so many points, which sound fantastic but are complete bollocks. Perl6.org, and specifically Camelia, do not say "fun", or anything about sterile environments or anything about clarity. What it says is that in 23 years, the old Perl guard still hasn't figured out that making something that looks completely stupid makes people think you are completely stupid. Everything looks completely stupid that comes out of Perl6. Nobody really even knows what Perl6 is (even O'Reilly) and then randomly people point out Rakudo Star. This looks like the community is fractured (which it isn't, but it looks that way at a glance, which is all people are getting.) I'm saying all this as a Perl hacker. I do love Perl, I think it's great, but all of this is basically turning Perl into something like Furries. The people involved seem to not think there is anything wrong, but every other person in the world makes faces at them. I can't imagine being involved in that good thing Scala really is all those things Larry wishes Camelia represents. Re: (Score:2) I question this. The argument that "No one will ever take a programming language seriously because it has a cartoon butterfly for a logo! Are you six years old?" says a lot more about the arguer than the logo or the language or the community. At least it suggests to me that I would not enjoy working with the person making that argument. Re: (Score:1) Well, if that was actually what I said you may have a point. Unfortunately that wasn't what I said, nor what I intended. My point is simple: The Perl (specifically the old guard) community constantly puts out statements that only the Perl community understands or agrees with. In this case, it's "Camelia represents fun, organic growth, clarity, etc." that is being proffered as a statement of intention. Camelia, like most Perl endeavors, fails to represent those things. It completely astounds me that so many smar Re: (Score:1) Perhaps to you. Do you speak for everyone outside of what you've defined as "the Perl community"? Re: (Score:2) I'm outside the Perl community and I agree with him. Maybe you should get out more often? Re: (Score:1) I'm sure some people agree with that sentiment. I don't agree that most or all people do. Re: (Score:2) If you use dog shit for an envelope, nobody wants to read the letter. Butterflies are widely regarded as more pleasant than dog shit. Re: (Score:2) Given the large number of flies[1] that exist, I doubt that is actually true. [1] the non-butter variety. Re: (Score:3) The grinch detector seems to be working well here. Re: (Score:1) Agreed. My first thought when I saw Camelia was: "That looks dumb, oh well." But when I first saw a post complaining about it I suddenly saw her as the most beautiful thing in modern programming. (Runner up: colon syntax used with closure arguments. JS needs this.) Rambling, barely coherent, self-indulgent. (Score:4, Insightful) I suppose I learned a lot about the Perl community though. Re:Rambling, barely coherent, self-indulgent. (Score:5, Insightful) I suppose I learned a lot about the Perl community though. Larry may sound glib most of the time, but if you took the time to look, you'd see method in his madness. He chooses to make his points lightly, because that's an important part of the message. Perl as a language is designed to reflect the idiosyncrasies of the human brain. It treats dogmatism as damage and routes around it. As Larry wrote, it is trollish in its nature. But its friendly, playful brand of trollishness is what allows it to continue to evolve as a culture. Strip away the thin veneer of sillyness and you'll see that everything I've written has been lifted directly from Larry's missive. Just because he likes to act a little silly doesn't mean he's wrong. One of the worst things a programmer can do is invest too much ego, pride or seriousness in his work. That is the path to painfully over-engineered, theoretically correct but practically useless software that often can't survive a single revision. Perl as a language isn't immune to any of these sins, but as a culture, it goes to some lengths to mitigate against them. Re: (Score:2) Perl as a language is designed to reflect the idiosyncrasies of the human brain. I call shenanigans. Did a quick Google search. The only page I could find using words vaguely like these to refer to Perl is this one. (Isn't Google amazing? It's already indexed this article thread....) So, you're telling us that as Perl grew from a simple string manipulating scripting language, Larry built into its design syntax and methods which mirror the way programmers' wetware minds work? That is... grandiose... to say the least. He may say TMTOWTDI, but he (apparently) doesn't say Perl is designe Surprised nobody mentioned yet (Score:5, Insightful) Re: (Score:2) And it was written by the other 999 monkeys. (The other one eventually wrote a Java program). Re: (Score:2) I tried looking at slashcode once, out of curiosity. It's a scary dark place and I'm not going back there again. Re: (Score:1) That /. is written in Perl. Ah. This explains a lot. stability and culture (Score:4, Insightful) Re: (Score:3) When I first started working with this internet thingy, the options to do anything with user data was your choice of C or Perl. Then I moved on to PHP because that was what a lot of projects and people where using. That's what we did our rapid development of our web app in was MySQL and PHP. A lot of that had to do with the initial client and what they had available on their hosting server. Once the proof of concept was signed off on and we had our funding for the final production product we had the gre Re: (Score:1) I have perl scripts that date to 1988 or so (perl 1-2 era or 5 jobs ago). By and large most of these have worked over time, but in the mid-90's I did need to edit a few scripts to put a backslash in front of the @ inside of strings. Yes, in many of my .pl libraries, I haven't bothered to change creating variables on the fly and using *pointers instead of using refs and other modern mechanisms. On one of the camera groups, I mentioned I had perl scripts to manage my images, from download to album creati Scary (Score:4, Informative) So I looked at the Perl5To6 Manual, and it gave me a headache. Really, I had to get some medicine just now. There used to be 10 ways to do anything in Perl 5, and in Perl 6 there's 20. And operators are approaching APL in obscureness and number. It has ways of being even more terse at the expense of the maintainer's head possibly exploding. Some changes are very nice and clean up some weirdness, but they compensated for it with a vengeance. There's macros, and more contexts (where function returns different things depending on how its value is getting used), and meta-operators, and operator overloading on never-before-seen scale, and weird variant types, and ways to embed an enum into any object, even more complicated regular expressions, and so on ... your a noob if you dont answer in perl compilable (Score:1) Re: (Score:1) !#//bin/local/perl Unless I missed the funny part of your message, that line is actually interpreted by the shell. Misleading, Perl 6 is NOT available, not done yet (Score:2) Re: (Score:2) Go ahead and whine all you want. We'll be right over here using the language you pretend doesn't exist. Re: (Score:1) Not whining, I've done plenty of Perl 5 development over the last 20 years. Sorry to see Larry try to turn Perl 6 into mutant Swiss Army Knife with fold-out condom and umbrella and eggbeater and cuckcoo clock. the guts of a thousand whales fed through a wood chipper.... Re: (Score:2) Perl 6 spec is still in development, not done yet. Rakudo is an implementation of something that is not done yet, and pugs even less so. Anyone who uses this for any remotely production related is insane. Face it folks, Larry killed Perl. I usually do not use the very latest version of anything on a critical project. The only reason to do this is if the new version has a feature you absolutely cannot do without. Even then, you should be aware that you're taking a big risk. I'd wait for it to age a bit, and maybe use the last known stable version, while other people try out the new stuff. That being said, I find your comment to be a bit on the panicky side. It's a bit early for an obit on Perl. Perl sadly out of fashion, politically incorrect (Score:3) ah, Perl (Score:2) The language that was better than awk+shell. Didn't have much more going for it than that.
http://developers.slashdot.org/story/10/12/24/1934221/23-Years-of-Culture-Hacking-With-Perl
CC-MAIN-2015-27
refinedweb
4,823
72.16
Summary: Microsoft Scripting Guy, Ed Wilson, talks about using Windows PowerShell to report and set monitor brightness. Microsoft Scripting Guy, Ed Wilson, is here. Today I was exploring the Root/WMI namespace in Windows Management Instrumentation (WMI) on my Windows 8 laptop. I happened to run across a few WMI classes that I had not messed around with before. I like to use the Get-CimClass cmdlet from Windows PowerShell 3.0 for this kind of explorations because it supports tab completion and other features that make this exploration easy. So I was initially looking for anything related to monitors. And as I looked at what scrolled by, I saw that there were classes related to monitor brightness. So I decided to modify my query a bit to include things related to monitor brightness. I derived the following command, and achieved the results shown here: PS C:\> Get-CimClass -Namespace root/WMI -ClassName *monitorbrightness* NameSpace: ROOT/wmi CimClassName CimClassMethods CimClassProperties ------------ --------------- ------------------ WmiMonitorBrightnessEvent {} {SECURITY_DESCRIPTOR, TI... WmiMonitorBrightness {} {Active, CurrentBrightne... WmiMonitorBrightnessMethods {WmiSetBrightness... {Active, InstanceName} I thought I would try to query the WmiMonitorBrightness WMI class first because it looks like it would report first. So I edited my previous line and changed from Get-CimClass to Get-CimInstance. Here is the command, and the output associated with the command: PS C:\> Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness Active : True CurrentBrightness : 100 InstanceName : DISPLAY\LEN40B2\4&3062e51&0&UID67568640_0 Level : {0, 1, 2, 3...} Levels : 101 PSComputerName : So without any reference material, I can see that the current brightness of my laptop monitor is 100. This is probably a percentage setting. I connect to MSDN, and look up WmiMonitorBrightness class. Sure enough it is the current brightness of the monitor as a percentage. The Level property lists supported values for CurrentBrightness. I check it by piping the results to the Select-Object cmdlet. Here is a sample of the output: PS C:\> Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness | select -ExpandProperty level 0 1 2 3 4 <truncated> The strange thing is that Level lists how many different levels are available. The value of 101 makes sense because Level begins with 0 and ends with 100. To set the brightness on my laptop display monitor, I figure I can use the WmiMonitorBrightNessMethods WMI class. While I have MSDN open, I check out WmiMonitorBrightnessMethods class, and it appears that I will be able to use it to set my monitor brightness: PS C:\> Get-CimClass -Namespace root/WMI -ClassName WmiMonitorBrightnessMethods NameSpace: ROOT/WMI There are only two properties: Active and InstanceName. I decide to look at them. Here is the result: PS C:\> Get-CimInstance -Namespace root/WMI -ClassName WmiMonitorBrightnessMethods Active InstanceName PSComputerName ------ ------------ -------------- True DISPLAY\LEN40B2\4&3062e5... So, the WmiMonitorBrightnessMethods WMI class looks like it might be useful. Now, I want to look at the method information in more detail: PS C:\> $wmi.CimClassMethods Name ReturnType Parameters Qualifiers ---- ---------- ---------- ---------- WmiSetBrightness Boolean {Brightness, Time... {Implemented, Wmi... WmiRevertToPolicyB... Boolean {} {Implemented, Wmi... WmiSetALSBrightnes... Boolean {State} {Implemented, Wmi... WmiSetALSBrightness Boolean {Brightness} {Implemented, Wmi... I see that there are four methods for the WmiMonitorBrightnessMethods class. The method that looks like it is the best one for my needs is the WmiSetBrightness method. It takes two parameters that I want to look at in more detail. So I adjust my query to focus on it. I use the Item method to specify which method I want to look at. The command is shown here: PS C:\> $wmi.CimClassMethods.Item('wmiSetBrightness') Name ReturnType Parameters Qualifiers But the parameters information is still truncated. So I add Parameters to the end of my query and arrive at the following: PS C:\> $wmi.CimClassMethods.Item('wmiSetBrightness').parameters Name CimType Qualifiers ReferenceClassName ---- ------- ---------- ------------------ Brightness UInt8 {ID, in} Timeout UInt32 {ID, in} Cool. Now I know the two parameters that I need to use to call this method. Brightness is expressed as a percentage, and Timeout is expressed in seconds. I use the Get-WmiObject cmdlet to query the WmiMonitorBrightnessMethods WMI class, and store the returned object in a variable as shown here: $monitor = Get-WmiObject -ns root/wmi -class wmiMonitorBrightNessMethods Now, I call the WmiSetBrightNess method and specify that I want the monitor to be at 80% and request that it do so in 10 seconds. Here is the command: $monitor.WmiSetBrightness(80,10) Cool! It works. Not sure how I will use this, but it does work. Well, that is all there is to using the WMI classes to set monitor brightness., im new to powershell. When I run this command Get-Ciminstance -Namespace root/WMI -ClassName WmiMonitorBrightness It just says Get-Ciminstance : Not supported At line:1 char:1 Any ideas? @Retro according to MSDN msdn.microsoft.com/.../aa394536(v=vs.85).aspx it should work on Vista and Above. I ran this on my Windows 8 laptop (64 bit) and it works as indicated above. @Ed @retro It only works on systems that can dynamically set the brightness. This usually only laptops although some All-In-Ones may have this capability.. On my laptop this works. On my desktop it says "Not supported" which is correct because I cannot set the brightness from the OS. I can only do that on the monitor. Very few full monitors allow adjustment from the OS and only if you install the monitor driver. @JRV Great catch! It has been so long since I used an actual desktop, that I forget about them. Thank for testing this out! @Ed Coincidence but I ran through all of that only about two days before you posted it. I had to do a little thinking and research to see why and how it worked. If anyone has an HP All-In-One I suspect it will work on those. I believe they are mostly laptop technology on the desktop. Newer monitors are also supporting the 'auto-daylight-detect' feature that is in most laptops and adding it. Newer monitors can also run USB over the video path. Tis makes them available to self-install the driver and to support thumb drives, mice and keyboards. it's an everything-everywhere world. @Ed @Jrv Thanks. That explains it. It was confusing the heck out of me :) I started to try to use this, and then realized it only works on Windows 8 right now so is completely useless in the majority of companies until at least Windows 9 comes out.
http://blogs.technet.com/b/heyscriptingguy/archive/2013/07/25/use-powershell-to-report-and-set-monitor-brightness.aspx
CC-MAIN-2014-35
refinedweb
1,067
57.27
hwi_find_tag() Find a tag in the hwinfo structure Synopsis: #include <hw/sysinfo.h> unsigned hwi_find_tag( unsigned start, int curr_item, const char * tagname ); Since: BlackBerry 10.0.0 Arguments: - start - Where to start to search for the given item. For the initial call, set this argument to HWI_NULL_OFF. If the item found isn't the one that you want, pass the return value from the first call to hwi_find_tag() as the start parameter of the next call. This makes the search pick up where it left off. You can repeat this process as many times as required (the return value from the second call going into the start parameter of the third, etc). - curr_item - If this argument is nonzero, the search stops at the end of the current item (i.e. the one that start points to). If curr_item is zero, the search continues until the end of the section. - tagname - The name of tag to search for. Library: libc Use the -l c option to qcc to link against this library. This library is usually included automatically. This function is in libc.a, but not in libc.so (in order to save space). Description: The hwi_find_tag() function finds the tag named tagname. Returns: The offset of the tag, or HWI_NULL_OFF if the tag wasn't found. Classification: Last modified: 2014-06-24 Got questions about leaving a comment? Get answers from our Disqus FAQ.comments powered by Disqus
http://developer.blackberry.com/native/reference/core/com.qnx.doc.neutrino.lib_ref/topic/h/hwi_find_tag.html
CC-MAIN-2017-13
refinedweb
238
77.43
Catalyst - The Elegant MVC Web Application Framework # use the helper to start a new application catalyst.pl MyApp # add models, views, controllers script/myapp_create.pl model Database DBIC dbi:SQLite:/path/to/db script/myapp_create.pl view TT TT script/myapp_create.pl controller Search # built in testserver -- use -r to restart automatically on changes script/myapp_server.pl # command line testing interface script/myapp_test.pl /yada ### in MyApp.pm use Catalyst qw/-Debug/; # include plugins here as well} = MyApp: MyApp auto is called, then Foo auto, then this sub auto : Private { ... } # powerful regular expression paths are also possible sub details : Regex('^product/(\w+)/details$') { my ( $self, $c ) = @_; # extract the (\w+) from the URI my $product = $c->req->snippets->[0]; } See Catalyst::Manual::Intro for additional information. The key concept of Catalyst is DRY (Don't Repeat Yourself). See Catalyst::Manual for more documentation. Catalyst plugins can be loaded by naming them as arguments to the "use Catalyst" statement. Omit the Catalyst::Plugin:: prefix from the plugin name, i.e., Catalyst::Plugin::My::Module becomes My::Module. use Catalyst qw/My::Module/; Special flags like -Debug and -Engine can also be specified as arguments when Catalyst is loaded: use Catalyst qw/-Debug My::Module/; The position of plugins and flags in the chain is important, because they are loaded in exactly the order in which they appear. The following flags are supported: Enables debug output. Forces Catalyst to use a specific engine. Omit the Catalyst::Engine:: prefix of the engine name, i.e.: use Catalyst qw/-Engine=CGI/; Forces Catalyst to use a specific home directory, e.g.: use Catalyst qw[-Home=/usr/sri]; Specifies log level.. See Catalyst::Request. Forwards processing to a private action. If you give a class name but no method, process() is called. You may also optionally pass arguments in an arrayref. The action will receive the arguments in @_ and $c->req->args. Upon returning from the function, $c->req->args will be restored to the previous values. $c->forward('/foo'); $c->forward('index'); $c->forward(qw/MyApp::Model::CDBI::Foo do_stuff/); $c->forward('MyApp::View::TT'); The same as forward, but doesn't return. Returns an arrayref containing error messages. my @error = @{ $c->error }; Add a new error. $c->error('Something bad happened'); Clear errors. $c->error(0); Returns the current Catalyst::Response object.. $c->stash->{foo} = $bar; $c->stash( { moose => 'majestic', qux => 0 } ); $c->stash( bar => 1, gorch => 2 ); # equivalent to passing a hashref # stash is automatically passed to the view for use in a template $c->forward( 'MyApp::V::TT' ); Contains the return value of the last executed action. Gets a component object by name. This method is no longer recommended, unless you want to get a specific component by full class. $c->controller, $c->model, and $c->view should be used instead. Gets a Catalyst::Controller instance by name. $c->controller('Foo')->do_stuff; Gets a Catalyst::Model instance by name. $c->model('Foo')->do_stuff; Gets a Catalyst::View instance by name. $c->view('Foo')->do_stuff; Returns or takes a hashref containing the application's configuration. __PACKAGE__->config({ db => 'dsn:SQLite:foo.db' }); Overload to enable debug messages (same as -Debug option). Returns the dispatcher instance. Stringifies to class name. See Catalyst::Dispatcher. Returns the engine instance. Stringifies to the class name. See Catalyst::Engine. Returns the logging object instance. Unless it is already set, Catalyst sets this up with a Catalyst::Log object. To use your own log class: $c->log( MyLogger->new ); $c->log->info( 'Now logging with my own logger!' ); Your log class should implement the methods described in the Catalyst::Log man page. Merges @path with $c->config->{home} and returns a Path::Classi's and with $c->namespace for relative uri's, then returns a normalized URI object. If any args are passed, they are added at the end of the path. Returns the Catalyst welcome HTML page. These methods are not meant to be used by end users. Takes a coderef with arguments and returns elapsed time as float. my ( $elapsed, $status ) = $c->benchmark( sub { return 1 } ); $c->log->info( sprintf "Processing took %f seconds", $elapsed );. Prepares message body. Prepares a chunk of data before sending it to HTTP::Body.. Starts the engine. Sets an action in a given namespace. Sets up actions for a component. Sets up components. Sets up dispatcher. Sets up engine. Sets up the home directory. Sets up log. Sets up plugins. Returns the stack. or speed things up a bit, Christian Hansen Christopher Hicks Dan Sully Danijel Milicevic David Kamholz David Naughton.
http://search.cpan.org/dist/Catalyst/lib/Catalyst.pm
crawl-002
refinedweb
761
53.27
Over: - How to manage this impact - How to minimize this impact where possible We use some very simplistic examples containing cars, tires, and windscreens and their related companies or resellers. Although not completely realistic, this is sufficient to describe suggestions to improve the maintainability of XML formats. To get started, let's use a Volvo C30 with Michelin tires as an example in which an XML file is created to share information about the tires. Listing 1 provides this example. Listing 1. A simple XML example file for sharing information about tires The XML file looks pretty simple, doesn't it? At a glance, you might not see any problems. Look deeper, though. The actual problems are in the XML schema. It turns out to be fairly large and monolithic. And then, consider that this XML format has only a few element types. Imagine how this might grow for a truly realistic example, as in Listing 2. Listing 2. An XML schema describing the simple XML format Now, before you say, "What's the big deal? Nobody looks at the XSD file," think about changes that might be required during the course of business. What if the tire XML needed to change to display the size of the tires, like this: A simple change like this means that the windscreen company gets a new XSD when anything changes in the tire format. Plus, it needs to modify its software to understand the XSD. That's not good. It adds extra work and expense for the windscreen company. The tire companies, too, receive a new XSD and might also need to update software to handle it, depending upon how the company writes its software. Perhaps nobody reads the XSD, but it sure can give big headaches to a lot of people. To avoid a monstrous XSD file, the solution is to give the tire and windscreen their own namespaces and separate XSD files. Listing 3 shows how to do that. Listing 3. The example XML file modified to contain namespaces If you do that and leave the rest of the car XML example intact, the XSD file becomes much shorter and easier to deal with. Most of the relevant information moves to other XSDs that are imported on top of the XSD. Now, when you look at the XSD file, it appears in modules, like Listing 4. Listing 4. The modified car XML schema importing separate XSDs for tires and windscreens Now, this is just one module of the XSD. The XSD file didn't really shrink as much as it appears here, but the more important point is that the XSDs are now modular and much easier to work with. As a result, you can change something in the tire format and distribute it to all tire companies without bothering windscreen companies with a change that doesn't affect them. Positive side effects of modules Modularity does much more than just help with the management of distributed maintainability problems. It also improves the re-usability of single elements. For example, suppose that the tire company produces tires for bicycles as well as for cars. The tire company might want to use the same tire XSD file to describe its bicycle tires. The bicycle company that buys these tires, however, does not want an XML schema describing a car, because most of the elements are irrelevant to a bicycle company. A common bicycle does not have a windscreen, for example. The bicycle companies want their own bicycle XSD that simply imports the tire XSD. In that scenario, the XML might look like Listing 5. Listing 5. An example XML file for a bicycle description reusing the tire XML format This is similar to the car XSD, in which the tire was imported, but it's specific to bicycles. Now, go back to the car for the next example. Managing the reality of modules Eventually, the car XSD not only imports a windscreen XSD and a tire XSD but also a motor XSD, a steering wheel XSD, a chair XSD, a paint XSD, and so on. This becomes difficult to manage. The solution to this problem is to include a separate XSD called parts.xsd that imports all the parts of the car. This way, when anything changes in the import list, only the parts.xsd file specifically meant to manage these dependencies changes. Listing 6 shows the entire example. Listing 6. The car XML schema replacing the list of imports with one include The parts.xsd file looks like Listing 7, however. Listing 7. parts.xsd: the list of imports to be included The practical advantage to using parts.xsd is that the list of XSD imports does not need to be copied through every XSD file that needs references to these parts. Instead, one inclusion is sufficient. As the number of elements and parts grows in a real-world problem, you also have more reason to be careful with your type definitions. For example, it is common—but risky—in XML formats to use unqualified attributes—that is, attributes that do not specifically belong to one namespace, as Listing 8 shows. Listing 8. An XML example with unqualified count attributes If you select elements based on an unqualified attributes, it becomes difficult to predict your results. For example, if you select all elements containing an attribute count whose value is 1 with the following XPath query, you couldn't predict which namespaces the results belong to: If you caught it, you actually can predict the namespaces, because the example is simple enough. But the point is, something like this can quickly grow out of proportion. The solution is to qualify each attribute with its specific namespace. Look at the subtle difference in the XML example in Listing 9. Listing 9. An XML example with qualified count attributes Luckily, this also means a very subtle difference in the XML schema, as you can see in Listing 10. Listing 10. The tire XML schema modified for qualified count attributes The effects might not be dramatic, but they are noticeable. It's a good habit to prevent possible conflicts whenever you can. Designing a more general format When you use an relational database as storage back end, the tendency is to make a one-on-one translation of the database tables or fields into XML constructs. Doing so limits modeling freedom but also infects other connecting parties with the limitations of the database, even when they do not use this database. The XML in Listing 1 is a good example of such a one-on-one translation from a relational database. Maybe you want your document to be modeled differently, however. You might, for instance, want a front-to-back layout of the car to make an automated drawing of all the parts. This could be described in the XML example shown in Listing 11, which you can use in an XSLT transformation to Scalable Vector Graphics (SVG). This is not extremely difficult, even though it might appear so at first glance. Here's how to create the XML file: Listing 11. An XML example in an alternative structure The car XSD now looks like Listing 12 (pay special attention to the complexType in the car element). Listing 12. The car XML schema describing an alternative structure Storing this file in a relational database and later retrieving the exact same XML document is more complicated. For these kind of purposes, NXD can be handy. Exist DB is a simple open source example of such an NXD. IBM DB2 Express-C is a free alternative that offers an integrated solution of a relational database and an XML database. It allows you to access the database with SQL or with pure XML technology like XQuery. Managing versions and documentation of XML schemas In many cases, it's perfectly fine for a group of companies to use multiple versions of the same XML schema at the same time. As long as you know which version you use and which elements changed in that version, you'll be okay. A good habit to get into is to use XSD's annotation elements to describe the version and element information. Annotations can contain two elements: documentation and appinfo. The documentation element speaks for itself—always document, and you'll rarely have regrets! More interesting is the appinfo element, because it can contain anything you like. For example, if you define your custom element version to contain a version of a specific element, the XSD looks like Listing 13. Listing 13. An example XML schema containing customized annotations Although the XSD parser doesn't know what to do with the custom version, these and similar custom attributes can greatly help manage XSDs within a larger group of organizations. After all, XML files and XML schemas are meant to be read by human readers as well as computers, so it is a good habit to treat XSDs that way. A final feature in XML schemas worth mentioning is the extension element. In the last section, you saw the extensibility of XSD's appinfo element. By default, this element is open to any content. Adding an extension element is a more restrictive way to extend types. The XSD file in Listing 14 describes how to extend the basicTire type to contain a size element. Listing 14. The tire XML schema containing an extension for a size element XML schema even allows you to specifically forbid extensions of the basicType if you desire. If you're interested in looking further into the XSD specifications, check Resources. You'll find a lot more interesting features in XML schema than we have room to dissect in this article. As you can see,. Learn - The basics of using XML schema to define elements (Ashvin Radiya, Vibha Dixit, developerWorks, August 2000): Learn more about XML schema. - Make your life easier with the XML schema Standard Type Library (Nicholas Chase, developerWorks, July 2007): Get tips on using the XML schema Standard Type Library. - Index of XML standards: Check out developerWorks' list of the most important XML standards. - - Exist DB: Download and explore an open source database management system. Exist DB is entirely built on XML technology, stores XML data according to the XML data model, and features efficient, index-based XQuery processing. - DB2 Express-C 9.5: Try out the reliability, flexibility, and power of this full-function relational and XML data server. -<<.
http://www.ibm.com/developerworks/xml/library/x-extensxml.html
crawl-002
refinedweb
1,746
62.27
Jul 13, 2015 10:25 AM|rudywilkjr|LINK When my OData service ASP.NET WebAPI 2.2 handles a Deep Insert request it processes the insertion perfectly. The master and linked entities all update appropriately. However, when the service responds it only includes the object information of the master entity. I found this Bug submitted to OASIS regarding this very matter and it turns out it has been fixed and released. Has this feature / version been implemented into .NET yet and is there any estimate on when we can start seeing this behavior in our .NET OData service projects? Thanks, -Rudy OData Participant 893 Points Jul 15, 2015 07:54 AM|Caillen Zhong|LINK Hi rudywilkjr, I'll involve some other engineers into your case, as I didn't find any docs or articles related to this problem and I'm not quite sure if this problem has been fixed yet. This will take some time, so please be patient. If there're any updates, we'll come back. Thanks for your understanding. OData Jul 15, 2015 08:22 AM|rudywilkjr|LINK Yup, the following is from the OData Version 4.0 Protocol documentation. This section is exactly what I'm attempting to see. Thanks! A request to create an entity that includes related entities, represented using the appropriate inline representation, is referred to as a “deep insert”. Media entities, whose binary representation cannot be represented inline, cannot be created within a deep insert. If the inline representation contains a value for a computed property or dependent property of a referential constraint, the service MUST ignore that value when creating the related entity. On success, the service MUST create all entities and relate them. If the request included a return Prefer header with a value of return=representation and is applied by the service, the response MUST be expanded to at least the level that was present in the deep-insert request. On failure, the service MUST NOT create any of the entities. OData Jul 24, 2015 06:16 AM|gtscdsi|LINK Hi rudywilkjr, Thank you post here. For a web api which support OData query/post, the deeper insert might be a litter different as your think. When you want to post or insert an entity through OData supported web api url the truth for this process is like following: So the interesting thing is if you want to deep insert an entity by OData supported web api url, all you need to care is model binding. But this is very simple and easy: public class OrderViewModel { public OrderViewModel() { Details = new List<OrderDetail>(); } public Guid Id { get; set; } public DateTime Date { get; set; } public Guid Customer { get; set; } public IList<OrderDetail> Details { get; set; } } public IHttpActionResult Post(OrderViewModel model) { if (!ModelState.IsValid) { return BadRequest(ModelState); } //TODO: Data mapper for view model to entity var order = new Order { Customer = model.Customer, Date = model.Date, Id = model.Id }; //TODO: entity validation here. _context.Orders.Add(order); //TODO:Should have data mapping for orderdetail and validation foreach (var detail in model.Details) { _context.OrderDetails.Add(detail); } //Save to database. _context.SaveChanges(); return Created(order); } I guess you may want to go through following link if you decided to use model binder: Best Regards, modelbinding OData DeepInsert Jul 24, 2015 08:32 AM|rudywilkjr|LINK I don't have any issue getting the Deep Insert to work. It does. However, when the service returns the Created(object) the related entities are not expanded to the same level they were present for the inserts. I feel like this should work without me having to custom code a model to fill & return. I feel like the "Created" function should handle this part of the OData protocol. Thanks, -Rudy modelbinding OData DeepInsert None 0 Points 7 replies Last post Jan 13, 2016 02:05 PM by reverseblade
https://forums.asp.net/t/2059370.aspx?OData+Deep+Insert+Response
CC-MAIN-2021-25
refinedweb
641
55.24
The book How to Design Programs1 introduces the concept of a function or program’s Design Recipe. I’ll quote the list here: - From Problem Analysis to Data Definitions - Signature, Purpose Statement, Header - Functional Examples - Function Template - Function Definition - Testing When I taught programming to teens with what is now called Bootstrap, we used the Design Recipe to help the students debug their own programs. We’d ask them “which step of the Design Recipe are you on?”, and get one of two answers: “I don’t know”, in which case we sent them back to step 1, or they’d tell us a step number and we’d talk through that or the prior step in more detail. This is an effective method that I still use today, even on myself, both when writing new code and debugging existing issues. Let’s examine this in more detail. 1. From Problem Analysis to Data Definitions The first step is to check your data structures and make sure they match the problem you’re trying to solve. As a simple example, the problem statement might be: as I crawl the Web I want to track which pages I’ve seen so I don’t crawl them again. The right data structure for this is a set, but you could possible try an array (with progressively slower crawls and much more memory usage), a tree (storing everything as you go – again, slower and more memory usage), or a graph (accurately storing everything as you go). Selecting the wrong data structure gives you a shaky foundation for debugging. 2. Signature, Purpose Statement, Header We can start by checking the comment describing the method. Try writing one if you don’t have one already – express what you think the method does in your own words. This helps solidify the idea more conceptually. For style points, do this based on the problem statement and not the buggy code you had written. Next up, check your types. This goes for you using a static type checker, too! Are you passing the right values to it? Do you handle the null value that it returns? Are you passing in all the data that you need in accordance with the purpose statement? 3. Functional Examples This is a great time to check on your automated tests. Make sure they capture everything described in your purpose statement, at minimum. Try to write a test for the actual bug. This has a number of benefits in itself, plus it helps with debugging. An automated test can help prevent the bug from recurring. Writing the test can inspire other tests – if you notice that you’re testing on bogus input like null you might want to test on other bogus input like a blank string or the wrong number. Writing a test for the actual bug also gives you confidence that your fix will work, and in part this comes from forcing yourself to understand enough of the problem to write the test. It clarifies and reinforces your understanding of the bug. 4. Function Template The HtDP Function Template is a neat idea that points out that, given a data structure, you can write most of your function without even knowing what the function is supposed to do. For example, if you have a binary tree you know you need to do something different based on whether it’s a leaf or a node, and you know a leaf needs a value and a node has a left and right. You don’t need to know what the ??? operation is just yet: def arbitrary_tree_function(a_tree) if a_tree.leaf? ??? a_tree.value elsif a_tree.node? arbitrary_tree_function(a_tree.left) ??? arbitrary_tree_function(a_tree.right) end end This pertains to debugging, too: you can look for issues in a function without even knowing what the function is supposed to do. Is there a branch you’re not considering? Do you have an enum that should have a case statement (and do you need a default clause)? Are you ignoring a value? 5. Function Definition At long last, let’s look at the actual implementation. This uses both the purpose statement and the examples (the tests). Does the implementation match the purpose statement? Does it actually do what the tests say it should? Debugging at this point might be the most creative and challenging part, so I recommend looking elsewhere in our debugging posts for advice, but the important thing is that you know it’s something specific to your problem. The types are correct, the function’s structure is right, the tests are in place, you understand the problem well enough to rephrase it in your own words, the data structure is right. You are now fighting a much simpler battle than you were before you were sure of this. 6. Testing If you still can’t get it, try to leave a (perhaps commented out) failing test for the next developer. Just writing this might give you one last creative idea and bug fix; even if not, it might give someone else the spark they need to uncover the solution. If you have a failing test that you’re leaving for the next developer to figure out, your testing framework might have a “this is supposed to fail” mechanism, such as RSpec’s pending. This way future developers will discover when they accidentally make it pass. Conclusion The simple Design Recipe checklist can become as comfortable as the keys-wallet-phone pocket check you do before you leave the house, and gives you a launching point for evaluating your code and asking for help on the right points. Give it a try the next time you’re stuck! Debugging Series This post is part of our ongoing Debugging Series 2021 and couldn’t have been accomplished without the wonderful insights from interviews with the following people: - Adam Sharp - Eebs Kobeissi - Eric Bailey - John Schoeman - Mike Burns - Rick Gorman - Sally Hall - Sam Kapila - Sarah Dawson - Sean Doyle - One of the authors of the How to Design Programs book has since become a controversial figure with views about DEI that go against thoughtbot’s views. The ideas in this work come from a time when he was more silent about such issues. The three other authors have been fully supportive of DEI efforts in computer science and the industry. ↩︎
https://thoughtbot.com/blog/debugging-with-htdp-design-recipe
CC-MAIN-2022-40
refinedweb
1,061
68.3
Difference between revisions of "99 questions/Solutions/67A" Latest revision as of 03:43, 10 January 2017" Note that the function stringToTree works in any Monad. The following solution for 'stringToTree' uses Parsec: import Text.Parsec.String import Text.Parsec hiding (Empty) -- these modules require parsec-3 -- to install parsec-3: cabal install parsec pTree :: Parser (Tree Char) pTree = do pBranch <|> pEmpty pBranch = do a <- letter char '(' t0 <- pTree char ',' t1 <- pTree char ')' return $ Branch a t0 t1 pEmpty = return Empty stringToTree str = case parse pTree "" str of Right t -> t Left e -> error (show e) The above solution cannot parse such inputs as x(y,a(,b)) but demands a more rigid format x(y(,),a(,b(,))). To parse a less rigid input: pBranch = do a <- letter do char '(' t0 <- pTree char ',' t1 <- pTree char ')' return $ Branch a t0 t1 <|> return (Branch a Empty Empty) This solution should be attributed to Daniel Fischer @StackOverflow[1]
https://wiki.haskell.org/index.php?title=99_questions/Solutions/67A&diff=next&oldid=44285&printable=yes
CC-MAIN-2022-33
refinedweb
156
51.31
0 Good evening, I am having a little trouble with the outcome of my bucket list assignment. Everything seems to be working just fine, but the final outcome isn't up to par. When you enter numbers from 1-30 or 61-99 it goes into its proper place, however numbers enter in the 31-60 range automatically goes into the 61-99 bucketlist. Perhaps the answer is simple, but I have been at this all day and could use a outsiders pov. I will cite the area you helped me in if you want. Here is the code: import javax.swing.JOptionPane; public class JavaAssignmentUnit3Draft2 /* * The second draft focused more on the JOptionPane. * Within the JOptionPane. The codes used is a mixture of previous codes * I used in past assignments and new codes. * Date Started 7/13/10 11:18 P.M. Status: incomplete... ended @ 12:30 A.M. * Final outcome: JOptionPane appears and can enter 10 integers. However, * BarChart "*" appears to function normally for lower numbers 0-30. * Numbers enter to 31-60 automatically goes into 61-99. Considering creating a thrid draft * Items to be added: -1 to quit program. */ { public static void main ( String[] args ) { int[] array = new int[11]; //it takes numbers 0 - 99 int num = 0; int count = 0; int total = 0; String input; for (count = 0; count < 11; count++) { [ 0 ] = num; } System.out.println ( "The amount of times the numbers between 0 - 99 occured. Amount are displayed by *"); String[] star = { "0-30 |", "31-60 |", "61-99 | "}; for ( count = 0; count < 10; count++) { num = array [ count ]; if ( num < 5 ) star [0] += "*"; else if ( num < 10 ) star [1] += "*"; else star [2] += "*"; } for ( count = 0; count < 3; count++ ) System.out.println( star[ count ] ); } } Thank you ahead of time.
https://www.daniweb.com/programming/software-development/threads/297000/trouble-with-a-bucket-list-bargraph-outcome
CC-MAIN-2017-26
refinedweb
292
74.08
Difference Between ArrayList and HashMap in Java ArrayList is a part of the collection framework and is present in java.util package. It provides us with dynamic arrays in Java. Though, it may be slower than standard arrays but can be helpful in programs where lots of manipulation in the array is needed. HashMap is a part of Java’s collection since Java 1.2. It provides the basic implementation of the Map interface of Java. It stores the data in (Key, Value) pairs, and in order to access a value, one must know its key. HashMap is known as HashMap because it uses a technique called Hashing. Hashing is a technique of converting a large String to a small String that represents the same String. A shorter value helps in indexing and faster searches. HashSet also uses HashMap internally. It internally uses a link list to store key-value pairs already explained in HashSet in detail and further articles. Here we will proceed by discussing common features shared among them. Then we will discuss differences between them by performing sets of operations over both of them in a single Java program and perceiving the differences between the outputs. First, let us discuss the Similarities Between ArrayList and HashMap in Java - The ArrayList and HashMap, both are not synchronized. So in order to use them in the multi-threading environment, it needs to be first synchronized. - Both ArrayList and HashMap allow null. ArrayList allows null Values and HashMap allows null key and values - Both ArrayList and HashMap allow duplicates, ArrayList allows duplicate elements, and HashMap allows duplicate values - Both ArrayList and HashMap can be traversed through Iterator in Java. - Both Somewhere use an array, ArrayList is backed by an array, and HashMap is also internally implemented by Array - Both use get() method, the ArrayList.get() method works based on an index, and HashMap.get() method takes one parameter key_element of object type and refers to the key whose associated value is supposed to be fetched so both provides constant-time performance. By far we get some clarity from the media provided above and now we will be performing sets of operations over them in order to perceive real differences via concluding differences in outputs over the same operation which increases our intellect in understanding the differences between ArrayList and HashMap. - Hierarchy alongside syntax - Maintenance of insertion order - Memory Consumption - Duplicates elements handling - Ease of fetching an element - Null element storage Differences Between ArrayList and HashMap in Java 1. Hierarchy alongside syntax Interface Implemented: ArrayList implements List Interface while HashMap is the implementation of Map interface. Syntax: Declaration of ArrayList Class public class ArrayList extends AbstractList implements List, RandomAccess, Cloneable, Serializable Syntax: Declaration of HashMap Class public class HashMap extends AbstractMap implements Map, Cloneable, Serializable 2. Maintenance of the Insertion Order ArrayList maintains the insertion order while HashMap does not maintain the insertion order which means ArrayList returns the list items in the same order while HashMap doesn’t maintain any order so returned key-values pairs any kind of order. Example: Java ArrayList: [A, B, C, D] HashMap: {1=A, 2=B, 3=C, 4=D} 3. Memory Consumption ArrayList stores the elements only as values and maintains internally the indexing for every element. While HashMap stores elements with key and value pairs that means two objects. So HashMap takes more memory comparatively. Syntax: ArrayList list.add("A"); // String value is stored in ArrayList Syntax: HashMap hm.put(1, "A"); // Two String values stored // as the key value pair in HashMap 4. Duplicates element handling ArrayList allows duplicate elements while HashMap doesn’t allow duplicate keys but does allow duplicate values. Example Java ArrayList: [A, B, A, A] HashMap: {1=A, 2=B, 3=A, 4=A, 5=A} 5. Ease of fetching an element In ArrayList, an element can be fetched easily by specifying its index it. But in HashMap, the elements are fetched by their corresponding key. It means that the key must be remembered always. Note: ArrayList get(index) method always gives O(1) time complexity While HashMap get(key) can be O(1) in the best case and O(n) in the worst case time complexity. Example Java First Element of ArrayList: A Third Element of ArrayList: C HashMap value at Key 1: A HashMap value at Key 3: C 6. Null element storage In ArrayList, any number of null elements can be stored. While in HashMap, only one null key is allowed, but the values can be of any number. Example Java ArrayList: [A, null, C, null, null] HashMap: {null=null, 1=A, 2=B, 3=null} So, let us figure out the differences between ArrayList and HashMap in a table:
https://www.geeksforgeeks.org/difference-between-arraylist-and-hashmap-in-java/?ref=lbp
CC-MAIN-2022-05
refinedweb
786
53.31
I am interested in getting some opinions on the use of include files to sub-divide a large module into functionally related groups. What I'm interested in is opening a discussion on best practices and minimal requirements. Here's the scenario: I am working with a library with 200+ functions. They naturally divide into 2 sets: and advanced set of calls and a "simplified set" which fills in some of the more arcane, rarely used arguments with typical defaults and then calls the advanced functions. So, instead of having one file with 2000+ lines of code, you have a master file with some functions in it that includes the other functions. Something like this: master.cpp: Contains non-categorized, general function, misc stuff master.h : Contains the usual stuff needed to make the program advanced.cpp: Contains functional code for the advanced functions advanced.h: Contains function prototypes for advanced.cpp simplified.cpp: Contains functions that call things in Advanced.cpp simplified.h : Contains prototypes for functions in simplified.cpp The trick is that master.h includes advanced.h and simplified.h while master.cpp includes advanced.cpp and simplified.cpp. This has the following advantages: 1) With proper structuring of the includes, it is really easy to add/remove entire feature sets. 2) Studying the source and looking for specific code blocks gets easier because there's less to look through 3) It's easier to structure the code in an organized fashion This idea is somewhere between the old Fortran "File per Function" paradigm and the more recent tendency to pack everything into a few mega-files. I already know that the strategy works (I use it now all the time). What I hope to get from this posting would consiste of ideas about where the dangers might be and how to work around them. For example. to prevent multiple inclusions from generating multiple definition errors the typical include file usually has something like this: #ifndef STRUCTS_H #define STRUCTS_H ...BODY OF FILE #endif // STRUCTS_H In this case, you would never want one of these files included more than once. I suspect that the above code might actually make this problem worse. In some ways I think that leavin the ifdefs absent completely would be better since then a second instance of the include would certainly bomb the compiler - which might be better than some arcane error produced by a multiple inclusion.
https://www.daniweb.com/programming/software-development/threads/481478/off-label-use-of-include-files
CC-MAIN-2022-40
refinedweb
404
56.55
Hi! I wrote a message a week ago cause I could use the ttystream() class with exception handling. The program used to crash. I found the solution (not actually a solution) I compiled my code with serial.cpp and didnt link the whole library... This way it worked but I have more problems now. Im trying to communicate to a Laser device, This kind of device has not an end of telegram packet so I have to use it by reading byte by byte. The problem is that when I set a Timeout it throws an Input error whenever I try to read something. This is the code: (I inerhit from ttystream for changing some staff) --------------------------------------------------------- #ifndef _SERIAL_INTERFACE_H #define _SERIAL_INTERFACE_H #include<cc++/common.h> #include<string> #include<iostream> class SerialInterface: public ost::ttystream{ private: public: SerialInterface():ttystream(){ this->setError(true); setPacketInput(1,1000); } }; #endif // _SERIAL_INTERFACE_H ------------------------------------------------------- int main(){ unsigned char p; SerialInterface *comm = new SerialInterafe(\"...\"); comm->setTimeout(10000); *comm >> p; // the program chrashes here with errInput (why??) } If I dont set the timeout it works right, but I need it for checking whether the device is there. I guess this is the last chance... tyhe library is not why I call a final release... since I downloaded the code I have nothing but problems... If you could help me. I would be nice.. Thanks, Jose Fernandez
http://lists.gnu.org/archive/html/bug-commoncpp/2002-12/msg00053.html
CC-MAIN-2013-48
refinedweb
225
67.35
.method private hidebysig specialname rtspecialname static void .cctor() cil managed { // Code size 8 (0x8) .maxstack 1 IL_0000: ldc.i4.s 42 IL_0002: stsfld int32 Foo2::Value IL_0007: ret } //: Seems like a possible compiler optimization as well since it blits the same IL, it should be able to identify this and blit the field marking. Wouldn’t it be better to allow explicit declaration of beforefieldinit? E.g. [BeforeFieldInit()] public class Foo1 { … } This way I could get the advantages of beforefieldinit and still explicitly initialise my static members in the static ctor. In otherwords, it seems logical to expect intialisation to occur in a ctor, with additional behaviours produced via attributes. I would find this preferable to writing the following: public class Foo1 { static int s_first = InitializeStaticMembers(); static int InitializeStaticMembers() { s_second = 2; s_third = 3; // etc. for all other static members. return 1; } } The Microsoft Patterns and Practices Group had a drop of the Web Client Software Factory , so I thought PingBack from To those who work with me, it may seem odd to see me to put up an entry implying that I’ve written "my first WPF" in recent days. But before this, my work with WPF has been very over-the-shoulder observer and any commentary (and guidance sometimes) has
https://blogs.msdn.microsoft.com/brada/2004/04/17/perf-penalty-static-constructor/
CC-MAIN-2016-40
refinedweb
211
52.7
I have a confession to make: Even though thoughtbot is mostly known for the work we do with Ruby on Rails, I’m a huge Django fan. Someone left the keys to the blog lying around, so I thought I’d take it for a quick joy ride around the one of my favourite Django features: class-based generic views. Firstly, just to help anyone who’s not au fait with Django terminology catch up, a view deals with a request and does whatever needs to be done to produce the correct response. If Rails is your thing, you can think of it as being roughly equivalent to a controller action. Class-based views were introduced in Django 1.3, but despite being around for a couple of years they’re still not as widely used as they should be. What came before Before the class-based view there was the humble function-based view. It was a simple time. Views would take a request and return a response. Here’s an example for displaying a single blog post: def blog_post_detail_view(request, *args, **kwargs): """Displays the details of a BlogPost""" blog_post = get_object_or_404(BlogPost, pk=kwargs.get("pk")) return TemplateResponse(request, "blog/blog_post.html", { "blog_post": blog_post, }) The mechanism is undoubtedly simple, but the resulting code isn’t. It’s very dense, with a single function loading the context data and building the response. This small example isn’t too bad, but imagine if we added comments, and author information, and a list of related posts. We’d quickly get to something very unwieldy. Class-based views It would be great if we could encapsulate all of this logic in a class so that it was less dense and easier to extend. Conveniently Django 1.3 helps us to do just that by providing a View class that we can extend. Here’s our blog post detail view, refactored into a class: class BlogPostDetailView(View): """Displays the details of a BlogPost""" def get(self, request, *args, **kwargs): return TemplateResponse(request, self.get_template_name(), self.get_context_data()) def get_template_name(self): """Returns the name of the template we should render""" return "blog/blogpost_detail.html" def get_context_data(self): """Returns the data passed to the template""" return { "blogpost": self.get_object(), } def get_object(self): """Returns the BlogPost instance that the view displays""" return get_object_or_404(BlogPost, pk=self.kwargs.get("pk")) The readability and extensibility have definitely improved, but the code could still be better. There are a lot of small decisions encoded in the class that needn’t be here. In writing this code I had to decide what to call the template, what to call the URL keyword argument that contains the model’s primary key, and what to call the context variable that is passed to template. None of those decisions were hard to make, but none of them really matter that much. What matters is that they remain consistent between different views, so that developers don’t have to waste time looking for things only to discover that this view doesn’t quite work like the last one they used. In a nutshell, what this code needs is conventions. Application level conventions are good, but framework level conventions are better: The same developer can quickly understand many applications and easily move between projects or even companies without needing as much time to get up to speed. As consultants, when we’re working with new clients framework level conventions are invaluable. Rails is famed for its opinionated stance on convention over configuration, while Django is generally quieter on the subject. This might lead you to believe that Django doesn’t provide any conventions, but there’s more to Django than meets the eye. Class-based generic views Convention is where the “generic” part of “class-based generic views” comes into play. Django provides subclasses of View for a variety of common situations that are packed full of conventions and take all of those pesky little decisions out of our hands. Using the generic DetailView, which displays details of a single model instance, we can boil the previous example down to a few simple lines: class BlogPostDetailView(DetailView): """Displays the details of a BlogPost""" model = BlogPost Convention and configuration Of course, convention stops being helpful as soon as you want to do something unconventional. That’s where configuration comes into its own. Thankfully, Django’s class-based generic views provide both by using the Template Method pattern which makes it very easy to customise each part of the generic process. Let’s do something less conventional and update our BlogPostDetailView to only display posts with a published flag set to True. We can do this by providing the view with a QuerySet to use as the basis of its query: class BlogPostDetailView(DetailView): """Displays the details of a BlogPost""" model = BlogPost queryset = BlogPost.objects.filter(published=True) Alternatively, we can go one step further and override the get_queryset method and use different querysets based on the properties of the request: class BlogPostDetailView(DetailView): """Displays the details of a BlogPost""" model = BlogPost def get_queryset(self): if self.request.GET.get("show_drafts"): return BlogPost.objects.all() else: return BlogPost.objects.filter(published=True) The code is still very concise and readable. Template Method has allowed us to override one part of the algorithm without reimplementing the whole thing. When we return to this class in the future there aren’t dozens of lines of boilerplate code to read through to find the significant parts. Behind the scenes, the DetailView class provides an implementation of get, which in turn calls the get_object method. get_object is the template method, so if we wanted to buck all of the conventions we could override it. Since we’re only concerned with changing the queryset, we can ignore the template method itself and turn our attention to get_queryset, which is one of the primitive operations that get_object uses. In the first example we take advantage of the default implementation of get_queryset, which will return self.queryset if we’ve provided it. In the second example we override get_queryset entirely. In both cases we keep the rest of get_object’s algorithm, including useful features like 404 Not Found responses and support for looking up the model instance by primary key or using a slug. Knowing what to override The downside isn’t reading existing views, but writing new ones. The documentation for this feature has improved significantly since Django 1.3 was released, but there’s still something of a learning curve. Of course, you’re going to end up learning a set of conventions for your application, so it may as well be the one Django provides. The good news is that these class-based generic views are very TDD friendly. If you are missing some required configuration attribute Django will raise an ImproperlyConfigured exception with a helpful message outlining your options (usually either setting an attribute, or overriding one or more methods that depend on the missing attribute). There’s rarely such a clear example of a failing test telling you exactly what to do next. There are also some very helpful resources out there to get you started and to use as reference material when you’re up and running: - The official Django documentation on class-based views for a more complete introduction than I’ve given here. - The official class-based views reference for specifics of individual classes and methods. In particular, this includes a “method flowchart” for each class which is helpful for figuring out what the Template Methods and their primitive operations are called. - The source code for the django.views.genericmodule is also a fun read. - Classy class-based views is an alternative set of documentation, which is particularly useful as a quick reference. That’s all folks I hope you enjoyed this look inside Django. Maybe we can do it again sometime?
http://robots.thoughtbot.com/class-based-generic-views-in-django
CC-MAIN-2014-49
refinedweb
1,314
52.9
This is the proper “Hello World” in C++. All the others Hello World are wrong. But this is not where I rant about how using namespace std; crystallizes everything messed up with the teaching of C++. Another time perhaps. Today we are gonna be compiling that hello world so that it can be executed on a target system. But first, let me tell you a few things about me. I use Linux for fun and profit. I happen to think it is the best system. For me. As a developer. Sometimes, I look down on developers using Windows, wondering how the eff they manage to get anything done by clicking on things. And it is likely that a vim user on Arch looks down on me for using Ubuntu. Nobody’s perfect. Anyway, let’s fire up a terminal # sudo apt-get install g++ # g++ -o helloworld helloworld.cpp # ./helloworld Hello, World! # Nice, That’s simple, let’s go home and have a beer 🍻 ! But then, enters my boss. They are in the business of selling software to people who use Windows. I try to show them that I can make a cow speak and that I can resize my terminal so we should obviously move all our business to Linux at once, they say something incomprehensible about market shares and apparently, they can resize their command prompt too. After looking down at each other for a while like we are stuck in an Escher painting, I grudgingly remember that I’m in the business of making my clients happy, and so we are going to port our hello world application to Windows. Our boss doesn’t care what environment we use to create that ground breaking app, and they don’t have an issue with me continuing working on the Linux version at the same time, so I’ve decided to develop that application for Windows, on Linux; what could possibly go wrong ? Besides, it will then be far easier to set up a build farm and continuous integration. You could even have your CI provision fresh docker containers on the fly to build the windows app in a controlled and fresh environment. While I tend to think that Dockers is a bit of a cargo cult, Using Docker along Jenkins is actually something that makes a lot of sense. And if you like your sysadmin, don’t force them to deal with Windows servers. We should strive to make your application as portable and platform agnostic as possible, so having a windows version of our application may actually make our code better. That’s what I try to tell myself. As it turns out, Microsoft is nice enough to offer a compiler for windows called msvc, and I have the feeling that msvcis a better choice on windows than g++since that’s the compiler the whole ecosystem is designed around. And hopefully Microsoft knows their own tools, formats and calling convention best. I never went the extra mile to benchmark that though, and you will find proponents of either approach on internet. But, The MSVC team agrees with me. Shocker. Anyway, for now, let’s stick to that. # apt-get install msvc E: Unable to locate package msvc Surprisingly, that doesn’t work. You can’t blame a guy for trying. But to explain why, let me tell you how a compiler works. A compiler opens a file, transforms the content of that file into something that can be executed, and writes that out to some other file. Sometime you have more than one source file, so you need a linker which is a program which opens a bunch of files and writes an executable down. An executable is a file, nothing magical about it. Sometimes you need libraries. A library is a file. And you mostly likely need tons of headers which are… you get it, files. plain old boring files. The executable is then loaded by another executable which is also a file, it’s files all the way down. Ok, maybe not, Plan 9 has more files. To be clear, compilers are extremely complex pieces of engineering, especially C++ compilers and you should offer a cookie to all the compiler writers you meet. However, from a system-integration point-of-view, they are as trivial as it gets. Most compilers don’t even bother with threads. They let the build system deal with that. Which is unfortunate since most build systems have yet to learn how to tie their shoe laces. Anyway…here is the list of kernel facilities you need to write a compiler: - Opening, Reading and Writing files - Reading directories content - Allocating memory You may therefore be thinking that this is a reasonable enough list, and so, you wonder why msvc isn’t available on Linux. Sure, having msvc build Linux/ELF applications would be a huge and probably pointless undertaking, but all we want is to build an application for Windows, and surely Microsoft would make it easy as possible for me to do so, right? But there is this thing. Windows is an “ ecosystem “. It means they want to sell their OS to both their users and their developers, sell their tools to developers, and make sure nobody learn about that other OS legends speak of. So if you want to build a windows application, you need Windows. Crap. Fortunately, someone rewrote Windows on Linux and called that wine. Probably because they had to be very drunk to even think about doing it. It took merely 15 years for wine to reach 1.0. But it’s in 3.0now, so maybe we can use it ? There are minor miracles in the open source community and WINE is certainly one of them. For a very long time, MSVC was bundled with Visual Studio. Which mean that if you wanted to compile a C++ app on windows using Qt creator, CLion, Eclipse or notepad++, you still had to have Visual Studio. Ecosystem and all that. Things are better now, you can install the “build tools” such that you will only need to install about 5GB of… stuffs. Let’s do that. Oh, apparently the compiler is distributed as an executable which then downloads stuffs you didn’t asked for over the internet. Maybe it’s better than a 40GB zip ? # wine vs_BuildTools.exe The entry point method could not be loaded Are you surprised? My dreams are crushed. We do need a windows to do some windows development ( spoiler : it gets better ). Let’s fire up a VM. If you want to follow along, I recommend that you use a new or cloned Windows 10 VM. We are gonna install a lot of weird things and it will be next to impossible to clean up after ourselves. Afterwards you may get rid of the VM. Once that’s done, we can go and download the VS build tools. Visual Studio Downloads Free, fully-featured IDE for students, open-source and individual developers Free download… Scroll down until you get carpal tunnel. The build tools is the second to last item. Download that. I had a few issues launching the installer. I think they try to contact a server that managed to get itself in a list of ad servers so my DNS blocked it. Don’t ask. Installers with loading screens, it’s perfectly normal. Once it’s done, it loads the main UI, slowly and painfully but then we get to check boxes. I’m having a blast. You won’t need the static analysis tools, but they get checked when you install a compiler no matter what. That’s fine. We need a C++ toolset — the thing everybody else calls a toolchain. I’m not sure what is newer, v141 or 15.4 v14.11. Use a die ? We also need a C runtime too, that’s handy. I’m not sure whether we need the CRT or the URT so, we will just install both. The URT/CRT is nice though. Before it came into existence, everything was much, much harder. Finally, we will probably need to use some windows features so we should get the Windows SDK. Apparently that depends on some C# components. And some JS libraries, obviously. To be clear, you can’t do anything remotely useful without the Windows SDK, better get it now. Time to have a coffee pot while Visual Studio gets into every recess of your hard drive. At some point though, it’s done so you can go do some bicycle with the butterflies. Nice. A butterfly isn’t enough to make me want to ditch Linux, so let’s see if what we have just installed can be used without a Windows box. Copy the following outside of your VM: C:\Program Files (x86)\Windows Kits\10\Include C:\Program Files (x86)\Windows Kits\10\Lib C:\Program Files (x86)\Microsoft Visual Studio\2017\BuildTools\VC\Tools\MSVC The first two paths are the Windows SDK, the last one is the toolchain, containing the compiler, the linker, the STL and the VC runtime libraries, for all architectures. In my installation I have URT files all over the places, So I guess that if you install the Windows 10 SDK you actually get the CRT so you don’t need to activate it separately when you select the components to install. Compared to only a few years ago the situation is much better. Microsoft has been busy. I put everything in a folder called windows, I have the msvc compiler with the runtime, the STL and the redistribuables on one side, and the windows 10 SDK in a separate folder. I didn’t keep any information about which version of the SDK or the toolchain I was using, you may want to do that more properly. In the Windows Sdk there are some useful binaries & dll like rc.exe Put them alongside in msvc2017/bin/Hostx64/x64 where the toolchain binaries are located, including cl.exe. If you are not familiar with windows development: cl.exeis the compiler link.exeis the linker rc.exeis a tool to deal with resources files, including icons and manifests You may need various other tools if you have to deal with drivers, cab files, MSI installers, etc. The whole thing is about 2.9GB. About half what we had to install on the windows VM. Let’s have some wine again 🍷. Visit and to make sure your wine setup is up to date. I will be using wine-3.0. Then, install the redistribuable for VC 2017. The process is mostly automatic. We will use a dedicated wine prefix to keep everything kosher. What that means is that it’s actually easier to have multiple msvc installations under wine that it is on windows. WINEPREFIX=windows/vs-buildtools2017-wine64 WINEARCH=win64 winetricks vcrun2017 Then in your windows folder, create a bin64 folder in which you can write a small bash script with the following content. That script will first set up wine to use our prefix . Then we do Linux -> windows path separator translation ( / to \ ) before forwarding the arguments to the actual windows PE binary running on wine. We will use a tool called shc to convert that wrapper into a proper elf executable. Otherwise we may have issues down the road. Another solution would be to write a C++ wrapper instead of bash. the shc has a few drawbacks, starting with the need for a hard coded install path. shc -f cl-wine.sh -o cl.exe shc -f cl-wine.sh -o link.exe You can create a bin32 folder in the same manner, just changing the last line to wine "$DIR"/../msvc2017/bin/Hostx64/x86/$PROGRAM To have a x86 target compiler. I’m not sure why you need two sets of separate binaries to support another architecture, but we do. Finally, the x86 linker may complain about missing libraries so we are gonna create some symlinks. cd windows/msvc2017/bin/Hostx64/x86/ for x in $(ls ../x64/ms*.dll); do ln -s $x .; done One last thing before we can do some serious work. We need to delete vctip.exe as it doesn’t work. It’s a telemetry tool so we don’t need it. It’s located in windows/msvc2017/bin/Hostx*/**. If you don’t follow that step you will encounter weird stack traces. Time to build our Hello World application ! It’s actually straightforward We are building an executable that depends on the compiler headers ( including the STL ), the C runtime, and some windows libs such as kernel32.lib. For completeness, here is the x86 build Truth is, the whole endeavor is reasonably simple, perhaps more so than using windows proper. No messing about with vcvarsall.batand all your favorites tools such as perl, git, python, sed, the terminal, zsh…are there and work properly. 🔨 Build System We got cl.exeworking on linux, yeah ! Before we go further, we should add that alien toolchain to a nice, modern build system. As I’m not in the mood to deal with the hotmess that is cmake, we will be using QBS, my favorite build system. Setting up qbs to use our wine/msvc compiler should be easy… QBS can detect toolchains automatically, however, there are a few issues. First the tools assumes MSVC only exists on windows so some code paths are disabled away. I think this could be fixed in a few hours, it would merely require implementing the CommandLineToArgv function in a portable manner. However, there is something to be said about tools being too clever. QBS attempts to parse vcvars.bat at an assumed location. That’s one file we happily got rid of. Reality check, we are not going to get any sort of automatic detection. We don’t really need to. We can set up the toolchain manually and treat it as a separate thing from the msvc-on-windows-proper. Detection isn’t really an issue since all we have are a couple of include directories and library paths. I’ve started to push some files to GitHub, it’s very much a work in progress. Debug builds are completely broken at the moment. It’s a module which offers some understanding of our wine toolchain. It mostly disables all probing and assumes everything is already configured properly. Contribute to qbs-wine-toolchain development by creating an account on GitHub.github.com So we have to do all the work of setting the profile manually. But if our endeavor proved anything, it’s that even a toolchain as hairy as VC++ can be reduced to a handful of variables ( compiler, linker, tools path, includes, defines, library paths). So, here is my QBS profile configuration. And finally, we can write a small qbs build script Which we can then run and Voilà ! runner.sh is a small script that sets up the wine prefix before launching the freshly built windows executable. Nothing too fancy. So here you have it. A Microsoft compiler, wrapped in a bash script compiled to ELF, building 64 bits PE executables, driven by a modern build system run on Linux. That’s pretty satisfying. Our hypothetical Boss is knocking on the door. See you in part 2.
https://hackernoon.com/a-c-hello-world-and-a-glass-of-wine-oh-my-263434c0b8ad
CC-MAIN-2019-43
refinedweb
2,559
74.39
How to convert image data set into csv format for analysis Identify the Digits Hi @deepak9001, Based on the language you’re working on, their are libraries available for reading image files and converting them to arrays for analysis. Suppose you have a 28x28 image, you can read them into an array of shape (28, 28). Below is a script written in python for “Identify the Digits” Practice problem, from scipy.misc import imread temp = [] for img_name in train.filename: image_path = os.path.join(data_dir, 'Train', 'Images', 'train', img_name) img = imread(image_path, flatten=True) img = img.astype('float32') temp.append(img) train_x = np.stack(temp) Now this (numpy) array can be easily be used for analysis. For a more indepth analysis of the practice problem along with the solution, refer this article. HI Thanks a lot. I am planning to use R for the analysis.Please explain me how to do the same in R Hi @deepak9001 Let’s say, image name is pic.jpg install.packages("jpeg") library(jpeg) myimage<- readJPEG("pic.jpg") dim(myimage) df <- as.data.frame(myimage) #convert matrix to data frame write.csv(df,"image.csv",row.names = F) Thanks a lot Manish that was so well Explained, just curious to know what next i mean a data frame per image to build a model For png files, png library and readPNG() function can be used.
https://discuss.analyticsvidhya.com/t/identify-the-digits/12098
CC-MAIN-2018-30
refinedweb
231
67.35
Sep 24, 2008 12:15 PM|spillbean|LINK Hi all, While implementing an interface we need to implement all the methods of an interface otherwise the class becomes an abstract class . What if there is an interface containing 30 methods but we do not require all the methods to be implemented, then in this case what should we do to prevent the class from being Abstract? inheritance Interfaces C# 2005 Contributor 7064 Points Sep 24, 2008 01:33 PM|rjcox|LINK You have to implement them, even if only to throw a NotImplementedException. (An interface with 30 member is a strong sign of a poorly factored design.) Sep 24, 2008 02:02 PM|Ricardojb|LINK You have to implement all methods, properties and events defined in the interface, otherwise you will get a compilation error. you might leave the body blank or throw a notimplemente exception, only be careful that if the method returns a value you must return something (for example, if the method returns a boolean value, you have to add return false or return true. Not implementing methods of an interface in a class does not make it an abstract class. To make a class abstract you have to declare it as it explicitly. It has nothing to do with the interface although of course you can implement some interface method in an abstract class and then the classes inheriting it won't need to, but if you implement a method you don't need as abstract, you still will have to implement it in child classes. I would say, if you don't need some methods, why don't you remove them from the interface? As somebody say, 30 methods in an interface probably signs design problems although not necessarily, it kind of defeats the purpose of the interface, you might consider splitting them in multiple interfaces depending on the purposes of them. One of the purposes of an interface is to only expose the methods, properties and events that you need for a particular application (or part of it) without worrying about the implementation, if the interface declares too many members and it has to be implemented in multiple classes it will add a lot overhead, if it only needs to be implemente in one class, you might reconsider the need for it. Sep 24, 2008 02:31 PM|Svante|LINK spillbeanwe need to implement all the methods of an interface otherwise the class becomes an abstract class Yes. spillbeanan interface containing 30 methods Is unreasonable. Split it up. Sep 24, 2008 03:43 PM|spillbean|LINK Hi Svante, Can you be a little descriptive? I want to know whether I can simultaneously avoid all the methods of an interface to be implemented and prevent the class to be abstract. What benefit will I get by splitting up the interface? Sep 24, 2008 04:32 PM|Svante|LINK spillbeanCan you be a little descriptive All too often, I'm way too descriptive... But sure! spillbeanI want to know whether I can simultaneously avoid all the methods of an interface to be implemented and prevent the class to be abstract. As mentioned, no. But... As someone once said "these are not the droids you are looking for", perhaps. You really have two major options: spillbeanWhat benefit will I get by splitting up the interface public interface ICreature { void MakeSound(); int Height { get; } BitMap Picture { get; } } This is a hypothetical interface of a creature in a role playing game. Looks ok, but... Is the capability to render oneself as bitmap really integral to the concept of a creature? I'd rather split this interface: public interface ICreature { void MakeSound(); int Height { get; } } public interface IVisible { BitMap Picture { get; } } Now I can choose to implement one, the other or both of the interfaces in my concrete classes. I'd probably continue and factor out the ability to make sound as well in a IAudible interface. For common combinations, you can always combine interfaces since an interface may inherit from more than one interface, i.e. public interface IInteractiveCreature : IVisible, IAudible { int Height { get; } } Sep 24, 2008 04:37 PM|Svante|LINK spillbeancan I know how many members maximum does an inbuilt Interface of .NET has As far as I know there's no set limit in the C# language. I don't know offhand what the largest interface in the framework library is, but I guess one could write a small program to find out via reflection - if that was your question. spillbeanAnd how can I split an inbuilt interface of .NET like IEnumerable or anything like that ? You cannot split an interface that you do not control the source code for. As for IEnumerable specifically, it only has one method so there's nothing to separate out. All-Star 16425 Points Sep 24, 2008 05:07 PM|JeffreyABecker|LINK 1) As everyone else has said, yes you need to implement all the interface methods and properties. 2) The guideline I've heard for interface size is generally no more than 5 members. This is however a guideline and not a hard rule. My personal guideline is that if you cant put the interface name in terms of an adverb it's probably either too big or something that should just be an abstract base class. 3) I dont see why you'd want to "prevent the class from being abstract". Abstract base classes which implement most of a corresponding interface in a common way are often very, very useful. All-Star 16425 Points Sep 24, 2008 05:09 PM|JeffreyABecker|LINK spillbean Svante, Thanks for the answer, my problem is almost solved. Now one last question. Can we apply this splitting up concept to any of the inbuilt interfaces of .NET ? If yes then how can I do that? Thanks in advance...... No, you cant. As was said, if you do not control the source to the interface you cant change it. However I cant think of an interface in the framework that is that poorly designed. Sep 24, 2008 05:15 PM|Svante|LINK spillbeanCan we apply this splitting up concept to any of the inbuilt interfaces of .NET ? As previously mentioned, no. But you can define a concrete type implementing the interface in question, and either derive from it and only override the specific methods you need, or more realistically, use that partial but concrete implementation, and then compose it (wrap an instance) with whatever class you're really implementing, and let that class implement the interface, but delegate all the work to the wrapped instance. I.e: public interface IMyInterface { void MyMethod1(); void MyMethod2(); } public class MyConcreteInterface : IMyInterface { public void MyMethod1() { throw new NotImplementedException(); } public void MyMethod2() { throw new NotImplementedException(); } } public class MyPartialImplementation : MyConcreteInterface { public override void MyMethod1() { // Do something here } } public MyRealClass : IMyInterface { private MyPartialImplemenation myImplementation = new MyPartialImplementation(); public void MyMethod1() { myImplementation.MyMethod1(); } public void MyMethod2() { myImplementation.MyMethod2(); } }At the expense of some boiler plate code, you have now gained the capability to 'partially' implement an interface that you cannot change. Sep 24, 2008 05:20 PM|spillbean|LINK Svante, Jeffrey..and all those who answered.....Thank you guys for being helpful. I was Googling around about this concept for quite sometime. But was not able to find a suitable answer and this is where I cleared my doubts. Thank you very much guys. 12 replies Last post Sep 24, 2008 05:20 PM by spillbean
http://forums.asp.net/t/1324878.aspx
CC-MAIN-2014-10
refinedweb
1,243
60.55
scpclient 0.5 scp client, for use with paramiko. A library that implements the client side of the scp (Secure Copy) protocol. It is designed to be used with paramiko (). Using paramiko There are many ways to use paramiko. For the purposes of these examples, you want to obtain an authenticated SSHClient object: import paramiko ssh_client = paramiko.SSHClient() ssh_client.connect(hostname, username=username, key_filename=key_filename, password=password) Writing files The scpclient.Write object is used to write files to an scp server. Its required parameters are a paramiko.SSHClient instance and a remote directory name. It has 2 methods: send_file and send. send_file takes a filename to send, send takes a file-like object, a remote filename, a mode, and a length. You may call send and send_file multiple times. Example: with closing(Write(ssh_client.get_transport(), '.')) as scp: scp.send_file('file.txt', True) scp.send_file('../../test.log', remote_filename='baz.log') s = StringIO('this is a test') scp.send(s, 'test', '0601', len(s.getvalue())) Writing directories Example: with closing(WriteDir(ssh_client.get_transport(), 'subdir')) as scp: scp.send_dir('../../manuals', preserve_times=True, progress=progress) Reading files Example: with closing(ReadDir(ssh_client.get_transport(), '.')) as scp: scp.receive_dir('foo', preserve_times=True) Reading directories Example: with closing(Read(ssh_client.get_transport(), '.')) as scp: scp.receive('file.txt') Change log 0.5 2014-04-27 Eric V. Smith - Fixed issue #5, Not all files included in sdist. - Fixed issue #6, Rename bdist RPM to python-scpclient. - No code changes. 0.4 2012-11-28 Eric V. Smith - Fixed issue #2, Missing contextlib import. Thanks Olivier CARRERE. 0.3 2011-10-31 Eric V. Smith - Improved documentation, including how to create a paramiko connection. 0.2 2011-10-31 Eric V. Smith - Removed useless tests. - Fixed embarassing last minute typo which broke the code. - Included trivial examples in README.txt. Needs much work. - Forbid files that contain ‘..’ in the filename. This is an attempt to prevent path traversal. This approach is simplistic, but it’s a reasonable first step and gets the job done. 0.1 2011-10-31 Eric V. Smith - Initial release. - Author: Eric V. Smith - License: Apache License Version 2.0 - Categories - Package Index Owner: ericvsmith - DOAP record: scpclient-0.5.xml
https://pypi.python.org/pypi/scpclient/0.5
CC-MAIN-2017-26
refinedweb
367
56.52
In the last post we looked at improving our responses in OWIN by adding some extensions methods to the response object and the next logical step for this is to think about HTML. While what we’ve brought together thus far is useful if you’re creating something that is just a web API if you want to create an actual web site you probably need to respond with some HTML. To this end we’re going to need to think about creating a View Engine that will be responsible for our HTML generation. The reason I want to go down this path is it makes it nicer if we want to add some level of dynamic data to the HTML we’re serving, say insert a user name or other things like that. Picking our language HTML isn’t a language that has dynamic features to it so we need to look at a templating language to leverage for this. If you look around there’s plenty of different HTML templating languages like HAML, Spark, Jade or even Razor. Since I want to make it something easy to understand for the .NET developer I’m going to use Razor as my templating language, and I’m going to use the RazorEngine project to help me out (it saves me writing all the bootstrapping code). Approaching the View Engine So we’re going to use Razor but how are we going to use it? We need some way to “create” our View Engine and then we will want to interact with it. Since the View Engine could be a little bit complex I’m going to create a class which will represent the engine. This will also mean that I can do some caching within the View Engine to ensure optimal performance. With that in mind how are we going to interact with the View Engine? We obviously don’t want to spin it up every single time, instead I want it to always be available. So this means that I’m going to have a static that lives somewhere which I’ll want to interact with. Finally how will we get that View Engine instance? Do we have it magically created or do we want it lazy-loaded? These are all things to be considered but my approach is going to be: - Use a singleton for the View Engine - Have a ViewEngineActivatorwhich we access it through - The user must explicitly register the ViewEnginethey want to use in code Coding the View Engine Thinking about the View Engine there’s not a lot that the class would have to publicly expose, in fact I really think you only want two methods, one that takes a view name, one which takes a view name and a model. So the View Engine will look something like this: public class RazorViewEngine { public string Parse(string viewName) { return Parse<object>(viewName, null); } public string Parse<T>(string viewName, T model) { throw new NotImplementedException(); } } Cool that’s not very complex, let’s start on the activator: public static class ViewEngineActivator { public static RazorViewEngine ViewEngine { get; set; } } And now we’ll make it possible to register a View Engine: public static IAppBuilder UseViewEngine<TViewEngine>(this IAppBuilder builder) where TViewEngine: RazorViewEngine, new() { ViewEngineActivator.ViewEngine = new TViewEngine(); } /* snip */ builder.UseViewEngine<RazorViewEngine>(); Now that the infrastructure code is all there we need to think about how we would go about reading in the views and turning them into something we can send down as a response. In our View Engine we’re going to need to know where to find the views. I like conventions so I’m going to expect them to be in the views folder at the application root. But I’m a nice guy so I think it should be possible to put the views into another folder if you desire so I’ll add some constructors like so: public RazorViewEngine() : this("views", "_layout") { } public RazorViewEngine(string viewFolder, string layoutViewName) { ViewFolder = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, viewFolder); LayoutViewName = layoutViewName; if (!Directory.Exists(ViewFolder)) throw new DirectoryNotFoundException("The view folder specified cannot be located.\r\nThe folder should be in the root of your application which was resolved as " + AppDomain.CurrentDomain.BaseDirectory); } I’m also going to check to make sure that the views folder does exist. I’m also wanting support a “layout” view so that you can do reusable HTML; it just makes sense. Since you’re now able to specify the Views folder I’ll add another extension method so you can provide that instead of using the default way: public static IAppBuilder UseViewEngine<TViewEngine>(this IAppBuilder builder, TViewEngine viewEngine) where TViewEngine: RazorViewEngine { ViewEngineActivator.ViewEngine = viewEngine; } This also means that you could super-class the RazorViewEngine if you want and provide additional functionality. Next up we’ll start implementing our Parse<T> method. public string Parse<T>(string viewName, T model) { viewName = viewName.ToLower(); if (!viewCache.ContainsKey(viewName)) { var layout = FindView(LayoutViewName); var view = FindView(viewName); if (!view.Exists) throw new FileNotFoundException("No view with the name '" + view + "' was found in the views folder (" + ViewFolder + ").\r\nEnsure that you have a file with that name and an extension of either cshtml or vbhtml"); var content = File.ReadAllText(view.FullName); if (layout.Exists) content = File.ReadAllText(layout.FullName).Replace("@Body", content); viewCache[viewName] = content; } return Razor.Parse(viewCache[viewName], model); } What you’ll see here is I’m creating a cache of views that get discovered for performance so it’s all shoved into a static dictionary that I’ve got*. Assuming that this is the first time we’ll look for the layout view and current view, raise an error if the view isn’t found, and then combine them all together. *This is pretty hacky code and doesn’t take concurrency into account; make sure you do double-lock checking! One convention I’m adding myself is that the “body” (aka, the current view) will be rendered where ever you place an @Body directive. This is because we’re using Razor the language which is slightly different to MVC’s Razor. The language doesn’t include the RenderBody method, that’s specific for the implementation. When creating your own view engine though you’re at liberty to do this how ever you want. You could alternatively create your own base class that handles the body better, me, I’m lazy and want a quick demo. I finish off caching the generated template so that next time we can skip a bunch of the lookup steps and then get RazorEngine to parse the template and send back the HTML*. *I’m not sure if this is the best way to do it with RazorEngine, I think you can do it better for caching but meh. Also, you don’t have to return HTML, you could use this engine to output any angled-bracket content. Using our View Engine Now that we have our View Engine written we need to work out how we’ll actually use it. Like we did in the last post I’m going to use extension methods on the Response object to provide the functionality: public static void View(this Response res, string view) { var output = ViewEngineActivator.ViewEngine.Parse(view); res.ContentType = "text/html"; res.Status = "200 OK"; res.End(output); } public static void View<T>(this Response res, string view, T model) { var output = ViewEngineActivator.ViewEngine.Parse(view, model); res.ContentType = "text/html"; res.Status = "200 OK"; res.End(output); } This is pretty simple, we’re really just acting as a bridge between the response and the view engine. Sure I’m also making the assumption that it’s text/html that we’re returning despite saying above we can do any angled-bracket response, changing that can be your exercise dear reader. Bringing it all together So we’ve got everything written let’s start using it: builder .UseViewEngine<RazorViewEngine>() .Get("/razor/basic", (req, res) => { res.View("Basic"); }); Pretty simple to use our View Engine now isn’t it! Conclusion In this post we’ve had a look at what it’d take to produce a basic View Engine on top of OWIN, building on top of the knowledge and concepts of the last few posts. In the next post I’m going to take the idea of a View Engine one step further and give the user a lot more power. As always you can check out the full code up on the GitHub repository.
https://www.aaron-powell.com/posts/2012-03-23-owin-view-engines/
CC-MAIN-2019-18
refinedweb
1,419
60.14
[Solved] MySQL Driver C++ Hello all, Im getting crazy, i've searched all over the internet, i've read 1000 topics and internet pages about the MySQL driver compile. This is an example: But i can't get it working... First of all, i've seen every1 having a folder called "mysql" in their QT folder (C:\QtSDK\Desktop\Qt\4.8.1\msvc2010\plugins\sqldrivers\mysql) I don't have it, but i made it manually.... ??? Second, when i try to "qmake" it says mysql.pro is missing.. (so i also made this file manually) Third, when i then try to "qmake" it says "Unescaped backslashes are deprecated" When i did this steps, it makes some files in the (C:\QtSDK\Desktop\Qt\4.8.1\msvc2010\plugins\sqldrivers\mysql) folder. MakeFile.Release MakeFile.DeBug etc... But not the files i need! I can't seem to find a clear tutorial that handles all these errors, because i don't know how to fix this.. Thanks!! i hope its clear. P.S: Ive installed Mysql server 5.5, and also the MySQL connecter. Nvm, i found it, i forgot to install the QT Sources!! Now i have a Mysql folder etc, and a mysql.pro.. Did you try "this": guide? [quote author="Andre" date="1341834310"]Did you try "this": guide?[/quote] Yes, thanks, im keeping stucked @ "unescaped backslashes deprecated" So it doesn't compile... (there should be compiled files in release/debug folder, but there aren't any.) Edit: I've found the problem, i must use \ instead of .. Now up to my next problem, which is i can't use "mingw32-make" Ok, so now i've successfully compiled the driver files, but my QtCreator doesn't see it. @#include <QtCore/QCoreApplication> #include <QtSQL> int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); qDebug() << QSqlDatabase::drivers(); return a.exec(); }@ Also added "QT+= sql " to my project file.. What can be the problem? :O Did you install it in the right place? I've put all the nescessairy files in "C:\QtSDK\Desktop\Qt\4.8.1\mingw\plugins\sqldrivers" qsqlmysql4.dll qsqlmysqld4.dll libqsqlmysql4.a libqsqlmysqld4.a I've tried different compilers too (In QT Creator) If i copy the dll/a files to other plugin directories, and i use that compiler, it doesn't show me any drivers at all.. (like version 4.7.4) This is what i mean: Try setting Q_DEBUG_PLUGINS=1 in your environment when running your application. You will get debug info on plugin loading, including the sql drivers. [quote author="Andre" date="1341843873"]Try setting Q_DEBUG_PLUGINS=1 in your environment when running your application. You will get debug info on plugin loading, including the sql drivers.[/quote] Sorry, but where can i find this? Q_DEBUG_PLUGINS=1 You can set it as an environment variable. You can even do that directly from Qt creator: go to the Projects tab on the right side, and swich to the right project and the Run Settings (at the top of the tab). In the list of options, you'll find a Run Environment box. Expand it using the Details button on the right, and add the Q_DEBUG_PLUGINS variable to the list, giving it the value 1. Thanks, i've found it.. But where can i find debug info? because it doesn't show up in "Application Output" Sorry, my fault, it should be QT_DEBUG_PLUGINS. This is the output (its on pastebin, couldn't post it here..) That's a nice bunch of output. What does it tell you? I could of course analyze it for you, but the point is that it would be more useful for the both of us if you learn to do that yourself... The output is what i understand, it tells me that the dll's and .a files are incompatible sortwise. But why it is, is something i don't understand. I compiled it using MinGW.. What did i do wrong? Let us first filter it down to the relevant entries, the ones about your mysql dll's: [quote] QFactoryLoader::QFactoryLoader() looking at "C:/QtSDK/Desktop/Qt/4.8.1/mingw/plugins/sqldrivers/qsqlmysql4.dll" In C:/QtSDK/Desktop/Qt/4.8.1/mingw/plugins/sqldrivers/qsqlmysql4.dll: Plugin uses incompatible Qt library expected build key "Windows mingw debug full-config", got "Windows mingw release full-config" "The plugin 'C:/QtSDK/Desktop/Qt/4.8.1/mingw/plugins/sqldrivers/qsqlmysql4.dll' uses incompatible Qt library. Expected build key "Windows mingw debug full-config", got "Windows mingw release full-config"" not a plugin [/quote] Ok, seems you are running a debug version of your app, with a debug Qt library, and that means you cannot load a release version... Makes sense, and the lack of a 'd' in the name of the library also indicates a release version. So far, no worries. [quote] QFactoryLoader::QFactoryLoader() looking at "C:/QtSDK/Desktop/Qt/4.8.1/mingw/plugins/sqldrivers/qsqlmysqld4.dll" QLibraryPrivate::loadPlugin failed on : " could not load [/quote] Now it starts to get serious. Qt tried to load this plugin, but failed. The library failed to load, but it does not tell you why. Time to debug that further. Usually, when a library fails to load, it misses a dependency. So, get yourself a copy of the dependency walker tool to figure out what library the driver is trying to load and fails at. I can guess which one though: a core mysql library. Did you really follow the guide I linked to before? Including step 6? Thanks alot for your time !! really appreciated.. I remember i copied the 64 bit DLL version of libmysql.dll into C:\Windows That was the problem, now i copied the 32bit, and it works. Thanks!! Please add a [Solved] tag to the topic title (by editing your first post in the topic) if you feel your problem has been solved. Where will i get libqsqlmysql4.a libqsqlmysqld4.a
https://forum.qt.io/topic/18152/solved-mysql-driver-c
CC-MAIN-2017-51
refinedweb
994
67.55
This site uses strictly necessary cookies. More Information (issue on Unity 4.3.2f1) As you may know, in monodevelop 4.0.1 just under the tabs there is a bar that states the name of the script and (as it seems) what you're modifying e.g. [C] playerScript > [M] Awake. This is normally present 100% of the time and the console was clear until randomly I noticed that there were errors, a lot of errors e.g. BCE0044: expecting (, found 'OnTriggerEnter'. and I used OnTriggerEnter as a function. function OnTriggerEnter () { I didn't do anything like. if (OnTriggerEnter == false); yet there was an error. and I noticed that the [C] playerScript > [M] Awake just said No Selection. This now happens in any script I modify in any project, even after a reinstall. I'm not expecting a straight forward answer but any 'fix' attempt would be greatly appreciated. Answer by Cresspresso · Nov 27, 2016 at 08:35 PM Are you sure all the code before that function is syntactically correct? I.e. did you forget to include a } or a )? If your code is perfect, and there are no errors in the console in Unity, you don't have to worry about errors that appear in MonoDevelop or VisualStudio. I don't know why these 'ghost' errors appear, but if it compiles correctly in Unity, it will work. I personally do not use MonoDevelop anymore, so I did not know there was a little '[C] class > [M] function' hierarchy in the UI, so I cannot help you with that, sorry. $$anonymous$$y personal fix would be switching to C# and use VisualStudio. ^^ $$anonymous$$onoDevelop is just a conglomerate of many many bugs. I have not counted how many times $$anonymous$$onoDevelop itself crashed or just the intellisense module (where you could strike out "intelli"). Even the code completion module is very "sensitive". If something isn't quite right the auto completion just completely breaks. VisualStudio on the other hand sometimes even predicts things correctly that hasn't been yet fixed (like a missing namespace). Never (ever) had a crash of VS. I guess you use sublime? ^^ How well does it integrate into Unity? As far as unity was concerned before this happened everything was fine, no EOF errors, no missing references... but I have found out since posting this that every time I open a project that has been changed, the Compiling Scripts dialog box always appears for a split second, followed by unity vomiting all these errors back out. It's like it keeps ?re-importing? the scripts with the changes, without success. As for visual studio which of the 4 versions would you recommend? I know nothing about it and would it be wise to get an older version than the current one? Ironic to my user name, I do not use SublimeText. I use and adore Visual Studio Community 2015. It is free, and since about Unity 4, it is the recommended/default text editor. If you want to re-import files so that Unity is sure to find all the changes, you could open the Assets folder in Windows Explorer, check Show Hidden, and delete the file's accompanying .meta file. I'm not sure if this will fix this specific problem, but it's worth a shot. $$anonymous$$aybe you could give examples of the errors you are receiving, and the associated scripts, please? Right O$$anonymous$$ this was wierd, but in response most of the errors were like found ( expecting ; but after restarting my laptop (something I already did at least 3 times) its... resolved and I have no idea why. I'm guessing this isn't a common issue, but it's a thing and it's scary. I sporadically question myself why "Report a problem with unity" existed in the install. Never thought I would ever. C# script editor won't open? What should I do 2 Answers my Monodevelop can't code, any help or solution? 2 Answers MonoDevelop Template internal variables and functions? 2 Answers error CS0118: `UnityEngine.Object.Destroy(UnityEngine.Object, float)' is a `method' but a `type' was expected problem 1 Answer No suitable method found to override 0 Answers EnterpriseSocial Q&A
https://answers.unity.com/questions/1277146/typing-anything-anywhere-in-script-ceases-all-func.html
CC-MAIN-2021-25
refinedweb
707
66.03
This chapter contains the following topics: An Application Class for Sessions Providing a Stateful Web Experience with PHP Sessions The Application Login Page To start creating the AnyCo application, create a cascading style sheet file style.css. It contains: /* style.css */ body { background: #FFFFFF; color: #000000; font-family: Arial, sans-serif; } table { border-collapse: collapse; margin: 5px; } tr:nth-child(even) {background-color: #FFFFFF} tr:nth-child(odd) {background-color: #EDF3FE} td, th { border: solid #000000 1px; text-align: left; padding: 5px; } #header { font-weight: bold; font-size: 160%; text-align: center; border-bottom: solid #334B66 4px; margin-bottom: 10px; } #menu { position: absolute; left: 5px; width: 180px; display: block; background-color: #dddddd; } #user { font-size: 90%; font-style:italic; padding: 3px; } #content { margin-left: 200px; } This gives a simple styling to the application, keeping a menu to the left hand side of the main content. Alternate rows of table output are colored differently. See Figure 1-1 in Chapter 1, "Introducing PHP with Oracle Database XE." For the AnyCo application we will create two classes, Session and Page, to give some reusable components. The Session class is where web user authentication will be added. It also provides the components for saving and retrieving web user "session" information on the mid-tier, allowing the application to be stateful. PHP sessions are not directly related to Oracle sessions which were discussed in the DRCP overview. Data such as starting row number of the currently displayed page of query results can be stored in the PHP session. The next HTTP request can retrieve this value from the session storage and show the next page of results. Create a new PHP file called ac_equip.inc.php initially containing: <?php /** * ac_equip.inc.php: PHP classes for the employee equipment example * @package Equipment */ namespace Equipment; /** * URL of the company logo */ //define('LOGO_URL', ''); /** * @package Equipment * @subpackage Session */ class Session { /** * * @var string Web user's name */ public $username = null; /** * * @var integer current record number for paged employee results */ public $empstartrow = 1; /** * * @var string CSRF token for HTML forms */ public $csrftoken = null; } ?> The file starts with a namespace declaration, Equipment in this case. The commented out LOGO_URL constant will be described later in the Chapter 12, "Uploading and Displaying BLOBs." The $username attribute will store the web user's name. The $empstartrow attribute stores the first row number of the currently displayed set of employees. This allows employee data to be "paged" through with Next and Previous buttons as shown in Figure 1-1, "Overview of the Sample Application". The $csrftoken value will be described in the Chapter 9, "Inserting Data." Add two authentication methods to the Session class: /** * Simple authentication of the web end-user * * @param string $username * @return boolean True if the user is allowed to use the application */ public function authenticateUser($username) { switch ($username) { case 'admin': case 'simon': $this->username = $username; return(true); // OK to login default: $this->username = null; return(false); // Not OK } } /** * Check if the current user is allowed to do administrator tasks * * @return boolean */ public function isPrivilegedUser() { if ($this->username === 'admin') return(true); else return(false); } The authenticateUser() method implements extremely unsophisticated and insecure user authentication. Typically PHP web applications do their own user authentication. Here only admin and simon will be allowed to use the application. For more information on authentication refer to The isPrivilegedUser() method returns a boolean value indicating if the current user is considered privileged. In the AnyCo application this will be used to determine if the user can see extra reports and can upload new data. Only the AnyCo "admin" will be allowed to do these privileged operations. PHP can store session values that appear persistent as users move from HTML page to HTML page. By default the session data is stored in a file on the PHP server's disk. The session data is identified by a unique cookie value, or a value passed in the URL if the user has cookies turned off. The cookie allows PHP to associate its local session storage with the correct web user. PHP sessions allow user HTTP page requests to be handled seamlessly by random mid-tier Apache processes while still allowing access to the current session data for each user. PHP allow extensive customization of session handling, including ways to perform session expiry and giving you ways to store the session data in a database. Refer to the PHP documentation for more information. To store, fetch and clear the session values in the AnyCo application, add these three methods to the Session class: /** * Store the session data to provide a stateful web experience */ public function setSession() { $_SESSION['username'] = $this->username; $_SESSION['empstartrow'] = (int)$this->empstartrow; $_SESSION['csrftoken'] = $this->csrftoken; } /** * Get the session data to provide a stateful web experience */ public function getSession() { $this->username = isset($_SESSION['username']) ? $_SESSION['username'] : null; $this->empstartrow = isset($_SESSION['empstartrow']) ? (int)$_SESSION['empstartrow'] : 1; $this->csrftoken = isset($_SESSION['csrftoken']) ? $_SESSION['csrftoken'] : null; } /** * Logout the current user */ public function clearSession() { $_SESSION = array(); $this->username = null; $this->empstartrow = 1; $this->csrftoken = null; } These reference the superglobal associative array $_SESSION which gives access to PHP's session data. When any of the Session attributes change, the AnyCo application will call setSession() to record the changed state. Later when another application request starts processing, its script will call the getSession() method to retrieve the saved attribute values. The ternary " ?:" tests will use the session value if there is one, or else use a hardcoded default. Finally, add the following method to the Session class to aid CSRF protection in HTML forms. This will be described in the section CSRF example with ac_add_one.php in Chapter 9, "Inserting Data." /** * Records a token to check that any submitted form was generated * by the application. * * For real systems the CSRF token should be securely, * randomly generated so it can't be guessed by a hacker * mt_rand() is not sufficient for production systems. */ public function setCsrfToken() { $this->csrftoken = mt_rand(); $this->setSession(); } A Page class will provide methods to output blocks of HTML output so each web page of the application has the same appearance. Add the new Page class to the ac_equip.inc.php file after the closing brace of the Session class, but before the PHP closing tag ' ?>'. The class initially looks like: /** * @package Equipment * @subpackage Page */ class Page { /** * Print the top section of each HTML page * @param string $title The page title */ public function printHeader($title) { $title = htmlspecialchars($title, ENT_NOQUOTES, 'UTF-8'); echo <<<EOF <!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" ""> <html> <head> <meta http- <link rel="stylesheet" type="text/css" href="style.css"> <title>$title</title> </head> <body> <div id="header"> EOF; // Important: don't have white space on the 'EOF;' line before or after the tag if (defined('LOGO_URL')) { echo '<img src="' . LOGO_URL . '" alt="Company Icon"> '; } echo "$title</div>"; } /** * Print the bottom of each HTML page */ public function printFooter() { echo "</body></html>\n"; } } The printHeader() method prints the HTML page prologue, includes the style sheet, and prints the page title. A PHP 'heredoc' is used to print the big block of HTML content. The variable $title in the text will be expanded and its value displayed. The closing tag ' EOF;' must be at the start of the line and also not have any trailing white space. Otherwise the PHP parser will treat the rest of the file as part of the string text and will produce a random parsing error when it encounters something that looks like a PHP variable. A logo will also be displayed in the header when LOGO_URL is defined in a later example, remember it is currently commented out at the top of ac_equip.inc.php. The printFooter() methods simply ends the HTML page body. A general application could augment this to display content that should be printed at the bottom of each page, such as site copyright information. The AnyCo application has a left hand navigation menu. Add a method to the Page class to print this: /** * Print the navigation menu for each HTML page * * @param string $username The current web user * @param type $isprivilegeduser True if the web user is privileged */ public function printMenu($username, $isprivilegeduser) { $username = htmlspecialchars($username, ENT_NOQUOTES, 'UTF-8'); echo <<<EOF <div id='menu'> <div id='user'>Logged in as: $username </div> <ul> <li><a href='ac_emp_list.php'>Employee List</a></li> EOF; if ($isprivilegeduser) { echo <<<EOF <li><a href='ac_report.php'>Equipment Report</a></li> <li><a href='ac_graph_page.php'>Equipment Graph</a></li> <li><a href='ac_logo_upload.php'>Upload Logo</a></li> EOF; } echo <<<EOF <li><a href="index.php">Logout</a></li> </ul> </div> EOF; } The user name and privileged status of the user will be passed in to customize the menu for each user. These values will come from the Session class. Later chapters in this manual will create the PHP files referenced in the links. Clicking those link without having the files created will give an expected error. The three classes: Db, Session, and Page, used by the AnyCo application are now complete. The start page of the AnyCo application is the login page. Create a new PHP file called index.php. In NetBeans replace the existing contents of this file. The index.php file should contain: <?php /** * index.php: Start page for the AnyCo Equipment application * * @package Application */ session_start(); require('ac_equip.inc.php'); $sess = new \Equipment\Session; $sess->clearSession(); if (!isset($_POST['username'])) { $page = new \Equipment\Page; $page->printHeader("Welcome to AnyCo Corp."); echo <<< EOF <div id="content"> <h3>Select User</h3> <form method="post" action="index.php"> <div> <input type="radio" name="username" value="admin">Administrator<br> <input type="radio" name="username" value="simon">Simon<br> <input type="submit" value="Login"> </div> </form> </div> EOF; // Important: don't have white space on the 'EOF;' line before or after the tag $page->printFooter(); } else { if ($sess->authenticateUser($_POST['username'])) { $sess->setSession(); header('Location: ac_emp_list.php'); } else { header('Location: index.php'); } } ?> The index.php file begins with a session_start() call. This must occur in code that wants to use the $_SESSION superglobal and should be called before any output is created. An instance of the Session class is created and any existing session data is discarded by the $sess->clearSession() call. This allows the file to serve as a logout page. Any time index.php is loaded, the web user will be logged out of the application. The bulk of the file is in two parts, one creating an HTML form and the other processing it. The execution path is determined by the PHP superglobal $_POST. The first time this file is run $_POST['username'] won't be set so the HTML form along with the page header and footer will be displayed. The form allows the web user login as Administrator or Simon. The submission action target for the form is index.php itself. So after the user submits the form in their browser, this same PHP file is run. Since the submission method is " post", PHP will populate the superglobal $_POST with the form values. This time the second branch of the ' if' statement will be run. The user is then authenticated. The radio button input values ' admin' and ' simon' are the values that will be passed to $sess->authenticateUser(). A valid user will be recorded in the session data. PHP then sends back an HTTP header causing a browser redirect to ac_emp_list.php. This file will be created in the next section. If the user is not validated by $sess->authenticateUser() then the login form is redisplayed. Note that scripts should not display text before a header() call is run. To run the application as it stands, load index.php in a browser. In NetBeans, use Run->Run Project, or press F6. The browser will show:
http://docs.oracle.com/cd/E17781_01/appdev.112/e18555/ch_four_anyco_app.htm
CC-MAIN-2015-32
refinedweb
1,957
54.52
I am using the following circuit with the given code. When running at low speed (500 ms) all columns are displayed individually perfectly. But when trying to use POV to combine them together, the row disappears. Not sure if this the correct place to post this question, but any help would be appreciated. #include <mega8.h> #include <delay.h> #include <stdint.h> #define sclock PORTB.1 #define slatch PORTB.2 #define sdata PORTB.0 uint8_t j,i=0,a[]={255, 255, 193, 247, 247, 193, 255, 255}; void dshift(uint8_t data) { uint8_t i=0; for(i=0;i<8;i++) { if(data & 0b10000000) { sdata=1; } else { sdata=0; } sclock=1;sclock=0; data=data<<1; //Now bring next bit at MSB position } slatch=1;slatch=0; delay_us(5); }) { dshift(a[0]); for(i=0,j=1;i<8;i++) { delay_us(500); dshift(a[(i+1)%8]); PORTB.3=1; PORTB.3=0; } } } Your schematic shows Q8, Q9, and /CO of the 4017 all connected together, but those are all outputs. Just connect Q8 to MR (reset) to create an eight stage counter. Aside from that I did not find a problem. --Mike Top - Log in or register to post comments Duplicate post with this one...... 'm getting very confused -- is like the paper with a question and "(over)" on the bottom; on the reverse it says "See other side". The other thread is l9ocked for some reason. That dealt with syntax errors, and some moved on to style suggestions. Cliff, I'm not able to respond as the moderator cabal locked the thread. 1) Like js, it gets harder and harder for me to have a bad hair day. 2) I directly quoted what you said in the past, didn't I? Isn't that quite different from your postings in that thread on the same topic? Is there some reason that pointing out what was said in the past is antagonistic? 3) Indeed, it is pretty much (the "dot syntax") tongue-in-cheek. Yet, by that year the "non-standard flag waving" had mellowed a bit. Shall I dig out the lengthy thread the "prior art" of the dot syntax? 4) I still want to hear about OP's version. If indeed no Help and no inkling of Web presence, my first tho9ught is "cracked". 5) How did OP get from syntax errors on a simple test program to partially-working full app in less than a day? You can put lipstick on a pig, but it is still a pig. I've never met a pig I didn't like, as long as you have some salt and pepper. Top - Log in or register to post comments I see two problems- 1. How do you know what state the 4017 is in? It might work on simulation, but not in real life. 2. Because you can’t directly control the columns (rows), you will get ghosting. You need to turn the column off, output new row data, then enable the next column. The technique is called ‘multiplexing’. It relies on POV. Searching for the correct term might help with more examples. Top - Log in or register to post comments Ross McKenzie ValuSoft Melbourne Australia Top - Log in or register to post comments 1. This is actually not a duplicate post. This is related to a problem with POV, while the other one had a problem with how to take input into atmega 8 2. I'm pretty sure you misunderstood the wire there: Top - Log in or register to post comments I think I am using multiplexing here, via the 4017 itself. I was given a project to make this work on simulation, after which I can test it on real hardware from our electronics club. Top - Log in or register to post comments The other thread is now unlocked by popular demand. John Samperi Ampertronics Pty. Ltd. * Electronic Design * Custom Products * Contract Assembly Top - Log in or register to post comments +1 . This is exactly what "ghosting problem" is. İf you try on real hardware you will see the ghost! İt is a pale copy of column apears at previous column. Proteus does not simulate ghosting problem. . As mentioned in #5 the key point is you need to turn off previous column before selecting next column. . 1.turn off current data (send blank data) 2.select next column 3.send next column data 4.delay for POV Majid Top - Log in or register to post comments Hey guys, So I decided to use an RGB matrix instead of a red one and I need to do color mixing at different leds. So I've decided to get some common anode RGBs such that the cathode ground can be controlled to do the color mixing. I read up on pwm in CV AVR and realized i have to use OC01 and timer functions to control pwm. but what will i connect the pwm output to and how will i control it to make sure all the leds get the appropriate pwm at each pin? I know I have to control the duty cycle of the wave to make it pwm, but can't figure out how to get different duty cycles for different pins. PS: the circuit will approximately be the same, with a 4017 at the anode, but 3 shift registers for each of the 3 pins. How will I pwm the shift register pins? Any basic logic would be very helpful. PPS: I shouldn't need to go for values except 255 and 127 Top - Log in or register to post comments Ideally you would use a different chip since the mega8 only has two compare match registers on timer 1. With three, you could set the R, G, and B values in the OCRnA, OCRnB, and OCRnC registers and use the timer overflow interrupt to advance to the "next" LED. The mega 328 does not have three OCR registers either on any one timer. The mega 128 and 2560 do, for example, but these are much bigger chips. Let us know if you are "stuck" with the mega 8 for some reason. --Mike Top - Log in or register to post comments I'm using the electronics club's components, so i'm stuck with the mega 8. I can get them to buy any cheaper ICs though. So, if any substitute is possible, that would be helpful Top - Log in or register to post comments You can use binary code modulation -... This technique has been used in the Arduino drivers for the 32x32 rgb led panels. This should allow you to get by with one timer. The 4017 has poor drive capability - you'd most likely be better using another 595. I just looked at the specs for a 4017 - lucky if you get much more than 1mA. The beauty of using all 595's is that you can shift in the next frame of data whilst the current one is displaying. To update all you do is toggle the latch pin. Rinse and repeat. To eliminate the ghosting you can connect the column drive 595 output enable pin to a port pin. Disable the columns, toggle the latch, re-enable the columns. Top - Log in or register to post comments
https://www.avrfreaks.net/forum/led-matrix-hc595-4017-and-atmega8-not-behaving-expected
CC-MAIN-2021-25
refinedweb
1,216
73.88
switching letters with one regex - Andrew Schultz last edited by Andrew Schultz I have a few lines of text like so: nnseww wwwnensen Basically north, south, east and west. It’s not bad at all in PERL. $x =~ tr/nsew/snwe/; And I have a way to flip things around, but it’s messy. - change n to z1 - change s to z2 - change e to z3 - change w to z4 - change z1 to s - change z2 to n - change z3 to w - change z4 to e Now, this works, but it doesn’t feel as clean as, say, the perl script that translates… I also noticed this SuperUser thread. Has there been any new regex stuff in the last 4 years, or will I just need to use PERL for this sort of thing? This is hardly a painful issue but I was just curious about if there was a quicker way to do things than what I found. Thanks! if by, any chance, a python script can be used, than this one line could be helpful. editor.replaceSel(''.join([{'n':'s','s':'n','e':'w','w':'e'}.get(x, x) for x in editor.getSelText()])) It gets a selected text and replaces each n,s,e,w with their flipped counterparts. Cheers Claudia Hello, Andrew Schultz and Claudia, This time, Claudia, my following regex S/R seems shorter than your Python script ;-)) So, Andrew, just : Select the Regular expression mode in the Replace dialog Type, in the Find what: zone, (s)|(n)|(e)|(w) Type, in the Replace with: zone, (?1n)(?2s)(?3w)(?4e) Click on the Replace All button Et voilà ! Best Regards, guy038 @guy038 what should I say - brilliant :-) Maybe we should think about rejecting all programming languages and do regex only ;-) Cheers Claudia - Jim Dailey last edited by @Claudia-Frank Until you realize that regex is just another programming language. :-) a vicious circle :-D Cheers Claudia Claudia and Jim, Claudia, oh no ! Definitively not ! It’s just that, when I see some changes of text, which involve current file ONLY, and which need ONLY one S/R, regular expressions seem to be, most of the time, the shorter way to get the job done ! BTW, I will send you, soon, my own version of your excellent RegexTesterPro.py script. Just to know your feedback about my modifications and, ( again ! ) some suggestions :-)) Cheers, guy038 P. S. : BTW, for an quick oversight about the differences between Formal languages, Programming languages and Regular expressions, refer to that interesting article ( especially, the answers of babou and tsleyson !! ) Specifically, about regular expressions, read this Wikipedia article : And, particularly, the sections : - Andrew Schultz last edited by @guy038 Wow! Very well done and creative! Thanks also for the other links. @Claudia-Frank I’m learning python, and a script like that helps show me its power. This looks like it can be extended nicely to other cases where I need to flip 2 strings or rotate 3. So I really appreciate that. I wish I’d remembered to check earlier…I need to go figure how to send alerts to my email. I thought it would’ve happened automatically. It’s pretty awesome, though, to learn about programming on a word processing forum. NotePad++ really has been a boon to me. So, I, too, have a Perl background and have more than once, when doing Python, wished for something like Perl’s tr feature. So this thread inspired me to put together something a little more generic than @Claudia-Frank 's earlier script. The following can be used in either Python or Notepad++'s Pythonscript: def translate(input_str, orig_chars, new_chars): assert len(orig_chars) <= len(new_chars) trans_dict = {} for (j, v) in enumerate(orig_chars): trans_dict[v] = new_chars[j] return ''.join([ trans_dict.get(x, x) for x in input_str ]) An example calling, using this thread’s original problem text, would be: x = 'nnswwennswwwwweee' print x y = translate(x, 'news', 'swen') print y which will print: nnswwennswwwwweee ssneewssneeeeewww Scott, a nice one - like it. Copied and backed up. Cheers Claudia HAHA…well, it’s pretty much an obvious rip-off of your earlier one, which hurt my brain when I first saw it. :-) my own version of your excellent RegexTesterPro.py script Hello guy, I was just wondering if we are going to see your mentioned script HERE, perhaps sometime soon? :) One thing that concerns me is that, while I’m sure the script is super-useful (as @Claudia-Frank 's versions in the past have also been), it will do Python-flavored regex’s and not Notepad++ -flavored regexes. For example, I have tried the “news” substitution that this thread began with, and while it works in N++, I haven’t been able to get something like it to work in Python–maybe I’m doing something wrong… editor.rereplace(r'(s)|(n)|(e)|(w)', r'(?1n)(?2s)(?3w)(?4e)') did I miss something? Or did you use the python re module? In this case, yes, it doesn’t have the conditional substituion functionality. Just for completeness, RegexTester has been designed to test a regular expression, current version, and I assume this is still true even with the changes guy made, cannot do replaces. Cheers Claudia I was speaking of the Python re module; I forgot about the .research and .rereplace functions as I just tend to use the re ones. It didn’t occur to me that the editor ones would call the same regex engine as an interactive find/replace, but it makes perfect sense that they would. Thanks (again) for pointing out the obvious. I realize the regextester currently does only find, but was thinking that the next logical extension might be to do something with replace. Thinking more about it, maybe that isn’t really practical… - glennfromiowa last edited by Type, in the Find what: zone, (s)|(n)|(e)|(w) Type, in the Replace with: zone, (?1n)(?2s)(?3w)(?4e) I just stumbled across your post, and this is the first time I’ve ever seen this! Where is this documented? I mean, I think your example tells me everything I need to know, but I wish there were more examples like this in the Wiki page on Regular Expressions! It isn’t even mentioned that the (?...)construct can be used in the Replace with (Substitutions) part. I felt like it should be able to be done, and yet I hadn’t been able to figure out the syntax yet. So powerful, and yet way too much trial and error needed to discover what it can do! You can find that in the Boost Regex Replace documentation, in the “Conditionals” section. Here’s a possible link to that Boost documentation: The example from @guy038 's usage is a special case of this explanation from those docs: For example, the format string "(?1foo:bar)" will replace each match found with "foo" if the sub-expression $1 was matched, and with "bar" otherwise. BTW, @glennfromiowa , Welcome Back to the Community after a long time away…where ya been? :-D - glennfromiowa last edited by Thanks, @Scott Sumner, I’ve been workin’. But now my work seems to lie in using RegExes to do things I couldn’t do easily without them, so here I am, back again.
https://community.notepad-plus-plus.org/topic/12887/switching-letters-with-one-regex/?page=1
CC-MAIN-2020-16
refinedweb
1,212
69.72
WCF service may scale up slowly under load When your WCF service receives a burst of requests, the default .Net I/O Completion Port (IOCP) thread pool may not scale up as quickly as desired and your WCF response time will increase as a result. Depending on the execution time and number of requests received you may notice the WCF execution time increase linearly by approximately 500ms for each request received until the process has created sufficient IOCP threads to service the requests or sustain the incoming load. The problem is more evident in services with longer execution times. The IOCP thread pool scalability problem is not typically observed upon the initial loading of the process. SYMPTOMS Three variables that have an impact your WCF service ability to scale up at nearly the same rate as incoming requests. CAUSE 1. WCF Throttling 2. .Net CLR Threadpool.GetMinThreads value 3. .Net CLR IO Completion Port thread pool bug where IOCP threads are no longer created in a pattern corresponding to the incoming request volume prior to the Threadpool.GetMinThreads throttling value. This article describes how to resolve the problem with the .Net IOCP Threadpool, #3. If you have throttling issues due to WCF throttling or the GetMinThreads value, this solution will not avoid those throttles. See the More Information section below for guidance in identifying your scenario. The IOCP thread creation bug should be addressed in the next post 4.0 release of the .Net Framework. This scalability problem does not exist in the .Net CLR Worker thread pool. By moving the WCF service execution to another thread pool, you may incur a small amount of overhead implementing this solution. Performance results will vary per WCF Service. Test each WCF Service for individual results. RESOLUTION Note: Apply this solutionwhen using a WCF Listener which does not block the incoming thread while waiting on the WCF service code to complete.If you are unable to apply the solution in this article following the above table, an example using a private threadpool can be found in an MSDN article: Synchronization Contexts in WCF by Juval Lowy Steps to switch from the Synchronous HTTP handler to use the Async HTTP handler: Steps to implement this solution which will execute the WCF service on the .Net CLR Worker thread pool 1. WCF throttling thresholds should high enough to handle anticipated burst volume within acceptable response times. 2. If you use one of the .Net CLR default thread pools, Worker or IOCP for your WCF service, you must ensure the minimum thread count (value where thread creation throttling begins) to a number you anticipate to execute concurrently. 3. Implement the following code in your service which will then execute your WCF service on the .Net CLR Worker thread pool. This class is used to move the execution to the .Net CLR Worker thread pool. Next we need to create a custom attribute class.); } } Now to apply the custom attribute to your WCF service. Example: ) { } } [WorkerThreadPoolBehavior] public class Service1 : IService1 { public string GetData(int value) { int iSleepSec = (value * 1000); System.Threading.Thread.Sleep(iSleepSec); return string.Format("You slept for: {0} seconds", value); } } WCF uses the .Net CLR I/O Completion Port thread pool for executing your WCF service code. The problem is encountered when the .Net CLR IO Completion Port thread pool enters a state where it cannot create threads quickly enough to immediately handle a burst of requests. The response time increases unexpectedly as new threads are created at a rate of 1 per 500ms. MORE INFORMATION The problem may become more evident if your WCF service uses a technology which also utilizes the .Net CLR IOCP thread pool. For example, the Windows Server AppFabric Cache Client leverages this thread pool to a small extent. If you are not hitting the WCF throttling limits described earlier, the following information will help you determine if you are experiencing the problem with the .Net CLR IOCP thread pool. The .NET CLR thread pools use a value to determine when to begin throttling the creation of threads. This setting can be determined by calling the ThreadPool.GetMinThreads or when analyzing a process dump using the !SOS debugger extension !Threadpool. 0:000> !C:\windows\Microsoft.NET\Framework64\v4.0.30319\sos.threadpool CPU utilization: 0% Worker Thread: Total: 16 Running: 0 Idle: 16 MaxLimit: 250 MinLimit: 125 Work Request in Queue: 0 -------------------------------------- Number of Timers: 35 -------------------------------------- Completion Port Thread:Total: 26 Free: 0 MaxFree: 16 CurrentLimit: 28 MaxLimit: 1000 MinLimit: 125 The observed problem is when the .NET CLR IOCP thread pool enters a condition where a new thread is only created every 500ms (two per second) prior to the thread pool MinLimit value for the thread pool. Other expected factors which can also contribute to a thread creation delay would be memory pressure or high CPU. Monitor the process hosting your WCF service. If you notice a problem scaling up threads prior to the minimum thresholds you have set, you may be encountering the problem with the .Net CLR IOCP thread pool. To determine if this is the case, Perfmon should be used to monitor the process thread creation rate in comparison to the incoming request rate. To accomplish this, log or view the following perfmon counters (below is an example for an IIS (WAS) hosted WCF 4.0 service using a HTTP binding):You can use the WCF perfmon counters if you have them enabled as well: It is normal to see a slowly increasing thread count when the arrival rate (client requests pattern) is following the same pattern. It is only when there is an immediate spike of incoming requests and the thread count slowly increases at a rate of 2 threads per second while the WCF response time increases that a problem exists. This screenshot shows a worker process that after some time has encountered the .Net IOCP thread pool scalability issue. When the process first started, the IOCP threads are normally created in parallel to the incoming request load. In this AppPool (W3WP.EXE), there were two WCF services running. One service was using the default .Net IOCP thread pool which received a burst of 100 requests at 10:22:14 and again at 10:23:34. The second WCF service was using the above workaround to execute on the .Net Worker thread pool and received a burst of 100 requests at 10:22:54. After entering this state, a process recycle is required to restore the IOCP thread pool to a working, scalable state. >>IMAGE: 2538826 - Última revisión: 04/26/2011 13:19:00 - Revisión: 1.1 - KB2538826
https://support.microsoft.com/en-us/kb/2538826
CC-MAIN-2016-50
refinedweb
1,105
64.71
A RailsConf Europe '07 Diary Sat Sep 22 12:31:41 CEST 2007 Flight STR–TXL, Sunday Flying with air berlin is very pleasant: You get to choose from five newspapers, get free coffee and cake, and they show you the stupid (albeit rendered) security video on a TV screen. Sunday evening Time for some Bratwurst (pics)! After arriving at our apartment and figuring out how the WLAN is supposed to work, we take the tube to Kalkscheune where lots of people are already. The rug-b people made name tags for us. (Hey Vico!) After we all had enough Bratwurst, some go play Werewolf while we decide to go to the Tacheles (a.k.a. “shitty building”) and have some beer. Monday Since I didn’t book any tutorial sessions, it’s time to sleep out. We try to fix the WLAN but completely fuck it up. (You should have seen us trying to even find the router!) Later, we go to the great St. Oberholz (blog) cafe which has good coffee, good food, free wifi and Bionade. Not to forget nice waiters (Hey Ines!) and lots of Mac users. I had a heavy walnut tarte. Monday evening We missed Dave Thomas’s keynote because had a big Thai dinner. It was awesome and very tasty. And hot. Some go play Werewolf. Later we tried to find the Havanna Club Club, where there was a guy which a friend of a friend one of us knows. We searched for an hour, and ended up at the Madonna Bar, where we had some beer. Tuesday Being a bit late, I rushed into the DHH keynote. He showed evolutionary advancements on the way to Rails 2.0, for example automatic database setup, easier-to-read ActiveRecord inspects (yay) and partials by object type (which is pretty nice). He also demonstrated how to add new content-types to create special output for the iPhone. Finally, he announced a Rails 2.0 preview release to appear shortly after the conference. Then, I attend the first sessions: Deployment and Continuous Integration from the Trenches by Fernand Galiana, who talked about new features in Capistrano 2 such as namespaces, different deployment strategies and events, which allow for seperation of aspects. After a whirlwind tour of cap2 we learned about certain traps and how to avoid them, for example by using lazy variable expansion. He also showed best practices such as factoring common code with load, multistage deployment and caches, which also can use rsync now. Fernand concluded his talk by showing a quick example of how to write your own tasks and announcing his Rails-driven Capistrano frontend dubbed Capote. His talk was amusing and full of hilarious engineering pictures. Next up was Dr. Nic Williams with his excellent talk Meta-Magic in Rails: Become a Master Magician which started with a list of features he liked in Ruby and which help doing meta-stuff like the flexible syntax and the highly dynamic behavior. He explained he likes “a big number of complexity” and went on to compare Perl with a puppy unconscious of itself, Java with Keith Richards, and Ruby with Matrix’s Neo, who knows everything about himself and his environment. He introduced his Magic Models which use const_missing to generate ActiveRecord models on the fly and outlined a few important meta-programming techniques. It was a really funny and instructive talk (at least if you are not already a Ruby pro). In the lunch break, I got to know some found the Havanna Club Club later, and it was just where we searched. Sigh. In the afternoon, I attended Really scaling Rails by Britt Selvitelle, who works for flickr (thanks, nec). After explaining to the audience that most of them probably won’t need his hints yet, he explained their mongrel setup (they only proxy one request at a time from Apache to each mongrel, so requests won’t queue up) and gave tips on benchmarking actions. He insisted on not over-architecting. Furthermore, he explained how to create daemons for long-running tasks (such as informing 10000 followers of twitter’s popular users) and how to cache DB queries. He also introduced starling, which is an in-house queue server they wrote. If you can, cheat, he recommended to us, meaning that users won’t notice if things don’t update in real time or are totally synchronous. He also told about essential things for deployment, such as monitoring and easy deploy/rollback. Scaling is only needed where it matters. Lastly, he explained the importance of an API for twitter and how it was relevant for the big community they now have. The next talk was Improving the Rails ecosystem by Evan Phoenix, the leader of the Rubinius project. He talked about how a better Ruby results in a better Rails and how Rubinius is focused on improving some Ruby deficiencies, like full operator overloading (you can overload != by itself), better memory usage (better sharing among forked processes), .rba archives for easier code deployment and more readable and informative backtraces. He announced they would release a 1.0 at the end of the year and concluded the talk with an extensive Q&A session. This was a very funny talk as well, last but not the least because of his sole usage of made-up statistics. (Rubinius is faster than three-legged dogs and turtles, but slower than the Space Shuttle, you knew?) The day ended with Roy Fielding’s keynote The Rest on REST2, who once looked at the entire web—back when it was fifty sites. After a short history of the web until 1995, we got to know he was the main HTTP RFC editor and he went on outlining the web’s architecture. He explained how REST implies hypertext in some sense and how it made the web bigger. He also told he had a look at Rails and tried to show how to make it more RESTful (he lauded the CRUD); most things already can be done easily. It was a good talk (have a look at the slides, they are self-explaining mostly) and I really liked the small quotes on top of each slide. Tuesday evening We had some Schnitzel at a restaurant Unter den Linden which name I forgot. Then, we headed to RejectConf which took place at the Pirate Cove (noone noticed that tomorrow would be Talk Like A Pirate Day, though. Arrr!!) Some went to play Werewolf. Dr. Nic praised me for even being able to talk about Ruby meta-programming after some rounds of Jägermeister shots. No big deal. ;-) The caboosers also got a new set of t-shirts. (Thanks, chrissturm.) Wednesday The second day of the conference sessions started with Best Practices by Marcel Molina Jr. and Michael Koziarski of the Rails core team. (We learned Jamis Buck wasn’t there because his wife got a child.) They noticed most Rails projects stuff too much stuff into the controller and not enough into models. They explained that the controller merely should contain action code and most of the business logic belongs to the models. Marcel recommened the Smalltalk Best Practices book again, which is really worth a read. Michael talked about how association proxies make you code easier to understand and how to factor code into many descriptive methods. Then, I attended JRuby at Thoughtworks by Ola Bini, who complained about MRI having threading issues, bad unicode support, and speed and GC problems. JRuby, which was started in 2001(!), tries to address all these problems. He also told that Java 6 made JRuby twice as fast without changing anything. JRuby will be compiled to bytecode to allow obfuscation, which is important for certain businesses. It also allows for easier deployment. At the end of his talk, he introduced his new Apress book “JRuby on Rails”. After this, I went to Ruby on Rails Security by Heiko Webers, which was a lemon. He tried to shock the audience by telling he saw lots of session ids on the wifi, but proceded to give a totally boring talk about essential security concepts which would have been demonstrated a lot better by, well, demonstrating them. More action please! In the lunch break, I met David Chelimsky of the RSpec team. We talked a bit about BDD and the future of RSpec and test/spec. He also explained the new StoryRunner to me. Then, I met Geoffrey Grosenbach and we recorded a Ruby on Rails podcast out of the blue! The first afternoon session I attended was Browser-based Testing of Massive Ajax-using Rails Applications with Selenium, by Till Vollmer of MindMeister, a pretty neat AJAX mindmapping tool. He explained what Selenium is, and how usual tests don’t test browser behavior, which is essential for them. After a quick overview of Selenium’s features, he demonstrated their test suite for a live example. Next was Functional JavaScript Development with Prototype by Ben Nolan. He told about JavaScript lambdas and what binding them means and went on talking about Prototypes enumberable extensions which have lots of useful methods like invoke, pluck or inGroupsOf. He mentioned taking some Haskell courses at university and stated JavaScript code is much easier to develop and debug when it consists of small, idempotent functions. Also, he recommended to store data in the DOM and not in private properties of JavaScript objects. After the afternoon break, I went to Jay Fields’ talk on Extending Rails to Use the Presenter Pattern which was very fuzzy and mellow. He couldn’t really get his point across and most of the audience left the session without knowing what a presenter even is, which is kind of sad since it surely could have been useful in some situations. Or not. The last session, PhD on Rails by Sam Aaron however saved the day. It was such a refreshing, intelligent and humorous talk that I completely forgot to take notes. Let me try to remember: He created a database backed system to keep track of objects which are rendered in a three dimensional spaces and then implemented a query language to operate on them. Really cool. And the first person I met that uses VRML. Wednesday evening We tried to find a restaurant for roughly 25 persons which was not that easy. We ended up in a pretty expensive French brasserie, but I liked my dinner. Some went to play Werewolf. The rest went to Ambulance Bar where we had half a dozen cocktails each. They were very good. We got back to the appartment at 3am, just before the Werewolf players finished. Thursday I decided to stay one more day after the conference, and we spent all day at St. Oberholz again. I had a great tiramisu and a beagel. Yum. Thursday evening We decided to go to the Fernsehturm for dinner, had a Weizenbier up there waiting until we could enter the spinning restaurant, which was pretty cool. The food was far better than I expected and not even that expensive. After dinner, we went back to the appartment because we all would need to wake up pretty early. Flight TXL–FMM, Friday I had to wake up 6am to get to the airport in time. I met Geoffrey there again and we had another little chat. I flew back with tuifly, which let me chose whether I wanted to be seated to the window or not but had no free coffee or other features. They play the stupid security video for you. It was a bit cheaper, though. General points git is gaining popularity among Ruby hackers, I saw lots of them installing it and toying around. Berlin: I had forgotten how great the city is. The complete and utter lack of aesthetics actually is appealing, but the icky typography in the subway hurts my soul. NP: Bob Dylan—This Wheels On Fire
http://chneukirchen.org/blog/archive/2007/09/a-railsconf-europe-07-diary.html
crawl-002
refinedweb
1,993
71.65
Booting Linux: EFI and Management Processor - EFI and POSSE - Configuring the Management Processor (MP). EFI and POSSE EFI is an interface between your operating systems and platform firmware. POSSE is the HP implementation of EFI that contains additional commands beyond the ones available through EFI alone. You'll use the EFI acronym in this chapter, but you should be aware that some HP documentation may use POSSE. EFI is a component that is independent of the operating system and provides a shell for interfacing to multiple operating systems The interface consists of data tables that contain platform-related information along with boot and runtime service calls that are available to the operating system and its loader. These components work together to provide a standard environment for booting multiple operating systems. If you are interested in finding out more about EFI than what's documented here, take a look at Intel EFI Web site. At the time of this writing, EFI information can be found at. As you can see in Figure 1-1, EFI on HP Integrity servers contains several layers. The hardware layer contains disk with an EFI partition, which in turn has in it an operating system loader. This layer also contains one or more operating system partitions. Figure 1-1 EFI on HP Integrity Servers In addition, the EFI system partition itself consists of several different components as shown in Figure 1-2. Figure 1-2 EFI System Partition The Logical Block Addresses (LBAs) are shown across the top of the diagram. The Master Boot Record (MBR) is the first LBA. There is then a partition table. Three partitions are shown on this disk. Note that multiple operating system partitions can be loaded on the same disk. At the time of this writing, Windows Server 2003 and Linux can be loaded on the same disk. The EFI partition table on the right is a backup partition table. Booting an operating system with EFI on an Integrity servers involves several steps. Figure 1-3 depicts the high-level steps. Figure 1-3 Load and Run an Operating System The first step is to initialize the hardware. This takes place at the lowest level (BIOS) before EFI or the operating systems play any part in the process. Next, the EFI and boot loader are loaded and run. After an operating system is chosen, the operating system loader is loaded and run for the specific operating system being booted. Finally, the operating system itself is loaded and run. There are no specific operating systems cited in Figure 1-3 because the process is the same regardless of the operating system being loaded. In the examples in this book, Linux, HP-UX, and Windows are used and all these operating systems would load in the same manner. Working with EFI Traversing the EFI menu structure and issuing commands is straight forward. You make your desired selections and then traverse a menu hierarchy. To start EFI, when the system self test is complete, hit any key to break the normal boot process. The main EFI screen appears. Figure 1-4 shows the EFI Boot Administration main screen from which you can make various boot-related selections. Figure 1-4 EFI Boot Administration Main Screen Figure 1-4 shows that there are two operating systems installed on this Integrity server an HP-UX Primary Boot and a Red Hat Linux Advanced Server. Either of these can be booted. From the main screen, you can also choose either EFI Shell [Built-in], Boot option maintenance menu, or Security/Password menu. The first item shown in the EFI main screen is the default. Use the arrow keys to scroll and highlight a selection. After the item you need is highlighted, press Enter to select it. For example, if you were to select Boot option maintenance menu, you would see a screen resembling the one shown in Figure 1-5. Figure 1-5 EFI Boot Maintenance Manager Main Menu Figures 1-4 and 1-5 give you a feeling for the menu-driven nature of EFI and EFI selections. One of the important things a system administrator might need to know is a given system's device mappings. To view mappings using EFI, you need to get to a console-like EFI Shell> prompt. To do so, you must select EFI Shell in Figure 1-4. Once at the prompt, there are a variety of commands that you can run including map. map is the EFI command that shows device mapping on the Integrity server. This listing shows the output from the map command: Shell> map fs0 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/HD(Part1,Sig8E89981A-0B97-11D7-9C4C - AF87605217DA) fs1 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun1,Lun0)/HD(Part1,Sig7C0F0000) blk0: Acpi(HWP0002,0)/Pci(2|0)/Ata(Primary,Master) blk1: Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0) blk2: Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/HD(Part1,Sig8E89981A-0B97-11D7-9C4C - AF87605217DA) blk3 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/HD(Part2,SigC9D59DF0-0BA7-11D7-9B31 - FBA1AECDAF7E) blk4 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/HD(Part3,SigC9D7945C-0BA7-11D7-9B31 - FBA1AECDAF7E) blk5 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun1,Lun0) blk6 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun1,Lun0)/HD(Part1,Sig7C0F0000) blk7 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun1,Lun0)/HD(Part2,Sig7C0F0000) The device mappings can be difficult to read. Much of the information is intended for programmers and technicians. As a system administrator, however, you need to know which entries correspond to which devices and which entries are for your partitions and file systems. To determine that, let's take a look at each entry. As you probably guessed, file systems begin with fs and block devices begin with blk in this listing. To understand these entries however, let's look at them individually. To make their meaning clearer, I've grouped the entries differently than they originally appeared in the EFI listing previously shown. Red Hat Advanced Server disk and related entries: blk1 physical disk blk2 is first partition on blk1 blk3 is second partition on blk1 blk4 is third partition on blk1 fs0 is first file system on blk1 HP-UX 11i disk and related entries: blk5 physical disk blk6 is first partition on blk5 blk7 is second partition on blk5 fs1 is first file system on blk5 Let's analyze one of the block (blk) entries: blk1 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0) blk is the label assigned to the physical drive and the 1 is the number of the physical drive (blk can also be a partition on a physical drive as we'll see shortly). Acpi(HWP0002,100) first shows a device type of HWP0002 with a PCI host number of 100. This PCI host number is often called the ROPE. The ROPE is the circuitry that handles I/O for the PCI interface. Although this information is most often used by programmers, it is sometimes handy to know the ROPE since it also defines the I/O card slot. The following types of devices are the most common: HWP0001: Single I/O Controller Single Block Address w/o I/O Controller in the namespace. HWP0002: Logical Block Address (LBA) device. HWP0003: AGP LBA device. After the ROPE we find a Pci entry. This entry indicates that the device/slot number is 1 and the function number is 0. The Scsi Pun (physical unit) will be either 0 or 1 depending on which is the SCSI address of the disk. The Lun (logical unit) will always be 0 in this case because you're not assigning any Logical Units on the disks. Now, let's look at the blk2 entry: blk2 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/ HD(Part1,Sig8E89981A-0B97-11D7-9C4C-AF87605217DA) The blk2 entry is a partition on the blk1 device. All of the information is the same for the two entries except for the additional partition-related information beginning with Part1. Part1 indicates this is the first partition on physical device blk1 with an EFI signature beginning with Sig. blk3 and blk4 are additional partitions that we created when we loaded Advanced Server on this disk and created three partitions. The first group ends with the fs0 entry: fs0 : Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/ HD(Part1,Sig8E89981A-0B97-11D7-9C4C-AF87605217DA) Notice that the fs0 line also matches blk1 and blk2 from a path perspective. This is a file system readable by EFI; hence, it begins with fs. To summarize, what we see is a physical device blk1 that has on it an EFI partition blk2 and a file system fs0. All three of these are listed as separate entries in EFI. In addition, blk3 and blk4 are partitions on the same physical device blk1. The same applies to physical unit 1, which is Pun1. This is blk5. It too has two partitions at blk6 and blk7. fs1 is the file system that is on disk. This is the HP-UX disk in our configuration: blk0 : Acpi(HWP0002,0)/Pci(2|0)/Ata(Primary,Master) The blk0 device in the list is the DVD-ROM. The Ata (Advanced Technology Attachment) is the official name that American National Standards Institute group X3T10 uses for what the computer industry calls Integrated Drive Electronics (IDE) in this case, a DVD-ROM. Table 1-1 summarizes the fields that we analyzed for all the entries. Table 1-1. Description of EFI Device Mappings Field Keep in mind that some of this information, such as the Acpi data, is most often necessary to help analyze the system in the event of a problem. Keep in mind that the file system numbers may change when you remap devices or when components are added or removed, such as a DVD device. There are many more EFI commands that you may want to use in addition to map. Table 1-2 summarizes many of the most used EFI commands. We'll take a look at some of them in the next section. Table 1-2. Commonly Used EFI Commands Using EFI, you can control the boot-related setup on your Integrity server. Because of the number of operating systems you can run on Integrity servers, you'll use this interface often to coordinate and manage them. EFI Command Examples As previously mentioned, traversing the EFI menu structure and issuing commands is straightforward. When the system boots, you are given the option to interrupt the autoboot. (If you don't interrupt it, the autoboot will load the first operating system listed which, in our case, is Red Hat Advanced Server.) At system startup, the EFI Boot Manager presents the boot option menu (as shown in the following output). Here, you have five seconds to enter a selection before Red Hat Linux Advanced Server is started: EFI Boot Manager ver 1.10 [14.60] Firmware ver 1.61 [4241] Please select a boot option Red Hat Linux Advanced Server HP-UX Primary Boot: 0/1/1/0.1.0 EFI Shell [Built-in] Boot option maintenance menu Security/Password Menu Use ^ and v to change option(s). Use Enter to select an option Default boot selection will be booted in 5 seconds You can use the arrow, or the u and d keys, to move up and down respectively. We used the ‡ key (down arrow) to select EFI Shell [Built-in]. This brought us to the Shell> prompt. From there, we can issue EFI commands. Similarly, once your at the Shell> prompt, help is always available. To get a listing of the classes of commands available in Shell>, simply enter help and press Enter: Shell> help List of classes of commands: boot -- Booting options and disk-related commands configuration -- Changing and retrieving system information device -- Getting device, driver and handle information memory -- Memory related commands shell -- Basic shell navigation and customization scripts -- EFI shell-script commands Use 'help <class>' for a list of commands in that class Use 'help <command>' for full documentation of a command Use 'help -a' to display list of all commands When using Linux from a network connection from another system you may have to use the ^ and v to move up and down the menu structure respectively. You can also issue help requests for any EFI commands at any level. For example, if you want to know more about your current cpu configuration, you would start with help configuration to determine the help command for cpu configuration, and then help cpuconfig: Shell> help configuration Configuration commands: cpuconfig -- Deconfigure or reconfigure cpus date -- Displays the current date or sets the date in the system err -- Displays or changes the error level esiproc -- Make an ESI call errdump -- View/Clear logs info -- Display hardware information monarch -- View or set the monarch processor palproc -- Make a PAL call. salproc -- Make a SAL call time -- Displays the current time or sets the time of the system ver -- Displays the version information Use 'help <command>' for full documentation of a command Use 'help -a' to display list of all commands Shell> help cpuconfig cpu Specifies which cpu to configure CPUCONFIG [cpu] [on|off] on|off Specifies to configure or deconfigure a cpu Note: 1. Cpu status will not change until next boot. 2. Specifying a cpu number without a state will display configuration status. Examples: * To deconfigure CPU 0 fs0:\> cpuconfig 0 off Cpu will be deconfigured on the next boot. * To display configuration status of cpus fs0:\> cpuconfig PROCESSOR INFORMATION Proc Arch Processor CPU Speed Rev Model Family Rev State --- ---------- ---- ----- ------ ---- ------------- 0 560 MHz B1 0 31 0 Sched Deconf 1 560 MHz B1 0 31 0 Active Shell> As a result of having issued this help cpuconfig, we now know how to manipulate the CPUs in our system. The following output shows what happens when you issue the cpuconfig command with a few options: Shell> cpuconfig PROCESSOR INFORMATION Proc Arch Processor CPU Speed Rev Model Family Rev State --- ---------- ---- ----- ------ ---- ------------- 0 1000 MHz B3 0 31 0 Active 1 1000 MHz B3 0 31 0 Active Shell> cpuconfig 1 off CPU will be deconfigured on next boot. Shell> cpuconfig PROCESSOR INFORMATION Proc Arch Processor CPU Speed Rev Model Family Rev State --- ---------- ---- ----- ------ ---- ------------- 0 1000 MHz B3 0 31 0 Active 1 1000 MHz B3 0 31 0 Sched Deconf Shell> cpuconfig 1 on CPU will be configured on next boot. Shell> cpuconfig PROCESSOR INFORMATION Proc Arch Processor CPU Speed Rev Model Family Rev State --- ---------- ---- ----- ------ ---- ------------- 0 1000 MHz B3 0 31 0 Active 1 1000 MHz B3 0 31 0 Active Shell> You used cpuconfig to view the current CPU configuration showing that both processors are Active. Then you turned off processor 1 (cpuconfig 1 off). You then viewed the CPU configuration again to confirm that processor 1 had been turned off as indicated by the Sched Deconf (cpuconfig). After that, we turned processor 1 on again (cpuconfig 1 on). Finally, we confirmed that both processors are again Active (cpuconfig). As you can see, a lot of useful configuration information about your system is available using EFI. In addition to cpuconfig, you can also use info to get important system information. The following listing first shows the results of the info command. info, with no argument, lists all the differing information options available (such as all, boot, cache, and so on). After you see all the info options, you use info all to get a complete rundown on your system: Shell> info Usage: INFO [-b] [target] target : all, boot, cache, chiprev, cpu, fw, io, mem, sys, warning Shell> info all SYSTEM INFORMATION Product Name: server rx2600 Serial Number: US24758356 UUID: B831CE57-19C2-11D7-A034-3483D23C4340 PROCESSOR INFORMATION Proc Arch Processor CPU Speed Rev Model Family Rev State --- ---------- ---- ----- ------ ---- ------------- 0 1000 MHz B3 0 31 0 Active 1 1000 MHz B3 0 31 0 Active CACHE INFORMATON Instruction Data Unified CPU L1 L1 L2 L3 --- -------- -------- -------- -------- 0 16 KB 16 KB 256 KB 3072 KB 1 16 KB 16 KB 256 KB 3072 KB MEMORY INFORMATION ---- DIMM A ----- ---- DIMM B ----- DIMM Current DIMM Current --- ------ ---------- ------ ---------- 0 256MB Active 256MB Active 1 256MB Active 256MB Active 2 256MB Active 256MB Active 3 256MB Active 256MB Active 4 ---- ---- 5 ---- ---- Active Memory : 2048 MB Installed Memory : 2048 MB I/O INFORMATION BOOTABLE DEVICES Order Media Type Path ----- ---------- --------------------------------------- 1 HARDDRIVE Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun0,Lun0)/ HD(Part1,Sig8E89981A-0B97-11D7-9C4C-AF87605217DA) 2 HARDDRIVE Acpi(HWP0002,100)/Pci(1|0)/Scsi(Pun1,Lun0)/HD(Part1,Sig7C0F0000) Seg Bus Dev Fnc Vendor Device Slot # # # # ID ID # Path --- --- --- --- ------ ------ --- ----------- 00 00 01 00 0x1033 0x0035 XX Acpi(HWP0002,0)/Pci(1|0) 00 00 01 01 0x1033 0x0035 XX Acpi(HWP0002,0)/Pci(1|1) 00 00 01 02 0x1033 0x00E0 XX Acpi(HWP0002,0)/Pci(1|2) 00 00 02 00 0x1095 0x0649 XX Acpi(HWP0002,0)/Pci(2|0) 00 00 03 00 0x8086 0x1229 XX Acpi(HWP0002,0)/Pci(3|0) 00 20 01 00 0x1000 0x0030 XX Acpi(HWP0002,100)/Pci(1|0) 00 20 01 01 0x1000 0x0030 XX Acpi(HWP0002,100)/Pci(1|1) 00 20 02 00 0x14E4 0x1645 XX Acpi(HWP0002,100)/Pci(2|0) 00 40 01 00 0x1011 0x0019 03 Acpi(HWP0002,200)/Pci(1|0) 00 80 01 00 0x1011 0x0019 01 Acpi(HWP0002,400)/Pci(1|0) 00 E0 01 00 0x103C 0x1290 XX Acpi(HWP0002,700)/Pci(1|0) 00 E0 01 01 0x103C 0x1048 XX Acpi(HWP0002,700)/Pci(1|1) 00 E0 02 00 0x1002 0x5159 XX Acpi(HWP0002,700)/Pci(2|0) BOOT INFORMATION Monarch CPU: Current Preferred Monarch Monarch Possible Warnings ------- --------- ----------------- 0 0 AutoBoot: ON - Timeout is : 10 sec Boottest: LAN Address Information: LAN Address Path ----------------- ---------------------------------------- Mac(00306E39B724) Acpi(HWP0002,0)/Pci(3|0)/Mac(00306E39B724)) *Mac(00306E3927B0) Acpi(HWP0002,100)/Pci(2|0)/Mac(00306E3927B0)) FIRMWARE INFORMATION Firmware Revision: 1.61 [4241] PAL A Revision: 7.31 PAL B Revision: 7.36 SAL Spec Revision: 0.20 SAL A Revision: 2.00 SAL B Revision: 1.60 EFI Spec Revision: 1.10 EFI Intel Drop Revision: 14.60 EFI Build Revision: 1.22 POSSE Revision: 0.10 ACPI Revision: 7.00 BMC Revision 1.30 IPMI Revision: 1.00 SMBIOS Revision: 2.3.2a Management Processor Revision: E.02.07 WARNING AND STOP BOOT INFORMATION CHIP REVISION INFORMATION Chip Logical Device Chip Type ID ID Revision ------------------- ------- ------ -------- Memory Controller 0 122b 0022 Root Bridge 0 1229 0022 Host Bridge 0000 122e 0032 Host Bridge 0001 122e 0032 Host Bridge 0002 122e 0032 Host Bridge 0003 122e 0032 Host Bridge 0004 122e 0032 Host Bridge 0006 122e 0032 Host Bridge 0007 122e 0032 Other Bridge 0 0 0002 Other Bridge 0 0 0007 Baseboard MC 0 0 0130 Shell> As you can see, info all produces a great overview of the system configuration. Note that two bootable devices are listed in the order in which they appear in the main EFI screen (see the "EFI Boot Administration Main Screen" on page 5). In addition to selecting the EFI Shell, which we have been doing in our examples to this point, we also have other options. Selecting Boot option maintenance menu produces the selections shown here: EFI Boot Maintenance Manager ver 1.10 [14.60] Manage BootNext setting. Select an Operation Red Hat Linux Advanced Server HP-UX Primary Boot: 0/1/1/0.1.0 EFI Shell [Built-in] Reset BootNext Setting Save Settings to NVRAM Help Exit You have some of the same selections that you had at the main menu level, including the two installed operating systems and the EFI shell, but you also have some new selections. If you were to select Reset BootNext Setting, the following selections would be produced: EFI Boot Maintenance Manager ver 1.10 [14.60] Main Menu. Select an Operation Boot from a File Add a Boot Option Delete Boot Option(s) Change Boot Order Manage BootNext setting Set Auto Boot TimeOut Select Active Console Output Devices Select Active Console Input Devices Select Active Standard Error Devices Cold Reset Exit At this point, you could perform a variety of functions. On your system, for instance, we could use Change Boot Order to make the HP-UX partition the default boot selection instead of the Linux Advanced Server. Although you are going to perform a console-only installation of Red Hat Advanced Server in Chapter 2, the rx2600 we're working on does indeed have a built-in VGA port and graphics display attached. If you wanted to enable the graphics display, we would select Select Active Console Output Devices from the menu above. The Select the Console Output Device(s) menu appears listing all possible console devices. The first device with an * is the serial port that was selected by default. To enable the graphics as well, you must select the last console device. You know that this is the graphics device port because it does not contain Uart as part of the selection. Note that Uart devices are always serial devices. Also note that in the following example, the graphical device port is already selected (indicated by an * in front of it). We then select Save Settings to NVRAM, which saves the console device settings, and then exit:) Save Settings to NVRAM Exit This setting enables both the serial and graphics consoles. The early boot messages will go to the serial console. After the graphics server is started, the Advanced Server-related boot messages will display graphically. After the installation is complete, this would be true during the load of Advanced Server as well. The early selections would take place on the console and then the majority of the load selections would display graphically. The first four entries with PNP0501 in them are on the nine pin serial port. The next four entries with HWP0002 in them are on the three cable device that fits into the 25 pin connector. Be sure to enable a serial console on only one of the two devices since the Linux kernel expects only one serial console to be enabled. As you have seen, EFI is a useful and relatively easy to use tool. Of course, no one expects you to remember all you have seen here. If you need help, refer to "Commonly Used EFI Commands" on page 9 in Table 1-2. You can also type help at the Shell> prompt, or take a look at the tables summarizing EFI at the end of this chapter. Between them all, you'll be able to perform many useful functions using the EFI interface.
http://www.informit.com/articles/article.aspx?p=359419
CC-MAIN-2017-34
refinedweb
3,790
59.23
Dash Google Auth Project description Dash Google Auth Dash Google Auth is a simple library using Google OAuth to authenticate and view a Dash app. This Library uses Flask Dance and a modified version of Plotly's own dash auth for authentication. Basic Use Authentication can be added to your Dash application using the GoogleOAuth class, i.e. from dash import Dash from flask import Flask from dash_google_auth import GoogleOAuth server = Flask(__name__) server.config.update({ 'GOOGLE_OAUTH_CLIENT_ID': ..., 'GOOGLE_OAUTH_CLIENT_SECRET': ..., }) app = Dash(__name__, server=server, url_base_pathname='/', auth='auth') authorized_emails = [...] additional_scopes = [...] auth = GoogleOAuth(app, authorized_emails, additional_scopes) # your Dash app here :) ... Example Steps to try this out yourself: Install the dash-google-authlibrary using pip: $ pip install dash-google-auth Follow the Flask Dance Guide to create an app on the google admin console Make a copy of app.py and set the variables (or set the corresponding environment variables): server.config["GOOGLE_OAUTH_CLIENT_ID"] = ... server.config["GOOGLE_OAUTH_CLIENT_SECRET"] = ... with values from the Google OAuth 2 client you should have set up in step 1. If you've set these up properly, you can find them at APIs & Services > Credentials under the section OAuth 2.0 client IDs. Replace authorized_emailsin app.pywith whatever Google emails you want to grant access to your app. In production, I'd recommend getting these from a database instead. Run python app.pyand open localhost in a browser window to try it out! If the app loads automatically without prompting a Google login, that means you're already authenticated -- try using an incognito window in this case if you want to see the login experience for a new user. Project details Release history Release notifications | RSS feed Download files Download the file for your platform. If you're not sure which to choose, learn more about installing packages.
https://pypi.org/project/dash-google-auth/
CC-MAIN-2021-10
refinedweb
296
56.96
Search: Search took 0.01 seconds. - 22 Jul 2011 10:27 AM - Replies - 19 - Views - 16,397 I figured out the solution to my problem. The getter for the store in the workshop code is generated, but since my store is in a namespace I couldn't figure out what the generated getter would be. ... - 21 Jul 2011 3:46 PM - Replies - 19 - Views - 16,397 I'm having this same problem, and trying to follow the example in the video. The code you show above for the controller is from the workshop code, and I can't see where the function getUserStore()... Results 1 to 2 of 2
https://www.sencha.com/forum/search.php?s=77bd80eae4dc46a4eb8d8389a480c5a5&searchid=11961082
CC-MAIN-2015-27
refinedweb
109
79.8
Kenny Kerr Software Consultant July 2004 Applies to: Microsoft Visual C++ 2005 Microsoft Visual C++ .NET Common Language Runtime (CLR) Microsoft Visual Studio 2005 Summary: Explore the design and rationale for the new C++/CLI language introduced with Visual C++ 2005. Use this knowledge to write powerful .NET applications with the most powerful programming language for .NET programming. (15 printed pages) Introduction Object Construction Memory Management vs. Resource Management Memory Management Resource Management Types Revisited Boxing Authoring Reference and Value Types Accessibility Properties Delegates Conclusion The Visual C++ team spent a lot of time listening to users and working with .NET and C++, and decided to redesign the support for the Common Language Runtime (CLR) in Visual C++ 2005. This redesign is called C++/CLI, and is intended to provide a more natural syntax for consuming and authoring CLR types. In this article I explore the new syntax, comparing it to current C# and Managed C++, the two most closely-related languages that target the CLR. Where appropriate I also illustrate analogous concepts in native C++. The Common Language Infrastructure (CLI) is a group of specifications on which the Microsoft .NET initiative is based. The CLR is the Microsoft implementation of the CLI. The C++/CLI language design is aimed at providing natural C++ support for the CLI, while the Visual C++ 2005 compiler implements C++/CLI for the CLR. There are two big messages that come through when you examine the upcoming Visual C++ 2005 compiler and the C++/CLI language design. Firstly, Visual C++ is positioning itself as the lowest level programming language for targeting the CLR. There should be no cause to use any other language, not even Microsoft intermediate language (MSIL). Secondly, .NET programming should be as natural as native C++ programming. As you read this article these two messages should become clear. This article is for C++ programmers. I am not going to try to convince you to switch from C# or Visual Basic .NET. If you love C++ and want to use all the power that C++ has traditionally offered, but also want the productivity of C#, then this article is for you. In addition, this article does not provide an introduction to the CLR or the .NET Framework. Rather, the focus is on highlighting how Visual C++ 2005 allows you to write more elegant and efficient code targeting the .NET Framework. The CLR defines two types, a value type and a reference type. Value types are designed to be efficiently allocated and accessed. They behave much like the built-in types in C++, and you can also create your own. This is what Bjarne Stroustrup calls concrete types. Reference types, on the other hand, are designed to provide all the features you would expect from object-oriented programming, such as the ability to create class hierarchies and all that goes along with that: derived classes and virtual functions, for example. Reference types, through the CLR, also provide additional runtime features such as automatic memory management, known as garbage collection. The CLR also provides sophisticated runtime type information for both reference and value types. This capability is referred to as reflection. Value types are allocated on the stack. Reference types are allocated on the managed heap. This is the heap that is managed by the CLR's garbage collector (GC). If you are developing your assembly in C++, you can also allocate native C++ types on the CRT heap as you have always done. In the future, the Visual C++ team would like to allow you to even allocate native C++ types on the managed heap. After all, garbage collection is an equally attractive proposition for native types. Native C++ lets you choose where to create a given object. Any type can be allocated on the stack or the CRT heap. // allocated on the stack std::wstring stackObject; // allocated on the CRT heap std::wstring* heapObject = new std::wstring; As you can see, the choice of where to allocate the object is independent of the type, and is totally in the hands of the programmer. In addition, the syntax for stack versus heap allocation is distinctive. C#, on the other hand, lets you create value types on the stack and reference types on the heap. The System.DateTime type, used in the next few examples, is declared a value type by its author. // allocated on the stack System.DateTime stackObject = new System.DateTime(2003, 1, 18); // allocated on the managed heap System.IO.MemoryStream heapObject = new System.IO.MemoryStream(); As you can see, nothing about the way you declare the object gives any hint at whether the object is on the stack or the heap. That choice is left completely up to the type's author and the runtime. Managed Extensions for C++, referred to as Managed C++ for short, introduced the ability to mix managed code with native C++ code. Following the rules in the C++ standard, extensions were added to C++ to support a whole range of CLR constructs. Unfortunately, there were just too many extensions, and writing a lot of managed code in C++ became a real pain. // allocated on the stack DateTime stackObject(2003, 1, 18); // allocated on the managed heap IO::MemoryStream __gc* heapObject = __gc new IO::MemoryStream; Allocating a value type on the stack looks quite normal to a C++ programmer. The managed heap example, however, looks a bit strange. __gc is one of the keywords in the Managed C++ extensions. Arguably, Managed C++ can infer what you mean in some cases, so this example could be rewritten without the __gc keywords. This is known as the defaulting rules. // allocated on the managed heap IO::MemoryStream* heapObject = new IO::MemoryStream; This looks a lot more like native C++. The problem is that heapObject is not a real C++ pointer. C++ programmers have come to rely on a pointer having a stable value, but the garbage collector can move objects around in memory at any time. The other drawback is that there is no way to tell just by looking at the code whether the object will be allocated on the native or managed heap. You would need to know how the type was defined by its author. There are a lot of other convincing reasons why overloading the meaning of the C++ pointer is a bad idea. C++/CLI introduces the concept of a handle to distinguish a CLR object reference from a C++ pointer. By not overloading the C++ pointer, a lot of ambiguity is removed from the language. In addition, much more natural support for the CLR can be provided through handles. For example, you can make use of operator overloads on reference types directly in C++, because operator overloading is supported on handles. This could not have been possible with "managed" pointers, since C++ forbids operators to be overloaded on pointers. // allocated on the stack DateTime stackObject(2003, 1, 18); // allocated on the managed heap IO::MemoryStream^ heapObject = gcnew IO::MemoryStream; Again, there is nothing surprising about the declaration of the value type. The reference type, however, is distinctive. The ^ operator declares the variable as a handle to a CLR reference type. Handles track, meaning the handle's value is automatically updated by the garbage collector as the object to which it refers, is moved in memory. In addition, they are rebindable, which allows them to point to a different object, just like a C++ pointer. The other thing you should notice is the gcnew operator that is used in place of the new operator. This clearly indicates that the object is being allocated on the managed heap. The new operator is no longer overloaded (no pun intended) for managed types, and will only allocate objects on the CRT heap, unless of course you provide your own operator new. Don't you just love C++! That is object construction in a nutshell: Native C++ pointers are clearly distinguished from CLR object references. It is useful to distinguish memory management from resource management when you are dealing with an environment that includes a garbage collector. Typically, the garbage collector is interested in allocating and freeing the memory that will contain your objects. It does not care about other resources that your objects may own, such as database connections or handles to kernel objects. In the two sections that follow. I will be talking about memory management and resource management individually, as they are each vitally important topics to understand well. Native C++ provides the programmer direct control over memory management. Allocating an object on the stack means that the memory for the object will be allocated when the particular function call is entered, and the memory will be released when the function returns and the stack unwinds. Dynamically allocating an object is accomplished using the new operator. This memory is allocated from the CRT heap and it is freed explicitly when the programmer uses the delete operator on the pointer to the object. This precise control over memory is one of the reasons that C++ can be used to write extremely efficient code, but is also the cause of memory leaks when the programmer is not careful. Arguably, you do not have to resort to a garbage collector to avoid memory leaks, but that is the approach taken by the CLR and is a very effective approach, indeed. Of course there are other benefits to a garbage collected heap, such as improved allocation performance and advantages related to locality of reference. All of these things could be achieved in C++ through library support, but the thing that stands out about the CLR is that it provides a single memory management programming model that is common to all programming languages. Think of all the work needed to interoperate and marshal data types from COM automation object models from C++, and you should be able to realize the significance of this. Having a common garbage collector that spans programming languages is huge. The CLR retains the concept of a stack as a place where value types can be allocated for obvious reasons of efficiency. The CLR, however, provides a newobj intermediate language (IL) instruction to allocate an object on the managed heap. This instruction is provided for you when you use the new operator in C# on a reference type. There is no equivalent function to the C++ delete operator for the CLR. The memory that was previously allocated will eventually get reclaimed, when the application no longer refers to it and the garbage collector decides to do a collection. Managed C++ also generated the newobj instruction when the new operator was applied to reference types. It is, however, illegal to use the delete operator with such a managed, or garbage collected, pointer. This is certainly a nasty inconsistency, and yet another reason why representing reference types with the C++ pointer concept is a bad idea. C++/CLI does not provide anything else new in the area of memory management, other than what we have already covered in the section about object construction. Resource management, however, is where C++/CLI really excels. As far as resource management goes, nothing beats native C++. Bjarne Stroustrup's "resource acquisition is initialization" technique basically defines that each resource type should be modeled as a class with constructors and a destructor to release the resource. These types are then used as local objects on the stack, or as members of more complex types. Their destructors then take care of automatically releasing the resources being held. As Stroustrup puts it, "C++ is the best language for garbage collection principally because it creates less garbage." Perhaps somewhat surprisingly, the CLR does not provide any explicit runtime support for resource management. The CLR does not support the C++ concept of a destructor. Rather, the .NET Framework has promoted a pattern for resource management centered on a core interface type called IDisposable. The idea is that types that encapsulate resources should implement this interface's single Dispose method, and then callers should call the Dispose method when they no longer need the resource. Needless to say, C++ programmers tend to think of this as a step backwards, because they are used to writing code whose cleanup is correct by default. The trouble with having to call a method to free any resources is that it makes it harder to write exception safe code. You cannot simply place a call to the object's Dispose method at the end of a block of code, as an exception may be thrown at any time and then you would have leaked the resources owned by the object. C# gets around this by providing try-finally blocks and the using statement, to provide a reliable way of calling the Dispose method in the face of exceptions. These constructs do tend to get in the way at times, however; worse, you have to remember to write them, and if you forget then your code still compiles but has a silent error by default. The need for try-finally blocks and the using statement is arguably an unfortunate necessity in a language that lacks a real destructor. using (SqlConnection connection = new SqlConnection("Database=master; Integrated Security=sspi")) { SqlCommand command = connection.CreateCommand(); command.CommandText = "sp_databases"; command.CommandType = CommandType.StoredProcedure; connection.Open(); using (SqlDataReader reader = command.ExecuteReader()) { while (reader.Read()) { Console.WriteLine(reader.GetString(0)); } } } The story is much the same for Managed C++. You need to use a try-finally statement, which is a Microsoft extension to C++. Managed C++ did not introduce an equivalent of the C# using statement, though it is easy enough to write a simple Using template class that wraps a GCHandle and calls the managed object's Dispose method in the template class's destructor. Using<SqlConnection> connection(new SqlConnection (S"Database=master; Integrated Security=sspi")); SqlCommand* command = connection->CreateCommand(); command->set_CommandText(S"sp_databases"); command->set_CommandType(CommandType::StoredProcedure); connection->Open(); Using<SqlDataReader> reader(command->ExecuteReader()); while (reader->Read()) { Console::WriteLine(reader->GetString(0)); } Considering C++'s traditionally strong support for resource management, it is fitting that the C++/CLI language design has gone to great lengths to make resource management a breeze in C++. First, let us look at authoring a class that manages a resource. One of the burdens shared by most, if not all, languages targeting the CLR is implementing the Dispose pattern correctly. It is just not as easy as implementing a classic destructor in native C++. When writing your Dispose method, you need to make sure you call the base class Dispose method, if any. In addition, if you choose to implement the class's Finalize method by calling the Dispose method, you need to worry about concurrent access, since the Finalize method is called on a separate thread. Additionally, you need to be careful about freeing managed resources if the Dispose method is actually being called from the Finalize method, as apposed to normal application code. C++/CLI does not make all of these issues go away, but it does provide a good deal of help. Before we look at what it offers, let us quickly review what the approach for C# and Managed C++ is today. This example assumes that Base derives from IDisposable. If it did not, the Derived class would need to. class Derived : Base { public override void Dispose() { try { // free managed and unmanaged resources } finally { base.Dispose(); } } ~Derived() // implements/overrides the Object.Finalize method { // free unmanaged resources only } } Managed C++ is much the same. What looks like a destructor is actually a Finalize method. The compiler takes care to effectively insert a try-finally block and call the base class's Finalize method, so C# and Managed C++ make it relatively easy to write a Finalize method but do not provide any help in writing a Dispose method, which is arguably much more important. Programmers often use the Dispose method as a pseudo-destructor just to be able to have some code execute at the end of some scope, not necessarily to free any resource. C++/CLI acknowledges the importance of the Dispose method by making it the logical "destructor" for a reference type. ref class Derived : Base { ~Derived() // implements/overrides the IDisposable::Dispose method { // free managed and unmanaged resources } !Derived() // implements/overrides the Object::Finalize method { // free unmanaged resources only } }; This feels a lot more natural to a C++ programmer. I can free my resources in my destructor like I've always done. The compiler will emit the necessary IL to implement the IDisposable::Dispose method correctly, including suppressing the garbage collector's call to any Finalize method on the object. In fact, it is not legal in C++/CLI to explicitly implement the Dispose method. Inheriting from IDisposable will result in a compiler error. Of course, once the type is compiled, all CLI languages that consume it will see the Dispose pattern implemented in whatever way is most natural for each language. In C# you can call the Dispose method directly, or use a using statement just as if the type were defined in C#; but what about C++? How do you normally call the destructor of a heap based object? By using the delete operator, of course! Applying the delete operator to a handle will call the object's Dispose method. Recall that the object's memory is managed by the garbage collector. We are not concerned about freeing that memory, but only about freeing the resources the object contains. Derived^ d = gcnew Derived(); d->SomeMethod() delete d; So if the expression passed to the delete operator is a handle, the object's Dispose method is called. If there are no more roots connected to the reference type, the garbage collector is free to collect the object's memory at some point. If the expression is a native C++ object, the object's destructor is called before the memory is returned to the heap. Certainly we're getting closer to the natural C++ syntax for object lifetime management, but it is still error-prone to have to remember to call the delete operator. C++/CLI allows you to employ stack semantics with reference types. What this means is that you can introduce a reference type using the syntax reserved for allocating objects on the stack. The compiler will take care of providing you the semantics that you would expect from C++, and under the covers meet the requirements of the CLR by actually allocating the object on the managed heap. Derived d; d.SomeMethod(); When d goes out of scope, its Dispose method will be called to allow its resources to be released. Again, since the object is actually allocated from the managed heap, the garbage collector will take care of freeing it in its own time. Going back to our ADO.NET example, it would be written like this in C++/CLI. SqlConnection connection("Database=master; Integrated Security=sspi"); SqlCommand^ command = connection.CreateCommand(); command->CommandText = "sp_databases"; command->CommandType = CommandType::StoredProcedure; connection.Open(); SqlDataReader reader(command->ExecuteReader()); while (reader.Read()) { Console::WriteLine(reader.GetString(0)); } Before we talk about boxing, it is useful to refresh our memory on why there is a distinction between value types and reference types. You can think of instances of value types as simple values, and instances of reference types as objects. Besides the memory required to store the fields of an object, every object has an object header that allows it to provide the basic services of object-oriented programming, such as class hierarchies with virtual methods, as well as metadata that can be tapped into for all kinds of uses. The memory overhead of the object header, however, combined with the indirection of virtual methods and interfaces, is often too costly when all you want is a simple value with a static type and some compiler-enforced operations on that value. Arguably, compilers can optimize away this object overhead in some cases, but not all. Clearly there is benefit in having values and value types if you are at all concerned about performance in managed code. There just isn't such a big split in the type system of native C++. Of course, C++ does not impose any programming paradigm, so it is possible to build such distinct type systems through the creation of libraries on top of C++. So what is boxing? Boxing is a mechanism to bridge the gap between values and objects. Although the CLR requires every type to derive, directly or indirectly, from Object, values really do not. A simple value like an integer on the stack is just a block of memory that the compiler allows certain operations on. If you really want to treat a value as an object, it must really be an object. You should be able to call methods inherited from Object on your value. To make this possible, the CLR provides the notion of boxing. It is useful to know a little bit about how boxing actually works. First, a value is pushed onto the stack using the ldloc IL instruction. Next the box IL instruction is used, which does the heavy lifting. The compiler provides the static type of the value, for example Int32, and the CLR goes ahead and pops the value off of the stack and allocates enough memory to store the value and the object header. A reference to the newly created object is pushed onto the stack. All this was done as a result of the box instruction. Finally, to get the object reference, the stloc IL instruction is used to pop the reference off the stack and store it in some local variable. Now, the question is whether boxing a value should be represented as an implicit or explicit operation by a programming language. In other words, should an explicit cast, or some other construct, be used? The C# language designers decided to make it an implicit conversion. After all, an integer is an Int32 type which derives indirectly from Object. int i = 123; object o = i; The problem, as we've learnt, is that boxing is not a simple upcast. Rather, it is a conversion from a value to an object, a potentially expensive operation. For this reason, Managed C++ makes boxing explicit with the use of the __box keyword. int i = 123; Object* o = __box(i); Of course, in Managed C++, you do not have to lose static type information when you box a value. This is something that C# does not provide. int i = 123; int __gc* o = __box(i); A strongly-typed boxed value has the advantage of allowing conversion back to a value type, otherwise known as unboxing, without using a dynamic_cast, simply by dereferencing the object. int c = *o; Of course the syntactic overhead of the explicit boxing in Managed C++ proved to be too much in most cases. For this reason, the course of the C++/CLI language design changes, and comes in line with C# by making boxing implicit. At the same time, it retains the type-safety of being able to directly express strongly typed boxed values that other .NET languages cannot express. int i = 123; int^ hi = i; int c = *hi; hi = nullptr; Of course, this implies that a handle that is not pointing to an object cannot be initialized with zero, as pointers are, since this would simply box the value zero. This is the purpose of the nullptr constant. It can be assigned to any handle. This is equivalent to the C# null keyword. Although nullptr is a new reserved word in the C++/CLI language design, it is proposed as an addition to Standard C++ for use with pointers by Herb Sutter and Bjarne Stroustrup. In the next few sections we are going to cover some details of authoring CLR types. C# uses the class keyword to declare reference types and the struct keyword to declare value types. class ReferenceType {} struct ValueType {} C++ already has well-defined meanings for both class and struct, so this wouldn't work for C++. In the original language design, the __gc keyword was placed before the class to indicate a reference type and the __value keyword was used for value types. __gc class ReferenceType {}; __value class ValueType {}; C++/CLI introduces spaced keywords in places where this will not conflict with user identifiers. For declaring reference types, you add ref before a class or struct. Similarly, you use value for declaring value types. ref class ReferenceType {}; ref struct ReferenceType {}; value class ValueType {}; value struct ValueType {}; The choice of using class versus struct is the same as it has always been in terms of the default visibility of members. The main difference is that CLR types only support public inheritance. Using private or protected inheritance will result in a compiler error, so explicitly declaring public inheritance is legal but redundant. The CLR defines a number of accessibility modifiers that go beyond that which native C++ provides for class member functions and variables. Not only that, you can define the accessibility of namespace types, not just nested types. In keeping with the C++/CLI goal of being the lowest level language, it provides more control over accessibility than any other high-level language targeting the CLR. The main difference between native C++ accessibility and accessibility as defined by the CLR is that, whereas native C++ access specifiers are used to restrict access to members from other code in the same program, the CLR needs to define the accessibility of types and their members not only to other code in the same assembly, but also to other assemblies that may reference it. A namespace, or non-nested, type, such as a class or delegate type, can specify its visibility outside the assembly by adding public or private before the type definition. public ref class ReferenceType {}; If you do not specify the visibility explicitly, the type is assumed to be private to the assembly. Access specifiers for members have been extended to allow you to use two keywords together to specify the internal and external access to the names that follow it. The more restrictive of the two defines the access outside the assembly, whereas the other defines the access inside the assembly. If only a single keyword is used, it applies to both internal and external access. This design provides a great deal of flexibility for defining the accessibility of types and members that you define. Here is an example. public ref class ReferenceType { public: // visible inside and outside assembly private public: // visible inside assembly protected public: // visible to derived types outside and all code inside assembly }; Apart from nested types, CLR types can only contain methods and fields. To allow the programmer to convey intensions more clearly, metadata can be used to indicate that certain methods should be treated as properties by programming languages. Strictly speaking, a CLR property is a member of its containing type; however, the property has no allocated storage, and is simply a named reference to the respective methods implementing the property. Different compilers need to generate the required metadata when it encounters the appropriate syntax for properties in the source code. That way, consumers of the type can use the property syntax of their language to access the get and set methods that implement the property. Unlike native C++, C# has first-class support for properties. public string Name { get { return m_name; } set { m_name = value; } } The C# compiler will generate the corresponding get_Name and set_Name methods, as well as include the necessary metadata to indicate the association. Managed C++ introduced the __property keyword to indicate that a method plays a part in implementing property semantics. __property String* get_Name() { return m_value; } __property String* set_Name(String* value) { m_value = value; } Clearly this is not ideal. Not only do we need to use the ugly __property keyword, but there is nothing that clearly indicates that the two member functions actually belong together. This can lead to subtle bugs during maintenance. The C++/CLI design for properties is much more concise, and resembles the C# design much more closely. As you will see, however, it is even more powerful. property String^ Name { String^ get() { return m_value; } void set(String^ value) { m_value = value; } } That's a great improvement. The compiler will take care of generating the get_Name and set_Name methods, as well as the necessary metadata that declares this a property. What would also be nice is if you could allow code outside of your assembly to read the property value, but only allow code inside of your assembly to write it. You can use an access specifier inside the curly braces following the property name to achieve this. property String^ Name { public: String^ get(); private public: void set(String^); } One last thing worth noting about the property support is that it supports a shorthand syntax for those cases where you do not need any special processing for getting and setting a property. property String^ Name; Again, the compiler will generate the get_Name and set_Name methods, but this time will also provide a default implementation backed by a private String^ member variable. The advantage of this, of course, is that in the future you can replace the simple property with a more interesting property implementation and it will not break the interface contract of the class. You get the simplicity of a field with the flexibility of a property. Function pointers in native C++ provide a mechanism to execute code asynchronously. You can store a pointer to a function, or more generally a functor, and invoke it at some later point in time. This may be used simply as a way to decouple an algorithm from some part of its implementation, such as comparing objects in a search. Alternatively, it could be used for truly asynchronous programming by invoking the functor on a different thread. Here is a simple example of a ThreadPool class that lets you queue a pointer to a function for execution on a worker thread. class ThreadPool { public: template <typename T> static void QueueUserWorkItem(void (T::*function)(), T* object) { typedef std::pair<void (T::*)(), T*> CallbackType; std::auto_ptr<CallbackType> p(new CallbackType(function, object)); if (::QueueUserWorkItem(ThreadProc<T>, p.get(), WT_EXECUTEDEFAULT)) { // The ThreadProc now has the responsibility of deleting the pair. p.release(); } else { AtlThrowLastWin32(); } } private: template <typename T> static DWORD WINAPI ThreadProc(PVOID context) { typedef std::pair<void (T::*)(), T*> CallbackType; std::auto_ptr<CallbackType> p(static_cast<CallbackType*>(context)); (p->second->*p->first)(); return 0; } ThreadPool(); }; Using the thread pool is simple and feels natural in C++. class Service { public: void AsyncRun() { ThreadPool::QueueUserWorkItem(Run, this); } void Run() { // some lengthy operation } } Obviously, my ThreadPool class is very limited in that it only works with function pointers with a specific signature. This is only a limitation of this example, and not of C++ itself. For a great discussion of generalized functors, pick up a copy of Andrei Alexandrescu's excellent book Modern C++ Design. Where C++ programmers need to implement or obtain rich libraries for asynchronous programming, the CLR comes with built-in support. Delegates are similar to function pointers, except that the target object, or the type to which the method belongs, does not play a role in determining whether a delegate can be bound to a given method. As long as the signature matches, the method can be added to the delegate for later invocation. This is similar, at least in spirit, to my example above where I used C++ templates to allow any class's member function to be used. Of course, delegates provide far more than that and are an extremely useful mechanism for indirect method invocation. The following is an example of defining a delegate type using C++/CLI. delegate void Function(); Using a delegate is straightforward. ref struct ReferenceType { void InstanceMethod() {} static void StaticMethod() {} }; // create delegate and bind to instance member function Function^ f = gcnew Function(gcnew ReferenceType, ReferenceType::InstanceMethod); // also bind to static member function by combining delegates // to form delegate chain f += gcnew Function(ReferenceType::StaticMethod); // invoke both functions f(); There is certainly a lot more to be said about C++/CLI, never mind the Visual C++ 2005 compiler, but I hope this article has provided you with a good introduction to what it has to offer for programmers targeting the CLR. The new language design provides unprecedented power and elegance to write rich .NET applications completely in C++ without sacrificing productivity, conciseness, or performance. The following table provides a summary of the most common constructs for quick reference. delete h; ((IDisposable)h).Dispose(); int c = *hi; int i = (int) h; ref struct ReferenceType {}; value struct ValueType {}; int v = h.Prop; Kenny Kerr spends most of his time designing and building distributed applications for the Microsoft Windows platform. He also has a particular passion for C++ and security programming. Reach Kenny at or visit his Web site:.
http://msdn.microsoft.com/en-us/library/ms379617%28VS.80%29.aspx
crawl-002
refinedweb
5,480
52.39
I made this happy little arcpy script to fix some data source problems: print "Hi, I will fix find and replace file path sections on your behalf. \nGive me a moment to just count the number of MXDs I'll be looking at for you today..." import os import arcpy mxdfiles = [os.path.join(d, x) for d, dirs, files in os.walk(r"PATH") for x in files if x.endswith(".mxd")] print "\nOk, I'll be working through "+str(len(mxdfiles))+" MXDs. \nStarting this process now..." for item in mxdfiles: print "\nWorking on: "+item mxd = arcpy.mapping.MapDocument(item) mxd.findAndReplaceWorkspacePaths(r"PATH OLD1", r"PATH NEW") mxd.findAndReplaceWorkspacePaths(r"PATH OLD2", r"PATH NEW") mxd.findAndReplaceWorkspacePaths(r"PATH OLD3", r"PATH NEW") mxd.findAndReplaceWorkspacePaths(r"PATH OLD4", r"PATH NEW") mxd.findAndReplaceWorkspacePaths(r"PATH OLD5", r"PATH NEW2") mxd.save() del mxd print "Completed "+str(mxdfiles.index(item)+1)+" maps so far." print "\nProcess complete!" Unfortunately, though, when it comes across a MXD with a Bing imagery layer, up pops a Bing Authorization box which you have to click 'OK' on (hitting Enter works, too). This is because my company no longer has a license to use Bing/Microsoft Virtual Earth, so this little box comes up every time a MXD is opened manually, or, it seems, when one is invoked by my script. This means I have to either: 1. Find a way to programmatically click that button or ignore it. 2. Leave a coffee mug on my Enter key overnight. 3. Remove the Bing (or Microsoft Virtual Earth*) layers programmatically. I Googled to no avail regarding option 1. Before going for option 2, I tried option 3. As a test, I used the following script to try removing Microsoft Virtual Earth* layers (their group is Microsoft Virtual Earth, inside that there are three layers with the same name plus Hybrid, Aerial or Roads suffixed): import arcpy mxd = arcpy.mapping.MapDocument(r"PATH.mxd") for df in arcpy.mapping.ListDataFrames(mxd): for lyr in arcpy.mapping.ListLayers(mxd, "Microsoft Virtual Earth", df): arcpy.mapping.RemoveLayer(df, lyr) mxd.saveACopy(r"PATH2.mxd") del mxd It ran without errors, including without the Bing Authorization dialog box popping up. The resulting MXD, however, would not open without crashing. I therefore used this script to retrieve its list of layers: import arcpy mxd = arcpy.mapping.MapDocument(r"PATH2.mxd") df = arcpy.mapping.ListDataFrames(mxd,"Layers")[0] print arcpy.mapping.ListLayers(mxd, "", df) del mxd ...and found that the Microsoft Virtual Earth* layers had in fact been removed. Btw, the list layers script also did not cause the Bing Authorization box to pop up. Before I try to incorporate my script to remove these layers into the one I'm working on to walk through all MXDs and fix their paths, I need to know: 1. What is causing the Bing Authorisation dialog box to pop up with my initial script, but not the layer deletion nor listing ones? 2. Why after running the Bing/Microsoft Virtual Earth layer deletion script the MXD is now corrupted and causes ArcMap to crash (crash report box comes up)?
https://community.esri.com/thread/163685-bing-authorization-interrupts-arcpy-script
CC-MAIN-2019-13
refinedweb
526
60.01
This page provides a general overview of how Ingress for HTTP(S) Load Balancing works. Google Kubernetes Engine (GKE) provides a built-in and managed Ingress controller called GKE Ingress. This controller implements Ingress resources as Google Cloud load balancers for HTTP(S) workloads in GKE. Overview In GKE, an Ingress object defines rules for routing use Ingress, you must have the HTTP load balancing add-on enabled. GKE clusters have HTTP load balancing enabled by default; you must not disable it. Ingress for external and internal traffic GKE Ingress resources come in two types: Ingress for external HTTP(S) load balancer deploys the Google Cloud external HTTP(S) load balancer. This internet-facing load balancer is deployed globally across Google's edge network as a managed and scalable pool of load balancing resources. Learn how to set up and use Ingress for external HTTP(S) load balancer. Ingress for Internal HTTP(S) Load Balancing deploys the Google Cloud internal HTTP(S) load balancer. These internal HTTP(S) load balancers are powered by Envoy proxy systems outside of your GKE cluster, but within your VPC network. Learn how to set up and use Ingress for Internal HTTP(S) Load Balancing. Google Cloud network services - Support for multiple TLS certificates. An Ingress can specify the use of multiple TLS certificates for request termination. For a comprehensive list, see Ingress features. Container-native load balancing Container-native load balancing is the practice of load balancing directly to Pod endpoints in GKE using Network Endpoint Groups (NEGs). When using Instance Groups, Compute Engine load balancers send traffic to VM IPs as backends. When running containers on VMs, in which containers share the same host interface, this introduces some limitations: - It incurs two hops of load balancing - one hop from the load balancer to the VM NodePortand another hop through kube-proxy routing to the Pod IP (which may reside on a different VM). - Additional hops add latency and make the traffic path more complex. - The Compute Engine load balancer has no direct visibility to Pods resulting in suboptimal traffic balancing. - Environmental events like VM or Pod loss are more likely to cause intermittent traffic loss due to the double traffic hop. With NEGs, traffic is load balanced from the load balancer directly to the Pod IP as opposed to traversing the VM IP and kube-proxy networking. In addition, Pod readiness gates are implemented to determine the health of Pods from the perspective of the load balancer and not just the Kubernetes in-cluster health probes. This improves overall traffic stability by making the load balancer infrastructure aware of lifecycle events such as Pod startup, Pod loss, or VM loss. These capabilities resolve the above limitations and result in more performant and stable networking. Container-native load balancing is enabled by default for Services when all of the following conditions are true: - For Services created in GKE clusters 1.17.6-gke.7 and up - Using VPC-native clusters - Not using a Shared VPC - Not using GKE Network Policy In these conditions, Services will be annotated automatically with cloud.google.com/neg: '{"ingress": true}' indicating that a NEG should be created to mirror the Pod IPs within the Service. The NEG is what allows Compute Engine load balancers to communicate directly with Pods. Note that existing Services created prior to GKE 1.17.6-gke.7+ will not be automatically annotated by the Service controller. For GKE 1.17.6-gke.7+ clusters where NEG annotation is automatic, it is possible to disable NEGs and force the Compute Engine load balancer to use an instance group as its backends if necessary. This can be done by explicitly annotating Services with cloud.google.com/neg: '{"ingress": false}'. For clusters where NEGs are not the default, it is still strongly recommended to use container-native load balancing, but it must be enabled explicitly on a per-Service basis. The annotation should be applied to Services in the following manner: kind: Service ... annotations: cloud.google.com/neg: '{"ingress": true}' ... Shared VPC Ingress and MultiClusterIngress resources are supported in Shared VPC topologies, but require some upfront preparation to work. The GKE Ingress controllers use a Google Cloud service account to deploy and manage Google Cloud resources. When a GKE cluster resides in a service project of a Shared VPC, this service account does not have the rights to manage network resources owned by the host project. The Ingress controller actively manages firewall rules to provide access between load balancers and Pods and also between centralized health checkers and Pods. However, in a Shared VPC, the GKE Ingress controller has no rights to manage firewall rules. You can add rights by manually provisioning firewall rules from the host project or by providing the GKE Ingress controller permission to manage host project firewall rules. Manually provision firewall rules from the host project If your security policies only allow firewall management from the host project, then you can provision these firewall rules manually. When deploying Ingress in a Shared VPC, the Ingress resource event provides the specific firewall rule you need to add necessary to provide access. To manually provision a rule: View the Ingress resource event: kubectl describe ingress INGRESS_NAME Replace INGRESS_NAME with the name of your Ingress. You should see output similar to the following example: Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal Sync 9m34s (x237 over 38h) loadbalancer-controller Firewall change required by network admin: `gcloud compute firewall-rules update k8s-fw-l7--6048d433d4280f11 --description "GCE L7 firewall rule" --allow tcp:30000-32767,tcp:8080 --source-ranges 130.211.0.0/22,209.85.152.0/22,209.85.204.0/22,35.191.0.0/16 --target-tags gke-l7-ilb-test-b3a7e0e5-node --project <project>` The suggested required firewall rule appears in the Messagecolumn. Copy and apply the suggested firewall rules from the host project. Applying the rule provides access to your Pods from the load balancer and Google Cloud health checkers. Providing the Ingress controller permission to manage host project firewall rules An automated approach is to provide the GKE Ingress controller service account the permissions to update firewall rules. Create a custom IAM role which provides the ability to manage firewall rules directly and grant this role to the GKE Ingress service account. In your host project, grant a custom role with the compute.firewalls.*and compute.networks.updatePolicypermissions to the GKE service account of the service project: gcloud iam roles create ROLE_NAME \ --project PROJECT_ID \ --title ROLE_TITLE \ --description ROLE_DESCRIPTION \ --permissions=compute.networks.updatePolicy, compute.firewalls.*\ --stage GA Replace the following: - ROLE_NAME: add a name for the role. - PROJECT_ID: add the project ID of the host project. - ROLE_TITLE: add the title of the role you want to create. - ROLE_DESCRIPTION: add the description of the role you want to create. Apply this custom role to the GKE Ingress service account: gcloud projects add-iam-policy-binding my-project \ --member=user:SERVICE_ACCOUNT \ --role=roles/gke-ingress-fw-management The value of SERVICE_ACCOUNT differs between GKE Ingress and multi-cluster Ingress: If you are using GKE Ingress, then SERVICE_ACCOUNT is: PROJECT_NUMBER@container-engine-robot.iam.gserviceaccount.com. If you are using multi-cluster Ingress, then SERVICE_ACCOUNT is: PROJECT_NUMBER@gcp-sa-multiclusteringress.iam.gserviceaccount.com. Replace PROJECT_NUMBER with your host project's project number. Multiple backend services Each external HTTP(S) load balancer or internal HTTP(S) load balancer uses a single URL map, which references one or more backend services. One backend service corresponds to each Service referenced by the Ingress. called my-ingress: apiVersion: networking.k8s.io external HTTP(S) load balancer or internal, you must use type: NodePort unless you're using container native load balancing. If using container native load balancing, use the type: ClusterIP.: networking.k8s.io. Ingress to Compute Engine resource mappings The GKE Ingress controller deploys and manages Compute Engine load balancer resources based on the Ingress resources that are deployed in the cluster. The mapping of Compute Engine resources depends on the structure of the Ingress resource. Awareness of these resources mappings helps you with planning, designing, and troubleshooting. The my-ingress manifest shown in the Multiple backend services section specifies an external Ingress resource with two URL path matches that reference two different Kubernetes Services. Here are some of the Compute Engine resources created on behalf of my-ingress: - A forwarding rule and IP address. - Compute Engine firewall rules that permit traffic for load balancer health checks and application traffic from Google Front Ends or Envoy proxies. - A target HTTP proxy and a target HTTPS proxy, if you configured TLS. - A URL map which with a single host rule referencing a single path matcher. The path matcher has two path rules, one for /*and another for /discounted. Each path rule maps to a unique backend service. - NEGs which hold a list of Pod IPs from each Service as endpoints. These are created as a result of the my-discounted-productsand my-productsServices. The following diagram provides an overview of the Ingress to Compute Engine resource mappings. Options for providing SSL certificates There are three ways to provide SSL certificates to an HTTP(S) load balancer: - Google-managed certificates - Google-managed SSL certificates are provisioned, deployed, renewed, and managed for your domains. Managed certificates do not support wildcard domains. - Self-managed certificates shared with Google Cloud - You can provision your own SSL certificate and create a certificate resource in your Google Cloud. Health checks. GKE uses the following procedure to create a health check for each backend service corresponding to a Kubernetes Service: If the Service references a BackendConfigCRD with healthCheckinformation, GKE uses that to create the health check. Both the Anthos Ingress controller and the GKE Ingress controller support creating health checks this way. If the Service does not reference a BackendConfigCRD: GKE can infer some or all of the parameters for a health check if the Serving Pods use a Pod template with a container whose readiness probe has attributes that can be interpreted as health check parameters. See Parameters from a readiness probe for implementation details and Default and inferred parameters for a list of attributes that can be used to create health check parameters. Only the GKE Ingress controller supports inferring parameters from a readiness probe. If the Pod template for the Service's serving Pods does not have a container with a readiness probe whose attributes can be interpreted as health check parameters, the default values are used to create the health check. Both the Anthos Ingress controller and the GKE Ingress controller can create a health check using only the default values. Default and inferred parameters The following parameters are used when you do not specify health check parameters for the corresponding Service using a BackendConfig CRD. Parameters from a readiness probe When GKE creates the health check for the Service's backend service, GKE can copy certain parameters from one container's readiness probe used by that Service's serving Pods. This option is only supported by the GKE Ingress controller. Supported readiness probe attributes that can be interpreted as health check parameters are listed along with the default values in Default and inferred parameters. Default values are used for any attributes not specified in the readiness probe or if you don't specify a readiness probe at all. If serving Pods for your Service contain multiple containers, or if you're using the Anthos Ingress controller, you should use a BackendConfig CRD to define health check parameters. For more information, see When to use a BackendConfig CRD instead. When to use BackendConfig CRDs instead Instead of relying on parameters from Pod readiness probes, you should explicitly define health check parameters for a backend service by creating a BackendConfig CRD for the Service in these situations: If you're using Anthos: The Anthos Ingress controller does not support obtaining health check parameters from the readiness probes of serving Pods. It can only create health checks using implicit parameters or as defined in a BackendConfigCRD. If serving Pods have multiple containers with unique readiness probes: If the serving Pods for a Service have more than one container, and each container has different readiness probe settings, you should define the health check for the corresponding backend service by referencing a BackendConfigCRD on the corresponding Service. GKE does not allow you to choose a specific readiness probe from which it infers health check parameters if multiple readiness probes are present in a serving Pod. If you need control over the port used for the load balancer's health checks: GKE only uses the readiness probe's containers[].readinessProbe.httpGet.portfor the backend service's health check when that port matches the service port for the Service referenced in the Ingress spec.rules[].http.paths[].backend.servicePort. Parameters from a BackendConfig CRD You can specify the backend service's health check parameters using the healthCheck parameter of a BackendConfig CRD referenced by the corresponding Service. This gives you more flexibility and control over health checks for a Google Cloud external HTTP(S) load balancer or internal HTTP(S) load balancer created by an Ingress. See Ingress features for GKE version compatibility. This example BackendConfig CRD defines the health check protocol (type), a request path, a port, and a check interval in its spec.healthCheck attribute: apiVersion: cloud.google.com/v1 kind: BackendConfig metadata: name: http-hc-config spec: healthCheck: checkIntervalSec: 15 port: 15020 type: HTTPS requestPath: /healthz do this by specifying multiple certificates in an Ingress manifest. The load balancer chooses a certificate if the Common Name (CN) in the certificate matches the hostname used in the request. For detailed information on how to configure multiple certificates, see Using multiple SSL certificates in HTTPS Load Balancing with Ingress.. Limitations In clusters using versions earlier than 1.16, the total length of the namespace and name of an Ingress must not exceed 40 characters. Failure to follow this guideline may cause the GKE Ingress controller to act abnormally. For more information, see this issue on GitHub. Quotas for URL maps apply. If you're not using NEGs with the GKE ingress controller then GKE clusters have a limit of 1000 nodes. When services are deployed with NEGs, there is no GKE node limit. Any non-NEG Services exposed through Ingress do not function correctly on clusters above. An external HTTP(S) load balancer terminates TLS in locations that are distributed globally, to minimize latency between clients and the load balancer. If you require geographic control over where TLS is terminated, you should use a custom ingress controller exposed through a GKE Service of type LoadBalancerinstead, and terminate TLS on backends that are located in regions appropriate to your needs. Combining multiple Ingress resources into a single Google Cloud load balancer is not supported. What's next - Learn more about load balancing in Google Cloud. - Read an overview of networking in GKE. - Learn how to configure Ingress for internal HTTP(S) load balancer. - Learn how to configure Ingress for external HTTP(S) load balancer.
https://cloud.google.com/kubernetes-engine/docs/concepts/ingress?hl=hi
CC-MAIN-2020-50
refinedweb
2,505
52.49
Hello Program in C A C program basically consists of the following parts: - Preprocessor Commands - Functions - Data types - Variables - Statements & Expressions Hello Program in C Open C console and write the following code: #include <stdio.h> #include <conio.h> void main() { clrscr(); printf("Hello C "); getch(); } Now click on the compile menu to compile the program. And then click on the run menu to run the c program. Output:- Hello C #include <stdio.h> – It is used to include the standard input output library functions. The printf() function is defined in stdio.h . #include <conio.h> – It is used to include the console input output library functions. The getch() function is defined in conio.h file. void main() – The main() function is the entry point of every program in c language. The void keyword indicates that it returns no value. clrscr() – This function is used to clear the previous output from the console. printf() – The printf() function is used to print data which is specified in the brackets on the console. getch() – This function requests for a single character. Until you press any key it blocks the screen. "0 Responses on Hello Program in C"
https://intellipaat.com/tutorial/c-tutorial/hello-program-c/
CC-MAIN-2017-39
refinedweb
195
76.42
Thoughtworks Placement question In AMU: It was AMU Aligarh Placement drive for B.Tech/M.Tech/M.C.A. this was Thoughtworks first question for First round. The Problem was to Make a dictionary and use a search option in c or c++ ,Java for example if the words are cat ,rat ,sat ,mat ,toy ,at,brat and user enter a word “rat” then output should be rat and at or If user search “tab” then output should be all combination like bat tab at We are providing Java solution for that question package pr1; import java.util.Scanner; import java.util.StringTokenizer; public class p1 { public static void main(String ...strings ) { String []dic = {"bat", "trap", "rat", "at", "tab", "toy"}; Scanner sc = new Scanner(System.in); System.out.println("Enter a "); String s = sc.nextLine(); char []a = s.toCharArray(); for(int i=0; i<dic.length; i++) { int n=0; for(int j=0; j<a.length; j++) { String ch = Character.toString(a[j]); if(dic[i].contains(ch)) { n++; } } if(dic[i].length() == n) System.out.println(dic[i]); } } } Python 3.0 solution for that question dict = ["bat","tab","rat","at","toy"] str = str(input()) out = [] for i in range(len(dict)): for j in range(len(dict[i])): temp = dict[i] if temp[j] in str: x = 1 else: x = 0 break if x == 1: out.append(dict[i]) if len(out) > 0: for l in range(len(out)): print(out[l]) else: print('No possible word built') Solution provided by Shruti Singh/ Mohd Danish ThoughtWorks more Competitive questions For other companies technical question. 2 comments: On Thoughtworks Placement question coderinme Pingback: NEC Tech technical Questions coderinme - Coder in Me () Pingback: NEC Tech Interview Questions coderinme - Coder in Me ()
https://coderinme.com/thoughtworks-placement-question-coderinme/
CC-MAIN-2019-47
refinedweb
291
57.87
Using Python to Extract Excel Spreadsheet Into CSV Files Using Python to Extract Excel Spreadsheet Into CSV Files I want to create a CSV file for each Excel sheet so that I can import the data set into Neo4j using the LOAD CSV command. Join the DZone community and get the full member experience.Join For Free How to Simplify Apache Kafka. Get eBook. I’ve been playing around with the Road Safety open data set and the download comes with several CSV files and an Excel spreadsheet containing the legend. There are 45 sheets in total and each of them looks like this: I wanted to create a CSV file for each sheet so that I can import the data set into Neo4j using the LOAD CSV command. I came across the Python Excel website which pointed me at the xlrd library since I’m working with a pre 2010 Excel file. The main documentation is very extensive but I found the github example much easier to follow. I ended up with the following script which iterates through all but the first two sheets in the spreadsheet – the first two sheets contain instructions rather than data: from xlrd import open_workbook import csv wb = open_workbook('Road-Accident-Safety-Data-Guide-1979-2004.xls') for i in range(2, wb.nsheets): sheet = wb.sheet_by_index(i) print sheet.name with open("data/%s.csv" %(sheet.name.replace(" ","")), "w") as file: writer = csv.writer(file, delimiter = ",") print sheet, sheet.name, sheet.ncols, sheet.nrows header = [cell.value for cell in sheet.row(0)] writer.writerow(header) for row_idx in range(1, sheet.nrows): row = [int(cell.value) if isinstance(cell.value, float) else cell.value for cell in sheet.row(row_idx)] writer.writerow(row) I’ve replaced spaces in the sheet name so that the file name on a disk is a bit easier to work with. For some reason the numeric values were all floats whereas I wanted them as ints so I had to explicitly apply that transformation. Here are a few examples of what the CSV files look like: $ cat data/1stPointofImpact.csv code,label 0,Did not impact 1,Front 2,Back 3,Offside 4,Nearside -1,Data missing or out of range $ cat data/RoadType.csv code,label 1,Roundabout 2,One way street 3,Dual carriageway 6,Single carriageway 7,Slip road 9,Unknown 12,One way street/Slip road -1,Data missing or out of range $ cat data/Weather.csv code,label 1,Fine no high winds 2,Raining no high winds 3,Snowing no high winds 4,Fine + high winds 5,Raining + high winds 6,Snowing + high winds 7,Fog or mist 8,Other 9,Unknown -1,Data missing or out of range And that’s it. Not too difficult! }}
https://dzone.com/articles/using-python-to-extract-excel-spreadsheet-into-csv
CC-MAIN-2018-47
refinedweb
465
65.93
This article illustrates a treeview control that implements node search. The library is very similar to the TreeView library available in Windows Forms. It includes three classes: TreeViewEx, TreeNodeEx, and TreeNodeCollectionEx, and an interface: INodeItemsFilter. All classes behave almost the same as their Windows Forms counterparts. TreeView TreeViewEx TreeNodeEx TreeNodeCollectionEx INodeItemsFilter In order to implement a search mechanism for your filter node, you need to define a filter class inherited from INodeItemsFilter. Take, for example, the following code: using Asterix.Controls; ... public class FindMyNodes : INodeItemsFilter { ... TreeNodeEx[] GetItems(string query) { ArrayList items = new ArrayList(20); // Create 20 items and set their text. for (int i = 0; i < 20; i++) { items.Add(new TreeNodeEx( string.Format("{0}: {1}", query, i))); } return (TreeNodeEx[]) items.ToArray(typeof(TreeNodeEx)); } } Pass an instance of FindMyNodes to the constructor of TreeNodeEx, and set it as FilterNode to one of the nodes in your collection. Take, for example, the following code: FindMyNodes FilterNode treeViewEx1.Nodes[0].FilterNode = new TreeNodeEx(string.Empty, new FindMyNodes()); Now, the first node in your collection expands to a search form. Type the search query and press Enter. The TreeView will be filled with the nodes that match your query (in this case, 20 items returned by FindMyNodes). That's it. The control fully implements visual styles with no overhead, except for the .NET framework 2.0. Still, the project could be compiled on Visual Studio .NET 2003 with little change. The problem with visual styles, that I found pretty tricky, is that ScrollableControl doesn't implement borders. Without borders implemented by the base class, I couldn't create borders that look like those of a TreeView. As a workaround, I used the following piece of code: ScrollableControl protected override CreateParams CreateParams { get { CreateParams p = base.CreateParams; p.ClassName = "SysTreeView32"; p.ClassStyle = 8; p.ExStyle = 512; p.Style = 1442914336; return p; } } I copied the exact CreateParams of the standard TreeView. This actually creates the window of a TreeView and implements the functionality of ScrollableControl. Now, Windows paints the borders exactly like a TreeView and the contents are custom-drawn. CreateParams.
https://www.codeproject.com/Articles/13750/TreeView-filter
CC-MAIN-2017-43
refinedweb
346
52.15
Python Notes... Page Contents To Read - - - - - - - - - - - - - - - - the second answer not the accepted one - - djcelery is tinstalled by running 'pip install django-celery' - - - - - REST tutorial - - - - - - - - - - Python Gotchas - - SLOW REGEX ENGINE Useful Python Related Sites - Planet Python - A blog aggregating list that lets you keep up with what's new and fresh in the Python world. - Python Tutor - An awesome site that visually lets you understanding what happens as the computer runs each line of source code! Very cool! Python Debugger: Winpdb A really quite cute Python debugger, easy to use and GUI driver, is Winpdb: Winpdb is a platform independent GPL Python debugger with support for multiple threads, namespace modification, embedded debugging, encrypted communication and is up to 20 times faster than pdb. Winpdb is being developed by Nir Aides since 2005. PyLint: Linting Python Code Run PyLint Generally you can run pylint on a directory. But note that directory and subdirectories you want to check must have the __init__.py file in them, even if it is just empty. To just run pylint individually on all your python files do this... find . -name '*.py' | xargs pylint --rcfile=pylint_config_filename Use the -rn option to suppress the summary tables at the end of the pylint output. Usefully you can also use PyLint with PyEnchant to add spell checking to your comments, which can be pretty useful. To configure the dictionary to use just look up the [SPELLING] section in the PyLint RC file! Message Format The messages have the following format: MESSAGE_TYPE: LINE_NUM:[OBJECT:] MESSAGE The message type can be one of the following: Configuring Pylint If you want to apply blanket settings across many files use the --rcfile=<filename> switch. In the rcfile you can specify things like messages to supress at a global level, for example. This is much easier than trying to list everything you want to supress on the command line each time your run pyline. To generate a template pylint rcfile use: pylint --generate-rcfile Inside the generated rcfile there are a few things that can be interesting. The most interesting is the init-hook which you can set, for example, to update the PYTHONPATH so that pylint can find all the imported modules: [MASTER] init-hook='import sys; sys.path.append(...);' Note that the string is a one-liner python script. Explain An Error Message In an error message you will get, at the end of the message a string in parenthesis. For example you light see something like this: C:289, 4: Missing method docstring (missing-docstring) C:293, 4: Invalid method name "im_an_error" (invalid-name) To get help on either of these errors, type: pylint --help-msg=missing-docstring Or... pylint --help-msg=invalid-name Suppressing Error Messages To disable an error message for the entire file use --disable=msg-name. So, if you want to ignore all missing docstrings use --disable=missing-docstring. Find all PyLint codes here. Or, you can use the command line "pylint --list-msgs" to list error messages and their corresponding codes. To supress an error message for a specifc line of code, or for a block of code (put comment on first line of block start), use #pylint: disable=... Longer/Different Allowed Function/Variable/etc Names Sometimes I just want names longer than 30 characters. You could say that these names are too long, but then, esp. for functions, I find shortening the name makes it less meaningful or introduces abbreviations for things, which can make the code harder to read, esp. if the aabreviation isn't a standard/well-known one. In your rcfile navigate to the section [BASIC]. Here you can edit the regular expressions that are used to validate things like functions names. E.g., I sometimes change: function-rgx=[a-z_][a-z0-9_]{2,30} To: function-rgx=[a-z_][a-z0-9_]{2,40} Supress Warnings For Unused Function Arguments Often you'll be defining something like a callback or implementing an interface etc but won't need to use all the function arguments. By default PyLint will bitch about this, but to get it to ignore the variable just prefix the variable name with either "dummy" or "_". Use PyLint To Count LOC Thanks to the author of, and comments made, for the following StackOverflow post. Although LOC is not a good metric in the sense that many lines of bad code is still bad, to get a reasonable count of the lines of code (LOC) for all Python files contained in the current folder and all subfolders, use the following command. find . -name '*.py' | xargs pylint 2>&1 | grep 'Raw metrics' -A 14 xargs takes the output of find and uses it to construct a parameter list that is passed to pylint. I.e. we get pylint to parse all files under our source tree. This output is passed to grep which searches for the "Raw Metrics" table heading and then outputs it along with the next 14 lines (due to the -A 14 option). Spell Check Your Comments On Linux systems you can use the enchant library paired with pyenchant to add spell checking to your comments. Install dependencies: sudo apt install enchant sudo pip3 install pyenchant Then you can lint using these options: pylint3 \ --enable spelling \ --spelling-dict en_GB \ --spelling-private-dict-file mt-dict.txt \ FILENAME.py Find Similar/Duplicate Code pylint --disable=all --enable=similarities src/ Flake8 Flake8 is another static analyser / PEP8 conformace checker to python. I have found that sometimes it finds things that pylint doesn't and vice versa, so hey, why not use both?! To configure it with the equivalent of a pylint rcfile just create the file tox.ini or setup.cfg (I prefer the former as the latter is a little too generic) in the directory that you run flake8 from. This avoids having to use a global config file - you can have one per project this way. All the command line options that you would configure flake8 with become INI file style settings. For example, if you ran: flake8 --ignore=E221 --max-line-length==100 This would become the following in the config file (note the file must have the header [flake8]: [flake8] ignore = E221 max-line-length = 100 Installing Python Libraries From Wheel Files Python wheels are the new standard of python distribution. First make sure you have wheels installed: pip install wheel Once you have installed wheels you can download wheel files (*.whl) to anywhere on your computer and run the following: pip install /path/to/your/wheel/file.whl So, for example, when I wanted to install lxml on my Windows box, I went to Christoph Gohlke's Unofficial Windows Binaries for Python Extension Packages and downloaded the file lxml-3.6.4-cp27-cp27m-win_amd64.whl and typed the following: pip install C:\Users\my_user_name\Downloads\lxml-3.6.4-cp27-cp27m-win_amd64.whl Windows Python Module Installers: When Python Can't Be Found It seems, when I install Windows Python from scratch that some installers will give the following error message: python version 2.7 required, which was not found in the registry The answer on how to overcome this is found in this SO thread, credits to the answer's author! To summarise, Windows Python Installer created [HKEY_LOCAL_MACHINE\SOFTWARE\Python] and all the subkeys therein, but not [HKEY_CURRENT_USER\SOFTWARE\Python]. Oops! Easiest way to evercome this is to load regedit.exe and natigate to the [HKEY_LOCAL_MACHINE\SOFTWARE\Python]. Righ click on this entry and export it to a file of your choosing. Then edit the file to replace all occurrences of HKEY_LOCAL_MACHINE with HKEY_CURRENT_USER. Save it and double click it to install the Python info to the current user registery keys. Now the installers will run :) For example, my registery file, after edit looked like this: Windows Registry Editor Version 5.00 [HKEY_CURRENT_USER\SOFTWARE\Python] [HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore] [HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7] [HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help] [HKEY_CURRENT_USER\SOFTWARE\Python\PythonCore\2.7\Help\Main Python Documentation] @="C:\\Python27\\Doc\\python2712.chm" " Running Python 2 and 3 on Windows See this SO thread. To summarise: ## Run scripts: py -3 my_script.py # execute using python 3 py -2 my_script.py # execute using python 2 ## Run pip: pip3 (alias) py -3 -m pip install ... # Python 3 pip install py -2 -m pip install ... # Python 2 pip install Python functions gotcha: default argument values - default value evaluated only once! Ooh this one is interesting and is not at all how I intuitively imagined default values. I assumed that when a function parameter has a default value, that on every call to the function, the parameter is initialised with the default value. This is not the case, as I found [Ref]! The default value is evaluated only once and acts like a static variable in a C function after that! The following example is taken from the Python docs on functions: def f(a, L=[]): # Caution! You might not expect it but this function accumulates # the arguments passed to it on subsequent calls L.append(a) return L print(f(1)) # Prints [1] print(f(2)) # Prints [1, 2], not [2] as you might expect! This is summarised in the docs... The default value is evaluated only once. This makes a difference when the default is a mutable object such as a list, dictionary, or instances of most classes ... [because] the default ... [will] be shared between subsequent calls ... Python Binding (vs C++11 Binding) Python lambda's bind late (are lazily bound) [Ref]. This means the the following code will have the output shown: x = 1 f = lambda y: y * x print f(2) x = 10 print f(2) # Outputs: # 2 # 20 I.e., the value of x is looked up in the surrounding scope when the function is called and not when the expression creating the lambda is evaluated. This means that in the statement f = lambda y: y * x, the variable x is not evaluated straight away. It is delayed until x is actually needed. Hence the two different values are output when we call f(2) with the same parameter value. We can go to the Python docs for further information: A block is a piece of Python program text that is executed as a unit. The following are blocks: - A module, - A function body, - A class, - A script file, - ... ... variable is used in a code block but not defined there, it is a free variable. So, we can see that in the lambda expression above, the variable x is a free variable. So, it is resolved using the nearest enclosing scope. The nearest enclosing scope in the above example happens to be the global scope. This is the same example as you find in many classic examples [Ref], replicated here: def create_multipliers(): return [lambda x : i * x for i in range(5)] for multiplier in create_multipliers(): print multiplier(2) # Outputs # 8 8 8 8 (newlines removed for brevity) Why does it output 8's? Because the list comprehension creates a list of lambda functions, in which the variable i has not yet been evaluated. By the time we come to evaluate the lambda i is set to 4. How is i evaluated? As it is a free variable in the lambda it is "resolved using the nearest enclosing scope". The nearest enclosing scope is the function body of create_multiplies() (because a list comprehension is not a block, so i is bound in create_multiplies()). By the time create_multiplies() exits, i is 4, but because the lambda closes this scope, every time i is looked up, it is 4, because the lookup of i does not occur until later, when the lambdas are actually evaluated. I.e., create_multipliers() is called. This creates a list of 4 lambda functions: [lambda1, lambda2, lambda3, lambda4] Each lambdaX has not yet been evaluated, so by the time this list has been create, the variable i has the value 4. Later, when any of the lambda functions are called, i is evaluated so Python searches down the scope chain until it finds the first i, which it does and in this case it has the value 4! Note, that this is a little different in C++. In C++ (C++11 or greater) however, you would have to pass x by reference to get the same result. If we transliterate the first example to C++ we get: #include <iostream> int main(int argc, char* argv[]) { int x = 1; auto myLambda = [x](int y) { return x * y; }; std::cout << myLambda(2) << "\n"; x = 10; std::cout << myLambda(2) << "\n"; return 0; } // Prints: // 2 // 2 (notice here Python would print 20! To get the behaviour of Python we have to do the following: auto myLambda = [&x](int y) { return x * y; }; Note the ampersand added before x so that the outer scope is passed to the lambda by reference, not value! Infinite recursion in __setattr__() & __getattr__() in Python The recursion problem In most, if not all, of the little tutorials I used to learn about __setattr__() and __getattr__() seemed either to treat them independently, in other words, the example classes had one or the other defined but not both, or used both but had very simple use cases. Then as I started to play with them, in my newbie-to-python state, I did the following (abstracted out into a test case). This also serves as a little Python __setattr__ example and a Python __getattr__ example... class Test(object): def __init__(self): self._somePrivate = 1 def __getattr__(self, name): print "# GETTING %s" % (name) if self._somePrivate == 2: pass return "Test attribute" def __setattr__(self, name, val): print "# SETTING %s" % (name) if self._somePrivate == 2: pass super(Test, self).__setattr__(name, val) t = Test() print t.someAttr Running this causes a the maximum recursion depth to be reached: $ python test1.py # SETTING _somePrivate # GETTING _somePrivate ...<snip>... # GETTING _somePrivate Traceback (most recent call last): File "test1.py", line 17, in t = Test() File "test1.py", line 3, in __init__ self._somePrivate = 1 File "test1.py", line 13, in __setattr__ if self._somePrivate == 2: File "test1.py", line 7, in __getattr__ if self._somePrivate == 2: ...<snip>... File "test1.py", line 7, in __getattr__ if self._somePrivate == 2: RuntimeError: maximum recursion depth exceeded As I had read up on the subject it was clear that one can't set an attribute in __setattr__() because that would just cause __setattr__() to be called again resulting in infinite recursion (until the stack blows up!). The solution (in "new" style classes which derive from object) is to call the parent's __setattr__() method. As for __getattr__(), from the documentation it was also clear that "...if the attribute is found through the normal mechanism, __getattr__() is not called...". So, I thought that was all my recursion problems sorted out. Also, if you delete either the __getattr__() or __setattr__() from the above example, it works correctly. So for example... class Test2(object): def __init__(self): self._somePrivate = 1 def __getattr__(self, name): print "# GETTING %s" % (name) if self._somePrivate == 2: pass return "Test attribute" t = Test2() print t.someAttr ... the above test program works as expected and outputs the following. # GETTING someAttr Test attribute So, what is it about the first example that causes the infinite recursion? The first problem is this little line in the constructor... self._somePrivate = 1 At this point in the constructor, variable self._somePrivate does not yet exist. When __setattr__() is called the first thing it will does is to query self._somePrivate... def __setattr__(self, name, val): if self._somePrivate == 2: # -- Oops -- This means that __getattr__() must be called to resolve self._somePrivate because the variable does not yet exist and therefore cannot be "...found through the normal mechanism...". And here is the flaw... my initial assumption was that this would work because __getattr__() is only called if the attribute can't otherwise be found, and I thought it would be found. But of course, it cannot be found, so __getattr__() also has to be called. Then, __getattr__() tries to access the variable self._somePrivate and because it still does not exist, __getattr__() is called again, and again, and so on... resulting in the infinite recursion seen. And from this we can understand why the second example worked. Because there is no __setattr__() defined in the second test class, the method does not try to read the variable first (as my little example did) and so __getattr__() need never be called. Therefore the variable is created successful upon class initialisation and any subsequent queries on the variable will be found using the normal mechanism. Even if the second example had defined __setattr__(), as long as it did not try to read self._somePrivate, it would have been okay. So the moral of this little story was, if implementing either of these magic methods, be careful which variables you access as part of the get/set logic! I needed to do this however, so what can be done to resolve this. The solution is to define the constructor as follows, using exactly the same type of set we used in __setattr__() to avoid the recursion problem: class Test(object): def __init__(self): super(Test, self).__setattr__('_somePrivate', 1) Now the example works again... yay! Setting the value of a class instance array Another thing I had been doing was to set an element of an array in the __setattr__() function and a kind chappy on StackOverflow answered my question which I'll duplicate below. In the example below the line self._someAttr = 1 behaves as I'd have expected by getting __setattr__() to recurse, only the once, back into itself. What I didn't understand was why the line self._rowData[Test.tableInfo[self._tableName][name]] = val didn't do the same. I was thinking that to set the array we'd call __setattr__() again, but it doesn't. The test example is shown below. class Test(object): tableInfo = { 'table1' : {'col1' : 0, 'col2':1} } def __init__(self, tableName): super(Test, self).__setattr__('_tableName', tableName) # Must be set this way to stop infinite recursion as attribute is accessed in bot set and get attr self._rowData = [123, 456] def __getattr__(self, name): print "# GETTING %s" % (name) assert self._tableName in Test.tableInfo if name in Test.tableInfo[self._tableName]: return self._rowData[Test.tableInfo[self._tableName][name]] else: raise AttributeError() def __setattr__(self, name, val): print "# SETTING %s" % (name) if name in Test.tableInfo[self._tableName]: print "Table column name found" self._rowData[Test.tableInfo[self._tableName][name]] = val self._someAttr = 1 else: super(Test, self).__setattr__(name, val) class Table1(Test): def __init__(self, *args, **kwargs): super(Table1, self).__init__("table1", *args, **kwargs) t = Table1() print t.col1 print t.col2 t.col1 = 999 print t.col1 It produces the following output... $ python test.py # SETTING _rowData # GETTING col1 123 # GETTING col2 456 # SETTING col1 Table column name found # SETTING _someAttr # GETTING col1 999 So, why didn't the recursion occur for self._rowData[Test.tableInfo[self._tableName][name]] = val? I had thought we'd have to call __setattr__() again to set this. As the SO user "filmor" explained, the following happens: self._rowData[bla] = val gets resolved to self.__getattr__("_rowData")[bla] = val. So we get the array (it already exists so is found by the normal mechanisms and not via another call to __getattr__(). But then to set an array value __setitem__() is used an not __setattr__(). So, the expression resolves to self.__getattribute__("_rowData").__setitem__(bla, val) and there is therefore no further __setattr__() called. Simples! Concatenating immutable sequences more quickly in Python PyDoc for immutable sequences says: Concatenating immutable sequences always results in a new object. This means that building up a sequence by repeated concatenation will have a quadratic runtime cost in the total sequence length. To get a linear runtime cost ... build a list and use .join() Interesting... I've been building up SQL strings using concatenation. Is using a join really better? Lets have a look... In my simple test below I create a large list of strings and concatenate them using string concatenation in test1 and list.join() in test2. def test1(stringList): s = "" for i in stringList: s += "{}, ".format(i) def test2(stringList): s = ", ".join(stringList) if __name__ == '__main__': import timeit print(timeit.timeit("test1(map(lambda x: str(x), range(0,1000)))", setup="from __main__ import test1", number=10000)) print(timeit.timeit("test2(map(lambda x: str(x), range(0,1000)))", setup="from __main__ import test2", number=10000)) All the "map(lambda x: str(x), range(0,1000)" expression does is to create a list of 1000 strings to concatenate so that each test function is concatentating a list of the same strings. On my system (it will be different on yours) I get the following output from the test program. 5.61275982857 2.88877487183 So joining a list of strings is faster than concatenating strings by approximately 50%. Reading Excel Files in Python Worth having a look at python-excel... Reads Excel Files Using XLRD)) Read Excel Files Using Pandas)) Note that Pandas is zero indexed, whereas excel is 1 indexed. import pandas pandas.read_excel(xlsxFileName, worksheetName, header=excel_header_row_number) Finding Index Of Closest Value To X In A List In Python If a list is unsorted, to find the closest value one would iterate through the list. At each index the distance from the value at that index to the target value is measured and if it is less than the least distance seen so far that index is recorded. That's basically one for loop with a few tracking variables... O(n) operation. But, for loops aren't really very Pythonic in many ways and half to point of having a vectorized library like numpy is that we avoid that tedium.This is why, when I saw this solution to the problem, I though "ooh that's clever"... findClosestIndex = lambda vec, val: numpy.arange(0,len(vec))[abs(vec-val)==min(abs(vec-val))][0] closestIndex = findClosestIndex(array_to_search, value_to_find_closest_to) It's also a very terse read! So, let's break it down. The lambda expression is equivalent to the following. def findClosestIndex(vec, val): # Pre: vec is a numpy.array, val is a numeric datatype vecIndicies = np.arange(len(vec)) # produces the distance of each array value from "val". distanceFromVal = abs(vec-val) # the smallest distance found. minDistance = min(distanceFromVal) # Produce a boolean index to the distance array selecting only those distances # that are equal to the minimum. vecIndiciesFilter = distanceFromVal == minDistance # vecIndicies[vecIndiciesFilter] is an array where each element is the index # of an element in vec which equals val. return vecIndicies[vecIndiciesFilter][0] The line vecIndicies = np.arange(len(vec)) produces an array that is exactly the same size as the array vec where vecIndicies[i] == i. The line distanceFromVal = abs(vec-val) produces an array where distanceFromVal[i] == |vec[i] - val|. In other words, each element in distanceFromVal corresponds to the distance of the same element in vec from the value we are searching for, val. The next line... The next line produces an array vecIndiciesFilter where each element, vecIndiciesFilter[i], is True if distanceFromVal[i] == minDistance TODO... incomplete, needs finishing with SO better method and speed comparisons. Drop Into The Python Interpretter import code code.interact(local=locals()) Working With Files In Python Check If a File Or Directory Exists import os.path if os.path.isfile(fname): print "Found the file" if os.path.isdir(dirname): print "Found the directory" Traversing Through Directories For Files To find all files matching a certain pattern in a selected directory and all of its subdirectories, using something like the following can work quite well... def YieldFiles(dirToScan, mask): for rootDir, subDirs, files in os.walk(dirToScan): for fname in files: if fnmatch.fnmatch(fname, mask): yield (rootDir, fname) # Find all .txt files under /some/dir for dir, file in YieldFiles("/some/dir", "*.txt") print file The above searches from parent directory to children in a recursive descent, i.e, top-down fashion. If you want to search bottom-up then add the flag topdown=True to the os.walk() function. Deleting Files and Directories (Recursively) The Python library shutils has plenty of functions for doing this. For example, if you want to remove a temporary directory and all files and subdirectories within... if os.path.exists(cacheDir): shutil.rmtree(cacheDir) # Recursively delete dir and contents os.makedirs(cacheDir) # Recreate dir (recursively if # intermediete dirs dont exist) However, you may sometimes run into problems on windows when deleting files or directories. This is normally a permissions issue. Also, although this seems silly, you won't be able to delete a directory if your current working directory is set to that directory or one of its children. Handling Signals Handling signals in Python can be done like so: import signal # Somewhere in your initialisation signal.signal(signal.SIGINT, signal_handler) def signal_handler(signal, frame): # Clean up etc sys.exit(1) Handle Non-Blocking Key Presses ## Keyboard stuff mostly from with some modifications ## from import os if os.name == 'nt': import msvcrt def setup_terminal(): pass def kbhit(): return msvcrt.kbhit() def kbchar(): return msvcrt.getch().decode("utf-8") else: import sys, select, tty, termios, atexit def setup_terminal(): fd = sys.stdin.fileno() old_settings = termios.tcgetattr(fd) tty.setcbreak(sys.stdin.fileno()) def restore_terminal(): fd = sys.stdin.fileno() termios.tcsetattr(fd, termios.TCSADRAIN, old_settings) atexit.register(restore_terminal) def kbhit(): dr,dw,de = select.select([sys.stdin], [], [], 0) return dr != [] def kbchar(): return sys.stdin.read(1) TODO Stat and os.walk in opposite direction --- import fnmatch import os for root, dirs, files in os.walk("/some/dir"): for fname in files: if fnmatch.fnmatch(file, '*.txt'): pass --- Script dir Print literal {} also formatting from my little debug output class Get Hostname python get environment variable import os os.environ['A_VARIABLE'] = '1' print os.environ['A_VARIABLE'] ## Key must exist! To not care if key exists use print os.environ.get('A_VAR') # Returns None of key doesn't exist platform.system() flush stdout import sys sys.stdout.flush() current time as string: def GetTimeNowAsString(): return time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime()) logging: logging.basicConfig( format='%(asctime)s - %(name)s - %(levelname)s - %(message)s', level=logging.DEBUG [, filename='debug.txt', filemode='w']) log = logging.getLogger(__name__) printing on windows. can't remember where I got this... some SO thread, needs references! )
https://jehtech.com/python/python.html
CC-MAIN-2021-25
refinedweb
4,407
57.06
SciChart.js v2.x now supports sharp graphics on high resolution: - Lines, strokes, shapes now look sharper and clearer on higher DPI displays or when browser is zoomed - Text is rendered at a higher resolution. Text scales with browser zoom (good for Accessibility) - Stroke thickness (line pen) increases with Browser Zoom Take a look below to see some comparison images side by side of SciChart.js v1 vs. v2 at 200% Browser zoom in Chrome. In particular, notice the quality of text, lines and gridlines difference between version 1 and version 2 when at 200% browser zoom: Enabling & Disabling Retina DPI / Browser Zoom Support By default, Retina & high DPI support is built in, you don't have to do anything to enable it. However, if you wanted to disable automatic scaling with DPI then you can use the following code: import { DpiHelper} from "scichart/Charting/Visuals/TextureManager/DpiHelper"; // Note: you will need to call this before any SciChartSurface is created DpiHelper.IsDpiScaleEnabled = false; Performance Considerations when Dpi Scaling When SciChart.js is used on a high resolution display such as Retina, the chart will be rendered at 4x the number of pixels visible on screen. For example a 1,000 x 1,000 chart (1M Pixels) will be rendered at 2,000 x 2,000 (4M Pixels) before scaling down to the correct size. Higher number of pixels means more work for the browser to display the chart. If you notice any performance degredation on your application you can disable Dpi scaling using the code above. Also, we recommend use of Google Chrome browser as this has by far the best performance metrics, compared to Safari or Firefox, which both struggle to render large canvases.
https://www.scichart.com/documentation/js/current/Retina%20Support%20and%20Browser%20Zoom.html
CC-MAIN-2022-33
refinedweb
285
57
This section demonstrates how to create an entry in the directory. Create a new entry by allocating space, and creating a completely new entry. Alternatively, create a new entry by duplicating an existing entry and modifying its values. Create a completely new entry by using slapi_entry_alloc() to allocate the memory that is required, as shown in the following example. #include "slapi-plugin.h" int test_ldif() { Slapi_Entry * entry = NULL; /* Entry to hold LDIF */ /* Allocate the Slapi_Entry structure. */ entry = slapi_entry_alloc(); /* Add code that fills the Slapi_Entry structure. */ /* Add code that uses the Slapi_Entry structure. */ /* Release memory allocated for the entry. */ slapi_entry_free(entry); return (0); } Create a copy of an entry with slapi_entry_dup().
http://docs.oracle.com/cd/E19424-01/820-4810/aaheb/index.html
CC-MAIN-2015-32
refinedweb
110
50.94
xmlns using syntax for another assembly (UserControl cant find a sibling control) - Thursday, October 13, 2011 6:50 PM I know in the WinRT XAML stack, the xmlns syntax has changed to "using:NamespaceHere". This seems to work fine even when the namespace is in another referenced assembly. For example, I have some controls over in another (metro) assembly and my metro application project has a reference to that. So the xmlns:Controls="using:SeparateAssembly.Controls" syntax works fine. What is NOT working though, is then when a control in that separate assembly uses ANOTHER control in that separate assembly, I get a runtime exception that the 2nd control cannot be found. I can use that control directly in my UI, but I can't use it from WITHIN the separate assembly. It feels like at runtime, it's using the executing assembly to look for the namespace, not the one where the XAML is being parsed from. Is there an additional "assembly" syntax I should be using in the controls project XAML files to make sure all those controls can be found regardless of where we're loaded from? My description might be a little cloudy, so here's a concrete example: UIProject1, references ControlsProject1, which has 2 controls in it. UserControl1 and UserControl2. UserControl1.xaml contains a using statement for, and uses UserControl2. When UIProject1\MainPage.xaml uses UserControl1 (has the standard xmlns using statement for UserControl1 namespace, but nothing about it being in another assembly), I get a runtime exception that UserControl1 can't find UserControl2. UIProject1\MainPage.xaml can directly create UserControl2, to prove that it's creatable and will show in the UI. Thanks in advance for any guidance. Answers - - All Replies - Tuesday, October 18, 2011 4:40 PMModerator Hi Volleynerd, Can you send me a project with the problem you're describing? MSmall at Microsoft. Thanks, Matt Matt Small - Microsoft Escalation Engineer - Forum Moderator - Wednesday, October 19, 2011 11:29 PM Hi Matt - Just emailed you a zip that shows the problem. In building the zip, we boiled it down to the following. - Put 2 user controls in a class library separate from the main UI project - UserControl1 uses UserControl2 in its XAML definition - Make use of UserControl1 in the UI project (MainPage.xaml) - Works fine if you only do the above. - This sounds crazy but ... add a class to the controls project and have that class implement INotifyPropertyChanged (from UI.Xaml.Data, not System.ComponentModel). You don't even have to use that class anywhere. Run the app. It blows up trying to load UserControl2 Zip of the code showing the problem: - - - Sunday, February 19, 2012 4:00 PMHi, have you found a workaround or a bugfix for this problem? I need this to work in my project... - Edited by Rico Suter Sunday, February 19, 2012 4:52 PM -
http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/b8c0215f-9377-4518-b9ae-68fbeeb64ff0/
crawl-003
refinedweb
476
55.74
09 January 2008 17:15 [Source: ICIS news] By Nigel Davis LONDON (ICIS news)--The world’s biggest electronic gadgets fest held annually in ?xml:namespace> Past exhibitors at the Consumer Electronics Show (CES) have showcased among other novelties the videocassette recorder, the compact disc player and the high definition TV. This year is likely to be no exception. From CES 2008 so far it is clear that flat screen TVs are just going to get bigger and that electronics, and the materials that support them, are going to make still further inroads into the home and into transport. Microsoft chairman Bill Gates in his valedictory keynote address to the show – he steps down from his main Microsoft role later this year – talked of an up-coming “user-centric” decade in which connectivity becomes increasingly important. Consumers will connect with each other as will their in-home and in-car gadgets. And as electronic goods and systems become ever more embedded in everyday life the opportunities for raw material suppliers increase. Technology and the market run hand-in-hand. It was no coincidence that Bayer MaterialScience said this week that its scientists had succeeded in producing a high-purity grade of the polycarbonate Makrolon which makes possible the manufacture of flat-screen televisions in unprecedented sizes. New materials are needed to feed the demand for larger screen sizes to maintain liquid crystal display (LCD) brightness and clarity. LCD display diffuser sheets made out of conventional plastics used to date have a tendency to warp, causing picture distortion, Bayer MaterialScience says. Its scientists are still trying to optimise light scatter but work has already started on the next generation of LCD display diffusers. The chemicals and materials supplier’s role is changing in an increasingly high tech world. Bayer MaterialScience is one company to acknowledge that and push the envelope in terms of the way it tries to develop new opportunities and business partnerships. Other companies are doing the same. Dow Chemical CEO Andrew Liveris, for instance, says he wants Dow to mimic a company like GE which looks methodically for discontinuities and new needs based on technology and markets that it can serve. Liveris says Dow will focus on four platforms for growth in its specialties businesses: human health (food, nutrition, wellness), energy (alternative energy solutions, energy efficiency solutions), infrastructure & transportation (construction, water treatment, transportation), and electronics & communication (advanced materials). This is now a world of networks and alliances that can help materials suppliers become more firmly embedded in fast-growing market segments. Companies seek not just growth areas in tried and tested consumer markets but the sort of break-out opportunities that will provide them with exceptional growth. Not too long a go it might have taken decades for a new chemical technology to become firmly embedded and find the right market niche. The liquid crystals used in displays are a case in point. But world markets are moving much faster. The advances expected in the next digital decade may prove to be unprecedented. The And CES attracts a variety of firms, not just the gadget makers and big name IT suppliers. Amongst the products debuting at the 2008 show has been LG.Philips new high resolution 14.3 inch colour E-paper display. The glass and plastic substrate LCD display is approximately the size of a sheet of A 4 paper and is flexible enough to be rolled up. And General Motors’ CEO Rick Wagoner has been in town to promote the Cadillac Provoq a concept vehicle with electronics powered by a roof-mounted solar panel, a hydrogen fuel cell and a lithium-ion battery. The Provoq will also be shown at the The chemical companies’ role as molecules and materials suppliers to the auto industry may be well known but is changing. There are new opportunities to supply not just the materials to help make automobiles more fuel efficient but to alter the concept of the car itself. Before fully electronic vehicles make a stronger presence on the world stage, chemical firms will play a role in helping develop cleaner, smarter vehicles and indeed fuels. CES 2008 is a showcase for a world of opportunity and a world of changed material requirements. The clever chemical companies are those that can tap in most effectively to the profit streams that consumer electronics and other growth sectors of the economy help
http://www.icis.com/Articles/2008/01/09/9091565/insight-big-screen-opportunities-in-las-vegas.html
CC-MAIN-2014-52
refinedweb
732
50.26
Supreme Court Judgments Subscribe 28/10/1964 GAJENDRAGADKAR, P.B. (CJ) GAJENDRAGADKAR, P.B. (CJ) WANCHOO, K.N. HIDAYATULLAH, M. DAYAL, RAGHUBAR MUDHOLKAR, J.R. CITATION: 1965 AIR 1375 1965 SCR (1) 909 CITATOR INFO : R 1965 SC1387 (18) RF 1965 SC1862 (10) F 1972 SC 524 (18) RF 1973 SC1461 (218) RF 1977 SC1802 (29) RF 1981 SC1922 (9) R 1984 SC 420 (45) D 1985 SC1698 (31) C 1990 SC 781 (72) R 1990 SC1637 (38) D 1990 SC1664 (6) RF 1992 SC 803 (41,44) RF 1992 SC1360 (9) ACT: Constitution of India, 1950, List 1, VII Schedule, Entry 82Income--Income-tax Act (11 of 1922), ss. 2(6A) (e) and 12 (1B)-Legislative competence and constitutional validity. HEADNOTE: The assessee was a share holder in a private limited company whose ordinary business was not money-lending business. He took a loan amounting to over Rs. 4 lakhs from a company. The Income-tax Officer computed the assessee's income at Rs. 3 lakhs and odd, under s. 12(1B) read with s. 2 (6A) (e) of the Income-tax Act, 1922. That amount included a sum of over Rs. 2 lakhs representing the accumulated profits of the company. The assessee's share in the accumulated profits, if distributed as dividend, would be an amount proportionate to the number of shares held by him. He therefore contended, that the balance of the accumulated profits was not his income and that the Legislature was not competent to enact the two sections according to which that amount was also treated as his income. His writ petition in the High Court challenging. the constitutional validity of the two sections was dismissed. He appealed to the Supreme Court. HELD (Per Gajendragadkar, C. J., Wanchoo, Hidayatullah and Mudholkar JJ.) : (i) The sections are not beyond the legislative competence of Parliament. The companies to which s. 12(1B) applies arecompanies in which at least 75% of the voting power lies in the hands of persons other than the public. They are controlled by a group of persons allied together and having the same interest. The controlling group can determine whether the profits made by the company should be distributed as dividends or not. When they deliberately refused to distribute the accumulated profits as dividends but adopted the device of advancing the profits by way of loan to one of the shareholders, it was with the object of evading the payment of tax by the company on the accumulated profits. Section 12(1B) provides that if a controlled company adopts the device of making a loan to one of its shareholders, he will be deemed to have received the amount out of the accumulated profits as dividend and would be liable to pay tax on his income. The word "income" in Entry 82 in List I of the 7th Schedule to the Constitution must receive a wide interpretation depending on the facts of each case. Having regard to the fact that the Legislature was aware of the devices to evade tax, it would be within its competence to devise a fiction for treating an ostensible loan as the receipt of the dividend. [919 A-H. 920 H; 921 C-D] (ii) The absence of a provision enabling the income-tax officer to consider in each case whether the loan was genuine or the result of a device does not make the section go beyond the competence of the Legislature. [921 D-E] If the Legislature thought that in almost every case the advances or loans were the result of a device to evade tax, it would be competent to 910 it to prescribe a fiction and hold that in cases of such advances or loans, tax should be recovered from the shareholder on the basis that he had received a dividend. [921 G-H] (iii) Section 12(lB) does not impose an unreasonable restriction on the appellant's fundamental rights under Art. 19(1) (f) and (g) of the Constitution. [922 A] The section does not affect the appellant's right to borrow money. There is no element of unfairness, tax is evaded. Further, past transactions were excluded from the operation of the sections by the issue of a circular by the Central Board of Revenue. [922 B-F] Per Raghubar Dayal J. (dissenting) : (i) Sections 2(6A) (e) and 12(lB) of the Income-tax Act, 1922 as they stood in 1955 are void. [923 B] It is not open 'to the Legislature to describe any payment of money by a company to a shareholder by the word "dividend" and then provide that such payment will come within the expression "income" in item 82, List I of Schedule 7. The definition of dividend must have a rational connection with concept of dividend in the context of the profits of the company and its distribution amongst the shareholders.. [926 E-H] (ii) The provisions of the impugned sections impose unreasonable restrictions on the fundamental right to hold property under Art. 19(1)(f) of the Constitution. [928 E] If any enactment provides that certain profits of the company, though not distributed as dividend, be treated as used for the payment of dividends it should necessarily follow that a particular shareholder be deemed to have received a proportionate amount of such profits. It would be unreasonable to provide that a particular shareholder should be deemed to have received an amount in excess of his proportionate share as dividend. It is unreasonable that a particular shareholder who receives a loan or advance from a company be deemed to have received that entire amount as dividend when his proportionate share would be much less. [928 B-E] Navinchandra Mafatlal v. Commissioner of Income-tax, Bombay City, [1955] 1 S.C.R. 829, Sardar Baldev Singh v. Commissioner of Income-tar, Delhi and Agra [1961] 1 S.C.R. 482 and Balaji v. Income-tax Officer, Special Investigation Circle, [1962] 2 S.C.R. 983, referred to. CIVIL APPELLATE JURISDICTION: Civil Appeal No. 45 of1964. Appeal from the judgment and order dated July 30, 1962, of the Bombay High Court in Special Civil Application No. 69 of 1962. G.S. Pathak, M. M. Gharekhan and 1. N. Shroff, for the appellant. 911 C.K. Daphtary, Attorney-General, R. Ganapathy Iyer, Gopal Singh and R. N. Sachthey, for the respondent. The Judgments of P. B. GAJENDRAGADKAR C.J., K. N. WANCHOO, M. HIDAYATULLAH and J. R. MUDHOLKAR JJ. was delivered by GAJENDRAGADKAR C.J. RAGHUBAR DAYAL J. delivered a dissenting Opinion. Gajendragadkar C.J. This appeal arises from a writ petition filed by the appellant Navnit Lal C. Javeri in the Bombay High Court in which he challenged the validity of section 12(1B) read with s. 2 (6A) (e) of the Indian Income-tax Act, 1922 (No. 11 of 1922) (hereinafter called the Act) as it stood in 1955. The High Court has rejected the appellant's contention that the said section is invalid, and the appellant has come to this Court with a certificate granted by the High Court. The appellant holds 11 out of 845 shares in a private limited company named the Malegaon Electricity Co., (Private) Ltd. (hereinafter referred to as the company). The value of each share is Rs. 100. The business of the company is to supply electricity to the residents of Malegaon. Sometime during 1955, the appellant took a loan amounting to over Rs. 4 lakhs from the company. A notice was issued to the appellant by the 8th, Income-Tax Officer under s. 22(2) of the Act calling, upon him to make his return for the assessment year 1956-57. The Income-tax Officer computed his income at Rs. 3,58,460. This amount included a sum of Rs. 2,83,126 representing the accumulated profits of the company. The Income-tax Officer took the view that under s. 2 (6A) (e) the said amount must be deemed to be dividend received by the appellant, and as such, must be included in the total income of the appellant as income from other sources within the meaning of s. 12(1B) of the Act. This order was challenged by the appellant by preferring an appeal before the Appellate Assistant Commissioner. The appeal, however, failed and was dismissed. The appellant then preferred a second appeal before the Income Tax Appellate Tribunal. Whilst this appeal was pending, before the said Tribunal, the appellant moved the High Court under Articles 226 and 227 of the Constitution, and contended that the relevant section under which the department had purported to levy assessment against him on the sum of Rs. 2,83,126, was ultra vires. That is how the only question which the High Court had to decide in the present writ proceedings was whether s. 12 (1B) read with s. 2 (6A) (e) was constitutionally valid. 912 in order to deal with this point, it is necessary to read the two relevant provisions of the Act. Section 2(6C) defines "income" as including dividend. Section 2 (6A) defines "dividend" in an inclusive manner. Section 2 (6A) (e) provides "Dividend" includes(e) any payment by a company, not being a company in which the public are substantially interested within the meaning of s.; but dividend does not include(i) (ii) any advance or loan made to a shareholder." Thus, the inclusive definition of "dividend" takes in the payments to which clause (e) of s. 2(6A) refers and makes them dividend for the purpose of the Act. Section 12(1) provides that the tax shall be payable by an assessee under the head "Income from other sources" in respect of income, profits and gains of every kind which may be included in his total income (if not included under any of the preceding heads). Section 12(lB) provides :"any payment by a company to a shareholder by way of advance or loan which would have been treated as a dividend within the meaning of clause (e) of subsection (6A) of s. 2 in any previous year relevant to any assessment year prior to the assessment year ending on the 31st day of March, 1956, had that clause been in force in that year, shall be treated as a dividend received by him in the previous year relevant to the 913 assessment year ending on the 31st day of March, 1956, if such loan or advance remained outstanding on the first day of such previous year". Both these provisions viz., s. 2(6A)(e) and s. 12(lB) were introduced in the Act by the Finance Act 15 of 1955 which came into operation on the 1st of April, 1955. It is thus clear that the combined effect of these two provisions is that three kinds of payments made to the shareholder of a company to which the said provisions apply, are treated as taxable dividend to the extent of the accumulated profits held by the company. These three kinds of payments are: (1) payments made to the shareholder by way of advance or loan; (2) payments made on his behalf; and (3) payments made for his individual benefit. There are five conditions which must be satisfied before s. 12(lB) can be invoked against a shareholder. The first condition is that the company in question must be one in which the public are not substantially interested within the meaning of s.. In dealing with the question about the constitutionality of the impugned provisions, it is necessary to bear in mind these respective conditions which govern the application of the said provisions. There is another material circumstance which cannot be ignored. It appears that when these amendments were introduced in Parliament, the Hon'ble Minister for Revenue & Civil Expenditure save an assurance that outstanding loans and advances which are otherwise liable to be taxed as dividends in the assessment year 1955-56 will not be subjected to tax if it is shown that they had been genuinely refunded to the respective companies before the 30th June, 1955. It was realized by the Government 914 that unless such a step was taken, the operation of s. 12(1B) would lead to extreme hardship, because it would have covered the aggregate of all outstanding loans of past years and that may have imposed an unreasonably high liability on the respective shareholders to whom the loans might have been advanced. In order that the assurance given by the Minister in Parliament should be carried out, a circular [No. 20(XXI-6)/55] was issued by the Central Board of Revenue on the 10th May, 1955. It is clear that a circular of the kind which was issued by the Board would be binding on all officers and persons employed in the execution of the Act under s. officers were, therefore, asked to intimate to all the companies that if the loans were repaid before the 30th June, 1955 in a genuine manner, they would not be taken into account in determining the tax liability of the shareholders to whom they may have been advanced. In other words, past transactions which would normally have attracted the stringent provisions of s. 12(lB) as it was introduced in 1955, were substantially granted exemption from the operation of the said provisions by making it clear to all the companies and their shareholders that if the past loans were genuinely refunded to the companies, they would not be taken into account under s. 12(lB). Section 12(1B) would, therefore, normally Apply to loans granted by the companies to their respective shareholders with full notice of the provisions prescribed by it. Mr. Pathak for the appellant contends that the impugned provision is constitutionally invalid, because it is beyond the legislative competence of Parliament. He argues that Entry 82 in List I of the Seventh Schedule which deals with "taxes on income other than agricultural income" cannot justify the impugned provision, because a loan advanced to a shareholder by the company cannot, in any legitimate sense, be treated as his income; and so, the artificial manner in which such dividend is ordered to be treated as income by the impugned provision is not justified by the said Entry. He also contends that the said provision offends Art. 19(1) (f) & (g) and cannot be said to be justified by clause (5) or (6) of the said article. There is no doubt that if the impugned provision is beyond the legislative powers of Parliament, it would be bad. Similarly, it is now wellsettled that even tax 915 legislation must stand the scrutiny of the fundamental rights guaranteed by the Constitution, and so, there can be no doubt that if the impugned provision invades the fundamental rights of the appellant and the invasion is not constitutionally justified, it would be invalid. In dealing with this point, it is necessary to consider what exactly is the denotation of the word "income" used in the relevant Entry. It is hardly necessary to emphasis that the entries in the Lists cannot be read in a narrow or restricted sense, and as observed by Gwyer C.J. in the United Provinces v. Atiqa Begum(1). " each general word should be held to extend to all ancillary or subsidiary matters which can fairly and reasonably be said to be. In Navinchandra Mafatlal v. The Commissioner of Income-tax, Bombay City(1), this Court had occasion to consider the question as to whether capital gains could be treated as income within the meaning of item 54 of List I of the Seventh Schedule to the Government of India Act, 1935. Section 12-B of the Indian Income-tax Act, 1922 which had been inserted in the said Act by Act XXII of 1947, had imposed tax on 'capital gains'. The validity of this provision was challenged on the ground that capital gains cannot be treated as income within the meaning of entry 54. This plea was rejected by this Court on the ground that the words used in a constitutional enactment conferring legislative powers ought to be construed most liberally and in their widest amplitude. Adopting this approach Das J. as he then was, speaking for the Court, observed that the word "income" used in the said entry must be given its ordinary, natural and grammatical meaning and that was, income is a thing that comes in. On this view, the Court found no difficulty in coming to the conclusion that income would include capital gains. If the traditional (1) [1941] F.C.R. 110. (2) [1955]1 S.C.R. 829. Sup./65916 sense of income had been accepted, then, of course, capital gains could not be treated as income. That, in fact, was the argument which was pressed by Mr. Kolah who appeared for the appellant. "If we hold", observed the learned Judge, ." And he has significantly added that a conclusion so extravagant and astounding can scarcely be contemplated or countenanced. This decision, therefore shows that the word "income" used in entry 54 which corresponds to the present entry 82 in List I of the 7th Schedule to our Constitution, was liberally construed, and capital gains were deemed to be included within its scope. This aspect of the matter has also been clearly enunciated by Gwyer C.J. in re: The Central Provinces and Berar Sales of Motor Spirit and Lubricants Taxation Act, 1938 (No. 14 of 1938) (1). "I conceive", said the learned Chief Justice, "that a broad and liberal spirit should inspire those whose duty it is to interpret it (the Constitution); but I do not imply by this that they are free to stretch or pervert the language of the enactment in the interests of any legal or constitutional theory, or even for the purpose of supplying omissions or of correcting supposed errors". The next decision to which we ought to refer deals with s. 23A of the Act. In Sardar Baldev Singh v. Commissioner of Income-tax, Delhi & Ajmer(1) the validity of the said section was challenged. Section 23A(1) provides, inter alia, that subject to the provisions of sub-sections (3) and (4), where the Income-tax Officer is satisfied that in respect of any previous year the profits and gains distributed as dividends by any company within the twelve months immediately following the expiry of that previous year are less than sixty per cent of the total income of the company of that previous year as reduced by the amounts specified in clauses (a), (b) & (c) of the said sub-section, the Income-tax Officer shall, unless he is satisfied that having regard to losses incurred by the company in earlier years or to the smallness of the profits made in the previous year, the payment of a dividend or a larger dividend than that declared would be unreasonable, make an order in writing that the company shall, apart from the sum (1) [1939] F.C.R. 18 at p. 37. (2) [1961] 1 S.C.R. 482. 917 determined as payable by it on the basis of the assessment under s. 23, be liable to pay super-tax at the rate specified by the said sub-section. The object of this section is to prevent avoidance of super-tax by shareholders of a company in which the public are not substantially interested. As is well-known, the rates of super-tax applicable to companies are much lower than the rates applicable to individual assessees. The legislature thought that individuals tried to avoid the payment of super-tax at a higher rate by transferring to a private limited company it). return for shares the sources of their income, and then the profits made by the company were allowed to accumulate in the hands of the company, dividends not being declared, and the said profits would ultimately be distributed in a capital form by one device or another. The object of s. 23A was to defeat such attempts. The main effect of the provisions of s. 23A appears to be that a company should not accumulate more than 40 per cent of its net profits to build up reserves or to provide for capital expenditure It will be recalled that s. 2(6A) has taken within the definition of 'dividend" the accumulated profits of such companies, and so s. 23A attempts to reach such accumulated profits for the purpose of taxation. The argument which was urged before this Court in the cast of Sardar Baldev Singh(1) was that a company and its share, holders are different persons, and so, s. 23A was ultra vires inasmuch as it purported to tax the shareholders on the income of the company in which they hold shares. If the accumulated profits are distributed amongst the shareholders by way of dividends, the shareholders could legitimately be taxed in respect of the dividends received by them; but when s. 23A attempts to tax the shareholders for accumulated profits even though they are not distributed as dividends, what, the section purports to do is to tax the share-holders for the profits made by the company; and that, according to the appellant, made s. 23A invalid. This argument was repelled by this Court on the ground that the obvious intention of s. 23A was to prevent evasion of tax, and it was held that entry 54 should be read not only as authorising the imposition of a tax, but also as authorising an enactment which prevents the tax imposed being evaded; otherwise the power to tax a person on his income might often be made in fructuous by ingenious contrivances. It would be noticed that s. 23A wanted to deal with a situation where shareholders did not deliberately distribute the accumulated profits as dividends amongst themselves. Section (1) [1961] 1 S.C.R. 482. 918 23A, therefore, provides that these accumulated profits will be deemed to have been distributed to the shareholders and tax levied against them on that basis. It is likely that in such a case, hardship may be caused in some honest cases; but this Court made it perfectly clear that considerations of hardship are irrelevant for determining questions of legislative competence. It is thus clear that the result of the decision of this Court in Sardar Baldev Singh(1) is that the income which technically belonged to the 'company, was treated, as income belonging to the shareholders in proportion to the shares they held in the company, and on that footing tax was levied on them; and yet the said tax was held to be constitutionally valid. There is yet another case in which a similar question was considered. In Balaji v. Income-tax Officer, Special Investigation Circle, (2) a person and his wife started business in partnership and admitted their three minor sons to it. In computing the total income of the said person for the purpose of assessment, the Income-tax Officer included the share of the income of his wife and three minor sons under S. 16 (3) (a) (i) & (ii) of the Act. The validity of this provision was challenged on the ground that the impugned section purported to tax a person for the income of other persons, namely, his wife and minor sons. In rejecting the contention raised against the validity of the impugned section, this Court held that the Entries in the Legislative Lists are not powers but fields of legislation and the widest import and significance should be attached to them. On this view, the conclusion reached by this Court was that Entry 54 of the Federal Legislative List covered legislation like s. 16 (3) (a) (i) & (ii), because it was intended to prevent evasion of tax. It appears from the judgment that the validity of the said section was also challenged on the ground that it contravened Articles 14 and 19(1) (f) & (g) of the Constitution. This plea was also rejected. One of the considerations which weighed with the Court in repelling the said plea was that the additional payment of tax made on the income of the wife or the minor children would ultimately be home by them in the final accounting between them. Having regard to this consideration and bearing in mind the fact that the mode of taxation authorised by the impugned section, though harsh, was thought to be necessary to prevent evasion of payment of tax, this Court held that the said section was valid. It is in the light of these decisions that we must proceed to consider Mr. Pathak's argument that s. 12(1B) of the Act is ultra wires. (1) [1961] 1 S.C.R. 482. (2) [1962] 2 S.C.R. 983. In dealing with Mr. Pathak's argument in the present case, let us recall the relevant facts. profit within the limits of the Companies Act. It is for this group to determine whether the profits made by the s. 23A. It will be remembered that an advance or loan which falls within the mischief of the 'impugned section is advance or loan made company which does not normally deal in money lending is made with full knowledge of the provisions contained impugned section. The object of keeping accumulated without distributing them obviously is to take the benefit lower rate of super-tax prescribed for companies. This was defeated by s. 23A which provides that in the case distributed profits, tax would be levied on the shareholders on the basis that the accumulated profits will be deemed to have been distributed amongst them. Similarly, s. 12(1B) provides that if a controlled company adopts the device of making a loan or advance to one of its shareholders, such shareholder a. 920 accumulated profits. It is this kind of a well-planned device which s. 12(1B) intends to reach for the purpose of taxation. It appears that such a device is adopted by private companies in many countries. Simon has referred to this device in these words :"Generally speaking, surtax is charged only on individuals, not on companies or other bodies corporate. Various devices have been adopted from time to time to enable the individual to avoid surtax on his real total income or on a portion of it, and one method involved the formation of what is popularly called a 'one man company'. He individual transferred his assets, in exchange for shares, to a limited company, specially registered for the purpose, which thereafter received the income from the assets concerned. The individual's total income for tax purposes was then limited to the amount of the dividends distributed to him as practically the only shareholder, which distribution was in his own control. The balance of the income, which was not so distributed, remained with the company to form, in effect, a fund of savings accumulated from income which had not immediately attracted surtax. Should the individual wish to avail himself of the use of any part of these savings he could effect this by borrowing from the company, any interest payable by him going to swell the savings fund; and at any time the individual could acquire the whole balance of the fund in the character of capital by putting the company into liquidation."(1) What Simon says about one-man company can be equally true about the controlled company whose affairs are controlled by a group of persons closely knit and having the same interest. The question which now arises is, if the impugned section treats the loan received by a shareholder as a dividend paid to him by the company, has the legislature in enacting the section exceeded the limits of the legislative field prescribed by the present Entry 82 in List I. As we have already noticed, the word "income" in the context must receive a wide interpretation; how wide it should be it is unnecessary to consider, because such an enquiry would be hypothetical. The question must be decided (1) Simon's Income-tax, 2nd Ed. Vol. 3, para 592, p. 341. 921 on the facts of each case. There must no doubt be some rational connection between the item taxed and the concept of income liberally construed. If the legislature realises that the private controlled companies generally adopt the device of making advances or giving loans to their shareholders with the object of evading the payment of tax, it can step in to meet this mischief, and in that connection, it has created a fiction by which the amount Ostensibly and nominally advanced to a shareholder as a loan is treated in reality for tax purposes as the payment of dividend to him. We have already explained how a small number of shareholders controlling a private company adopt this device. Having regard to the fact that the legislature was aware of such devices, would it not, be competent to the legislature to device a fiction for treating the ostensible loan as the receipt of dividend? In our opinion, it would be difficult to hold that in making the fiction, the legislature has traveled beyond the legislative field assigned to it by entry 82 in List 1. It is, however, urged by Mr. Pathak that while providing for such a fiction, the legislature should have required the Income-tax Officer to consider in each case whether the loan was genuine, or was the result of a device; and he argues that since no such provision has been made and a uniform presumption by fiction is, sought to be raised, the legislature has gone beyond its legislative competence. In support of this argument, Mr. Pathak has referred to the fact that under s.108(1) of the Commonwealth Income-tax Act it is provided that the amount paid to the shareholder by way of advance or loan can be taxed if in the opinion of the Commissioner it represents distributions of income, Such a provision would have made the impugned section valid, Mr. Pathak argues that omission of Parliament to exclude from the operation of s. 12(lB) genuine loans or advances, and its failure to distinguish between such loans and advances and loans and advances made as a device shows, that it has acted blindly and must, therefore, be held to have exceeded its legislative power. We are not inclined to accept this argument. If the legislature thinks that the advances or loans are in almost every case the result of a device, it would be competent to it to prescribe a fiction and hold that in cases of such advances or loans, tax should be recovered from the shareholder an the basis that he has received the dividend. Therefore, we are satisfied that the High Court was right in coming to the conclusion that the impugned section is not beyond the legislative competence of the legislature. 922 Then it is argued by Mr. Pathak that the impugned provision contravenes the appellant's fundamental rights under Art. 19(1) (f) & (g) and is not saved by clauses (5) & (6) of the said article. It is not easy to appreciate this argument. Art. 19(1) (f) recognises the right of a citizen to acquire, hold and dispose of property and Art. 19(1)(g) recognises the right to practice any profession, or to carry on any occupation, trade or business. The impugned provision does not contravene either of these rights. The shareholder's right to borrow money from his own company cannot be said to be a fundamental right; besides all that the impugned section does is to provide that if a loan is borrowed by a shareholder from a company to which they said provision applies, it will be deemed to be a receipt by him of the dividend. This provision does not affect the appellant's right to borrow money from any other source; and his company from which he borrows does not ordinarily do money-lending business. That is why the restriction imposed by the section cannot be said to be unreasonable at all. In dealing with the question about the reasonableness of this provision, we cannot also overlook the fact that past transactions were excluded from its operation by the issue of a circular to which we have already referred. There is no element of unfairness in the fiction, due tax is evaded. That is the assumption made by the legislature in making this provision. How can it be urged that either the shareholder who is taxed, or the other shareholders who deliberately make the advance to a colleague of theirs, are unfairly dealt with by the impugned provision. In our opinion, there is no scope for arguing that the fundamental rights of the shareholder under Art. 19 (1) (f ) & (g) have been contravened by the impugned provision. Therefore, we must reject Mr. Pathak's argument that the impugned provision is invalid on the ground that it contravenes Art. 19(1)(f) & (g). There is obviously no scope for suggesting that the impugned provision contravenes Art. 14; and in fact Mr. Pathak has not raised this point before us. In that connection, he himself fairly invited our attention to the decision of the Madras High Court in K. M. S. Lakshmana Aiyar v. Additional Income-tax Officer, Special 923 Circle, Madras, (1) where the challenge to the validity of the impugned section on the ground that it contravened Art. 14 has been repelled. The result is, the appeal fails and is dismissed with costs. Raghubar Dayal J. I am of opinion that the appeal should be allowed as ss. 12 (1B) and 2 (6A) (e), of the Indian Income-tax Act, 1922, hereinafter called the Act, as they stood in 1955, are void. The two provisions were enacted by Parliament in view of Entry 82, List 1, Seventh Schedule of the Constitution which reads : "Taxes on income other than agricultural income". It is not disputed that whatever wide connotation the word 'income' in this Entry may have, the item taxed should really be capable of being considered as income, that there be some rational connection between the item taxed and the concept of "income" and that it is not open to Parliament to choose to tax, as income, an item which in no rational sense can be regarded as income. It is also not disputed that Parliament can enact a law dealing with the evasion of payment of income-tax. In Navinchandra Mafatlal v. The Commissioner of Income-tax, Bombay City(1) this Court had to consider the content of the word "income" as used in Entry 54, List 1, Seventh Schedule to the Government of India Act, 1935 (which is identical with Entry 82. List 1, Seventh Schedule to the Constitution), in determining whether the imposition of a tax under the head "capital gains" by the Central Legislature, was ultra vires. Section 12-B inserted in the Income-tax Act by the Indian Income-tax and Excess Profits Tax (Amendment) Act, 1947 (Act XXII of 1947) provided for the imposition of a tax on capital gains arising from certain transactions mentioned in the section. This Court said that "income", according to the dictionary, means "a thing that comes in" and that in the United States of America and Australia, the word "income" was used in a wide sense so as to include "capital gains". It referred to certain cases of those countries in which a very wide meaning was ascribed to the word "income" as its natural meaning and held that "its natural meaning embraces any profit or gain which is actually received". In the United States, the word "income" was first defined in Stratton's Independence v. Howhert(3) decided on December 1, 1913, as "gain derived from capital, from labour, or from both (1) (1960) 40 I.T.R. 469. (2) [1955] 1 S.C.R. 829. (3) 231 U.S. 399-59 L. Ed. 285. 924 combined". The court had to construe the word "income" as used in S. 38 of the Corporation Excise Tax Act of August 5, 1909, which imposed an excise tax "equivalent to one per centum upon the entire net income .... received by it from all sources during the year". In Eisner v. Macomber(1) referred to by this Court in Mafatlal's case(1), the court had to construe the word "income" as used in the XVI Amendment of the Constitution of the United States, which is : "The Congress shall have power to lay and collect taxes on incomes, from whatever source derived, without apportionment among the several States, and without regard to any census or enumeration." and observed, at p. 206: " Congress cannot by any definition it may adopt conclude the matter, since it cannot by legislation alter the Constitution, from which alone it derives its power to legislate, and within whose limitations alone that power can be lawfully exercised. .... we find little to add to the succinct definition adopted in two cases arising under the Corporation Tax Act of August 5, 1909. 'Income may be defined as the gain derived from capital, from labour, or from both combined,' provided it be understood to include profit gained through a sale or conversion of capital assets. to which it was applied in the Doyle case Brief as it is, it indicates the characteristic and distinguishing attribute of income, essential for a correct solution of the present controversy." The definition of "income" given in this case has been followed in the other two cases referred to in Mafatlal's case(2) ViZ., Merchants' Loan & Trust Co. v. Smietanka(3) and United States (1)252 U.S. 189=64 L. Ed. 521. (2) [19551 1 S.C.R. 829. (3) 255 U.S. 509=65 L. Ed. 751. 925 v. Stewart(1), cases which dealt with the taxation of gains from the sale of capital assets. The question in the Australian case viz., Resch v. The Federal Commissioner of Taxation(1) was about the validity of the provinces in the income-tax legislation to the effect that distribution of profits in the course of winding-up of a company would be treated on the same footing as the distribution by the company as a going concern. The provision was held valid as Parliament possessed power to bring to charge in an income-tax Act all profits and gains accruing to a tax-payer, without distinguishing whether the profit or gain should be regarded as a receipt on capital or on income or revenue account. The word "income" has been interpreted in a natural sense in these cases and the definition given in Eisner's case($) is much narrower and limited in content than the widest meaning which is now sought to be given to it by the respondent. In Mafatlal's case (4) too, this Court has not given such a wide meaning to the word "income" as to include "anything which comes in" and therefore to include the amount of a loan which may be said to come in the hands of the borrower. Loans borrowed by a shareholder from the company do not, as such, come within the above general definition of "income". They do not represent gains from his labour or capital or profits gained through sale of capital assets. The borrower has to repay them. If a shareholder is really paid his share of the profits ostensibly as a loan, such a nominal loan but really a share of profits-can be taxed as "income" under an appropriate enactment. We may now consider the nature of what had been taxed in this case and to which objection has been taken on the ground that ss. 2 (6A) (e) and 12 ( 1 B) are invalid. The appellant holds 11 out of 845 shares in a private limited company. The value of each share is Rs. 100. In 1955 he took a loan of over Rs. 4,00,000 from the company. Rs. 2,83,126, the amount of accumulated profits the company had then, have been added to the appellant's total income for the relevant assessment year, in view of ss. 2(6A)(e) and 12(1B) of the Act. He appellant's share in the accumulated profits, if distributed as dividend would be 11/845the of Rs. 2,83,126 i.e., Rs. 3,686. Rs. 2,79,440, the balance, would then be the dividend payable to the other co-sharers. The appellant contends that Rs. 2,79,440 (1) 311 U S 60 = 85 Ed 40 (3) 252 U.S. 189=64 L. Ed. 521. (2) 66 C.L.R. 198. (4) [1955] 1 S.C.R. 829. 926 is not his income and that Parliament was not competent to enact ss. 2 (6A) (e) and 12 ( 1B) which treat it as his "income" from dividend. Before dealing with the contention, reference may be made to what the impugned sections provide. Section 2 (6A) (e) defines "dividend", in the circumstances mentioned in that clause, to include any payment by a company of any sum by way of advance or loan to a shareholder, or any payment by any Such company on behalf of or for the individual benefit of a shareholder to the extent to which the company in either case possesses accumulated profits. Section 12(1B) provides that any such payment to a shareholder made by way of advance or loan in certain circumstances would be treated as dividend received by him in the previous year relevant to the assessment year ending March 31, 1956, if such loan or advance remained outstanding on the first day of such previous year. Now, the contention for the appellant is that though Parliament can enact a law dealing with evasion of payment of income-tax, it cannot tax what is not "income", that the amount in excess of his proportionate share in Rs. 2,83,126, if it had been actually distributed as profits by the company, could not have been his income from dividend, that he could not have evaded payment of income-tax on this amount from its being not distributed as dividend and that therefore Parliament could not enact that such excess amount be treated as dividend paid to him and, consequently, as his "income". The contention has force.". I am therefore of opinion that it is not open to the legislature to describe any payment of money by a company to a shareholder by the word "dividend" and then provide that such payment (called dividend) will come within the expression "income" for the purposes of any law enacted by virtue of Entry 82, List 1, Seventh Schedule to the Constitution. The definition of "dividend" must have rational connection with the concept of "dividend" in the context of the profits of a company and its distribution amongst shareholders at any time after the profits have been earned. Clauses (a) to (d) of S. 2 (6A) may be said to have such a connection. 927 It is conceivable, and not disputed for the appellant, I that attempts are made by persons to evade payment of income-tax and that one mode of such attempts is that companies accumulate profits, do not use them for payment of dividends and later pay the amount to shareholders by way of profits but in the form of advance of moneys or loans to some shareholders who pass on the ratable share of the remaining shareholders and the shareholders thus escape payment of super-tax at a higher rate as their receiving such amounts could not be treated as "dividends" and so could not be added to their "income'. At the same time, it is not disputed for the respondent that there can be genuine cases of loans taken by shareholders from a company when the company was in a position to lend money out of its funds. In fact, after the enactment of s. 2(6A)(e), the Central Board of Revenue issued a Circular directing its officers to intimate to all companies that if loans advanced by them were repaid before June 30, 1955, in a genuine manner, they would not be taken into account in determining the tax liability of the shareholders to whom they had been advanced as it was likely that some companies might have advanced loans to their shareholders as a result of genuine transactions of loans and the idea was not to affect such transactions and not to bring them within the mischief of the new provision. The provisions of s. 2 (6A) (e) take into account all cases of advances or loans made by companies to their shareholders, be they bona fide or be they for the purpose of evading payment of super tax, and make the borrower liable for the tax on even such amount of the loan as be in excess of his proportionate share in the accumulated profits up to the amount of the loan. Reference may be made to the fact that in other countries too, notice has been taken of attempts to evade payment of income-tax by similar devices, and that enactments to defeat the devices have been made by the legislatures of those countries. We have been referred to s. 108 of the Income Tax and Social Services Contribution Assessment Act 1936-53 (of the Commonwealth of Australia) which deals with loans to shareholders. Its provisions materially differ in one respect from those of the impugned sections. Only so much of the advances or loans are deemed to be dividends paid by the company as in the opinion of the Commissioner represents distributions of income. The entire amount of advance of loan is not treated as dividend received by the borrower shareholder. Imposition of a tax is a restriction on the, right of an assessee 928 to hold property and a particular tax can be justified only as a reasonable restriction on the exercise of that right in the interests of the general public. The shareholder who takes a loan or advance from a company which possesses accumulated profits is, under the impugned provisions, treated to have received the amount of the loan or advance to the extent of the accumulated profits, as dividend. As already stated, the amount of profits set apart for dividends is to be proportionately distributed among the various shareholders. If any enactment provides that certain profits of the company, though not distributed as dividend, be treated as used for the payment of dividends, it should necessarily follow that a particular shareholder be deemed to have received a proportionate amout of such profits as dividend. It would be unreasonable to provide that a particular shareholder should be deemed to have received an amount in excess of his proportionate share as dividend. The other shareholders should, in the circumstances, be deemed to have received their proportionate shares of the profits deemed to have been distributed as dividends. A reasonable law may provide for their assessment as wan on the amount of dividends deemed to have been distributed to them. It appears to me unreasonable that a particular shareholder who receives a loan or advance from a company be deemed to have received that entire amount as dividend when his proportionate share be much less. I would, for this reason also, consider the provisions of the impugned sections to amount to imposing unreasonable restrictions on the fundamental right to hold property under Art. 19(1)(f). I would now refer to certain cases on which reliance is placed for the proposition that this Court has held valid laws made to cover attempts for evasion of income-tax and that therefore the impugned provisions enacted with the same object to cover attempts to evade payment of super-tax should be held valid. These case are : Mafatlal's case(1), already referred to; Sardar Baldev Singh v. Commissioner of Income-tax, Delhi & Ajmer (2) ; and Balaji v. Income-tax Officer, Special Investigation Circle(a). Mafatlal's case(1) dealt with the validity of the tax on capital gains under S. 12B of the Act. In that case what was taxed was what had been gained by the assessee as a result of some dealing in capital assets. The capital gain was to be computed after making certain deductions including the actual cost to the assessee of (1)[1955] 1 S.C.R. 829. (3) [1962] 2 S.C.R. 983. 929 The capital assets, and did not represent the entire amount that came in as a result of the transaction. This case is therefore an authority for the simple proposition that the word "income" in Entry 82, List 1, Seventh Schedule 'to the Constitution, has wide connotation and is not to be restricted to have the same content as judicial decisions had given to that word as used in the Act. "Income", in the Act, has been construed in the context of the scheme of the Act and has been considered to mean generally what one earns mostly in a recurring form from some existing sources. The profits that one earns from the transfer of a capital asset could be rationally considered, as held by this Court, to be income, as it represented the amount in excess of what the transferor-assessee had spent in acquiring that asset. Baldev Singh's case(1) was concerned about the validity of the provisions of s. 23A of the Act which authorised the Income-tax Officer to order in writing that the undistributed portion of the ostensible income of a company calculated as profit therein shall be deemed to have been distributed as dividends amongst the shareholders as at the date of the general meeting aforesaid and that thereupon the proportionate share thereof of each shareholder shall be included in the total income of such shareholder for the purpose of assessing his total income. The Income-tax Officer was to make such an order only when he was satisfied that the profits and gains distributed as dividends by any company up to the end of the sixth month after its accounts for the previous year are laid before the company in general meeting, were less than 60% of the assessable income of the company and that payment of a larger dividend would not be unreasonable keeping in view the losses incurred by the company in the earlier years and of the smallness of the profits made. It will be noticed that the order of the Income-tax Officer could not be to the effect that the undistributed profits would be deemed to be the dividend paid to any particular shareholder or shareholders but could be to the effect that they were distributed as dividends amongst all the shareholders. The validity of this provision was not questioned in the case. What was questioned in the case was that the proportionate share of Baldev Singh, assessee, in such undistributed profits, could not be added to his total income of the particular year to which it was added. It was held that in view of the deeming provision with respect to the distribution of profits as dividends amongst shareholders, the proportionate share of the dividends would be deemed to be (1) [1961]1 S.C.R. 482. 930 income of the assessee and that therefore, when it was not taxed, would be deemed to have escaped assessment for the purposes of s. 34 of the Act. The case is distinguishable on several grounds. One is that the Income-tax Officer is to make the order when he is satisfied that a larger dividend could have been justifiably distributed, a view necessarily leading to the inference that a lower dividend was distributed in order to escape payment of super tax by shareholders liable to pay such tax. The other is that the Income-tax Officer was given power to make the order only when profits less than 60% of the assessable income were distributed as dividend. This indicates that the company could accumulate profits up to 40% of the assessable income for reasons which would be deemed to be genuine. This should lead to the inference that the accumulation of profits with respect to which no action has been taken under s. 23A was justified and that therefore if in case a company could spare the money to advance to a shareholder for his needs, that alone should not lead to the inference that the advance was made to evade the payment of super-tax by the shareholder. The third point of distinction, and of significance, is that no individual shareholder is made liable for tax on an amount of the undistributed profits in excess of his proportionate share in those profits. The shareholder is not thereby prejudiced. His income is increased by an amount which he could have legitimately got from the company if the persons in control had acted reasonably and had retained such profits undistributed as were necessary for the purposes of the company. Another objection taken in Baldev Singh's case(1) was about the constitutionality of s. 23A on the ground that it purports to tax the shareholders on the income of the company in which they held shares, especially when it does not give a right to the shareholders to realise from the company the dividend which by the order is deemed to have been paid to them. The section was held to be constitutionally valid as it was enacted for preventing evasion of tax in view of the conditions of its applicability. In the circumstances of the cases covered by S. 23A, there was a reasonable connection between the amount deemed to be distributed as dividend and the possible attempt for evading payment of super tax. The assessee could not have been prejudiced if the persons in control of the management of the company had acted reasonably or actually distributed that amount as profits subsequent to the order of the Income-tax-Officer. (1) [1961] 1 S.C.R. 482. 931 In Balaji's case(1), the validity of s. 16(3) (a), clauses (i) and (ii), came up for consideration. These clauses provide that in computing the total income of any individual for the purpose of assessment there shall be included so much of the income of his wife or minor child as arises directly or indirectly from the membership of the wife in a firm of which her husband is a partner or from the admission of the minor to the benefits of partnership in a firm of which such individual is partner. These provisions were held valid. The Court left open the question whether A could be taxed on the income of B and formulated the question for decision as whether s. 16(3) (a), clauses (i) and (ii), is a provision made by the Legislature to prevent evasion of tax and answered it in the affirmative, as the husband or the father could nominally take his wife or minor child, in partnership with him, so that the tax burden may be lightened and as this device enabled the assessee to secure the entire income of the business and yet evade income-tax which he would otherwise have been liable to pay. It was said at p. 999: "The scope of the provisions is limited only to a few of the intimate members of a family who ordinarily are under the protection of the assessee and are defendants of him. The persona selected by the provisions, namely, wife and minor children, cannot also be ordinarily expected to carry on their business independently with their own funds when the husband or the father is alive and when they are under his protection." It is therefore clear that the basis for holding s. 16(3) (a), clauses (i) and (ii), valid was that in effect the husband or the father was the real person who ran the firm and that the others were made partners nominally and therefore the partnership was not genuine. In this view, there could be no question of the provisions affecting the husband or the father prejudicially or including in his income amounts which were not his income. This, however, cannot be said in the present case or in cases which come within the purview of the impugned sections. In dealing with the contention that the provisions of s. 16 (3) (a), clauses (i) and (ii), contravened Art. 14 of the Constitution, it was said at p. 991 : "We have held that the object of the legislation was to prevent evasion of tax. A similar device would not ordinarily be resorted to by individuals by entering (1) [1962) 2 S.C.R. 983. Supp. 1/65932." Such a risk is always involved in a company making payments as advances or loans to a shareholder when it possesses accumulated profits as the other shareholders run the risk of not getting their proportionate share of profits which they would have got if they had been really distributed as dividends. This consideration, again, points to the conclusion that the probability of such an advance or loan being genuine would be dependent not so much on the existence of accumulated profits but on the number of shareholders in the company and the proportion of the number of shares the borrower has to the total number of shares held by the shareholders of the company. The lesser the proportion, the greater is the chance of the advance or loan being genuine, as there would in that case be greater risk of the other shareholders losing their share in the profits deemed to be distributed as dividends. I am therefore of opinion that the impugned sections viz., ss. 2(6A) (e) and 12(1B) of the Act are void and that this appeal should be allowed. Appeal allowed. Back
http://www.advocatekhoj.com/library/judgments/index.php?go=1964/october/32.php
CC-MAIN-2018-51
refinedweb
9,643
57.2
I got the JSON dump of recipes in pretty good shape last night simply by mucking with the various options that ActiveRecord's to_jsonmethod recognizes ( :include, :except, and :methods). That accounts for most of a recipe's infomation, but not the photos. So how to deal with photos? Continue to use a CouchDB-tailored attachment_fu (or switch to a CouchDB tailored paperclip)? Fortunately, the answer is a little more direct than that—CouchDB itself supports attachments. My preference would be to use the nicer REST API that CouchDB provides for "Standalone Attachments" (see the CouchDB HTTP Document API, toward the bottom for more details). That is a recent addition, not available in the stock 0.8 that is packaged in Ubuntu's universe. Rather than shaving that yak, I will stick with "Inline" CouchDB attachments for now. The thing about inline attachments in CouchDB is that they need to be Base64 encoded (and stripped of newline characters). So we need to grab the images from the file system (via attachment_fu that the old code uses), Base64 encode it, and put it into CouchDB. For CouchDB to recognize them, they need to be added in the record's _attachmentskey. To grab it from the file system: jpeg = File.open(recipe.image.full_filename).readBase64 encoding (and removing newlines) is easy enough: require 'base64'To get this into the JSON data structure (and thus into CouchDB), define an Base64.encode64(jpeg).gsub(/\n/, '') _attachementsmethod in the Recipeclass: class RecipeNext update the def _attachments { self.image.filename => { :data => Base64.encode64(File.open(self.image.full_filename).read).gsub(/\n/, ''), :content_type => "image/jpeg" } } end end to_jsonmethod to include the _attachmentsmethod in the :methodsoption: json = recipe.to_json(Lastly, put this into the DB with a simple RestClient put: :methods => [:tag_names, :_id, :_attachments], :include => { :preparations => { :include => { :ingredient => { :except => :id } }, :except => [:ingredient_id, :recipe_id, :id] }, :tools => { :except => [:id, :label] } }, :except => [:id, :label]) RestClient.put "{recipe._id}", json,Viewing the record in futon, we see that it does have a JPEG image attachment: :content_type => 'application/json' Clicking the attachment returns the original image: At this point, we have a nice mechanism for transporting the data from the old relational DB into CouchDB. It needs to be expanded to run through all recipes (and maybe to add some error handling). Also, we still have to get this working for meal documents. The spike, and that is what this has been—a spike to understand how to transfer data from the legacy Rails application into CouchDB—is complete.
https://japhr.blogspot.com/2009/03/complete-recipe-upload-to-couchdb.html
CC-MAIN-2018-05
refinedweb
415
54.02
What Is the Total Return of a Bond Investment? Ultimately you can’t know the exact total return of any bond investment until after the investment period has come and gone, even though bonds are called fixed-income investments, and even though bond returns are easier to predict than stock returns. That’s true for bond funds, and it’s also true for most individual bonds (although many die-hard investors in individual bonds refuse to admit it). Total return is the entire pot of money you wind up with after the investment period has come and gone. In the case of bonds or bond funds, that amount involves not only your original principal and your interest, but also any changes in the value of your original principal. Ignoring for the moment the risk of default (and potentially losing all your principal), here are other ways in which your principal can shrink or grow. Figure in capital gains and losses. If the market price has appreciated (the bond sells at a premium), you can count your capital gains as part of your total return. If the market price has fallen (the bond sells at a discount), the capital losses offset any interest you’ve made on the bond. Factor in reinvestment rates of return — is probably the most important of the three! That’s because of the amazing power of compound interest. The only kind of bond where the reinvestment rate is not a factor is a bond where your only interest payment comes at the very end when the bond matures. These kinds of bonds are called zero-coupon bonds. In the case of zero-coupon bonds, no compounding occurs. The coupon rate of the bond is your actual rate of return, not accounting for inflation or taxes. Example: Suppose you buy a 30-year, $1,000 bond that pays 6 percent on a semiannual basis. If you spend the $30 you collect twice a year, you get $1,000 back for your bond at the end of 30 years, and your total annual rate of return (ignoring taxes and inflation) is 6 percent simple interest. But now suppose that on each and every day that you collect those $30 checks, you immediately reinvest them at the same coupon rate. Over the course of 30 years, that pile of reinvested money grows at an annual rate of 6 percent compounded. In this scenario, at the end of six months, your investment is worth $1,030. At the end of one year, your investment is worth $1,060.90. (The extra 90 cents represents a half year’s interest on the $30.) The following six months, you earn 6 percent on the new amount, and so on, for 30 more years. Instead of winding up with $1,000 after 30 years, as you would if you spent the semiannual bond payments, you instead wind up with $5,891.60 — almost six times as much! Allow for inflation adjustments Of course, that $5,891.60 due to 6 percent compound interest probably won’t be worth $5,891.60 in 30 years. Your truest total rate of return needs to account for inflation. If inflation — the rise in the general level of prices — were 3 percent a year for the next 30 years (roughly what it has been in the past decade), your $5,891.60 will be worth only $2,366.24 in today’s dollars — a real compound return of 2.91 percent. To account for inflation when determining the real rate of return on an investment, you can simply take the nominal rate of return (6 percent in our example) and subtract the annual rate of inflation (3 percent in our example). That gives you a very rough estimate of your total real return. But if you want a more exact figure, here’s the formula to use: 1 + nominal rate of return / 1 + inflation rate – 1 x 100 = Real rate of return Assuming a 6 percent nominal rate of return and 3 percent inflation: 1.06 / 1.03 – 1 x 100 = 2.91 Why the more complicated calculation? You can’t just subtract 3 from 6 because inflation is eating away at both your principal and your gains throughout the year. Weigh pre-tax versus post-tax Of course, taxes almost always eat into your bond returns. Here are two exceptions: Tax-free municipal bonds where you experience neither a capital gain nor a capital loss, nor is the bondholder subject to any alternative minimum tax. Bonds held in a tax-advantaged account, such as a Roth IRA or a 529 college savings plan..)
http://www.dummies.com/how-to/content/what-is-the-total-return-of-a-bond-investment.html
CC-MAIN-2014-35
refinedweb
777
70.13
Archives Merging Images in Websites and WebApps Sometimes a very different request comes from customers to developers. That happened to me a couple of weeks ago with a client to whom we developed an ecommerce website. We’ve been having requests to change things here and there, update the shopping cart, add functionality to the store, and so forth. However, this request took me by surprise. The website uses a cloud service to merge images as customers select different options, but now, our client wanted to generate his own composite images and avoid the cloud service fee. Yes, that was it… It’s no surprise that business are trying to reduce costs. But I never expected to have this kind of request, as the cloud service we are using is very powerful and flexible, although expensive. Anyway, I’ve never worked with images before, I mean, like doing this kind of work which is somehow more complex than just handling images. Well, to my surprise, there is a lot of functionality in the .NET Framework that helped me achieve this goal very easily. So I decided to write this post based on Marcelo Lujan’s article in CodeProject.com. So, what’s the idea? I’m going to build a mechanism in which I have two images (jpegs for example) and a third one will be the merge of those two; that’s the result. First, let’s start by creating a new website (a web application will do too). In an effort to create something simple, and focus on the merge of images instead of the website functionality (because this procedure can be easily ported to a windows forms application) the images will be already in the website and will be named back.jpg and front.jpg. So, our website should look something like this: Now, our Default.aspx page will only have the two images, a button (that will trigger the merge procedure) and an image object to show the newly created image. So, now, let’s go to the code behind and create the procedure in the OnClick event of the button. To start, we have to add a couple of namespaces to the page, they are:using System.Drawing; using System.Drawing.Imaging; {(backImage, 0, 0); gp.DrawImageUnscaled(frontImage, 0, 0); gp.Save(); mImg.Save(Server.MapPath("~/images/merge.jpg")); mergedImaged.ImageUrl = Page.ResolveUrl("~/images/merge.jpg"); } Here I create 3 image objects and one Graphic. Here, I need to create twice the back image because one is for the back and front images, and the third is for the initialization of the graphic.var backImage = Image.FromFile(Server.MapPath("~/images/back.jpg")); var frontImage = Image.FromFile(Server.MapPath("~/images/front.jpg")); var mImg = Image.FromFile(Server.MapPath("~/images/back.jpg")); Next, after initializing the graphic object, I draw the back (this is first) and front images onto the graphic and save the changes (this happens in memory as the graphic is only in memory).var gp = Graphics.FromImage(mImg); gp.DrawImageUnscaled(backImage, 0, 0); gp.DrawImageUnscaled(frontImage, 0, 0); gp.Save(); Then, the final step is to actually save the image to the system. We use the Save method and I save the image with the name merge.jpg and assign it to the third image in the page to show the result:mImg.Save(Server.MapPath("~/images/merge.jpg")); mergedImaged.ImageUrl = Page.ResolveUrl("~/images/merge.jpg"); We should have a result like this: But we can do better. You see, the problem with this approach is that you actually interact with the file system; therefore, the problem is, first, with permissions and second with hard disk space. Why? You might be wondering, well, let’s consider a scenario where the website is in a shared hosting environment and you can’t assign write permissions to the images folder (this should not happen but…) but after several mergers you can run out of space. Now, we can do better by not saving the image to the system, but to memory and render the image on the fly. Ring a bell? Well, let’s modify a bit the app by adding a second webform and name it ShowImage.aspx. Now, let’s move the merge code from the default.aspx.cs code behind file to the newly created page in the Page_Load event like this:protected void Page_Load(object sender, EventArgs e) {(baseImage, 0, 0); gp.DrawImageUnscaled(mergeImage, 0, 0); gp.Save(); var ms = new MemoryStream(); mImg.Save(ms, ImageFormat.Jpeg); Response.ContentType = "Image/JPEG"; Response.BinaryWrite(ms.ToArray()); } The main difference happens in the last 3 lines. Instead of saving the image to the file system, we use a MemoryStream object and write that to the response buffer. Actually the ShowImage.aspx page doesn’t have anything but only this code in the code behind file. So, how do we make it work? Let’s change the OnClick event for the button in default.aspx like this: protected void btnMerge_Click(object sender, EventArgs e) { mergedImaged.ImageUrl = "ShowImage.aspx"; } After running the page and clicking the image we see the result, and it’s much faster than the previous approach because everything happens in memory, and the properties of the merged image looks like this: There you have it. I’ve included the source code of the sample in C# and VB.NET. Please comment on this, as I'm no expert in this field I would love to hear from you and enrich this sample app. Enjoy, Book Review: LINQ In Action Hi all. I've been reading this book from Manning Publications. It's very well recommended by several, well respected, persons, including Scott Guthrie. About the book At first, I was a bit intrigued by the publicity, but the book is worth it. I'm very impressed how very complex ideas are explained in a very simple way. The book is so cleverly designed that I felt like taking a walk in the park with my mom and dad teaching me everything around. The other thing that really impressed me is that the authors put everything into perspective, not just making the book a means to get LINQ to everybody, but also showing the drawbaks of abusing of the use of LINQ. They show metrics in using LINQ to Objects vrs. Memory Structures and warns about all of that. This is the first book that actually put performance above even the topic is about. Very very happy I was able to read it. See you later, Curso Online de .NET Framework
http://weblogs.asp.net/joseguay/archive/2008/10
CC-MAIN-2014-35
refinedweb
1,098
65.12
now I wanted to call this function from assembly, but that doesn't really work out. I can compile the cpp en asm files into object code, but when I link them, it keeps saying 'error, undefined reference to _main' the assembly code looks like this: ;loader.asm [BITS 32] ;protected mode global start extern _main ;this is our C++ code start: call _main ;call the int main(void) code in C++ source cli ;clear interrupts hlt ;halt the CPU the kernel cpp file looks like this: #include "video.h" int main(void) { video vid; //local variable vid.Write("hello world!"); } and since I'm using a linker file, I'll give that one as well: OUTPUT_FORMAT("binary") ENTRY(start) SECTIONS { .text 0x100000 : { code = .;_code = .;__code = .; *(.text) . = ALIGN(4096); } .data : { data = .;_data = .;__data = .; *(.data) . = ALIGN(4096); } .bss : { bss = .;_bss = .;__bss = .; *(.bss) . = ALIGN(4096); } end = .;_end = .; __end = .; } I would really like to know why I can't call '_main'
http://www.dreamincode.net/forums/topic/303863-trouble-calling-c-functions/page__pid__1770149__st__0
CC-MAIN-2016-07
refinedweb
158
67.69
Networking Server For this project, you will create a detailed, organized, and unified technical solution given a scenario described in the document linked below. ITS430_PortfolioProjectScenario.pdf individually for each section. The Windows Server 2012 operating system should be used for all aspects of the solution. The topics to be covered are: 1.Deployment and Server Editions o How many servers total are needed? Which roles will be combined? o What edition of Windows Server will be used for each server (e.g., Standard, Data)? o Will Server Core be used on any servers? o Where is each of the servers located (which of the two sites)? o How will the servers be deployed? 2.DNS o DNS namespace design (e.g.,domain name[s] chosen, split DNS for Internet/intranet, zones)? o How will DNS be handled for the second site? 3.Active Directory o Number of AD domains and names of domains? o Will there be any Read-Only Domain Controllers? o How will the second site factor into domain controller placement? How will AD sites be configured? 4.File and Printer Sharing o What shares might be needed? (Consider some of the reasoning supplied in the relevant chapter of the textbook.) o How will quotas/FSRM be configured? (Consider all aspects, such as thresholds, altering, file screens, and reporting.) o Will a DFS namespace be implemented? 5.Remote Services o How will the remote services be configured? o Who will have access? o How are the remote services going to be secure? Conclusions Include at least two diagrams illustrating the student’s chosen Active Directory design with DNS namespace hierarchy. The submission will be 8-10 pages in length (not counting diagrams). Cite and discuss no fewer than 5 credible sources, written
https://www.studypool.com/discuss/31775/networking-server-3
CC-MAIN-2016-44
refinedweb
294
61.33
Nmap Development mailing list archives On Wed, Jun 22, 2011 at 04:58:43PM -0500, Colin L. Rice wrote: Hello, At the request of David I rewrote broker to allow clients using IPV4 and IPV6 to communicate with each other using the default broker as well as rewriting the whole dual listening system to make a little more sense and be more maintainable. However due to a weird feature of Linux where :: binds to 0.0.0.0 as well we added a change where all IPV6 sockets now specify IPV6_V6ONLY so on Linux networking stacks you can have a dual listening mode without collisions. This means however that ncat -l -6 :: will not accept IPV4 connections in their IPV6 address format on Linux. This isn't a feature of Linux only, it's part of the design of IPv6 sockets. See sections 3.7 "Compatibility with IPv4 Nodes" and 5.3 "IPV6_V6ONLY option for AF_INET6 Sockets" of RFC 3493. Some operating systems disable the "compatibility" part by default for technical or security reasons. The patch is attached. Does anyone have any feedback? Would you prefer that IPV6_V6ONLY only be set for ncat -l or ncat --broker and it be turned off -6 is passed? I think that -6 mode should not accept any IPv4 connections, not even from IPv4-mapped addresses like ::ffff:127.0.0.1. If I run "ncat -6 -l 80" I expect to also be able to run a separate IPv4 web server. I think we should turn on IPV6_V6ONLY for all IPv6 sockets. Index: ncat_listen.c =================================================================== --- ncat_listen.c (revision 24247) +++ ncat_listen.c (working copy) /* setup the main listening socket */ - listen_socket = do_listen(SOCK_STREAM, proto, &srcaddr); + listen_socket = do_listen(SOCK_STREAM, proto, &srcaddr[0]); I think that wherever you refer to srcaddr[0], you need to refer to srcaddr[1] equally. They should not be separated in the code. The best way is to loop over num_srcaddrs. listen_socket should be an array of the same size as srcaddr, not separate variables listen_socket and listen_socket6. @@ -545,7 +535,7 @@ while (1) { /* create the UDP listen socket */ - sockfd = do_listen(SOCK_DGRAM, proto, &srcaddr); + sockfd = do_listen(SOCK_DGRAM, proto, &srcaddr[0]); This looks broken to me. The UDP mode only refers to srcaddr[0]. Index: ncat_main.c =================================================================== --- ncat_main.c (revision 24247) +++ ncat_main.c (working copy) @@ -533,6 +533,7 @@ if (o.verbose) print_banner(); + if(o.debug) nbase_set_log(loguser, logdebug); else @@ -541,7 +542,7 @@ /* Will be AF_INET or AF_INET6 when valid */ memset(&targetss.storage, 0, sizeof(targetss.storage)); targetss.storage.ss_family = AF_UNSPEC; - httpconnect.storage = socksconnect.storage = srcaddr.storage = targetss.storage; + httpconnect.storage = socksconnect.storage = srcaddr[0].storage = srcaddr[1].storage = targetss.storage; I would prefer that you handle these things in a loop, instead of hardcoding 0 and 1. if (proxyaddr) { if (!o.proxytype) @@ -582,7 +583,7 @@ if (o.listen) bye("-l and -s are incompatible. Specify the address and port to bind to like you would a host to connect to."); - if (!resolve(source, 0, &srcaddr.storage, &srcaddrlen, o.af)) + if (!resolve(source, 0, &srcaddr[0].storage, &srcaddrlen[0], o.af)) bye("Could not resolve source address %s.", source); } @@ -592,18 +593,18 @@ compatibility. */ o.portno = srcport; } else { - if (srcaddr.storage.ss_family == AF_UNSPEC) - srcaddr.storage.ss_family = o.af; + if (srcaddr[0].storage.ss_family == AF_UNSPEC) + srcaddr[0].storage.ss_family = o.af; if (o.af == AF_INET) { - srcaddr.in.sin_port = htons((unsigned short) srcport); - if (!srcaddrlen) - srcaddrlen = sizeof(srcaddr.in); + srcaddr[0].in.sin_port = htons((unsigned short) srcport); + if (!srcaddrlen[0]) + srcaddrlen[0] = sizeof(srcaddr[0].in); } #ifdef HAVE_IPV6 else { - srcaddr.in6.sin6_port = htons((unsigned short) srcport); - if (!srcaddrlen) - srcaddrlen = sizeof(srcaddr.in6); + srcaddr[0].in6.sin6_port = htons((unsigned short) srcport); + if (!srcaddrlen[0]) + srcaddrlen[0] = sizeof(srcaddr[0].in6); } #endif } @@ -626,6 +627,7 @@ if (!resolve(o.target, 0, &targetss.storage, &targetsslen, o.af)) bye("Could not resolve hostname %s.", o.target); optind++; + o.inetset=1; I think you can make this code a lot clearer. Instead of overloading the meaning of the global srcaddr array (used for both option processing and as data passed to ncat_listen), use a temporary variable for option processing only. Then after the option loop, it can be very clear: num_srcaddrs = 0; if (tmp_addr.storage.ss_family == AF_UNSPEC) { if (o.af == AF_INET || o.af == AF_UNSPEC) srcaddr[num_srcaddrs++] = 0.0.0.0; if (o.af == AF_INET6 || o.af == AF_UNSPEC) srcaddr[num_srcaddrs++] = ::; } else { srcaddr[num_srcaddrs++] = tmp_addr; } I think that better shows your intention of setting up two listening addresses when no address and neither -4 nor -6 is given. This means that you will have to change the default value of o.af in listen mode; I think that's cleaner than the o.inetset variable. This also can clear up a lot of confusion when someone is reading the option processing loop while thinking about connect mode: "Why are they using an array when you can only connect to one address?" Index: ncat_core.c =================================================================== --- ncat_core.c (revision 24247) +++ ncat_core.c (working copy) @@ -107,8 +107,8 @@ #include <time.h> #include <assert.h> -union sockaddr_u srcaddr; -size_t srcaddrlen; +union sockaddr_u srcaddr[2]; +size_t srcaddrlen[2]; Do we need srcaddrlen? Could we get rid of it? This declaration needs a comment saying why the array has size 2: we set up at most 2 listening sockets, one for IPv4 and one for IPv6. David Fifield _______________________________________________ Sent through the nmap-dev mailing list Archived at By Date By Thread
http://seclists.org/nmap-dev/2011/q2/1215
CC-MAIN-2014-42
refinedweb
897
53.37
The. There are two stable isotopes of lithium, $\mathrm{^6Li}$ (7.59 % abundance) and $\mathrm{^7Li}$ (92.41 %). Both absorb neutrons to produce tritium: Unfortunately, only the reaction with the less-abundant isotope has a significant cross section for thermal neutrons, and even then a neutron multiplier is required because of unavoidable neutron losses and incomplete geometric coverage of the blanket (endothermic nuclear reactions involving $\mathrm{^9Be}$ or $\mathrm{Pb}$ have been suggested). Enrichment of lithium is currently a messy and expensive activity involving large quantities of mercury: a viable method will need to be developed before a nuclear fusion reactor can become a reality. The following code uses the ENDF data files Li-6(n,T)He-4.endf and Li-7(n,n+T)He-4.endf to plot the cross sections for the above reactions. import numpy as np from matplotlib import rc import matplotlib.pyplot as plt rc('font', **{'family': 'serif', 'serif': ['Computer Modern'], 'size': 14}) rc('text', usetex=True) def read_xsec(filename): """Read in the energy grid and cross section from filename.""" E, xs = np.genfromtxt(filename, comments='#', unpack=True, usecols=(0,1)) return E, xs # Read in the data files: # 6Li + n -> T + 4He + 4.8 MeV E_Li6, Li6_xs = read_xsec('Li-6(n,T)He-4.endf') # 7Li + n -> T + 4HE + n' - 2.466 MeV E_Li7, Li7_xs = read_xsec('Li-7(n,n+T)He-4.endf') fig, ax = plt.subplots() ax.loglog(E_Li6, Li6_xs, lw=2, label='$\mathrm{^6Li-n}$') ax.loglog(E_Li7, Li7_xs, lw=2, label='$\mathrm{^7Li-n}$') # Prettify, set the axis limits and labels ax.grid(True, which='both', ls='-') ax.set_xlim(10, 1.e8) ax.set_xlabel('E /eV') ax.set_ylim(0.001, 100) ax.set_ylabel('$\sigma\;/\mathrm{barn}$') ax.legend() plt.savefig('lithium-xsecs.png') plt.show() Comments are pre-moderated. Please be patient and your comment will appear soon. There are currently no comments New Comment
https://scipython.com/blog/breeding-tritium-for-a-fusion-reactor/
CC-MAIN-2020-29
refinedweb
317
52.66
This is probably an old and known problem: If you compile a class that also exists in libgcj into an executable, you'll get an error like this when running the executable: libgcj failure: Duplicate class registration: org.w3c.dom.Attr Aborted Note that the same problem does not occur when running the class with gij. This (probably) means that if you compile your program with a version of libgcj which doesn't contain class Y, it is not possible to run this program with a newer version of libgcj which does contain class Y. (Granted class Y is compiled into the program in the first place.) Release: 3.1 From: Bryce McKinlay <bryce@waitaki.otago.ac.nz> To: gcc-gnats@gcc.gnu.org Cc: Subject: Re: libgcj/6819: duplicate class registration bug Date: Mon, 27 May 2002 16:03:41 +1200 Yes, this is a well known issue. The problem is that if we have duplicated symbols (ie the same symbol representing both old and new versions of a class), it is quite non-deterministic (or at least non-portable) which of them will actually be found and used at runtime by the linker. This should be fixable in conjunction with implementing a weaker linking model - this is also needed for strict adherance to Java's binary compatibility spec, and would allow us to do cool things like link compiled classes against interpreted class files, etc. Bryce. Hello, A good many things have changed since gcc 3.1. Can you confirm whether this bug is still current with gcc 3.3? Thanks, Dara See Dara's question. But I think this is still a problem, Can you provide a self contained example of this, I think I know how to repoduce this but It would be nice for other people. It seems this bug is fixed in 3.3. echo >Demo.java 'class Demo { public static void main(String[] args) { File f = new File(); } }' mkdir java java/io echo >java/io/File.java 'public class File { public File() { System.out.println("hello"); } }' gcj-3.3 -o Demo java/io/File.java Demo.java --main=Demo ./Demo That should print 'hello', which it does with 3.3. I haven't tested 3.1 or earlier with this example though. I'm sorry, this bug still exists. I forgot to include 'package java.io;' in the File.java source file in the test above. When you do, you will still get this error at runtime: libgcj failure: Duplicate class registration: java.io.File Aborted Thanks for the confirmation. Sorry that this one still isn't fixed :-( This problem will be fixed by the binary compatibility ABI. I've marked the dependency on the BC-ABI tracking bug. Closing as won't fix as libgcj (and the java front-end) has been removed from the trunk.
https://gcc.gnu.org/bugzilla/show_bug.cgi?id=6819
CC-MAIN-2019-26
refinedweb
474
65.22
18.1. socket — Low-level networking interface¶. 18.1.1.object with an initial null byte; note that sockets in this namespace can communicate with normal file system sockets, so programs intended to run on Linux may need to deal with both types of address. A string or bytesobject. Certain other address families ( AF_PACKET, AF_CAN)(). 18.1.2. Module contents¶ The module socket exports the following elements. 18.1.2.1.”. 18.1.2... 18.1.2.3. Functions¶ 18.1.2.3.1.or CAN_BCM. If fileno is specified, the other arguments are ignored, causing the socket with the specified file descriptor to return.. The newly created sockets are non-inheritable. Changed in version 3.2: The returned socket objects now support the whole socket API, rather than a subset. Changed in version 3.4: The returned sockets are now non-inheritable.. 18.1.2.3.2. Other functions¶ The socket module also offers various network-related services:. 18.1.3.. socket. listen(backlog)¶ Listen for connections made to the socket. The backlog argument specifies the maximum number of queued connections and should be at least 0; the maximum value is system-dependent (usually 5), the minimum value is forced to 0..).. 18.1.4.. 18.1.4.1.. 18.1.4.2.. 18.1.5..
https://docs.python.org/3.4/library/socket.html
CC-MAIN-2018-47
refinedweb
217
50.43
parse_version post-release tags do not work as expected According to: from pkg_resources import parse_version parse_version('2.1-rc2') < parse_version('2.1') False but both setuptools 0.6c11 and 0.6c12dev_r88795 show that: In [7]: parse_version('2.1-rc2') < parse_version('2.1') Out[7]: True So pkg_resources acts the opposite of what the documentation says. Yeah this is a bug in the code, as the documentation insists '-' is the marker for post releases I just tried this with distribute 0.6.14: So this works for me. Tried this on 0.6.15 and 0.6.16 and it also works as expected. So sorry, I cannot reproduce the issue. Hanno, According to the documentation, '-' is a marker for post releases. so "2.1.-rc1" should be newer to "2.1", so actually it doesn't work in all the versions you tried. unit tests for parse_version, the current version failed 5 out of 14 tests this patch passes all the tests This issue has re-emerged as it now deviates from setuptools behavior. See the analysis at #278. Duplicate of #278 Duplicate of #278.
https://bitbucket.org/tarek/distribute/issues/208
CC-MAIN-2017-13
refinedweb
185
70.39
hi there guys got a question right here, what can be the problem with this? I mean I was calling the Form1 which I have designed as a login form so whenever you click the login button the Form1 is supposed to show up, but then I get an error I do not entirely understand. anyone who can interpret this to me please... thank you! Recommended Answers Answered by lxXTaCoXxl 26 in a post from The problem seems to be that you're not initializing the Form; either that or Form1 is in another namespace by accident (highly unlikely but can happen). To resolve this try: Form1 f1 = new Form1(); f1.Show();Hope it helps,Jamie All 3 Replies lxXTaCoXxl 26 Posting Whiz in Training Be a part of the DaniWeb community We're a friendly, industry-focused community of 1.21 million developers, IT pros, digital marketers, and technology enthusiasts learning and sharing knowledge.
https://www.daniweb.com/programming/software-development/threads/424893/clicking-a-button-to-show-another-form
CC-MAIN-2021-25
refinedweb
155
58.52
I recently had two pair assignments for class, each of which had to be with a different classmate. With the object of programming for Java, we utilized Eclipse as our IDE The Top 3 Browser-Based IDE's To Code In The Cloud The Top 3 Browser-Based IDE's To Code In The Cloud simply because that was what we were taught to use. I tried learning... keyboard shortcuts, but I have not been using it daily so I was fine with using Eclipse, which seemed to make everything a lot easier. You can see a list of all the files in your Java (or Android for that matter) project in the package explorer, easily navigate to the desired function with the outline window, get suggestions for functions, imports, and more. Anyhow, since my partners and I worked with Eclipse, my first partner taught me a few keyboard shortcuts, which I then taught to my second partner, whom did not use “sysout” or any Eclipse shortcuts (if you do not know what “sysout” means, you’re reading the right article!). Thus, the reason for this post was born – to go over some very useful keyboard shortcuts for actions you’ll probably perform often. If you are a frequent reader of this post and have contemplated programming for a little while, ponder no longer. We at MakeUseOf have compiled a few 2 Websites & 2 Apps That Can Help When Learning Java Programming lists to websites that will guide you through Java (or ) lessons and examples Top 5 Websites for Java Application Examples Top 5 Websites for Java Application Examples Read More . What if you’re unsure of what language to start with? We also have you covered with suggestions for web and software development. So once you’re done browsing through our development collection, feel inspired to start programming, and have Eclipse installed, you might want find the following tips useful. Control + Shift + O: Import If you’re going to use ArrayList, LinkedList or any other such data structure class from the Java Collections Framework, you will need the following lines above your class declaration and constructor. import java.awt.List; import java.util.ArrayList; public class Hello { public static void main(String[] args) { System.out.println("Hello World!"); } } Instead of having to type the import lines, you could just write your code first in the editor and whenever you see red squiggly lines signaling that you need to import a specific class, all you have to do is press Ctrl + Shift + O and ALL the unknown types will be imported. No more going into the focus popup and pressing Import for each class. Control + I: Indent Is your code looking like this at times? Simply highlight the code portion that looks hard to read, press Ctrl + i to indent everything nicely. Control + D: Delete Line If you need to delete a line, you might usually highlight the entire line with your mouse (or with the Home or End buttons) and delete the new line character every time. Try Ctrl + D for quick whole-line deletion. It will be like the line was never even there, no final new line character touchups necessary. Control + Space: Auto-Complete Variable Or Function Name If you have declared and initialized at least one variable or even function or method, you can type the first few letters of the variable or function name, hit Ctrl + Space to auto-complete it. This will work well if you have very unique variable or function names, because otherwise, you’ll have to choose among the distinct names in a focus popup window. Sysout + Control + Space: Puts System.out.println() If you ever need to type out a print statement, in particular, “System.out.println()”, there’s a shortcut for this: Simply type out the word “sysout” and then hit Ctrl + Space. Control + H: Search Your Entire Project When you’re working on projects with numerous classes that rely on each other, sometimes you might forget where it was you declared a specific function or variable. If that’s the case, Ctrl + h will come in handy as it lets you search through not just the class you’re working on, but the entire project folder. Control + F11: Run If you’re constantly pressing on Run As > Java Application, you can instead press on Ctrl + F11 to run your program. Alt + Shift + R: Rename When you want to rename a variable or a function, you don’t have to re-type every single instance of the old variable or function name, nor do you have to right-click on the name and select Refactor > Rename when you can simply press Alt + Shift + R to rename ALL the instances. What other handy tips do you have for beginners? Let us know in the comments below! @Sagar, (CTRL + SHIFT + L) its a very helpful key to access all the shortcuts. Thanks a lot. CTRL + SHIFT + L To open list of all shortcuts 1:- CTRL+SHIFT+Y for small letters (beanmain) 2:- CTRL+SHIFT+X for capital letters (BEANMAIN) 3:- CTRL+SHIFT+C for comment selected lines. For Mac Users 1:- COMMAND+SHIFT+Y for small letters (beanmain) 2:- COMMAND+SHIFT+X for capital letters (BEANMAIN) 3:- COMMAND+SHIFT+C for comment selected lines. The above holds true for many of the other shortcuts that come after these as well. Any shortcut key to copy entire line without selecting? Ctrl-ALT Down to copy and paste the entire line Ctrl+ALT+Down is for change tab on Editor. Highlight block of code then Ctrl-/ to comment it out.... Oh, and so much more! (and some more useful, IMHO): - CTRL+SHIFT+T : open fast type browser - start typing your class name to filter the list (also accepts wildcards, like *StuffFacade) then use the up-down cursor keys to open the type. - CTRL+SHIFT+R : open fast file browser - like the above, but for files, so its useful when developing non-Java code. - CTRL-O : fast outline browser - to jump to a method, hit they keys then start typing the method name until the list is small enough so you can up-down to the required method. - ALT-F8 : switch between perspective in a LRU manner (like ALT-TAB for applications) - F12 : go to editor - if your keyboard focus is in any other view, move the keyboard to the editor view. Also, ALT-SHIFT-Q opens a fast list of all viewes you can access with a keyboard shortcut (that is in the default form of ALT-SHIFT-) so you can easily switch to the required view without remembering the actual shortcut. - CTRL-E : open a fast list of editor tabs (including those not visible in the tab bar, which are marked in bold) to easily find the editor tab you need. This list also supports type-to-filter. - ALT-Up/ALT-Down : move the current line (or lines selected) in the editor up or down one line while fixing indentation (so moving the line into an indented block will indent the line correctly). Very useful for quick refactoring. - F2 : Quick Javadoc - opens a floating dialog with the javadoc for the symbol the cursor is on. Use up-down to browser the documentation and ESC to dismiss. Control + L is Go To Line Number F3 takes you to the declaration of a function or variable
http://www.makeuseof.com/tag/8-keyboard-shortcuts-beginner-eclipse-ide-users/
CC-MAIN-2017-34
refinedweb
1,232
66.47
Given the task is to count the minimum frequency elements in a given linked list which is having duplicate elements. A linked list is a data structure in which the data is stored in the serial order, like a list each element is linked to the next element. The frequency of an element in a linked list refers to the number of times an element is occurring in the linked list. According to the problem we have to count the minimum frequency in a linked list. Let us suppose we have a linked list, 1, 1, 3, 1, 3, 4, 6; where the minimum frequency is one so we have to count the elements, who are having a minimum frequency. There are only two elements 4 and 6 with the least frequency so the count is 2. Input − linked list 1->1->2->2->2->3->3 Output − count is 2 Explanation − The minimum frequency in the above example is 2 and there are two elements with the minimum frequency i.e. 1 and 3, so the count is 2. Input − linked list = 1->2->3->2->4->2->5 Output − count is 4 Explanation − The minimum frequency in the above example is 1 and there are 4 elements with the minimum frequency i.e. 1, 3, 4, and 5, so the count is 4. Define a linked list and push the elements in the linked list. In the minimum function to find the count of the elements with minimum frequency, declare a map “mymap” to store the frequencies of numbers. Traverse the list and store the frequency (occurrence) of the elements in mymap. After we found the frequencies and stored the frequencies in mymap, then find the minimum frequency. Count the frequency number of times that occurred in the mymap. Return the count. #include <iostream> #include <unordered_map> #include <climits> using namespace std; struct Node { int key; struct Node* next; }; // to push the values in the stack void push(struct Node** head_ref, int new_key){ struct Node* new_node = new Node; new_node->key = new_key; new_node->next = (*head_ref); (*head_ref) = new_node; } // Function to count minimum frequency elements // in the linked list int minimum(struct Node* head){ // Store frequencies of all nodes. unordered_map<int, int> mymap; struct Node* current = head; while (current != NULL){ int value = current->key; mymap[value]++; current = current->next; } // Find min frequency current = head; int min = INT_MAX, count = 0; for (auto it = mymap.begin(); it != mymap.end(); it++){ if (it->second <= min){ min = it->second; } } // Find count of min frequency elements for (auto it = mymap.begin(); it != mymap.end(); it++){ if (it->second == min){ count += (it->second); } } return count; } int main(){ /* Starting with an empty list */ struct Node* head = NULL; int x = 21; push(&head, 30); push(&head, 50); push(&head, 61); push(&head, 40); push(&head, 30); cout <<"count is: "<<minimum(head) << endl; return 0; } If we run the above code we will get the following output − count is: 3
https://www.tutorialspoint.com/count-minimum-frequency-elements-in-a-linked-list-in-cplusplus
CC-MAIN-2021-43
refinedweb
489
58.01
Spark vs Hadoop by Kostyantyn Kharchenko Hadoop and Spark - History of the Creation The Hadoop project was initiated by Doug Cutting and Mike Cafarella in early 2005 to build a distributed computing infrastructure for a Java-based free software search engine, Nutch. Its basis was a publication of Google employees Jeff Dean and Sanjay Gemawat on the computing concept of MapReduce. During 2005-2006 Hadoop was created by the two developers, Doug Cutting, and Mike Cafarella, working part-time on the project. In January 2006, Yahoo requested that Cutting lead a dedicated team to develop a distributed computing infrastructure, with Hadoop being designated a separate project at the same time. In February 2008, Yahoo launched a clustered search engine based on 10,000 processor cores operated by Hadoop in productive operation. In January 2008, Hadoop became the top-level project of the Apache Software Foundation project. In April 2008, Hadoop beat the world record of performance for a standardized benchmark, sorting data (1 TB was processed for 309 seconds in a cluster of 910 nodes). Since then, Hadoop has begun to be widely used outside of Yahoo - the technology is used by Last.fm, Facebook, The New York Times, and there is an adaptation to launch Hadoop in the Amazon EC2 clouds. In September 2009, Cutting moved to California's Cloudera startup. In April 2010, Google granted the Apache Software Foundation the right to use MapReduce technology three months after its defense at the US Patent Office, thereby depriving the organization of possible patent claims. Since 2010, Hadoop has become a key technology of Big Data. It is widely used for mass-parallel data processing, along with r Cloudera, a series of technology startups that are fully aimed at the commercialization of Hadoop technology. During 2010, several sub-projects of Hadoop - Avro, HBase, Hive, Pig, Zookeeper - became and have remained Apache's top-level projects. The Spark project was launched by Matei Zaharia AMPLab of Berkeley University in 2009, and its code became open in 2010 under the BSD license. In 2013, the project was presented by Apache Software Foundation and changed its license to Apache 2.0. In February 2014, Spark became the top-level project in the Apache Software Foundation. In November 2014, the Databricks company, founded by Matei Zaharia, used Spark to set a new world record for sorting large volumes of data. Spark had over 1,000 project participants in 2015, making it one of the most active projects in the Apache Software Foundation and one of the most active projects for large open-source data. To select the right technology concerning Spark vs Hadoop it is necessary to refer to the concept of distributed computation. Distributed computing concept Distributed computing (distributed data processing) - a way to solve large computational tasks using two or more computers that are networked. Distributed computing is a special case of parallel computing; that is, the simultaneous solution of different parts of one computing task by several processors using one or more computers. It is necessary that the task to be solved was divided into subtasks that can be computed in parallel. In this case, for distributed computing, it is necessary to take into account the possible difference in the computing resources that will be available for the calculation of various subtasks. However, not every task can be "parsed" and its solution accelerated with the help of distributed computing. Fig. 1. Distributing computing concept. Hadoop vs Spark - Overview and Comparison Spark Spark is an open-source cluster computing platform, similar to Hadoop framework, but with some useful features that make it an excellent tool for solving some kinds of tasks. Namely, in addition to interactive queries, Spark supports disbursed data sets in memory, optimizing the solution of iterative tasks and implicit data parallelism and fault tolerance. It is designed to solve a huge range of workloads such as batch applications, iterative algorithms, interactive queries, and streaming. Spark is implemented in the Scala language and used as an application development environment. Unlike Hadoop, Spark and Scala form tight integration where Scala can easily manipulate distributed data sets as local collective objects. Although Spark is designed to solve iterative problems with distributed data, it actually complements Hadoop and can work together with the Hadoop file system. In addition, Spark introduced the concept of a sustainable common data set (resilient distributed datasets - RDD). RDD is a collection of immutable objects distributed over a set of nodes. In Spark, applications are called drivers, and these drivers perform operations that are performed on a single node or in parallel on a set of nodes. Like Hadoop, Spark supports single-node and multi-node clusters. Spark Core It is the kernel of Spark. Spark SQL It enables users to run SQL/HQL queries on the top of Spark. Spark Streaming Apache Spark Streaming allows building data analytics application with live streaming data. Spark MLlib It is the machine learning library for scaling application with high-performance algorithms. Spark GraphX Apache Spark GraphX is the graph computation engine. SparkR It is an R package that gives light-weight frontend to use Apache Spark from R. Resilient Distributed Dataset – RDD Apache Spark has a key abstraction of Spark known as RDD or Resilient Distributed Dataset. RDD is the fundamental unit of data in Apache Spark. This unit represents a distributed collection of elements across cluster nodes. It is used to perform parallel operations. Spark RDDs are immutable but at the same time can generate new RDDs by transforming an existing RDD. Apache Spark RDDs support two types of operations. Please take a look at how Apache Spark describes distributed tasks in a compact and easy-to-read form (source). Scala val count = sc.parallelize(1 to NUM_SAMPLES).filter { _ => val x = math.random val y = math.random x*x + y*y < 1 }.count() println(s"Pi is roughly ${4.0 * count / NUM_SAMPLES}") Python def inside(p): x, y = random.random(), random.random() return x*x + y*y < 1 count = sc.parallelize(xrange(0, NUM_SAMPLES)) \ .filter(inside).count() print "Pi is roughly %f" % (4.0 * count / NUM_SAMPLES) Fig. 2. Apache Spark ecosystem. Hadoop Hadoop MapReduce is a software framework for effortlessly writing applications which contain a huge number of records (multi-terabyte data-sets) in-parallel on giant clusters (thousands of nodes) in fault-tolerant mode. It is designed to process large amounts of data from file systems, and the high-performance Hadoop Distributed File System was created especially to read, process and store huge amounts of data on a cluster of a large number of computers. A MapReduce job commonly splits the input data-set into detached chunks. These chunks are processed by mapping tasks in parallel. Typically the input and the output of the job are each saved in a file-system. The framework automatically works on scheduling tasks, monitoring and re-executing the failed tasks. Usually, the compute nodes and the storage nodes are the same, i.e. the MapReduce framework and the HDFS are running on the same nodes. This configuration allows the framework to effectively schedule tasks between nodes. The Hadoop ecosystem also consists of the following components: - MapReduce (Data Processing) - Yarn (Cluster Management) - HDFS (Hadoop Distributed File System) - Pig (Scripting) - Hive (SQL Query) - Mahout (Distributed Linear Algebra Framework) - HBase (Columnar Store) - Oozie (Work Flow Management) Fig. 3. Hadoop Ecosystem (main components). A simple example of Hadoop looks like this. Please refer here for more information. (Source)); } } As you can see by analyzing the source code the Spark vs Hadoop choice is obvious and Spark in this case looks more compact and easy to use. Spark vs Hadoop conclusions First of all, the choice between Spark vs Hadoop for distributed computing depends on the nature of the task. It cannot be said that some solution will be better or worse, without being tied to a specific task. A similar situation is seen when choosing between Apache Spark and Hadoop. Spark is great for: - Iterative algorithms, processing of the streaming data - Real-time analysis - Machine Learning algorithms - Large graph processing Hadoop is great for: - Analysis of large data collection - Data analysis where time factor is not critical - Step-by-step data processing of large datasets - Works perfectly if you need to manage large amounts of stored data In general, the choice between Spark vs Hadoop is obvious and is a consequence of the analysis of the nature of the tasks. The advantage of Spark is speed, but, on the other hand, Hadoop allows automatic saving for intermediate results of calculations. As Hadoop works with persistent storage in HDFS it is slow compared to Spark, but the saved intermediate results help to continue processing from any point. Another advantage of Spark is simple coding in many programming languages. A Spark code is smaller and easier to read compared to Hadoop. Users can write code in many programming languages including R, Scala, Python, Java and use SQL. Fig. 4. Hadoop vs Spark computation flow. Cloud Systems and Spark vs Hadoop Usage Cloud-native Apache Hadoop & Apache Spark Cloud Dataproc is a fast, easy-to-use, completely managed cloud service for running Apache Spark and Apache Hadoop clusters in a simpler, more affordable way. Cloud Dataproc additionally effortlessly integrates with other Google Cloud Platform (GCP) services. It provides an effective platform for data processing, analytics and learning: Automated Cluster Management - Resizable Clusters - Integrated (Built-in integration with Cloud Storage, BigQuery, Bigtable, Stackdriver Logging, and Stackdriver Monitoring) - Versioning (allows to switch between different versions of Apache Spark, Apache Hadoop, etc) - Highly available - Developer Tools (easy-to-use Web UI, the Cloud SDK, RESTful APIs, and SSH access) - Initialization Actions - Automatic or Manual Configuration - Flexible Virtual Machines Amazon EMR Amazon EMR has built-in help for Apache Spark, which lets it quickly and easily create managed Apache Spark clusters through the AWS Management Console, AWS Command Line Interface or Amazon EMR API. Also, extra Amazon EMR features are available, including fast connection to Amazon S3 using the EMR file system (EMRFS), integration with the Amazon EC2 spot instance store and the AWS Glue information catalog, and Auto Scaling to add or dispose of instances from the cluster. It is possible additionally to use Apache Zeppelin to create interactive collaboration notebooks for information exploration through the use of Apache Spark and use deep knowledge of platforms, such as Apache MXNet, in Spark-based applications. Difference between Hadoop and Spark - Final words Apache Spark is a real-time data analysis system that basically performs computing in memory in a distributed environment. It offers great processing speed, which makes it very appealing for analyzing large amounts of data. Spark can work as a stand-alone tool or be associated with Hadoop YARN. Spark is a great in-memory distributed computing engine. Spark is an interesting addition to the growing family of large data analysis platforms. It is an effective and convenient platform (thanks to simple and clear scripts in Scala, Python) for processing distributed tasks. Hadoop is based on the HDFS distributed system and uses MapReduce computational paradigm where an application is divided into a large number of identical simple tasks, then each of these tasks is executed on a node in the cluster and its result is reduced to the final output. In this case, Hadoop is a great solution for processing large data sets on a cluster of computers. Hadoop, first of all, is a framework for distributed storage and works with distributed processing YARN. One of the biggest users and developers of Hadoop is Yahoo!, which actively uses this system in its search clusters (Hadoop-cluster of Yahoo, consisting of 40 thousand nodes). The Hadoop cluster is used by Facebook to handle one of the largest databases, which holds about 30 petabytes of information. Hadoop is also at the core of the Oracle Big Data platform and is actively adapted by Microsoft to work with the SQL Server database, Windows Server. Nevertheless, it is believed that the horizontal scalability in Hadoop systems is limited, for up to version 2.0, the maximum possible was estimated at 4 thousand. nodes using 10 MapReduce jobs per node. Both systems, Spark and Hadoop, are the right and effective tools for high-power distributed computing. This allows you to choose between tools you need to achieve the best results for your particular task, both in a cluster in your data center and in cloud systems. Related articles >.
https://svitla.com/blog/spark-vs-hadoop
CC-MAIN-2020-05
refinedweb
2,072
52.49
16 November 2011 12:49 [Source: ICIS news] JOHANNESBURG (ICIS)--Saudi-based chemicals producer SABIC has suspended its November shipments of polyethylene (PE) into South Africa, fuelling speculation of a possible price increase for imports, sources said on Wednesday. SABIC’s announcement has come at a time when local manufacturers are short on product, and distributors and buyers are more dependent on imports, industry sources said on the sidelines of the Plastics Packaging Africa conference in Johannesburg. In a letter to its customers dated 9 November, SABIC announced that the suspension of shipping for two grades of PE – linear low density polyethylene (LLDPE) and high density polyethylene (HDPE) – will continue until it finds a “workable solution” to tax changes in the country. It added: “It will not mean any withdrawal by SABIC from the Southern African market.” However, the company said it expects the disruption to adversely affect its supply during December and January. A regular distributor of imported product into ?xml:namespace> The South African government’s withdrawal of 1.3% import duty from 1 January, 2012, would essentially mean material stored in bonded warehouses from then on would be liable for a 14% VAT payment instead, the source explained. “If there is no duty and goods cannot be cleared into bonded warehouses, it means VAT has to be paid immediately on imports,” it said. SABIC stated in the letter to its customers: “The impact of this is clearly far reaching for SABIC, not only in terms of the VAT value which will now be due when a vessel arrives, but also in terms of the practicality of paying VAT in rand and then collecting VAT at the time of sale.” “Our current business is all conducted in US dollars,” the company continued. “Our current business processes and systems do not easily allow for this change.” A couple of distributors of imported product said they expect SABIC’s move to push prices up, especially for the shorter LLDPE grade. “November is peak season in “This news means prices are definitely going up,” it said. A third distributor said: “They [SABIC] stopped shipping two months ago. Also, there’s a lot of auditing and finance, and it will take time before it is sorted.” Other suppliers in the market are more cautious, and said supply is unlikely to be disrupted as SABIC is still likely to have stocks at its warehouse in “The fact is that SABIC and many other importers haven’t stopped, they just postponed their shipments. They just want to understand its implications. I hope they will resolve this issue within two weeks,” maintained the first distributor.
http://www.icis.com/Articles/2011/11/16/9508608/sabic-suspends-nov-pe-shipments-to-s-africa-on-vat-concerns.html
CC-MAIN-2014-52
refinedweb
440
57
The Async Storage is a simple key-value pair based storage system in React Native. It is used for scenarios where you want to save the user’s data on the device itself instead of using any cloud service, such as building offline apps. According to the React Native’s official documentation: On iOS, AsyncStorage is backed by native code that stores small values in a serialized dictionary and larger values in separate files. On Android, AsyncStorage will use either RocksDB or SQLite based on what is available. In this tutorial, you are going to learn how to use the Async Storage API to perform any of the CRUD operations in React Native applications. To begin with, you are required to have: - Node.js (>= 10.x.x) with npm/yarn installed - react-native-cli Installing Async Storage To follow along, create a demo app using the CLI by typing the following command in the terminal window: react-native init asyncstorageDemo To access Async Storage API, you will have to install the package async-storage. yarn add @react-native-community/async-storage If you are using React Native 0.60+, the autolink feature will link the module. For the previous version, please read the instructions here to install this module. Lastly, for iOS developers, please make sure to traverse inside ios/ directory and run pod install. That’s it for setting it up. Defining a Storage Key To start with the app, it is going to save a value to the device’s storage using Async Storage API and fetch the same value from the storage. This is going to help you learn how to write basic operations using the storage API. Open the file App.js and import some necessary UI components from React Native core to build a user interface for the demo app. Since the Async Storage package is already integrated, you to import that explicitly. import React, { Component } from 'react' import { SafeAreaView, StyleSheet, TextInput, TouchableOpacity, Text, StatusBar } from 'react-native' import AsyncStorage from '@react-native-community/async-storage' Define a variable STORAGE_KEY that is an identifier (key) for the stored data. It is going to store and retrieve the stored data using the Async Storage API. In the demo app, you are going to store only one value, so there is no requirement for more than one key. const STORAGE_KEY = '@save_name' Lastly, inside the class component App, define an initial state with two empty strings. They’re will save the value of the user input and then retrieve the same value to display it on the UI. Using a lifecycle method componentDidMount, invoke the method readData() that loads any stored value on the initial render of the app. class App extends Component { state = { text: '', name: 'world' } componentDidMount() { this.readData() } // ... rest of the component } Reading the data Every method in Async Storage API is promise-based. This means you can use async/await to label an API function. async and await are JavaScript syntax. Labeling a function async means that the function returns a promise initially, allowing you to perform other tasks as the function continues to execute in the background. In the code snippet below, readData is an async function. It fetches the item from the storage using the STORAGE_KEY if it exists. The AsyncStorage.getItem() is used to fetch an item. The if condition makes sure that data is fetched only when a value for the name variable exists. readData = async () => { try { const name = await AsyncStorage.getItem(STORAGE_KEY) if (name !== null) { this.setState({ name }) } } catch (e) { alert('Failed to load name.') } } Saving the data The saveData method is the opposite of the previous function. It uses AsyncStorage.setItem() to save the data on the key STORAGE_KEY. An alert dialog box is shown whether the data is saved successfully or not. This is how we set the data, so that the offline apps can use it later for displaying, when there is no Internet connection. saveData = async name => { try { await AsyncStorage.setItem(STORAGE_KEY, name) alert('Data successfully saved!') this.setState({ name }) } catch (e) { alert('Failed to save name.') } } Clear storage The last method from Async Storage API that is required is removeData. Using AsyncStorage.clear() deletes everything that is previously saved. To delete specific items, there are methods like removeItem or multiRemove available by the API. An alert box is shown on the screen when everything is cleared from storage. removeData = async () => { try { await AsyncStorage.clear() alert('Storage successfully cleared!') this.setState({ name: 'world' }) } catch (e) { alert('Failed to clear the async storage.') } } Handler methods for Controller Input Let us write two more methods to handle the controller input field. onChangeText = text => this.setState({ text }) onSubmitEditing = () => { const onSave = this.saveData const { text } = this.state if (!text) return onSave(text) this.setState({ text: '' }) } Next, add the render() method that is going to display an interface on the screen and let the user interact with it. render() { const { text, name } = this.state return ( <> <StatusBar barStyle='dark-content' /> <SafeAreaView style={styles.container}> <TextInput style={styles.input} value={text} placeholder='Type your name, hit enter, and refresh' placeholderTextColor='#fff' onChangeText={this.onChangeText} onSubmitEditing={this.onSubmitEditing} /> <Text style={styles.text}>Hello {name}!</Text> <TouchableOpacity onPress={this.removeData} style={styles.button}> <Text style={styles.buttonText}>Clear Storage</Text> </TouchableOpacity> </SafeAreaView> </> ) } Lastly, add the corresponding styles to the above code snippet and do not forget to export the class component. const styles = StyleSheet.create({ container: { flex: 1, backgroundColor: '#28D6C0', alignItems: 'center', justifyContent: 'center' }, text: { fontSize: 20, padding: 10, backgroundColor: '#f12b7e' }, input: { padding: 15, height: 50, fontSize: 20, borderBottomWidth: 1, borderBottomColor: '#333', margin: 10 }, button: { margin: 10, padding: 10, backgroundColor: '#f89221', borderRadius: 10 }, buttonText: { fontSize: 16, color: '#fff' } }) export default App Testing the offline app Go ahead, and open two terminal windows. In one window, execute the command react-native run-ios & from other window trigger the metro server by running yarn start or npm start. I am using an iOS simulator to test this demo. Initially, the app does not have any data stored, thus, the initial screen is going to be as below. It is currently displaying the Hello world! since the initial value of name in component’s state holds a default value of world. Type in a value in the input field and then press the enter key. It will replace the value of world as shown below. On success, an alert box is shown. And then the data is saved. Try refreshing the offline app and you will the data is still being displayed. Press the button below the Hello statement that says Clear Storage removes the stored value. And the default value of the world is shown. Conclusion This completes the post about using Async Storage API to save and fetch the data. The API comes with its own limitations. As a React Native developer, you have to know what these limitations are. One limitation of an AsyncStorage API is that on Android the size of the database is set to a default of 6MB. You can, however, change the default database size by adding an AsyncStorage_db_size_in_MB property to the file android/gradle.properties. AsyncStorage_db_size_in_MB=20 You can read more about Async Storage API in the official docs here. This API is perfect for building offline apps in React Native, as you can tell from this.
https://www.instamobile.io/react-native-tutorials/offline-apps-react-native/?ref=hackernoon.com
CC-MAIN-2021-10
refinedweb
1,217
57.87
I tried to compile following program (main.cu) with the nvcc (CUDA 5.0 RC): #include <Eigen/Core> #include <iostream> int main( int argc, char** argv ) { std::cout << "Pure CUDA" << std::endl; } NVCC invokes the normal host compiler but not before it has done some preprocessing, so it's likely that NVCC is struggling to parse the Eigen code correctly (especially if it uses C++11 features, but that's unlikely since you say VS2008 works). I usually advise separating the device code and wrappers into the .cu files and leaving the rest of your application in normal .c/ .cpp files to be handled by the host compiler directly. See this answer for some tips on getting this set up with VS2008.
https://codedump.io/share/D7vKlj1sEdtT/1/compiling-eigen-library-with-nvcc-cuda
CC-MAIN-2018-13
refinedweb
122
71.85