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
Understanding __get__ and __set__ and Python descriptors The descriptor is how Python's property type is implemented. A descriptor simply implements __get__, __set__, etc. and is then added to another class in its definition (as you did above with the Temperature class). For example: temp=Temperature()temp.celsius #calls celsius.__get__ Accessing the property you assigned the descriptor to ( celsius in the above example) calls the appropriate descriptor method. instance in __get__ is the instance of the class (so above, __get__ would receive temp, while owner is the class with the descriptor (so it would be Temperature). You need to use a descriptor class to encapsulate the logic that powers it. That way, if the descriptor is used to cache some expensive operation (for example), it could store the value on itself and not its class. An article about descriptors can be found here. EDIT: As jchl pointed out in the comments, if you simply try Temperature.celsius, instance will be None. Why do I need the descriptor class? It gives you extra control over how attributes work. If you're used to getters and setters in Java, for example, then it's Python's way of doing that. One advantage is that it looks to users just like an attribute (there's no change in syntax). So you can start with an ordinary attribute and then, when you need to do something fancy, switch to a descriptor. An attribute is just a mutable value. A descriptor lets you execute arbitrary code when reading or setting (or deleting) a value. So you could imagine using it to map an attribute to a field in a database, for example – a kind of ORM. Another use might be refusing to accept a new value by throwing an exception in __set__ – effectively making the "attribute" read only. What is instanceand ownerhere? (in __get__). What is the purpose of these parameters? This is pretty subtle (and the reason I am writing a new answer here - I found this question while wondering the same thing and didn't find the existing answer that great). A descriptor is defined on a class, but is typically called from an instance. When it's called from an instance both instance and owner are set (and you can work out owner from instance so it seems kinda pointless). But when called from a class, only owner is set – which is why it's there. This is only needed for __get__ because it's the only one that can be called on a class. If you set the class value you set the descriptor itself. Similarly for deletion. Which is why the owner isn't needed there. How would I call/use this example? Well, here's a cool trick using similar classes: class Celsius: def __get__(self, instance, owner): return 5 * (instance.fahrenheit - 32) / 9 def __set__(self, instance, value): instance.fahrenheit = 32 + 9 * value / 5class Temperature: celsius = Celsius() def __init__(self, initial_f): self.fahrenheit = initial_ft = Temperature(212)print(t.celsius)t.celsius = 0print(t.fahrenheit) (I'm using Python 3; for python 2 you need to make sure those divisions are / 5.0 and / 9.0). That gives: 100.032.0 Now there are other, arguably better ways to achieve the same effect in python (e.g. if celsius were a property, which is the same basic mechanism but places all the source inside the Temperature class), but that shows what can be done... I am trying to understand what Python's descriptors are and what they can be useful for. Descriptors are objects in a class namespace that manage instance attributes (like slots, properties, or methods). For example: class HasDescriptors: __slots__ = 'a_slot' # creates a descriptor def a_method(self): # creates a descriptor "a regular method" # creates a descriptor def a_static_method(): "a static method" # creates a descriptor def a_class_method(cls): "a class method" # creates a descriptor def a_property(self): "a property"# even a regular function:def a_function(some_obj_or_self): # creates a descriptor "create a function suitable for monkey patching"HasDescriptors.a_function = a_function # (but we usually don't do this) Pedantically, descriptors are objects with any of the following special methods, which may be known as "descriptor methods": __get__: non-data descriptor method, for example on a method/function __set__: data descriptor method, for example on a property instance or slot __delete__: data descriptor method, again used by properties or slots These descriptor objects are attributes in other object class namespaces. That is, they live in the __dict__ of the class object. Descriptor objects programmatically manage the results of a dotted lookup (e.g. foo.descriptor) in a normal expression, an assignment, or a deletion. Functions/methods, bound methods, property, classmethod, and staticmethod all use these special methods to control how they are accessed via the dotted lookup. A data descriptor, like property, can allow for lazy evaluation of attributes based on a simpler state of the object, allowing instances to use less memory than if you precomputed each possible attribute. Another data descriptor, a member_descriptor created by __slots__, allows memory savings (and faster lookups) by having the class store data in a mutable tuple-like datastructure instead of the more flexible but space-consuming __dict__. Non-data descriptors, instance and class methods, get their implicit first arguments (usually named self and cls, respectively) from their non-data descriptor method, __get__ - and this is how static methods know not to have an implicit first argument. Most users of Python need to learn only the high-level usage of descriptors, and have no need to learn or understand the implementation of descriptors further. But understanding how descriptors work can give one greater confidence in one's mastery of Python. In Depth: What Are Descriptors? A descriptor is an object with any of the following methods ( __get__, __set__, or __delete__), intended to be used via dotted-lookup as if it were a typical attribute of an instance. For an owner-object, obj_instance, with a descriptor object: obj_instance.descriptorinvokes descriptor.__get__(self, obj_instance, owner_class)returning a value This is how all methods and the geton a property work. obj_instance.descriptor = valueinvokes descriptor.__set__(self, obj_instance, value)returning None This is how the setteron a property works. del obj_instance.descriptorinvokes descriptor.__delete__(self, obj_instance)returning None This is how the deleteron a property works. obj_instance is the instance whose class contains the descriptor object's instance. self is the instance of the descriptor (probably just one for the class of the obj_instance) To define this with code, an object is a descriptor if the set of its attributes intersects with any of the required attributes: def has_descriptor_attrs(obj): return set(['__get__', '__set__', '__delete__']).intersection(dir(obj))def is_descriptor(obj): """obj can be instance of descriptor or the descriptor class""" return bool(has_descriptor_attrs(obj)) A Data Descriptor has a __set__ and/or __delete__. A Non-Data-Descriptor has neither __set__ nor __delete__. def has_data_descriptor_attrs(obj): return set(['__set__', '__delete__']) & set(dir(obj))def is_data_descriptor(obj): return bool(has_data_descriptor_attrs(obj)) Builtin Descriptor Object Examples: classmethod staticmethod property - functions in general Non-Data Descriptors We can see that classmethod and staticmethod are Non-Data-Descriptors: classmethod), is_data_descriptor(classmethod)(True, False) is_descriptor(staticmethod), is_data_descriptor(staticmethod)(True, False)is_descriptor( Both only have the __get__ method: classmethod), has_descriptor_attrs(staticmethod)(set(['__get__']), set(['__get__']))has_descriptor_attrs( Note that all functions are also Non-Data-Descriptors: def foo(): passis_descriptor(foo), is_data_descriptor(foo)(True, False) Data Descriptor, property However, property is a Data-Descriptor: property)Truehas_descriptor_attrs(property)set(['__set__', '__get__', '__delete__'])is_data_descriptor( Dotted Lookup Order These are important distinctions, as they affect the lookup order for a dotted lookup. obj_instance.attribute - First the above looks to see if the attribute is a Data-Descriptor on the class of the instance, - If not, it looks to see if the attribute is in the obj_instance's __dict__, then - it finally falls back to a Non-Data-Descriptor. The consequence of this lookup order is that Non-Data-Descriptors like functions/methods can be overridden by instances. Recap and Next Steps We have learned that descriptors are objects with any of __get__, __set__, or __delete__. These descriptor objects can be used as attributes on other object class definitions. Now we will look at how they are used, using your code as an example. Analysis of Code from the Question Here's your code, followed by your questions and answers to each: class Celsius(object): def __init__(self, value=0.0): self.value = float(value) def __get__(self, instance, owner): return self.value def __set__(self, instance, value): self.value = float(value)class Temperature(object): celsius = Celsius() - Why do I need the descriptor class? Your descriptor ensures you always have a float for this class attribute of Temperature, and that you can't use del to delete the attribute: del t1.celsiusTraceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: __delete__t1 = Temperature() Otherwise, your descriptors ignore the owner-class and instances of the owner, instead, storing state in the descriptor. You could just as easily share state across all instances with a simple class attribute (so long as you always set it as a float to the class and never delete it, or are comfortable with users of your code doing so): class Temperature(object): celsius = 0.0 This gets you exactly the same behavior as your example (see response to question 3 below), but uses a Pythons builtin ( property), and would be considered more idiomatic: class Temperature(object): _celsius = 0.0 def celsius(self): return type(self)._celsius def celsius(self, value): type(self)._celsius = float(value) - What is instance and owner here? (in get). What is the purpose of these parameters? instance is the instance of the owner that is calling the descriptor. The owner is the class in which the descriptor object is used to manage access to the data point. See the descriptions of the special methods that define descriptors next to the first paragraph of this answer for more descriptive variable names. - How would I call/use this example? Here's a demonstration: 0.0t1.celsius = 1t1.celsius1.0t2 = Temperature() t2.celsius1.0t1 = Temperature() t1.celsius You can't delete the attribute: del t2.celsiusTraceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: __delete__ And you can't assign a variable that can't be converted to a float: '0x02'Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 7, in __set__ValueError: invalid literal for float(): 0x02t1.celsius = Otherwise, what you have here is a global state for all instances, that is managed by assigning to any instance. The expected way that most experienced Python programmers would accomplish this outcome would be to use the property decorator, which makes use of the same descriptors under the hood, but brings the behavior into the implementation of the owner class (again, as defined above): class Temperature(object): _celsius = 0.0 def celsius(self): return type(self)._celsius def celsius(self, value): type(self)._celsius = float(value) Which has the exact same expected behavior of the original piece of code: 0.0t1.celsius = 1.0t2.celsius1.0del t1.celsiusTraceback (most recent call last): File "<stdin>", line 1, in <module>AttributeError: can't delete attribute>>> t1.celsius = '0x02'Traceback (most recent call last): File "<stdin>", line 1, in <module> File "<stdin>", line 8, in celsiusValueError: invalid literal for float(): 0x02t1 = Temperature() t2 = Temperature() t1.celsius Conclusion We've covered the attributes that define descriptors, the difference between data- and non-data-descriptors, builtin objects that use them, and specific questions about use. So again, how would you use the question's example? I hope you wouldn't. I hope you would start with my first suggestion (a simple class attribute) and move on to the second suggestion (the property decorator) if you feel it is necessary.
https://codehunter.cc/a/python/understanding-get-and-set-and-python-descriptors
CC-MAIN-2022-21
refinedweb
1,969
54.02
Learn how to program the ESP32 and ESP8266 NodeMCU boards using VS Code (Microsoft Visual Studio Code) with PlatformIO IDE extension. We cover how to install the software on Windows, Mac OS X or Ubuntu operating systems. The Arduino IDE works great for small applications. However, for advanced projects with more than 200 lines of code, multiple files, and other advanced features like auto completion and error checking, VS Code with the PlatformIO IDE extension is the best alternative. In this tutorial, we’ll cover the following topics: - Installing VS Code (Visual Studio Code): - Installing PlatformIO IDE Extension on VS Code - Visual Studio Quick Interface Overview - PlatformIO IDE Overview - Uploading Code using PlatformIO IDE: ESP32/ESP8266 - Changing the Serial Monitor Baud Rate – PlatformIO IDE - Installing Libraries on PlatformIO IDE. Installing Python on Windows To program the ESP32 and ESP8266 boards with PlatformIO IDE you need Python 3.5 or higher installed in your computer. We’re using Python 3.8.5. Go to python.org/download and download Python 3.8.5 or a newest version. Open the downloaded file to start the Python installation wizard. The following window shows up. IMPORTANT: Make sure you check the option Add Python 3.8 to PATH. Then, you can click on the Install Now button. When the installation is successful you’ll get the following message. You can click the Close button. Now, go to this section to install PlatformIO IDE extension.. Installing Python on Mac OS X To program the ESP32 and ESP8266 boards with PlatformIO IDE you need Python 3.5 or higher installed in your computer. We’re using Python 3.8.5. To install Python I’ll be using Homebrew. If you don’t have the brew command available, type the next command: $ /bin/bash -c "$(curl -fsSL)" Then, run the brew command to install Python 3.X: $ brew install python3 Now, go to this section to install PlatformIO IDE extension. C) Installing VS Code on Linux Ubuntu (Visual Studio Code) Go to and download the stable build for your operating system (Linux Ubuntu). Save the installation file: To install it, open a Terminal windows, Python on Linux Ubuntu To program the ESP32 and ESP8266 boards with PlatformIO IDE you need Python 3.5 or higher installed in your computer. We’re using Python 3.8. Open the Terminal window and check that you already have Python 3 installed. $ python3 --version python 3.8.2 As you can see in the preceding figure, Python 3.8.2 is already installed. If you don’t have Python 3.8.X installed, run the next command to install it: $ sudo apt install python3 Whether you already have Python installed or not, you need to run the following command to install Python utilities. $ sudo apt install python3-distutils Now, go to this section to install PlatformIO IDE extension. Installing PlatformIO IDE Extension on VS Code It is possible to program the ESP32 and ESP8266 boards using VS Code with the PlatformIO IDE extension. Follow the next steps to install the PlatformIO IDE extension. Open VS Code: - Click on the Extensions icon or press Ctrl+Shift+X to open the Extensions tab - Select the first option - Finally, click the Install button (Note: the installation may take a few minutes) After installing, make sure that PlatformIO IDE extension is enabled as shown below. After that, the PlatformIO icon should show up on the left sidebar as well as an Home icon that redirects you to PlatformIO home. That’s it, PlatformIO IDE extension was successfully added to VS Code. If you don’t see the PIO icon and the quick tools at the bottom, you may need to restart VS code for the changes to take effect. Either way, we recommend restarting VS Code before proceeding. VS Code Quick Interface Overview Open VS Code. The following print screen shows the meaning of each icon on the left sidebar and its shortcuts: - File explorer - Search across files - Source code management (using gist) - Launch and debug your code - Manage extensions Additionally, you can press Ctrl+Shift+P or go to View > Command Palette… to show all the available commands. If you’re searching for a command and you don’t know where it is or its shortcut, you just need to go to the Command Palette and search for it. At the bottom, there’s a blue bar with PlatformIO commands. Here’s the what icon does from left to right: - PlatformIO Home - Build/Compile - Upload - Clean - Serial Monitor - New Terminal If you hover your mouse over the icons, it will show what each icon does. Alternatively, you can also click on the PIO icon to see all the PlatformIO tasks. If the tasks don’t show up on your IDE when you click the icon, you may need to click on the three dot icon at the top and enable PlatformIO tasks as shown below. PlatformIO IDE Overview For you to get an overview on how PlatformIO works on VS code, we’ll show you how to create, save and upload a “Blinking LED” sketch to your ESP32 or ESP8266 board. Create a New Project On VS Code, click on the PlartfomIO Home icon. Click on + New Project to start a new project. Give your project a name (for example Blink_LED) and select the board you’re using. In our case, we’re using the DOIT ESP32 DEVKIT V1. The Framework should be “Arduino” to use the Arduino core. You can choose the default location to save your project or a custom location. The default location is in this path Documents >PlatformIO >Projects. For this test, you can use the default location. Finally, click “Finish”. For this example, we’ll be using the DOIT ESP32 DEVKIT board. If you are using an ESP8266 NodeMCU board the process is very similar, you just need to select your ESP8266 board: The Blink_LED project should be accessible from the Explorer tab. VS Code and PlatformIO have a folder structure that is different from the standard .ino project. If you click on the Explorer tab, you’ll see all the files it created under your project folder. It may seem a lot of files to work with. But, don’t worry, usually you’ll just need to deal with one or two of those files. Warning: you shouldn’t delete, modify or move the folders and the platformio.ini file. Otherwise, you will no longer be able to compile your project using PlatformIO. platformio.ini file The platformio.ini file is the PlatformIO Configuration File for your project. It shows the platform, board, and framework for your project. You can also add other configurations like libraries to be included, upload options, changing the Serial Monitor baud rate and other configurations. - platform: which corresponds to the SoC used by the board. - board: the development board you’re using. - framework: the software environment that will run the project code. With the ESP32 and ESP8266, if you want to use a baud rate of 115200 in your Serial Monitor, you just need to add the following line to your platformio.ini file. monitor_speed = 115200 After that, make sure you save the changes made to the file by pressing Ctrl+S. In this file, you can also include the identifier of libraries you’ll use in your project using the lib_deps directive, as we’ll see later. src folder The src folder is your working folder. Under the src folder, there’s a main.cpp file. That’s where you write your code. Click on that file. The structure of an Arduino program should open with the setup() and loop() functions. In PlatformIO, all your Arduino sketches should start with the #include <Arduino.h>. Uploading Code using PlatformIO IDE: ESP32/ESP8266 Copy the following code to your main.cpp file. /********* Rui Santos Complete project details at *********/ #include <Arduino.h> #define LED 2 void setup() { // put your setup code here, to run once: Serial.begin(115200); pinMode(LED, OUTPUT); } void loop() { // put your main code here, to run repeatedly: digitalWrite(LED, HIGH); Serial.println("LED is on"); delay(1000); digitalWrite(LED, LOW); Serial.println("LED is off"); delay(1000); } This code blinks the on-board LED every second. It works with the ESP32 and ESP8266 boards (both have the on-board LED connected to GPIO 2). We recommend that you copy this code manually, so that you see the autocompletion and other interesting features of the IDE in action. Additionally, if you have a syntax error somewhere in your program, it will underline it in red even before compiling. After that, press Ctrl+S or go to File > Save to save the file. Now, you can click on the Upload icon to compile and upload the code. Alternatively, you can go to the PIO Project Tasks menu and select Upload. If the code is successfully uploaded, you should get the following message. After uploading the code, the ESP32 or ESP8266 should be blinking its on-board LED every second. Now, click on the Serial Monitor icon and you should see it printing the current LED state. Note: if you don’t see the Terminal window, go to the menu Terminal > New Terminal. Detect COM Port PlatformIO will automatically detect the port your board is connected to. To check the connected devices you can go to the PIO Home and click the Devices icon. Troubleshooting If when trying to upload code you get the following error: “Failed to connect to ESP32: Timed out waiting for packet header” it usually means that your board is not in flashing mode when you’re uploading the code. When this happens you need to press the ESP32 on-board BOOT button when you start seeing a lot of dots in the debugging window. If you don’t want to have to press the BOOT button every time you upload new code, you can follow this guide: [SOLVED] Failed to connect to ESP32: Timed out waiting for packet header. Changing the Serial Monitor Baud Rate – PlatformIO IDE The default baud rate used by PlatformIO is 9600. However, it is possible to set up a different value as mentioned previously. On the File Explorer, under your project folder, open the platformio.ini file and add the following line: monitor_speed = baud_rate For example: monitor_speed = 115200 After that, save that file. Installing ESP32/ESP8266 Libraries on PlatformIO IDE Follow the next procedure if you need to install libraries in PlatformIO IDE. Click the Home icon to go to PlatformIO Home. Click on the Libraries icon on the left side bar. Search for the library you want to install. For example Adafruit_BME280. Click on the library you want to include in your project. Then, click Add to Project. Select the project were you want to use the library. This will add the library identifier using the lid_deps directive on the platformio.ini file. If you open your project’s platformio.ini file, it should look as shown in the following image. Alternatively, on the library window, if you select the Installation tab and scroll a bit, you’ll see the identifier for the library. You can choose any of those identifiers depending on the options you want to use. The library identifiers are highlighted in red. Then, go to the platformio.ini file of your project and paste the library identifier into that file, like this: lib_deps = adafruit/Adafruit BME280 [email protected]^2.1.0 If you need multiple libraries, you can separate their name by a coma or put them on different lines. For example: lib_deps = arduino-libraries/Arduino_JSON @ 0.1.0 adafruit/Adafruit BME280 Library @ ^2.1.0 adafruit/Adafruit Unified Sensor @ ^1.1.4 PlatformIO has a built-in powerful Library Manager, that allows you to specify custom dependencies per project in the Project Configuration File platformio.ini using lib_deps. This will tell PlatformIO to automatically download the library and all its dependencies when you save the configuration file or when you compile your project. Open a Project Folder To open an existing project folder on PlatformIO, open VS Code, go to PlatformIO Home and click on Open Project. Navigate through the files and select your project folder. PlatformIO will open all the files within the project folder. VS Code Color Themes VS Code lets you choose between different color themes. Go to the Manage icon and select Color Theme. You can then select from several different light and dark themes. Shortcuts’ List For a complete list of VS Code shortcuts for Windows, Mac OS X or Linux, check the next link: Wrapping Up In this tutorial you’ve learned how to install and prepare Visual Studio Code to work with the ESP32 and ESP8266 boards. VS Code with the PlatformIO IDE extension is a great alternative to the classical Arduino IDE, especially when you’re working on more advanced sketches for larger applications. Here’s some of the advantages of using VS Code with PlatformIO IDE over Arduino IDE: - It detects the COM port your board is connected to automatically; - VS Code IntelliSense: Auto-Complete. IntelliSense code completion tries to guess what you want to write, displaying the different possibilities and provides insight into the parameters that a function may expect; - Error Highlights: VS Code + PIO underlines errors in your code before compiling; - Multiple open tabs: you can have several code tabs open at once; - You can hide certain parts of the code; - Advanced code navigation; - And much more… If you’re looking for a more advanced IDE to write your applications for the ESP32 and ESP8266 boards, VS Code with the PlatformIO IDE extension is a great option. We hope you’ve found this tutorial useful. If you like ESP32 and ESP8266, check the following resources: 91 thoughts on “Getting Started with VS Code and PlatformIO IDE for ESP32 and ESP8266 (Windows, Mac OS X, Linux Ubuntu)” How about asm? Hi. What are you referring to? Can you debug the code under Microsoft Visual Studio Code? Hi. Yes. Learn more here: Regards, Sara Great! Troubleshooting, error syntax and useless code ! You have an resolve with Alien code ? What do you mean? Besides the link Sara mentions here are some other references: A good video from Andreas Spiess demonstrating hardware debug in platformio: youtube.com/watch?v=psMqilqlrRQ Another good reference and video: hackster.io/brian-lough/use-the-platformio-debugger-on-the-esp32-using-an-esp-prog-f633b6 Most guides show only Windows installation. To get the JTAG interface to work in Linux you need to install the 99-platformio-udev.rules so the USB ingterface recognizes the device as explained in: docs.platformio.org/en/latest/plus/debug-tools/esp-prog.html For MacOS, you apparently need to remove the default FTDI drivers (same reference above). I recommend the ESP-PROG made by Espressif. Besides the usual Chinese suppliers, it is available from US mainstream distributors for $12-13 without shipping. Hi. Thank for sharing this 🙂 Great tutorial! Do you also have a tutorial on how to use esp idf in Platformio? Hi. Unfortunately, we don’t have any tutorial about that subject. Regards, Sara Is there any experience, what is the speed difference on program run/code size VS coded vs. C coded? Is it possible to handle interrupts in VS? pretty complex to setup microsoft visual studio and platformIO What is the big advantage of using with VS Code and PlatformIO IDE over the Arduino-IDE that would be worth the hassle of this setup-process? The wrapping up statement gives you the main benefits for your efforts, i will add that your programming skills will be taken to a higher level. I wish i had this when i installed it on my pc. This ia a great tutorial to get you started on what could be a career changing journey for some. Stefan: I was wondering the same thing! What is the advantage of using VS Code and PlatformIO! With the Arduino platform, I know, at time, there is issue. I have learned to deal with it. I don’t have any project that the Arduino platform doesn’t work. Hi. It is very useful if you’re setting up a web server with separated HTML, CSS and Javascript files. You can program all the files using the same software and you can open the files side by side. It also allows you to upload the files to the ESP32 or ESP8266 filesystem easily. Additionally, if you’re working on a quite complex project, it can be useful because it highlights errors, helps with autocompletion, identation, etc. Regards, Sara Thanks Brian and Sara, I did see the benefit. I will try VS and PlantformIO. Hopefully, it does not break the Arduino IDE. Thank you for the recommendation. I would love to get it running immediately Great! Try it on! 😀 Excelent Guide to start! Can not wait for a book with some full projects to fully understand it maybe multi platform and some debugging tutorials? Thanks for a great writeup! It was nice to have instructions for Windows, MacOS, and Linux. I’ve always thought the code editing and management of VSCode was so much better than the Arduino. I used the old (not VSCode) Platformio before for ESP and STM, but as Stefan mentions, it’s a bunch of overhead. As you mention, for larger projects VSCode is way better. The best reason to use platformio is to get interactive hardware debugging inside VSCode. That is a game-changer. It would be great to add another tutorial to the series on how to use hardware debug on Windows/Mac/Linux. I have an EDP-Prog (<$13) but I haven’t had time to play with it. I mean’t ESP-Prog Thanks for your comment. We are definitely planning to add some more tutorials about this subject. Regards, Sara Thank you for introducing here this new tool! It showed very useful here when I used it to create a project using ESP32 FreeRTOS (ESP-IDF). I already used the VS Code when I was studying FreeRTOS here, but without using the PlatformIO resources. Now it’s much better to use it! Hi Sara, wonderfull tutorial up to the Blink_LED tutorial. All is running ok and I thank you very much for your patience and precision. I’ve a simple question : can I copy all Arduino ESP32 projects now running with Arduino compilation in PlatformIO without any changes ( I mean instruction and declaration define etc. ) and uploading it with PLatformIO on ESP32 board ? Or it’s a long way of conversion and test ? Regards and thanks again. Hi. You can easily do that. In PlatformIO Home, select the Option “Import Arduino Project”. Tick the option “Use libraries installed by Arduino IDE”. And that’s it. Regards, Sara Thanks a lot. Very kind of you to answer to my question. You’re welcome. Regards, Sara Hi Sara, it seems to me very close to ESPhome platform used for Home Assistance. Am I wrong? Thanks again. Hi, Is it required to press the boot switch of the esp32 while downloading? I am asking so as I got: “*** [upload] Error 1 =========================================== [FAILED] Took 3.74 seconds =========================================== The terminal process “platformio ‘run’, ‘–target’, ‘upload'” terminated with exit code: 1.” Or I am missing something? Zvika Hi. Yes, you may need to press the boot button while uploading. Regards, Sara I was really waiting for this tutorial! THANKS! hope to see more about programming with VS Code. Great! I’m glad you liked it 😀 Regards, Sara I am mostly a hobbyist / tinkerer. I’ve played around with VSCode / Platformio a bit, alongside the Arduino IDE. My take on it is that VSCode / Platformio is extremely convenient for those who are writing complex code that involves (for example) writing new libraries alongside the actual Arduino or ESP code, or working with files of different kinds all next to each other (as in the article summary). And the syntax error underlining and completion tools are helpful. But I suspect that VSCode / Platformio is overkill for those who are comfortable with the Arduino IDE, are writing simple code for Arduino or ESP, and are largely following “recipes” online using pre-baked libraries. VSCode / Platformio has a learning curve in terms of figuring out how folders are organized, where your code is, what the windows do, how to properly update libraries and board configuration files, etc. Hobbyists may find it’s not worth climbing that learning curve. A short take on it would be that VSCode / Platformio is more “programmer” focused while the Arduino IDE is more “hobbyist” focused. I myself bounce back and forth between the two — quite often switch back to the Arduino IDE when I find myself frustrated with a basic problem (often board compatibility) that I don’t know how to fix in VSCode / Platformio. Hi Jordan. That’s very true. It may be overwhelming for beginners. For simpler and smaller programs Arduino IDE works just fine. Thanks for sharing your experience. Regards, Sara Have tried one of Your projects from book ordered from You. Works good in Windows, but in Linux i have problem not directly pertaining Your lesson but with Arduino IDE has problem with serial. I’m not talking about connecting board to computer’s USB, that works fine. It’s rather whether You call for “Serial.print” in code or not, when compiling it gives error: No module named ‘serial’. I understand that ESP32 needs python to work with IDE (or that I’m just assuming, correct me if I’m wrong). ESP8266 works fine. I have Python 3 installed ans also installed pyserial(with pip3 comm.) But no matter I tried it gives error again. Hi. If you’re one of our students, I suggest that you place your question on the RNTLAB forum: That way, we can better follow your issue and ask you questions to better understand what’s going on. Regards, Sara This is probably not a correct answer but you typed “Serial.print” works and “serial” does not. Might the problem be that we need to use a Capital S in Serial? I’ve made that mistake many times in Java and assume Python and Arduino are case sensitive too. Thank you for this informative tutorial! Another HUGE benefit from using PIO is the portability! When using Arduino IDE, copying a project to another computer involves adding new boards or libraries using the board and library manager (often quite a hassle to satisfy all dependencies). By using the lib_deps statement in the platformio.ini PIO just downloads missing libraries! That’s true! That’s another advantage of VS Code with PIO. Regards, Sara Hi Sara, Thanks for providing details and steps for that. I am ESP8266 and ESP32 developer and I have total 2 to 2.5 years experience for same. Till now we are using ESP32 IDF behing our own SDK and developed almost 10 to 12 products. I just want to know that VS will support for ESP32 IDF or just for Arduino? Hi. It also supports IDF. Regards, Sara I am newbie for ESP32 and keen to know in detail how to interface it with AM2301 on vscode with platformio to monitor the values both on serial and web,(without arduino) Hi Sara Thanks for this tutorial !! after som mistakes it works !! Great! I have just started using VS Studio with PlatformIO. How do I “update” external libraries specified in “lib_deps” to the latest version? In the Arduino IDE, I just click on “Manage Libs” and it updates all my specified external libraries. Hi. If you want to use the latest version of the library, you can search for the library in the Libraries tab, select the installation tab and there should be several options for the lib_deps. Usually there’s something indicating the library version. So, you just need to copy the name of the latest version. Regards, Sara I already followed the example in Windiws 10 without any problem. Only have a question: Why is required to load phyton? REgards I believe that vscode is a Python program. So to run vscode you must have Python loaded onto the computer being used. Similar to eclipse being a Java program that requires Java to run. Can we do arduino assembly on VScode? “Follow the next procedure if you need to install libraries in PlatformIO IDE.” Do you need to do this if you already have a lot of installed libraries under the Arduino IDE? Okay, yes. The libraries I’ve accumulated are within the Arduino file structure, not the PIO structure. I don’t think I want to import many of my Arduino projects into PIO. Converting .ino files and backtracking its libraries is a little bit of a pain. Going forward, on new projects, I will start using PIO instead of the arduino IDE, and I’ll give it a shot. But, the LED_blink example is a big help, and you guys have made implementing PIO pretty easy. Put me down as a PlatformIO convert. Intellisense, variable and code hinting for the most part are a big help. “Attaching” a board to a project (by way of pasting two or three lines of formatted text into a project’s platform.ini file) is a better board management practice, as are attaching libraries that may change over time. You can import older sketches into PIO, you just have to make a few changes, like adding arduino include and changing the .ino file to .cpp. Hi Donald. That’s great! I’m glad you liked using PlatformIO. It’s way easier to write code and manage libraries. Once you get used to it, you won’t want to go back 🙂 Regards, Sara I received this error after I installed the BME280 library according to the tutorial, then uploaded: “In file included from .pio\libdeps\esp32dev\Adafruit BME280 Library\Adafruit_BME280.cpp:31:0: .pio\libdeps\esp32dev\Adafruit BME280 Library\Adafruit_BME280.h:27:17: fatal error: SPI.h: No such file or directory” What is missing? Do you have #include <Arduino.h> at the very top of the sketch? Yes, it is the first line of the main.cpp sketch. I have the same issue with that library. Hi. If you’re not using the libraries in your sketch, just remove them from the plaformio.ini file. Regards, Sara After purchasing the “building Webservers” book, I installed the platform io extension into VSCODE which I’d had installed for a while. It seemed to work, but I didn’t have time to play with it. Today I opened vscode, received and update, and the PlatformIO home page doesn’t appear nor do the buttons on the status bar. I can’t click on “New Project” because it isn’t there, and no “Home” button on the status bar. I’ve uninstalled PIO, and reinstalled, I uninstalled VScode and reinstalled, nothing seems to work. I’d like to complete this course, but I’m dead in the water right now. Any suggestions?? Hi John, I don’t know exactly what happened there, but did you check wether the PlatformIO plugin is enabled? Go to the Extensions menu and check if the platformio extension is enabled. Sometimes it is installed, but is disabled. Well, I don’t have any better clues for this. There is an activateOnlyOnPlatformIOProject setting that disables PlatformIO on non PlatformIO projects. I don’t know if that is your problem, but I use the feature so all the platformio stuff doesn’t get included in my python, etc. projects. It was off when I installed originally, but maybe the default changed. You can check your settings (gear in lower right), Extensions->Platformio to see if the activateOnlyOnPlatformIOProject is set. I don’t remember now how to create a new project if the UI isn’t activated, but maybe it needs an empty (or blank line) platformio.ini. If you have a platformio.ini, in your workspace directory, then the PIO extension should activate. Thank you, yes I’ve checked all the settings, even turn that one on and off to no avail. But thanks for the reply. Hello, Do you have any keys or suggestions that help with importing Arduino files to Platformio? I have tried and there are some things that are asked by Platformio upon import that I do not understand? Thanks. DB Hi. What things are asked? Can you be a little more specific? Regards, Sara Hello Sara, Thank you for your time with an enterprise such as yours I imagine that you are very busy spreading your knowledge of physical computing and networking science. My issue was with importing Arduino IDE created files into Platformio. I have many many Arduino files and libraries and I was concerned with loosing or changing them to conform to Platformio and not being able to recover them. Libraries are quite differently handled in Platformio, but since my first question to you I have solved that riddle. I think that I answered my own questions. For now. I am gratefull to you for getting me started with Platformio. Thanks Dave Great! I’ll try to create more VS Code tutorials, so that it is easier to handle your projects. Regards, Sara Hello Sara, I am manually entering the post “Build an ESP8266 Web Server – Code and Schematics (NodeMCU)” in VS Code and PlatformIO, but I have a problem. I enter: const char* ssid = “XXXXXXXXXXXX”; const char* password = “HHHHHHHH”; and at the moment of saving it it becomes: const char *ssid = “XXXXXXXXXXXX”; const char *password = “HHHHHHHHH”; Is there any way to solve it? If not, you will have to do everything with the Arduino IDE Thank you for your time, Carles Hi Carles. I’m sorry but I didn’t understand your issue. Arduino IDE sketches do work on PlatformIO. Regards, Sara Hi Sara, I write “const char“, a space and “ssid”. When I save it it becomes “const char”, a space and “ssid”. The asterisk has passed from the end of the word “char” to the beginning of “ssid”. This is the problem. Regards, Carles Sara, I have taken out the quotes because the asterisks were lost when I answered. In the initial post you can check it. I write const char*, a space and ssid. When I save it it becomes const char, a space and *ssid. The asterisk has passed from the end of the word char to the beginning of ssid. Regards, Carles The VSCode editor has a formatting feature to reformat code to a consistent notation, “prettier”, and seems that it’s enabled. Google “How to disable prettier in VSCode”. Click the gear icon in the lower left corner and you’ll get the settings then look for prett and format. (OR just look at text editor settings.) You can also disable the extension. There is a setting to format on save, which seems to be what is happening to you. It could be a different extension than prettier, so you might need to check which extensions are enabled. Hi Carl, I have uninstalled all the extensions except C/C++ and PlatformIO. Continue changing the asterisk. I use it in MacOS Mojave 10.14.6, Spanish version. Is there anyone who has the same configuration and it doesn’t happen the same? Thanks Thanks for the clear write-up. I noticed many asking why VSCode over arduino…. As an old grey-beard I feel compelled to point out that one of the true great features of VSCode is the git integration. Having built-in source control is truely a blessing. being aware of and using source control is one of the things that separates professional developers from hobby coders. For those unfamiliar with git or source control, git is the premier means of managing source code as it evolves; and it can save your bacon and it removes the fear of breaking your program when you want to experiment or are just learning a new platform. It truely is magic. I urge everyone to learn it, use it, live it. It will make your development life much easier. The third icon down (the branch one) is the gateway. Happy Trails.. followed your instruction step-by-step (thank you) I got the message concerning #include <Arduino.h> “The include file not found in browse.path” any idea what to change, what to add? Thank you! hi, my esp32 board was working fine. I was working in arduino. I followed your instructions for PlatformIO and when I uploaded my board got a fatal error. A fatal error occurred: Failed to connect to ESP32: Timed out waiting for packet header *** [upload] Error 2 What can I do to fix this error and upload to my board? I’m on Ubuntu 20.04.2 LTS. Thank you Hi. Press the ESP32 on-board BOOT button when you start seeing a lot of dots on the debugging window. Regards, Sara Hi Sara, I am pushing the BOOT button repeatedly but I keep getting the same error… I also used the capacitor technique I saw on the site’s instructions, but it did not work either… When I did a search about this error, I found this: MD5 of file does not match data in flash! What do you think is happening and how do you think it can be fixed ? Thank you ! Will Hi. I’m not sure what is happening. Do you have any peripherals connected to your board? If you have, you should disconnect them before uploading the code. Regards, Sara I am working with VSCode although I miss how to configure the partitions like the Arduino. I am using an ESP32 and would like to choose Minimal SPIFFS (1.9MB APP with OTA / 190KB SPIFFS) for OTA updates. Thanks, great job greetings. Hi. I think this is what you must be looking for: Regards, Sara That’s it!! well thank you very much. All the best. Hi! Thanks for the tutorial. I was able to follow this and get the LED flashing, but I’m a bit confused as to why Python was needed, seeing as the code is written in C++. I found this article because I was hoping to program an ESP32 with MicroPython via VSCode. Is there a way to do this? Hi. Yes, there is an extension to write MicroPython code in VS Code. However, there isn’t an “interface” with buttons to upload the code and so on. You’ll have to do it using the Terminal. Regards, Sara Thanks for your reply 🙂 So why is Python necessary for this tutorial? By the way, I found RT-Thread which is a MicroPython extension for VSCode, works really well and has full UI Hi. Here’s the reason: I didn’t know about RT-Thread. I have to take a look. Regards, Sara Hi Sara: can you tell me about this error: ____could not open port ‘COM5’: could not open port ‘COM5’: PermissionError(13, ‘Accès refusé.’, None, 5)_____ Thak you Hi. That means that VS Code can’t establish a serial connection with your board. That may be because you have the board connected on another program like Arduino IDE. Close Arduino IDE. It may also be the case that VS Code can’t find the right COM port. Check that it is connecting to the right port. If it isn’t, you can manually set a COM port on the platformio.ini file. Add the following to the platformio.ini file: upload_port = COMX Replace X with the number of the COM port. I hope this helps. Regards, Sara Ciao come posso modificare la libreria dei display Nextion per usarla con PIO? vedi tutorial rnd per usare nextion e esp32 Hi Is ota programming supported in PlatformIO? BR Jesper Yes.
https://randomnerdtutorials.com/vs-code-platformio-ide-esp32-esp8266-arduino/?replytocom=499889
CC-MAIN-2021-31
refinedweb
5,988
74.29
Allows to highlight search results on one or more fields. The implementation uses either the lucene highlighter, fast-vector-highlighter or postings-highlighter. The following is an example of the search request body: { "query" : {...}, "highlight" : { "fields" : { "content" : {} } } } In the above case, the content field will be highlighted for each search hit (there will be another element in each search hit, called highlight, which includes the highlighted fields and the highlighted fragments). In order to perform highlighting, the actual content of the field is required. If the field in question is stored (has store set to true in the mapping) it will be used, otherwise, the actual _source will be loaded and the relevant field will be extracted from it. The _all field cannot be extracted from _source, so it can only be used for highlighting if it mapped to have store set to true. The field name supports wildcard notation. For example, using comment_* will cause all fields that match the expression to be highlighted. If index_options is set to offsets in the mapping the postings highlighter will be used instead of the plain highlighter. The postings highlighter: - Is faster since it doesn’t require to reanalyze the text to be highlighted: the larger the documents the better the performance gain should be - Requires less disk space than term_vectors, needed for the fast vector highlighter - Breaks the text into sentences and highlights them. Plays really well with natural languages, not as well with fields containing for instance html markup - Treats the document as the whole corpus, and scores individual sentences as if they were documents in this corpus, using the BM25 algorithm Here is an example of setting the content field to allow for highlighting using the postings highlighter on it: { "type_name" : { "content" : {"index_options" : "offsets"} } } Note that the postings highlighter is meant to perform simple query terms highlighting, regardless of their positions. That means that when used for instance in combination with a phrase query, it will highlight all the terms that the query is composed of, regardless of whether they are actually part of a query match, effectively ignoring their positions. The postings highlighter does support highlighting of multi term queries, like prefix queries, wildcard queries and so on. On the other hand, this requires the queries to be rewritten using a proper rewrite method that supports multi term extraction, which is a potentially expensive operation. If term_vector information is provided by setting term_vector to with_positions_offsets in the mapping then the fast vector highlighter will be used instead of the plain highlighter. The fast vector highlighter: - Is faster especially for large fields (> 1MB) - Can be customized with boundary_chars, boundary_max_scan, and fragment_offset(see below) - Here is an example of setting the content field to allow for highlighting using the fast vector highlighter on it (this will cause the index to be bigger): { "type_name" : { "content" : {"term_vector" : "with_positions_offsets"} } } The type field allows to force a specific highlighter type. This is useful for instance when needing to use the plain highlighter on a field that has term_vectors enabled. The allowed values are: plain, postings and fvh. The following is an example that forces the use of the plain highlighter: { "query" : {...}, "highlight" : { "fields" : { "content" : {"type" : "plain"} } } } Added in 1.0.0.RC1. Forces the highlighting to highlight fields based on the source even if fields are stored separately. Defaults to false. { "query" : {...}, "highlight" : { "fields" : { "content" : {"force_source" : true} } } } By default, the highlighting will wrap highlighted text in <em> and </em>. This can be controlled by setting pre_tags and post_tags, for example: { "query" : {...}, "highlight" : { "pre_tags" : ["<tag1>"], "post_tags" : ["</tag1>"], "fields" : { "_all" : {} } } } Using the fast vector highlighter there can be more tags, and the "importance" is ordered. { "query" : {...}, "highlight" : { "pre_tags" : ["<tag1>", "<tag2>"], "post_tags" : ["</tag1>", "</tag2>"], "fields" : { "_all" : {} } } } There are also built in "tag" schemas, with currently a single schema called styled with the following pre_tags: "> and </em> as post_tags. If you think of more nice to have built in tag schemas, just send an email to the mailing list or open an issue. Here is an example of switching tag schemas: { "query" : {...}, "highlight" : { "tags_schema" : "styled", "fields" : { "content" : {} } } } An encoder parameter can be used to define how highlighted text will be encoded. It can be either default (no encoding) or html (will escape html, if you use html highlighting tags). Each field highlighted can control the size of the highlighted fragment in characters (defaults to 100), and the maximum number of fragments to return (defaults to 5). For example: { "query" : {...}, "highlight" : { "fields" : { "content" : {"fragment_size" : 150, "number_of_fragments" : 3} } } } The fragment_size is ignored when using the postings highlighter, as it outputs sentences regardless of their length. On top of this it is possible to specify that highlighted fragments need to be sorted by score: { "query" : {...}, "highlight" : { "order" : "score", "fields" : { "content" : {. { "query" : {...}, "highlight" : { "fields" : { "_all" : {}, "bio.title" : {"number_of_fragments" : 0} } } } When using fast-vector-highlighter than specified as it tries to break on a word boundary. When using the postings highlighter it is not possible to control the actual size of the snippet, therefore the first sentence gets returned whenever no_match_size is greater than 0. { "query" : {...}, "highlight" : { "fields" : { "content" : { "fragment_size" : 150, "number_of_fragments" : 3, "no_match_size": 150 } } } } It is also possible to highlight against a query other than the search query by setting highlight_query. This is especially useful if you use a rescore query because those are not taken into account by highlighting by default. Elasticsearch does not validate that highlight_query contains the search query in any way so it is possible to define it so legitimate query results aren’t highlighted at all. Generally it is better to include the search query in the highlight_query. Here is an example of including both the search query and the rescore query in highlight_query. { "fields": [ "_id" ], "query" : { "match": { "content": { "query": "foo bar" } } }, "rescore": { "window_size": 50, "query": { "rescore_query" : { "match_phrase": { "content": { "query": "foo bar", "phrase_slop": 1 } } }, "rescore_query_weight" : 10 } }, "highlight" : { "order" : "score", "fields" : { "content" : { "fragment_size" : 150, "number_of_fragments" : 3, "highlight_query": { "bool": { "must": { "match": { "content": { "query": "foo bar" } } }, "should": { "match_phrase": { "content": { "query": "foo bar", "phrase_slop": 1, "boost": 10.0 } } }, "minimum_should_match": 0 } } } } } } Note that the score of text fragment in this case is calculated by the Lucene highlighting framework. For implementation details you can check the ScoreOrderFragmentsBuilder.java class. On the other hand when using the postings highlighter the fragments are scored using, as mentioned above, the BM25 algorithm. Highlighting settings can be set on a global level and then overridden at the field level. { "query" : {...}, "highlight" : { "number_of_fragments" : 3, "fragment_size" : 150, "tag_schema" : "styled", "fields" : { "_all" : { "pre_tags" : ["<em>"], "post_tags" : ["</em>"] }, "bio.title" : { "number_of_fragments" : 0 }, "bio.author" : { "number_of_fragments" : 0 }, "bio.content" : { "number_of_fragments" : 5, "order" : "score" } } } } require_field_match can be set to true which will cause a field to be highlighted only if a query matched that field. false means that terms are highlighted on all requested fields regardless if the query matches specifically on them. When highlighting a field using the fast vector highlighter, boundary_chars can be configured to define what constitutes a boundary for highlighting. It’s a single string with each boundary character defined in it. It defaults to .,!? \t\n. The boundary_max_scan allows to control how far to look for boundary characters, and defaults to 20. The Fast Vector Highlighter can combine matches on multiple fields to highlight a single field using matched_fields. content is analyzed by the analyzer and content.plain is analyzed by the standard analyzer. { "query": { "query_string": { "query": "content.plain:running scissors", "fields": ["content"] } }, "highlight": { "order": "score", "fields": { "content": { "matched_fields": ["content", "content. { "query": { "query_string": { "query": "running scissors", "fields": ["content", "content.plain^10"] } }, "highlight": { "order": "score", "fields": { "content": { "matched_fields": ["content", "content.plain"], "type" : "fvh" } } } } The above highlights "run" as well as "running" and "scissors" but still sorts "running with scissors" above "run with scissors" because the plain match ("running") is boosted. { "query": { "query_string": { "query": "running scissors", "fields": ["content", "content.plain^10"] } }, "highlight": { "order": "score", "fields": { "content": { "matched_fields": ["content.plain"], "type" : "fvh" } } } } The above query wouldn’t highlight "run" or "scissor" but shows that it is just fine not to list the field to which the matches are combined ( content) in the matched fields. . There is a small amount of overhead involved with setting matched_fields to a non-empty array so always prefer "highlight": { "fields": { "content": {} } } to "highlight": { "fields": { "content": { "matched_fields": ["content"], "type" : "fvh" } } } The fast-vector-highlighter has a phrase_limit parameter that prevents it from analyzing too many phrases and eating tons of memory. It defaults to 256 so only the first 256 matching phrases in the document scored considered. You can raise the limit with the phrase_limit parameter but keep in mind that scoring more phrases consumes more time and memory. If using matched_fields keep in mind that phrase_limit phrases per matched field are considered.
https://www.elastic.co/guide/en/elasticsearch/reference/1.3/search-request-highlighting.html
CC-MAIN-2019-26
refinedweb
1,435
60.45
#include <Wire.h> #include <LiquidCrystal_I2C.h>// Set the LCD address to 0x27 for a 16 chars and 2 line displayLiquidCrystal_I2C lcd(0x27, 16, 2);void setup() { lcd.init(); lcd.backlight(); lcd.setCursor(0,0); lcd.print("LCD & I2C"); delay(500); lcd.setCursor(0,1); lcd.print("**********");}void loop() { lcd.backlight(); lcd.print("Hello"); delay(5000); lcd.noBacklight(); delay(5000);} If the backlight works, the address (0x27) is correct. (That sketch doesn't attempt to control the backlight on & off, so it seems to be an unknown) There are several different backpack designs. And then there is the pin mappings in the library that must match the way pcf8574 pins are connected to the lcd and backlight circuit. The LiquidCrystal_I2C library being used has those pin mappings hard coded. Thomas wrote: "Working only backline/ nobacklight" (note: I assume "backline" was a typo), so there is communication between the Arduno, the backpack and the LCD. That means the I2C address is correct. I read somewhere on this forum that most LCD's have the same pinout, so I didn't expect any problems there.
https://forum.arduino.cc/index.php?topic=623332.msg4222729
CC-MAIN-2020-29
refinedweb
182
66.74
Is it possible to make socket.io broadcast to all users of a namespace who are in both room A and room B but not those who are just in room A or room B? If not, how would I go about implementing this myself? Is there a way to retrieve all users in a namespace who are in a given room? I am working with socket.io 1.0 in node Edit: If there is no native method, how would I go about to create my own syntax such as: socket.broadcast.in('room1').in('room2').emit(...)? You can look up all the users of a room using (ref How to update socket object for all clients in room? (socket.io) ) var clients = io.sockets.adapter.room["Room Name"] So given two arrays for your 2 rooms’ roster list, you can compute the intersection using something like the answer here (ref: Simplest code for array intersection in javascript) And finally you can take that list of users in both rooms and emit events using (ref: How to update socket object for all clients in room? (socket.io) ) //this is the socket of each client in the room. var clientSocket = io.sockets.connected[clientId]; //you can do whatever you need with this clientSocket.emit('new event', "Updates"); The alternate ofcourse is to have hidden rooms, where you maintain a combination of all rooms, and add users to those rooms behind the scenes, and then you are able to just simply emit to those hidden rooms. But that suffers from an exponential growth problem. There is no in-built way to do this. So first let’s look up how the broadcast works: 206…221-224…230 this.adapter.broadcast(packet, { rooms: this.rooms, flags: this.flags }); Now we know every broadcast creates a bunch of temp objects, indexOf lookups, arguments slices… And then calls the broadcast method of the adapter. Lets take a look at that one: 111-151 Now we are creating even more temp objects and loop through all clients in the rooms or all clients if no room was selected. The loop happens in the encode callback. That method can be found here: But what if we are not sending our packets via broadcast but to each client separately after looping through the rooms and finding clients that exist both in room A and room B? socket.emit is defined here: Which brings us to the packetmethod of the client.js: Each directly emitted packet will be separately encoded, which again, is expensive. Because we are sending the exact same packet to all users. To answer your question: Either change the socket.io adapter class and modify the broadcast method, add your own methods to the prototype or roll your own adapter by inheriting from the adapter class). ( var io = require('socket.io')(server, { adapter: yourCustomAdapter });) Or overwrite the joinand leave methods of the socket.js. Which is rather convenient considering that those methods are not called very often and you don’t have the hassle of editing through multiple files. Socket.prototype.join = (function() { // the original join method var oldJoin = Socket.prototype.join; return function(room, fn) { // join the room as usual oldJoin.call(this, room, fn); // if we join A and are alreadymember of B, we can join C if(room === "A" && ~this.rooms.indexOf("B")) { this.join("C"); } else if(room === "B" && ~this.rooms.indexOf("A")) { this.join("C"); } }; })(); Socket.prototype.leave = (function() { // the original leave method var oldLeave = Socket.prototype.leave; return function(room, fn) { // leave the room as usual oldLeave.call(this, room, fn); if(room === "A" || room === "B") { this.leave("C"); } }; })(); And then broadcast to C if you want to broadcast to all users in A and B. This is just an example code, you could further improve this by not hard coding the roomnames but using an array or object instead to loop over possible room combinations. As custom Adapter to make socket.broadcast.in("A").in("B").emit()work: var Adapter = require('socket.io-adapter'); module.exports = CustomAdapter; function CustomAdapter(nsp) { Adapter.call(this, nsp); }; CustomAdapter.prototype = Object.create(Adapter.prototype); CustomAdapter.prototype.constructor = CustomAdapter; CustomAdapter.prototype.broadcast = function(packet, opts){ var rooms = opts.rooms || []; var except = opts.except || []; var flags = opts.flags || {}; var packetOpts = { preEncoded: true, volatile: flags.volatile, compress: flags.compress }; var ids = {}; var self = this; var socket; packet.nsp = this.nsp.name; this.encoder.encode(packet, function(encodedPackets) { if (rooms.length) { for (var i = 0; i < rooms.length; i++) { var room = self.rooms[rooms[i]]; if (!room) continue; for (var id in room) { if (room.hasOwnProperty(id)) { if (~except.indexOf(id)) continue; socket = self.nsp.connected[id]; if (socket) { ids[id] = ids[id] || 0; if(++ids[id] === rooms.length){ socket.packet(encodedPackets, packetOpts); } } } } } } else { for (var id in self.sids) { if (self.sids.hasOwnProperty(id)) { if (~except.indexOf(id)) continue; socket = self.nsp.connected[id]; if (socket) socket.packet(encodedPackets, packetOpts); } } } }); }; And in your app file: var io = require('socket.io')(server, { adapter: require('./CustomAdapter') }); io.sockets.adapter.room["Room A"].forEach(function(user_a){ io.sockets.adapter.room["Room B"].forEach(function(user_b){ if(user_a.id == user_b.id){ user_a.emit('your event', { your: 'data' }); } }); });
https://exceptionshub.com/socket-io-broadcast-only-to-users-who-are-in-room-a-and-b.html
CC-MAIN-2021-21
refinedweb
868
60.31
Red Hat Bugzilla – Bug 442323 removal of client package breaks bcfg2-server package modules Last modified: 2008-04-14 09:06:27 EDT Description of problem: a) server depends on client, considering that there are problems in packaging, you probably don't want problems to reconfigure your production server. So far it appears, that there is no technical reason (that is, like module dependency) to make them to depend on each other. (judging it by rpm -ql listing) b) Removing it using --nodeps breaks the bcfg2-server package's modules for no reason. # rpm -qf /usr/lib/python2.4/site-packages/Bcfg2/__init__.py bcfg2-0.9.5.7-1.el5 # rpm -e bcfg2 --nodeps # service bcfg2-server start Starting bcfg2-server: Traceback (most recent call last): File "/usr/sbin/bcfg2-server", line 6, in ? import Bcfg2.Server.Plugins.Metadata ImportError: No module named Bcfg2.Server.Plugins.Metadata Version-Release number of selected component (if applicable): reinstalling the client fixes the issue. How reproducible: always. Steps to Reproduce: 1. rpm -e --nodeps bcfg2 2. service bcfg2-server restart 3. bang Actual results: traceback Expected results: you don't need to install web browser in order to have apache running in your server, why would you need a configuration client. Additional info: I guess splitting up the python module dirs to Bcfg2 --> Bcfg2-Client,Bcfg2-Server would allow both have their own __init__.py files and remove the pkg dependency. That's probably an upstream change (imports, install) If you don't want to run the configuration client on your server, there are methods within Bcfg2 to disable the client and preventing it from making any changes on the server. Until upstream reorganizes the code, it makes sense to put all of the common code into the client package and have the server package require it. That's something that you should discuss directly with upstream: I've found them to be extremely receptive to well-reasoned arguments, especially if accompanied by patches. in IRC i got some explanation: That isn't really a fixable problem. we can change things so that we had a separate path to server and client modules, but the server depends on modules included in the client as well and in some cases, there is a hard (versioned) dependency between the server and client code so the server dependency on the client is really there for a reason. Well, this is common problem and like in samba, it has samba-common pkg for shared stuff and they all are distributed together, under a same version. It's just a matter of making it possible to split them into different pkgs with the installation.
https://bugzilla.redhat.com/show_bug.cgi?id=442323
CC-MAIN-2017-13
refinedweb
447
52.19
These are chat archives for rust-lang/rust struct Node { ptr: std::rc::Weak<Node>,} struct Fixturethat is created as the first thing in the test and the cleanup can go into its dropimplementation. But I was thinking if it made sense to have somewhat more integrated support. Defaultand possibly Drop(the fixture), I could annotate its methods with #[test]. In that case the compiler would first create an instance of the fixture with the Defaultimplementation, run the test and then drop it. I think it feels somewhat natural, but does anyone see a problem? Or, if I wanted to make an RFC, should I first consult with somebody, or simply write it and create a merge request? def teardown(self)and def setup(self)into a class inheriting from unittest.TestCase. But it's a long time since I wrote something bigger in python and it may have changed. struct TestFixture { test_data: usize, } impl Default for TextFixture { fn default() -> Self { Self { test_data: 42 } } } // impl Drop needed here... impl TextFixture { #[test] fn test(&self) { assert_eq!(self.test_data, 42); } } struct TempDirFixture { ... } #[test] fn test_foo(tmpdir: TempDirFixture) { } setUp/tearDownstyle class hooks of JUnit, which couple your fixtures to single inheritance model. @vorner I think you can even implement "fixtures as parameters" without too much magic.... Like, I can imaging something along the lines of impl<F1, F2> Test for FnOnce(F1, F2) where F1: TestFixture, F2: TestFixture. The awkward thing about this approach though is that sometimes you need to parametrize your fixtures... That is, Default does not work, and it's not obvious how to pass arguments nicely. fn(isize, isize) -> isizehere instead of boxing them as Fn(isize, isize) -> isizetrait objects operator_*functions all have different types (box of that first closure, box of that second closure, ..) glutin::VirtualKeyCodewithout having a blank space in the docs.
https://gitter.im/rust-lang/rust/archives/2017/09/25?at=59c8ea0bbac826f054f7ca91
CC-MAIN-2019-47
refinedweb
306
64
Hi, On Tue, 14 Jan 2014, Nordgren, Bryce L -FS wrote: Hi Dimitri,Just to be sure I understand. You have internal users - they are in AD. You have external users - they are in LDAP. You merge two directories and you want to replace this setup with IPA.Yes.It seems that to support your use case you would need to make the external users be IPA users and make AD and IPA trust each other.I think I concur about migrating my external users into IPA and making IPA trust AD. I may be ignorant of some AD nuance, but I do not see why AD needs to trust IPA. AD does not need to trust my LDAP clients currently. IPA needs to be able to look up users and groups in AD. To do so, it uses Kerberos authentication against AD's Global Catalog services with own credentials (per each IPA host). We are using cross-realm Kerberos trust here, AD DC trusts cross-realm TGT issued by IPA KDC and vice versa, so IPA hosts can bind as their own identity (host/...) to AD. Since we don't implement fully all services needed to grant privileges beyond read-only in AD, these binds to AD Global Catalog become read-only. They are still required. An alternative would have been to always keep an account in AD for each IPA host that needs to query user and group identities from AD. We decided to go with the cross-realm Kerberos trust instead since it gives better way of privilege separation. Cross-realm Kerberos trust is known as cross-forest domain trust in AD speak since there are more protocol layers than Kerberos involved (SMB protocol, in particular, is used to set up and verify trust relationship). Once we implement AD GC service, AD admins will be able to subject IPA users/hosts to further limit their access to other AD services beyond simple read-only access to AD LDAP and SMB services. As result, in future more fine-grained privilege and security separation between AD and IPA will be possible. Also if external users do not authenticate using Kerberos (for example they always use a special portal) then it does not matter what trust is between AD and IPA because those users will not have kerberos tickets that are leveraged in SSO in trust case.I want to be able to point either an LDAP or a Kerberos client at IPA, and have it authenticate my "enterprise" and "external" users for me. I'm not going to tangle with SSO at the moment. Right now, we're just establishing an identity store. That is what provided by IPA's AD trusts. IPA machines can resolve identities of the users and groups in AD and can authenticate those users on logons, subject to HBAC policies. IPA can trust AD. Formally it is a mutual trust but in reality IPA does not have global catalog support for users in IPA to be able to access the resources in AD.In many of the tutorials/HOWTOs, I see that there is a requirement to provide credentials having the permission to add a computer to the domain, or being a member of an AD administration group. I'm a lowly standard "User" in the AD. I don't know if that means I can add a computer to the domain or not. I know I lack the ability to edit AD entries that aren't mine, so I really need a solution that does not require creating a trust relationship inside AD. Both AD integration solutions we have (synchronization and cross-forest domain trusts) assume having higher level access privileges at the time integration is set up. I'm unaware of other mechanisms that would give you the same flexibility and level of privilege separation between the AD and IPA domains. Having a standard 'User' account in AD only entitles you to join up to 10 machines in AD. These machine will become a part of AD domain and are subject of their policies which are quite extended by default. Cross-forest domain trusts, on the other hand, are subject to inter-domain trust relationship policies which are better constrained. One could try to fiddle with AD-joined machine accounts to represent IPA hosts but it is very much uncharted territory since there will be no integration whatsoever on any of IPA features (access controls to IPA services, ID allocation, etc) and everything will need to be set up and maintained manually, including periodical refreshes of the machine accounts. In addition, Kerberos authentication will simply not work as AD has certain assumption over DNS namespace mapping to Kerberos realms. Is there a way for me to comment out the AD->IPA trust creation, or would that break the IPA->AD trust? The latter, since AD->IPA part of the trust is used to query AD users and groups. In other words, it is used to provide the key resources needed to operate IPA->AD trust part. -- / Alexander Bokovoy _______________________________________________ Freeipa-users mailing list Freeipa-users@redhat.com
https://www.mail-archive.com/freeipa-users@redhat.com/msg09895.html
CC-MAIN-2019-04
refinedweb
855
59.74
When we first saw [Ben Jojo’s] post about the Internet inside EvE Online, we didn’t think we’d be that interested. We don’t play EvE — a massively multiplayer game. But it turns out, the post is really about understanding BGP (Border Gateway Protocol) and how it helps route traffic in large networks. The best part? He actually simulates a network with 8,000 nodes to test out what he’s talking about. Obviously, you wouldn’t want to fire up 8,000 Raspberry Pi computers for such an experiment. Using Buildroot, he set up a very small Linux image that had the bare minimum required to run the tests. The qemu provided virtualization, including an obscure feature that allows you to transfer data between virtual machines using UDP. The whole thing ran on some pretty beefy hardware in the cloud. Sure, you could have provisioned 8,000 cloud instances, but that would run into some serious money pretty fast, we imagine. As a wrap-up, he even uses BGP to model his local mass transit system. While it might seem odd to model a transit system using BGP, this isn’t the strangest thing he’s done with it. If you want to follow along though, all the code is sitting on GitHub. If you haven’t dealt with large networks before, you might not be familiar with BGP. Most people understand how DNS converts host names to IP addresses. But how does a packet addressed to an IP address in New York City find its way from your computer in Pasadena to the Big Apple? You can find out in the post, but the simple answer is that BGP builds routing tables so that a gateway you connect to can look up the IP address and discover a path that starts with a router it connects to and ends with one that connects to the New York server. It turns out that even if you don’t play EvE, the post is a fun read and you’ll learn something about how traffic flows on the Internet that you could apply to big systems you might create. Even if they are virtual. 3 thoughts on “Learn About BGP With The Internet Of EvE” You could also use net namespaces to get a new tcp/ip stack each and interconnect them by using openvswitch. I’ve no tried to get 8000 of them though… The least expensive way to simulate something of this size would probably be ultralight containers using nspawn. I haven’t been to 8k containers before, but been past 1k on 32 cores and 64gb of memory with pretty minimal resource impact. If there is heavy IO generated this won’t work though, as this is the only real bottleneck. In any case you don’t need the cloud, you can do this on pedestrian server hardware. If you have unused server hardware at hand, you can. For such experiments, cloud is the best. If I had unused server, I’d quickly find use for it.
https://hackaday.com/2019/02/11/learn-about-bgp-with-the-internet-of-eve/
CC-MAIN-2020-34
refinedweb
512
69.92
Hey everyone, new to java here some troubles getting this down mostly step 4 i believe i have everything else correct not sure though. 1. Create a one-dimensional array of 99 double values. Then, use a for loop to add a random number from 0 to 100 to each element in the array. For each value, use the random method of the Math class to get a double value between 0.0 and 1.0, and multiply it by 100. 2. Use an enhanced for loop to sum the values in the array. Then, calculate the average value and print that value on the console followed by a blank line. Compile and test this class. 3. Use the sort method of the Arrays class to sort the values in the array, and print themedian value (the 50th value) on the console followed by a blank line. Then, test this enhancement. 4 .Print the 9th value of the array on the console and every 9th value after that. Then,test this enhancement Code : import java.util.Arrays; public class ArrayTestApp { public static void main(String[] args) { double[] testArray = new double [99]; //add a random number to each element in the array for (int i=0; i < testArray.length; i++) testArray[i] = 100.0*Math.random(); //sum the values and print out the average double average = 0.0; for(int i = 0; i < testArray.length; i++) average += testArray[i]; average /= 99; System.out.println("Average is: " + average); System.out.println(); //sort the values and print the median Arrays.sort(testArray); System.out.println("Median is: " + testArray[testArray.length/2]); System.out.println(); //print the 9th value and every 9th value after } }
http://www.javaprogrammingforums.com/%20whats-wrong-my-code/15338-help-one-dimensional-array-printingthethread.html
CC-MAIN-2014-15
refinedweb
280
60.01
List of Build Options This page lists the full set of options that - log_filename If specifies, all of the output (such as print statemetns and error messages) is written to a file. The $USER_APPDATA/prefix can be used to write refer to the AppData directory of the current user. - log_append The default is to erase the log file every time the application is re-run. If this is set to True, it will instead preserve the existing contents and instead append to the end of the log file. - log_filename_strftime New in Panda3D 1.10.9. If set to true, the log_filenamestring can contain additional formatting parameters containing the current date or time, such as $USER_APPDATA/My Game/logs/%Y-%m-%d.log. - platforms A list of PEP 425 platform tags to build applications for. The default differs on the version of Python used. See Building Binaries for an explanation and a list of options. - plugins A list of dynamically loaded Panda3D plug-ins included with the built applications. A list is available on Building Binaries. - requirements_path A path to a requirements.txt file to use with PIP when fetching wheels (defaults to ./requirements.txt) - use_optimized_wheels If set, try to download optimized wheels for Panda3D using an extra index url (defaults to True). These optimized builds of Panda3D are built without extra debug information and error checks; these are useful when developing a Panda3D application, but take up more disk space and run slower, so they are disabled in the optimized wheels. Optimized wheels are versioned such that they will have higher priority than regular wheels of the same version, but will have less priority than a newer version of a regular wheel. In other words, if the latest available version does not have an optimized wheel available, a regular wheel is used instead. - optimized_wheel_index The extra index url to use to find optimized wheels (Panda3D will try to set a reasonable default if this is not set) - icons New in Panda3D 1.10.4. A dictionary mapping gui_apps/console_apps keys to a list of images from which an icon file is generated. This list should contain versions the same image at different resolutions. Panda3D will automatically resize the image to provide for missing resolutions if necessary, so it is possible (but not recommended) to specify only one high-resolution image. If “*” is used as key, sets the icons for all included apps. - file_handlers A dictionary with keys matching extensions and values being functions of the form: def func(build_cmd, srcpath, dstpath): The function is run when encountering a file with the given extension. User-defined file handlers for an extension override the default handler. By default, there is only one file handler registered: for .egg files, which runs egg2bam.
https://docs.panda3d.org/1.10/python/distribution/list-of-build-options
CC-MAIN-2022-27
refinedweb
459
54.32
STAT 19000: Project 1 — Spring 2022 Motivation: Last semester each project was completed in Jupyter Lab from ondemand.brown.rcac.purdue.edu. Although our focus this semester is on the use of Python to solve data-driven problems, we still get to stay in the same environment. In fact, Jupyter Lab is Python-first. Now instead of using the f2021-s2022-r kernel, instead select the f2021-s2022 kernel. Context: In this project we will re-familiarize ourselves with Jupyter Lab and its capabilities. We will also introduce Python and begin learning some of the syntax. Scope: Python, Jupyter Lab Dataset(s) The following questions will use the following dataset(s): /depot/datamine/data/noaa/*.csv Questions Question 1 Let’s start the semester by doing some basic Python work, and compare and contrast with R. First, let’s learn how to run R code in our regular, non-R kernel, f2021-s2022. In a cell, run the following code in order to load the extension that allows us to run R code. %load_ext rpy2.ipython Next, in order to actually run R code, we need to place the following in the first line of every cell where we want to run R code: %%R. You can think of this as declaring the code cell as an R code cell. For example, the following will successfully run in our f2021-s2022 kernel. %%R my_vector <- c(1,2,3,4,5) my_vector Great! Run the cell in your notebook to see the output. Now, let’s perform the equivalent operations in Python! my_vector = (1,2,3,4,5) my_vector As you can see — the output is essentially the same. However, in Python, there are actually a few "primary" ways you could do this. my_tuple = (1,2,3,4,5,) my_tuple my_list = [1,2,3,4,5,] my_list import numpy as np my_array = np.array([1,2,3,4,5]) my_array The first two options are part of the Python standard library. The first option is a tuple, which is a list of values. A tuple is immutable, meaning that once you create it, you cannot change it. my_tuple = (1,2,3,4,5) my_tuple[0] = 10 # error! The second option is a list, which is a list of values. A list is mutable, meaning that once you create it, you can change it. my_list = [1,2,3,4,5] my_list[0] = 10 my_list # [10,2,3,4,5] The third option is a numpy array, which is a list of values. A numpy array is mutable, meaning that once you create it, you can change it. In order to use numpy arrays, you must import the numpy package first. numpy is a numerical computation library that is optimized for a lot of the work we will be doing this semester. With that being said, its best to get to learn about the basics in Python first, as a lot can be accomplished without using numpy. For this question, read as much as you can about tuples and lists, and run the examples we provided above. Code used to solve this problem. Output from running the code. Question 2 In general, tuples are used when you have a set of known values that you want to store and access efficiently. Lists are used when you want to do the same, but you have the need to manipulate the data within. Most often, lists will be your go-to. In Python, lists are an object. Objects have methods. Methods are most simply defined as functions that are associated with and operate on the data (usually) within the object itself. Here you can find a list of the list methods. For example, the append method adds an item to the end of a list. Methods are called using dot notation. The following is an example of using the append method and dot notation to add the number 99 to the end of our list, my_list. my_list = [1,2,3,4,5] my_list.append(99) my_list # [1,2,3,4,5,99] Create a list called my_list with the values 1,2,3,4,5. Then, use the list methods to change my_list to contain the following values, in order: 7,5,4,3,2,1,6. Do not manually set values using indexing — just use the list methods. Code used to solve this problem. Output from running the code. my_list = [1,2,3,4,5] my_list.append(7) my_list.reverse() my_list.append(6) my_list [7, 5, 4, 3, 2, 1, 6] Question 3 Great! You may have noticed (or already know) that to get the first value in a list (or tuple) we would do my_list[0]. Recall that in R, we would do my_list[1]. This is because Python has 0-based indexing instead of 1-based indexing. While at first this may be confusing, many people find it much easier to use 0-based indexing than 1 based indexing. Use indexing to print the values 7,4,2,6 from the modified my_list in the previous question. Use indexing to print the values in reverse order without using the reverse method. Use indexing to print the second through 4th values in my_list (5,4,3). Code used to solve this problem. Output from running the code. my_list[::2] my_list[::-1] my_list[1:4] [7, 4, 2, 6] [6, 1, 2, 3, 4, 5, 7] [5, 4, 3] Question 4 Great! If you have 1 takeaway from the previous 3 questions it should be that when you see [] think lists. When you see () think tuples (or generators, but ignore this for now). Its not a Data Mine project without data. After we get through some basics of Python, we will be primarily working with data using the pandas and numpy libraries.With that being said, there is no reason not to do some work manually in the meantime! Okay! Let’s get started with our noaa weather data. The following is a very small sample of the /depot/datamine/data/noaa/2020.csv dataset. Since we aren’t using the pandas library, we need to use something in order to bring the data into Python. In this case, we will use the csv library — a library used for reading and writing dsv (data separated value) data. If you read the first example in the csv.reader section here, you will find the following quick and succinct example. import csv (1) with open('eggs.csv', newline='') as csvfile: (2) spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|') (3) for row in spamreader: (4) print(', '.join(row)) (5) Spam, Spam, Spam, Spam, Spam, Baked Beans Spam, Lovely Spam, Wonderful Spam You do not need to understand everything that is happening in this example (yet). With that being said, the following is an explanation for each part. One important part of learning a new language is jumping right in and trying things out! Modify the provided code to read in the 2020.csv file and print the 4th column only. Code used to solve this problem. Output from running the code. import csv with open('/depot/datamine/data/noaa/2020.csv') as csvfile: reader = csv.reader(csvfile, delimiter=',') for row in reader: print(row[3]) break 168 Question 5 Below we’ve provided you with code that we would like you to fill in. Print the first 10 rows of the data. import csv with open('/depot/datamine/data/noaa/2020.csv') as my_file: reader = csv.reader(my_file) # TODO: create variable to store how many rows we've printed so far for row in reader: print(row) # TODO: increment the variable storing our count, since we've printed a row # TODO: if we've printed 10 rows, run the break statement break Code used to solve this problem. Output from running the code. import csv with open('/depot/datamine/data/noaa/2020.csv') as my_file: reader = csv.reader(my_file) for ct, row in enumerate(reader): print(row) if ct == 9: break [', '']
https://the-examples-book.com/projects/current-projects/19000-s2022-project01
CC-MAIN-2022-33
refinedweb
1,333
75.5
This article was originally written in English. Text in other languages was provided by machine translation. Adobe Flash and AIR are ubiquitous platforms to develop rich internet applications. Flash is used for browser based applications and AIR is used for developing native platform applications. Both platforms have considerable support for globalization. Globalization enablement features like locale aware formatting/parsing, collation, case transforms, localization and multi-lingual text rendering are supported by both these platforms. But some more globalization features like text normalization, transliteration, Unicode character properties, encoding conversions, charset detections, Unicode string utilities etc are still missing in the Adobe AIR and Flash platforms. One of the primary reasons for not adding all these features inside the Adobe runtime platforms is the size of the software. To overcome the size limitation issue, Adobe AIR and Flash can invoke the services of external dynamic libraries through ActionScript. There are some well known external libraries which have rich globalization support like ICU, GNU glib, Verisign IDN library to name a few. Fortunately the upcoming Adobe AIR 3.0 (now available as Adobe pre-release) has a wonderful feature called ActionScript native extensions, which is about ActionScript programming interface for a native code library like MS Windows DLL, Os X FrameWork, Android JAR or shared library or iOS static library. Please see Adobe AIR3 beta site on how to download and take part in the Adobe AIR pre-release. Please make a note that this native extensions feature is available _only_ in Adobe AIR platform, not in the Flash platform. In this blog, I demonstrate a sample (Download air_icu ) application to invoke ICU from an Adobe AIR application on Windows platform. Readers are reminded that this is only illustration sample software and by no means production quality software. Hence readers must exhibit discretion in using this software as it is. The sample illustrates ICU word breaking, sentence breaking, utf-conversion and Unicode character property verification. You will need the following software to build an ICU extension for AIR platform. - MS Visual Studio 2010 (to build AIR native extension DLL coded in C/C++) - Adobe Flex SDK 4.5.1 (). Download this to C:Flex4.5.1. - Adobe Air 3 Beta2 download (To build Adobe Actionscript extension) from . Unzip this in to C:Flex4.5.1. This step overwrites the AIR related components in Flex4.5.1 sdk with latest Adobe Air3 beta2. Also keep a copy in C:air3_beta2 folder. - The Adobe pre-release Flash runtime web site has more information, documentation and samples on how to use ActionScript extensions. The ‘product details’ tab in the web page has a FAQ on how to join the Adobe pre-release program. - beta 2. It also has the wrapper routines calling ICU C functions. 3) This is a DLL project and the build output is AirIcuExtension.dll 1.2 Building ActionScript Library 1) Build the actionscript library using the below command. C:Flex4.5.1bincompc.exe -source-path src -include-classes com.adobe.extensions.AirIcuExtension -external-library-path C:air3_beta2frameworkslibsairairglobal.swc -output binAirIcuExtension.swc The file AirIcuExtension.as in the folder srccomadobeextensions has the public class AirIcuExtension which calls the ICU routines. In this sample, calling ICU sentence breaker, word breaker, normalizer, utf-conversion and Unicode character property have been illustrated. 1.3 Packaging ActionScript native extension Open the binAirIcuExtension.swc is a zipped archive. Open it using WinRAR or WinZip program and extract the library.swf file in the swc package into the AirIcuExtension/bin:air3_beta2.x or C:air3_beta2binadt program, one can make an AIR certificate. The output is an archive file AirIcuExtension.ane in the AirIcuExtension/bin folder. 1.4 Building the Test program AirIcuExtensionTest.mxml Now that we built and packaged the native extension package AiricuExtension.ane, we are readu. Using the mxml compiler, AirIcuExtensionTest.swf is built as follows in AirIcuExtensionTest folder. C:Flex4.5.1bincompc.exemxmlc +configname=air -external-library-path ..AirIcuExtensionbinAirIcuExtension.ane -output bin-debugAirIcuExtensionTest.swf — srcAirIcuExtensionTest.mxml The output swf file AirIcuExtensionTest.swf is placed in the bin-debug folder. 1.5 Building AIR package for executing AirIcuExtensionTest The final step is to package the above AirIcuExtensionTest .swf and AirIcuExtension.ane files into an AIR executable folder. Execute the following command C:air3_beta2binadt -package -XnoAneValidate -storetype pkcs12 -storepass <passwd> –keystore <AIR certificate> -tsa none -target bundle AirIcuExtensionTest.air AirIcuExtensionTest-app.xml AirIcuExtensionTest.swf -extdir ….AirIcuExtensionbin The output of the above command is a folder AirIcuExtensionTest.air. Inside the folder, there is AirIcuExtensionTest.exe. You can execute and see the output. 2 Conclusion The sample illustrated how to invoke ICU from ActionScript. The AIR ICU extension is easy to build using the publicly available Adobe Flex SDK and AIR3 Beta 2 SDKs. It will be much easier to do all this in the future Adobe Flash Builder IDE using GUI. The advantages of this feature are - AIR developers looking to develop international applications for desktop or mobile have the full power of ICU at hand. Many Unicode features, encoding conversions, IDN conversion utilities, string processing, transforms and many more international features can be easily coded. - The native ICU extension once built can be used any any developer as it is a library. - The Actionscript APIs calling ICU can be coded using the same signatures as ICU C++ API. This eliminates the learning curve. - Since ICU is in native code, performance is not compromised. - Since it is ICU, developers can expect cross-platform behavior in AIR programs. - Since the extension is a AIR library, ICU updates can be easily re-packaged in to the ane file. In the future once AIR3 is released, a full fledged ICU native extension with proper API definitions will be a great globalization project. 19 thoughts on “Invoking ICU from Adobe AIR Applications” Hey, nice post. I guess this won’t work with Windows 7 64 bit obviously ^^. Maybe you could provide something for 64 bit as well 🙂 Cheers, Joggl89 Thanks for the comment. You are right. ICU 64bit dlls donot work in AIR 3.0. I remember I could not build the extension DLL in VS2010. AIR 3.0 does not yet support 64bit. We have to wait until it supports. Let us wait for post-Air3.0. Thanks, Harish Just to clarify further. I tested my extension on Win 7 64 bit laptop but used ICU 32 bit dlls. -harish Thanks for getting me started on native extensions. I’ve put a hello world example & ant script online, based on the info in this post. You can read about it & check it out at I can’t build ane using adt. I ran adt at C:air3_RC1samplesair_icuAirIcuExtensionbin after setting “set path=c:air3_RC1bin;%PATH%”. I have following files under AirIcuExtensionbin directory, but i got “system can not find the file specified.” Did I miss anything? Thanks, 09/02/2011 03:46 PM 9,216 AirIcuExtension.dll 09/23/2011 03:16 PM 2,712 AirIcuExtension.swc 08/19/2011 08:29 AM 514 extension.xml 07/19/2011 04:43 PM 18,277,376 icudt48.dll 07/19/2011 04:36 PM 1,313,792 icuin48.dll 07/19/2011 04:42 PM 36,352 icuio48.dll 07/19/2011 04:33 PM 1,043,456 icuuc48.dll 09/23/2011 03:16 PM 1,867 library.swf Which file it cannot find? Is it adt? or the air license file? Are you in the directory C:air3_RC1samplesair_icuAirIcuExtensionbin when executing adt? There are somany files involved that you run into this error just like me when I first ran. Harish, thanks for help. Error message was not detail enough to see which file was missing. ADT runs okay. What is air license file? I can’t see any instruction about license file. Does it mean AIR certificate? This error is raised from adt run in step 1.3. Thanks, I solved the issue by adding certificate file. Thanks for the help. Sorry I meant AIR certificate. You can generate air certificate using adt program. This is powerfull, I hope we will see more of ANEs in near future 🙂 Nicely build on win7 x64 following steps of your research. I just needed to manually copy the *48.dll files into air dir, I must of have missed something regarding packaging… Thanks for new knowledge! For God sake, please give us an example of AIR 3.0 NativeExtension with C# .dll. C# is more popular in .NET framework today. I have been looking for C# sample for NativeExtension .dll from weeks and couldn’t find a single example. Hi James, Sorry, my example only illustrated C++/C but not C#. One way to try C# dll is you should invoke C# dll from a C++ dll using interop (Just google for calling C# from C++). The C++ dll must implement all AIR needed framework glue as in my sample here. This is only my guess. Hello James, where you able to make it work with c#? I’m also looking for an example in c# ANE Example here 🙂 After I finish all steps, I got a problem when I execute the .exe file in the folder air It jumps a message e.g. ” can’t find the icuuc48.dll componet” but I have found the file “icuuc45.dll” in the folder Windows-x86~ just like the following AirIcuExtensionTest.airMETA-INFAIRextensionscom.adobe.extensions.AirIcuExtensionMETA-INFANEWindows-x86 Do I miss something? thanks P.S. please forgive my poor English >< The icuuc48.dll must be present in the same folder as where the .exe file resides. Infact all icu dlls must be there. The other way is to add the icu dll folder localtion to windows path variable. thanks harish suvarna ‘s help
http://blogs.adobe.com/globalization/2011/09/03/invoking-icu-from-adobe-air-applications-2/?replytocom=381
CC-MAIN-2018-39
refinedweb
1,616
60.82
Subject: [ggl] Re: Finding intersection points of a ray and polygon? From: Elvis Stansvik (elvstone) Date: 2010-02-23 12:47:58 Hi Barend, 2010/2/23 Barend Gehrels <Barend.Gehrels_at_[hidden]>: >. Yes, I realized this after doing some research. It's however, given the simple nature of my project, not a catastrophy as it would be OK with me to work with "rays" of finite length. That is, line strings. > >. Right. I could work with a linestring with just two points as my "ray". No problem. > >)? > > If segments are OK for you, and you realize the state the library is in now > (we're preparing it for incorporation, namespaces will change, etc), I will > come back soon about this.? Anyway, thanks a lot for your thorough answer. Elvis > > Regards, Barend > > > _______________________________________________ > ggl mailing list > ggl_at_[hidden] > > > Geometry list run by mateusz at loskot.net
https://lists.boost.org/geometry/2010/02/0626.php
CC-MAIN-2021-04
refinedweb
145
81.83
Outputting CSV with Django¶ This document explains how to output CSV (Comma Separated Values) dynamically using Django views. To do this, you can either use the Python CSV library or the Django template system. Using the Python CSV library¶ MIME type,header, When dealing with views that generate very large responses, you might want to consider using Django’s StreamingHttpResponse instead. For example, by streaming a file that takes a long time to generate you can avoid a load balancer dropping a connection that might have otherwise timed out while the server was generating the response. In this example, we make full use of Python generators to efficiently handle the assembly and transmission of a large CSV file: import csv from django.utils.six.moves import range from django.http import StreamingHttpResponse class Echo(object): """An object that implements just the write method of the file-like interface. """ def write(self, value): """Write the value by returning it, instead of storing in a buffer.""" return value def some_streaming_csv_view(request): """A view that streams a large CSV file.""" # Generate a sequence of rows. The range is based on the maximum number of # rows that can be handled by a single sheet in most spreadsheet # applications. rows = (["Row {}".format(idx), str(idx)] for idx in range(65536)) pseudo_buffer = Echo() writer = csv.writer(pseudo_buffer) response = StreamingHttpResponse((writer.writerow(row) for row in rows), content_type="text/csv") response['Content-Disposition'] = 'attachment; filename="somefilename.csv"' return response Using the template system¶. example.
https://docs.djangoproject.com/en/1.8/howto/outputting-csv/
CC-MAIN-2018-05
refinedweb
247
56.35
Hi Team, I am trying to implement push notifications with Parse 1.9.2 jar in xamarin android. I was able to create the java Android native binding for Parse 1.9.2 jar. I created a new PCL project and and added a reference dll of parse binding library. When i build the new PCL project, i get following errors: **error: ParseCallback1 is not public in com.parse; cannot be accessed from outside package com.parse.ParseCallback1 error: name clash: done(ParseException) in MainActivity overrides a method whose erasure is the same as another method, yet neither overrides the other public void done (com.parse.ParseException p0) first method: done(Throwable) in MainActivity second method: done(T) in ParseCallback1 where T is a type-variable: T extends Throwable declared in interface ParseCallback1 error: name clash: done(Throwable) in MainActivity and done(T) in ParseCallback1 have the same erasure, yet neither overrides the other public void done (java.lang.Throwable p0) where T is a type-variable: T extends Throwable declared in interface ParseCallback1** This is the main activity class: **public class MainActivity : global::Xamarin.Forms.Platform.Android.FormsApplicationActivity,Com.Parse.ISaveCallback { protected override void OnCreate (Bundle bundle) { base.OnCreate (bundle); Parse.Initialize (this,"AppID","RESTAPIKEY"); ParseUser.EnableAutomaticUser(); ParseInstallation.CurrentInstallation.Save (); ParsePush.SubscribeInBackground ("Android", this); ParseInstallation.CurrentInstallation.Get ("deviceToken"); global::Xamarin.Forms.Forms.Init (this, bundle); LoadApplication (new App ()); } public void Done(Java.Lang.Throwable p0) { } public void Done(Java.Lang.Object p1) { } public void Done(Com.Parse.ParseException p0) { } }** Below is the metadata.xml for the native binding libarary project: **<attr path="/api/package[@name='com.parse']/interface[@name='ParseCallback1']" name="visibility">public</attr> <attr path="/api/package[@name='com.parse']/interface[@name='ParseCallback2']" name="visibility">public</attr> <attr path="/api/package[@name='com.parse.codec.net']/class[@name='RFC1522Codec']" name="visibility">public</attr> <attr path="/api/package[@name='com.parse.codec.binary']/class[@name='Base32']/method[@name='isInAlphabet']" name="visibility">protected</attr> <remove-node <remove-node <remove-node ** I am really stuck. It would be really helpful if Xamarin support team can help me to resolve this issue. Regards, Amit Answers Hi Amit. Thanks for using Parse! If it's Push Notification for Android you're looking for, we actually support it in our .NET 1.5.0 SDK. You can get it from the Xamarin Component Store/NuGet/our website:. To get started: Let me know if you need any further help. @ListiarsoWastuargo Hi Listiarso, Thanks for your reply. I Created a new project by adding Parse.Android.dll and Xamarin.Android.Support.v4.dll to Android project. I tried to run the app by initializing with app id and .Net key. Installation class of my Parse project was updated with one device. But it only contains installationId. There is no device token created. I don't think sending push is possible without device token. Could you please advise me on this? Regards, Amit @ListiarsoWastuargo Cool that the .NET SDK finally supports push notifications, thanks for that! However, I am also unable to make it work with Xamarin.Android. When launching the app, I can see in the debug log: I am 100% sure the <service android: as well as everything else that is needed, is included within the AndroidManifest.xml. No typos etc. However, since I am using Xamarin.Android 5.0, in the actual generated AndroidManifest.xml it is declared like: <service android: This is apparently because:. developer.xamarin.com/releases/android/xamarin.android_5/xamarin.android_5.0/#Android_Callable_Wrapper_Naming Can this cause problems? Any ideas? Yes, it doesn't work well with Xamarin.Android 5.0. Talking with the Xamarin team, trying to fix it now. I'll let you guys know immediately. Sorry for the inconvenience. @ListiarsoWastuargo Thanks a lot! And no problem, I can fall back to the native Android JAR for the time being. Will then switch to the .NET version when it works. I don't know if it is of any help to you, but some details: 1) I am able to see the installation at the Parse console. 2) But no device token. 3) And as mentioned, in the debug log the parse.ParsePushService is said to be missing from the app manifest. 4) Maybe this is because in the generated manifest it is declared with the MD5SUM (md558c46fa16d0b39f594789d5760860ef7.ParsePushService), maybe not. In any case, very nice that the .NET SDK now supports push notifications. Hi @crossplatformer , I am stuck while using Parse Android jar native binding for push notifications.I've provided error details in my Initial post above. Could you please provide me any pointers for resolving it. Thanks. @ListiarsoWastuargo , Looking forward to .NET version supporting Android/iOS push notifications. Hey @AmitLimje, error: name clash: done(Throwable) in MainActivity and done(T) in ParseCallback1 have the same erasure, yet neither overrides the other Your problem is related to Java type erasure: ISaveCallback extends ParseCallback1, and they both have the same name method Done - during Java compilation the type information is erased, so you end up with "two same methods" and it cannot be decided which one to use. Search for Java type erasure etc. you will find information E.g. change the method name. This one you have already solved: error: ParseCallback1 is not public in com.parse; cannot be accessed from outside package com.parse.ParseCallback1 The solution is in your metadata.xml: <attr path="/api/package[@name='com.parse']/interface[@name='ParseCallback1']" name="visibility">public</attr> Bump. I'm also having this issue- on build I get 05-30 03:08:01.181 W/parse.ManifestInfo( 9039): Cannot use GCM for push because AndroidManifest.xml is missing:): I was getting the same notice about missing the parse.ParsePushService attribute but that's gone away, now it's saying something else: " All the above permission attributes are in the manifest. Hi all, We've just launched Parse 1.5.1 that should fixed the problem with Push Notification on Xamarin iOS and Xamarin Android. Tested that it worked on both Xamarin 4.x and 5.x, foreground or background. Let me know if you still encounter any problem. @ListiarsoWastuargo Great, thanks! I will check it out and let you know if any problems should occur, thanks again : ) Updated my component, cleaned the solution, removed the existing package, removed all the mono runtimes, restarted Xamarin, no change, same errors: " I still get a device under Installations but no device token. Same problems also for me (I just update Parse to 1.5.1) and the error is the same: [parse.ManifestInfo] Cannot use GCM for push because AndroidManifest.xml is missing: [parse.ManifestInfo] . [parse.ManifestInfo] [parse.ManifestInfo] [parse.ManifestInfo] [parse.ManifestInfo] [parse.ManifestInfo] [parse.ManifestInfo] [parse.ManifestInfo] [parse.ManifestInfo] I also updated to 1.5.1 but noticed that there's no Xamarin.Android.Support.v4.dll included. Hi, I've also updated to 1.51. In Release config, I can't get the device to receive a push, but I don't get any parse.ManigetInfo errors anymore. In DEBUG config I do get the below error. I also see the same errors/behaviour in the parsexamarinpushsample project..parse.parsexamarinpushsample" [parse.ManifestInfo] intent-filter [parse.ManifestInfo] receiver FYI, if you post those logs, kill the "<" and ">", it removes the content inside. @Jared : same thing here. I don't have the exception anymore with 1.5.1 and I can register my devices. But I don't receive any push message.... I am on Xamarin.Android 4.x (but tried also 5.x). Do we need to sign the build with a prod certificate? @ListiarsoWastuargo : can you post a zip file with your working sample? Maybe the tutorial on parse.com telling what we need to put in the AndroidManifest.xml is wrong. If I look at the Android / Java tutorial there is more to put in the manifest file. @ListiarsoWastuargo Not working at all. I got the same error at application output:[parse.ManifestInfo].optisage.bniwinners" [parse.ManifestInfo] intent-filter [parse.ManifestInfo] receiver Hi all, This is the project that I used and tested. Hope it helps. I also added my own project there so it should totally work just by building it and deploying it directly to device. @ListiarsoWastuargo thanks for making that available. I see your sample has a later version of the Parse.Android.dll (1.5.2). I ran your sample using the Release build on my Nexus 5 (api 22), and using my access keys, and successfully received messages. I then added the 1.5.2 dll to my project and my app now works as well. With 1.5.1 the GCM registration doesn't happen. With 1.5.2 it does. Is the 1.5.2 Parse.Android.dll ready for production? @Nicolas77 - You don't appear to need a prod cert...I was wondering the same thing. Note: I can only get it working using a Release build on a physical device. @ListiarsoWastuargo : Thanks for the sample that works on the first try! @JaredLangguth : Same thing here. I successfully make it working in my own project with the dll included in the sample project. Thanks for the tip! @ListiarsoWastuargo Same for me with Parse 1.5.2 now its work. Is possible to have a date when version 1.5.2 go in production as a Xamarin Components? Thanks Glad it works! The 1.5.2 has been submitted to Xamarin component store since yesterday. We'll just have to wait for their approval. Meanwhile, it's already available on NuGet. Also confirming adding the 1.5.2 component worked for me. It didn't work at first though, I had to make a new solution and import all my work. I also had to play around with my manifest, for some reason I couldn't get Google Maps and Push to work together, one or the other worked at any given time. I finally took out all the lines related to GMaps so it was only Push and added them one at a time until it worked. My end file was no different from my copy/paste so I'm not sure what fixed it but I seem to be running fine now. For some reason the project @ListiarsoWastuargo provided worked here the day before yesterday, but today it immediately closes after running. Does anyone know what could cause this? I also tried to add Parse via NuGet to my own projects, but I get a runtime error everytime I run it in that way @ListiarsoWastuargo successfully register the device. But, when test the push notification, only can receive the notification sound, but no notification is display the the notification area. Any idea? TQ. @ListiarsoWastuargo it is working now after setting the android:name="bni" and android:label="BNI" attributes of the Application element in the androidManifest file. TQ. @ListiarsoWastuargo Version 1.5.2 seems to work in the sense that it is able to receive and show the push notifications. Thanks for that! However, it took some time to figure out the "right configuration" in terms of the AndroidManifest and the Application class. Still not sure if what I have is 100% correct, but at least the notifications come through now. Following the documentation, it would not work, so what I have at the moment is gathered from comments here and there... I think Parse needs to check and clean up the documentation ASAP... I still have one problem: when sending JSON, the "uri" -field seems not to work anymore. For example, sending a JSON like... ...would before launch the browser with the given URL - but now it just takes me into my app. Also, just a side note: apparently, the push notification icon does not need to be mentioned in the AndroidManifest anymore, it seems to use the app icon automatically ? What if a different icon would like to be used ? @LuukvandeWiel what kind of RuntimeError did you get? @crossplatformer if you take a look at the docs inside Parse.Android.dll(and mentioned in) the handler provided in DefaultParsePushNotificationReceivedHandleris just a helper method to help you get started with app icon push notification. You can add another handler to ParsePush.ParsePushNotificationReceivedto suit your requirement (such as displaying other icon/doing different action other than going to default activity). That said, I agree that we'll need to fix the documentation. And we'd love to get your help! You can send a PR to if you feel that any part of our docs is lacking/not up to date. @ListiarsoWastuargo Thanks for clarifying I was just wondering, because it was automatic before, i.e. when sending JSON with a proper URI, such as "http", "tel", "sms", it (the default handler) would automatically act upon those. But cool, this is no problem and gives me more freedom (custom icons, different JSON etc.) by providing my own handler, thanks. I will go through the docs and send a pull request / push fix, I think (at least in my case) the ParseClient.Initialize() is not enough - I had to subscribe to "all channels" and provide the default handler to make the push notifications to work. @ListiarsoWastuargo When I try to build your sample project on Debug, I get the following error: Deployment failed because of an internal error: Failure [INSTALL_FAILED_UPDATE_INCOMPATIBLE]. When I try it on release, the app starts up for half a second and closes afterwards. When I try to run the 1.5.1 example from the Parse site after updating Parse in the project, I get the following exception:.TypeLoadException: Could not load type 'Android.OS.BaseBundle' from assembly 'Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065'. at at Parse.PlatformHooks.Initialize () at at Parse.ParseClient.Initialize (string,string) at UMTCApp.App..ctor () [0x00008] in ...\App.cs:10 at UMTCApp.MainActivity.OnCreate (Android.OS.Bundle) [0x0004b] in ...\MainActivity.cs:40 at Android.App.Activity.n_OnCreate_Landroid_os_Bundle_ (intptr,intptr,intptr) [0x00011] in /Users/builder/data/lanes/1502/4ab8d98a/source/monodroid/src/Mono.Android/platforms/android-19/src/generated/Android.App.Activity.cs:2475 at at (wrapper dynamic-method) object.dde690b6-fc19-4234-91d2-973b873c7219 (intptr,intptr,intptr) at at md50b5a9cbdf799836e962c32a4a9e2199a.MainActivity.n_onCreate(Native Method) at at md50b5a9cbdf799836e962c32a4a9e2199a.MainActivity.onCreate(MainActivity.java:28) at at android.app.Activity.performCreate(Activity.java:5990) at at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1106) at at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2278) at at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2387) at at android.app.ActivityThread.access$800(ActivityThread.java:151) at at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1303) at at android.os.Handler.dispatchMessage(Handler.java:102) at at android.os.Looper.loop(Looper.java:135) at at android.app.ActivityThread.main(ActivityThread.java:5254) at ... 4 more @LuukvandeWiel I think the first error means the application is already installed and was not uninstalled, for some reason or other - try to manually remove the app from device, restart VS or XS, whatever IDE you are using, etc. This one: System.TypeLoadException: Could not load type 'Android.OS.BaseBundle' from assembly 'Mono.Android, Version=0.0.0.0, Culture=neutral, PublicKeyToken=84e04ff9cfb79065'. Is most probably just some version problem - check that your references are OK and correct versions. I follow all the steps same like sample project . But when i run my app i Got exception "Could not load type 'Android.OS.BaseBundle' from assembly 'Parse.Android'." I am facing same problem . When using Parse 1.5.3 (and following the Quick Start on the Parse website) now I get other issues. The error message is the following: Installing application on device Deployment failed because of an internal error: Unexpected install output: pkg: /data/local/tmp/com.umtc.app-Signed.apk Failure [INSTALL_PARSE_FAILED_MANIFEST_MALFORMED] Deployment failed. Internal error. I suppose this has something to do with my AndroidManifest.xml being corrupted. I googled a bit, and found that my package name can't start with caps. It doesn't, and has never done, however. This is my AndroidManifest.xml file : It could be just a little problem or something I did wrong. Could someone help me please? TRY THIS .. I changed my target framework Android 4.4(kitkat)n to android 5.0(lollipop) .Now its working fine foe me .
https://forums.xamarin.com/discussion/41871/android-native-binding-library-with-parse-1-9-2-issue-dll-is-created-but-can-not-use-in-pcl-project
CC-MAIN-2019-26
refinedweb
2,714
53.07
I have been playing around with the Arduino for a few months and one of the things I wanted to build was a nice temperature monitor with a simple screen. I have the Arduino Uno board and had a GHI Electronics LCD Button Shield that I thought I could use. After playing around with connecting the Arduino to the LCD Shield I found that I could control it and even use the buttons (with some slight tweaks to the logic that is used in the standard Arduino Button Shield logic). I had also previously purchased one of the Sparkfun waterproof temperature probes and went through the trouble of installing the resistor inline as recommended here: This is how I have it wired to the Arduino (using the LCD Shield pins as mounting points): I have the resistor and the solder connections in the shrink tube here: The probe itself can be pruchased at Sparkfun: I also had to make sure I knew the address of the probe, but they also have a nice tutorial for getting the address of your probe here: To run the LCD Button Shield I used the simple LiquidCrystal code I found here: It should work with any of the Arduino Button Shields. The final code I used is here: // This Arduino sketch reads DS18B20 "1-Wire" digital // temperature sensors. // It also uses the LCD button shield which needs the LiquidCrystal Library available here: // // Tutorial: // #include <OneWire.h> #include <DallasTemperature.h> #include <LiquidCrystal.h> // initialize the library with the numbers of the interface pins LiquidCrystal lcd(8, 9, 4, 5, 6, 7); // Data wire is plugged into pin 3 on the Arduino #define ONE_WIRE_BUS 3 //: // // this is a unique sensor Id and will be specific to your sensor, use the link above to discover the Id of your sensor DeviceAddress tempProbe = { 0x28, 0xB0, 0x0C, 0x37, 0x04, 0x00, 0x00, 0x68 }; //holds the latest temp reading float tempF; void setup(void) { // start serial port Serial.begin(9600); // Start up the library sensors.begin(); // set the resolution to 10 bit (good enough?) sensors.setResolution(tempProbe, 10); // set up the LCD's number of columns and rows: lcd.begin(16, 2); //set the cursor to first row, first character lcd.setCursor(0,0); //show which version of software it is running lcd.print("LCD:TempProbe v1"); } void printTempSerial(float temp) {//sends temp info to serial port Serial.print("Probe temperature is: "); if (temp < -100) { Serial.print("Error getting temperature"); } else { Serial.print("F: "); Serial.print(temp); } Serial.print("\n\r\n\r"); } void LCDTemp(float temp) {//send temp info to LCD shield //first character, second row lcd.setCursor(0,1); if (temp < -100) { lcd.print("Error: check connection"); } else { lcd.print (temp); lcd.print (" Fahrenheit"); } } void loop(void) { //gets all temp probes on bus (i.e. pin 3) sensors.requestTemperatures(); //get the temp of a specific sensor on bus by unique probe Id tempF = sensors.getTempF(tempProbe); //send temp over serial debug printTempSerial(tempF); //send temp to LCD display LCDTemp(tempF); //wait 2 seconds to next reading delay(2000); } Hello thank you for the code for the temp sensor.when I first ran it it went fine but now it says error check com which I did and its on com 4 which is checked then it displays temp at 32 f and stays there….any idea what I may be doing wrong? Thanks in Advance @geoff are you using a screen with yours or are you just displaying the data via serial? If you dont use a screen then I would suggest trying to comment out all the LCD code. Hi James just got back to this project and uploaded the code once again and it works just fine,thanks very much.I was just wondering how I could add a piezo to this code to add an alarm at a given temp.Trying to build a fish locator…at the ideal water temp. Thanks In Advance Geoff Yeah yhat would be pretty easy, just add an if statement after you get the temp. If the temp is above your threshold, ring the piezo. Thanks James
http://contractorwolf.com/arduino-temperature-probe/
CC-MAIN-2015-48
refinedweb
687
69.52
My own commons library for flutter. void main(){ return runApp(Module().register<Service>(ServiceImpl()).build(MyApp())); } final svc = inject<Service>(context); Changed name of streaming widget to Streaming${widgetName} and added future based widgets. Added PaddedCard and ChangeBasedTextFormField. This library now exports an instance of FirebaseAnalytics as a global variable. DocBuilder now allows customizing loading widget and null data. inject now returns null if nullOk == true when any implementation is not registered. FirestoreListViewcan forward some properties to ListView. Initial release. Add this to your package's pubspec.yaml file: dependencies: app_base: ^0.3.0 You can install packages from the command line: with Flutter: $ flutter packages get Alternatively, your editor might support flutter packages get. Check the docs for your editor to learn more. Now in your Dart code, you can use: import 'package:app_base/app_base.dart'; We analyzed this package on Dec app_base.dart.
https://pub.dartlang.org/packages/app_base
CC-MAIN-2018-51
refinedweb
145
53.78
- ) - GNU General Public License version 2.0 (16) - GNU Library or Lesser General Public License version 2.0 (3) - BSD License (2) - Apache License V2.0 (1) - Artistic License (1) - Eclipse Public License (1) - GNU Library or Lesser General Public License version 3.0 (1) - Open Software License 3.0 (1) - PHP License (1) - Python License (1) - Zope Public License (1) - Grouping and Descriptive Categories (26) - Linux (26) - BSD (24) - Modern (18) - Mac (17) - Windows (17) - Other Operating Systems (5),394 weekly downloads Apache Mobile Filter The fastest and easiest way to detect mobile devices8ambo CMS Mambo is a mature, award winning, feature rich content management system used for everything from simple websites to complex corporate applications. NOTE: Files here are older releases only. Please visit for the latest releases.68 weekly downloads WebGUI A perl-based web application and web site framework designed to let the people who create the content manage it, and let the technical folks get back to tech stuff.37ope Zope is an open source application server specializing in content management, intranets, and custom web applications. Zope is written in Python and has a large, global community of developers and companies @1 Last Modified Date and Time This Perl script checks the "Last Modified" date and time of a file. You can choose the display formats. More ..... @1 Quote Publisher Display categorized random quote of the day or message of the day via SSI. More .....ero CMS A Powerful Content Management System that runs on PHP, Mod_Rewrite, the MySQL Database. Exero CMS has an easy to use AdminCP that allows the admin to create/edit or delete Pages, Blocks and Items(links,images,polls) and Modules. Family Site Provide geneology information, contact information, personal descriptions and webpages, calendars, etc in a web interface. This system will use php and any database system and will provide various level of public and private access. HTP for Ampoliros With HTP for Ampoliros, maintenance of a very large site handled with Magellan and with a lot of templates is very easy. It is useful for smaller sites too. Kehei Wiki Source distribution for Kehei Wiki, one of the oldest wiki implementations. Targeted at commercial environments, provides adjustable enforcement of author rights, WYSIWYG editing, optional blog by page, multi namespaces, templates for everything.. Linkerdoodle Written in PHP and designed to maintain a personal database of bookmarks, Linkerdoodle is a simple link organizer. - Nifty Nerds Web Authentication Nifty Nerds Web Authentication - Authentication for your website that will make it easy to set up authentication and user tracking.(PHP) TTS Data Center TTS Data Center Is a Open Source content management system (CMS) Project Built for the sol purpose of cataloging Mods for PC Games. eZ Publish content management system Open-source Content Management System, powered by PHP eZ trade, has been merged into eZ publsi All our activity has moved to our homepage. ()
https://sourceforge.net/directory/internet/www/sitemanagement/developmentstatus:mature/os:posix/
CC-MAIN-2017-13
refinedweb
482
52.49
Create an RSS 2.0 document from a template. RSS 2.0 is an update of RSS 0.91, and so does not follow the RDF approach taken by RSS 1.0. After RSS 0.91 and RSS 1.0, it is the third most popular RSS format. You can find the spec for RSS 2.0 at. It is similar to RSS 0.91, but offers some clarifications and additional elements. The following, news.xml, is a minimal example of RSS 2.0: <rss version="2.0"> <channel> <title>Wy'east Communications</title> <link></link> <description> Wy'east Communications is an XML consultancy.</description> <item> <title>Legend of Wy'east</title> <link></link> <description>The Native American story behind the name Wy'east.</description> </item> </channel> </rss> Like RSS 0.91, RSS 2.0 doesn't declare a namespace for its own elements. Also like 0.91, rss is the document element. It must have a version attribute with a value of 2.0. The channel element is required, as are its children title, link, and description. The language element is required as a child of channel by 0.91, but under 2.0 it is optional. The image element is also required by 0.91; it's optional under 2.0. Table 6-2 compares the required and optional elements of channel in 2.0 and 0.91. The purpose of each is briefly described. Under the item element in RSS 2.0, a description element can contain entity-encoded HTML. In other words, it can hold an article or story in itself, written in HTML (with & for & and < for <). Table 6-3 compares the 0.91 and 2.0 children of item. An item element may represent a story such as an article from a newspaper or a magazine. In such a case, the item's description child should contain a synopsis of the story, with a URI in the link element pointing to the full story. On the other hand, an item may also contain a complete story. In this case, the description child of item will contain the text of the whole story (which may be entity-encoded HTML), so the link and title children of item don't have to be included. Though all elements of item are optional in 2.0, at least one title or description must be present. With Radio UserLand, you can generate an RSS 2.0 document for your Radio weblog by going to Prefs and then clicking RSS Configuration under Weblogs. A link to this RSS document will appear on your weblog home page.
https://etutorials.org/XML/xml+hacks/Chapter+6.+RSS+and+Atom/Hack+83+Create+an+RSS+2.0+Document/
CC-MAIN-2021-31
refinedweb
436
71.21
From: Sebastian Benoit <benoit-lists@fb12.de> Date: Tue, 28 Jan 2003 20:16:45 +0100 David S. Miller(davem@redhat.com)@2003.01.28 10:35:34 +0000: > Good set of debug checks would be the following: no output, i did 4 tests, everytime i was able to lock the ssh-connection within a few seconds. kernel 2.5.59 + your debug-patch.Thanks for testing, how about this new patch at the end of this email?Does it make the problem go away?Alexey, most solid report is that 2.5.43-bk1 makes bug appear.This is good because it sort of narrows things down. What iscontained there in networking is:1) initial stackable dst logic, should not cause problems2) addition of UDP sendfile and ip_append_*() logic3) fix to tcp_check_req() "fix" :-) it only changes bahevior on connect so should not be a problemI heavily, therefore, suspect #2 which is why I am poking aroundin the tcp.c changes to change checksumming and copying semantics.--- net/ipv4/tcp.c.~1~ Tue Jan 28 12:40:09 2003+++ net/ipv4/tcp.c Tue Jan 28 12:41:48 2003@@ -1089,11 +1089,13 @@ if (!skb) goto wait_for_memory; +#if 0 /* * Check whether we can use HW checksum. */ if (sk->route_caps & (NETIF_F_IP_CSUM|NETIF_F_NO_CSUM|NETIF_F_HW_CSUM)) skb->ip_summed = CHECKSUM_HW;+#endif skb_entail(sk, tp, skb); copy = mss_now;-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
https://lkml.org/lkml/2003/1/28/224
CC-MAIN-2022-21
refinedweb
251
67.15
When you create an instance of a subclass, Java automatically calls the default constructor of the base class before it executes the subclass constructor. Consider the following classes: public class Ball { public Ball() { System.out.println("from the Ball constructor"); } } class BaseBall extends Ball { public BaseBall() { System.out.println("from the BaseBall constructor"); } } If you create an instance of the BaseBall class, the following two lines are displayed on the console: from the Ball constructor from the BaseBall constructor If you want, you can explicitly call a base class constructor from a subclass by using the super keyword. Because Java automatically calls the default constructor for you, the only reason to do this is to call a constructor of the base class that uses a parameter. Here's a version of the Ball and BaseBall classes in which the BaseBall constructor calls a Ball constructor that uses a parameter: public class Ball { private double weight; public Ball(double weight) { this.weight = weight; } } class BaseBall extends Ball { public BaseBall() { super(5.125); } } Here the BaseBall constructor calls the Ball constructor to supply a default weight for the ball. You need to obey a few rules when working with superclass constructors: If you use super to call the superclass constructor, you must do so in the very first statement in the constructor. If you don't explicitly call super, the compiler inserts a call to the default constructor of the base class. In that case, the base class must have a default constructor. If the base class doesn't have a default constructor, the compiler refuses to compile the program. If the superclass is itself a subclass, the constructor for its superclass is called in the same way. This continues all the way up the inheritance hierarchy until you get to the Object class, which has no superclass.PreviousNext
https://www.demo2s.com/java/java-class-inheritance-and-constructors.html
CC-MAIN-2021-04
refinedweb
307
50.26
DSON Import Error when opening Genesis figure in Poser Pro 2012 64-bit edited December 1969 in Poser Discussion Followed instructions for installation and have Genesis Content in my DAZ Studio folder and have imported the "new" Runtime into Poser, and have a DSON item under Scripts in Poser pro 2012, but get the follwing error when opening up any Genesis figure. I am running Windows 7 64-bit. Traceback (most recent call last): File "C:\Users\David\Documents\DAZ 3D\Studio\My Library\Runtime\libraries\Character\DAZ People\Basic Female.py", line 1, in import dson.dzdsonimporter ImportError: No module named dson.dzdsonimporter First question: Do you have SR3 or SR3.1 installed? Second question: Do you have the embedded library active? If so, does the problem go away if you use the external library (must be set in the General Preferrences) SR3. General Prefs in Poser Pro? Edit Menu, General Preferences, Library tab, Launch behavior It should be set to external. Internal seems to cause a problem. Not saying, this is problem, but set it to external for now Other question: What is the location where you installed Poser? (full pathname) Will try that setting... Current path: C:\Program Files\Smith Micro\Poser Pro 2012 I will also try to see if SP 3.1 does anything to "fix" Poser. The program is on SP 3.0, which is within the DSON prerequisites... Ok, the install location is default for PoserPro 2012 - that is good If I look at the error message, you seem to load the Genesis figure from a runtime which is imbedded in DAZ Studio Now it gets tricky. Let me explain what happens, then you can see where the problem might be The CR2 file which you load activates a python script. This python script calls the DSON Importer. That last call fails and should not happen If the DSON Importer is executed (which it isn't at this point), it will load the DUF file from the same location as the cr2 file and the python script; The importer reads it and gets the actual location of the resource/dsf/object file from this duf file. It then loads the rest of the files and constructs a new CR2. This CR2 file is written to a writeable runtime after it instructs Poser to read the new CR2. So the runtime should be different from program files/Smith Micro/Poser Pro 2012 runtime since that location is not writeable in WIndows 7/.Windows 8/Vista due to user permissions. If I remember correctly the installer asks for a location. The default Poser runtime at users/public/Public Documents/Poser Pro 2012 Content is OK but it could be any other external runtime. That is how it works. There are a couple of things you should check: Is the addon in the correct location: Addon should be in program files/Smith Micro/Poser Pro 2012/Runtime/Python/addons and the folder is called dson. Second thing you should check is if the DSON importer is pointing at the correct writeable runtime location. You can do this by running a python script in Scripts!DSON Support!Importer Preferences. Oncve you run it check if this is NOT located in the program files location. Otherwise change it Next thing to check is if all of the locations which are being references are connected as external runtimes in Poser. In your case C:\Users\David\Documents\DAZ 3D\Studio\My Library should be mapped - it probably is, since you loaded the CR2 from there Then we get into unknown territory - the DUF file may reference files outside the this external runtime. This depends on how it is saved. If that is the case, you could try to connect the C:\Users\David\Documents\DAZ 3D\Studio folder as a runtime. If Poser won't let you, create an empty runtime structure at this location and Poser will let you add it. There are many variables, so it is difficult to say what is wrong What I did is the following. I created a new runtime called Posergenesis. This is the location where I install all genesis content. The DSON files and the Poser Companion files (so all the essentials - both of them - you did install both of the did you?), Then I added that runtime to Poser. I kept my DS installation separate from Poser. I only added the Posergenesis runtime to the browseable locations to Studio I hope this helps Yes your explanation has been most helpful in *understanding* how the DSON importer works. Apart from changing the Runtime to external in Poser Pro 2012'a prefs, I did nothing much else and the DSON importer still refused to work, but I installed SP 3.1 and IMMEDIATELY the importer worked, with NO other changes. Perhaps DAZ ought to revise their documentation and change the prerequisites to SP3.1 minimum on Poser Pro 2012 instead of the "SR3 or later" as stated. Thanks again. I just upgraded one of my machines to Windows 8. I installed a fresh copy of Windows 2012 on it and then the DSON importer. I then go an ERROR: DLL not found for DSON. I disabled firewall, AV scanner - no change, Ran Poser and installers as admn - no change Then I decided to update the DSON installer to the latest version (I still had 1.0.9) and it suddenly worked. Now - who or what caused the problem? Poser, the installer, WIndows 8 or the DSON module? SInce I tried various things it might very well be a combination. I had the 1.0.9 version running on my Windows 7 system (before the upgrade). So it is difficult to say what causes the problem. Installing 3.1 will reset some of the preference files, so that might have solved it. Or your version of 3.0 was corrupted somehow or maybe because of the SR update the runtimes are re-ordered. Glad you have it working now On my Mac the * external * Librarie * causes crashes all sorts of problems when using Genesis.
http://www.daz3d.com/forums/viewreply/158128/
CC-MAIN-2015-35
refinedweb
1,021
64.51
Using autograd to plot implicit functions Posted October 02, 2019 at 09:30 PM | categories: autograd, nonlinear-algebra, implicit-function | tags: | View Comments Consider the solution to these equations (adapted from): \(e^{-e^{-(x_1 + x_2)}} = x_2 (1 + x_1^2)\) and \(x_1 \cos(x_2) + x_2 \sin(x_1) = 1/2\) It is not clear how many solutions there are to this set of equations, or what you should guess for the initial guess. Usually, the best way to see where a solution might be is to plot the equations and see where they intersect. These equations are implicit though, and it is not easy to plot them because we cannot solve for \(x_2\) in terms of \(x_1\) in either case. Here we explore a strategy to get plots so we can see where solutions could be. The idea is that we find one solution to each equation independently. Then, we derive a differential equation for each equation so we can integrate it to find the curve that is defined by the implicit function. First, we find a solution for each equation. We guess a value for \(x_2\) and then find the value of \(x_1\) that solves each equation independently. import autograd.numpy as np from scipy.optimize import fsolve def f1(x1, x2): return np.exp(-np.exp(-(x1 + x2))) - x2 * (1 + x1**2) def f2(x1, x2): return x1 * np.cos(x2) + x2 * np.sin(x1) - 0.5 x2_1 = 0.6 x1_1, = fsolve(f1, 0, args=(x2_1,)) print('f1: ', x1_1, x2_1) x2_2 = 1.0 x1_2, = fsolve(f2, 0 ,args=(x2_2,)) print('f2: ', x1_2, x2_2) f1: 0.08638978040861575 0.6 f2: 0.32842406163614396 1.0 Next, we need a differential equation that is \(dx_2/dx_1\). If we had that, we could just integrate it from one of the starting points above, and get the curve we want. The functions are implicit, so we have to use the implicit derivative, which for the first equation is \(dx_2/dx_1 = -df1/dx_1 / df1/dx_2\). We will get these gradients from autograd. Then, we just integrate the solution. Here we do this for the first equation. from scipy.integrate import solve_ivp from autograd import grad df1dx1 = grad(f1, 0) df1dx2 = grad(f1, 1) def dx2dx1_1(x1, x2): return -df1dx1(x1, x2) / df1dx2(x1, x2) x1_span = (x1_1, 1) x2_0 = (x2_1, ) sol1 = solve_ivp(dx2dx1_1, x1_span, x2_0, max_step=0.1) And then, we do it for the second equation. df2dx1 = grad(f2, 0) df2dx2 = grad(f2, 1) def dx2dx1_2(x1, x2): return -df2dx1(x1, x2) / df2dx2(x1, x2) x1_span = (x1_2, 1) x2_0 = (x2_2, ) sol2 = solve_ivp(dx2dx1_2, x1_span, x2_0, max_step=0.1) Finally, we plot the two solutions. %matplotlib inline import matplotlib.pyplot as plt plt.plot(sol1.t, sol1.y.T) plt.plot(sol2.t, sol2.y.T) plt.xlabel('$x_1$') plt.ylabel('$x_2$') plt.legend(['f1', 'f2']) <Figure size 432x288 with 1 Axes> You can see now that in this range, there is only one intersection, i.e. one solution, and it is near \(x_1=0.4, x_2=0.6\). We can finally use that as an initial guess to find the only solution in this region, with confidence we are not missing any solutions. def objective(X): x1, x2 = X return [f1(x1, x2), f2(x1, x2)] fsolve(objective, [0.4, 0.6]) array([0.35324662, 0.60608174]) That is the same solution as reported at the Matlab site. Another use of autograd for the win here. Copyright (C) 2019 by John Kitchin. See the License for information about copying. Org-mode version = 9.2.3
http://kitchingroup.cheme.cmu.edu/blog/category/implicit-function/
CC-MAIN-2020-05
refinedweb
589
74.69
It is quite easy to send an email from Python. With just a few simple lines of Python code, you can send an email with a subject and body to one or more recipients with optional attachments. The hardest part of sending email with Python is probably setting up your mail server. While email server setup is outside of the scope of this tutorial, I’m going to assume you’ve taken care of this. So let’s jump right into it. Send Email from Python The follow Python code was tested with Python 3.6.5, but any python version above Python 3.0 should work for you. If you have an older version of Python, you can get setup with the latest and greatest version of Python on your Mac or Linux by watching this video. Enough delay. Let’s send an email from Python! From in a Python interpreter (i.e. simply type python from a terminal window), import the following packages. import smtplib from email import message Next, let’s define a few variables: one for the from email address and one for the to email address. Additionally, define strings for the subject content and body content. from_addr = 'you@example.com' to_addr = 'me@example.com' subject = 'I just sent this email from Python!' body = 'How neat is that?' Moving on, we will create our message object next with a header and body. In this case, the payload is the body of the email. msg = message.Message() msg.add_header('from', from_addr) msg.add_header('to', to_addr) msg.add_header('subject', subject) msg.set_payload(body) Finally, make a connection to the email server and send your first email from Python! Of course, change the value of ‘password’ to be the actual password for that email address. Also, if you are not using DreamHost email hosting, modify the SMTP object to have the correct mail server address. For those of you who aren’t familiar, SMTP stands for Simple Mail Transfer Protocol. server = smtplib.SMTP('smtp.dreamhost.com', 587) server.login(from_addr, 'password') server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr]) Next, hop on over to the destination email client and your Python email should be right there at the top. Send Email from Python with Attachment To send email from python with an attachment, things get slightly more complicated, but definitely doable! Consequently, our email will have multiple parts now: a header, body, and attachment. Thus, we will use the MIMEMultipart class MIME type from the email package to build up our an email object. Let’s take it from square one. Import the following packages. You’ll see that instead of importing message, we are importing MIMEText, MIMEMultipart, and MIMEApplication. import smtplib from os.path import basename from email.mime.text import MIMEText from email.mime.multipart import MIMEMultipart from email.mime.application import MIMEApplication Similar to above, let’s define some variables. from_addr = 'you@example.com' to_addr = 'me@example.com' subject = 'I just sent this attachment from Python!' content = 'How neat is that?' This time, we will build our MIMEMultipart object a bit differently and attach the body to the message as MIMEText. msg = MIMEMultipart() msg['From'] = from_addr msg['To'] = to_addr msg['Subject'] = subject body = MIMEText(content, 'plain') msg.attach(body) Moving right along, we will next read our text file into memory and attach it to our message as MIMEApplication. Of course, make sure a file called test.txt exists in the same directory that you opened the Python interpreter. filename = 'test.txt' with open(filename, 'r') as f: part = MIMEApplication(f.read(), Name=basename(filename)) part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename)) msg.attach(part) As before, login to the email server and send the email. Don’t forget to change the value of ‘password’ to the proper password. Also, if you are not using Dreamhost email hosting, change the SMTP server to the correct address for your setup. server = smtplib.SMTP('smtp.dreamhost.com', 587) server.login(from_addr, 'password') server.send_message(msg, from_addr=from_addr, to_addrs=[to_addr]) Finally, open up your email client and you’ll find a nice looking message with an attachment waiting to be opened. Taking It a Step Further Now that you know how to send simple emails with Python, here are additional ways that you can expand on your newly found knowledge. Send Email to Multiple Recipients from Python It’s also worth pointing out that to_addr can be a list and the send_message command can accept multiple email addresses as recipients. For example, you can send to multiple email addresses like this. to_addr = ['him@example.com', 'her@example.com'] Send Email with Multiple Attachments from Python In addition, if you have multiple attachments to send out, you can loop over the filenames in a way similar to below. filenames = ['test1.txt', 'test2.txt', 'test3.txt'] for filename in filenames: with open(filename, 'r') as f: part = MIMEApplication(f.read(), Name=basename(filename)) part['Content-Disposition'] = 'attachment; filename="{}"'.format(basename(filename)) msg.attach(part) As a result of making it all the way through this Python tutorial, you now have all the knowledge you need to send email from Python. If you are interested in more tutorials like this, check out some of my other Python tutorials here. Most of all, thank you for stopping by. Please let me know if you have questions in the comments below. 1 thought on “How to Easily Send an Email from Python” Regarding the “with” statement, everything following the colon must be indented (four spaces, not a tab).
https://tonyteaches.tech/send-email-from-python/
CC-MAIN-2021-31
refinedweb
924
58.99
ssl — TLS/SSL wrapper for socket objects¶() .... When keylog_filenameis supported and the environment variable SSLKEYLOGFILEis set, create_default_context()enables key logging..8: Support for key logging to SSLKEYLOGFILEwas added.¶ A string mnemonic designating the OpenSSL submodule in which the error occurred, such as SSL, PEMor X509. The range of possible values depends on the OpenSSL version. New in version 3.3. -¶ strong generator. New in version 3.3. ssl. RAND_pseudo_bytes(num)¶)¶.Context. ssl. wrap_socket(sock, keyfile=None, certfile=None, server_side=False, cert_reqs=CERT_NONE, ssl_version=PROTOCOL_TLS,. checked but none of the intermediate CA certificates. The mode requires a valid CRL that is signed by the peer cert’s issuer (its direct ancestor CA). If no proper CRL has been loaded with PROTOCOL_TLS. Deprecated since version 3.6:¶¶¶¶. OP_IGNORE_UNEXPECTED_EOF¶ Ignore unexpected shutdown of TLS connections. This option is only available with OpenSSL 3.0.0 and later. New in version 3.10..¶) sendfile()(but os.sendfilewill be used for plain-text sockets only, else send()will be used) -)¶()¶... Changed in version 3.9: IPv6 address strings no longer have a trailing new line. SSLSocket. cipher()¶()¶.. Note Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the method raises NotImplementedError. New in version 3.8.( Contexts¶)¶ Create a new SSL context. You may pass protocol which must be one of the PROTOCOL_*constants defined in this module. The parameter specifies - 1(1,2) SSLContextdisables SSLv2 with OP_NO_SSLv2by default. - 2(1,2) SSLContextdisables SSLv3 with OP_NO_SSLv3by default. - 3(1,2) TLS 1.3 protocol will be available with PROTOCOL_TLSin OpenSSL >= 1.1.1. There is no dedicated PROTOCOL constant for just TLS 1.3.()¶ Application Layer Protocol Negotiation. After a successful handshake, the SSLSocket.selected_npn_protocol()method will return the agreed-upon protocol. This method will raise NotImplementedErrorif HAS_NPNis False. New in version 3.3. SSLContext. sni_callback¶ sni_callback is set to Nonethen the callback is disabled. Calling this function a subsequent time will disable the previously registered callback. The callback function text. For internationalized domain name, the server name is an IDN A-label ( "xn--pythn-mua.org")._socket(),. Whether to match the peer cert’s. The PROTOCOL_TLS_CLIENTprotocol enables hostname checking by default. With other protocols, hostname checking must be enabled explicitly. Example: import socket, ssl context = ssl.SSLContext(ssl.PROTOCOL_TLSv1_2). keylog_filename¶ Write TLS keys to a keylog file, whenever key material is generated or received. The keylog file is designed for debugging purposes only. The file format is specified by NSS and used by many traffic analyzers such as Wireshark. The log file is opened in append-only mode. Writes are synchronized between threads, but not between processes. New in version 3.8. Note This features requires OpenSSL 1.1.1. New in version 3.7. SSLContext. minimum_version¶ Like SSLContext.maximum_versionexcept it is the lowest supported version or TLSVersion.MINIMUM_SUPPORTED. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.0g or newer. New in version 3.7. SSLContext. num_tickets¶ Control the number of TLS 1.3 session tickets of a TLS_PROTOCOL_SERVERcontext. The setting has no impact on TLS 1.0 to 1.2 connections. Note This attribute is not available unless the ssl module is compiled with OpenSSL 1.1.1 or newer. New in version 3.8... Note Only available with OpenSSL 1.1.1 and TLS 1.3 enabled. Without TLS 1.3 support, the property value is None and can’t be modified New in version 3.8.). Note Only writeable with OpenSSL 1.1.0 or higher. New in version 3.7. Changed in version 3.9.3: The flag had no effect with OpenSSL before version 1.1.1k. Python 3.8.9, 3.9.3, and 3.10 include workarounds for previous versions.¶. Examples¶ Testing for SSL support¶ To test for the presence of SSL support in a Python installation, user code should use the following idiom: try: import ssl except ImportError: pass else: ... # do something that requires SSL support_CLIENT) >>> context.load_verify_locations("/etc/ssl/certs/ca-bundle.crt") (this snippet assumes your operating system places a bundle of all CA certificates in /etc/ssl/certs/ca-bundle.crt; if not, you’ll get an error and have to adjust the location) The PROTOCOL_TLS_CLIENT protocol configures the context for cert validation and hostname verification. verify_mode is set to CERT_REQUIRED and check_hostname is set to True. All other protocols create SSL contexts with insecure defaults. When you use the context to connect to a server, CERT_REQUIRED and check_hostname validate the server certificate: it ensures that the server certificate was signed with one of the CA certificates, checks the signature for correctness, and verifies other properties like validity and identity of the hostname: >>>). Notes on non-blocking sockets¶. Memory BIO Support¶¶. This class has no public constructor. An SSLObjectinstance must.. Manual settings¶.. Cipher selection. HTTP Server
https://docs.python.org/3/library/ssl.html
CC-MAIN-2021-39
refinedweb
809
54.69
- Advertisement Search the Community Showing results for tags 'Tilesets'. Found 25 results OpenGL Chunk batch drawing an isometric map? menyo posted a topic in Graphics and GPU ProgrammingI am currently trying to draw a isometric map in batches, these batches are meshes put together from map data. For each wall and floor I am creating a quad and add that to the chunks mesh. Because I am using alpha blending for a lot of objects I generate these meshes in the order they should be drawn and draw the combined chunk meshes back to front and bottom to top for multiple height levels. This works all great and I can draw a huge part of my map while remaining my target FPS of 60.The meshes and objects go allong the normal axis and I just rotate a Orthographic camera to get it's isometric projection matrix. Now comes the tricky part, the dynamic objects have transparency as well, they are also just quads with a transparent texture. If I draw a mesh later in sequence but behind a transparent object in the world that mesh won't be visible trough the transparency of the object in front of it. I guess this is because the object behind does not exist at the moment of drawing the front object and so it is not being rendered on it's transparent pixels. If there is an obvious not too expensive solution for this issue I am saved. I need to draw moving transparent meshes in between these walls and objects belonging to the chunk mesh and I do not know OpenGL good enough to know if there is a trick for this. I can think of two unwanted options: Adding these dynamic objects to the chunks in the right draw does not seem like a proper solution since that means rearranging the whole mesh each time something moves. Dump the whole chunk idea and just draw each object individually and deal with the loss in frames in other area's. Making dynamic objects full 3D instead of just a quad with a texture. Now I can just draw it before the chunk and depth sorting should sort it. However, I cannot use any transparency on these objects which is a sever limitation and I wanted to avoid going "full 3D". Besides that, I might want to add 2D particle effects at a much later stage so I am really a much happier man if I can sort the drawing out. Don't combine the transparent objects in the chunks mesh and draw all these later, together with the dynamic meshes and properly sorted. The latter seems like the best option now but it feels hacky and error prone. This is a whole other question but if this is a viable solution are there good and proven ways to add and remove meshes/vertex data/indices from a mesh and keeping vertex data and indices properly sorted, I also need to add meshes in the proper draw order as I explained earlier. I guess I need to keep this data somewhere when I create my chunk meshes and look it up later. Anyway, a proper solution (magic trick) to get the draw order and transparency correct in the first place would be awesome. I am using LibGDX btw and here is some code I use for drawing. Gdx.gl.glEnable(GL20.GL_DEPTH_TEST); Gdx.gl.glEnable(GL20.GL_BLEND); // I tried a lot of different combinations of blend functions, but as always this comes closest. Gdx.gl.glBlendFunc(GL20.GL_SRC_ALPHA, GL20.GL_ONE_MINUS_SRC_ALPHA); // Very basic shader just taking in position and UV coordinates. // If the shader can do anything for me in regard of my problem I'd really like to know. shader.begin(); shader.setUniformMatrix("u_worldView", cam.combined); // If I draw the player before the chunk the transparent pixels of the player would not render the chunk. player.getMesh().render(shader, GL20.GL_TRIANGLES); // Drawing the mesh chunk combines of floors, walls and objects of each tile within the chunk. chunk.getCombinedMesh().render(shader, GL20.GL_TRIANGLES); // If I draw the player after the chunk the player would not be drawn if it is behind a transparent mesh like a window or a tree. player.getMesh().render(shader, GL20.GL_TRIANGLES); shader.end(); So is this drawing order problem really that complicated or expensive to easily solve by OpenGL or have I been looking in the wrong places for a solution? 2D Faction Faceoff Dev-Team Invitation HighKey21 posted a topic in Hobby Project ClassifiedsHello~ I've been Developing an Indie Game for about 2 Months now; that is rather close to being a 2D Version of StarCraft 2; you can read about all of the differences from SC2 at the Link near the bottom of the Page. At the Top of the Page in the Link, there are 4 other Links; these can help you get a FULL Understanding of what the Project is; as well as allow you to view its' Progress, and Join the Dev-Team if you should so wish via the Discord. Any people who are considering joining, please know that I understand that you may be busy with other priorities, and I entirely understand; I don't wish to take your time from that, I'd be happy with only as much time as you feel you can spare as I know that this is a daunting Project and that levels of commitment across Members of the Team will vary. While this is starting out as a Hobby Project, I genuinely dont hope that it will forever remain that way. I'm here working on this to kick-start my Career with Design, while getting some much needed experience in the process, so that I can be better when I go to school. Hiring: The Dev-Team is looking for both Artists and Coders, I feel as though we can wait awhile before looking for any Composers simply due to the fact that the game is in a very early state and there just wouldn't be a lot of Sounds to make so far; but I'm open to it if some Composers want to join. For the Current Game Files, they are intended to be interpreted as the Core of the Game; as the Test Phase is only supposed to create a very limited working Version of the Game, most of the Images will have been revamped by the time that Alpha arrives. Artists: I understand that each Artist will have their own Art Style; infact, I'm counting on it. I believe that as many Art Styles as possible would make the game feel really special. Coders: While the Game may be capable of being Coded in C#; I'm entirely open to it also being coded in Java at the same time. Currently, we are working on creating a Program to allow us to link multiple pictures together into one file, all the while attaching custom variables to each image in the file; so that our Coders can easier work with the Images. Link: Thank you for your consideration, have a splendid day. sample0001.png cfrankb posted a gallery image in Member Albums 6.jpg cfrankb posted a gallery image in Member Albums 7.jpg cfrankb posted a gallery image in Member Albums 5.jpg cfrankb posted a gallery image in Member Albums 4.jpg cfrankb posted a gallery image in Member Albums 3.jpg cfrankb posted a gallery image in Member Albums 2.jpg cfrankb posted a gallery image in Member Albums 0001.png cfrankb posted a gallery image in Member Albums 1.jpg cfrankb posted a gallery image in Member Albums. Optimization 2D Tile Map Rendering (C++ w/ SFML) CPPapprentice posted a topic in General and Gameplay ProgrammingHi Forum, in terms of rendering a tiled game level, lets say the level is 3840x2208 pixels using 16x16 tiles. which method is recommended; method 1- draw the whole level, store it in a texture-object, and only render whats in view, each frame. method 2- on each frame, loop trough all tiles, and only draw and render it to the window if its in view. are both of these methods valid? is there other ways? i know method 1 is memory intensive but method 2 is processing heavy. thanks in advance I'm having trouble figuring out the tile size of the tiles in a tileset/tilesheet octopusarms posted a topic in 2D and 3D ArtI. C# Combining a 3D Environment With 2D Characters Ovicior posted a topic in General and Gameplay ProgrammingHey, So for the past month or so I've slowly been working on a melee-combat centered dungeon crawler. Everything has been coming along very well, but environment art is a bit iffy considering our style (We have 3D rendered pixel art with normal maps for lighting in Unity) and doesn't seem to work well in a 2D environment. Due to this, I've been strongly considering making the game 3D and having the environment be made out of 3D tiles created in a voxel editor. This would work much better with our style as a whole, I think, since our art doesn't look especially 2D. We also use a good bit of lighting, which would work better in 3D. The only issue is, I want the game to still play as if it were a 2D game. I want to treat everything as if it's in 2D (which it will be, every asset that's not an environment tile will be a 2D sprite. This includes enemies, attacks, environment objects, etc.) while having the game be technically 3D. I know Enter the Gungeon takes an approach similar to this, where their '2D' game is really a bunch of pixel art mapped onto 3D objects. This provides a really good sense of depth, and also makes it so I don't have to implement typical hacks to make the game appear more 3D. How would one approach this in Unity? My game uses 2D colliders for attacking and movement, and I'm not sure how I'd translate that to a 3D environment (at least to an extent where the game still feels 2D). I understand that I could just completely ignore the y-axis, and treat the z-axis as my new "y-axis", but I have no idea beyond that. My Twitter has a bunch of art if you want to check that out. The devlog also has a good bit of art. C++ Creating maps with Tiled for SFML and C++ game owenjr posted a topic in General and Gameplay ProgrammingHi there. I'm pretty new to this and I don't know if it has been asked before, but here I go. I'm developing a game using SFML and C++. I would like to use the "Tiled" tool to load maps into my game but I don't actually find any tutorial or guide on how to exaclty use it (I know that I have to read an XML file and stuff). I just step into diverse projects that make all a mess. Anyone knows where can I find good information to make my map loader by myself? Thanks in advantage!! [Pixel Artist Wanted] Want to help us finish our 2d Tactics RPG? balthatrix posted a topic in Hobby Project ClassifiedsHey All, My name's Jeron. I'm a programmer of 5 years, and work a full-time job doing web/game development. On the side, I've been working on a cool 2d retro-style tactical RPG with a small team, and we need to find another pixel artist, especially one who likes to create environments. The game is built on Open Gaming Content. That means it uses a lot of the similar rules as D&D games. Here's a screenshot of a combat situation: Here's a channel where you can see some dev updates I did along with some gameplay: The game's core mechanics have already been implemented. Here are a few to give you an idea: -Modular character/equipment animation system (what you see is what you have equipped) -Combat basics -Terrain FX -Stealth/Vision -Level-Up/Multi-Classing/exp. system -Various UI's, like action bar, combat log, inventory window, battle cue -Hotseat multiplayer/Skirmish -Tutorial system -Overmap for in-between combat situations -Spellcasting system Please reply if you'd be interested in learning more about joining the team as a talented pixel artist! Open Source Does anyone need map exporter from NES/SMD games to TMX format? Sanya Boyko posted a topic in Engines and MiddlewareHello! I'm making the CadEditor utility. This is a universal level map editor for NES / SMD games, used to inplace change ROM files. The program has been done for a long time to edit a couple of old console games, now I have to do a little bit of updating it, perhaps turning it into a block editor, like Tiled. Would anyone be interested in such a tool, or is there enough of the existing map editors functionality? And other question. It's possible to do export blocks from all the games already supported by the editor to tileset, and the map itself to the TMX format supported by Tiled editor, as well by many engines - so you can immediately get blocks and a game map from some old games for experiments with them into modern engines. Will anyone need this feature, if I implement it? Tile Explosion for Diagonal Roads Outliner posted a topic in For Beginners's ForumRoads that turn at only 90 degrees seem unnatural, but rendering 45 degree turns is turning into a major headache, because it means that roads cut diagonally across tiles and leave pieces of themselves in neighboring tiles. In addition to having textures to render all the various turns an intersections, we also need every combination of nearby roads sticking out in the corners of the tile. In total that seems to be 4096 road tiles just to cover all the possibilities, even when we restrict roads to only going tile-center to tile-center. We can save memory by doing some flips and rotations in UV coordinates, but I estimate we'd still need dozens of tiles. We can also save some effort by making the tiles transparent beyond the edges of the road, and then layer together multiple tiles when appropriate, either in pre-processing or in the shader. Whatever we do, it is becoming a major headache for something which seems to be so simple in concept. Am I somehow approaching this problem from the wrong direction? Tile Map Editor ( Drawing ) Pether posted a topic in 2D and 3D ArtHeyo, I've been looking for a tool in which I can create tile maps, where I'll see the result in real time / per save so that it will be possible to see transitions between the different tiles directly, without needing to load them up in an editor / game just to check. Are there any tools like this? I have vague memories of seeing one in development a couple of years ago, but all I can find are mapping tools. I'm looking to make simple black and white tile maps at the moment. Preferred to be hexagonal tiles as well! C++ C++ SDL2 tile map collision platformer shouniox posted a topic in General and Gameplay ProgrammingI'm trying to do platformer with a map reading from a file. I did it. It works well. The problem with it is, I don't know how to implement collision for it, that would be more advanced. I would like to add some more things like moving platforms etc. in the future. I wrote this : File Manager : void FileManager::LoadFromFile(std::string fileName, std::vector<std::vector<int>> &map, std::vector<std::vector<int>> &col, std::vector<std::vector<int>> &shadow) { fileName = "Files/Config/" + fileName; std::ifstream openFile(fileName); map.clear(); col.clear(); if (openFile.is_open()) { while (!openFile.eof()) { std::string line; std::getline(openFile, line); std::vector<int> tempVector; if (line.find("[map]") != std::string::npos) { tempVector.clear(); state = MAP; continue; } else if(line.find("[collision]") != std::string::npos) { tempVector.clear(); state = COLLISION; continue; } else if (line.find("[shadows]") != std::string::npos) { tempVector.clear(); state = SHADOW; continue; } std::stringstream str(line); while (str) { std::getline(str, line, ' '); if (line != "") { switch (state) { case MAP: tempVector.push_back(atoi(line.c_str())); break; case COLLISION: tempVector.push_back(atoi(line.c_str())); break; case SHADOW: tempVector.push_back(atoi(line.c_str())); break; } } } switch (state) { if (tempVector.size() > 0) { case MAP: map.push_back(tempVector); break; case COLLISION: col.push_back(tempVector); break; case SHADOW: shadow.push_back(tempVector); break; } tempVector.clear(); } } } openFile.clear(); openFile.close(); } it reads from a file a tile map and a collision map //---------------------------------------------- //------------- GameplayScreen ----------------- bool GameplayScreen::checkCollision(int pLeft, int pTop, int pRight, int pBot) { for (int y = 0; y < col.size(); y++) { for (int x = 0;x < col[y].size(); x++) { if (col[y][x] != 0) { int top = y * 32; int bot = y * 32 + 32; int left = x * 32; int right = x * 32 + 32; if (pRight < left || pLeft > right || pTop > bot || pBot < top) { std::cout << "NIC" << std::endl; return false; } else { std::cout << "COLLISION" << std::endl; return true; } } } } } this method is going through the collision map, and if somewhere in a file is a number 1, it means that this block is collideable. If it's 0 it means this block isn't colideable. So if somewhere is 1 it returns collision. //---------------------------------------------- //-------------- Player engine ----------------- Config::getSM() stands for ScreenManager that handle all screens like main menu, options menu, gameplay screen etc. ->GetGame() returns GameplayScreen instance which handle player class, enemies, tiles. ->getPosX() returns position of a map, because it's moving depends of player direction and position. If movespeed is negative, player is moving left, if positive, player moving right. If checkCollision returns false that mean, there is no collision, so player can easly move left or right. So I did check, if(!Config::getSM()->GetGame()->checkCollision()). The problem is that, it always returns false. How can I make it works? How can I make my code more advance? Industry standard pixel art program Pro Motion NG is coming to Steam BrashMonkey posted a topic in Your AnnouncementsSeptember 20th 2017 BrashMonkey LLC and Cosmigo are pleased to announce that starting September 25th 2017, Pro Motion NG, a new version of Cosmigo's industry standard pixel art and animation tool will be published on Steam by BrashMonkey. Pro Motion can be found in the Steam marketplace here: The September 25th Steam release coincides with the latest build update of ProMotion NG, wich includes lots of great new features and a new lower price-point, making perhaps the most powerful and popular pixel art tool in the industry more accessible than ever to anyone who wants to create pixel art and retro style graphics, tile-sets, tile-maps and animations. Cosmigo was founded in in 1996 and the first version of Pro Motion was released in 1997. It's strong feature set specifically dedicated to pixel art and indexed color mode graphics creation quickly established it as an industry standard for game developers. Each iteration of Pro Motion introduced more features to its arsenal and work-flow enhancements based on user feedback. Pro Motion NG is the latest iteration and culmination of well over a decade of development and direct user feedback. BrashMonkey LLC was founded in May of 2012, shortly after the release of their flagship product, Spriter Pro, which played a key role in making modular 2d animation commonplace and accessible for independent game developers and small studios. Spriter Pro differs from the majority of the competing tools that have arrived since its release in that it has built in support for working with pixel art and features for taking advantage of indexed color mode images. Spriter's support for pixel art make it the only modular animation tool perfect to join forces with Pro Motion NG in a tool-chain for the creation of 2d pixel art style games. 2D [Java] LibGDX Isometric map - movement of an entity ben berizovsky posted a topic in Graphics and GPU ProgrammingHello there, I am new to the forum and in game development in general! I am currently building a simulator for some game, and I am having a few problems already, and I am using the libgdx framework. I have an isometric map drawn, where each tile is a spot that only one entity can be at. An entity can either move left, right or just forward in a straight line. Now this is what it looks at the moment: As you can see, my ship entity is located at 1,1. I want to start with adding a function that moves the ship in a straight line, so I need to move this ship to 1,2. So I have a Vector2 that represents the ship's position, I made a dummy one in the local class where it paints entities, and the map and it's set to isometric coordinates of 1,1: r = new TextureRegion(texture, location.getX(), location.getY(), location.getWidth(), location.getHeight()); local = new Vector2(getIsometricX(1,1, r), getIsometricY(1,1, r)); "r" is my texture region, which is my sprite image off the spritesheet. Now I have set a target position to 1,2: target = new Vector2(getIsometricX(1,2, r), getIsometricY(1,2, r)); So now my question is, how can I make that ship move to the target position? If i add 1 to x and y every tick, it will just move too much to the right. This is how I paint everything: @Override public void render() { batch.setProjectionMatrix(camera.combined); batch.begin(); // Render the map renderSeaBattle(); // Render ships renderEntities(); batch.end(); } And the map painting: private void renderSeaBattle() { // The map tiles GameTile[][] tiles = map.getTiles(); for (int i = 0; i < tiles.length; i++) { for(int j = 0; j < tiles.length; j++) { GameTile tile = tiles[j]; Texture texture = tile.getTexture(); int x = (i * GameTile.TILE_WIDTH / 2) - (j * GameTile.TILE_WIDTH / 2) -texture.getWidth() / 2; int y = (i * GameTile.TILE_HEIGHT / 2) + (j * GameTile.TILE_HEIGHT / 2) -texture.getHeight() / 2; batch.draw(texture, x, y); } } } And the entities: private void renderEntities() { batch.draw(r, local.x + location.getOffsetx(), local.y + location.getOffsety()); } location is an instance that contains the offset position for that specific sprite, because not all sprites are the same size, so to center it on the tile, each one has set offsetX and Y. And this is my coordinate conversion methods: public int getIsometricX(int x, int y, TextureRegion region) { return (x * GameTile.TILE_WIDTH / 2) - (y * GameTile.TILE_WIDTH / 2) - (region.getRegionWidth() / 2); } public int getIsometricY(int x, int y, TextureRegion region) { return (x * GameTile.TILE_HEIGHT / 2) + (y * GameTile.TILE_HEIGHT / 2) - (region.getRegionHeight() / 2); } After I do the straight line, how can I create left/right movements in curves? Thanks! Hexagon Game Tiles pat thompson posted a gallery image in Member Albums From the album: PK Game ArtHexagon terrain tile set sample for the Mouchet Software game "Cohorts". These tiles are meant to be aerial views, and play important strategic roles in the game. Should I use tiles or a single large image for my games background mrpeed posted a topic in For Beginners's Forum? - Advertisement
https://www.gamedev.net/search/?type=&tags=Tilesets
CC-MAIN-2018-39
refinedweb
3,906
60.55
Memory allocation and deallocation have always been the bane of developers. Even the most experienced C++ and COM programmer is faced with memory leaks and attempts to access nonexistent objects that either never existed or have already been destroyed. In an effort to remove these responsibilities from the programmer, .NET implements a memory management system that features a managed heap and automatic Garbage Collection. Recall from Chapter 2, "C# Language Fundamentals," that the managed heap is a pre-allocated area of memory that .NET uses to store reference types and data. Each time an instance of a class is created, it receives memory from the heap. This is a faster and cleaner solution than programming environments that rely on the operating system to handle memory allocation. Allocating memory from the stack is straightforward: A pointer keeps track of the next free memory address and allocates memory from the top of the heap. The important thing to note about the allocated memory is that it is always contiguous. There is no fragmentation or complex overhead to keep track of free memory blocks. Of course, at some point the heap is exhausted and unused space must be recovered. This is where the .NET automatic Garbage Collection comes into play. Each time a managed object is created, .NET keeps track of it in a tree-like graph of nodes that associates each object with the object that created or uses it. In addition, each time another client references an object or a reference is assigned to a variable, the graph is updated. At the top of this graph is a list of roots, or parts of the application that exist as long at the program is running (see Figure 4-9). These include static variables, CPU registers, and any local or parameter variables that refer to objects on the managed heap. These serve as the starting point from which the .NET Framework uses a reference-tracing technique to remove objects from the heap and reclaim memory. The Garbage Collection process begins when some memory threshold is reached. At this point, the Garbage Collector (GC) searches through the graph of objects and marks those that are "reachable." These are kept alive while the unreachable ones are considered to be garbage. The next step is to remove the unreferenced objects (garbage) and compact the heap memory. This is a complicated process because the collector must deal with the twin tasks of updating all old references to the new object addresses and ensuring that the state of the heap is not altered as Garbage Collection takes place. The details of Garbage Collection are not as important to the programmer as the fact that it is a nondeterministic (occurs unpredictably) event that deals with managed resources only. This leaves the programmer facing two problems: how to dispose of unmanaged resources such as files or network connections, and how to dispose of them in a timely manner. The solution to the first problem is to implement a method named Finalize that manages object cleanup; the second is solved by adding a Dispose method that can be called to release resources before Garbage Collection occurs. As we will see, these two methods do not operate autonomously. Proper object termination requires a solution that coordinates the actions of both methods. Core Note Garbage Collection typically occurs when the CLR detects that some memory threshold has been reached. However, there is a static method GC.Collect that can be called to trigger Garbage Collection. It can be useful under controlled conditions while debugging and testing, but should not be used as part of an application. Objects that contain a Finalize method are treated differently during both object creation and Garbage Collection than those that do not contain a Finalize method. When an object implementing a Finalize method is created, space is allocated on the heap in the usual manner. In addition, a pointer to the object is placed in the finalization queue (see Figure 4-9). During Garbage Collection, the GC scans the finalization queue searching for pointers to objects that are no longer reachable. Those found are moved to the freachable queue. The objects referenced in this queue remain alive, so that a special background thread can scan the freachable queue and execute the Finalize method on each referenced object. The memory for these objects is not released until Garbage Collection occurs again. To implement Finalize correctly, you should be aware of several issues: Finalization degrades performance due to the increased overhead. Only use it when the object holds resources not managed by the CLR. Objects may be placed in the freachable queue in any order. Therefore, your Finalize code should not reference other objects that use finalization, because they may have already been processed. Call the base Finalize method within your Finalize method so it can perform any cleanup: base.Finalize(). Finalization code that fails to complete execution prevents the background thread from executing the Finalize method of any other objects in the queue. Infinite loops or synchronization locks with infinite timeouts are always to be avoided, but are particularly deleterious when part of the cleanup code. It turns out that you do not have to implement Finalize directly. Instead, you can create a destructor and place the finalization code in it. The compiler converts the destructor code into a Finalize method that provides exception handling, includes a call to the base class Finalize, and contains the code entered into the destructor: Public class Chair { public Chair() { } ~Chair() // Destructor { // finalization code } } Note that an attempt to code both a destructor and Finalize method results in a compiler error. As it stands, this finalization approach suffers from its dependency on the GC to implement the Finalize method whenever it chooses. Performance and scalability are adversely affected when expensive resources cannot be released when they are no longer needed. Fortunately, the CLR provides a way to notify an object to perform cleanup operations and make itself unavailable. This deterministic finalization relies on a public Dispose method that a client is responsible for calling. Although the Dispose method can be implemented independently, the recommended convention is to use it as a member of the IDisposable interface. This allows a client to take advantage of the fact that an object can be tested for the existence of an interface. Only if it detects IDisposable does it attempt to call the Dispose method. Listing 4-10 presents a general pattern for calling the Dispose method. public class MyConnections: IDisposable { public void Dispose() { // code to dispose of resources base.Dispose(); // include call to base Dispose() } public void UseResources() { } } // Client code to call Dispose() class MyApp { public static void Main() { MyConnections connObj; connObj = new MyConnections(); try { connObj.UseResources(); } finally // Call dispose() if it exists { IDisposable testDisp; testDisp = connObj as IDisposable; if(testDisp != null) { testDisp.Dispose(); } } } This code takes advantage of the finally block to ensure that Dispose is called even if an exception occurs. Note that you can shorten this code by replacing the try/finally block with a using construct that generates the equivalent code: Using(connObj) { connObj.UseResources() } When Dispose is executed, the object's unmanaged resources are released and the object is effectively disposed of. This raises a couple of questions: First, what happens if Dispose is called after the resources are released? And second, if Finalize is implemented, how do we prevent the GC from executing it since cleanup has already occurred? The easiest way to handle calls to a disposed object's Dispose method is to raise an exception. In fact, the ObjectDisposedException exception is available for this purpose. To implement this, add a boolean property that is set to true when Dispose is first called. On subsequent calls, the object checks this value and throws an exception if it is true. Because there is no guarantee that a client will call Dispose, Finalize should also be implemented when resource cleanup is required. Typically, the same cleanup method is used by both, so there is no need for the GC to perform finalization if Dispose has already been called. The solution is to execute the SuppressFinalize method when Dispose is called. This static method, which takes an object as a parameter, notifies the GC not to place the object on the freachable queue. Listing 4-11 shows how these ideas are incorporated in actual code. public class MyConnections: IDisposable { private bool isDisposed = false; protected bool Disposed { get{ return isDisposed;} } public void Dispose() { if (isDisposed == false) { CleanUp(); IsDisposed = true; GC.SuppressFinalize(this); } } protected virtual void CleanUp() { // cleanup code here } ~MyConnections() // Destructor that creates Finalize() { CleanUp(); } public void UseResources() { // code to perform actions if(Disposed) { throw new ObjectDisposedException ("Object has been disposed of"); } } } // Inheriting class that implements its own cleanup public class DBConnections: MyConnections { protected override void CleanUp() { // implement cleanup here base.CleanUp(); } } The key features of this code include the following: A common method, CleanUp, has been introduced and is called from both Dispose and Finalize . It is defined as protected and virtual, and contains no concrete code. Classes that inherit from the base class MyConnections are responsible for implementing the CleanUp. As part of this, they must be sure to call the Cleanup method of the base class. This ensures that cleanup code runs on all levels of the class hierarchy. The read-only property Disposed has been added and is checked before methods in the base class are executed. In summary, the .NET Garbage Collection scheme is designed to allow programmers to focus on their application logic and not deal with details of memory allocation and deallocation. It works well as long as the objects are dealing with managed resources. However, when there are valuable unmanaged resources at stake, a deterministic method of freeing them is required. This section has shown how the Dispose and Finalize methods can be used in concert to manage this aspect of an object's life cycle.
https://flylib.com/books/en/4.253.1.52/1/
CC-MAIN-2020-45
refinedweb
1,652
53.1
A guest post by Christopher Hiller, the author of Developing an AngularJS Edge and a Software Architect for Decipher, Inc. He enjoys gaming, coding, and gleaming the cube. He can be reached on GitHub or as @misterhiller on Twitter. AngularJS is not a silver bullet. It doesn’t just magically generate maintainable and extensible apps. You might get lucky with a small app and write it from scratch elegantly and efficiently, using each of AngularJS’ features correctly, and maybe you even have 100% unit test coverage (read my post on writing tests and stomping bugs). Your app might do one thing, and do it flawlessly. This series, however, is not about those applications. This series is about applications that: - May be giant, frothing behemoths, yet… - Might be delicate flowers, whose petals shed at the slightest breeze - Have been written by multiple developers, but you didn’t write it - Integrate closely with other non-AngularJS apps, or have non-AngularJS apps fully embedded into it - Have lackluster unit tests or no unit tests whatsoever - Use a scaffolding tool designed for much smaller applications - Don’t have anyone on the team that fully understands the implementation - Take many weeks or even months to fully grasp to a new team member And finally, if you’re 90% through developing a simple feature for this application and think, “you know what? I should have finished this a week ago,” and you still have 90% left to go, this post is for you! There are steps you can take to improve your application and get it back in shape for easy development. That means quicker bug fixes, less bugs, and the faster implementation of new features. Taking some time to knock these out will save you from experiencing a lot of pain down the road. Modularization In an AngularJS context, modularization is organization by function instead of type. To compare, given arrays time = [60, 60, 24, 365] and money = [1, 5, 10, 25, 50], both are of the same type, but their functions are completely different. That means your components (controllers, filters, directives) will live in modules instead of wherever they live now. The benefits of modularization includes the following: - Encapsulation. Developers access the modules you create by including them within other modules. If you want the whole enchilada, you can still get it, but if you only want a bite, it’s easy to take. If your module relies on nothing but itself, you can easily make that module available to other applications. - Context. Each module provides a context. Given horn.service.jsand horn.directive.js, if they belong to modules instrumentand headrespectively, you get a hint of their purposes. Without a module, there is no context and no meaning. This is especially important to developers new to the application, who will find it easier to connect the dots. - Testability. If you have to include your entire application every time you write a unit test, that’s not particularly unit -y, now is it? With modules, you will still need to include the module itself (or the test can’t access your component), but this is leagues better than including everything and potentially having to stub out run()and config()blocks of other modules. When to Modularize If your directory structure looks like this (and your app is large) you should modularize: Or even if it looks like this… Then you need to modularize. You have everything grouped by component type, which is fine in smaller applications because there aren’t many components. But soon those directories bloat. The locations of the files have nothing to do with what subsystem of your app they live in, and even the filename has no context. This is not helping you. Let’s create modules. How to Modularize Here is a 13 step guide to modularization in AngularJS: - Unless you’re on pre-1.0 code, you probably already have a module declared for your main application. If not, declare one in its own file: …and upgrade. It will be painful, but not as painful as rewriting your app from scratch, because you should be able to save most of your code. Modularize while you upgrade, because you’re going to have to reorganize into modules anyway. (Upgrade to the newest version. You might even be able to retain the thissyntax in your controllers.) - Bring up your app in the browser. Define sections or subsystems or whatever you want to call them. If you need a hint, peek at the markup or even the controller hierarchy; it says a lot about your structure. - Each section of your app is a bucket, so look at your files (all front-end files; not just .jsor AngularJS files) and toss them into buckets. If you find that one file belongs in multiple buckets, one of two things are happening: - You have common functionality. It’s OK to create a bucket explicitly for this, but tread lightly as you might want to create a bucket within a bucket instead. - You have functionality that needs splitting up. Make a note of this; we’ll deal with it later. If you can put a bucket within another bucket, now’s the time to do it. - Name your buckets if you haven’t already. Create directories (in the filesystem; we’re talking about real life now) for each bucket and subdirectories for, well, subbuckets. - Move all of your files into their proper buckets. You may want to keep images in an images/directory or CSS/LESS files in their own place; it’s your decision. At a minimum, this should be any AngularJS-specific .jsfile or a partial. - In each of those directories, create a .jsfile named corresponding to its directory. If you have a naming scheme (like in the second directory tree above), use it. For example, if you have a bucket named nonsense, you may have nonsense/nonsense.module.js. - In each of these files, write: where myModuleis your bucket/directory/file name. The second example above now looks like this: - Modify your files. A search/replace across many .jsfiles would probably do it. You used to have every controller, filter, service, and so on, belonging to the myAppmodule. Eventually, myapp.module.jsshould be small, and it will serve mainly as a namespace. Find occurrences of your myAppmodule name, and see if you can’t replace them (within the proper directory) with myApp.myModule. - If you have any files that need to be manually split because they belong in two modules, do it now. - Partials may need special attention because to load one you need a path, and that path just changed. Find where you reference your partials and change as necessary. What I like to do first is this: Then, if you need the directory path for your module, inject myModuleConstinto component, and put it on your controller’s $scopeif the view needs it. If you need to reorganize again in the future, this will save time, because of “DRY”. - Much like the above, your paths have changed, so update whatever loads your .jsfiles and change those paths too. First, load angular.js, then you will want to explicitly load the *.module.jsfiles and all component files thereafter, or a component will throw an exception because it can’t find it’s mommy/module. If you have a naming convention, this is easier, because you know modules have the suffix .module.js. RequireJS can help you with this sort of thing, but that’s beyond the scope here. - Because AngularJS’ module system (as of this writing) is rather rudimentary, all you need to do to include everything is to modify your root myAppmodule and include all of your submodules. The myapp.module.jsabove might look like: …in addition to whatever third-party modules you may require. - Finally, take anything out of your main application module ( myapp.module.jshere) that you can, and put that stuff into a proper module in its module definition file ( *.module.jsin the example). run(), config(), constant(), and value()blocks all commonly live in a module file. You can also put these blocks in separate files to ease unit testing. Application-wide settings should still live in your main module file. Conclusion That’s the 13-step guide to modularization. The next article in this series will discuss adding (more) unit tests to a large AngularJS application. Happy Angularing! Don’t forget your license. For more details about AngularJS, see the resources below or explore our AngularJS library on Safari. bl4de What about such functionality, like for example models and collections used in many modules? For example, I’ve got some front-end logic to manipulate objects such as ‘User’, ‘Customer’ and even the whole collections of them. Should I create separate bucket ( e.g. models/, collections/ or something) and then include them something like this way: angular.module(“MyApp.Users”, [“MyApp.models.userModel”, “MyApp.collections.userCollection”]); angular.module(“MyApp.Customers”, [“MyApp.models.customerModel”]); angular.module(“MyApp”, [“MyApp.Users”, “MyApp.Customers”]); Am I thinking right? Christopher Hiller bl4de, it kind of depends what the xCollection and xModel modules consist of. If I were setting up something like this I’d probably define a MyApp.User or (or MyApp.Users) module and that would house all components corresponding to users. I’m not understanding the need to break it up into “collection” and “model” submodules? Smajl Good article. This is very close to how I modularize our enterprise-level app these days. ;)
https://www.safaribooksonline.com/blog/2014/03/27/13-step-guide-angularjs-modularization/
CC-MAIN-2016-07
refinedweb
1,584
65.01
Engineering Equation Solver for Microsoft Windows Operating Systems Commercial and Professional Versions F C F-Chart Software email : info@fchart.com The authors make no guarantee that the program is free from errors or that the results produced with it will be free of errors and assume no responsibility or liability for the accuracy of the program or for the results that may come from its use. EES was compiled with DELPHI 5 by Borland Registration Number__________________________ ALL CORRESPONDENCE MUST INCLUDE THE REGISTRATION NUMBER V6.160 EES Engineering Equation Solver for Microsoft Windows Operating Systems F C F-Chart Software email : info@fchart.com ............................................................................................................................................................ 1 Chapter 1: Getting Started ....................................... 37 Diagram Window ................................................................................................................................................................................................................................. 24 Solution Window................................................................. 151 ii ............................................................ 99 The Plot Menu.............................. 107 The Windows Menu.............................................................. 9 Chapter 2: EES Windows ................................................................... ......................................................................................................................................... 77 The Options Menu ............................................................................................................................................................................................................................... 33 Lookup Table Window................... 21 Formatted Equations Window ...................................................................... 59 Chapter 3: Menu Commands . 120 Chapter 4: Built-in Functions ............ 51 Debug Window............................................................................................... 63 The File Menu ............................................... 123 Mathematical Functions ........... 31 Parametric Table Window ............................................................................................................................................................................................ 117 The Help Menu .............................................................................................................................................. 29 Residuals Window......................................................................................................................................................................................................................................................................... 19 General Information ........................................................................................................................................................................................................................................................................................ 132 Thermophysical Property Functions.............. 119 The Textbook Menu ................... 134 Using Lookup Files and the Lookup Table .................. 70 The Calculate Menu ............ 6 An Example Thermodynamics Problem............................................ 5 Starting EES ........................................................................................................... 5 Installing EES on your Computer.......................................................... 73 The Search Menu ........................................................................... 123 String Functions...................... 27 Arrays Window........................................................ 93 The Tables Menu ............................. 19 Equations Window ..................................Table of Contents Overview .......................... 5 Background Information............................................ 63 The Edit Menu ..................... 39 Plot Window .......... 143 The $OpenLookup and $SaveLookup Directives . ....................................DLP Format ............................ 223 Blocking Equation Sets ........................... 233 Appendix D: Example Problem Information ............... 200 Creating and Using Macro Files ......... 199 Integration and Differential Equations ........................ 154 EES Procedures ....................... 153 EES Functions . 162 Modules and Subprograms ................................. 176 EES Compiled Procedures (........................................... 226 Determination of Minimum or Maximum Values............................................................................................................................................................................................................ 180 Compiled Procedures with the ...............Chapter 5: EES Modules............................................................ 187 Chapter 7: Advanced Features ............... 163 Library Files ............................................................................................ 156 Single-Line If Then Else Statements ......................................................................................................................................................... ........................... 219 Appendix B: Numerical Methods used in EES.. 189 String Variables ........................................................................................................... 185 Help for Compiled Routines.................................................................................DLP Files) ... 161 Warning Procedure ............................ 190 Array Variables....... 173 EES Compiled Functions (...a Pascal Example ....................................... 243 -iii- ...................... 228 Numerical Integration...................................................................................................a FORTRAN Example........... 211 Appendix A: Hints for Using EES ...... 183 Multiple Files in a Single Dynamic Link Library (............. 169 The $INCLUDE directive ...........................................FDL Format .............. 229 References for Numerical Methods .................................................. 197 Using the Property Plot.DLF Files)......................................................................................................................................................................................................................................... 159 GoTo and Repeat-Until Statements ..............................................................................FDL and .............................. 160 Error Procedure.......................................................................................................................................................................................................................................................................... 166 $COMMON Directive .............................. 179 Compiled Procedures with the ..................... 170 The $EXPORT directive ............................................... 194 The DUPLICATE Command ...... 231 Appendix C: Adding Property Data to EES ................................................................................................................................... 158 Multiple-Line If Then Else Statements ............ Functions and Procedures .............. 223 Solution to Algebraic Equations......... 172 Chapter 6: Compiled Functions and Procedures .................................... 171 The $IMPORT directive ............................................................................................................... 196 Matrix Capabilities ................... 173 The PWF Example Compiled Function.......................................DLL) ...................................................... 189 Complex Variables . These three methods of adding functional relationships provide very powerful means of extending the capabilities of EES. This manual describes the version of EES developed for Microsoft Windows operating systems. and modules can be saved as library files which are automatically read in when EES is started.__________________________________________________________________________ Overview __________________________________________________________________________ EES (pronounced 'ease') is an acronym for Engineering Equation Solver. do optimization. as are psychrometric functions and JANAF table data for many common gases. which are selfcontained EES programs that can be accessed by other EES programs. methane. written in a high-level language such as Pascal. The functions. procedures. ammonia. This feature simplifies the process for the user and ensures that the solver will always operate at optimum efficiency. the steam tables are implemented such that any thermodynamic property can be obtained from a built-in function call in terms of any two other properties. EES provides many built-in mathematical and thermophysical property functions useful for engineering calculations. C or FORTRAN. The library of mathematical and thermophysical property functions in EES is extensive. Similar capability is provided for most organic refrigerants (including some of the new blends). Second. provide linear and non-linear regression and generate publication-quality plots. EES can also solve differential equations. EES also provides support for user-written modules. There are two major differences between EES and existing numerical equation-solving programs. including Windows 95/98/2000 and Windows NT 4. Third. The basic function provided by EES is the solution of a set of algebraic equations. equations with complex variables. First. Second. Transport properties are also provided for most of these substances. EES automatically identifies and groups equations which must be solved simultaneously. Versions of EES have been developed for Apple Macintosh computers and for the Windows operating systems. the EES language supports user-written functions and procedure similar to those in Pascal and FORTRAN. Air tables are built-in. but it is not possible to anticipate every user's need. EES allows the user to enter his or her own functional relationships in three ways. compiled functions and procedures. a facility for entering and interpolating tabular data is provided so that tabular data can be directly used in the solution of the equation set. carbon dioxide and many other fluids. can be dynamically-linked into EES using the dynamic link library capability incorporated into the Windows operating system. For example. First. 1 . it is no more difficult to do design problems than it is to solve a problem for a fixed set of independent variables. it is necessary for the student to work problems. the capabilities of this program are extensive and useful to an expert as well. Chapter 4 describes the built-in mathematical and thermophysical property functions and the use of the Lookup Table for entering tabular data. Interesting practical problems that may have implicit solutions. EES is particularly useful for design problems in which the effects of one or more parameters need to be determined. EES offers the advantages of a simple set of intuitive commands that a novice can quickly learn to use for solving any algebraic problems. The user identifies the variables that are independent by entering their values in the table cells. it is ideally suited for instruction in mechanical engineering courses and for the practicing engineer faced with the need for solving practical problems. The time and effort required to do problems in the conventional manner may actually detract from learning of the subject matter by forcing the student to be concerned with the order in which the equations should be solved (which really does not matter) and by making parametric studies too laborious. are often not assigned because of their mathematical complexity. further use of the tables does not contribute to the student's grasp of the subject. To learn the material in these courses. EES will calculate the values of the dependent variables in the table. procedures and modules and saving them in 2 .The motivation for EES rose out of experience in teaching mechanical engineering thermodynamics and heat transfer. Chapter 5 provides instructions for writing EES functions. much of the time and effort required to solve problems results from looking up property information and solving the appropriate equations. which is similar to a spreadsheet. fluid mechanics. EES can be used for many engineering applications. With EES. Chapter 2 provides specific information on the various functions and controls in each of the EES windows. The program provides this capability with its Parametric Table. EES allows the user to concentrate more on design by freeing him or her from mundane chores. such as those involving both thermodynamic and heat transfer considerations. The remainder of this manual is organized into seven chapters and five appendices. nor does algebra. EES also provides capability to propagate the uncertainty of experimental data to provide uncertainty estimates of calculated variables. and heat transfer. Once the student is familiar with the use of property tables. A new user should read Chapter 1 which illustrates the solution of a simple problem from start to finish. The relationship of the variables in the table can then be displayed in publication-quality plots. Chapter 3 is a reference section that provides detailed information for each menu command. However. The large data bank of thermodynamic and transport properties built into EES is helpful in solving problems in thermodynamics. However. Chapter 7 describes a number of advanced features in EES such as the use of string. 3 . A number of example problems are provided in the Examples subdirectory included with EES. the solution of simultaneous differential and algebraic equations. Appendix B describes the numerical methods used by EES. can be integrated with EES. Appendix A contains a short list of suggestions. Appendix D indicates which features are illustrated in the example problems provided with EES. and property plots. written as Windows dynamic-link library (DLL) routines. Chapter 6 describes how compiled functions and procedures.Library files. Appendix C shows how additional property data may be incorporated into EES. complex and array variables. 4 . CHAPTER1 __________________________________________________________________________ __________________________________________________________________________ Getting Started Installing EES on your Computer EES is distributed in a self-installing compressed form in a file called SETUP_EES. Starting EES The default installation program will create a directory named C:\EES32 in which the EES files are placed. that file will be automatically loaded. the installation program will start automatically when the CD is placed in the drive. place the first disk in the drive and select the Run command from the Start menu and then enter A:\SETUP_EES. Here A: is your floppy drive designation.exe. Double-clicking the left mouse button on the EES program or file icon will start the program.EES file if you do not wish to have it appear when the program is started. To install EES from a floppy disk. The EES program icon shown above will identify both the program and EES files. EES will load the HELLO. Otherwise. the installation program will provide a series of prompts which will lead you through the complete installation of the EES program.EES file which briefly describes the new features in your version. In either case. it is necessary execute the SETUP_EES installation program. To install EES. If you double-clicked on an EES file.exe which may be provided on two floppy disks or on a CD. You can delete or rename the HELLO. If you are installing EES from a CD. 5 . the version number and other information. Detailed help is available at any point in EES. 6 . The version number and registration information will be needed if you request technical support. Pressing the F1 key will bring up a Help window relating to the foremost window. Click the OK button to dismiss the dialog window.Chapter 1 Getting Started Background Information EES begins by displaying a dialog window that shows registration information. Clicking on an underlined word (shown in green on color monitors) will provide help relating to that subject. Clicking the Contents button will present the Help index shown below. similar to a spreadsheet. The Edit menu provides the editing commands to cut. A command is also provided for displaying information on built-in and user-supplied functions. The Tables menu contains commands to set up and alter the contents of the Parametric and Lookup Tables and to do linear regression on the data in these tables. if you wish. default information. The System menu is not part of EES. with a control in the Preferences dialog (Options menu). Detailed descriptions of the commands appear in Chapter 3. The Lookup table holds user-supplied data which can be interpolated and used in the solution of the equation set. resizing. and program preferences. allows the equation set to be solved repeatedly while varying the values of one or more variables. The Calculate menu contains the commands to check. the unit system. and paste information. The Plot menu provides commands to modify an existing plot or prepare a new plot of data in the Parametric. See the discussion of the Load Textbook command File menu in Chapter 3. It holds commands that allow window moving. and switching to other applications. or Array tables. The Windows menu provides a convenient method of bringing any of the EES windows to the front or to organize the windows. The Search menu provides Find and Replace commands for use in the Equations window. The toolbar can be hidden. a few words will appear to explain the function of that button. but rather a feature of the Windows Operating System. copy.) A brief summary of their functions follows. The Help menu provides commands for accessing the online help documentation. format and solve the equation set. The System menu represented by the EES icon appears above the file menu. Lookup. The Options menu provides commands for setting the guess values and bounds of variables. merging and saving work files and libraries. If you move the cursor over a button and wait for a few second.Getting Started Chapter 1 EES commands are distributed among nine pull-down menus. The Parametric Table. and printing. (A tenth user-defined menu can be placed to the right of the Help menu. Curve-fitting capability is also provided. The toolbar contains small buttons which provide rapid access to many of the most frequently used EES menu commands. Note the a toolbar is provided below the menu bar. The File menu provides commands for loading. 7 . Chapter 1 Getting Started The basic capability provided by EES is the solution of a set of non-linear algebraic equations. If you wish. A dialog window will appear indicating the progress of the solution. To demonstrate this capability. Click the Continue button. The solution to this equation set will then be displayed. the button changes from Abort to Continue. Select the Solve command from the Calculate menu. 8 . you may view the equations in mathematical notation by selecting the Formatted Equations command from the Windows menu. Note that EES makes no distinction between upper and lower case letters and the ^ sign (or **) is used to signify raising to a power. When the calculations are completed. start EES and enter this simple example problem in the Equations window. In addition. State 1 T = 50°C P = 700 Vel = 15 m/s State 2 T=? P = 300 kPa Vel = ? To solve this problem. the pressure is 300 kPa. specific enthalpy normally has units of [kJ/kg] so some units conversions may be needed. A steady-state energy balance on the valve is: 2 Vel1 Vel2 2 " " m1 h1 + = m2 h 2 + 2 2 (5) where h is the specific enthalpy and Vel2/2 is the specific kinetic energy. so that the mass balance is: m1 = m2 (1) (2) (3) where m1 = A1 Vel1 / v1 m1 = A2 Vel2 / v2 m = mass flowrate [kg/s] A = cross-sectional area [m2] Vel = velocity [m/s] v = specific volume [m3/kg] We know that A1 = A2 (4) The valve is assumed to be well-insulated with no moving parts. mass flow rate and velocity at the valve exit. The inlet and outlet fluid areas are both 0. Refrigerant-134a enters a valve at 700 kPa.0110 m2. The mass flow is steady. The heat and work effects are both zero. typical of that which may be encountered in an undergraduate thermodynamics course. 50°C with a velocity of 15 m/s. In SI units. EES provides unit conversion capabilities with the CONVERT function as documented in Chapter 4. Determine the temperature. The problem. it is necessary to choose a system and then apply mass and energy balances. is as follows. the Check Units command (Calculate menu) can be applied to 9 .Getting Started Chapter 1 An Example Thermodynamics Problem A simple thermodynamics problem will be set up and solved in this section to illustrate the property function access and equation solving capability of EES. At the exit of the valve. The system is the valve. P ) 1 (6) (7) (8) (9) Ordinarily. P2 ) v2 = v (T2 . the solution to the problem is defined. however. However. primarily because the kinetic energy effects are usually small and also because these terms make the problem difficult to solve. This is where EES can help. set the unit system for the built-in thermophysical properties functions. From relationships between the properties of R134a: h2 = h (T2 . There are nine unknowns: A2. A1. m2 . Start EES and select the New command from the File menu. with EES. A blank Equations window will appear. P in kPa. It is now only necessary to solve the equations. These defaults may have been changed during a previous use. The values of T1. Since there are 9 equations. the computational difficulty is not a factor. Click on the controls to set the units as shown above. h2. Before entering the equations. v2. Vel2. EES is initially configured to be in SI units with T in °C. P1. To view or change the unit system.Chapter 1 Getting Started determine check that all unit conversions have been made and the units in each equation are dimensionally consistent. T2. Click the OK button (or press the Return key) to accept the unit system settings. v1. P2 ) h1 = h (T1 . P ) 1 v1 = v (T1 . m1 . The user can solve the problem with the kinetic energy terms and judge their importance. the terms containing velocity are neglected. and specific property values in their customary units on a mass basis. h1. select Unit System from the Options menu. Vel11 and P2 are known. 10 . 3. Blank lines and spaces may be entered as desired since they are ignored. String variables (Chapter 7) are identified with a $ as the last character in the variable name. The position of knowns and unknowns in the equation does not matter. 2. Comments must be enclosed within braces { } or within quote marks " ". Comments within quotes will also be displayed in the Formatted Equations window. Formatting rules are as follows: 1. The caret symbol ^ or ** is used to indicate raising to a power. Comments are normally displayed in blue on a color monitor. the Equations window will appear as shown. After entering the equations for this problem and (optionally) checking the syntax using the Check/Format command in the Calculate menu. e. X[5. EES will recognize the comma (rather than a decimal point) as a decimal separator. The order in which the equations are entered does not matter.)1. Text is entered in the same manner as for any word processor. 11 .g. the semicolon (rather than the comma) as an argument separator. 6. 4. The maximum length of a variable name is 30 characters.Getting Started Chapter 1 The equations can now be entered into the Equations window. Variable names must start with a letter and consist of any keyboard characters except ( ) ‘ | * / + .. 1 If a comma is selected as the Decimal Symbol in the Windows Regional Settings Control Panel. Multiple equations may be entered on one line if they are separated by a semi-colon (. Array variables (Chapter 7) are identified with square braces around the array index or indices. 7. The maximum line length is 255 characters. Comments within braces may be nested in which case only the outermost set of { } are recognized. Other formatting options are set with the Preferences command in the Options menu.. EES will (optionally) change the case of all variables to match the manner in which they first appear.3].^ { } : " or . and the colon : (rather than the semicolon) as the equation separator. 8. 5. Comments may span as many lines as needed. Upper and lower case letters are not distinguished. The information in the rectangle may be changed.) An easy way to enter functions. An example of the function showing the format will appear in the Example rectangle at the bottom. (For psychrometric functions. to bring it into view. Click on the ‘Thermophysical properties’ radio button. U. P. if needed. relative humidity. and B. The following arguments are the independent variables preceded by a single identifying letter and an equal sign. S. Allowable letters are T. if necessary. dewpoint temperature. and X. The first argument of the function is the substance name. specific enthalpy. 12 . The list of built-in thermophysical property function will appear on the left with the list of substances on the right. specific volume. The thermodynamic property functions. without needing to recall the format. additional allowable letters are W. This command will bring up the dialog window shown below. corresponding to humidity ratio. D. Additional information is available by clicking the Function Info and Fluid Info buttons. and wetbulb temperature. The Convert function is most useful in these problems. specific internal energy. V. using the scroll bar. such as enthalpy and volume require a special format. R134a in this case. R. specific entropy. Select the property function by clicking on its name. H. corresponding to temperature. and quality. Select a substance in the same manner. is to use the Function Information command in the Options menu. Clicking the Paste button will copy the Example into the Equations window at the cursor position.Chapter 1 Getting Started Note the use of the Convert function in this example to convert the units of the specific kinetic energy [m^2/s^2] to the units used for specific enthalpy [kJ/kg]. pressure. See Chapter 4 for a detailed description of its use. (The lower and upper bounds are shown in italics if EES has previously calculated the value of the variable. and then solves all equations with one unknown. each variable has a guess value of 1. which will force EES to recalculate the value of that variable. In this case. EES does not automatically do unit conversions but it can provide unit conversions using the Convert function (Chapter 4) and 13 . if desired. bold. The units of the variables can be specified.) The A in the Display options column indicates that EES will automatically determine the display format for numerical value of the variable when it is displayed in the Solution window.0 with lower and upper bounds of negative and positive infinity. In this case. The third Display options column controls the hilighting effects such as normal (default). The Variable Information dialog will then appear. These italicized values may still be edited. Alternative display options are F (for fixed number of digits to the right of the decimal point) and E (for exponential format). EES checks syntax and compiles newly entered and/or changed equations. EES will select an appropriate number of digits. The display and other defaults can easily be changed with the Default Information command in the Options menu. discussed in Chapter 3. The units will be displayed with the variable in the Solution window and/or in the Parametric Table. By default. boxed. so the digits column to the right of the A is disabled. This is done with the Variable Information command in the Options menu. The Variable Information dialog contains a line for each variable appearing in the Equations window. Before displaying the Variable Information dialog. Automatic formatting is the default. the Guess value column displays the calculated value.Getting Started Chapter 1 It is usually a good idea to set the guess values and (possibly) the lower and upper bounds for the variables before attempting to solve the equations. e. m2. 14 . Scroll the variable information list to bring Vel2 into view. When the calculations are completed. as described in Appendix B. If the maximum residual is larger than the value set for the stopping criteria. In the example problem. should be reasonably close to the value of h1. (It is not necessary for this problem. select the Solve command from the Calculate menu. to 0. and Vel2 are determined. The lower bound of Vel2 should also be zero. v2. When the calculations are completed. information entered here is only for display purposes. maximum residual (i. These defaults can be changed with the Stop Criteria command in the Options menu. An information dialog will appear indicating the elapsed time.. h2. it is sometimes necessary to provide reasonable guess values and bounds in order to determine the desired solution. The units With nonlinear equations. EES displays the total number of equations in the problem and the number of blocks. the enthalpy at the outlet. A block is a subset of equations that can be solved independently. To solve the equation set.1 and its lower bound to 0.) The bounds of some variables are known from the physics of the problem. to improve the calculation efficiency.Chapter 1 Getting Started unit checking with the Check Units command in the Calculate menu. the button will change from Abort to Continue. The problem is now completed since the values of T2. the difference between the left-hand side and right-hand side of an equation) and the maximum change in the values of the variables since the last iteration. By default. Set its guess value to 100 and its lower bound to 0. the elapsed time exceeds 60 sec. the equations were not correctly solved. Clicking the Continue button will remove the information dialog and display the Solution window shown on the next page. EES automatically blocks the equation set. possibly because the bounds on one or more variables constrained the solution. the calculations are stopped when 100 iterations have occurred. Set the guess value of the outlet specific volume. whenever possible. the maximum residual is less than 10-6 or the maximum variable change is less than 10-9. Getting Started Chapter 1 One of the most useful features of EES is its ability to provide parametric studies. For example, in this problem, it may be of interest to see how the throttle outlet temperature and outlet velocity vary with outlet pressure. A series of calculations can be automated and plotted using the commands in the Tables menu. Select the New Table command. A dialog will be displayed listing the variables appearing in the Equations window. In this case, we will construct a table containing the variables P2, T2, Vel2, and h2. Click on P2 from the variable list on the left. This will cause P2 to be highlighted and the Add button will become active. Now click the Add button to move P2 to the list of variables on the right. Repeat for T2, h2, and Vel2, using the scroll bar to bring the variable into view if necessary. (As a short cut, you can double-click on the variable name in the list on the left to move it to the list on the right.). The table setup dialog should now appear as shown above. The default table name is Table 1. This name can be changed at this point or later. Click the OK button to create the table. 15 Chapter 1 Getting Started The Parametric Table works much like a spreadsheet. You can type numbers directly into the cells. Numbers that you enter are shown in black and produce the same effect as if you set the variable to that value with an equation in the Equations window. Delete the P2 = 300 equation currently in the Equations window or enclose it in comment brackets { }. This equation will not be needed because the value of P2 will be set in the table. Now enter the values of P2 for which T2 is to be determined. Values of 100 to 550 have been chosen for this example. (The values could also be automatically entered using Alter Values in the Tables menu, by right clicking on the table cell that shows P2 and selecting Alter Values from the popup menu, or by using the Alter Values control at the upper right of each table column header, as explained in Chapter 2.) The Parametric Table should now appear as shown below. Now, select Solve Table from the Calculate menu. The Solve Table dialog window will appear allowing you to choose the runs for which the calculations will be done. If more than one Parametric table was defined, a choice of tables would also be available. 16 Getting Started Chapter 1 When the Update Guess Values control is selected, as shown, the solution for the last run will provide guess values for the following run. Click the OK button. A status window will be displayed, indicating the progress of the solution. When the calculations are completed, the values of T2, Vel2, and h2 will be entered into the table. The values calculated by EES will be displayed in blue, bold or italic type depending on the setting made in the Screen Display tab of the Preferences dialog window in the Options menu. The relationship between variables such as P2 and T2 is now apparent, but it can more clearly be seen with a plot. Select New Plot Window from the Plot menu. The New Plot Window dialog window shown below will appear. Choose P2 to be the x-axis by clicking on P2 in the x-axis list. Click on T2 in the y-axis list. Select the scale limits for P2 and T2, and set the number of divisions for the scale as shown. Grid lines make the plot easier to read. Click on the Grid Lines control for both the x and y axes. When you click the OK button, the plot will be constructed and the plot window will appear as shown below. Once created, there are a variety of ways in which the appearance of the plot can be changed as described in the Plot Windows section of Chapter 2 and in the Plot menu section of Chapter 3. This example problem illustrates some of the capabilities of EES. With this example behind you, you should be able to solve many types of problems. However, EES has many more capabilities and features, such as curve-fitting, uncertainty analyses, complex variables, arrays. 17 Chapter 1 Getting Started 18 CHAPTER 2 __________________________________________________________________________ __________________________________________________________________________ EES Windows General Information The information concerning a problem is presented in a series of windows. Equations and comments are entered in the Equations window. After the equations are solved, the values of the variables are presented in the Solution and Arrays windows. The residuals of the equations and the calculation order may be viewed in the Residuals window. Additional windows are provided for the Parametric and Lookup Tables, a diagram and up to 10 plots. There is also a Debug window. A detailed explanation of the capabilities and information for each window type is provided in this section. All of the windows can be open (i.e., visible) at once. The window in front is the active window and it is identified by its highlighted (black) title bar. The figure below shows the appearance of the EES windows in Microsoft NT 4.0/2000. The appearance may be slightly different in other Windows versions. One difference between EES and most other applications is worth mentioning. The Close control merely hides a window; it does not delete it. Once closed, a window can be reopened (i.e., made visible) by selecting it from the Windows menu. 19 Chapter 2 EES Windows Every window has a number of controls.. 20 also. EES equations must be less than 255 characters, comments may be of any length. The comments will automatically line break to fill the Equations window if the Wrap Long Lines option in the Preferences Equations tab is selected. The Formatted Equations window will also line break the comments in the display window and in the printed output. 3. Equations may be entered in any order. The order of the equations has no effect on the solution, since EES will block the equations and reorder them for efficient solution as described in Appendix B. 4. The order of mathematical operators used in the equations conform (X – 3) / 4 = 5 5.. 21 Chapter 2 EES Windows 6. Variable names must start with a letter and consist of any keyboard characters except (‘|)*/+-^{ } ":;.). 7. As you enter an equation, an unmatched open or close parenthesis will be displayed in bold font. 8. The commercial and educations versions of EES have an upper limit of 6000 variables. The Professional version can have 10,000 variables. 9. Equations are normally entered one per line, terminated by pressing the Return or Enter keys. Multiple equations may be entered on one line if they are separated by a semicolon2. Long equations are accommodated by the provision of a horizontal scroll bar which appears if any of the equations is wider than the window. However, each equation must be less than 255 characters. highlighting of the line in which the problem was discovered. 11. Equations can be imported or exported from/to other applications by using Cut, Copy and Paste commands in the Edit menu. The Merge and Load Library commands in the File menu and the $INCLUDE directive may also be used to import the equations from an existing file. The Merge command will import the equations from an EES or text file and place them in the Equations window at the cursor position. Equations imported with the $INCLUDE directive will not appear in the Equations window. 12. Clicking the right mouse button in the Equations window will bring up a pop-up menu that will allow commenting (or uncommenting), cutting, copying or printing of the selected text.. 22 23 . The complex mode configuration can be changed in the Preferences Dialog (Options menu) or with the $Complex On/Off directive. all variables as assumed to have real and imaginary components.EES Windows Chapter 2 13 If EES is configured to operate in complex mode. in addition to the mathematical notation. An examination of the Formatted Equations Window will reveal a number of EES features to improve the display. Array variables. Note that comments appearing in quotes in the Equations window are displayed in the Formatted Equations window but comments in braces are not displayed.Chapter 2 EES Windows Formatted Equations Window The Formatted Equations window displays the equations entered in the Equations window in an easy-to-read mathematical format as shown in the sample windows below. such as B[1] are 24 . can be used within the scope of Duplicate statements. hold the Shift key down while issuing the Copy command.. first select it by clicking the left mouse button anywhere within the equation rectangle. Alternatively. You can copy one or more equation pictures from this window to other applications (such as a word processor or drawing program). Sums and integrals are represented by their mathematical signs.g. the variable name GAMMA will be displayed as Γ. move the cursor to the item and then press and hold the left mouse button down while sliding the equation or comment to a new location. For example. as in variable G_2. Comments normally appear in blue text on the Formatted Equations window and they will appear in color when copied to the Clipboard. Both the equations and comments will be formatted using these special symbols. and if the capital Greek letter is distinct from the English alphabet. note that although G[2] and G_2 will display in the same manner in the Formatted Equations Window. i. The variable JTHETA will be displayed as a J in Symbol font which appears as a theta with a “curly” tail. For example.e. If a variable name contains an underscore. bar. so EES will display the lower case equivalent. _bar. If the variable name in the Equations window is entered entirely in capital letters. You may select additional equations. Placing _dot. A special form is provided for variables beginning with DELTA. Variables having a name from the Greek alphabet are displayed with the equivalent Greek letter. they are different variables with different properties. If you wish to have the comments displayed in black. 25 . or with the Sum and Product functions. The equations will be unselected after the copy operation. To move an equation or comment. or _hat after a variable name places a dot. The formatted equations and comments are internally represented as Windows MetaFilePict items or pictures. e. To copy an equation. A selected equation or comment will be displayed in inverse video. ß. The _infinity results in a subscript with the infinity symbol (∞). the capital Greek letter will be used. The formatted equations and comments appearing the Formatted Equations window can be moved to other positions if you wish. The index of array variables. In addition. Capital BETA looks just like a B. However. the calculated value of G[2] can be displayed in the Arrays Window. For example. Copy the selected equations and comments to the clipboard with the Copy command. G|o will display as G o . or hat (^) centered over the name. the variable name beta will display as ß and mu will display as a µ. G[2]. A vertical bar character in a variable name signifies the start of a superscript. as described in more detail in this chapter.EES Windows Chapter 2 (optionally) displayed as subscripted variables. the Select Display command in the Edit menu can be used to select all of the equations and comments which are currently visible in the Formatted Equations window. DELTAT displays as ∆T.. the underscore will signify the beginning of a subscript. For example. However. clicking the right mouse button on an equation in the Formatted Equation window will bring the Equations window to the front with that equation selected where it can be edited. 26 .Chapter 2 EES Windows The text in the Formatted Equations window cannot be edited. The values and units of all variables appearing in the Equations window will be shown in alphabetical order using as many columns as can be fit across the window. The changes made in the Format Variable dialog are applied to ALL selected variables. If a variable is hidden. etc. The format of the variables and their units can be changed using the Variable Info command in the Options menu. it can be made visible again with the Display controls in the Variable Info dialog window. Pressing the Enter key will also bring up the Format Variable dialog window. When configured in Complex mode. The selected variables can also be highlighted (with underlining. Double-clicking the left mouse button (or clicking the right mouse button) brings up the Format Variable dialog window. Clicking the left mouse button on a selected variable unselects it. Clicking the left mouse button on a variable selects that variable which is then displayed in inverse video.EES Windows Chapter 2 Solution Window The Solution window will automatically appear in front of all other windows after the calculations. directly from the Solution window. are completed. foreground (FG) and background (BG) colors. The Solution window is accessible only after the calculations are completed. The unit settings made with the Unit System command in the Options menu will be displayed at the top of the Solution window if any of the built-in thermophysical property or trigonometric functions is used. bold font.) or hidden from the Solution window. 27 . The Solution menu item in the Windows menu will be dimmed when the Solution window is not accessible. an additional formatting option is provided for displaying the variable in rectangular or polar coordinates. The numerical format (style and digits) and the units of the selected variables can be selected in this dialog window. or more simply. initiated with the Solve or Min/Max commands in the Calculate menu. Additional information pertaining to the operation of the Solution window follows. 2. 1. 6. particularly for debugging purposes. The Solution window will normally be cleared and hidden if any change is made in the Equations window. An underscore character is used to indicate a subscript so lb_m will appear as lbm. EES will display the most recent values of local variables in EES Functions. select the Paste Special command and select picture. For example. 28 . Most word processors will. there is an option in the Preferences dialog of the Options menu to allow the Solution window to remain visible. The Select Display command in the Edit menu will select all variables currently visible in the Solution Window. The picture will show only those variables which are selected in the same format as they appear in the Solution window. by default. the name of the Solution window will be changed to Last Iteration Values and the values of the variables at the last iteration will be displayed in the Solution window. The Copy Solution command will copy the selected variables (shown in inverse video) to the clipboard both as text and as a picture. 4. The number of columns displayed on the screen can be altered by making the window larger or smaller. If the ! Display subscripts and Greek symbols option in the General Display tab of the Preferences dialog is selected. The values of these local variables are ordinarily not of interest but you may wish to know them. Modules and Subprogram in separate tabbed windows within the Solution window. Procedures. and its units. (If you wish to force a black and white picture.Chapter 2 EES Windows 3. m^2 will appear as m2. 7. such as a word processor. If the ! Show function/procedure/module values option in the General Display tab of the Preferences dialog is selected. EES will display subscripts and superscripts of variable units. paste the text. hold the Shift key down when you issue the Copy Solution command. However. 5. the Copy command in the Edit menu will appear as Copy Solution.) Both the text and the picture can be pasted into another application. If EES is unable to solve the equation set and terminates with an error. When the Solution window is foremost. To paste the picture instead of the text. 8. its value. The text will provide for each variable (selected or not) a line containing the variable name. simple arithmetic operations are supported for array indices so array variables can be more convenient in some problems as discussed in Chapter 7. array variables may optionally be displayed in a separate Arrays window. display format and column position can be changed. Each array variable has its own guess value. lower and upper bounds and display format. However. e. Note that you can enter a number in the column number field or use the up/down arrows to 29 .. If this option is selected. Part or all of the data in the Arrays window can be copied to another application by selecting the range of cells of interest followed by use of the Copy command in the Edit menu. X[5] and Y[6. The following dialog window will appear in which the units.2]. The format of values in any column of the Arrays window can be changed by clicking the left mouse button on the array name at the top of the column. an Arrays window such as that shown below will automatically be produced after calculations are completed showing all array values used in the problem in alphabetical order with the array index value in the first column. The values in the Arrays window may be plotted using the New Plot Window command in the Plot menu. hold the Ctrl key down while issuing the Copy command. rather than in the Solution window. However. If you wish to include the column name and units along with the numerical information in each column. This option is Place array variables in the Arrays window check box in the controlled with the Preferences dialog (Options tab) in the Options menu. EES array variables have the array index in square brackets. In most ways. array variables are just like ordinary variables. The values of all variables including array variables are normally displayed in the Solution window after calculations are completed.g.EES Windows Chapter 2 Arrays Window EES allows the use of array variables. the column will be positioned at the right of the table.Chapter 2 EES Windows change its value. 30 . If the value you enter is greater than the number of columns in the table. 3 The relative residuals are monitored during iterative calculations to determine when the equations have been solved to the accuracy specified with the Stopping Criteria command in the Options menu. as described in more detail in Appendix B.e. EES will recognize that these equations can be blocked.. i.e. The relative residual is the magnitude of the absolute residual divided by the value of left side of the equation. in addition to the relative and absolute residual values. without simultaneously finding the values of other variables. the following set of six equations and six unknowns. broken into two or more sets.. Variables having values that can be determined directly. such as G in the example above. for example. Consider. 31 . are determined first and 3 If the value of the left hand side of an equation is zero. the absolute and relative residuals assume the same value. The blocking information is displayed in the Residuals window. The absolute residual of an equation is the difference between the values on the left and right hand sides of the equation. i.EES Windows Chapter 2 Residuals Window The Residuals window indicates the equation blocking and calculation order used by EES. See the Diagram Window section. Z can be determined. Similarly.Chapter 2 EES Windows assigned to Block 04. Note that the variable(s) that are determined by the equation(s) in each block are shown in bold font. You may need to change the guess values or bounds for the variables in this block using the Variable Info command in the Options menu. and so on until all equations are solved. It is possible to display the Residuals window in a debugging situation. A. Once G is known. then Block 2. the second and fourth equations. The first and third equations in the example above can be solved independently of other equations to determine X and Y and are thereby placed in Block 1. The information in the Residuals window is useful in coaxing a stubborn set of equations to converge. EES will not be able to solve the equation set. Use the Find command in the Search menu to help locate the equations. With X. Doubling-clicking the left mouse button (or clicking the right mouse button) on an equation in the Residuals window will cause the Equations window to be brought to the front with the selected equation highlighted. When one or more equations are missing. 4 Variables specified in the Diagram Window are identified with a D rather than a block number. If the number of equations is less than the number of unknowns. After solving all equations in Block 0. The Residuals window will normally be hidden when any change is made in the Equations window. the block numbers appear in sequential order. Normally. Y. The equations in the following blocks should be carefully reviewed to determine whether they are correctly and completely entered. An examination of the residuals will indicate which equations have been solved by EES and which have not. so it appears in Block 3. which determine A and B. EES will skip a block number at the point in which it encounters this problem. H can be determined. This automatic hiding can be disabled with the Display Options command in the Options menu. once for the real part identified with (r) and again for the imaginary component labeled with (i) 32 . and B now known. are placed in Block 2. In Complex mode. The entire contents of the Residuals window will be copied as tab-delimited text to the Clipboard if the Copy command is issued when the Residuals window is foremost. Check these equations to be sure that there is a solution. The order in which these individual equations are solved in Block 0 is indicated by the order in which they appear in the Residuals window. the block of equations that EES could not solve can be identified. but the Residuals window can be made visible by selecting it from the Windows menu. In this way. each equation is shown twice. EES will simultaneously solve the equations in Block 1. g. 3. are assumed to be independent variables and are shown in normal type in the font and font size selected with the Preferences command (Options menu). Numerical values can be entered into any of the cells. The number of rows is selected when the table is generated. The initial order in which the columns in the Parametric Table appear is determined by the order in which the variables in the table were selected in the New Parametric Table dialog. A parametric table is created using the New Parametric Table command in the Tables menu. bold type. To change the column number order. Variables may be added to or deleted from an existing Parametric Table using the Insert/Delete Vars command in the Tables menu.. Entering a value in the Parametric Table produces the same effect as setting that variable to the value with an equation in the Equations window. Each row of the Parametric Table is a separate calculation.EES Windows Chapter 2 Parametric Table Window The Parametric Table window contains one or more Parametric Table(s). The maximum number of rows in the Commercial version is 6500. A pop-up menu will 33 . 2. Each new table is given a name that appears on a tab at the top of the Parametric Window. The variables that are to appear in the table are selected from a list of variables currently appearing in the Equations window. 3. clicking on the tab brings the corresponding Parametric Table to the front. 1. There is no limit to the number of rows in the Professional version. One or more columns can be deleted more simply by right-clicking in the column header and selecting Delete from the popup menu. click the right mouse button in the column header cell (but not on the alter values control at the upper right). the values in the P2 column in the above table. Dependent variables will be determined and displayed in the table in blue. When there is more than one table. e. A Parametric table operates somewhat like a spreadsheet. or italics (depending on the choice made with the Preferences command) when the Solve Table or Min/Max Table command in the Calculate menu is issued. Entered values. but may be altered using the Insert/Delete Runs command in the Tables menu. A green 'go' triangle is displayed in the upper left cell of the Parametric table. right-clicking in the column cell header and selecting Alter values from the pop-up menu or clicking the mouse on the control at the upper right of the column header cell will bring up the dialog window shown below which provides the same automatic entry somewhat more conveniently. units. Values can be automatically entered into the Parametric table using the Alter Values command in the Tables menu. A dialog window will appear as shown below in which the column number can be changed be clicking the up or down arrows to the right of the column number or by directly editing the column number. click the left 34 . The row range is that selected during the last use of the Solve Table dialog. Select the Properties menu item.Chapter 2 EES Windows appear with Properties as one of the menu items. column width. 6. 5. To select a different range. and column background color can also be entered or changed at this point. Clicking the left mouse button in this triangular area will initiate the foremost Parametric Table calculations for the rows indicated below the triangle. Alternatively. The display format. The data are placed on the clipboard with a tab between each number and a carriage return at the end of each row. The TableName$ function returns the name of the Parametric table (as displayed on the tab in the Parametric window) that is currently in use. click the mouse in the upper left cell. The TableRun# function returns the row of the table for which calculations are currently in progress. The selected cells will be shown in inverse video. 8. Hold the Shift key down and then click the mouse in the last row. units. Hold the Shift key down and click in the lower right cell. All of the cells in a column can be selected in a similar manner by clicking the left mouse button in the column header. If the mouse button is held down while the clicking in leftmost column of other rows. and other options. 7. With this format. the upper left cell is selected and it will be placed on the clipboard with other cells when the Copy command is issued. If you wish to include the column name 35 . EES will not have to recalculate the Jacobian and blocking factor information and can thus do the calculations more rapidly. these rows will be added to the selection. using the scroll bar as needed. even though it may not displayed in inverse video. the table data will paste directly into a spreadsheet application. Rows can also added by holding the Shift key down while clicking in the leftmost column. 9 A Parametric Table can be used to solve differential equations or integrals. (When the Shift key is released. 14. To copy data from any of the EES tables. Tabular data may be imported or exported from the Parametric Table via the Clipboard using the Copy and Paste commands in the Edit menu. Clicking the left mouse button in the leftmost column of a row in any table will select all of the cells in that row. A right-click in the cell header will bring up the dialog that allows the format. Right-clicking after selecting a range of cells brings up a popup menu that allows selected printing. and other information in a column to be edited. See Chapter 7 for additional information. The TableValue function returns the value of a table cell at a specified row and column.EES Windows Chapter 2 mouse button in the first row. the upper left cell that has the focus will return to normal display. 12. 10. when the independent variables are the same in all rows. Continue to hold the Shift key down while clicking in the green triangle. copying. A Sum row which displays the sum of the values in each column may be hidden or made visible using the 'Include a Sum row in the Parametric table’ control provided in the Preferences dialog window (Options tab) in the Options menu.) Use the Select All command in the Edit menu to select all of the cells in the table. The independent variables in the Parametric Table may differ from one row to the next. However. 13. 11. However. Arrays.Chapter 2 EES Windows and units along with the numerical information in each column. This option provides a convenient way to print a specified section of a table. or Integral table windows will bring up a pop-up menu allowing the current selection to be cut. Lookup. 36 . 15. The Copy command is also accessible from a pop-up menu by right-clicking the mouse in a selected cell. Right-clicking in Parametric. or printed. Right clicking in the Row column of any table now brings up a menu that allows a back color or border to be associated with the row. copied. hold the Ctrl key down while issuing the Copy command. A sample Lookup Table is shown above. See Chapter 4 for details. and LookupRow functions allow data in a Lookup Table to be linearly interpolated (forwards and backwards) and used in the solution of the equations. The number of rows and columns in the table are specified when the table is created and may be altered with Insert/Delete Rows and Insert/Delete Cols commands in the Tables menu or by right-clicking in the row or column headers. .EES Windows Chapter 2 Lookup Table Window A Lookup Table provides a means of using tabular information in the solution of the equations.CSV filename extension. All Lookup Tables are saved with other problem information when the EES file is saved. In addition. as explained in more detail in Chapter 4. There is no limit. In addition. the Lookup. A .CSV filename extension. The Lookup Table may either reside in the Lookup Table Window or in a previously-saved Lookup File with a . However. the Lookup functions will also accept ‘ColumnName’ in place of the column number where ‘ColumnName’ is the 37 .LKT. The column number is displayed in small type at the upper left of each column header cell. Lookup files can also be saved in ASCII format with a .TXT. LookupCol. The Interpolate commands provide linear. quadratic or cubic interpolation or extrapolation of the data in the Lookup Table. or . The column number can be used to specify a specific column when used with the Lookup functions. a Lookup Table may be saved on a disk (separately from the EES file) using the Save Lookup command in the Tables menu.LKT filename extension is used to designate EES Lookup files. on the number of Lookup Tables that can be placed in the Lookup Table Window. Each Lookup table is associated with a table name that appears on the tab at the top of the Lookup Table Window. The Lookup table may then be accessed from other EES programs in any of these formats. A Lookup Table is created using the New Lookup Table command in the Tables menu.TXT or . other than available memory. TXT . The column title can be changed and units for the values in the column may be specified. etc. Data may be automatically entered into control at the upper right of the column header cell. but these default names can be changed by clicking the right mouse button in the header cell and selecting Properties from the popup menu that appears. 38 . Lookup Table files saved with a . Data can be imported to or exported from the Lookup Table through the Clipboard in the same manner as described for the Parametric Table.Chapter 2 EES Windows name of the column shown in the column heading surrounded by single quote marks. with the Delete Lookup Table menu item in the Options menu. 5 EES will also accept #ColumnName in place of the column number. Column2. The column width and position may also be changed by either clicking the up or down arrows to the right of the column number or by editing the number directly. Hold the Shift key down when issuing the copy command if you wish to copy the column names and units with the other numerical information on the Clipboard. or . if desired. The Format controls allow the data in each column of the table to be displayed in an appropriate numerical format. Data may be interchanged between the Parametric and Lookup Table windows. .CSV filename extension can not be deleted from within EES. the Lookup table by clicking on the as described for the Parametric table.5 The column names are initially Column1. One or more Lookup Tables can be deleted from the Lookup Table Window. A control is provided to change the background color for each column.LKT. Second. First. or start other programs. the Diagram window can be used for to provide convenient input and output of information and for report generation. A scanned image in bitmap format can also be used 39 . save or load input values. it provides a place to display a graphics and text relating to the problem that is being solved. when clicked. or PowerPoint. a schematic diagram of a system identifying state point locations can be displayed in the Diagram window to help interpret the equations in the Equations window. 'hot areas' can be defined that. Link buttons can be put on the Diagram that display plots. First. For example. Designer. Shown below is a typical diagram window. or web site. Corel Draw. a graphical or text objects can be created in any drawing program that produces an object drawing such as Microsoft Draw (included in Word for Windows). Windows help file. In the Professional version. A Calculate button can be placed on Diagram and child windows to conveniently initiate the calculations. A Help button can be used to access help information from a text file. Creating the Diagram There are two ways to place objects on the Diagram window.EES Windows Chapter 2 Diagram Window The Diagram window serves several functions. open additional child Diagram windows. Select and copy the item(s) in the drawing application and then use the Paste command to place them into the Diagram window. circles. When the tool bar (shown below) is visible.Chapter 2 EES Windows as the diagram provided that it is copied as an picture. The tool bar can be hidden by clicking on the X in its title bar or by selecting the Show/Hide Diagram Tool Bar command. The two methods of creating a drawing can be combined. and rectangles. Graphic objects generated in either manner are saved along with all other problem information. and graphic objects (lines/arrows. Input variables are enabled and calculations can be initiated using the optional calculate button or the commands in the Calculate menu. all objects such as the picture. For example. the Diagram window is in development mode. An easy way to convert the bitmap into a picture is to paste the bitmap into PowerPoint. or deleted as indicated below. In the development mode. rather than a bitmap. ellipses) added to the Diagram window. the Diagram window is in application mode. text. PaintBrush or other programs that convert graphical images. Then copy the image from this program into the Diagram window. The characteristics of these graphic objects can be changed by rightclicking or double-clicking the mouse button on the object while the toolbar is visible. modified. In application mode. Add text item Add line or arrow Add rectangle Add circle or oval Align selected items Group selected items Ungroup selected items Add Calculate button Add Plot access button Add Print button Add Save Inputs button Add Retrieve Inputs button Add Link button Add Help button 40 . Development and Application Modes The Diagram window and child Diagram windows operate in two modes. When the tool bar is hidden. can be moved. Input variables are disabled in development mode and calculations initiated with the Calculate button are suppressed. you can position a rectangle on top of a scanned image. rectangles. The tool bar can be made visible or hidden using the Show/Hide Diagram Tool Bar command or the Diagram window speedbutton. A second way to create a drawing is to use the drawing tools provided on the Diagram window toolbar. The toolbar provided graphic primitives such as lines/arrows. it is not possible to move any of the objects or change their display characteristics. Buttons that are placed on the Diagram window can be resized independently by holding the Ctrl-key down while using the arrow keys. The left arrow key reduces the width. The up and down arrow keys increase and decrease the button height. to increase the width of a button. graphic object or button. An Output 41 . The aspect ratio of Diagram window information is not changed it is resized. Select the variable by clicking on its name in the list. For example. The contents of the Diagram window can be made larger or smaller by first changing the size of the Diagram window itself by dragging its lower left corner to a new location and then double-clicking in the window to resize the contents. respectively. superscripts. the graphical and text items will be proportionally resized to fit in the Diagram window. After a positive confirmation. the contents of the Diagram window can be resized by doubleclicking the left mouse button (or clicking the right mouse button) anywhere within the Diagram window (or child Diagram window) except on a text. Each right arrow press increases the width of the button by one pixel. Resizing the Diagram In development mode. in which the text and its characteristics can be specified. as shown. click on the button to select it (in development mode) and then press the right arrow key while holding the Ctrl key down. and symbols. The items can also be moved one pixel at a time with each press of the arrow keys. The formatting buttons to the right of the text type radio buttons simply entry of subscripts. The text will initially appear in a default position within the Diagram window when the dialog is dismissed.EES Windows Chapter 2 Moving the Diagram Selected items in the Diagram window can be moved in development mode by pressing and holding the left mouse button down anywhere within a selected item while sliding the mouse. Adding and Moving Text on the Diagram Window The Add Text button on the Diagram window toolbar allows text to be placed anywhere on the Diagram window. Three different types of text may be selected using the radio buttons at the upper left of the Add Text dialog window. It can then be dragged to a new position by pressing and holding the left mouse button down while sliding the text to the desired location. Use the Select All command in the Edit menu to move the all of the contents of the Diagram Window to a new position. Selecting the Text radio button will cause the window to appear as shown below. The text or any of its characteristics can later be changed by doubleclicking the left mouse button (or by clicking the right mouse button) while the cursor is positioned over the text. Both Input and Output variables values are displayed on the diagram with the option of also displaying the variable name and unit string. Clicking the Input or Output radio buttons changes the dialog window display so that a list of currently defined variables replaces the text edit box. A value which is set in the Diagram window cannot also be set in the Equations window. EES will provide the option of selecting the variable from a pull-down list of string constants that you provide. if any. This value can be edited and it provides the same function as an equation in the Equations window which sets the variable to a value. String variables can also be used to enter EES equations.Chapter 2 EES Windows variable displays the value of the selected variable calculated during the previous calculation. After the calculations are completed. as described below. 42 . An Input variable will be displayed with the value enclosed in a rectangle. the newly-calculated values of the Output variables will be displayed on the Diagram window. For example. String variables can be used for many purposes including the names of fluids as described in Chapter 7. The Solve Table and Min/Max Table commands provide a check box to indicated whether Diagram window information should be used. EES will first examine the Diagram window to see which variables. The selection from the pull-down menu is assigned to the string variable. If a string variable (identified with a $ character as the last character in the variable name) is selected for an Input variable. the Diagram window shown at the start of this section employs pull-down lists for the unit system and type of compressor data. Output values will display in gray-colored text if the value is not currently defined. Assuming that the Diagram window is not hidded. are to be input from the Diagram window when the Solve or Min/Max commands (Calculate menu) are issued.. Using Drop-Down Lists to Set One or More EES Variables When a string variable is selected for input in the Diagram Window. conductivity=91 Zinc // density=7140.. suppose you wish to use a drop-down list to have a user select the density and thermal conductivity of one of several substances. An Edit button will appear which will allow the existing choices to be viewed and/or changed. You could create a drop-down list with the following strings: Copper // density=8933. conductivity=237 Nickel // density=8900. The Diagram window can be used with the Parametric table (i. conductivity=400 Aluminum // density=2700. The string choices are displayed in a drop-down list box which displays the available choices when the user clicks in the box.e. conductivity=116 User Input // density=?. the option of including the units is replaced with an option for providing a list of alternative choices for the string variable in a drop-down list. conductivity=? 43 . the Solve Table command) if the ‘Use Input from Diagram’ check box is checked in the Solve Table dialog window. It is possible to use the strings in the drop-down list to set the values of one or more EES variables. For example. This is accomplished by following the string that is to be displayed with characters // and then with one or more EES equations on one line.EES Windows Chapter 2 The Diagram window input is ignored if the Diagram window is hidden. and circles tools on the toolbar. An interesting extension of this concept is provided in the last string of this list which is 'User Input // density=?. rectangles or circles (ellipses) can be drawn on the Diagram window or child diagram windows using the line. The graphic items can be resized or moved in development mode as described next. The align button in the tool bar can be used to facilitate alignment of the selected items relative to one another. rectangle. vertical. If the Format Display control in the Modify Diagram Text dialog is checked. the dialog box displays the characteristics of the first selected text item. the variables density and conductivity must be displayed on the Diagram window as Output variables.Chapter 2 EES Windows When an item from the drop-down list is selected or when calculations are initiated. size. EES will execute the equations to the right of the // characters and update the Diagram Window display. conductivity=?'. An example of this capability is provided in the Diagram_In_Out. EES interprets the '=?' to mean that that the value of the variable should be entered in an edit box. EES will look for these Output variables and change them to Input variables. Clicking anywhere in the Diagram window that is not on a text or graphic object unselects all selected items. then the font size of the selected text items will not be changed. Any change made to a text characteristic in the dialog window will be applied to all selected text items. color. Similar capability is provided if all selected items are graphic objects. In order for this to work. pressing the right mouse button will bring up a dialog box in which the font. A selected graphic object will be displayed with its 'handles' (small boxes on each edge) showing. such as the font size. is not changed in the dialog window. Hold the Shift key down to select more than one item. Holding the Shift key down while drawing rectangles and circles will cause them to be draw with its width equal to its height. Holding the Shift key down while drawing a line will cause the line to be drawn horizontal. When it first appears. the drop-down list will only show the characters to the left of // like this. Selecting.ees example file. Adding Graphic Items Lines. Modifying and Aligning Text and Graphic Items One or more text and graphic items in the Diagram window or child diagram windows can be selected by clicking the left mouse button on the item while in development mode. If a text characteristic. A red dotted box will be displayed around each selected text item. All selected items can be moved at once using the mouse or the arrow keys. In this case. and style of the selected text items can be changed as a group. When the 'User Input' item is selected. If all of the selected items are text items. or to the closest 45° angle. The general capability afforded by the '=?' notation is that selected variables can be changed from Output to Input or from Input to Output variables on the Diagram Window by a user selection from a drop-down list. 44 . Text items which provide input or output on the Diagram window can not be grouped. Adding a Plot Window Access Button A Plot Window access button can be placed on the Diagram window or child Diagram window by selecting the Add Plot Window button in the tool bar. select the items that are to be in group and then click the Group button the toolbar. the Calculate button caption is "Calculate" and pressing the button provides exactly the same function as selecting Solve from the Calculate menu or pressing F2. In general. A group can be resized. The calculate button caption and the action taken when the Calculate button is clicked can be changed by right-clicking the button and providing the desired text while in development mode. Clicking OK in this dialog window will create a plot window access button. A dialog window will appear after clicking this toolbar button in which the caption and plot window name for the plot window access button can be specified. or into the Diagram window of another instance of EES. To create a group. If the plot window does not exist. By default. right click on the grouped item and select the Ungroup menu command from the pop-up menu. When the toolbar is hidden (application mode). the arrow keys affect the size of the button. moved. copied and pasted. The plot window access button can be dragged to any location when the toolbar is visible. into a different child Diagram window. Alternatively. The copied information on the clipboard can then be pasted into a word processor or other application. Grouped items act just like a single item. right click on one of the selected items and select the Group menu command from the pop-up menu that appears. It can also be moved with the arrow keys. The plot window is selected by clicking the appropriate radio button. its radio button will be disabled. The Copy command can be used to copy the either the entire contents of the Diagram window or selected items to the Clipboard. A group can be included in another group to form nested groups. Group information is saved with other file information when the Save command is issued. clicking the plot window access button will display the specified plot in front of all other windows. click on the grouped item and then click the Ungroup button on the toolbar. Adding a Calculate Button A Calculate button can be placed on the Diagram or (child Diagram) window by selecting the Show/Hide Calculate button in the Diagram window tool bar. Input/Output 45 . To ungroup a previously defined group. Right-clicking on the plot window access button when the toolbar is visible will bring up the dialog so that the plot window number or button caption can be changed. If a plot window does not exist. only simple text items can be included in a group. However. this button will do nothing.EES Windows Chapter 2 Group and Ungroup Buttons Two or more graphic and/or text items can be grouped in development mode. If the Ctrl-key is held down. Alternatively. To create a hot area. a window will appear in which you provide a name for the child Diagram window. Hold the Ctrl and Shift keys down to see an outline of all currently defined hot areas. The child Diagram window will appear whenever you click the mouse in the designated area. Creating Hot Areas and Child Diagram Windows (Professional Version only) A 'Hot Area' is a rectangular region on the main Diagram window that will open a child Diagram window when the cursor is positioned in the region and the left mouse button is clicked. including the ability to have hot areas with its own child windows. If the .VAR filename extension. it will be automatically loaded and the input 6 See the Make Distributable Program command in the File Menu section of Chapter 3 for information on Distributable programs. The Save button is needed only for Distributable6 programs.VAR file when the Distributable program is started or when one of the five files contained in the Distributable program is selected from the recent file list at the bottom of File menu. The hot area can also be deleted with this dialog. EES will look for this . Saving User Inputs A Save User Inputs button can be placed on the Diagram window (but not on a child Diagram window) by selecting the Show/Hide Save Inputs button in the Diagram window tool bar. The characteristics of the child Diagram window can be changed by clicking the right mouse button in the region while holding the Ctrl and Shift keys down. When the user presses the mouse on the Save button. 46 .. a file containing the current values of the all EES variables. When the mouse button is let up. The file is written to the directory that the Distributable program is located in. You can copy a figure into this window and add text and graphic objects using the commands in the tool bar in the same manner as in the main Diagram window. including the current values of inputs. is written to the disk. Note that the tool bar must be visible (i. The child Diagram window includes all of the features of the main Diagram window. Use the Select All and Delete command to remove the entire contents of a Diagram window.e.VAR file is found. A dialog window will appear in which the name and the region bounds. since regular EES programs can always save all program information with the normal Save command. and other information can be viewed or changed. development mode) to move or modify any text or graphic objects. The file that is written has the same parent name as the EES file that is executing and a .Chapter 2 EES Windows text items should not be copied into another instance of EES since they contain specific pointers to EES variables that will not be appropriate in the copy. move the cursor to the upper left of the region and drag it to the lower right while holding both the Ctrl and Shift keys down. it will be automatically reloaded. The $SAVELOOKUP and $OPENLOOKUP directives make this process more convenient. to be started when the user clicks the link button in the Diagram window while in application-mode. EES will check the date/time stamp of any lookup file it uses and if the file is changed. This option is useful when the results of one EES program provides data for use in the next EES program. EES will check to see that the current EES file is saved. The caption and properties can be changed at a later time by right-clicking on the link button while the Diagram window is in development mode. The Save button is disabled until calculations have been successfully completed. A dialog window will appear after clicking this toolbar button in which the caption and link properties can be specified and assigned to a button that will appear on the foremost Diagram window.EES. The caption can be changed by right-clicking on the button and providing the desired text while in development mode. as usually the case. In this way. it is not possible to write a set of input information that will not successfully calculate. 47 . the Save button caption is "Save". Alternatively. just the name of the file that is to be opened is needed if the application information is provided in the operating system registry. the following link property will start a second copy of EES and load file TEST. For example. The link button property can be the full filename and optionally. Use the arrow keys to reposition the button and the Ctrl arrow keys to resize the button. ask for confirmation before closing the existing file. In addition. the name of the file that is to be opened when the application starts. and if not.EES EES can communicate with other programs using Lookup files (Chapter 4). information can be calculated and saved in a Lookup Table that is automatically loaded in the next EES program with the $OPENLOOKUP directive. Link type 2: Open EES File This link type will close the existing EES file and open the EES file specified as the link button property.EES Windows Chapter 2 information on the Diagram windows will be updated. By default. C:\EES32\TEST. Five different types of links can be created: Link type 1: Start an External Program This link type allows any program. including another instance of EES. As an example. Creating Links (Professional Version only) Link buttons can be placed on the Diagram window or child Diagram window by selecting the Create Link button in the tool bar. this link type allows one EES file to open another. Note that calculations must be completed to enable the button.EMF R$. Right-clicking on the link button while in development mode will bring up the Link Properties dialog so that link properties can be changed or the button can be deleted. The property plot will then be drawn.EMF filename extension. %%2 with the value of EES variable Thigh. 48 . and %%3 with 0. If this sequence is found. The Ctrl-arrow keys allow adjustment of the height and width of the button. The button can be dragged to any location while the Diagram Window is in development mode or moved with the arrow keys. but in the case of a distributable program the EES file must be one of the five included with the distributable program.Chapter 2 EES Windows Link type 3: Open Distributable File This link type is applicable only to distributable programs created with the Make Distributable Program command. so it no necessary to click on the hot area for the child Diagram window. EES will process the Macro file looking for the character sequence %%N where N is an integer value. However. Link type 4: Open Child Diagram Window This link type is applicable if one or more child Diagram Windows have been created. 0 EES will replace %%1 with the value of the EES string variable R$. This is done by providing parameters after the macro file name separated with a space or comma. the button can be positioned anywhere in the Diagram window. It is possible to provide information to the macro file that allows its capability to be programmed. It is referred to by its number. just as if the user had clicked the mouse within the hot area for the child Diagram window. All other parameters are optional. or strings. Distributable programs can include up to 5 EES files. Clicking OK in the Link Properties dialog will create the link button. Link type 5: Play Macro adapted with EES variables This link type will play a predefined Macro file that has been stored with a . numerical values. As with option 2.EMF has a line that contains: PropPlot %%1 PH 2 %%2 %%3 0 DoQLines If the Play Macro link information is doPropPlot. These parameters can be EES variable names. A list box showing the names of all child Diagram windows is provided. 1 to 5. %%N is replaced with the Nth parameter. The first parameter that must be supplied in the edit box is the macro filename. suppose the macrofile name doPropPlot. Thigh. For example.EMF filename extension. including the . Clicking the button will open the specified child Diagram Window. a Windows help file (*. The Print button can be dragged to any location in the window while the toolbar is visible. the toolbar will be visible. Clicking the left mouse button on the Print button while in application mode will print the contents of the window to the default printer that has been selected with Printer Setup command. by default. Each child Diagram window will have a small 'home' button which. respectively.HLP) or an HTML file (*. 49 . a second button with a left arrow will also be displayed at the lower right. This capability is available only in the Professional version. If the parent of the Diagram window is not the main Diagram window. EES will automatically determine the file type independent of the filename extension. Adding a Print Button A Print button can be placed on the Diagram window or child Diagram window when the window is in development mode. Save and Load buttons are needed only for Distributable programs.HTM). The child Diagram window can also have 'hot areas' forming grandchildren and so on. Clicking this button will close the child Diagram window and bring its parent. since regular EES programs always save all program information with the normal Save command. is initially located in the lower right corner of the window. the toolbar will be visible. The button can be removed by clicking the Show/Hide Print button on the tool bar. The location of the button can also be changed with the arrow keys. The Help button will appear along with a small dialog in which you may enter the caption for the Help button and the name of the help file that will be displayed when the user selects the Help button in Application mode. Clicking this button will close the window and bring up the main Diagram window. This file can either be an ASCII text file (*. Click on the Show/Hide Print button on the tool bar which is identified with a printer icon. In this case. In this case. The caption can be changed or removed by right-clicking on the button. A caption can be added to either button by right-clicking on the button in development mode. The location and size of these navigation buttons can be changed using the arrow and Ctrl-arrow keys.TXT). Click on the Show/Hide Help button on the tool bar which is identified with a yellow circle containing a question mark symbol. The help button can be removed by clicking the Show/Hide Help button in development mode. Navigating through Child Diagram Window (Professional Version) The main Diagram window can have 'hot areas' which bring up child Diagram windows when clicked. Saving and Loading User Inputs (Professional Version) Save and Load Inputs buttons can be placed on the Diagram window (but not on a child Diagram window) by selecting the Show/Hide Save or Load Inputs buttons in the Diagram window tool bar.EES Windows Chapter 2 Adding a Help Button A Help button can be placed on the Diagram window or child Diagram window when the window is in development mode. VAR file can later be loaded with the Load button. automatically loaded and the input information on the Diagram windows will be updated.VAR file in the same directory the Distributable program having the same parent name as the EES file.VAR file is found with this parent name. A standard file open dialog will appear in which a . When opening one of the five EES files contained in the Distributable program. The Save button is disabled until calculations have been successfully completed. If confirmed. The default name is the same name as the EES file with a filename extension of . Both the Save and Load buttons will be disabled if the Diagram window does not contain input variables. The captions can be changed by right-clicking on the button and providing the desired text while in development mode. By default. The Diagram windows will be updated with the values of the variables found in this file. 50 . If a . the Save button caption is "Save" and the Load button caption "Load". including the current values of inputs. This .VAR in order for EES to recognize the file. The filename and directory information can be changed but the filename extension must be . In this way.VAR file can be selected.Chapter 2 EES Windows When the user clicks the Save button.VAR. is written to the disk. a file containing the current values of the all EES variables. it is not possible to write a set of input information that will not successfully calculate. a standard file save dialog will appear in which the name of the a file can be entered. EES will look for a . and each may have any number of overlayed plot lines. lines. There are many plotting options such as choice of line type and plot symbol. An alignment button on the tool bar allows selected items to be aligned in a specified manner. is provided on the Plot Window with buttons to add text. Add text item Add line or arrow Add rectangle Add circle or oval Align selected items The appearance of the plot can be changed in many ways using the plot menu commands in the Plot menu and controls in the Plot window. When clicked. Lookup. which is equipped with tabs at the top of the window to allow easy identification and access to each plot. The visibility of the tool bar is controlled by the Show/Hide Tool Bar menu item in the Plot menu. The Plot window controls are as follows. Array or Integral tables may be plotted with the New Plot Window or Overlay Plot commands in the Plot menu. An outline of the plot will move with the cursor and the plot will move to the new location when the button is released. boxes. A tool bar. Adding / Changing Text and Text Characteristics A text item can be added to the plot window by clicking on the text button in the plot window toolbar. There is no limit on the number of tabbed plot windows that can be constructed (other than available memory). All plots appear in the Plot Window. the Format Text dialog shown below will appear. plots of the thermodynamic properties can be generated using the Property Plot command. shown below. tick frequency. These options can be set when the plot is first drawn or at a later time using the Plot window controls described below or the Modify Plot and Modify Axes commands in the Plot menu. Moving the Plot The entire plot. linear/logarithmic scaling. Right-clicking the mouse within the plot window (but not on any plot item) will also toggle the visibility of the tool bar. including the axis scales and all text items. The choice is made 51 .EES Windows Chapter 2 Plot Window Variables which appear in the Parametric. Two basic types of text items can be created: plain text and EES variables. and grid line control. and ellipses. In addition. can be moved to a different location in the Plot window by holding the mouse button down in any location within the plot rectangle (but not on a text item) while sliding the mouse to its new location. spline fitting. size. 52 . The EES variable option provides the same capability with the difference being that the text can include the name. If a plot is selected. that symbol will be added to the text item at the current insertion point. Plain text is used to identify fixed information displayed in the plot or to produce a legend. Clicking in the Legend symbol box will produce a drop-down list containing a descriptor of each existing plot. A palette of symbols will be displayed to the right of the button.. This is done by selecting the text that is to be subscripted or superscripted and then clicking the button. Press and hold the mouse button down on one of the three symbol buttons. The symbol entry buttons operate as follows. Controls are provided to change the font. EES allows any horizontal text item to be associated with a plot symbol to facilitate construction of a legend. value and units of a pre-defined EES variable and this information can optionally updated dynamically. the line type and symbol used for that plot will be displayed just to the left of the text item and it will move when the text item is moved. Subscripts and superscripts can be generated using the 'speed' buttons. color and style of the text item as well as the text itself. While holding the mouse button depressed. slide the mouse cursor to the symbol palette and position it over the symbol you wish to select.Chapter 2 EES Windows by checking the corresponding radio button at the top of the dialog. The text is entered or edited in the text edit field and it is displayed as it will appear on the plot at the top of the dialog. When the mouse button is released. Three additional speed buttons are provided below the subscript button to facilitate entry of lower or upper case Greek letters and useful symbols. The Delete key will cut all selected text items. Once on the Clipboard. place equations from Mathtype in the Plot Window or place a small version of another plot within a Plot. Selected text items can be copied to the Clipboard using the Cut and Copy commands in the Edit menu. Clicking the left mouse button on a text item will select it. is not changed in the dialog window. Additional text items can be added to the plot using the Add Text command in the Plot menu. Selected text items are displayed within a red dotted rectangle. With this capability. Double-clicking the left mouse button (or clicking the right mouse button) on a text item will bring up a dialog window in which the characteristics of all selected items can be changed. the Format Text Item dialog window displays the characteristics of the first selected text item. the Paste command can be applied to move the text item from the Clipboard to any EES plot window. The selected items can be copied or cut using the Copy or Cut commands. just like any of the other items in the Plot window. If only one text item is selected. for example. The Paste command can then be applied to move them from the clipboard to this plot or to any other EES plot window. You can select multiple text items by holding the Shift key down as you click on the text items. such as the font size. The easiest way to place a plot within a plot is to copy the Plot Window to the Clipboard and then Paste it into PowerPoint or Word. Moving Text Text fields to label the X and Y axes are automatically generated when a plot is constructed. it can be moved and sized. If a text characteristic. The Delete key provides the same function as the Cut command. Rescale it and then paste it back into the EES Plot window. Adding Graphics and Text from the Clipboard Graphic and text items that have been copied to the Clipboard from other applications in the Windows metafile format can be pasted into the Plot Window using the Paste command in the Edit menu. you can change just the font without affecting other characteristics such as the size or color. Each arrow key press moves all selected text one pixel in the arrow direction. 53 . When more then one text item is selected. a red dotted box will be drawn around it to indicate that this item is selected. You can move any text item or set of selected text items to any position on the screen by pressing and holding the left mouse button down while the cursor is on the text item and dragging it to its new location.EES Windows Chapter 2 When you click on a text item in a plot window. use the Paste command to restore them. If you accidentally delete text or lines. the Format Text Item dialog window shown above will appear displaying the text and its current characteristics. After an item has been pasted. it is possible to. (Use the Shift key to select more than one text item. Any change made to a text characteristic in the dialog window will be applied to all selected text items.) Selected text items can also be moved using the arrow keys. In this way. then the font size of the selected text items will not be changed. deselect the Moveable check box. resize. Initially. If you wish to prevent these capabilities. After clicking on the line button in the toolbar. Double-clicking the left mouse button (or clicking the right mouse button) will cause the Modify Line dialog window to appear in which the characteristics (such as arrow style. and color may be selected. You can also use the arrow keys to move one or more selected lines. or rotate the line after it is created. Holding the Shift key down while rotating the line will force it to be horizontal. small boxes will be displayed at either end of the line. the Paste command can be applied to move the line from the Clipboard to any EES window of the same type. 54 . or the nearest 45° angle. Release the mouse button to complete the line construction. Press and hold the mouse button down at the position where you wish the line to begin. Rectangles and Circles Clicking on a line will cause it to be displayed with small boxes at both ends.Chapter 2 EES Windows Adding Lines and Arrows. Rectangles and Circles The Add Line toolbar button in the plot window toolbar allows lines or arrows to be placed anywhere within the Plot window. Rectangles and circles can be drawn in a similar fashion using the rectangle and circle buttons on the plot window toolbar. By default. for example to add or change an arrowhead. or on a 45° angle. vertical. Move the end to its new position and release the mouse button. If you wish to change the type. press and hold the mouse button within either of the two small boxes. The Delete key will cut all selected lines. The current line and following lines created with the Add Line toolbar button will then have the same characteristics as the previous line. the cursor will appear as a cross. You can move. line thickness. a line will be created of the type that was last chosen. Moving Lines and Arrows. vertical. The position and length of the line can also be controlled by entering values for the Start and End position in the plot line dialog. Once on the Clipboard. To rotate the line and/or change its length. Hold the mouse button down while moving the mouse to the desired end position of the line. line thickness. the line will be forced to horizontal. the line can be resized. A dialog window will appear in which the arrowhead type. To move the line. Multiple lines can be selected by holding the Shift key down. Rectangles and Circles can be moved and copied in the same manner. arrow size. Selected lines can be copied to the Clipboard using the Cut and Copy commands in the Edit menu. If you hold the Shift key down. moved. double-click or right-click on the line. When you select a line by clicking on it. and color) of all selected lines can be changed at one time. or rotated. press and hold the mouse button down anywhere near the middle of the line while dragging it to its new position. Holding the Shift key down while resizing a rectangle or circle will force the width and height to be the same size. e. If the tool bar is visible. In this case.EES Windows Chapter 2 Resizing the Plot The size or aspect ratio of the plot can be changed by pressing and holding the left mouse button with the cursor located within the resize area at the lower right corner of the plot rectangle. (You can prevent the text font size from changing if you hold the Ctrl key down while resizing the plot. if the 'Automatic scaling' checkbox is checked then the axes will be automatically scaled as appropriate to contain plotted data for all lines in this plot window. The cursor will change from an arrow to the resize indicator when it passes over the resize control. The #Ticks/Division is the number of minor ticks. However. the edit boxes for the minimum. If Grid lines is selected. the resize area is marked with three 45° lines. the size and positions of all text items and lines are proportionally changed. the number of tick marks between each interval. clicking on #Ticks/Division will change it to #Grids/Division 55 . Either action will bring up the Modify Axes dialog window. When the plot is resized. Selecting the Zero line causes a vertical (for x-axis) or horizontal (y-axis) line to be drawn at a value of zero. These values can be changed as desired.) Modifying the Axis Information The axis scaling and appearance can be changed by double-clicking the left mouse button on the abscissa or (left or right) ordinate scales or by selecting the Modify Axes menu item in the Plot menu. The size of the plot will change as you drag the lower right corner to a new position. By default automatic axis scaling if off and the scaling of the selected axis is controlled by the minimum. maximum and interval values shown in the edit boxes. If a new plot line is added or if the data in one or more of the plots are changed such that one or more points are outside the range of the axis scale.. i. Scale numbers are placed at the position of each interval. The axis for which the changes are to be made is indicated by the radio-button controls at the upper left. the axis scale will automatically change. as are Grid lines if selected. maximum and interval values will be disabled. the scale numbers will be displayed. The characteristics of these numbers are controlled by the remaining fields on the right-side of the dialog window. If the Show Scale control is selected (as shown). 56 .Chapter 2 EES Windows allowing grid lines to be placed at points in between the major ticks. All current plots in the current plot window will be listed in the rectangle at the upper left in the order in which they were constructed. color.EES Windows Modifying the Plot Information Chapter 2 The line type. and other information relating to each plot can be viewed or modified by double-clicking the left mouse button anywhere within the plot rectangle (but not on text or a line.g. will cause EES to plot the line using cubic splines to produce a smooth curve through the data. row range. EES allows plots to be created that use the right-hand y-axis (Y2) and a top x-axis (X2) scale. The Spline fit control. 57 . The check box controls for X-axis and Y-axis error bars are enabled only if the data being plotted were obtained with the Uncertainty Propagation Table command in the Calculate menu.. plot symbol (or bar type for bar plots). Automatic Update sets up a direct link between the plot and the data in the Parametric Table so that the plot will be automatically redrawn if any change is made to the data in the Parametric Table.) The dialog window shown below will appear. Clicking the Data button to the right of Automatic Update allows the characteristics of the link (e. if selected. Select the plot by clicking on its name. X and Y axis variables) to be changed. This dialog window can also be made to appear with the Modify Plot menu item in the Plot menu. Click the Apply button if you wish to view the changes you have made. The scales in use for the selected plot are shown at the lower left of the dialog in radio button controls that allow changes to be made. Click OK to proceed with the alignment of the selected items. Add Rectangle. The coordinates at the intersection of the crosshairs can be viewed in the plot window title bar.Chapter 2 EES Windows Aligning Items on the Plot Window The Align button on the Plot Window toolbar is enabled when two or more text items. rectangles. and Add Ellipse toolbar buttons. lines. Add Line. These objects are created with the Add Text. Crosshairs Holding the Shift and Ctrl keys down will change the cursor into crosshairs. or ellipses are selected. a small dialog window will appear showing alignment choices. After selecting this button. 58 . The information used to construct this second list is determined by examination of the blocking order of the equations in the Residuals window. Clicking the Yes button will bring up the Debug window. except for informational purposes. and Unit Checking Report. The second list shows the variables which are most likely to be involved in any missing or extra equations. This window provides two lists of variables. The first list shows all variables which are referenced only once in the Equations Window.EES Windows Chapter 2 Debug Window The Debug Window displays diagnostic information of three types: Incorrect Degrees of Freedom. 59 . Incorrect Degrees of Freedom Whenever an attempt is made to solve a set of equations in which the number of equations is not equal to the number of variables. For example. a message box such as that shown below will appear. You may also find the information in the Residuals window helpful in identifying the problem with your equation set. These variables are possibly spelled wrong or otherwise not being directly used in the problem. Each of these capabilities is described below. Constrained Solution. Clicking the left mouse button on a variable name will open the Variable Info dialog window in which the lower or upper bound can be changed. If this happens. 60 . If the user wishes to see the additional information. Clicking on an equation will move the cursor to that equation in the Equations window. the Debug window will appear similar to that shown below showing the variables that are constrained and the affected equations. EES will present a dialog box warning of this problem and offer more information. Constrained Solution In some cases. a problem cannot be solved to within the specified tolerances because the lower and/or upper bounds one or more variables have restricted the solution.Chapter 2 EES Windows Clicking the left mouse button on a variable name in the Debug window will bring the Equations Window to the front with that variable name selected. the following equation will set the Q_dot to 1000 with units of Btu/hr. Each equation that is found to have a dimensional or unit inconsistency will be displayed (in black) followed by an explanation (in blue). You can add new units or modify information in this file using any text editor. It may be somewhat more convenient to enter the units of each variable in the Solution window. Note that the Check Units command uses the dimensional information contained in the Units. Opening a .var files to be saved from the Variable Info dialog which save the units and all other information. Left-clicking will select or unselect a variable. The Professional version allows . The Default Variable Info command (Options menu) allows the units (and other information) to be set based on the first letter of the variable name. Q_dot = 1000 “[Btu/hr]” The units of variables in the Parametric and Arrays tables can be changed by right-clicking on the column header. 61 .txt file which exists in the directory that the EES program is located. For example. Clicking the left mouse button on the equation will jump the focus to offending equation in the Equations window. Units of constants can be declared directly in the Equations Window by following the equation with a comment with the units provided in comments.EES Windows Chapter 2 Unit Checking Report The Check Units command in the Calculate menu will display its finding in the Debug window. The units that are associated with each variable can be entered in a number of ways. Clicking the right mouse button on the equation will bring up an abbreviated form of the Variable Information dialog window showing only the variables in that equation. A direct way of entering units is to type them directly into the Variable Info dialog (Options menu).var file using the Read Var File button in the Variable Info dialog or using a $Include directive sets the variable information for all variables that have been previously saved. Right-clicking will bring up a dialog window in which the units of all selected variables can be modified at once. The units that EES recognizes can be displayed using the Unit Conversion Info command (Options menu). 62 . the dialog window shown above will appear. The current directory is indicated below the text Folders: and EES files in that folder (directory) are shown in the list on the left. After the confirmation for unsaved work. To select a file.CHAPTER 3 __________________________________________________________________________ __________________________________________________________________________ Menu Commands The File Menu Open will allow you to access and continue working on any file previously saved with the Save or Save As… commands. click on the file name in the 63 . All variables and equations will be cleared. and the size and locations of the windows.EES file to be merged with the current contents of the Equations window at the cursor position. Choose the OK button to select the file (or directory) displayed in the Filename field. Text files with a . New initiates a new work session.EES filename extension are the norm. Import files with a . EES functions. EES can read four types of files that are identified as EES file. A check mark will appear to the left of the word Save in the File menu if the current problem information has been saved on disk. Library files are EES files containing one or more functions. variable information.EES filename extension. By default. EES files with a . The format is selected with the drop-down list at the bottom left of the dialog window. All information concerning the problem definition is saved. as described in Chapter 5. you will be prompted to supply a file name. Text file. just as if the Save As… command were given. procedures or modules which can be automatically loaded at startup. procedures and modules can be loaded using the Load Library command or $INCLUDE directive. Save will save your problem definition with the same file name (which appears after Save in the File menu and in the title bar of the Equations window) as it was last saved. and Library file formats. The unit system will be restored to the settings that would be in effect if the program were restarted. Click on the drive name to select it. Merge allows the equations previously saved in an .TXT filename extension contain ASCII text which is read into the Equations window. You can open files in another directory by entering the directory name in File Name: field or by clicking on the folders listed in the Folders list. such as the Macintosh. Import file. including the equations. If an unsaved problem definition exists. For a new work session which has not yet been named. If you wish to export the file to a version of EES on a different operating system. Equations can also be entered from a text file using the $INCLUDE directive. the tables. use the Export format in the file type available in the Save As… command. Any change in the problem information will cause the check mark to disappear. The Merge dialog window operates in the same manner as for the Open command.Chapter 3 Menu Commands list or enter the filename in the File Name: edit box. you will be asked if you first wish to save your current problem information. the file will be saved in the standard EES file format with a .XPT extension are files saved by EES with the Export option from a different operating system. Clicking on the Drives list displays the available drive designations. Enter the file name of your choice 64 . the plots. Save As… provides the same function as the Save command except that it will first prompt you to supply a filename in the Save File dialog window. The Save As command allows the problem definition to be saved with another filename or in a form which can be exported to EES versions on other operating systems. Menu Commands Chapter 3 in its place. The file name may include drive and directory information. The Library type will change the filename extension to be . if you define a variable X with the equation X=6 and later decide that the equation should read X1=6. and format. e.g. particularly problems using array variables. bounds. These functions can be used exactly like the EES built-in functions. EES will display a check box in the Save As dialog with the caption "Purge XXX unused variables" as shown above.XPT filename extension and save the file in a generic ASCII format which can be transferred to other operating systems such as the Macintosh. However. In cases when there are many variables that are not in use.LIB. EES normally saves every variable defined during the work session regardless of whether or not it currently is in use when the Save or Save As command is issued. The Text file type will apply a . See Chapter 5 for additional information. guess value. EES recognizes four file types. units.TXT filename extension and save only the text in the Equations window in an ASCII file. The 32-bit version of EES supports long file names. For very large problems. Library files are one of the most powerful features of EES because the user can easily develop special purpose functions. To save only those variables which are currently in use. it opens all of the . and modules in these files. procedures. Each time EES is started.EES (the norm) and files having this extension will be displayed in the filenames list. The Export file type will apply a .LIB files in the USERLIB\ sub-directory and automatically loads the functions. it is not necessary to enter a filename extension. the extension in the File Name: field will be set to . EES will still keep the variable X and all of its characteristics in memory. If EES is displayed in the Type box at the lower left. For example. EES could run out of space. EES can store up to 6000 variables. since EES will supply the extension automatically. click this 65 .. click the mouse while the cursor is positioned in the box. See the 66 . the window will be printed. The printed output will be sent to the selected printer. To place an X in the box or to remove an existing X. such as the Plot Window and the Parametric and Lookup Table windows. Some windows. When purging variables. It is possible to direct the output to a file.Chapter 3 Menu Commands checkbox. clicking in a check box will bring up a small supplementary window to select the plots or tables that are to be printed. with the Connect options in the Printers applications. may contain many sub-windows. rather than a printer. For these windows. accessible by tabs at the top of the window. Each window has a small check box preceding its name. it is advisable to save the file with a new name. Print will print any or all of the EES windows to the printer or to a file on the disk. If an X appears in the box. In this case. the original file can be recovered if a problem develops. If the check box is grayed (as it is for the Arrays window in the Print dialog window shown below) the window is not available for printing. The drop-down box at the top of the dialog allows the printer selection to be changed. If the “Page breaks” check box is selected. If the “Print in color” check box is selected. and/or modules which operate as described in Chapter 5. all printing will occur in black and white. Printing options such as the font. Note that when EES starts. The following dialog will appear when this menu command is chosen. Make Distributable Program (Professional version only) will create a special purpose version of EES which will run one to five pre-selected problems. The Textbook menu section at the end of this chapter provides instructions for creating and using a Textbook menu. The Load Library can also be used to load external functions and procedures with filename extensions of . 67 . See Chapter 6 for additional information. EES will attempt to print selected windows using the same colors as appear on the screen. Printer Setup provides a dialog window that allows the printer to be selected along with printing options. A textbook index file can also be loaded automatically by placing the textbook index file and associated problem files in a subdirectory within the USERLIB subdirectory The Textbook menu provides convenient access to set of problems. procedures. Library files contain usersupplied functions. a forced page break will occur so that the printed output for each window starts on a new page. When this control is deselected. it will preload all of the library and externally-compiled files which are found in the USERLIB\ sub-directory so the Load Library command is not needed for these files. and font size are set in the Preferences dialog window (Options menu). such as the paper size and orientation. Load Library will bring up the standard open file dialog showing EES Library files (which have a . An expiration date can be optionally set which will prevent the program from being used thereafter. The Preview button will direct a facsimile of the printed output to the screen. Load Textbook reads a user-generated Textbook index file with the filename extension (.FDL. A special version of the EES program with one to five EES problems and all supporting files are placed in a single executable file when you select the OK button. This Make Distributable Program command is available only in the Professional version. such as those developed for use with a text. Once loaded. This executable file can be freely distributed to others. The printer selection can also be made in the Print dialog window.Menu Commands Chapter 3 Windows manual for additional information on selecting printers. and .DLP. these library files remain in memory until EES is closed.LIB file name extension) in the file selection box.TXB) and uses the information in this file to create a Textbook menu at the far right of the menu bar. . Colored text may not print clearly on some black and white printers. The $INCLUDE directive described in Chapter 7 can also be used to load library files.DLF. line spacing. any one of the five files can be selected as the file that appears at startup by providing /# as a parameter where # is an integer between 1 and 5. By default. the first file will automatically be loaded by default. The button on the right saves all of the information in the Make Distributable dialog window into a file having a . The other files can be selected from the recentlyaccessed file list at the bottom of the File menu. click the 'Equations Window Visible' check box. However. The names that appear in the file menu are entered in the third edit field for each file. However. However. The advantage of this feature is that you can freely distribute any program you generate in EES to others. Two small buttons are provided just below the Cancel button in the Make Distributable dialog. The other button will open *. even if the user changes the equations. For example.MDI (Make Distributable Information) filename extension. entering MyPrg. The remaining items in the dialog window are a series of check boxes that control the capabilities the user will have when running the distributable version. the name is the filename without the path or filename extension. You can make this window read-only by clicking the following check box. These buttons allow saving and loading of scripting files to simplify the process of creating distributable programs. If you want you user to have the ability to view the equations window.exe /2 in the Windows Run dialog will start the distributable program and display EES file 2. the changes cannot be saved with the distributable version.MDI files and fill all of the field in the Make Distributable dialog window using the information in the file. it can be edited to be any name that you wish to see presented in the File menu. 68 .Chapter 3 Menu Commands When the distributable program is started. (You can download a copy of the WinZip program from www. EES has been tested with both MiKTeX versions 1. This installation program will install MiKTeX into the C:\texmf\miktex directory by default.tug. the PDFLaTeX accessory that is included with the TeX compiler can also produce a .20e.html. EES must know the location of the PDFLaTeX. 69 .20.exe to a temporary directory. The TeX document is an ASCII file with a .exe program that is provided with MiKTeX. the Create LaTeX/PDF Report command does not directly print but instead creates a TeX document in LaTeX2e.20 folder and then doubleclick on the SetupWiz.zip to a temporary directory on your hard drive. When you unzip this file. Create Latex/PDF Report generates a report including the Diagram.Menu Commands Chapter 3 Open or Create Macro (Professional version only) will initiate the process of recording a series of EES instructions that can later be started from the Windows Run command or from a different program to replay all of the instructions in the Macro file.adobe. this program will be located at C:\texmf\miktex\bin\pdflatex. if they are not already installed on your computer. To make use of the output generated by this command you will need to install the LaTeX2e compiler and Adobe Acrobat Reader.20e and beta version 2.) Open the 1.. The recommended installation of Latex2E is MiKTeX. Both of these programs are available at no cost. solution. Execute this file to install Adobe Acrobat Reader.com if it is not already installed on your machine.com/products/acrobat/readstep. Used in this manner. LaTeX2e produces a . However.dvi (device independent) output file that can be viewed and printed by various utilities. tables. EES can also run the Macro file on demand by a Dynamic Data Exchange (DDE) command. The following installation directions are applicable to MiKTeX version 1. EES can be directed to solve a set of equations in a specified text or EES file and put the solution into another specified text file without ever appearing on the screen.20 folder in the temporary directory.tex filename extension that must be processed by a LaTeX2e compiler. equations. In this respect.0 can be downloaded from:. Adobe Acrobat can also be installed from the EES CD when you install EES.zip. However. The MiKTeX homepage is (portable document interface) file that can be viewed and printed with Adobe Acrobat Reader.exe application.exe. Save the distribution zip file called 1. the distribution files will be located in the 1. Select the language and operating system from the dialogs provided on this webpage and download file ar405eng.WinZip. this command is similar to the Print command. Additional information concerning Macro files is provided in Chapter 7. Adobe Acrobat Reader 4. Download the distribution zip file in one step by either clicking on the appropriate link in the MiKTeX home page or entering the following URL into your browser program. If you install MiKTeX into its default directory.20. and plots.org. will be displayed centered at the top of report. In this case. 70 . The Title field is by default filled with the EES filename and the date. The title of each group box begins with a left bracket character. If the window is to be included in the report.tex filename extension if it is to be recognized by the pdflatex application. The Parametric Table. a dialog will appear when you click on the group name to allow selection of the tables or plots that are to be included in the report. the corresponding window is not available. which can be changed to whatever you wish. This title. the character following the left bracket must be an X or a number.Chapter 3 Menu Commands A dialog shown above will appear after selecting the Create LaTeX/PDF Report command. At the top of the dialog is an edit field for a filename.tex filename extension. Each window is represented with a group box with one or more options. have tabs with the possibility of accessing more than one window. If there is only one possibility. Lookup Table and Plot windows. On the left side of the dialog are controls to select the windows that will be included in the report. By default. Solution. The filename can be changed. but is should have a . The Browse button to the right of the filename should make it easy to select an alternative location for the file. the number enclosed in the brackets in the group name is the number of tables or plots that are to be included. If the group box is displayed in grayed text. this filename is set to the name of the EES file but with a . Click on the group name to change the selection. If there are multiple windows. such as for the Equations. you can of course modify the . seems to provide a reasonable balance. The . The allowable values are 1 to 99.pdf file sizes) but sacrifice graphic quality. _P2.TeX file as needed. long equations may end up running off the right margin. a long equation can be broken into two or more shorter equations by introducing some new variables.jpg filename extension in the same directory as the .tex file. but you can control this problem quite well by specifying the number of columns. The Diagram and Plots that are to be included in the LaTeX document are stored in separate files having a . The user has control over this decision with the JPG quality input box.exe application to compile that . When creating a .tex file with the addition of _D for the diagram and _P1. For example. Long equations are the major problem. Large values result in high quality graphics. The figures will be scaled to the width you specify while maintaining the existing aspect ration. The Solution and table group boxes each have a field to specify the number of columns that will be used to display the data in the report.jpg file.TeX processor does not wrap the information if it is too wide for the page. These . but depending on the formatting.jpg files have same parent name as the . EES allows you to break an equation so that it continues on the following line if the last character on the line is a &. If the Create PDF document checkbox is selected. Each group box provides controls to deal with this situation. One limitation of the LaTeX report is that it will not automatically fit the contents to the width of the paper.tex file that it has just saved. EES will attempt to start Abode Acrobat to display 71 . The default value. Both of these options help to reduce the long line problem. 75. it may produce a LaTeX error. but at an expense of great file sizes. Other tools available to deal with long lines are the font size and margins that are specified on the right side of the dialog. You can control this situation somewhat by modifying the equations you enter in the Equations window. rather than a number will be enclosed within the brackets if the window is to be included. an X. If you are familiar with LaTeX code. a decision must be made to balance the file size with file quality. even if it is broken into multiple lines with the & character.) The LaTeX report will also attempt to break the equation at the & symbol. The check boxes in the Equations group box allow multiple equations that are entered on a single line in EES to appear on separate lines in the report and comments that appear on the same line as the equation to be be placed on a separate line. If the Display PDF document checkbox is selected. (Note: the total length of an EES equation must be less than 255 characters. Also. for the plots. For example.Menu Commands Chapter 3 and Arrays windows.jpg file sizes (which result in small . The PDFLaTeX group box on the right side of the dialog contains three checkboxes. The width of the Diagram and plot windows can be directly entered. EES will attempt to start the PDFLatex. Low values result in small . etc. The remaining items in the File menu are recently accessed filenames. You can specify or change the default location by clicking on the Setup button.pdf file. the LaTeX file will be deleted leaving only the . EES will write the information in the dialog to a small file called EES_tex. If the Delete TEX document checkbox is selected. When you click the Create button.PDF file. It is recommended that this list be disabled if the program is installed and used on a network. This list can be disabled in the Preferences dialog. Should any problems occur that cause EES to stop.ini so that it is available as the default the next time you enter this dialog.exe application resides.Chapter 3 Menu Commands the . note that EES will save your file when starting the Create LaTeX/PDF report command with a filename created by appending a ~ to the current name. EES must know where the PDFLaTeX. Selecting any of these filenames opens the file. Exit provides a graceful way to exit the program.exe. The default location is C:\textmf\miktex\bin\pdflatex. your file can be recovered. 72 . Also. Most programs. Copy Solution will place the contents of the Solution window on the Clipboard both as ASCII text with each variable 73 .line feed. The deleted item is placed on the Clipboard where it can be pasted to another location with the Paste command. If Undo is unavailable. but it produces a high quality image when printed. the text items added with the Add Diagram Text command will not be included. provide a Paste Special command in which you can select among the available formats that have been placed on the clipboard. The bitmap requires more memory. Data in this standard format can be pasted into any location of the Parametric or Lookup tables or into other applications. the Copy command will copy the selected cells (shown in inverse video.) The data copied from the table are stored on the Clipboard in a standard format in which numbers within the same row are separated by a tab and each row ends with a carriage return . the menu will be disabled. If you hold the Ctrl key depressed while copying the Diagram window. such as a word processor.Menu Commands Chapter 3 The Edit Menu Undo restores the Equations window to the condition it was in before the last editing operation.) Copy will move a selected Plot window or the Diagram window graphics into the Clipboard from which it can be pasted into other applications. Copy functions in a manner dependent on which window is foremost. The Picture format produces exactly the image that you see on the screen. (Hold the Shift key down when selecting the Copy command if you wish to also copy the column heading and units. EES copies the Plot window to the clipboard in two formats: as a picture and as a high-resolution bitmap. If you are intending to print the image that you have copied and you are concerned with the print quality. The copy of the Plot or Diagram window is stored in MetaFilePict object format. or Array Table window is foremost. When the Parametric. Copy will place the selected text from the Equations window on the Clipboard from which it can be restored at the cursor position with the Paste command. Cut deletes the selected (highlighted) text or selected item. use the Paste Special command and select the bitmap option. Lookup. Scroll bars will appear as needed to allow access to array cells that are not visible in the window. If no arrays are defined. The Select All command is normally followed by Copy which places the selected items on the clipboard. The Paste button is enabled only if text has been placed on the clipboard. Data can thus be moved between the Parametric and Lookup tables. Clear removes the selected text without placing a copy on the Clipboard. Tabs separate the different items on each line of the Residuals windows. See the description of the Solution Window for more information. Copy and Paste can also be used with text items placed on the Plot windows.Chapter 3 Menu Commands is on a separate line and as a picture of the formatted Solution window. Select the name of the array for which you wish to enter or modify values. 74 . The Copy button should then be enabled . click the mouse in the upper left cell. this rectangle will display -> Enter array name. When Paste is used in the Parametric or Lookup Table window. Use the Paste Special in another application. Select All will select all of the text in the Equations window. Clear can also be used to delete the contents of the Diagram window. The copy and paste capability make it possible to import or export data to and from a spreadsheet. the Select All command appears as Select Display. Lookup. It is enabled only if two or more cells in the table are selected. Hold the Shift key down and click in the lower right cell. click the mouse in the upper left cell for which the paste operation is to start. The dropdown edit rectangle at the top of the dialog displays the names of all of the arrays that are defined in the Equations window. Plot and Diagram windows. The Clipboard contents can be pasted into a word-processor. Insert/Modify Array provides an easy way to enter or modify the values in EES Arrays. Paste moves the text (or graphics for the Diagram window) previously placed on the Clipboard with the Cut or Copy commands in EES or in other applications. such as a word processor. This command will select all currently visible items in the window. depending on which window is foremost when the command is issued. The two speed buttons provide access to Copy and Paste. or all of the cells in any of the three tables. The dialog window is shown below. To paste text into this window. To select a range of cells. Pasting will proceed to the right and down the table. the values stored on the clipboard will be copied to the table starting in the cell in which the cursor is currently located. to select either the text or the picture for pasting. Parametric. The number of columns and rows in the array can be adjusted with the Rows and Columns controls. Enter the name of the new array. If the Formatted Equations window or Solution window is foremost. The top button is the Copy button. Paste is active for the Equations. Copy will place the entire contents of the Residuals window on the Clipboard as text. EES will convert the values that you have entered into EES equations and enter these into the Equations window. EES uses these comments to locate the position in the equations window in which the array elements are defined. When you click the OK button. The entered will be placed within comments of the form: {Array A} A[1]=1 A[2]=2 … {Array A end} where A is the array name.Menu Commands Chapter 3 Enter the values of the array elements that you wish to define in the table. EES will find the previous array using these comments and overwrite the array with the newly entered values. 75 . If you later wish to redefine the array. Do not delete or edit these comments. Chapter 3 Menu Commands The Search Menu Find will search the Equations window for the first occurrence of the text entered in the Find what: field. The Cancel button will change to Done after the find process is completed. The search options will be remain in effect if they were set in the Find command. Next will find the next occurrence of the text previously entered with the Find or Replace command.. 76 . If the ‘Match whole word only’ option is selected. The search is case-insensitive unless the ‘Match case’ option is selected. The Cancel button will change to Done after the find process is completed. the text will be found only if it is delimited by spaces or mathematical operators. in which the guess value. bounds. and units of all variables currently appearing in the Equations window can be viewed and changed. as shown below. If the program contains one or more modules (see Chapter 5 for a discussion of modules). all array elements appear in the Variable Info dialog and the guess value. The “Show Array Elements” checkbox control will be visible at the upper left of the dialog window if there any arrays are used in the Equations window.Menu Commands Chapter 3 The Options Menu Variable Info will provide a dialog window. selected based on the first letter of the variable name. The information for the selected module can then be changed or viewed. a control will be provided at the top of the dialog to select the module or main program. display format. These data are initially set to default values. lower and upper bounds. may be set with the Default Info command. display format. When this control is selected. and units can be set for each individual element as for any other 77 . The defaults. The Convert function described in Chapter 4 can be used to convert units. other characteristics.e. and hilighting effects. The same update feature is provided with the Update Guesses command in the Calculate menu. If the variable name is changed. EES will change every occurrence of the original variable name in the Equations. number of significant digits. as well as a number. All fields. Variables for which the value has been pre-calculated are identified by having the bounds shown in italics. The units of the variable (or any other desired information) may be entered in the units column. The Cancel button will restore all fields to the condition they were in when the Variable Information dialog was first presented and then remove the dialog. including the variable name. The Guess. such as the bounds and units. Units are used by EES only for display purposes in the Solution and Parametric Table windows. Note that the display format and units of each variable can also be changed by clicking on the variable in the Solution Window. X[ ] represents all array elements having the parent name X. For example. the value determined in the last calculation. When the OK button is pressed. Note that the height and width of this dialog window can be changed by selecting an edge and dragging it in the usual Windows manner. The words. Clicking in these fields will produce a pop-up menu for the display style. that change is applied to ALL array elements. Lower and Upper value fields will also accept a variable name. the array name can be changed by editing the name in the first column of the Variable Info dialog. The display format of a variable in the Solutions or Table window is controlled by the three fields in the Display columns. The Variable Info dialog window can be resized by dragging the lower right corner. respectively. The Print button will direct a copy of the information in this table to the selected printer. EES uses the current value of that variable as the guess value or bound. i. In addition. Use the scroll bar on the right side of the dialog window to bring the variable information into view. However. would not be affected. -infinity and infinity can be used to indicate unlimited lower and upper bounds. The pre-calculated value appears in the Guess column. The Update button replaces the guess value of each variable with its current value. 78 . may be changed as required. EES attempts to solve equations having a single unknown before this display appears. If any of the characteristics for a parent array are changed. Parametric table and Diagram windows. When a variable name is provided. all changes made to the variable information since the dialog window appeared are accepted.. These guess values and bounds may still be edited which will then cause EES to recalculate the value. when the control is not selected. all arrays elements are represented by a single entry. Changing the guess value for X[ ] will result in the new guess value being applied to all array elements in array X.Chapter 3 Menu Commands variable. However. You save the variable information to an existing file that already has variable information for variables A. when preparing your next problem. However. In this case. B. In this case. limits and units will be automatically updated. Y. If a program contains one or more modules. C. and X. 79 . Variable information is saved in a file having a . T2. The first application is to provide different sets of guess values for a problem that has difficulty converging. the file is updated with the current information for the variables that are in use. if you commonly use variables T1. the information in this file is in tab-delimited ASCII format so that it can be opened. Information in the file concerning variables that are not currently in use is not modified or deleted. and C is not altered. Used in this way. B. and Z. The variable information for X is updated to the current settings and variable information for Y and Z are appended to the file.Menu Commands Chapter 3 Professional Version Variable information for a module or main EES program can be saved to or loaded from a disk file. viewed or modified with a word processor or spreadsheet.VAR filename extension. A more general application is to use a variable information file to store information for variables that you use repeatedly in your problems. suppose you have a program that uses variables X. For example. but in this case. Variables that are in a module are stored in the variable information file with the module name so that the same variable names can be used in modules and the main program with no confusion. the Save or Open Variable Information operation will be applied only to the selected module or main program. Variable information data can be saved to an existing . The information in a .VAR file. The file operations are accomplished using the two small buttons at the upper right of the Variable Information dialog. For example. Then. limits and units in the Variable Information dialog and Save the information in a Variable information file. a dropdown list appears at the top center of the Variable Info dialog from which the module or main program can be selected. the saved information does not need to relate to the first letter in the variable name. There are several important applications for variable information files. the variable information files provide a similar capability to that available with the Default Variable Information command. you can set their guess values. The information for variables A. you can open this variable information file and the guess values.VAR file can be automatically loaded using the $Include directive (Chapter 7). and T3 in your problems. Each set of guesses can be stored in a separate file and loaded as needed. CO2) are modeled as an ideal gas and use JANAF table reference values for enthalpy and entropy.g. respectively. The substances for which property data are available are shown in the Substance list on the right. Thermophysical property functions require specification of a substance. The units of the thermophysical property function are shown in the function list box. The User Library button provides a list of the user functions.. CarbonDioxide) are modeled as real fluids and do not use JANAF table reference values. 80 . procedures. ‘Real substance’ will appear if liquid and vapor states are determined. and modules loaded from Library files. Menu Commands The four buttons at the top of the dialog window indicate which information is to be provided. Math Functions and Thermophysical Props refer to the built-in functions for mathematical and thermophysical property relations. Substances represented by their chemical formula (e. Substances with their name spelled out (e.. Click on the substance name in the scrollable list to select the substance. click on the function name in the scrollable list. ‘Ideal gas’ will appear above the substance list if the properties of the selected substance are calculated using ideal gas law approximations. Click the Function Info button to obtain specific information relating to the function you have selected. The Fluid Info button provides information relating to the source and range of applicability of the property correlations. Air is modeled as an ideal gas. To select a function. (See Chapter 5 for additional information on Library files). The functions corresponding to the selected button will be displayed in the Function list on the left. Air is an exception to this rule.Chapter 3 Function Info will bring up the following dialog window. Psychrometric functions are applicable only to the substance AirH20.g. Additional information regarding all built-in functions is provided in Chapter 4. The External Routines button refers to compiled routines which can be linked to EES as described in Chapter 6. g.) Many of the unit identifiers are obvious. if you click on Area. press the Store button. The selected units are saved with other problem information when the Save command in the File menu is issued. (Note that the single quotes marks around the unit identifies are optional. The units will be changed for the remainder of the work session if the OK button is pressed. but not all. If you click the Paste button. All of the units which have been defined with the selected dimension are listed in the list on the right. 81 . only Acre and Hectares will be displayed. The unit settings are displayed in the Solution window. The unit system is only needed for the built-in function calls. any combination of units having the dimensions indicated at the top of the right list (e. Unit Conversion Info provides information to support the use of the Convert and ConvertTemp conversion functions. Unit System provides a dialog window shown below in which the units of the variables used in the built-in mathematical and thermophysical property functions may be set. They are stored in the UNITS. However. L^2 for Area) can be used in the Convert function. These units are then restored with the problem using the Open command. the contents of the Example rectangle will be pasted into the Equations window at the cursor position. Instructions for adding information are provided at the top of the file. as shown below. The purpose of this command is to list the unit identifiers that have been defined. EES does not provide automatic unit conversion.TXT file in the main EES directory. This file may be read as a text file and edited in EES. Note that only the defined units having the selected dimension are listed. You can add additional units if needed. The Convert function has the following format: Convert('From'. If you wish to permanently change the default values. 'To') where From and To are character strings identifying the unit type such as 'Btu/hrft2-R' or 'mph'. For example.. You can edit this information in the usual manner.Menu Commands Chapter 3 An example of the function with default variables will be shown in the Example rectangle at the bottom. Click on the dimension in the list at the left. small values for these quantities increase the number of iterations required for a solution and therefore the computation time. The stop criteria are saved with other problem information when the Save command in the File menu is issued and restored using the Open command. The stop criteria are the number of iterations. the calculations terminate. However. 82 . To change the default stop criteria that EES presents at the start of a new session. If any of these criteria is satisfied. Loss of precision is unlikely to be a problem even when very small values are set for the maximum residual or variable change. the maximum relative residual. press the Store button. All calculations in EES are done in extended precision with 21 digits of significance. The stop criteria will be set as displayed for the remainder of the session by pressing the OK button.Chapter 3 Menu Commands Tolerances will display a dialog with two tabbed windows allowing a specification of Stop Criteria and Integration auto step parameters. the maximum change in a variable value from one iteration to the next and the elapsed time. The two radio buttons control whether EES will use a fixed or a variable step. The test that is done is as follows: Every N steps EES will compare the value of the integral for that step with the value obtained using two half steps. If "Vary step at intervals of" is selected. During this checking process. If the normalized truncation error is greater than the value provided for 'Reduce step if rel. The difference between these two values is the truncation error. The minimum and maximum allowable steps and tolerances which control whether the step size is changed are input by the user. The parameters in this tabbed section of the Tolerances dialog only affect the step size that EES automatically selects during numerical integration with the equation-based integral function. error <'. The truncation error is normalized by dividing it by the value of the integral for the two half-steps. If the Stop Criteria parameters are set to allow convergence with errors larger than that used to reduce the step size. error >' the step size if reduced. the step is increased. EES will check the numerical situation of the integration process every N steps where N is input by the user.Menu Commands Chapter 3 EES uses numerical integration to determine the value of an integral or to solve differential equations. If the "Use fixed step size' button is selected. The equation-based Integral function can use either a fixed usersupplied step or an automatic step adjusted to meet some accuracy criteria. Note that there is an indirect relation between the Stop Criteria parameters and the integration truncation error parameters. If the normalized truncation error is less than the value provided for 'Increase step if rel. assuming that it is greater than the minimum allowable step size. assuming that it differs from zero. but rather use a fixed step equal to the interval divided by the number of steps indicated by the user. no change is made to the step size. EES will not attempt to adjust the step during calculation. Otherwise. increase. EES may decrease. 83 . or maintain the current step size. the calculation time and solution accuracy will both be adversely affected. provided that the increased step size does not exceed the maximum allowable step. Show/Hide Diagram Tool bar is enabled when the Diagram window or a child Diagram window (Professional version) is foremost. bounds. if you change the units for variables beginning with letter T to [K] and press the OK button. If the problems you do all tend to have the same nomenclature. display format and units of new or existing variables depending on the first letter in the variable name. 84 . When the tool bar is hidden. all text and graphic objects are locked and the window is in application mode. rectangles. When the tool bar is visible. Each new variable beginning with letter T will then also take on units of [K]. The Store button will cause the current default settings to be permanently saved so that these defaults will appear at the start of the program the next time EES is run. When enabled. No other changes to existing variables will be made. the Diagram window is in development mode. all existing variables beginning with letter T will take on these new units. it is best to set the default variable information and save it by pressing the Store button. Text and graphic objects such as (lines/arrows. The Default Variable Information command can also be used to selectively change information for existing variables. For example. Input is accepted for input variables and calculations can be initiated using the input variables supplied in the Diagram window. An Align button is provided to facilitate alignment of objects relative to one another. changed or deleted in development mode. and ellipses) may be moved. See the Diagram window section in Chapter 2 for more detail. The OK button sets the current default setting for this problem session only. The tool bar visibility can also be toggled using the Diagram Window button on the speedbutton bar just below the menu bar.Chapter 3 Menu Commands Default Info provides a means for specifying the default guess values. selecting this command will toggle the state of the tool bar for the foremost Diagram window. There are two ways to use this command. The Store button saves the preferences so that they will be in effect at the start of the program the next time EES is run. plot window. but if this control is selected. However. and complex number options. so do not depend upon it for permanent storage. general display options. EES Internal Functions and Procedures (Chapter 5) employ assignment statements as in FORTRAN and Pascal.EES file that has the same name as the open EES file. (EES modules use equality statements as in the main body of the EES program and thus cannot use the := assignment statement syntax. These options are shown and described below. equations display. printer display. the last saved copy of the backup file should still be available in your directory. file C:\EES32\ABC. X:=X+1 is a valid assignment statement. the selected preferences remain in effect for the remainder of the work session. For example. rather than equations as used in the main body of the EES programs. ! Autosave every XXX minutes instructs EES to save all information at regular intervals. The information is saved to a temporary . the autosave file is deleted when a new file is created or opened or when EES is closed at the end of the worksession. ! Allow = in function/procedure equations will suppress the error message that would normally occur if the assignment symbol (:=) is not used in EES Functions and Procedures. EES will also accept X=X+1.Menu Commands Chapter 3 Preferences provides six tabs for user choices concerning program options.EES will be autosaved as C:\EES32\~ABC. Under normal operation. You should always save any file that you intend to use at a later time using the Save or Save As commands. but it obviously is not an equality. If the OK button is clicked.EES.) An assignment statement sets the variable identified on the left of the statement to the numerical value on the right. The := sign is used to signify assignment. but with a tilde (~) preceding the filename. 85 . if EES quits unexpectedly. procedures and modules to be displayed in the Solution window. particularly for debugging purposes. The values of these local variables are ordinarily not of interest but you may wish to know them. ! Hide Solution Window after change causes the Solution. Warnings can also be turned on or off using the $Warnings On/Off directive in the Equations window. Procedures. and Subprograms which appear in the Equations window are affected by this setting. ! Place array variables in the Arrays Window instructs EES to display all array variables in the Arrays window rather than in the Solution window after calculations are completed. If this option is not selected and a change is made in the Equations window. and Subprograms that have been loaded from library files (See Chapter 5) are not displayed.FNL in the EES directory. ! Display warning messages will enable or disable warning messages during calculations. Modules. Procedures. Values in the Arrays window can be plotted and copied just like values in the Parametric and Lookup tables. ! Include a Sum row in Parametric Table will result in an extra row being added to the Parametric table which displays the sum of the values in each column. the Solution window title will change to Last Solution. ! Maintain a list of recent files in the File menu enables or disables a list of up to 8 recent files at the bottom of the File menu. The file names are stored in a file entitled EES. 86 . Module equations will also appear in the Residuals window. Only the Functions. Warnings are issued if thermophysical property correlations are applied outside of their range of applicability. and Residual windows to be removed from the screen display if a change is made in the Equations window.) ! Display menu speedbar controls the visibility of the toolbar appearing below the menu bar. The local values of variables in Functions. Modules. it is best to disable this feature. The toolbar will be hidden if this control is unselected. This list is a convenience that you normally would want to have. if EES is placed on a server where multiple users can access the program. However. (This capability is disabled for educational versions.Chapter 3 Menu Commands ! Show function/procedure/module values will allow the most recent values of local variables in EES functions. See the Arrays Window section of Chapter 2 for additional information. Arrays. Menu Commands Chapter 3 The font and font size can be selected from the drop-down lists. For example. X_hat will display as X . X_dot will display as X . beta. will appear in Symbol font. such as alpha. A dot. Calculated values are provided by EES during the Solve Table or Min/Max Table commands. The printer font and font size is selected separately in the Printer Display Tab. Display subscripts and Greek symbols controls the appearance of EES variables in the Solution. Formatted Equations. bar. The vertical bar character signifies the start of a superscript. Parametric Table and Diagram windows. The printer display is unaffected. The Calculated Table Values and Entered Table Values pertain to the display of values in the Parametric Table. or _hat to the " name. either directly by typing the value or indirectly through application of the Alter Values dialog. X_star will ˆ display as X*. Variables which have the name of Greek symbols. G|o will be displayed as G o . Additional underscores within the same variable name will be changed into commas. The following characters in the variable name will be displayed in smaller type and lower case. Entered table values are values which are provided by the user. and gamma. For example. Two fields are provides for each category to set the color and the font style of the display. _bar. the underscore will be used to signify the start of a subscript. Array variables will also be changed to appear as subscripted variables. The new font and font size will display in all of the EES windows. If the variable name is entirely in capital letters. 87 . the Greek symbol will be shown as a capital letter. or hat can be positioned over the variable name by adding _dot. X_infinity will display as X ∞ . If this option is selected. Note that a separate font style can be selected for printing in the Printer Preferences tab. " Function names (such as ENTHALPY. 88 . or as typed. the comment will be displayed in the Equations window but not in the Formatted Equations window. etc. etc.Chapter 3 Menu Commands EES can display comments in two different colors and/or styles which are selected by the user with the two drop down controls that follow the comment type label. ! Display uniform case for variable names causes each variable to appear with the upper and lower case lettering sequence set in the first occurrence of the variable in the Equations window. If braces are used. ! Wrap long lines in the Equations window will hide the horizontal scroll bar. This option controls whether line break characters appear in the left margin of continuation lines. DUPLICATE. {!This is a Type 2 comment} "!This is also a Type 2 comment and it will display in the Formatted Equations Window} "This is a Type 1 comment. For example. A red > symbol will be displayed in the left margin of continuation lines if Display line-break indicator is selected. ! Display line-break indicator is applicable only if the Wrap long lines option is selected. Both Type 1 and Type 2 commands must be enclosed within braces or single quotes. lower case. the Check/Format command in the Calculate menu will change all other occurrences.) can be displayed in upper case. Comment Type 2 is distinguished from Comment Type 1 by having an exclamation character ! as the first character in the comment. Lines which are too long to be displayed in the Equations window will be broken at an appropriate point and continued on the following line.) and keywords (such as FUNCTION. as selected with the drop-down controls. fluid names. If the first occurrence of the variable is changed. SIN. Font and size provide choices for the type in which the printed output will appear. space and one-half.Menu Commands Chapter 3 The options in the Printer Tab only affect the appearance of the printed output. This option is particularly useful when the comments are displayed in color on the screen but are to be printed on a black and white printer. or double-space options. Printed output line spacing provides single. These controls allow the comments to be printed in a different style than is displayed on the screen. Printed comment style 1 and Printed comment style 2 fields allow a font style to be set for each comment type. A Print in Color control is provided in the Print dialog window. 89 . Comment type 2 is distinguished from comment style 1 by having an exclamation mark (!) as its first character. font style. The plot width and height are entered in point units. Selecting Picture will paste the enhanced metafile. Ticks are the short line segments on the axis scale.Chapter 3 Menu Commands The Plots tab allows the default setting for the plot width and height. 600. or 1200 dots per inch. picture (enhanced). the font. The Copy in Color check box controls whether the Copy command will reproduce the plot in color or in black and white. they result in much greater memory utilization particularly if the copy is done in color. The device independent bitmap will paste the bitmap. After a plot has been copied to the Clipboard. font size. and the major and minor tick sizes for the axis scales to be changed. If the plot is copied as both a picture and bitmap. The plot can be configured for outdented ticks by specifying negative values for the tick sizes. The resolution of the copy may be specified as 100. as a bitmap. You may want to test both of these options to see which provides the best choice for a high quality image in your application. device independent bitmap. The default value is 300 dots per inch. the paste special command provides a choice of picture. These default characteristics are applied whenever a new plot is generated. bitmap. 90 . a point is either 1/96 or 1/120 inch. or as both a picture and bitmap depending on the setting of the radio buttons in the Copy as box. 300. Depending on your equipment and video setting. Higher resolutions generally produce a better image. but in the case of the bitmap copy. Major ticks are placed on the scale at the point where the axis numbers appear whereas minor ticks occur between the axis numbers. Ticks which are drawn into the plot rectangle are represented with positive numbers. The plot will be copied to the clipboard as a picture (enhanced metafile). it can be pasted into another application using the application's Paste or Paste Special command. The controls in the Clipboard Copy box affect the manner in which plots from EES are transmitted to other applications. The complex capability can also be turned on or off with the $COMPLEX ON/OFF directive. The imaginary variable name representing the square root of –1 can be designated to be either i or j depending on the radio button setting. 91 .Menu Commands Chapter 3 The Complex Tab allows the complex algebra capability in EES to be turned on or off. EES will use also open all of the library files in this directory at startup. it transparently loads library files from the USERLIB folder located in the directory in which the EES application is located. In any of the Preferences in any of the tabbed windows are changed. However. commands are issued. if a valid directory name is provided in the "Alternate user library folder" field. The default directory information is stored in the EES. Deleting this file resets the directory information.Chapter 3 Menu Commands The Default File Folder specifies the folder that EES will open whenever the Open or Save As. If the directory specified in this field does not exist or if no directory is specified. EES will initially use the directory that the EES program was started in and thereafter. it will use the last accessed directory. The default folder for Macro files is used when the Build Macro command (Professional vesion) is issued. When EES is started.. EES will use the directory in which EES is located. If no folder name is provided. 92 . The Store button will cause the Preferences to be permanently saved so that they will be in effect at the start of the program the next time EES is run.. pressing the OK button will set the Preferences for this session only.DIR file. The first syntax error found will be indicated with a message. The methods used by EES for solving equations are described in Appendix B. If no errors are found and if the number of equations is equal to the number of variables.) The dialog shown below will appear. number of blocks. EES will provide the option of viewing the Debug window which may help locate a problem. Choosing this option results in EES doing the calculations for all of the Parametric tables in sequential order. a solution to the equation set will be attempted. the information dialog indicates the elapsed time. EES will indicate the number of equations and variables in the Equations window. If the Diagram window is being used to enter one or more variable values. 93 . If no syntax errors are encountered. Solve will first check the syntax of the equations in the Equations window. the maximum residual (i. difference between the left and right hand sides of an equation). More than one Parametric tables may be defined in which case the table for which the calculations are to be done must be selected from the drop-down list. and the maximum change in the value of a variable since the previous iteration. See Chapter 2 for more information concerning the Debug and Diagram windows. (See the description of Parametric menu commands on the following pages for information on the use of the Parametric Table. One of the choices in the drop-down list is “All Parametric Table”. When the calculations are completed. An information dialog window summarizes the progress of the solution. If the number of equations is not equal to the number of variables. it must be open when the Solve command is issued. Solve Table will initiate the calculations using the Parametric Table..Menu Commands Chapter 3 The Calculate Menu Check/Format will recompile all equations and apply the formatting options selected with the Preferences command in the Options menu.e. Chapter 3 Menu Commands Each row in a Parametric Table is a separate problem. Otherwise. EES will accept input values from the Diagram window. EES will continue the calculations for the remaining rows. If no errors are found. If this control is selected. EES will first check the syntax of the equations in the Equations window. A message will be displayed after all of the table calculations are completed indicating the rows in which a warning occurred. The “Use input from Diagram” control will be enabled if the Diagram window is open and if it has one or more input variables. or italic type from a previous Solve Table command) are dependent variables. Warnings are issued if a property correlation is applied outside of the range for which it was developed. blue. Blank cells (or cells with bold. Min/Max is used to find the minimum or maximum of an undetermined variable in an equation set for which there is at least one and ten or fewer degrees of freedom. The values of independent variables are shown in normal type. If the Update Guess Values control is selected. a dialog window will appear presenting the undetermined variables in two lists. just as if these inputs were specified in the Equations window. EES will terminate the table calculations on the run at which the warning occurred. the guess values for each run will be set to the calculated values from the previous run. The values of these variables will be cleared and the newly calculated values will be entered in the table. If the Stop if warning occurs control is selected. otherwise each run will be initiated with the guess values specified with the Variable Info command. 94 . See the description of the Variable Info command in the Options menu for additional information on setting the bounds. depending on the settings of the buttons at the bottom of the dialog window. Multi-dimensional optimization may be done using either Direct Search or a Variable Metric algorithm. which uses numerical derivatives.) The recursive Quadratic Approximations method is usually faster. usually performs much better than the Direct Search method. 95 . To select (or unselect) a variable. This will bring up an abbreviated version of the Variable Info dialog containing just the selected independent variables. The Variable Metric method. but it may be confounded if the optimum is constrained to be on a bound. It is necessary to select as many independent variables as there are degrees of freedom in the Equations window. If there is one degree of freedom. You can view or change the bounds and guess value for each selected independent variable by clicking the Bounds button. The variable which is to be minimized/maximized is selected by clicking on its name in the list on the left. The number of independent variables which must be selected is indicated above the right-hand list. EES requires finite lower and upper bounds to be set for each independent variable. Careful selection of the bounds and the guess value(s) of the independent variables will improve the likelihood of finding an optimum.Menu Commands Chapter 3 Click the Minimize or Maximize button above the left list. (See Appendix B for information on the optimization algorithms. click on its name in the list. The independent variable(s) whose value(s) will be changed in searching for the optimum appear in the list on the right. EES will minimize/maximize the selected variable using either a Golden Section search or a recursive quadratic approximation method. but the Golden Section method is more reliable. or 2) the number of steps exceeds the specified maximum. along with the relative tolerance. except that the calculations will be repeated for each row in the Parametric Table. X1 = 300 ± 2.Chapter 3 Menu Commands The maximum number of times in which the equations are solved (i... Values in the Parametric Table which are shown in normal type are fixed and are treated just as if they were set to that value with an equation in the Equations window.g. Guidelines for Evaluating and Expressing the Uncertainty of NIST Measurement Results. the optimum is computed and the values of the remaining columns in the table are entered for each run. 1994). the variable which is to be optimized and all of the independent variables (whose values will be varied in seeking the optimum) must appear in the Parametric Table. The purpose of this command is to calculate how the uncertainties in all of the measured variables propagate into the value of the calculated quantity. EES will also stop the calculations if the equations cannot be solved with specified value(s) of the independent variables within the tolerance and allowable number of iterations specified with the Stopping Criteria command in the Options menu. a dialog window will appear in which the variable to be maximized or minimized and the independent variable(s) can be selected. an important quantity is not directly measured but is rather calculated as a function of one or more variables that are directly measured. etc.e. Calculations will stop if: 1) the relative change in the independent variable(s) between two successive steps is less than the specified tolerance. In this case. however. . The method for determining this uncertainty propagation is described in NIST Technical Note 1297 (Taylor B... Min/Max Table provides the same capability as the Min/Max command. National Institute of Standards and Technology Technical Note 1297. Y.. X2.).E. Uncertainty Propagation determines the uncertainty of a selected calculated variable as a function of the uncertainties of one or more measured values upon which it depends.e. The variable which is to be optimized and the independent variable(s) must be the same for each run.N. i.) As with the Min/Max command. The start and stop runs in the Parametric Table for which the calculations will be done may be specified. X2. and Kuyatt.. If no errors are encountered. (See the description of Parametric menu commands on the following pages for additional information on the use of the Parametric Table. have a random variability which is referred to as its uncertainty. In EES.. Y = f( X1. The measured variables. e. that uncertainty is displayed with a ± symbol. the uncertainty in the calculated quantity can be estimated as UY = F ∂Y I ∑ G ∂X J U H K 2 i i 2 Xi 96 . X1. Assuming the individual measurements are uncorrelated and random. C. In many experiments. the number of function calls) may be specified. just as if the Solve Table command were applied. Click the OK button Uncertainty Propagation dialog to start the calculations. The Parametric Table calculations will proceed after the OK button is selected. An uncertainty value for each measured variable must be provided. Select one or more measured variables from the list on the right. click the Set Uncertainties button below the right list. the Uncertainty Propagation dialog window will appear in which the calculated quantity is selected from list of variables on the left and the measured variable(s) are selected from the list on the right. After selecting the command. Click the OK button to set the uncertainties and close the Specify Uncertainties dialog window. To specify the uncertainty associated with the measured variables. The results are reported in the Debug window. EES will present two lists of variables. Uncertainty Propagation Table provides the same function as the Uncertainty Propagation command. Check Units will check the dimensional and unit consistency of all equations in the main part of the equations window.Menu Commands Chapter 3 where U represents the uncertainty of the variable. Select the variable for which the uncertainty propagation is to be determined from the list on the left. EES will display an abbreviated Solution Window containing the calculated and measured variables and their respective uncertainties. A second dialog window will appear in which the absolute or relative (fraction of the measured value) uncertainties for each selected measured variable can be specified. The units can be entered in the Variable Information dialog window or in the Solution window. The calculated and measured variables must all be in the Parametric Table before this command is used. The partial derivative of the calculated variable with respect to each measured variable will also be displayed. After selecting this command. For example: P=140 “[kPa] this line will set P=140 and its units to kPa” 97 . The units of a variable set to a constant in the Equations window can also be set with in a comment by enclosing the units in square brackets. The value and uncertainty for the calculated variable and each measured variable will be displayed in the Parametric Table after the calculations are completed. The difference is that this command allows the uncertainty calculations to be repeated for one or more measurements by using the Parametric Table. The equations in internal functions and procedures do not have units and they are not checked. The calculated variable can then be plotted with error bars representing the propagated uncertainty using the New Plot Window command. After the calculations are completed. Note that the variables appearing in the measured variables list must be constants so that their values are set to a numerical constant with an equation in the EES Equations window. It is necessary to enter the units of each variable for the checking process to function properly. namely the determination of the uncertainty propagation in a calculated variable. the focus will jump to that equation in the Equations window.in) The Check Units command will display the equation and an explanatory message for each equation that is found to have dimensional consistency or unit consistency errors. L_inch and L_feet. You should reset the guess values only if you are experiencing convergence difficulties and you have changed the guess values in an attempt to find a solution.0. but the Update Guesses command is more accessible.Chapter 3 Menu Commands The checking algorithm cannot know the units of conversion constants. For example. If you click the left mouse button on an equation. the Debug window will appear and this equation will be flagged as having an error because the units of 12 are not known. an abbreviate form of the Variable Information dialog window will appear showing just the variables that appear in that equation. Reset Guesses replaces the guess value of each variable in the Equations window with the default guess value for that variable. Update Guesses replaces the guess value of each variable in the Equations window with the value determined in the last calculation. However. L_inch=L_feet*convert(ft. The Convert function should be used instead. L_inch=L_feet*12 When the Check Units command is issued. 98 . respectively which are used in the following equation. Exactly the same function is provided with the Update button in the Variable Info dialog window. Update Guesses improves the computational efficiency of an EES calculation since it ensures that a consistent set of guess values is available for the next calculation. If you click the right mouse button on an equation. so it is best to avoid them in your equations. suppose you have two variables. Unless otherwise specified. the equation will be accepted with no error. if the Convert function is employed as shown next. whose units are set to inches and feet. This command is accessible after calculations have been successfully completed. EES assumes all guess values are 1. You can change the default guess values with the Default Info command in the Options menu. and to present data for plotting or curve-fitting. A dialog window will appear in which information must be entered to create the table. which corresponds to rows in the table. There is no limit on the number of tables that can be created. click on its name 99 . Each table is identified with a table name that is entered when the table is created.Menu Commands Chapter 3 The Tables Menu New Parametric Table creates a new Parametric Table in the Parametric Table Window. To select a variable. Parametric Tables are used in EES to automate repetitive calculations. The table name can later be changed by clicking the right mouse button on the tab. All variables (both independent and dependent) which are to appear in the table are selected from the alphabetical list of variables on the left. The table name is displayed on a tab at the top of the Parametric Table Window. is entered in the field at the top. other than available memory. The number of runs. as in this example. to solve differential equations. overwriting any existing table. Entered values are assumed to be independent variables and are shown in normal type. Click the Add button to move the highlighted variable names to the list on the right. Pressing the OK button will create the Parametric Table. Min/Max Table. The list box below the First Value 100 .Chapter 3 Menu Commands in the list. otherwise the problem will be overspecified. The column for this variable will be cleared if the Clear Values control is selected. The variable for which changes are to be made is selected from the list by clicking on its name.e. values for the selected variable will be entered automatically in the table starting with the value in the First Value field. The independent variables may differ from one row to the next. This command will bring up the Alter Values dialog. (As a shortcut. Dependent variables will be determined and entered into the table in blue. However.) The variables in the right-hand list will appear in the columns of the table in the same order in which they appear in the list. shown below. which will cause it to be highlighted. The runs (i. rows) affected are specified at the upper left of the dialog. If Set Values is selected.. A variable can be removed from the table list by clicking on its name in the right list and then clicking the Remove button or by double-clicking on the variable name. or Uncertainty Propagation Table command is issued. a variable is automatically added to the list on the right when you double-click on its name in the list on the left. Alter Values provides an automatic way to enter or clear the values of a variable for multiple runs. for every row. The Parametric Table operates somewhat like a spreadsheet. it can not also be set in the Equations window. Numerical values can be entered in any of the cells. the number of independent variables plus the number of equations must equal the total number of variables in the problem. or italic (depending on the choice made in the Preferences dialog) when the Solve Table. Entering a value in a table produces the same effect as setting that variable to the value in the Equations window. Multiple names can be selected. Each row of the table is a separate calculation. bold. If a variable is set in the table. The Store and Retrieve Parametric Table commands were originally developed to overcome the limitation of a single Parametric Table in earlier versions of EES. Increment. they are shown in normal type. blue or bold depending on the choice made in the Preferences dialog. the preceding table value by the value provided in the box. The Apply button will change the Parametric table as specified but control will remain in the Alter Table Values dialog window so that additional changes can be made. See the Store Parametric Table command below for details. The OK button accepts and finalizes all of the changes made to the Parametric table. either directly or through the Alter Values command.Menu Commands Chapter 3 controls the manner in which successive values in the table are generated. However. The Retrieve Parametric Table is provided to allow Parametric Tables saved in older versions of EES to be opened and to allow Parametric Tables from one EES file to be ported to another EES file. has a . These values are automatically entered in the table with the Solve Table and Min/Max Table commands. respectively. The numerical values entered in a table. The choices are Last Value. so it should no longer necessary to Store and Retrieve Parametric Tables. Dependent variables are shown in italic. otherwise an error message will be displayed.PAR file and restore the Parametric table to the same condition it was in when the Store Parametric Table command was issued. EES now allows an unlimited number of Parametric Tables to be defined. Store Parametric Table saves the current Parametric Table to a binary disk file which. identify independent variables in the equation set. Independent variables are fixed to a constant for each run. Also. and Multiplier. All information related to the Parametric Table is saved. If a value is set in a table. If Last Value is selected (as shown) the increment will be selected such that the last run has the specified value.PAR filename extension. just as if there were an equation in the Equations window setting the variable to the constant. it must not also be set in the Equations window. There are other ways of changing the data in the Parametric table. by default. The file can later be read to recreate the table with the Retrieve Parametric Table command. Insert/Delete Runs allows the number of runs in an existing Parametric Table to be changed by inserting or deleting one or more rows in a specified Parametric table at a specified 101 . Retrieve Parametric Table will read a specified . you can simply type the values directly into the Parametric Table. Increment or Multiplier result in successive values in the table being determined by either adding or multiplying. Clicking on the control at the upper right of each column header cell (or selecting Alter Values from the popup menu that appears when the right-mouse is clicked in the header cell) will bring up a dialog window which operates just like the Alter Values dialog. The list on the right shows the variables which currently appear in the Parametric Table. Insert/Delete Variables allows variables in an existing Parametric Table to be added or removed. Variables that may be added to the table appear in the list on the left. To add one or more variables to the table. Variables can also be added or deleted from the Parametric Table by clicking the right mouse button in the column header cell following by selecting Insert Column or Delete Column from the popup menu that appears. The following dialog window will appear. Rows in the Parametric Table can also be inserted or deleted by clicking the right mouse button in the first column of the table and selecting Insert Row or Delete Row from the popup menu. Click the Add button to move the highlighted variable names to the list on the right. (You can also add a variable by double-clicking on the variable name.) Variables can be deleted from the table by selecting them from the list on the right. followed by clicking on the Remove button.Chapter 3 Menu Commands position. 102 . click on the variable name(s) causing them to be highlighted. . Each file format has advantages and disadvantages. ASCII Lookup files usually have a .CSV filename extension) and the Lookup Files stored in disk files can also be accessed by the Interpolate. differentiated. A name derived from the filename is given to the Lookup Table and this name appears on the tab at the top of the Lookup Table Window.LKT. for details. and LookupRow commands. . Using Lookup Files and the Lookup Table. The binary form is read in more quickly and it requires smaller file sizes. after a confirmation. Lookup. Interpolate. and LookupCol functions described in Chapter 4. New Lookup creates a table with the specified number of rows and columns in which tabular numerical or string data may be entered. Open Lookup will read into the Lookup Table Window a Lookup file which was previously stored with the Save Lookup command or as a text file.CSV filename extension. Differentiate. The order of the variables in this list can be changed by pressing and holding the left mouse button on a variable name while sliding it up or down to a new position in the list. A name and display format for each column of data may also be stored. EES recognizes both binary and ASCII forms for Lookup files. Differentiate. Save Lookup copies the data in the Lookup Window into a Lookup file.LKT filename extension. delete the Parametric Table and recover the memory it required. The ASCII form is easier to edit and it can be written by spreadsheet or other applications. Lookup. Binary files are identified with a . Lookup files can be accessed by the Differentiate. The Lookup file can be later read with the Open 103 .Menu Commands Chapter 3 Variables will appear in columns of the Parametric Table in the same order as they appear in the list on the right. A name must be provided for the Lookup Table. or . See Chapter 4. LookupCol. The tabular data may be automatically interpolated. In addition.CSV filename extensions.TXT. The column order of an existing Parametric table can also be changed by clicking on the column header cell as described in Chapter 2. LookupRow.TXT or. A Lookup file is a two-dimensional table of data that has been stored in a disk file. and used in the solution of the problem using the Interpolate.LKT filename extension or as an ASCII file with a . data in the Lookup Window may be saved in a Lookup File (with a . depending on the file format. This is the name that must be used with commands that use the Lookup Table. There is no limit (other than available memory) on the number of Lookup Tables that may appear in the Lookup Table Window. Delete Parametric Table will. and LookupCol functions. The name will appear on a tab at the top of the Lookup Table Window. Lookup tables and files provide a great deal of power to EES by allowing any functional relationship between variables which can be represented by tabular information to be entered and used in the solution of the equations. LookupRow.TXT or . Lookup. Lookup files can be stored either as a binary file with the . Lookup. Rows and columns can also be inserted by clicking the right mouse button in the header column (for rows) or header row (for columns) followed by selection of Insert or Delete from the table popup menu. Using Lookup Files and the Lookup Table. Differentiate.Chapter 3 Menu Commands Lookup Table command or used directly from the disk with the Interpolate. Insert/Delete Lookup Rows and Insert/Delete Lookup Cols allows one or more rows or columns to be inserted or deleted at a specified position in an existing Lookup Table. for more information relating to Lookup tables and files. The information in the Lookup Table Window is also stored with the problem information when the Save or Save As commands are given. There is no Undo for this operation. See Chapter 4. LookupRow. and LookupCol functions. Delete Lookup will delete one or more selected Lookup Tables from the Lookup Table Window and recover the memory it required. 104 . The independent variable(s) are selected by clicking on the names in the right list. A removed term is displayed within a crossed-out red box as shown above. The order of the polynomial is set between 0 and 6 by clicking on the 'spin button' up or down arrows. You may exclude some terms from the regression by clicking on the term. Click the Exclude button to remove the term from further consideration. Note that the Curve Fit command in the Plot menu also provides regression capability but only for one independent variable. Lookup. Select the table you wish to operate on from the drop down lists at the upper right and the starting and stopping rows in that table. Specify the dependent variable by clicking on the variable name in the list on the left. If you later wish to include an 105 . If the cross-terms box is selected then terms involving the product of the independent variables will be included in the correlation. or Arrays tables. With the Linear Regression command. This action will display a box around the selected term and enable the Exclude button. a representation of the equation to be fit is displayed in the box at the bottom as shown above. click it a second time. The dialog window shown below appears after the command is chosen. The dependent variable will be represented as a linear polynomial function of the independent variables. To de-select an item. the data in any column can be regressed as a function of the data in up to 6 other columns.Menu Commands Chapter 3 Linear Regression provides regression capability for the data in the Parametric. As any information relating to the equation form is entered. Clicking the Stats button will provide a table listing all of the coefficients. You can then paste this equation into the EES Equations window or into any other application that accepts text. the Fit button in the Linear Regression dialog window will be changed to Copy and the Cancel button will changed to Done. Note. click the Fit button. click on it. The Exclude button will then be titled Include. The Copy button will first copy the fitted equation to the clipboard.Chapter 3 Menu Commands excluded term. their associated standard errors. and other statistics such as the root-meansquare (rms) error. Either button will dismiss the dialog window. The Stats button will been enabled. The coefficients can be copied to the clipboard by checking the Copy to clipboard box. that the Copy process will overwrite any other information in the clipboard. as shown below. the bias error. however. and the R2 value. such as the coefficients copied from the Linear Regression Coefficients dialog window. Coefficients which have been excluded will be represented in the table with stars. the fitted equation will appear in the display box. After a successful fitting process. If the fitting process is successful. 106 . When the form of the equation is that which you want to fit. Click the Include button. Each plot created with this command is placed in a separate window of the Plot Window. Arrays. All plot windows are saved with other program file information when the Save or Save As commands are applied. bar. All of the information provided in this dialog window can later be changed using Modify Axes and Modify Plot commands and the Plot Window controls described in Chapter 2. or contour plot involving one or more variables defined in the Parametric. Once created. X-Y and Bar Plots 107 . Lookup. or Integrals Tables as a function of any other variable in that table.Menu Commands Chapter 3 The Plot Menu New Plot Window will display a child menu to generate an X-Y. the plots can be modified or copied using the Plot Window controls. Use the Overlay Plot command if you wish to plot in an existing plot window. Each plot window can have of plot overlays that are created with the Overlay Plot command. The information needed to produce the plot is specified in the New Plot Window dialog. There is no intrinsic limit on the allowable number of plot windows. the minimum and maximum axis values. The number in the second field is the number of decimal places (for fixed notation) or significant figures (for exponential notation). The plot may be formatted in a variety of ways. respectively. F and E format the numbers with a fixed number of decimal places or exponential notation. and the interval when a variable is selected. The variables to be plotted on the X and Y axes are selected from the lists by clicking on their names. while clicking on a selected variable unselects it. One or more Y-axis variables can be selected. The two fields to the right of the word Format contain pop-up menus that control the format of the numbers appearing in the scale for each axis. The number of grid lines and scale numbers is determined by the specified interval value. This name will appear on the tab at the top of the Plot Window. The 108 . All of these axis formatting variables may be changed. A separate plot line will be generated for each selected Y-axis variable. Clicking on an unselected variable name selects that variable. All selected variables will be plotted with the same axis scale. first select the table from which you wish to plot using the drop-down list controls at the upper right of the window. The name can later be changed by right-clicking on the tab. using the scroll bar or up/down arrow keys. Click on the desired line type or make a selection with the up and down arrow keys. Grid lines will be drawn if the ‘Grid Lines’ checkbox control is selected.Chapter 3 Menu Commands To create an X-Y or bar plot. if necessary to bring the variable names into view. Clicking the spin box arrows to the right side of the Line list box toggles the display through a list of the available line types. Enter a name for the plot in the edit box at the top of the dialog. EES will automatically select appropriate values for the number of display digits. rather than the data which existed when the plot was first drawn.Menu Commands Chapter 3 plot symbol and line color are chosen in a similar manner. Contour Plots 109 . the symbol and color list boxes will display 'auto'. The “Show error bars” control is accessible only if one or both of the variables selected for plotting have associated uncertainty values specified with the Uncertainty Propagation Table commands. The Data button allows the number of rows and the X and Y axis variables to be viewed or changed. If the ‘Add legend item’ is selected. the symbol and color for each plot line will be automatically selected by EES so that each plot line has a different symbol and color. The X and Y error bars can be individually controlled with the Modify Plot command. changed. The legend item text can be moved. preceded by the line and symbol type used for the plot. If more than one Y-axis variable is selected. This feature can be overridden by simply selecting the symbol and color. the plot will be generated using the current data in the Parametric Table. The plot will be updated as the data in the table are changed. a text item having the name of the Y-axis variable will be placed at the upper left corner of the plot. error bars are generated in both the X and Y directions. By default. The ‘Spline fit’ control will provide a spline-fit curve through the plotted points. as described in the Plot Window section of Chapter 2. With the 'auto' option. When the ‘Automatic update’ control is selected. or deleted just as any plot window text item. the selected data are first scaled and then fitted to a function of the form Z x . the selected data must be interpolated or extrapolated as necessary to provide values of the contour variable Z over the entire range of X and Y at relatively fine intervals. A number of methods were investigated for this task. This parameter can significantly change the appearance of the contour plot. The X and Y axis scaling is. EES will assume the column numbers in the table are proportional to the X-coordinate and the rows are proportional to the Y-coordinate. but it can be changed to provide scaling. A contour plot requires three-dimensional data for construction. Controls are provided to allow a subset of rows and/or columns in the table to be plotted. by default. The default value of 1 seems to work well in most problems. The relative (scaled) value of s is chosen with the Smoothing slider which has a range between 0 and 5. Y. The X.Chapter 3 Menu Commands The Contour Plot option generates lines or color bands indicating the path of a fixed value of the contour variable (Z) in X-Y space. set to the number of columns and rows in the table. EES will expect that three dimensional data to be provided in three columns from one of the table windows. and s is a relative smoothing parameter. Larger values of s cause the contour lines to be more damped. To prepare the contour plot. particularly in regions in which extrapolation is necessary. the w values are weighting factors. If the 3-column data radio button is selected. and Z variables are then selected from the three lists. If the 2-D table data radio button is selected. Lookup or Arrays table windows. The method which was found to be most successful is the multiquadric radial basis function. 110 . y = ∑ wi j =1 b g N d x − xi + d y − yi + σ 2 2 j j 2 where N is the number of data points. With this approach. The data may be provided in either of two ways from the Parametric. The Z-values will be read from the table. You may need to experiment with different values of this parameter to produce a satisfactory plot. This command can also be invoked by double-clicking the mouse button within the plot rectangle. whereas the color band plot is simply one plot. The plots appear in this list in the order in which they were generated. Each isometric line is a separate plot overlay. Overlay Plot allows a new plot curve to be drawn over existing plots. Even so. A maximum of 25 isometric lines and 250 colors is allowed. Controls are provided to create or select an existing top x-axis or right y-axis. on a color band contour plot. There is a practical upper limit to the number of points that can be fit and this upper limit is controlled by the Resolution slider. A (Y2) following a variable name indicates that it is plotted using the right Y-axis. These text items can be moved or changed just as any other Plot window text items. Similarly (X2) indicates that the plot uses the X-axis at the top of the plot. The contour plot may be produced using isometric lines or color bands representing constant values of Z. An X-Y or bar plot can be overlayed on the contour plot using the Overlay Plot command.Menu Commands Chapter 3 The weights are found by linear least square fitting. The resulting plot can be quite pretty. If more data points are provided than are specified by the Resolution slider. but the time required to display the plot will increase with the number of colors. a color legend will be displayed to the right of the plot relating colors to the values of Z. If a banded color plot is chosen. The X-axis and Y-axis scales 111 . depending on the number of data points provided and the speed of your computer. EES will generate a text item containing the value for each contour line and place it on the line. Note that. the contour plot algorithm involves extensive calculations and you may have to wait a while for the plot to be prepared. A Label Contours check box control is provided for isometric contour plots. The number of lines or bands is determined as the difference between the maximum and minimum values divided by the interval value. EES will select a subset of the data using a clustering algorithm. In this case. Modify Plot allows the characteristics of existing plot curves to be changed by manipulation of information in the following dialog window. you can read the value of Z directly in the Plot Window title bar at any X-Y position by holding the Ctrl key down and moving the mouse. Note that selecting a large number of colors (>100) results in a plot that has nearly continuous colors ranging from blue (low values) to red (high values). The use of this command is identical to that for the New Plot command described above except that it does not first clear the Plot window. If the Include Legend check box is selected. The plot for which changes are to be made is selected from the list at the upper left. The range of the Resolution slider is 100 to 1024. an Include Legend check box is provided. The line type. This command can also be invoked by double-clicking the mouse on the axis scale for which changes are to be made. The dialog window shown below will appear. Legend text for the plot is also deleted. 112 . A single plot curve may be selectively deleted (leaving all other plots intact) using the Delete button. symbol. Modify Axes allows the appearance of the axes of an existing plot to be changed. The plot window will immediately show any changes. the size and characteristics of the plot border and the grid lines. The axis scales can be changed by clicking on these buttons. The ‘Spline fit’ and ‘Automatic update’ options may be changed. The Delete Plot Window command described below will delete an entire plot window. Click the Apply button after changing the plot line characteristics and before selected another plot. symbol size.) Controls are provided to change the plot window title. and color of the plot curve can be changed using the drop-down lists at the lower left. including all overlays. The axis for which changes are to be made is selected with the radio-button controls at the upper left. symbol frequency.Chapter 3 Menu Commands employed for the selected plot are indicated with the radio buttons at the lower left of the dialog. (See the New Plot Window command for a description of these options. The toolbar is ordinarily displayed when the plot window is created. this command will have a Hide Toolbar caption and if selected.Menu Commands Chapter 3 The current minimum. However. the #Ticks/Division toggles to #Grids/Division if you click on this control. These fields will be hidden if the Show Scale checkbox is not selected. Grids/Division to a value greater than 0. The Cancel button will restore the plot to the condition it was in before this command was issued. The #Ticks/Division is the number of minor tick marks in each interval. The display format. font size. and interval values for the selected axis are shown. font style. It can be hidden by clicking in the small box with the cross at the upper right of the toolbar. The Show Toolbar command displays the toolbar if it was previously hidden. in which case a scale will not be drawn. Clicking the Apply button applies the changes so that they can be viewed in the Plot window. Note that the 2nd axis scales (initially located at the top of the plot for the X axis and to the right of the plot for the Y-axis) can be moved to other locations by holding the Ctrl key down while pressing the arrow keys. The OK button accepts the changes and exits the dialog. it will hide the 113 . If selected. and color of the scale numbers can be changed using the drop-down menus appearing on the right of the dialog window. The up/down arrows control the position of the X2 scale and the left/right arrows control the position of the Y2 scale. scaled with the new values. font. Show/Hide Toolbar controls the visibility of the tool bar that is provided with each plot window to add new text or drawing items to the plot window or to manipulate these items. Grid lines can be placed at positions between the major ticks by setting the No. These values can be changed and the plot will be redrawn. Grid lines are normally placed at each major tick mark. If the toolbar is visible. maximum. click on the check box preceding the value. 114 . the plot characteristics and axis scales can be modified in the usual manner with the Modify Axes and Modify Plot commands.Chapter 3 Menu Commands toolbar. Property Plot creates a new plot window with thermodynamic property data for a selected substance. The general rule is that the substance is modeled as a real fluid if its name is spelled out (e. Air is the exception to this rule. Use the Delete button in the Modify Plot dialog window if you wish to delete only one of several overlayed plots.g..g.. The AIRH2O substance provides a field in which the total pressure can be specified. Oxygen) and as an ideal gas if its name is a chemical formula (e. additional property data or thermodynamic cycle state points can be superimposed on the plot using the Overlay Plot command. Once created. If you do not wish to display this line. Also. add ellipses and to align selected items. The toolbar contains buttons to add text. Delete Plot Window will delete the entire contents of the selected Plot Window. The substance type (real fluid or ideal gas) is shown above the list. Controls are provided to allow specification of up to six isobars. Suggested values are provided. For all substances except AIRH2O (psychrometric air-water mixtures). isotherms or isentropes. add lines. there are buttons to allow specification of the axes for the property plot. O2). add rectangles. A line with the value shown in a box will be superimposed on the plot. Select the substance from the list at the left. or the Arrays Table with the New Plot or Overlay Plot commands. Note that data can be plotted from the Parametric Table. The Linear Regression command in the table menu allows a variable to be fitted with as many as 6 independent variables. Chose the data to be fitted from the list of plots at the left. 115 . (The Curve fit dialog provides a fit with a single independent variable. A sample of the equation form will appear in blue in the box at the bottom of the dialog window.) The dialog window shown below will appear. The first four buttons correspond to commonly used equation forms for which linear least squares can be used to determine the unknown coefficients. You will prompted to supply guess values and bounds for the unknown parameters. Select the form of the curve fit by clicking the appropriate radio button.Menu Commands Chapter 3 Curve Fit will find the best fit of a smooth curve through a previously plotted set of data points using unweighted least squares. The equation you enter may be linear or non-linear in the unknown parameters. The Enter/edit equation button allows you to enter any equation form or to edit a previously entered equation. the Lookup Table. bias is the bias error of the fit. 116 . Std. A Stats button will appear.Chapter 3 Menu Commands Click the Fit button (or press the Enter key). a legend containing the equation will be created and displayed on the plot. Error is the standard error of the curve-fitted parameter value. If the Plot Legend check box is selected. The fitted equation will be displayed in the box at the bottom of the dialog window. Clicking the Stats button will display the following statistical information relating to the curve fit. The Fit button will now have changed into the Plot button. R^2 is the ratio of the sum of squares due to regression to the sum of square about the mean of the data. rms is the root mean square error of the fit. The curve fit equation will be copied to the clipboard if the To Clipboard checkbox is selected when either the Plot or Cancel button is selected. Click the Plot button if you wish to have the curve fit equation overlayed on your plot. the name of the Solution window will be changed to Last Iteration Values and the values of the variables at the last iteration will be displayed in the Solution window. and Residual windows. the residuals for the last iteration will be displayed in the Residuals window. This title is entered when the plot is first created. The title can be modified by right-clicking on the tab or by entering the modified title in the Modify Plot dialog. The graphics in any of the plot windows can be copied to the Clipboard by selecting Copy from the Edit menu. 117 . Any change made to the Equations window will remove these windows from the screen if the Hide Solution after Change Option in the Preferences dialog (Options tab) is selected. The tab position can be modified by right-clicking on the tab. If EES is unable to solve the equation set and terminates with an error. Plot Windows will bring the Plot Window to the front of all other windows. Each plot is identified by a title that appears on the tab displayed at the top of the Plot Window. Arrays and Residuals cause the Solution. Solution. Arrays. Formatted Equations first checks the syntax of the equations and then brings the Formatted Equations window to the front displaying the contents of the Equations window in mathematical format. to be moved to the front of all other windows. These windows are normally viewed after the Solve. Min/Max. There is no limit (other than memory limitations) to the number of plot windows that can be created and an unlimited number of overlayed plots may be drawn in each plot window using the Overlay Plot command.Menu Commands Chapter 3 The Windows Menu Equations causes the Equations window to become the active window by bringing it to the front of all other windows and making it visible if it were hidden previously. The menu item will be grayed if no plots have been created. or Uncertainty Propagation command has been successfully completed. respectively. This window is available only after the Solve command is attempted with the number of equations not equal to the number of variables. the Diagram Window menu option will display a ‘fly-out’ menu listing all of the Diagram and child Diagram windows. If one or more child Diagram Windows have been created. Cascade arranges the currently visible windows so that the title bar of each is shown. Any change made to the Equations window will clear the Debug window and disable this menu item. A diagram can be entered into EES from a drawing program or it can be created in EES using the Diagram Window drawing tools. Debug Window will generally be disabled.Chapter 3 Menu Commands Parametric Table and Lookup Table bring the Parametric and Lookup Table windows. In this case. There may be one or more tables in each of these window. Tile arranges all open windows to fill the screen so that a portion of each can be viewed. 118 . The Parametric and Lookup Table windows may be hidden by choosing close from the Windows control menu or by pressing Ctrl-F4. Diagram Window will bring the Diagram Window or a child Diagram Window to the front of all other windows. Click on the tab at the top of the window to access the desired table. an option is presented to display the Debug Window and this menu item becomes enabled. to the front of all other windows and make it the active window. respectively. Menu Commands Chapter 3 The Help Menu Help Index will activate the Help processor which provides specific information on the use of EES.pdf must be in the same folder as the EES application. The Help processor will open to the EES Information index which lists the subjects for which help is available. The online help provides most of the information contained in this manual. EES Manual (Acrobat) will start Abode Acrobat and display the electronic version of this manual which is in file ees_manual. About EES will bring up the EES header window. Help can also be accessed by pressing the F1 key which will bring up help information specific to the window or dialog which is foremost. The Help menu may also contain a menu item to provide specific help for a problem that has been accessed with the Textbook menu. 119 . This information will be needed in any correspondence with F-Chart Software. This window registration information and indicates the version of your EES program. The program developers can be contacted by e-mail through the web site. Note that ees_manual.pdf. f-Chart web site will open your default browser program and set the URL to the f-Chart web site. The f-Chart web site has a “goodies’ section with free examples and support programs for EES. as described in the next section. Using Help shows information provided by the Windows Help processor on how to use the features in the Help program. Clicking on the subject opens the Help window to information for that subject. EES | HelpFile5. as shown above. it creates the Textbook menu at the far right of the menu bar.BMP The first line in the file is the menu title.BMP NO.HLP | >Your menu item 2 Descriptive problem name4 | FileName4. 120 . etc | FileName1.TXB). EES currently ignores this line but a 1 should be provided. The following three lines provide information about the textbook or problem set.HLP | NO. This title is the name of the menu which will appear in the menu bar to the right of the Help menu.HLP | Descriptive problem name6 | FileName6. The menu shown above was created with the following textbook index file.EES | HelpFile1.BMP NO. Your Menu Here 1 Textbook information line 1 Textbook information line 2 Textbook information line 3 Reserved >Your menu item 1 Descriptive problem name1 | FileName1. The format of the textbook index file is quite simple. A fourth line containing the word "reserved" is provided for possible future use.Chapter 3 Menu Commands The Textbook Menu The Textbook menu is a user-defined menu that is designed to allow easy access to EES files.BMP NO. A textbook index file is an ASCII file identified with the filename extension (.EES | NO. but it must be provided. and thus its name.HLP | Descriptive problem name3 | FileName3.EES | HelpFile4.HLP | Descriptive problem name5 | FileName5. The following line is a version number used internally by EES. as shown.EES | HelpFile1.BMP NO.EES | HelpFile2. etc.BMP >Your menu item 3.EES | HelpFile3. This menu can be created either by opening a textbook index file with the Load Textbook command (File Menu) or by placing the textbook index file in the USERLIB subdirectory. The following lines contain a menu item name (preceded by an identifying > character) and then one or more problem descriptions. It has been used to provide a convenient means to access EES problems associated with a textbook. This information will be displayed whenever any menu item is selected from the Textbook menu.HLP | Descriptive problem name2 | FileName2. EES currently ignores the information on this line. When EES reads a textbook index file. The menu item name is the name that will appear in the Textbook menu list.BMP NO.HLP | NO. The help file can be an ASCII text file. If no help file is available. but a figure name must be provided. The final item is the filename for a figure associated with the problem.HTM filename extension. The textbook index file should be placed in the same location (i. However. can be accessed from an additional menu item that is placed in the Help menu.Menu Commands Chapter 3 Each problem description line contains four pieces of information. the help files have a . subdirectory. C:\myBook\Chapter1\Problem1. directory information is not necessary and it should not be included. which may be up to 128 characters.e. This filename may be partially or fully qualified with directory information.HLP or . e. separated by a | character. The third item is an optional help file which is to be associated with this file. The first item is a descriptive name for the problem. a dialog window will appear showing a list of the descriptive names of the problems for that menu item. enter NO.g. EES does not currently use the figure. if provided. or an HTML file readable by a browser program. By convention. Use NO.BMP as a placeholder.. a Windows HLP file produced by a Help formatting program. The help file. in most cases.. or folder) with all of the referenced EES program and help files.HLP for this field. When the user selects a command from the Textbook menu. 121 . The user can then select a name from the list and the file associated with that problem will be opened.EES. The second item is the filename for the EES program file. floppy disk. 122 . Thermodynamic and transport properties of steam.) All of the functions (except pi and tableRun#) require one or more arguments which must be enclosed in parentheses and separated with commas.. All three functions return the angle in the correct quadrant of the complex plane. The argument may be a numerical value. angle(X). abs(X) returns the absolute value of the argument. Note that the Angle functions are used to extract the angle of a complex number variable or expression but they cannot be used for assigning the angle of a complex number. angleDeg(X) and angleRad(X) all return the angle (also called amplitude or argument) of complex variable X. R22. error functions. The first two sections of this chapter provide reference information for the built–in mathematical and thermophysical functions. (The functions which operate on the Lookup Table are described in the Using the Lookup Table section at the end of this chapter. carbon dioxide. however. Many of these (e. etc. The third section provides information on the use of the Lookup Table. Built-in Functions Mathematical Functions The mathematical functions built into EES are listed below in alphabetical order. In complex mode. (See also Magnitude(X)). R134a. Angle will return the angle in either degrees or radians depending on the Trig Function setting in the Unit System dialog. hyperbolic. EES also provides a function to convert units and functions that help manipulate complex numbers. For example. this function returns arctan(X_i/X_r). abs returns the magnitude of the complex argument. R407C. Much of the information provided in this chapter can also be obtained from within the program using the Info button in Function Info dialog. a variable name. EES also provides a Lookup Table which allows tabular data to be entered and used in the solution of the equation set. Bessel. the equation Angle(X)=4 will produce an error.CHAPTER 4 __________________________________________________________________________ __________________________________________________________________________ EES has a large library of built-in mathematical functions. is its extensive library of built-in functions for thermophysical properties.g. Representing X as X_r + i*X_i. 123 . The major feature that distinguishes EES from other equation solving programs. and many others are implemented in a manner such that any independent set can be used to determine the remaining unknown properties. AngleDeg will always return the angle in degrees and AngleRad will always return the angle in radians.) are particularly useful for engineering applications. air. ammonia. or an algebraic expression involving values and variables. arcCosh(X) returns the value which has a hyperbolic cosine equal to the value of the argument. 124 . arcSinh(X) returns the value which has a hyperbolic sine equal to the value of the argument. ) will return the average value of the arguments. An array or subset of an array can be provided as an argument list by using array range notation.75≤ X <infinity. bessel_K0(X) returns the value of zeroth-order Modified Bessel function of the second kind for argument value X where 0≤ X <infinity.. arcTanh(X) returns the value which has a hyperbolic tangent equal to the value of the argument.. bessel_K1(X) returns the value of first-order Modified Bessel function of the second kind for argument value X where 0≤ X <infinity. arcSin(X) returns the angle which has a sine equal to the value of the argument. Arg3. X[1. The units of the angle (degrees or radians) will depend on the unit choice made for trigonometric functions with the Unit System command. average(Arg1. Arg2. e.50]. bessel_J0(X) returns the value of zeroth-order Bessel function of the first kind for argument value X where -3≤ X <infinity. The units of the angle (degrees or radians) will depend on the unit choice made for trigonometric functions with the Unit System command.. arcTan(X) returns the angle which has a tangent equal to the value of the argument.75≤ X<infinity. The number of arguments must be between 1 and 1000..Chapter 4 Built-In Functions arcCos(X) returns the angle which has a cosine equal to the value of the argument.g. . bessel_I1(X) returns the value of first-order Modified Bessel function of the first kind for argument value X where -3. bessel_J1(X) returns the value of first-order Bessel function of the first kind for argument value X where -3≤ X <infinity. The units of the angle (degrees or radians) will depend on the unit choice made for trigonometric functions with the Unit System command. bessel_I0(X) returns the value of zeroth-order Modified Bessel function of the first kind for argument value X where -3. i*X_i. such as Btu/hr-ft^2-R. and Rankine (R). ConvertTemp('C'. conj(X) returns the complex conjugate of a complex variable X. or R. If you find that a unit you need is not defined. The third parameter is a temperature in the scale indicated by the first 125 . as in the example below. In a combination of units. a dot (character Alt-250) or division symbols. convert('From'..e. Representing X as X_r + i*X_i. The single quote marks are optional. FI = convert(ft^2. Four scales are supported: Celsius (C). Y=conj(X). T) converts temperatures from one scale to another.. K. F. V=3*cis(20deg) will set the value of complex variable V to have a magnitude of 3 and an angle of 20 degrees. Note the this function returns a complex result. a star. raised to a negative power. The single quotes surrounding the string constants are not required. For example. the individual units are separated with dash (i. kPa) The defined unit symbols can be displayed with the Unit Conversion Info command in the Options menu.e. However.) The ^ symbol is optional so ft2 and ft^2 are equivalent. this function returns X_r . 'To') returns the conversion factor needed to convert units from the unit designation specified in the ‘From’ string to that specified in the ‘To’ string. bessel_Y1(X) returns the value of first-order Bessel function of the second kind for argument value X where 0< X <infinity. you can enter it by editing the UNITS. Kelvin (K). For example.Built-in Functions Chapter 4 bessel_Y0(X) returns the value of zeroth-order Bessel function of the second kind for argument value X where 0< X <infinity. will set the real part of Y (Y_r) to the real part of X and the imaginary part of Y to negative of the imaginary part (Y_i).TXT file in the EES directory. The required units (degrees or radians) of the angle is controlled by the unit choice made for trigonometric functions with the Unit System command. 'F'. Combination of units and multiple unit terms may be entered. you can append deg or rad to the angle to override the Unit System setting. The convert function will accept multiple unit terms if each term is enclosed within parentheses. The first two parameters are string constants or string variables which must be C. Both upper and lower case letters are permitted. The EES equation. All units to the right of the division symbol are assumed to be in the denominator (i. Farenheit (F). P =15* Convert((lbm/ft3)*(ft)/(s^2/ft). cis(X) is a complex mode function that returns cos(X)+i*sin(X). in^2) will set FI to a value of 144 because 1 square foot is 144 square inches. Terms are separated with an optional * symbol or with a / symbol. Only one division symbol may be used in any one term. regardless of the Unit System setting. minus). It is preferable to use the if then else. you can enter X_i=4. the equation Imag(X)=4 will produce an error. Stop. differentiate('Filename'. i. imag(X) returns the imaginary part of a complex variable X. if A=B. if A>B. and Step are not provided. The Imag function cannot be used for assigning the imaginary part of a complex number. If A<B. and (optionally) Step are 126 . if (A. 'ColName2'. B. cos(X) will return the cosine of the angle provided as the argument.. VarName must be a legal variable name which has values defined in one of the columns of the Parametric table and Integrand can be a variable or any algebraic expression involving VarName and other variables or values. Instead you should just enter X=4*i which will set X to 0 + 4*i.Chapter 4 Built-In Functions parameter. In this case. Representing X as X_r + i*X_i. If you wish to only set the imaginary part of X. ColName2=Value) returns the derivative determined from two columns of tabular data based on cubic interpolation. Start. exp(X) will return the value e raised to the power of the argument X. If Start. repeat until and goto statements in a function or procedure for conditional assignments.e. Z) allows conditional assignment statements in the Equations window. VarName. Step) returns the integral of the expression represented by Integrand with respect to the variable VarName. The function returns the temperature in the scale indicated by the second parameter. Stop. the integral function is used only in conjunction with the Parametric Table. cosh(X) will return the hyperbolic cosine of the value provided as the argument. If the values of Start. the function will return the value of Z.0 integral(Integrand. For example. use of the if function may cause numerical oscillation. The required units (degrees or radians) of the angle is controlled by the unit choice made for trigonometric functions with the Unit System command. Example: TF=convertTemp('C'. VarName) or integral(Integrand. See Chapter 5 for additional information. this function returns X_i. X. 'ColName1'. erf(X) returns the Gaussian Error function of X. Stop. 100) sets TF to 212. There are two basic forms of the integral function which differ in their reliance on the Parametric table. ∫(Integrand) d(VarName). 'F'. See the Using Lookup files and the Lookup Table section of this chapter for more information and examples. In some problems. erfc(X) returns the complement of the Gaussian Error function of X which is 1-erf(X). Y. the function will return a value equal to the value supplied for X. the function will return the value of Y. ColName2=Value) provides the same function as the interpolate command except that it uses quadratic interpolation. Values of X corresponding to values of t that are not included in the integration range may not be properly defined. a Lookup file (if filename is provided). See the Using Lookup files and the Lookup Table section of this chapter for more information and examples. Interpolation between rows is not allowed. or the Parametric table using cubic interpolation. Row. ColName2=Value) returns an interpolated or extrapolated value from tabular data in the Lookup table. 'ColName1'. If Step is not provided. integralValue(t.’X’) returns a value from the Integral Table that is created using the $IntegralTable directive. 'ColName2'. 'ColName1'. As in the lookup function the. In that sense. the IntegralValue function is similar to the TableValue function which retrieves data from the Parametric Table and the Lookup and Interpolate functions which retrieve data from the Lookup Table window or Lookup files. lookup$ function operates just like the lookup function except that it returns a string rather than a numerical value. 'ColName2'. See Chapter 7 for additional information. interpolate('Filename'. This row value should be an integer. 'ColName2'. lookup(‘Filename’. X is the name of a variable that has been included in the Integral Table. EES will internally chose a step size using an automatic stepsize adjustment algorithm. 'ColName1'. interpolate2('Filename'. setting the value of VarName to values between Start and Stop as appropriate. as it is in the lookup function. interpolate1('Filename'.Built-in Functions Chapter 4 provided. Filename is optional. The integral function can be used to solve initial value differential equations. lookup$ function can have two or three arguments. the first is a string that provides the name of a Lookup table stored on disk. ColName2=Value) provides the same function as the interpolate command except that it uses linear interpolation. The next argument is a numerical value or expression that provides the row in the table. EES will numerically integrate all equations involving variable VarName. See Using Lookup files and the Lookup Table section of this chapter for more information and examples. The column can be indicated by a numerical value or expression which provides the column number or by the name of the column provided in a string constant or 127 . (The single quotes around the variable name are optional.) The value provided for t must be less than or equal to the current value of the independent integration variable. t is the value of the independent integration variable for which the value of X is to be returned. If three arguments are provided. The final parameter indicates the column. Column) returns the value in the Lookup Table or Lookup file at the specified row and column. An older format which is still accepted is to supply the column title preceded with the # symbol. In complex mode. it may be entered by providing the column name as a string constant or a string variable. See the Using Lookup files and the Lookup Table section of this chapter for more information and examples. The magnitude function cannot be used for assigning the magnitude of a complex number. 128 . In order to accept string information. log10(X) will return the base 10 logarithm of the argument. For example. Interpolation between rows will be provided as needed. In order to accept string information. magnitude(X) returns the magnitude (also called modulus or absolute value) of a complex variable X. Alternatively. this function returns sqrt(X_r^2+X_i^2). lookupCol(‘Filename’. The function returns the row in the table in which this string exists. Value) uses the data in the specified column of the Lookup Table or Lookup file to determine the row which corresponds to the value supplied as the second argument. lookupRow(‘Filename’. ln(X) will return the natural logarithm of the argument. Filename is optional. Filename is optional. First. See the Using Lookup files and the Lookup Table section of this chapter for more information and examples. The function will return the row in the Lookup Table corresponding to the value supplied as the second argument. As in the LookupRowfunction the. Representing X as X_r + i*X_i. the format style of the column in the Lookup table must be set to STRING. To change the format style. the format style of the column in the Lookup table must be set to STRING. The final argument is a string constant or string variable holding the string that will be searched in the table. If three arguments are provided. the first is a string that provides the name of a Lookup table stored on disk.Chapter 4 Built-In Functions string variable. Col. click in the column header and make the change in the Format Table dialog window. click in the column header and make the change in the Format Table dialog window. Note. Value) uses the data in the specified row of the Lookup Table or Lookup file to determine the column which corresponds to the value supplied as the second argument. the abs function also returns the magnitude. Row. it may be entered as an integer value. Lookup$Row function can have two or three arguments. To change the format style. The next argument is the column in the table. The column may be indicated in several ways. the equation magnitude(X)=4 will produce an error. Lookup$Row operates just like the LookupRowfunction except that it its final argument is a string rather than a value. The row value returned will not necessarily be an integer. . you can enter X_r=4. Instead you should just enter X=4 which will set X to 4 + i*0. the function returns zero. This function can be used only within EES Functions and Procedures round(X) will return a value equal to the nearest integer value of the argument. 129 . Series_info provides the name of the product index variable and the lower and upper limits which must be integers or variables which have been previously set to integer values. X3. If you wish to only set the real part of variable X. 'Arrays'. the function call will result in an error message. ntableruns(‘name’) takes one string argument which must be 'Parametric'. Arg can be any algebraic expression. 'Lookup'. j=1. product (j. The function returns the number of rows in the specified table. real(X) returns the real part of a complex variable X. …) will return the value of the largest of its arguments. Series_info) returns the product of a series of terms. e.4) will return 1*2*3*4 or 24. The number of arguments must be greater or equal to 1. random(A. For example. The function returns the number of rows in the specified table. which is 4 factorial. The number of arguments must be greater or equal to 1. If the specified table does not exist. nLookupRows(‘name’) takes one argument which must be either a string constant or a stringvariable. For example. X2. j=1.B) returns a uniformly distributed number in the range between A and B. Example: n=nlookuprows('LOOKUP 1') "number of rows in the Lookup Table1" pi is a reserved variable name which has the value of 3. or the name of a Lookup file stored on disk.g. Representing X as X_r + i*X_i. the product of the square of all 10 elements in the vector X can be obtained as product (X[j]*X[j]. The product function is most useful when used with array variables.10). product(Arg. the name may be provided as a string constant or string variable. In this last case. this function returns X_r. X3. The string contains the name of a Lookup table (as in appears on a tab in the Lookup TableWindow) or the name of a Lookup file stored on disk. X2. X[j]. the equation real(X)=4 will produce an error. Example: n=ntableruns('LOOKUP') “returns the number of rows in the Lookup Table.Built-in Functions Chapter 4 max(X1. …) will return the value of the smallest of its arguments. min(X1. If the specified table does not exist.1415927. The real cannot be used for assigning the real part of a complex number. . tableName$ returns the name of Parametric Table that is currently being used in the calculations. The step and if functions are provided to maintain compatibility with earlier versions. Parametric table names are seen on the tabs at the top of the Parametric Table Window. sum(j. The function is best explained by examples. ‘VariableName’) returns the value stored in a specified row and column of the Parametric Table.ArgN) returns the sum of the arguments. The step function can be used to provide conditional assignments. sum(Arg1..e. The column number may be either 130 .10). The sum function is most useful when used with array variables. e. the current row in the Parametric Table or zero. the scalar product of two vectors. The required units (degrees or radians) of the angle is controlled by the unit choice made for trigonometric functions with the Unit System command. X[j]. sqrt(X) will return the square root of the value provided as the argument which must be greater than or equal to zero.100]) returns the sum of the 100 elements in the X array. See Chapter 7 for information on how the sum function can be used with array variables to manipulate matrices. Series_info provides the name of the summation index variable and the lower and upper limits. Series_info) returns the sum of a series of terms.g. if the Parametric Table is not being used in the calculations. Array range notation is particularly convenient for the list form. similar to the if function. Arg can be any algebraic expression. tableRun# returns the Parametric Table run number. sinh(X) will return the hyperbolic sine of the value provided as the argument. i. each with 10 elements can be obtained as sum(X[j]*Y[j].. This function should only be used with the Solve Table or Min/Max Table command in the Calculate menu. j=1. There are two forms for the sum function. The name of a Parametric Table can be changed by right-clicking on the tab. EES determines which format is in use by context.. This function has no arguments and it should only be used only when calculations are initiated with the Solve Table or Min/Max Table command in the Calculate menu. step(X) will return a value of 1 if the argument is greater than or equal to zero. X and Y. ΣArg.4) will return 1+2+3+4 or 10. These limits must be integers or variables which have been previously set to integer values. .Chapter 4 Built-In Functions sin(X) will return the sine of the angle provided as the argument. Column) or tableValue(Row.e. otherwise the Step function will return zero. j=1.. Arg2. SUM(X[1. i. Conditional assignments are more easily and clearly implemented with the IF THEN ELSE statement in functions or procedures as described in Chapter 5. sum(Arg. For example. For example. tableValue(Row.. 2*unitsystem('Eng') will set g equal to 1 if the user has selected the SI unit system and g equal to 32. #ABC). As an example. TableValue(6. EES will also accept the #symbol preceding the variable name in place of enclosing it within single quotes. trunc(X) will return a value equal to the integer value corresponding to the argument rounded toward zero.. e. The required units (degrees or radians) of the angle is controlled by the unit choice made for trigonometric functions with the Unit System command. This function takes one argument which must be placed within single quote marks. the following assignment statement in an EES function or procedure. e. 'K'.Built-in Functions Chapter 4 entered directly as an integer number or indirectly by supplying the variable name for the desired column. 'atm'. UnitSystem(‘Unittype’) is a function which allows an EES program to know what unit settings have been selected with the Unit System command.. 'C'.2 if the user has selected the English unit system.g. TableValue(6. 'kPa'. 'F'. The tableValue function is useful in the solution of some 'marching-solution' type problems in which the current value of a variable depends on its value in previous calculations. 'bar'. 'Deg'. 131 . 'psia'. 'Rad'. enclosed by the single quotes. g:=unitsystem('SI') + 32. 7 For compatibility with earlier versions. An error message will be generated if the row or column (or corresponding variable name) does not exist in the Parametric Table or if the referenced cell does not have a value.’ABC’)7. tan(X) will return the tangent of the angle provided as the argument. 'Eng'. 'Molar'. The function returns either 1 (for true) or 0 (for false). and 'R'. Legal arguments are 'SI'. tanh(X) will return the hyperbolic tangent of the value provided as the argument.g. 'Mass'. The StringVal function provides the inverse operation.String$(10+12)) {sets R$ ti 'R22'} StringLen returns the number of characters in the string constant or string variable provided as the argument. The second argument indicates the character position at which the substring starts. Example: T$=concat$('Today is '. This function can be applied with a string variable dropdown list on the Diagram window when it is desired to allow the user to select from a pre-determined set of numerical values. variable. Example: Neat$=COPY$('This is neat'. The function returns a single string that concatenates the two strings. Concat$ accepts two arguments both of which must be either a string constant or a string variable. and the third parameter is the substring length. If the first string is not contained within the second. The function returns a string representing the numerical value of the argument. or expression. The function uses Auto format to set the format of the value before converting it to a string. Example: E$=LowerCase$('EESy') {sets E$ to ‘eesy’} String$ accepts one argument which can be a numerical constant. converting a string to numerical value. It is not necessary to change the case of fluid names or file names as the functions that use this information are case insensitive. You may wish to use the LowerCase$ or UpperCase$ functions. Example: p=StringPos(‘y’. It returns a string in which all letters in the string are converted to lowercase. The function returns the position of the first string within the second. the function returns 0.Chapter 4 Built-In Functions String Functions EES supports both numerical and string variables. The function has no arguments. Example: R$='12345'. Example: R$=CONCAT$('R'. String constants are enclosed in single quote marks. This function is casesensitive.. 255) {sets Neat$ to 'neat'} Date$ returns the current date. The following functions operate on string constants and variables. Fluid$. String variable are identified by a $ as the last character in the variable name. If this length exceeds the length of the string expression. V=StringLen(R$) “V is set to value 5” StringPos accepts two arguments both of which must be either be a string constant or string variable.'22') {R$ will be set to 'R22'} Copy$ creates a string that is a substring of the string expression provided as the first argument. 9. Example: R$=CONCAT$('R'. ‘EESy does it’) {Sets p to 4} 132 .g.DATE$) LowerCase$ accepts one string variable or string constant argument. The format of the date is controlled by the settings in the Regional Options Control Panel of your Windows Operating System. e. it is set to the length of the string expression. It is not necessary to change the case of fluid names or file names as the functions that use this information are case insensitive.TIME$) Uppercase$ accepts one string variable or string constant argument. Example: T$=concat$('The time is now '. It returns a string in which all letters in the string are converted to uppercase. V=StringVal(R$) {Sets V to 22} Time$ returns the current time. Example: E$=UpperCase$('ees') {Sets E$ to 'EES'} 133 . The format of the string returned by this function is controlled by the settings in the Regional Options Control Panel of your Windows Operating System. Example: R$='22'. The function has no arguments. This function provides the inverse operation of the String$ function. This function can be applied with a string variable dropdown list on the Diagram window when it is desired to allow the user to select from a pre-determined set of numerical values.Built-in Functions Chapter 4 StringVal returns the numerical value formed by the characters of a string constant or string variable. This correlation provides accurate results for temperatures between 273. 1987) with modifications to adjust to the International Temperature Scale of 1990.15 K and 1273. The substance names recognized by EES are8: Ideal Gas Air AirH2O + C2H4 C2H6 C3H8 C4H10 CH4 CO CO2 H2 H2O N2 NO2 O2 SO2 Recognized Substance Names for Property Functions Real Gas Ammonia Neon* R141b* Ammonia_ha* Nitrogen* R152a Argon* Propane R290 CarbonMonoxide* Propane_ha* R404A CarbonDioxide* R11 R407C Ethane* R12 R410A Helium* R13 R500 Hydrogen* R14 R502 Isobutane* R22 R507A Methane R22_ha* R600 Methane_ha R23* R600a Mehtanol* R32* R717 * Oxygen R114a R718 n-Butane* R123 R744 n-Hexane* R134a Steam* n-Pentane* R134a_ha* Steam_IAPWS# Steam_NBS* Water + * AirH2O provides psychrometric relations Fluid is represented with a high-accuracy equation of state. The modifications are described by Wagner and Pruss (J. Data.. 134 . Hemisphere Publishing Co. Property data may be added as described in Appendix C. Gallagher. Chem. Phys. 783. Chem. 8 Your version of EES may have additional fluids. and Kell (NBS/NRC Steam Tables. # Steam_IAPWS implements high accuracy thermodynamic properties of water substance with the 1995 Formulation for the Thermodynamic Properties of Ordinary Water Substance for General and Scientific Use.15 K at pressures up to 1000 MPa. This correlation replaced the 1984 formulation of Haar. 1984) which is implemented in substance Steam_NBS. Steam_IAPWS is available only in the Professional version. Data. issued by The International Association for the Properties of Water and Steam (IAPWS).Chapter 4 Built-In Functions Thermophysical Property Functions The first argument of all built-in thermophysical property functions is the name of the substance. Ref. 1993). The new formulation is based on the correlations of Saul and Wagner (J. The formulation allows extrapolation of properties to 5000 K. 16. Phys. 893. 22. Ref. Refer to the online help for the specific publication the describes the equation of state. The Water property correlations assume the fluid is incompressible in the subcooled region. R12. When both the high accuracy and simpler formulations appear for the same fluid. Q_LIBR. this assumption is not accurate for pressures above 350 atm and for states near the critical point. The entropy of these substances is based on the Third Law of Thermodynamics. CO2.. The property keywords Steam and Steam_NBS are treated identically. andR134a_ha. Also provided in the USERLIB subdirectory are the external routines providing thermodynamic property data for lithium bromide-water mixtures (H_LIBR. Either keyword uses property correlations for water substance published by Harr. P_LIBR. X_LIBR)... e. Fluids identified in the above table with * following their name are implemented using a high accuracy equation of state. CH4 etc. Whenever a chemical symbol notation (e. Water and Steam_NBS. both of which are modeled as ideal gases. N2 and Nitrogen. Exceptions to this rule occur for Air and AirH2O. The Steam_IAPWS keyword provides the 1995 Formulation for the Thermodynamic Properties of Ordinary Water Substance for General and Scientific Use which supercedes the formulations provided in Steam_NBS. as described in Appendix C. The JANAF table reference for enthalpy is based on the elements having an enthalpy value of 0 at 298K (537R). ammonia-water mixtures (NH3H2O) and specific heat. N2.g. The property keyword Water provides access to approximate water property functions based on empirical correlations which have been developed for rapid calculations. and Kell (Hemisphere. CO2.) the substance is modeled as a real fluid with subcooled. saturated. Gallagher. These property correlations are accurate over a large range of conditions.. Clicking the Function Info button will provide the documentation. property data for the same fluids may also be implemented using a simpler equation of state that is less accurate near the critical region and in the subcooled regime. It may appear from the above list that some substances. Steam. psychrometrics. T_LIBR. However. and superheated phases. Nitrogen. AirH2O is the notation for air-water vapor mixtures. the substance is modeled as an ideal gas and the enthalpy and entropy values are based on JANAF table references.) is used. V_LIBR. 1984). CarbonDioxide. In some cases. Steam (or Water). Methane. enthalpy and entropy for hundreds of additional substances with JANAF table references (JANAF). i. _ha is appended to the fluid name for the high accuracy formulation.MHE filename extension. etc. Information 135 . H2O. Whenever the substance name is spelled out (e.g. R134a.Built-in Functions Chapter 4 Additional substances may be provided in external files in the USERLIB subdirectory with a user-supplied property file having a . but this is not quite true.e. Documentation for these routines is provided through the Function Info command in the Options menu. they require considerably more computing effort than the Water relations.g. are duplicated. Click the External routines button at the top right and then select the external routine name from the list. Many of the thermodynamic functions can take alternate sets of arguments. In general. P=P1) The latter method is preferable in that the iterative calculations implemented for thermodynamic properties are less likely to have convergence difficulty. EES will display the function name in the format selected for Functions in the Display Options dialog window. but T1 is unknown. as in the examples shown below. For example: h1 = enthalpy(STEAM. the same equation will return the appropriate value of the temperature. are identified by a single case-insensitive letter followed by an equal sign. provided that the substance name is first. The value or algebraic expression representing the value of the argument follows the equal sign. The units. the value of h1 is known. T1 and P1. The letters which are recognized in function arguments and their meaning are as follows: Property Indicators for Use in Thermophysical Functions B D H P R S = Wetbulb Temperature = Dewpoint Temperature = Specific Enthalpy = Pressure = Relative Humidity = Specific Entropy T = Temperature U = Specific Internal Energy V = Specific Volume W = Humidity Ratio X = Quality Arguments must be separated with commas and may be in any order. aside from the substance name. alternatively. the enthalpy function for steam can be accessed with temperature and pressure as arguments. The built-in thermophysical property functions are listed below in alphabetical order. however. All arguments in thermophysical property functions. which depend on the choices made with the Unit System command in the Options menu. The substance name is an EES keyword and it will be displayed in the format selected for Keywords in the Display Options dialog window EES does not require the argument to a function to have a known value. any independent set of arguments can be supplied for thermodynamic functions. If. the same function could be accessed with entropy and quality as arguments. 136 . T=T1. For example. h = h1. Alternatively. the temperature could be found by: T1 = temperature(STEAM. P=P1) will return the value of h1 corresponding to known temperature and pressure.Chapter 4 Built-In Functions concerning the source of the property data and the range of applicability is provided when the Fluid Info button in the Function Info dialog. 5. Btu/hr-ft-R] returns the thermal conductivity of the specified substance. Two independent properties. T=80. respectively. the Conductivity function takes one parameter in addition to the fluid name and this parameter must be temperature. For pure substances which obey the ideal gas law. T=100. T=200) k2 = conductivity (AMMONIA. are also given. P=14. X (for quality) is not allowed. temperature and pressure.7) 137 . h=850. One or more examples. at saturation.3. Two arguments are required for all pure substances.R=0. One of these arguments must be total pressure (P). P=400) d3 = Density (AirH2O. relative humidity (R). pressure and temperature are not independent.. Btu/lb-R. enthalpy (H). kgmole/m3. Examples: k1 = conductivity (AIR. T=300. it is necessary to provide the quality or some other quality-dependent property. three are needed for moist air. For AirH2O (moist air). humidity ratio (W). provided that the state does not consist of two phases. lbmole/ft3] returns the density of a specified substance.5) CP and CV [kJ/kg-K. three arguments are required for the CP function. Example: d1 = Density(AIR. For ideal gas substances. T=350) Cv2 = CV (AMMONIA. any two independent properties can be supplied. lb/ft3. Note also that the specific heat returned for substance AirH2O (psychrometrics) is per unit mass of dry air. wetbulb (B).50) Density [kg/m3. Note that. P=200) k3 = conductivity (STEAM_NBS.7.g. P=14. must both be provided as arguments for substances modeled as real fluids. the specific heat function has temperature as its only other argument in addition to the substance name. Example: Cp1 = CP(AIR. P=30) CP3 = CP(AIRH2O. x=1) k4 = conductivity (AIRH2O. or dewpoint (D).P=101.T=25. the temperature. pressure. kJ/kgmole-K. P=100) d2 = Density (Steam.R=0. T=70. T=100. The specific heat of a two-phase mixture with a quality other than 0 or 1 is infinite and a value cannot be returned for this state.Built-in Functions Chapter 4 are shown in brackets. The remaining two can be any of the following: temperature (T). and humidity ratio (or relative humidity) must be supplied as arguments. R=0. T=100. For AirH2O. showing the allowable formats for the function. For real fluids. Btu/lbmole-R] return the constant pressure and constant volume specific heats of the specified substance. e. If the constant volume specific heat of saturated liquid or vapor is required. Conductivity [W/m-K. . P=14. T=70.Chapter 4 Built-In Functions DewPoint [°F. require a single argument (temperature or enthalpy) whereas real fluid pure substances. STEAM and CARBONDIOXIDE. Btu/lb Btu/lbmole] returns the specific enthalpy of a specified substance. P=300) h3 = enthalpy(AIRH2O.7. in addition to the substance name whereas real fluid substances. Btu/lb-R.g. will always require two independent variables. Three arguments follow the substance name in any order: temperature.5) D3 = dewpoint(AIRH2O. kJ/kgmole-K. the entropy function always requires two arguments.50) Entropy [kJ/kg-K. Example: s1 = entropy(O2. P=14. such as air. P=300) 138 .7. T=70. The function requires three arguments which must include pressure and any two remaining independent variables such as temperature.7. Substances which obey the ideal gas law. e. P=14. enthalpy.50) HumRat [dimensionless] returns the humidity ratio (defined as the mass of water vapor per mass of dry air) for air-water gas mixtures. For AIRH2O. P=14. T=900. B=50) Enthalpy [kJ/kg. (temperature or internal energy). T=70. will always require two arguments in addition to the substance name. For AIRH2O. Substances which obey the ideal gas law. Example: h1 = enthalpy(AIR. three arguments are required. T=70. T=1320. require a single argument. °C. total pressure. P=100) s2 = entropy(AIRH2O. Example: D1 = dewpoint(AIRH2O. like steam. relative humidity. w=0. kJ/kgmole. Example: w1 = humRat(AIRH2O. Btu/lbmole-R] returns the specific entropy of a specified substance. T=70. in addition to the substance name.7. Btu/lbmole] returns the specific internal energy of a specified substance. P=14. Example: u1 = intEnergy(AIR. The exact form of the enthalpy function depends on the substance and independent variable(s) selected. P=14. R. h=25) IntEnergy [kJ/kg. T=400.7.010) D2 = dewpoint(AIRH2O. R=0. or dew point. kJ/kgmole.7. such as air.50) w2 = humRat(AIRH2O. The exact form of the IntEnergy function depends on the substance and independent variable(s) selected. R=0. R=0. K] returns the dewpoint temperature for air-water gas mixtures. three arguments are required. T=300) u2 = intEnergy(STEAM. T=70. For all pure substances. AIRH2O requires three additional arguments. P=14. This function can be used only with AIRH2O as the substance name. Btu/lb. and relative humidity (or humidity ratio or wetbulb temperature). T=300) h2 = enthalpy(STEAM. R=0.7. T=70. This function is applicable only to the substance AIRH2O. The convention used in EES is that fluid names that are chemical symbols. O2. bar. R=0. Example: P1 = pressure(STEAM. h=1450. T=70. The function returns either 1 (meaning true) or 0 (meaning false). psia. The need for the IsIdealGas function arises because the number of arguments may differ is the fluid is represented by the ideal gas law. P=14. psia. e. That is the purpose of this function. e. Air is an exception to this rule.. are considered to be real fluids with subcooled.Built-in Functions Chapter 4 u3 = intEnergy(AIRH2O. saturated and vapor phases. The pressure function is not implemented for AIRH2O. If you are trying to write a general function to return a property of a fluid that is specified in a string variable. but temperature and another property such as pressure are needed to determine the enthalpy of Oxygen. The fluid may be a fluid name or a string variable.7. you may not know how many parameters it requires unless you know if the fluid is represented by the ideal gas law. and CarbonDioxide. Example: M_CO2 =MolarMass(CarbonDioxide) Pressure [kPa. are modelled with the ideal gas law whereas fluid names that are spelled out.g.. is determined by temperature alone for O2. Use an IF THEN ELSE statement testing on the value of IsIdealGas to branch to the correct form of the property function you wish to determine. Example: B=IsIdealGas(O2) C=IsIdealGas(R$) MolarMass returns the molar mass (often called molecular weight) of the fluid provided as the parameter.50) IsIdealGas is a very simple function that requires only one parameter and that is the name of the fluid. atm] returns the pressure of a specified substance. each item separated by commas. however. the fluid is considered to behave according to the ideal gas law. Enthalpy. and CO2. bar. Nitrogen.g. Example: Pc=P_Crit(R134a) "returns the critical pressure of R134a" 139 . Oxygen. N2. an unknown pressure can still be determined using any of the functions which are applicable to moist air and which take pressure as an argument. for example. atm] returns the critical pressure of the specified fluid. The argument list for the pressure function always requires the substance name followed by two arguments. Critical property information is not available for ideal gas substances. T=900) P_Crit [kPa. If the function returns true. 100 is returned. P=14. the quality is returned as –100. The three arguments are temperature. enthalpy. If it is superheated. B=55) Specheat [kJ/kg-K. P=30) SoundSpeed [m/s. Btu/lbmole-R] returns the constant pressure specific heat of the specified substance. this simplifies to: c = RT cp cv 140 . ft/s] through the fluid. Two independent arguments are required. T=70. the specific heat function has temperature as its only other argument in addition to the substance name. The temperature and pressure must both be provided as arguments for substances modeled as real fluids. T=350) Cp2 = specheat (AMMONIA.T=100. There are three arguments to this function. Temperature and pressure are not independent for saturated states. If the state of the substance is found to be subcooled. h=50. w=0. The Prandtl number requires temperature as an input for ideal gas substances and temperature and pressure for real substances. Example: R1 = relhum(AIRH2O. in addition to the substance name. The speed of sound is defined as: c= ∂P ∂ρ s but for an ideal gas. Example: x1 = quality(R12.7.Chapter 4 Built-In Functions Prandtl returns the dimensionless Prandtl number for the specified fluid defined as Pr = µ cp k where µ is the viscosity. T=80) Relhum [dimensionless] returns the relative humidity as a fractional number for air-water gas mixtures. For pure substances which obey the ideal gas law.P=50) Quality [dimensionless] returns the quality (vapor mass fraction) for substances modeled as real fluids such as WATER and R12. or humidity ratio. Example: Pr_1=Prandtl(Air.01) R2 = relhum(AIRH2O. total pressure and any two remaining independent variables such as temperature. Example: Cp1 = specheat(AIR.7. T=70. depending on the temperature and pressure values provided. T=100. T=70. cp is the specific heat. h=25) R3 = relhum(AIRH2O. kJ/kgmole-K. ft/s] function returns the speed of sound c with units [m/s. dew point. P=14. wetbulb. The specific heat of the liquid or vapor may be returned.T=100) Pr_2=Prandtl(Steam. P=14. AIRH2O. and k is the thermal conductivity.7. Btu/lb-R. R=0. may require one or two arguments whereas pure real fluid substances. P=100) T_Crit [°C. will always require two arguments. Example: v1 = Volume(AIR. P=14. h=25. in addition to the fluid name. Example: sigma=surfacetension(Water. total pressure. T=70. T=70. m3/kgmole.7. R] returns the temperature of the substance. °F. w=0. w=0.Built-in Functions Chapter 4 Examples: C1 = SoundSpeed(Air. T=400) Temperature [°C. P=100) v2 = Volume(Steam. like STEAM.7) V_Crit [m3/kg. R] returns the wetbulb temperature for air-water gas mixtures. ft3/lbmole] returns the specific volume of a specified substance.01) B2 = wetbulb(AIRH2O. T=300. and that is the temperature. three are needed for moist air. P=14. h=25. Example: Tc=T_Crit(R134a) Volume [m3/kg. Example: vc=V_Crit(R134a) "returns the critical volume of R134a" Wetbulb [°C. K. s=1. P=14. lbf/ft] returns the surface tension at the liquid-vapor interface of a saturated fluid. Substances which are assumed to obey the ideal gas law. Example: B1 = wetbulb(AIRH2O. P=14. Two arguments are required for all pure substances. P=400) v3 = Volume(AirH2O. and relative humidity (or humidity ratio or dewpoint). °F. such as air. h=850. ft3/lb. T=300) C2 = SoundSpeed(R134a_ha. Critical property information is not available for ideal gas substances. R] returns the critical temperature of the specified fluid. The exact form of the function depends on the substance and argument(s) selected. ft3/lbmole] returns the critical specific volume of the specified fluid. K.75. ft3/lb. °F. D=30) 141 .7. K. The three arguments are temperature (or enthalpy).P=100) SurfaceTension [N/m. There are three arguments to this function.T=300. Example: T1 = temperature(AIR.5. This function is applicable only to the substance AIRH2O. h=300) T2 = temperature(AIR.7. Critical property information is not available for ideal gas substances. This function requires only one argument. in addition to the substance name.01) B3 = wetbulb (AIRH2O. m3/kgmole. For ideal gas substances. P=14. T=100. R=0. T=80.7.Chapter 4 Built-In Functions Viscosity [N-sec/m2. the Viscosity function takes one parameter in addition to the fluid name and this parameter must be temperature. lbm/ft-hr] returns the dynamic viscosity of the specified substance. For real fluids. Example: v1 = viscosity(AIR.335) v4 = viscosity(AIRH2O. T=40. v=0. the temperature. and humidity ratio (or relative humidity) must be supplied as arguments. Any two independent properties can be supplied. For AirH2O (moist air). T=300) v2 = viscosity(R134a. the Viscosity function takes two parameters. pressure.5) 142 . provided that the state does not consist of two phases. x=1) v3 = viscosity(STEAM_NBS. The Open Lookup Table command will read the data in a Lookup file stored on disk into a Lookup Table in the Lookup Table Window. Lookup Tables must have a name to be used with functions that operate on the Lookup Table data. EES assigns the names "COLUMN1'. 'COLUMN2'. This is the name that must be used with commands that use the Lookup Table. LookupCol. The six menu commands which pertain to the Lookup Table Window appear at the bottom of the Options menu and are summarized here. In the basic form. one or more Lookup Tables can exist in the Lookup Table Window where they can be viewed and changed. Differentiate. including the Lookup. Once created.LKT) Binary Lookup files store all of the information that appears in a Lookup Table window in a binary file on disk. Binary Lookup files (. and display format for each file type. Each following line provides the data for one row with the value for each column separated by one or more spaces or a tab character. You can change the name by right-clicking on the tab. The name will appear on a tab at the top of the Lookup Table Window. A name must be provided for the Lookup Table. LookupRow. Lookup files can be accessed directly with Interpolate. the Lookup file can be opened into the Lookup Table window using the Open Lookup Table command. including the data. Interpolate. A binary (. There are three Lookup File Formats. the first line of the file contains the number of rows and columns in the table. they cannot be created. In addition to being read into the Lookup Table. etc. and LookupRow functions.TXT) There are several variations for the ASCII Lookup file format. and these column names should be used when the file is used with the 143 . units. Lookup files provide a means to enter functional relationships with tabular data and to use these relationships in the solution of the equations.Built-in Functions Chapter 4 Using Lookup Files and Lookup Tables A Lookup file is a two-dimensional set of data with a specified number of rows and columns. The name appears on a tab at the top of the Lookup Table Window. Lookup. and the column name. The name that is given to the Lookup Table that is read in is the filename without the drive and filename extension.LKT) Lookup file is created using the Save Lookup Table command. ASCII Lookup files (. Binary files require less disk storage space and the can be opened and saved more quickly by EES. or display format for the data. and all three can be opened with the command. New Lookup Table creates a new empty Lookup Table with a specified number of rows and columns in the Lookup Table Window. However. and Differentiate commands. In addition. Lookup files can be stored in a disk file. units. Lookup$. edited or viewed by any application other than EES. The basic form does not provide a means of specifying the names. Differentiate.56 7. The 144 . A3. EES will expect to find the format specification (e.CSV format is necessary when you wish to export the data to another application.23E-12 2 2. Lookup. ColB. such as a spreadsheet. The following lines contain the data for each row. These functions are documented below. The example below would create a table with 2 rows and 3 columns. LookupCol. Save Lookup saves the foremost Lookup Table in the Lookup Table Window as a Lookup file on the disk. Lookup files in either the binary or ASCII formats can be accessed directly with Interpolate. Values on each row are separated with the list separator character. The .. and ColC. and F3 format specifications and the column names will be ColA. The units are enclosed in square brackets. Lookup files can be accessed with the Lookup functions described below. The number of rows in the table is equal to the number of rows of data. separated by one or more spaces or a tab. and LookupRow functions. The following example shows the ASCII data needed for a Lookup file with five rows and three columns. ASCII Lookup files (. F0. If the number of columns is a negative number. Automatic formatting is used to display the data if the file is read into the Lookup Table with the Open Lookup Table command.g. F3 or E4) followed by one space and then the column heading and units for each column. The columns would be formatted with E4. 5 3 1 2 3 4 5 11 22 33 44 55 111 222 333 444 555 If a negative number is provided in the file for the number of rows.CSV file provides only data without any information concerning the column names or data format.34E-11 4 4. 2 -3 E4 ColA [Btu] F0 ColB F3 Col 1. EES will determine the number of rows of data in the file.CSV) The .Chapter 4 Built-In Functions Interpolate or Differentiate commands.89 In addition to being read into the Lookup Table.carriage return. The number of values in the first row of the file determines the number of columns in the table. Each row ends with a linefeed . Chapter 7 provides details on the use of string variables.LKT (for binary lookup files) or . The filename extension can either be .. Note that the Lookup Tables in the Lookup Table Window are also saved with other problem information when the Save command is issued. Lookup$. If a filename extension is not provided. EES will assume that the file format to be binary (i. Insert/Delete Lookup Cols will allow one or more columns to be added or removed from an existing Lookup Table in the Lookup Table Window. Note that rows in a Lookup Table can be delete more simply by clicking in the row header (in the leftmost column) to select the row followed by pressing the Delete key or selecting the Delete command in the Edit menu. EES will automatically append the . In the latter case. a Lookup file.CSV (for ASCII lookup files). Select the Lookup Tables that you wish to delete by clicking on their names in the list. ColName2=Value) returns the derivative determined from two columns of tabular data based on cubic interpolation. Lookup$Row. Selected files will be deleted when the OK button is clicked. Lookup. Select the name of the Lookup Table for which the change is to be made from the drop-down list at the top of the dialog. The ASCII format allows the data to be exported to another application.TXT or . 'ColName1'.LKT extension).. Interpolate. These functions may either operate on data in the Lookup Table window or in a Lookup file on disk. 'ColName2'. LookupRow. These data can be in the Lookup table. and LookupCol functions. Data in the Lookup Table can be accessed with the Differentiate. Differentiate(TableName. the first argument of the function is the Lookup filename as it is stored on disk.e. the name of the Lookup Table that is accessed is provided as the first argument as a string constant (surrounded with single quotes) or string variable (identified by the $ character at the end of the variable name). TableName is a string constant or string variable that provides that provides the name of the Lookup table in the 145 . Note that columns in a Lookup Table can be delete more simply by clicking in the column header to select the column followed by pressing the Delete key or selecting the Delete command in the Edit menu. The file name can be supplied as a string constant or as a string variable. Select the name of the Lookup Table for which the change is to be made from the drop-down list at the top of the dialog. It is not necessary to save a Lookup Table separately unless it is to be used program. Delete Lookup Table will present a dialog that shows all Lookup Tables in the Lookup Table Window.LKT filename extension or as an ASCII text file. In the former case. Insert/Delete Lookup Rows will allow one or more rows to be added or removed from an the specified Lookup Table in the Lookup Table Window.Built-in Functions Chapter 4 Lookup file can be saved as a binary file with a . or the Parametric table. If the name of a disk file is supplied. Lookup table names appear on the tabs at the top of the Lookup Table Window.T=100) {returns the derivative dT/dX at a value of T=100 using data from Lookup file myFile. In this case.CSV filename extension.TXT. EES will return an estimate of the derivative d(ColName1)/d(ColName2) at a point fixed by the specified value of either ColName1 or ColName2.X. The string constant must be enclosed within single quote marks.34 using data in Lookup Table l} Y=Differentiate('C:myFile'. or the Parametric table using cubic interpolation. the Differentiate function will be applied to date in the foremost Lookup Table.Chapter 4 Built-In Functions Lookup Window or the name of an existing Lookup file stored on disk.LKT. Value is a numerical value or expression. 'ColName2'. 'Y'. ColName1 and ColName2 are the column header names. Lookup table names appear on the tabs at the top of the Lookup Table Window. The final parameter is of the form ColName2=Value where the text to the left of the equal sign can be either of the column header names (ColName1 or ColName2) specified with the two previous parameters. 'ColName1'. or . Examples: dXdY=Differentiate(‘Lookup 1’. The Differentiate function can also be made to operate on data in the Parametric table if Filename is set to ‘Parametric’. the Interpolate function will be applied to date in the foremost Lookup Table. Value is a numerical value or expression. ColName2=Value) returns an interpolated or extrapolated value from tabular data in the Lookup table. If the TableName parameter is not supplied. the values in the Parametric table must already exist. The single quotes enclosing the column header names are optional.LKT on drive C} Interpolate('TableName.TXT. or .CSV filename extension.'X'. Y=2. If the TableName parameter is not supplied. it must be the name of an existing Lookup file having with a .LKT. If the name of a disk file is supplied. it must be the name of an existing Lookup file having having a . Values which are to be calculated when the Solve Table command is issued cannot be used with the Differentiate command. TableName is a string constant or string variable that provides that provides the name of the Lookup table in the Lookup Window or the name of an existing Lookup file stored on disk. . EES will return the interpolated value from the data in column ColName1 146 . . ColName1 and ColName2 are the column header names. a Lookup file. The final parameter is of the form ColName2=Value where the text to the left of the equal sign can be either of the column header names (ColName1 or ColName2) specified with the two previous parameters. The column header names can alternatively be entered as string variables. These single quotes enclosing the column header names are optional. such as those entered from the keyboard.T. The string constant must be enclosed within single quote marks. These columns names can also be supplied with string variables.34) {returns the derivative dX/dY at a value of Y=2. the value in the first row or column will be returned. Lookup table names appear on the tabs at the top of the Lookup Table Window. EES will return the interpolated value of ColName2.} interpolate1('Filename'.LKT. it must be the name of an existing Lookup file having with a . Column) returns the value in a Lookup Table or Lookup file at the specified row and column.3) {returns a value from the Lookup Table in table Lookup 1 from column Col2 of the Lookup table corresponding to a value in Col1 equal to 2. 'ColName1'.5) {returns a value from column X in the lookup table called myData. .} X= Interpolate(C:\myData. ‘Col2’. An older format in which the column name is preceded with the # symbol is still supported. ‘Col1’. However.5 using cubic interpolation. or . Similarly. Note that the quotes are optional.3 using cubic interpolation. TableName is a string constant or string variable that provides that provides the name of the Lookup table in the Lookup Window or the name of an existing Lookup file stored on disk. If Filename is 'Parametric'. If the name of a disk file is supplied. Col1=2. Lookup(‘Lookup 1’.2. Note that the column (last argument) can be specified either by providing a numerical value (or expression) for the column number or by providing the column name as a string constant (enclosed in single quotes) or as a string variable. Examples: Z=interpolate(‘Lookup 1’. The value returned will be interpolated between rows and columns as needed. ColName2=Value) provides the same function as the interpolate command except that it uses linear interpolation. For example. the value in the last row or column will be returned. Row. 'ColName2'. The row and column arguments need not be integers. ColName2=Value) provides the same function as the interpolate command except that it uses quadratic interpolation. 3) will return a value which is midway between the values on the second and third rows in the third column. the interpolate command will be applied to the existing Parametric table.Built-in Functions Chapter 4 corresponding to the specified value of ColName2. If the specified row or column is less than 1.Y=4. 'ColName2'. such as those entered from the keyboard.Y.LKT. Values which are to be calculated when the Solve Table command is issued cannot be used with the interpolate command. the values in the Parametric table must already exist. 147 .LKT on drive C: corresponding to a value in column Y equal to 4. The Lookup function can be used with the LookupCol and LookupRow functions to provide interpolated values of user-supplied tabular information. If the value of ColName1 is supplied. if the row or column is greater than the number of rows and columns in the lookup table. In this case. The string constant must be enclosed within single quote marks.CSV filename extension. interpolate2('Filename'. 'ColName1'. Lookup(TableName.X.5. the Interpolate commands are usually more convenient for this purpose.TXT. The string constant must be enclosed within single quote marks. To change the format style. as it is in the Lookup function. X) {Set C to the column number in row R of \Lookup file C:\abc\ CopperK.R.LKT having the value X} LookupRow(Tablename.LKT’.Chapter 4 Built-In Functions Examples: X=Lookup(‘Lookup 1’.1.Column. As in the Lookup function the first argument is the name of the table in the Lookup Table window or a name of a Lookup file stored on disk. click in the column header and make the change in the Format Table dialog window.2) {Column 2 must be set to STRING format} LookupCol(‘Filename’. The column value returned may not be an integer. TableName is a string constant or string variable that provides that provides the name of the Lookup table in the Lookup Window or the name of an existing Lookup file stored on disk. Value) uses the data in the specified row of the Lookup Table or Lookup file to determine the column which corresponds to the value supplied as the second argument. Value) uses the data in the specified column of the Lookup Table or Lookup file to determine the row corresponding to the value supplied as the second argument.2) { Set X to the value in row 1.2. the format style of the column in the Lookup table must be set to STRING. Note. The purpose of the LookupCol function is to provide a means of relating tabular information in different rows of the Lookup Table or Lookup file. } X=Lookup(‘C:\abc\ CopperK.LKT’. Row.. Example: R$=Lookup$(‘Lookup 1’. This row value should be an integer.’T’) {Set X to the value in row R and the column which is named T in Lookup file C:\ abc\ CopperK.1. Interpolation between rows is not allowed. The column can be indicated by a numerical value or expression which provides the column number or by the name of the column provided in a string constant or string variable. In order to accept string information. R.LKT} Lookup$ operates just like the Lookup function except that it returns a string rather than a numerical value. Examples: C=LookupCol(‘Lookup 1’. 148 . The final parameter indicates the column. Interpolation between columns will be provided as needed. The next argument is a numerical value or expression that provides the row in the table.1. column 2 in the Lookup Table named ‘Lookup 1’} X=Lookup(‘Lookup 1’.’X’) { Set X to the value in row 1 of the column in the Lookup table which is named X. 100) {Set C to the column number in row 2 of table Lookup 1 which has a value of 100} C=LookupCol(‘C:\abc\ CopperK. etc.LKT which has the value X} Lookup$Row operates just like the LookupRow function except that it its final argument is a string rather than a value. Data may be copied from the Clipboard by clicking the upper-left cell into which the data are to be 149 . or .LKT. 100) {Set R to the row number in column 2 of the Lookup table which has a value of 100} R=LookupRow(‘C:\abc\ CopperK. The final argument is a string constant or string variable holding the string that will be searched in the table. See the Lookup Window section of Chapter 2. Hold the Shift key down and then click in the lower right cell.LKT’. in addition to the selected data. If the name of a disk file is supplied. These default names and the table display format can be changed by clicking the right mouse button in the header cell and selecting Properties from the popup menu. Use the Select All command in the Edit menu to select all of the cells in the Lookup table. As in the LookupRowfunction the. the format style of the column in the Lookup table must be set to STRING. If three arguments are provided. The row value returned may not be an integer. Examples: R=LookupRow(‘Lookup 1’. The purpose of the LookupRow function is to provide a means of relating tabular information in different columns of the Lookup Table. To change the format style. Note. data may be transferred between the Lookup Table and the Parametric Table or between other applications such as a spreadsheet program. click in the column header and make the change in the Format Table dialog window. Note that the last argument which indicates the column in the table can be indicated either by supplying its numerical value or by providing the column name as a string constant (enclosed in single quotes) or as a string variable. X) {Set R to the row number in column C Lookup file C:\abc\ CopperK. Information can be copied to or from the Lookup Table via the Clipboard. C. In this way. Interpolation between rows will be provided as needed. The function returns the row in the table in which this string exists. it must be the name of an existing Lookup file having with a . Next. . In order to accept string information. use the Copy command in the Edit menu to copy a selected range of table cells to the Clipboard. Hold the Ctrl key depressed if you wish to copy the column header name and units.TXT. Lookup$Row function can have two or three arguments. To select a rectangular group of cells in the Table. Selected cells will be displayed in inverse video. An older format in which the column name is preceded by the # symbol is also accepted. The next argument is the column in the table. Column2.CSV filename extension. the first is a string that provides the name of a Lookup table stored on disk. the columns are initially named Column1. When a new Lookup Table is created.Built-in Functions Chapter 4 Lookup table names appear on the tabs at the top of the Lookup Table Window. click the left mouse in the upper left cell. 2. Chapter 4 Built-In Functions pasted. 150 . The data in the Clipboard will be pasted into the Lookup Table. followed by the Paste command. starting from the selected cell. $OPENLOOKUP 'C:\EES32\myTable. This name must be a string constant. For example: $OpenLookup ?? myLookupFile$ will bring up a standard file input dialog from which the file name can be selected. EES will display a standard save file dialog from 151 . If the Lookup table has already been opened and the time/date information for the disk file has not changed.TXT or . If a ? is provided. The format is: $SAVELOOKUP LookupTableName 'C:\EES32\myTable. The name of the Lookup file that is opened is assigned to this variable. If a single question mark (?) is provided as a file name.lkt' $OPENLOOKUP FILE$ {File$ has been previously set to a valid lookup file name} $OPENLOOKUP ? {Bring up a dialog window to choose the lookup file} When EES encounters this directive. The filename should include the filename extension.LKT Lookup file format. EES will open the selected file. it will first check to see if it has already opened a Lookup table with this filename. no action will be taken.Built-in Functions Chapter 4 The $OpenLookup and $SaveLookup Directives The $OPENLOOKUP directive (available in the Professional version) opens a file having the specified name and reads that file into the Lookup Table. EES will present a Windows open file dialog and use then substitute the selected file name for the ? after opening the file.lkt' LookupTableName is the name of the Lookup Table (as seen on the tabs in the Lookup Table Window) that is to be saved. If two question marks are provided. The last parameter is the name of the file. The $SAVELOOKUP directive will save a specified Lookup table into a disk file after calculations are completed. LookupTableName can be a string constant contained in single quotes or a string variable (identified with a $ as its last character). The $ OPENLOOKUP directive can have an optional second parameter which must be a string variable name. as in the following examples. a string variable that has been set to a valid file name or a ? or ??. The filename may be a string constant (enclosed within single quotes) or a string variable that has been previously assigned to the filename. That Lookup file will be opened and copied into the Lookup Table and the string variable myLookupFile$ will be set to the name of the file. .CSV. but not make the substitution so that the open file dialog is presented during every execution. The file can be have . It is not necessary to use the $OPENLOOKUP and $SAVELOOKUP directives for this purpose. If ?? is provided.e. The directives are useful for chaining EES programs. $SAVELOOKUP 'LookupTableName' ? will save the data in the lookup table name 'LookupTableName' into a file that is selected from the save file dialog.Chapter 4 Built-In Functions which the name of the file can be selected. when the an EES program writes information into the Lookup Table using the Lookup command in a function or procedure so that a following EES program can use that information. i. Several EES programs can be chained in sequential operation by saving the Lookup table as a Lookup file in one EES program and loading that Lookup file in the next EES program. 152 . Link buttons on the Diagram window facilitate the chaining process. it will not be overwritten and the save file dialog will appear after every calculation. The ? will be overwritten with the selected filename. Lookup tables are automatically saved and opened when an EES file is saved and opened.. The Lookup command can be used to save calculated results in the Lookup Table. That file name will then overwrite the ? so that the save file dialog does not reappear> For example. procedures. EES reorders the equality statements as needed to efficiently solve the equations. as explained below. Third. it differs from a procedure in that it employs equalities rather than assignment statements. or any compiled language. C++. The combination of both statement types offers a great deal of flexibility in the manner in which a problem can be formulated in EES. they make it easier to formulate the solution for a complicated system by breaking the problem up into a number of smaller parts. rather than equality statements. They can even provide help when requested. EES functions and procedures (but not modules) allow use of if then else. repeat until and goto statements. A function is a subprogram that accepts one or more inputs and returns a single result. EES can access both internal subprograms that have been written within EES and external subprograms written in Pascal. EES subprograms offers a number of advantages. However. and/or modules which have been saved with a . Library files are EES files containing one or more functions. Modules employ equality statements just as those used in the main body of an EES program. They are executed in the order in which they appear. In addition. A procedure can return one or more results. There are several ways to access subprograms. EES also allows subprograms to be saved in a library file. Subprograms stored in library files that reside in the USERLIB\ subdirectory are automatically and transparently loaded when EES starts. procedure. EES also offers this capability in a variety of ways. Procedures and Modules . A module is similar to a procedure in that it can return one or more results. The statements appearing in functions and procedures differ from those in the main body of EES in that they are assignment statements. similar to those used in most high-level programming languages. Library files can also be loaded with the Load Library command in the File menu and with the $INCLUDE directive. Both internal and external subprograms can be stored in the USERLIB\ subdirectory from which they are automatically loaded when EES is started. Functions. The Merge command in the File menu can be used to import EES subprograms from one EES file into another. or module written within EES. First. subprograms can be saved in a library file and reused in other EES programs. The development of external subprograms is described in Chapter 6. Programs which rely on subprograms are easier to understand. C.lib filename extension using the Save As command. An EES subprogram is a function. procedures and modules in library files act just like EES internal functions. FORTRAN. The steps necessary for creating library files is described at the end of this chapter. Second. 153 EES Functions.Built-in Functions Chapter 4 CHAPTER 5 ____________________________________________________________________________ ____________________________________________________________________________ Most high-level programming languages allow the user to write subprograms. 9. 3. 4. An assignment statement sets the variable identified on the left of the statement to the numerical value on the right. Repeat Until and goto statements may be used in functions and procedures to alter the calculation order. similar to those used in FORTRAN and Pascal. Equations in user functions may call any of the built-in functions. If Then Else. The function name and arguments. they may call any previously-defined user function or procedure or any functions or procedures previously loaded as Library files. However. User functions begin with the keyword FUNCTION.Chapter 5 EES Functions and Procedures EES Functions EES provides the capability for the user to write functions directly in the Equations window using the EES equation processor. The arguments must follow the name. The equations appearing in EES functions and procedures are fundamentally different from those appearing in the main body of EES. follow on the same line. 2. EES functions are similar to those in Pascal. as assumed for all equations in the main body of EES. X:=X+1 is a valid assignment statement but it obviously cannot be an equality. Functions are called simply by using their name in an equation. Functions always operate in real mode regardless of the setting for complex algebra. however. 6. Functions may not call modules. EES normally processes the assignment statements in a function or procedure in the order they appear. The equations in functions and procedures are more properly called assignment statements. The function returns the value to which its name is assigned. However. The format of these logic control statements is described below. before any modules or any equations in the main body of the EES program. The function is terminated by the keyword END. The function must be called with the same number of arguments appearing in the FUNCTION statement. The := sign (rather than the = sign) is used to signify assignment. In addition. enclosed in parentheses. 5. EES will accept an equal sign in assignment statements if the ! Allow = in Functions/Procedures control in the Display Options dialog window (Options menu) is selected. 154 . 8. 7. Recursive functions which call themselves are. All variables used in the function body are local to the function except those variables defined in the scope of the $COMMON directive. enclosed in parentheses and separated by commas. The user functions must appear at the top of the Equations window. not allowed. The rules for these functions are as follows: 1. P1.17 “ft/s^2 gravitational acceleration psi := (h-ho). ho and so are constants. often called ψ.ho) .To * (s – so) + (V^2 / 2 + g * Z) * Convert(ft^2/s^2. V. T=T. Using the UnitSystem function (Chapter 4) and the IF THEN ELSE statements documented below. For example. they depend on the EES unit settings to be properly set. Btu/lbm) END Functions can also be used to change the name of any built-in function and/or to shorten the argument list. FUNCTION w(T. END The two example functions both employ EES internal property functions and as a result. and sets the total pressure to 100 kPa in each case.RH) w := humrat(AIRH2O. For example.so) + V2/2 + g z where h and s are specific enthalpy and entropy. relative to a selected zero point Once the temperature and pressure of the dead state are selected. T=T. it is possible to write general functions that will operate correctly with any unit settings. A reference to psi(T1. is ψ = (h . V1. the following function changes the name of humrat. the specific availability of a flowing stream. FUNCTION psi(T. P=100.05 “Btu/lbm specific enthalpy at dead state conditions” so := 0. could be implemented by placing the following statements at the top of the Equations window. To and Po V is the velocity g is gravitational acceleration z is elevation. P. T=T. Z1) from an equation would return the specific availability of steam in Btu/lbm for the chosen ‘dead’ state. respectively ho and so are specific enthalpy and entropy at the ‘dead’ state condition. R=RH).To (s . eliminates the need to specify the substance AIRH2O as an argument. A user function for the availability of steam. Z) To := 530 “R dead state temperature” ho := 38. the built-in function for humidity ratio. with To=530 R and Po=1 atm. P=P) s := entropy(STEAM.EES Functions and Procedures Chapter 5 Functions can be used to implement an analytical relationship between two or more variables.0745 “Btu/lbm-R specific entropy at dead state conditions” h := enthalpy(STEAM. to w. P=P) g = 32. 155 . B. string variables.B. In the example above. the equations are really assignment statements. TEST. The equations within a procedure differ from ordinary EES equations in modules or in the main body of an EES program. or algebraic expressions. END Procedures must be placed at the top of the Equations window.. in the example above. all variables except for the inputs and outputs are local to the procedure... Procedures may also call other functions and procedures. rather than equalities. can be any valid EES variable name. 156 . EES will evaluate the outputs using the input variables supplied in the argument list. Third. and C are inputs and X and Y are outputs. if then else.Chapter 5 EES Functions and Procedures EES Procedures EES procedures are very much like EES functions. The arguments may be constants. The format of these flow control statements is described in the next section.. Additional arguments can be passed between the main body of an EES program and a procedure using the $COMMON directive.3 : X. The numbers of inputs and outputs in the CALL statement argument list must exactly match the PROCEDURE declaration statement. before any of the modules or equations in the main body of an EES program. provided that they are defined previously..Y) .Y) ... First. except that they allow multiple outputs. You may override this convention by enabling the ! Allow = in Functions/Procedures control in the Preferences dialog window (Options menu).. . Each output variable must be defined by an equation with the output variables name on the left of the assignment sign. the assignment symbol (:=) is used in place of the equal sign...2. The procedure name. A. Procedures may not call modules. To use the procedure.. The argument list consists of a list of inputs and a list of outputs separated by a colon.C : X. and to make this distinction clear.. Each procedure must have at least one input and one output. Second. place a CALL statement anywhere within your equations. repeat until and goto statements may be used. The CALL statement appears as . The format of a Procedure is: PROCEDURE test(A. numerical variables. X :=. An END statement closes the procedure. CALL test(1. Y :=. EES supports both internal and externally-compiled procedures.Y:0. it is possible to program your own iterative loop. Repeat Until and goto statements. the CALL Turbine statement can be used to determine the turbine work and outlet state variables. However. Y = 3. Here's a program which does this. it is also possible to have EES solve implicit equations within a procedure. Commonly-used procedures may be saved separately and merged into the Equations window with the Merge command in the File menu. Procedures can be selectively loaded with the Load Library command in the Options menu or with the $INCLUDE directive. as described later in this chapter.106 when executed} Procedures offer a number of advantages for the EES user. the procedure could be saved as a library file so that it is loaded automatically when EES is started.EES Functions and Procedures Chapter 5 Implicit equations can not be directly solved in a procedure or function. PROCEDURE Solve(X. Internal procedures are entered directly at the top of the Equations window. Compiled procedures are written in a high-level language such as C. R1 and R2. For example.Y:R1. as described in this section.23456 END CALL Solve(X. respectively. 157 .23456 To solve for X and Y in a procedure. Now use EES to solve for X and Y such that the residuals are 0. However. Pascal. X^3 + Y^2 = 66 X/Y = 1. Each time a turbine calculation is needed. as they are in modules and in the main equation body. For example. consider the following two non-linear equations. or FORTRAN and called from EES. Using the If Then Else. See Chapter 6 for a detailed description of writing and using compiled functions and procedures. subtract the right-hand side from the left hand side of each equation and set them to residuals.R2) R1:=X^3+Y^2-66 R2:=X/Y-1. it should be noted that implicit equations could be solved more directly and efficiently using a module. the equations describing a turbine can be entered once and saved.834. The CALL statement for both types of procedures is identical. Alternatively.0) {X = 3. 4. Statement 1 can be either an assignment or a GoTo statement. and <> (for not equal). The following example function uses If Then Else statements to return the minimum of its three arguments.y. EES processes the logical operations from left to right unless parentheses are supplied to change the parsing order. The format is very similar to that used in Pascal. >. <. Recognized operators are =.Chapter 5 EES Functions and Procedures Single-Line If Then Else Statements EES functions and procedures support several types of conditional statements. The most common conditional is the If Then Else statement. The Then keyword and Statement 1 are required.z) { returns smallest of the three values} If (x<y) Then m:=x Else m:=y If (m>z) Then m:=z MIN3:=m End Y = MIN3(5. If (x>y) or ((x<0) and (y<>3)) Then z:=x/y Else z:=x 9 Note the the built-in MIN function accepts any number of arguments so this function would not be needed. Note that the parentheses around the (x>0) and (y<>3) are required in the following example to override the left to right logical processing and produce the desired logical effect. 158 . the entire If Then Else statement must be placed on one line with 255 or fewer characters. The Else keyword and Statement 2 are optional.9 Function MIN3(x. In the single-line format. <=. If (Conditional Test ) Then Statement 1 Else Statement 2 The conditional test yields a true or false result. Both single-line and multiple-line formats are allowed for If Then Else statements. Note that string variables (see Chapter 7) can be used in the condition test.6) { Y will be set to 4 when this statement executes} The AND and OR logical operators can also be used in the conditional test of an If Then Else statement. These conditional statements can not be used in modules or in the main body of an EES program. >=. The single-line format has the following form. The parenthesis around the conditional test are optional. 75 when this statement executes} 159 . followed by the statements which execute if the conditional test is false.. is required and it must appear on a line by itself. This conditional statement can be used in functions and procedures. Indentation is used to make the logic flow more clear.. The format is as follows: If (Conditional Test) Then Statement Statement . Else Statement Statement . The format is illustrated in the following example. The EndIf keyword. Function IFTest(X.. Y) If (X<Y) and (Y<>0) Then A:=X/Y B:=X*Y If (X<0) Then { nested If statement} A:=-A. and Then keyword must be on the same line. which terminates the multiple-line If Then Else statement. However EES ignores the blank spaces.. EndIf The If keyword. but not in modules or the main body of an EES program. An Else (or EndIf) keyword terminates this first group of statements. The Else keyword should appear on a line by itself. B:=-B EndIf Else A:=X*Y B:=X/Y EndIf IFTest:=A+B End G=IFTest(-3. The statements which are to be executed if the conditional test is true appear on following lines.4) { G will be set to 12. Also upper and lower case are treated equally.EES Functions and Procedures Chapter 5 Multiple-Line If Then Else Statements The multiple-line If Then Else statement allows a group of statements to be executed conditionally. the conditional test. The parentheses around the conditional test are optional. These statements may include additional If Then Else statements so as to have nested conditionals. The format of a GoTo statement is simply GoTo # where # is a statement label number which must be an integer number between 1 and 30000. Statement labels precede an assignment statement separated with a colon (:). Note that Repeat Until statements can only be used in functions and procedures. The format is identical to that used in Pascal. the flow control can be altered using GoTo statements.. The GoTo statement must be used with If Then Else statements to be useful.Chapter 5 EES Functions and Procedures GoTo Statements EES will normally process the assignment statements in a function or procedure in the order they appear starting with the first statement. Until (Conditional Test) The conditional test yields a true or false result using one of the following operators: =. Repeat Statement Statement . Function FACTORIAL(N) F:=1 i:=1 10: i:=i+1 F:=F*i If (i<N) Then GoTo 10 FACTORIAL:=F End Y= FACTORIAL(5) { Y will be set to 120 when this statement executes} Repeat Until Statements Looping within functions and procedures can be implemented with If Then Else and GoTo statements described above. Here is the same Factorial example presented in the previous section implemented with a Repeat Until construct. Function Factorial(N) 160 .. The Repeat Until statement has the following format. but it is generally more convenient and readable to use a Repeat Until construct. <. However. >. <=. >=. The following function illustrates the use of GoTo and If Then Else statements in the calculation of the factorial of a value supplied as the argument. and <> (for not equal). X) or Call Error(X) where ‘error message’ is an optional character string enclosed within single quotes and X is the value of the parameter which caused the error. A value of -3. Function abc(X. EES will display that string.4) When this function is called. such as F1 or E4 follows the XXX. Calculations have been halted because a parameter is out of range. The format of the Error procedure is Call Error(‘error message’. If a formatting option. The value of X supplied to the Error procedure replaces XXX. otherwise a default format will be applied. supplied.000E0 was supplied. If the error message string is not provided.EES Functions and Procedures Chapter 5 F:=1 Repeat F:=F*N N:=N-1. X) abc:=Y/X end g:=abc(-3. the following message will be displayed and calculations will stop: X must be greater than 0.THEN .'.Y) if (x<=0) then CALL ERROR('X must be greater than 0. The ERROR procedure will most likely be used with an IF . the value of X will be accordingly formatted. inserting the value of X in place of the characters XXX.ELSE statement as in the following example. The value of the parameter is XXX. If an error string is provided. Until (N=1) Factorial:=F End Y= FACTORIAL(5) { Y will be set to 120 when this statement executes} Error Procedure The Error procedure allows the user to halt calculations if a value supplied to a function or procedure is out of range. A value of XXXE4 was 161 . EES will generate the following error message when it executes the ERROR procedure. as in the example below. automatic format is assumed. If a warning string is provided. The WARNING procedure generates a warning message which is placed in the warning message que and displayed when calculations are completed. otherwise a default format will be applied. The WARNING procedure has the following formats: CALL WARNING(X) CALL WARNING('My warning message XXXF1'. Note: To insert a string. or if a $Warnings On directive is provided. use $ as the formatting option following the XXX. The sum was XXXA1 '. Function abc(X.ELSE statement as in the following example. but if it is provided.Chapter 5 EES Functions and Procedures Warning Procedure The WARNING procedure can be used only within an internal function or procedure. "A warning message was issued due to the value XXX in XXX. it must be placed within single quote. such as A3. If no format is supplied. If a formatting option. the value of X will be accordingly formatted.-4) 162 .THEN . If a warning string is not provided.Y) G:=X+Y if (G<=0) then CALL WARNING('The sum of X and Y should be greater than zero. as in the example above. The WARNING procedure is similar to the ERROR procedure which halts calculations when some user-specified error condition is encountered. X is the value of the parameter which initiates the warning. rather than a numerical value.G) abc:=G end g=abc(3. the variable X is optional. EES will display that string. inserting the value of X in place of the characters XXX." Here XXX is the parameter value provided in the WARNING call statement and YYY is the function or procedure name in which the Call WARNING statement appears. for example: CALL WARNING('My error string is XXX$'. EES will generate the following generic warning message.X) CALL WARNING('My warning message') The warning string is optional. F1 or E4 follows the XXX.X$) The WARNING procedure will most likely be used with an IF . If a warning string is provided. Note that the message que is displayed only if the 'Display Warning Messages' checkbox in the Options tab of the Preferences dialog is selected. every variable in the module. The Module / Subprogram is supplied with inputs and it calculates outputs. using blocking and iteration as necessary. For example. including each input and output in the 163 . B : X. X. The formal format of the Module statement uses a colon in the argument list. the following statement would access the Testme Module or Subprogram. MODULE Testme(A. At this point. it should not be used in the CALL statement. B. EES Modules / Subprograms employ equalities rather than assignment statements as used in Procedures. In most cases. First. this is the preferred way to use Modules and Subprograms. B. However. the colon which separates inputs from outputs is irrelevant and it can be replaced with a comma (or semi-colon for the European numerical format). you must be curious as to the difference between a Module and a Subprogram. B : X. Y) or SUBPROGRAM Testme(A. Y) In this case. the number of values that must be supplied to have the number of equations equal to the number of unknowns within the module. or stated another way. it opens a new workspace and it then solves the equations in the SUBPROGRAM. The format of a Module / Subprogram is similar to that for an internal Procedure. When EES encounters a CALL statement to a MODULE. The number of arguments provided to the left of the colon is the number of degrees of freedom in the module. When EES encounters a CALL statement to a SUBPROGRAM.1. The calculated variables appearing as parameters in the SUBPROGRAM statement are returned to the main program. As a consequence. CALL Testme(77. X. Similarly if a colon is not used in the MODULE /SUBPROGRAM statement. Y) A Module / Subprogram is accessed with a CALL statement. Y) or SUBPROGRAM Testme(A.Y) Note that if a colon is used to separate the inputs and output in the MODULE / SUBPROGRAM statement. An example of a formal Module / Subprogram statement is MODULE Testme(A.5. X. EES understands that there are two inputs (A and B) and two outputs (X and Y). it does not matter what variables are specified as inputs as long as the appropriate number are specified. it must also be used in the CALL statement. The steps necessary for this process are as follows. The difference is explained below. In fact. The following form for the Module / Subprogram statement is equivalent to the format shown above. it transparently grafts the equations in the module into the equations in the main program.EES Functions and Procedures Chapter 5 Modules and SubPrograms Modules and Subprograms can be considered to be stand-alone EES programs that can be called from the main EES program. The important difference between a Procedure and a Module (or Subprogram) is that the module is composed of equality statements whereas the Procedure is composed of assignment statements. Subprograms are more reliable. 164 . You will need to test both forms to determine which is better for your application. Note that the guess values and limits for the EES variables appearing in the CALL statement in the main program override the specified guess values and limits for the variables in the argument list of the MODULE statement. are merged into the EES program at the point at which it is called. the equations in the module may not necessarily be called in sequence. but with a different qualifier for the variable names in the module. In fact. The $COMMON directive may be used to pass variables that are defined in the main program to a Module / Subprogram. the process is repeated. and order independent equation input. Finally. when needed. this is rarely the case. but it can provide iterative solutions to implicit equations. The Module / Subprogram is terminated with an END statement.Chapter 5 EES Functions and Procedures MODULE statement. You can view the equations in the order that EES has rearranged them in the Residuals window. EES then uses its efficient blocking techniques to reorganize the equations for optimal solution. As a result of this reorganization. Variable information for Modules / Subprograms is accessible with the Variable Info command. the following equation in the Residuals window Turbine\2: h2=h1+Q/m would indicate that the equation h2=h1+Q/m originated from the second call to the Turbine module.000 in the Professional version) so rather large problems can be developed. just as for the procedure. just as in the main part of EES. with their renamed variables. The net effect is that a copy of all of the equations in the module are merged into the main EES program each time a CALL statement is encountered. For example. The local variables in a Module / Subprogram are always real regardless of the Complex Numbers setting. Equations from a module are identified with the module name followed by a backslash and then the call index number. Tests thus far have shown that Modules tend to solve a problem more efficiently but in some cases. A CALL statement is used to call the Module / Subprogram. EES currently allows up to 6000 equations (10. Variables values are normally passed to the module through the argument list. If the module is called a second time. a Module / Subprogram cannot support logic constructs such as IF THEN ELSE. all of the equations in the module. Consequently. Then EES adds one equation for each input and output which sets the value of the parameter in the calling program to the value of the value in the module. So which is better? Modules or Subprograms. is renamed with a unique qualifier that EES can recognize. The library files can be automatically loaded if they are placed in the USERLIB subdirectory. Alternatively.EES Functions and Procedures Chapter 5 Note that the local variables for each call to the TestMe module will be shown only if the "Show function/procedure/module values" control in the Options tab of the Preferences dialog is selected. just like Internal Functions and Procedures.HTM filename extension. Modules and Subprograms can significantly increase the capabilities of your EES programming. Help can be included within the Module / Subprogram (using the same syntax as used in Procedures) or it can be supplied with a separate help file having the same filename as the library file with a .HLP or . a $INCLUDE directive can be used to transparently load a library file. Modules / Subprograms may be stored as library files. 165 . The simplest way is to include the help text as a comment within the EES library file.Y). the user overrides the dummy fRK4 function by entering another fRK4 function in the EES Equations window.Y) dX where f(X. corresponding to the initial value of X. and/or modules into the Equations window. To create a Library file. The RK4 and fRK4 functions 166 . In this case.LIB filename extension. Solve or Solve Table. the final value of X (HighX).Chapter 5 EES Functions and Procedures Library Files EES allows files containing one or more functions.hlp file can contain ASCII text or it can be a Windows Help file. In an actual application. RK4 requires 4 parameters: the initial value of X (LowX). The Library file concept is among the most powerful features of EES because it allows the user to easily write customized subprograms for personal use or for use by others. are the help text that will be displayed when the user selects the Info button in the Function Info dialog window as shown in the example below.Y) is any function involving the dependent variable Y and independent variable X. EES will be able to recognize the file type from its contents. Then save the file with a . followed by the name of the function. A Library file has a . it will automatically load all of the functions. Y must have a known initial value. Library subprograms will not displayed in the Equations window. The . Alternatively.LIB file as a placeholder. There are several ways to provide the help information. The RK4 function calls another function. Library files can also be loaded manually with the Load Library command in the File menu and with the $INCLUDE directive. procedures. procedures. Subprograms in library files can provide help information in the Function Info dialog window. procedure or module followed by a carriage return.htm file should be designed to be read by a browser. The lines following.LIB filename extension using the Save As command. Y0. and the value of Y at X=LowX (Y0). fRK4(X. The function returns the value of Y at X=HighX. When EES starts. Compile the equations using Check.htm. A dummy fRK4 function is provided in the RK4. up to the closing comment brace.hlp or . procedures or modules (subprograms) to be saved as Library files. The Runge-Kutta algorithm is used to numerically solve a differential equation of the form: dY = f (X . a separate help file can be supplied with the same name as the library file and a filename extension of . the step size (StepX). just like the built-in functions. They are used just like EES built-in functions. The following example uses a library file to provide a fourth-order Runge-Kutta numerical integration function in EES. enter one or more functions. the first character after the opening comment brace must be a $. and modules in the library files which reside in the USERLIB\ subdirectory. The Runge-Kutta algorithm has been implemented as a general purpose library function called RK4. The . to provide the value of dY/dX for given X and Y values. 20: RK4:=Y END 167 . This function is used with the RK4 function to solve differential equations with the Runge-Kutta method.HighX.StepX. See the RK4 function for additional information.5*k1) k3 := StepX*fRK4(X+0. you would see the following statements.EES Functions and Procedures Chapter 5 have been saved in a library file called RK4. The user must supply the fRK4 function. FUNCTION fRK4(X.Y+k3) Y := Y+k1/6+(k2+k3)/3+k4/6 X := X+StepX GOTO 10.Y+0. Y0 is the value of Y when X is equal to LowX. If you were to open the RK4. Note how the functions provide help text as a comment with the $filename key.Y)*StepX k2 := StepX*fRK4(X+0.Y) function in the Equations window to evaluate dY/dY for your problem.5*k2) k4 := StepX*fRK4(X+StepX.5*StepX. EES will load these functions when it starts.Y0) {$RK4 RK4 is a general purpose function which solves a first-order differential equation of the form dY/dX=fRK4(X.} fRK4:=(Y+X)^2 END FUNCTION RK4(LowX. RK4 requires four input parameters. HighX is the final value of independent variable X and StepX is the step size.LIB file in EES.} X := LowX Y := Y0.1*StepX 10: IF (X>HighX-Tol) THEN GOTO 20 k1 := fRK4(X.LIB in the USERLIB\ sub-directory. Enter a fRK4(X.Y) {$fRK4 fRK4 is a user-supplied function to evaluate dY/dX.Y) supplied by the user to evaluate dY/dX at specified values of X and Y.Y) using the Runge-Kutta 4th order algorithm. LowX is the initial value of independent variable X. The RK4 function calls function fRK4(X. Tol := 0.Y+0.5*StepX. 667 in the Solution window.0. This algorithm works fine for differential equations it fails when there are combined algebraic and differential equations that must be solved. 0 Suppose you wish to numerically solve the equation You provide a function fRK4 to evaluate the integrand. The built-in Integral function is more efficient for solving differential equations and integrals than the Runge-Kutta method described in the above example.1. all that would be needed is: FUNCTION fRK4(X.Y) fRK4:=X^2 END V=RK4(0.Chapter 5 2 EES Functions and Procedures X 2dx using the RK4 function.2. EES will display V=2. Your function overrides the fRK4 function in the RK4 library file.0) When you solve this problem. Note: The RK4 function solves an integral or differential equation using the Runge-Kutta algorithm. Assuming RK4 was in the USERLIB\ subdirectory when EES was started. 168 . which is X2 in this case. D=6 G=TESTCOMMON(3) $COMMON should only be used with functions.C. procedures. The $COMMON directive must directly follow the FUNCTION. FUNCTION TESTCOMMON(X) $COMMON B. or MODULE declaration on a line by itself. procedures. C=5. and modules appearing in the Equations window.C. It differs in that information flow is one-way.D {variables B. PROCEDURE. and D are from the main program} TESTCOMMON:=X+B+C+D END B=4. Variable values can be passed from the main program to the function or procedure. as in the following example. and modules.EES Functions and Procedures Chapter 5 $COMMON Directive The $COMMON directive provides a means for passing information from the main program to internal functions. This directive is similar in concept to the COMMON statement in FORTRAN. Variables appearing in the $COMMON statement are separated with commas. However. Use of $COMMON provides an alternative to passing values as arguments. the function or procedure may not assign or alter these values. 169 . It should not be used with library functions. However.TXT. . Nested use of the $INCLUDE directive is not supported so that the text file must not include any $INCLUDE statements.FDL or . EES internal functions.HLP or . . EES will automatically load the referenced library file if it is not already loaded.FDL. Equations can also be entered from a file with the Merge command in the File menu.HTM will also be loaded automatically. procedures. It is best to place the $INCLUDE directives at the top of the Equations Window to ensure that the directive is processed before compilation of the equations is initiated. 170 .Chapter 5 EES Functions and Procedures $INCLUDE Directive The $INCLUDE directive provides an automatic method for loading a library file or ASCII text file containing EES equations.TXT. The $INCLUDE statement must be on a line by itself. EES will expect the file to be a library file of a type corresponding to the filename extension. However. .TXT.LIB. it will provide the opportunity to browse so that you can locate it. EES will look in the current directory. starting in column 1. Note that library files can also be loaded automatically when EES is started by placing them in the USERLIB subdirectory or by applying the Load Library command. . the equations and the variables associated with these equations will be hidden.. and modules are recognized with the . The difference between the Merge command and the $INCLUDE directive is that equations entered with the Merge command are placed directly into the Equations window as if they were typed and they remain visible. EES will include these equations with others in the Equations window during compilation. Syntax errors can not be identified in the library file so care should be taken to ensure the equations are correct before saving the library file.DLF.DLP extension. or . The text entered with the $INCLUDE directive will be hidden.LIB extension.TXT Files If the filename extension is . whereas external functions use a . The format is: $INCLUDE FILENAME FILENAME is the filename including the filename extension which can be one of . e. The filename should also include the complete path name.LIB. EES expects FILENAME. Library Files If the filename extension is . if a path name is not provided.DLF extension and external procedures use either the . . . If EES is unable to find the file.DLF.TXT to be an ASCII text file containing EES equations. Use of the $INCLUDE directive for very large problems can eliminate this problem on slower machines.DLP.FDL. Help files having the same name as the library file and a filename extension of . C:\EES32\myDefn.g. or . Note that the speed of editing in the Equations window is reduced as the size of the text in the Equations window increases.DLP. ..2. EES will assume that the data should be written with header information in the EES Lookup file format that can be read directly by the Open Lookup Table command.1.00000000E+00. The format of the $Export Directive is $Export /A 'FileName'. and its display format. the output will be placed as delimited text on the clipboard. X[1. FileName can be either a string constant (within single quotes) or a string variable containing the name of the file that the values will be written to. Var2. The /A is optional. If the filename extension is .CSV (commaseparated values). If present.B.csv will be written with the values 5. If filename is specified to be 'CLIPBOARD'. such as a spreadsheet program...5]. Example: T$='C:\temp\junk. X[1. but the $Export directive is much more convenient. A maximum of 32760 characters can be written to the clipboard. Var1.25000000E+02 171 . If the filename extension is .EES Functions and Procedures Chapter 5 $EXPORT Directive The $Export directive provides a simple way of writing selected variables to an ASCII file.C After solving. it indicates that the values should be appended to the existing file. In this format.csv' A=5 B=A^2 C=A^3 $Export T$ A. Saving the Lookup table as a . The Lookup command can be used to write (as well as read) values in the Lookup Table. This file can then be read by the Open Lookup Table command in EES or by another application.5] represent variables that are used in the main section (not in a Module) of your EES program.CSV file also provides export capability. its units.50000000E+01. The $Export directive can be placed anywhere in the Equations Window. the data will be written as a CSV ASCII text file that is easily recognized by spreadsheet applications. Var2. file C:\temp\junk.TXT. Note that array range notation is supported. each value is separated by a list separator character. Var1. and they will be evaluated in the order that they occur in the Equations Window. The header information will include the name of the variable. if it exits. Multiple $Export directives are permitted. . X[2]. C After solving. X[1. S$. X[1. If FileName is specified to be 'CLIPBOARD'. Example: File text. and C will be set to the values in the file...csv' X[1..5]. Note that array range notation is supported as are string variables. The $IMPORT directive can be placed anywhere in the Equations Window. and they will be evaluated in the order that they occur in the Equations Window. The data could be provided from a file written using the $Export directive or from another application. Var2. the values of the variables will be read from the clipboard in text format. X[3]. 172 . B$. Multiple $IMPORT directives are permitted. The format of the $IMPORT Directive is $Import FileName. variables X[1]. B$.csv contains the following data: 1.2. The combination of $EXPORT and $IMPORT directives provides a convenient way to transfer information from one EES program to another. Var1.Chapter 5 EES Functions and Procedures $IMPORT Directive The $Import directive provides a simple way of reading selected variables from an ASCII file.4 5 'string 1' 'string 2' 6 $IMPORT 'text.. Var1. FileName can be either a string constant (within single quotes) or a string variable (ending with a $) holding the name of the file that the values will be read from.5] represent variables that are used in your EES program.3]. 3. A$.. Var2. A$. To avoid having to set a fixed upper limit on the number of inputs.DLP and .FDL filename extension are assumed to be compiled functions or procedures and they are automatically loaded. but it is not possible to anticipate the needs of all users. The 16-bit version of EES can only use 16-bit DLLs and the 32-bit version can only use 32-bit DLLs. There are two formats for compiled procedures identified by . Compiled functions and procedures can (optionally) be setup to work with the Function Info command (Options menu) so that they provide an example and detailed help when it is requested. . Compiled Functions and Procedures EES Compiled Functions (.DLF files) Compiled functions can be written in C. The 32-bit version of EES will display (32-bit) on the same line as the version number and in the main window title. The function statement header. the input information to a compiled function is implemented as a linked list. This capability gives EES unlimited flexibility and it is among its most powerful features.1. Pascal. A remarkable feature of EES is that the user can add (and later remove) functions and procedures written in any compiled language.DLF. Instructions for preparing both DLL types are provided in this chapter. Any files having a . If you are not sure as to whether you are using the 16-bit or 32-bit version of EES. Functions return a single value whereas procedures may return multiple values. The 16-bit version will run under any Windows operating system. it examines the files in the EES USERLIB\ subdirectory. start the program and examine the startup screen.CHAPTER 6 __________________________________________________________________________ __________________________________________________________________________ EES has an extensive library of built-in functions. The 32-bit version of EES can be used with Windows 95 or NT.DLP. or . C++ or FORTRAN. C. The following sections of this chapter provide detailed information and examples of compiled functions and procedures. C++. Compiled functions and procedures are written as dynamic link library (DLL) routines under the Windows operating system10. must have a specific format. The function name to be referenced in EES equations is the filename (without the extension). These compiled routines may have any number of arguments. but it executes more slowly than the 32-bit version.FDL filename extensions. The linked list record or structure consists of an extended precision value and a pointer to the next input. however.DLF. When EES is started. Compiled functions are identified with a . The compiled routines are used in exactly the same manner as internal EES subprograms. The last input 10 Note that there are both 16 and 32-bit DLLs in the Windows Operating System and they are not interchangeable. 173 . or any language which can produce a dynamic link library (DLL). External routines can also be loaded using the Load Library command in the File menu or with the $INCLUDE directive. but not with Window 3. such as Pascal. 0 (32-bit). stdCall. Only the function result will be used by EES.. S is a standard 255-character Pascal string. The compiled function should check that the number of inputs supplied in the linked list is equal to the number the function expects. EES will pass this string to the external routine. FuncName:=Value. next: ParamRecPtr. must be the same as the filename. called FuncName in the above example.. If the first parameter provided in the EES function is a string (within single quotes). exports FuncName. 11 The stdCall keyword is required for Delphi 3. begin .0 (32-bit) is as follows: library XTRNFUNC. EES will terminate calculations and display S as an error message. these changes are local and will be disregarded by EES. It is not needed for Delphi 1. A skeleton listing of a compiled function written in Borland's Delphi 1. S should be set in the external routine to an appropriate error message. {$N+} type ParamRecPtr = ^ParamRec. Inputs:ParamRecPtr): extended. Some compiled languages. To be recognized by EES. ParamRec = record { defines structure of the linked list of inputs } Value: extended. such as FORTRAN 77 do not support pointers so . The function statement has three arguments.Chapter 6 Compiled Functions and Procedures points to nil. begin end. function FuncName (var S:string.) Although the values of the inputs may be changed in the function. Mode:integer. end. 11 The major concern is the function header. (The PWF function example in the next section shows how this checking can be done.0 (16-bit) or Delphi 3.FDL format described in this chapter should be used in this case. the function name. The first character contains the actual length of the string. If the length of S is not zero. If an error is encountered. export.DLF compiled functions cannot be written in these languages The .0 (16-bit) 174 . { Funcname must be extended precision } end. S can be used for both input and output. return (v). The function may have one or more inputs.not needed in Borland C++ { return TRUE. Currently. struct ParamRec *next. } Note that the pascal keyword must be provided to ensure that the calling parameters are in an order that will be understood by EES. WORD wDataSeg. struct ParamRec *FirstInput) { …. } int far pascal LibMain //DLL entry point for initiation (HINSTANCE hInstance. LPSTR lpstrCmdLine) { if (cbHeapSize) UnlockData(0). }. struct ParamRec *FirstInput). The next field of the last input will be a null pointer (nil). 175 . The function should count the inputs to be sure that the number supplied is as expected and issue an error message in S if this is not the case. then EES is requesting that the function return in S an example of the function call.h> #include <stdlib. WORD cbHeapSize. as indicated by the ParamRec structure. int Mode. // Use extern "C" to prevent C++ name mangling extern "C" { long double far pascal _stdcall _export FUNCNAME (char* S. …. then the function should simply return the function value.h> #define EXAMPLE=-1. return TRUE. Each input consists of a value (extended precision) and a pointer to the next input. long double far _export _stdcall pascal FUNCNAME(char* S. EES does not use the return value of Mode. int Mode. If Mode>=0. If Mode=–1.Compiled Functions and Procedures Chapter 6 Mode is an integer set by EES. } struct ParamRec { long double value. } int far pascal WEP(int nParam) //Windows exit procedure .h> #include <string. Inputs is a pointer to the head of a linked list of input values supplied by EES. A skeleton listing of a compiled function written in Borland's C++ follows: #include <windows. Pr. Soave. Vol.g. The third parameter is optional. respectively. EES treats this compiled function just like any of its internal functions.i. It's EESY! 12 13 Duffie. J. The dimensionless enthalpy departure is defined as (h[ideal]h)/(R Tc). pp. w) returns the dimensionless fugacity coefficient (fugacity / pressure).e. Chem. Shown on the following pages is the complete listing for the PWF compiled function written in Borland’s Delphi 3. w) return the dimensionless enthalpy and entropy departures. EnthalpyDep(Tr.. Tr is the reduced temperature. PWF is the present worth of a series of N future payments which inflate at rate i per period accounting for the time value of money with a market discount rate per period of d. called PWF. Pr. R is the gas constant and Tc is the critical temperature. 1197-1203. Chapter 11. 2nd edition.A. and w is the acentric factor. h[ideal]-h is the difference in enthalpy between an ideal gas and a real gas at the same temperature and pressure. Wiley and Sons. the ratio of the specific volume of the gas to the specific volume of an ideal gas at the same conditions. Pr. w) returns the compressibility of a gas. J.DLF file on the EES disk. Compressibility(Tr. Science.Chapter 6 Compiled Functions and Procedures The PWF Compiled Function EES does not have any internal economic functions.. These functions implement a generalized equation of state using Redlich-Kwong-Soave equation13. i. Solar Engineering of Thermal Processes. 27. W.A.d) = Σ N j=1 1+i j–1 j 1+d = 1 1+i d –i 1– 1+d N 1+i N if i ≠ d if i = d where N is the number of periods (e. The dimensionless entropy departure is similarly defined as (s[ideal]-s)/(R). has been written to do this economic calculation. 1972 176 .0 (32-bit version). An economic function called the present worth factor (PWF)12 has been added as a compiled function. expressed as a fraction A compiled function. The equation for PWF is PWF(N. expressed as a fraction d is the market discount rate per period. Do you need a function which EES doesn't include? Write your own. Pr is the reduced pressure. Eng.. Four other compiled functions are included with EES. w) and EntropyDep(Tr. and Beckman. FugCoef(Tr. Pr. years) i is the interest rate per period. G. 1992. This function is stored in the PWF. while (P <> nil) do begin N := N + 1. begin N := 0. begin PWFCalc:=0. exit. var N: integer. {CountValues} function PWFCalc: extended. CountValues := N. end. Periods := round(P^. stdcall. Inputs:ParamRecPtr):extended. function CountValues (P: ParamRecPtr): integer. type ParamRecPtr=^ParamRec. end. CountValues := N. end.Compiled Functions and Procedures Listing of the PWF Compiled Function in Borland’s Delphi 3. V: extended. function CountValues (P: ParamRecPtr): integer. uses SysUtils.next end. ParamRec=record Value:extended. Mode:integer. export. {CountValues} Chapter 6 function PWF(var S:Shortstring. begin N := 0. interest. var Periods. var P: ParamRecPtr. end. P := P^. if (Periods < 1) then begin S := 'The number of periods for the PWF function must be >0.0 library PWFP. {in case of error exit} S := ''.next end. NArgs: integer. P := Inputs.'. discount: extended. {$N+} const doExample = -1. P := P^. next:ParamRecPtr. var N: integer. Classes.value). 177 . while (P <> nil) do begin N := N + 1. DLL filename extension for the compiled code. end. end. begin {no initiation code needed} end.DLF extension. end.next.'.Interest. Compiled functions must have a . discount := P^. a dynamically-linked library routine is created. exit. end.next. The compiler automatically generates a . {PWF} exports PWF.Discount) 178 . end.0. exit.exp(Periods * ln((1 + interest) / (1 + discount)))) else PWFCalc := Periods / (1 + interest). if (CountValues(Inputs)<>3) then S := 'Wrong number of arguments for PWF function. interest := P^. When this Pascal code is compiled with the Borland Delphi 3.value. P = PWF(Periods. It does this by the filename extension. EES must distinguish compiled functions from compiled procedures. P := P^. {PWF} begin PWF:=1.interest) * (1 .Interest. if (interest <> discount) then PWFCalc := 1 / (discount .'. Access the external PWF function by a statement of the following form in your EES program. Rename the compiled file so that it has a .' else begin PWF:=PWFCalc. end.value.Chapter 6 Compiled Functions and Procedures P := P^. if (interest >= 1) or (interest < 0) then begin S := 'The interest rate is a fraction and must be between 0 and 1. if (Mode = doExample) then begin S := 'PWF(Periods. exit.DLF filename extension. if (discount >= 1) or (discount < 0) then begin S := 'The discount rate is a fraction and must be between 0 and 1.Discount)'. The .DLP external procedure formats and provide a simple example which should serve as a model. Y.FDL filename extension. or algebraic expressions. The major difference between functions and procedures is that procedures can return one or more values.FDL format passes inputs and outputs in double precision floating point arrays.) are to be determined given one set of independent variables (e. appearing to the left of the colon. Inputs may be numerical constants. the user supplies the function or procedure in compiled form as a Windows dynamically linked library routine. temperature and pressure). X. Y. Note that the CALL statement used to access compiled functions is identical in format to the CALL statement used for internal EES Procedures.DLP. Z) where procname is the name of the procedure ‘text’ is an (optional) text string that will be passed to the procedure. There are two formats for external procedures and they are identified to EES by their filename extension. etc. Procedures are useful. 179 . C++. There may be one or more inputs. External procedures using arrays to hold the inputs and outputs must have a .g. entropy. B : X. The two formats differ in the manner in which EES exchanges information with the external routine.FDL and . (See Chapter 7). External procedures are written as 32-bit dynamic link libraries (DLL's). There should be one or more outputs to the right of the colon. EES identifies the format by the filename extension which must be .DLP format passes inputs and outputs as linked lists (as in the . whereas a function returns a single value.g. volume. Compiled procedures are accessed from EES with the CALL statement which has the following format. In either case. enthalpy. and Z are outputs determined by the procedure. CALL procname(‘text’. and Pascal procedures can use either format.. The following two sections describe the . The . C. separated by commas. This is the usual case when providing DLLs written in FORTRAN.FDL or .DLP files) EES compiled procedures are very similar to EES compiled functions. This text can either be a string constant enclosed in single quote marks or a string variable.FDL and .DLF functions) so there is no limit to the number of inputs and outputs. EES variable names. A.. String variables cannot be provided for outputs. separated by commas. String variables cannot be supplied as inputs.Compiled Functions and Procedures Chapter 6 EES Compiled Procedures (. A and B are inputs. for thermodynamic property evaluations where multiple properties (e. for example. Outputs must be EES numerical variable names. If S is defined.1000].NOUTPUTS. MODE =0 and S need not be defined. it will be displayed in the EES error message. Up to 1000 variables can be passed in the argument list of external functions and procedures using array element notation. as noted above.FDL Format .. Note that the two !DEC$ATTRIBUTES directives should be included in the main program. and NOUTPUTS are the number of inputs and outputs provided by EES.0 compiler SUBROUTINE MYPROC(S. NINPUTS The external program must be compiled and linked as a dynamic link library (DLL) routine.FDL library using the Digital Visual FORTRAN 6. The routine should check to see if these agree with the expected number of inputs and outputs and return an error condition (MODE>0) if this is not the case. If the first parameter in the EES Call statement is a text string (within single quotes). The code may differs slightly depending on which compiler is being used. as EES will allocate memory as necessary.e. When EES calls the subroutine with MODE =-1. S is also used to return user-supplied error messages if necessary. 32-bit .Chapter 6 Compiled Functions and Procedures Compiled Procedures with the . it is asking for an example of the calling sequence of this procedure from EES to be placed in S so that it can be displayed in the Function Info Dialog window. A new project workspace is selected as a Dynamic Link Library.OUTPUTS) !DEC$ATTRIBUTES ALIAS:'MYPROC' :: MYPROC !DEC$ATTRIBUTES DLLEXPORT :: MYPROC INTEGER(4) MODE. The FORTRAN sources file(s) are inserted into the workspace and compiled with the standard options. i.0 is most easily done within the Microsoft Developer Studio environment.FDL format is illustrated by the following FORTRAN subroutine fragments. The output filename in the Link settings should be set to 180 . If an error is detected in the subroutine. There is no inherent limit on the number of elements of these arrays. Results calculated by the subroutine are placed in the OUTPUTS. EES will supply the values in the INPUTS array. INPUTS and OUTPUTS are arrays of double precision (REAL*8) values. NOUTPUTS REAL(8) INPUTS(50).. The compiling procedure differs among different languages and compilers. Creating a 32-bit DLL with Digital Visual Fortran 6. EES will pass this string to the external program in S. In normal operation.a FORTRAN Example The .INPUTS. OUTPUTS(50) CHARACTER(255) S … OUTPUTS(1)=… … RETURN END S is a null-terminated C-style character string containing 255 characters. X[1.NINPUTS.MODE. MODE should be set to a value greater than 0 to signal EES to terminate calculations. NINPUTS. Alternatively.DLL should be changed to MYPROC. and difference of two input values.FDL after building the dynamic link library project. sum. dividend. 181 . The simple FORTRAN program listed below provides the product. the default filename MYPROC.FDL where MYPROC is the name that will be used in the EES Call statement. This program should provide a model for writing external EES procedures in FORTRAN.Compiled Functions and Procedures Chapter 6 MYPROC. -1) GOTO 900 IF (NINPUTS.2) GOTO 100 IF (NOUTPUTS.NOUTPUTS.NINPUTS.NE. EES WILL DISPLAY THE STRING IN THE ERROR MESSAGE.4) GOTO 200 DO CALCULATIONS X=INPUTS(1) Y=INPUTS(2) IF (ABS(Y).NE. 200 300 900 C. C.B.OUTPUTS) The following two lines are specific to Microsoft Power Station 4. THEN EES WILL DISPLAY THE MODE NUMBER IN AN ERROR MESSAGE. THE C AT THE END OF THE STRING INDICATES C-STYLE S='MDASF REQUIRES 2 INPUTS'C MODE=1 RETURN CONTINUE S='MDASF EXPECTS TO PROVIDE 4 OUTPUTS'C MODE=2 RETURN CONTINUE S='DIVISION BY ZERO IN MDASF'C MODE=3 RETURN CONTINUE PROVIDE AN EXAMPLE OF THE CALLING FORMAT WHEN MODE=-1 S='CALL MDASF(X. C. C.0 !MS$ATTRIBUTES ALIAS:'MDASF' :: MDASF !MS$ATTRIBUTES DLLEXPORT :: MDASF Replace INTEGER(4) with INTEGER*2 for a 16 bit DLL in the following line INTEGER(4) MODE. 100 C.Y:A. IF S IS EQUAL TO A NULL STRING. C.MODE. C.EQ.INPUTS.1E-9) GOTO 300 OUTPUTS(1)=X*Y OUTPUTS(2)=X/Y OUTPUTS(3)=X+Y OUTPUTS(4)=X-Y MODE=0 S=''C RETURN CONTINUE ERROR: THE NUMBER OF INPUTS ISN'T WHAT THIS SUBROUTINE EXPECTS NOTE: SET MODE>0 IF AN ERROR IS DETECTED.C. IF S IS DEFINED.Chapter 6 Listing of the FORTRAN MDASF Program Compiled Functions and Procedures C. C. NINPUTS. OUTPUTS(25) CHARACTER(255) S IF (MODE.D)'C RETURN END C. C. NOUTPUTS REAL(8) INPUTS(25). SUBROUTINE MDASF(S.LE. 182 . ) The code checks to make sure that the number of inputs and outputs provided in the CALL statement are what the routine expects before it does the calculations and sets S to an error message if this is not the case. begin N := 0.DLF files) described previously. Mode: integer. Both are provided for backward compatibility and complete flexibility. There is essentially no difference in efficiency between the two formats. S. (This is the same program used in the . a linked list of output values. uses SysUtils. 183 . Compiled procedures using the . in addition to a linked list of input values. Outputs is a linked list of extended values which provides the results of the calculations to EES in the order in which they appear in the CALL statement. end.DLP) in Borland’s Delphi library MDASP.DLP Format . and thereby is not suitable for use with FORTRAN. called MDAS (an acronym for MyDearAuntSally) which provides the product. ParamRec=record Value:extended. Inputs. type ParamRecPtr=^ParamRec. and difference of two input values.FDL example. Mode. The .FDL format described in the previous section was illustrated with FORTRAN. Example Compiled Procedure (. Shown on the following page is a complete listing of an EES compiled procedure. but it can be implemented in any compiled language.Compiled Functions and Procedures Compiled Procedures with the . The only difference is that a procedure must have. while (P <> nil) do begin N := N + 1. The calling sequence for a compiled Pascal procedure with the .DLP calling format described in this section uses linked lists for inputs and outputs. var N: integer. Outputs: ParamRecPtr). dividend. Classes.DLP format are very similar to compiled functions (. next:ParamRecPtr. {$N+} const Example = -1. and Inputs are identical to their counterparts for the EES compiled functions. sum. function CountValues (P: ParamRecPtr): integer.DLP format has the following form procedure procname (var S: string.a Pascal Example Chapter 6 The . P^. export. P2: extended. var P1.Value. stdcall. P: ParamRecPtr. Inputs.Value := P1 / P2.P2.next. {doCall} begin {MDAS} if (Mode = -1) then S := 'CALL MDAS(In1.Out3. P1 := P^. S:=''. end.'. P := Outputs. if (CountValues(Outputs) <> 4) then begin S := 'Wrong number of outputs for MDAS.Value := P1 + P2.Value := P1 . P^. end. procedure MyDearAuntSally. P^. P2 := P^.next. P := P^. end.Out4)' else begin if (CountValues(Inputs) <> 2) then begin S := 'Wrong number of inputs for MDAS. exit.value. CountValues := N. {CountValues} procedure MDAS(var S:Shortstring.next. begin {no initiation code needed} end. {MDAS} exports MDAS.Out2. end. begin P := Inputs. P := P^.'.next end. P := P^.In2:Out1. end. P^.Chapter 6 Compiled Functions and Procedures P := P^.next. end. exit. Mode:integer. MyDearAuntSally.Outputs:ParamRecPtr). P := P^. 184 .Value := P1 * P2. begin StrCopy(Names. {***********************************************************************} {There are 2 functions. names are separated with commas} procedure DLFNames(Names : PChar). The character string is filled with the names of the routines of each type that are contained in the DLL file. DLFName.DLL) EES recognizes three different types of externally compiled files. stdcall. The external file can have any name but it must have a . They have one argument which is a character string. {***********************************************************************} type ParamRecPtr = ^ParamRec.DLF. ParamRec = record Value : Extended. DLPNames.DLP.dynamically-linked function DLP . Next : ParamRecPtr. only one external routine could reside in a file. end. A short example in DELPHI 5 code follows.DLL file and their type (DLF.dynamically-linked procedure FDL . const doExample = -1. it is also possible to place one or more external routines in a single file and this single file can contain all three types of external routines.dynamically-linked procedure with calling sequence accessible from FORTRAN Originally. library MYEXTRNLS {This DLL file contains two DLF functions and one DLP procedure} uses SysUtils.Compiled Functions and Procedures Chapter 6 Multiple Files in a Single Dynamic Link Library (. A zero length string is used to indicate that there are no files of that type. If this file is placed in the USERLIB subdirectory. and FDLNames that do nothing but return the calling names of each routine type in the DLL file. . A comma separates each file name. EES will automatically load all the external routines in the file at startup. {***********************************************************************} 185 . DLPNames. export.DLL filename extension. The filename extension (. end. DLP.FDL) identified the type of externally compiled file and the name of the external routine had to be the same name as filename (without the extension). The three types are: DLF . or FDL) because the calling arguments differ for each type. The mechanism for telling EES the names and types of the external routines is to provide three short routines in the DLL file with names DLFNames. or . myFunc2'). and FDLNames must be exported in the DLL. However.'myFunc1. EES must know the names of the external routines in the . . 186 . begin {Code for myFunc1} .. begin StrCopy(Names. begin {Code for myDLP} .. begin StrCopy(Names.. end.. Inputs. myFunc2. export. begin {Code for myFunc2} . {***********************************************************************} function myFunc1 (var PString: ShortString.Chapter 6 {There is one DLP procedure} procedure DLPNames(Names : PChar). stdcall. end. Mode: integer.. end.''). Inputs: ParamRecPtr): extended. stdCall. Mode:integer. end. stdCall.. export. DLPNames.. {myDLP} {***********************************************************************} exports DLFNames. {myFunc1} {***********************************************************************} function myFunc2 (var PString: ShortString. Mode: integer..'myDLP'). end. myFunc1. {myFunc2} procedure myDLP(var PString:Shortstring. export. stdCall.. export. ..Outputs:ParamRecPtr).. export. FDLNames. myDLP. . Inputs: ParamRecPtr): extended. . stdcall. begin end. Compiled Functions and Procedures {***********************************************************************} {no FDL procedures so return a null string} procedure FDLNames(Names : PChar). when used.CTX file when help is requested.HLP file such that EES will jump the appropriate topic when the user clicks the Func Info button. Note that the Windows .CTX file is found. This help file will be displayed if the file is found in the directory in which the external library file resides. a (.Compiled Functions and Procedures Chapter 6 Help for Compiled Functions and Procedures The Function Info dialog (Options menu) has an INFO button which. Each line in the .HLP and HTML (. Either of these help file formats can be composed using any of the commercial Help generating programs. provides help explaining the use of the selected function. EES will open the file to find the context number for the topic that has the name of the function for which help is requested.CTX file is not provided. Blank lines and spaces can be used to make the text more clear. EES will look for a file with the name of the compiled routine and a . The help context file has the same name as the library file but with a . otherwise a message will appear which states the help is not available for this item. A single library file can hold many functions.DLL. a Windows .HLP extension.DLL) library file written in EES can have any number of functions and procedures. the Help file will open to the first topic. Long lines which do not fit within the Help window will be broken and word-wrapped as needed. For example. it should be formatted so that each paragraph ends with a carriage return.CTX file contains two items: the context number (as it is used in the Help program) and a string which contains the function name. When the user clicks the INFO button.HTM) files allow figures and formatting options to be used so it is a better way of providing help. If an ASCII file is provided. The Help file will be then opened directly to that topic. If the topic is not found or if the . 1 LiBr_External_Routines 2 H_LIBR 3 T_LIBR 4 P_LIBR 5 V_LIBR 6 X_LIBR 7 Q_LIBR 8 VISC_LIBR 9 COND_VISC 187 .HLP file or an HTML file. If a . This is done by providing a file containing help context information. EES will look for the .CTX filename extension. This file can be an ASCII text file. Shown below is the context file for the external files in the LiBr. It is possible to design a Windows . 188 . B$=A$ String variables may be passed as arguments to internal functions.P=P) String variables may be used with the Parametric table. the name of a fluid provided to a thermophysical property function may be a string variable. h=enthalpy(R$. String variables can be set to string constants. e. The variable name must begin with a letter and consist of 30 or fewer characters. A string constant is a set of up to 255 characters enclosed within single quote marks. The commands and functions which implement these features are described in this chapter and illustrated with examples..CHAPTER 7 ____________________________________________________________________________ ____________________________________________________________________________ The advanced features in EES allow the program to work with string. In general. For example. as in the BASIC language. a Parametric table is used to tabulate the values of specific enthalpy for four refrigerants at 0°C. A string variable is identified to EES with a variable name that ends with the $ character.. e. string variables can be used in EES equations anywhere in which character information is provided.g.g. A string variable holds character string information. In the example below. e.g. and array variables and solve simultaneous algebraic and differential equations. complex. Note that the single quote marks which are normally used when specifying a string constant should not be used when entering the strings in the Parametric table. Advanced Features String Variables EES provides both numerical and string variables types. 100 kPa. procedures and modules or to external functions and procedures as described in Chapter 6. A$='carbon dioxide' String variables can be set equal to other string variables.T=T. including the $ character. 189 . In any case. For example: U$='kJ/kg' h=15 "[U$]" The comment to the right of the 15 sets the units of variable h to U$. When set in complex mode.. See the Diagram Window section in Chapter 2 for more information on this capability. EES will recognize that U$ is a string variable and set the units of h to the string that is assigned to U$. Complex Variables EES will solve equations involving complex variables of the form a+b*i if the ‘Do Complex Algebra’ control in the Complex tab of the Preferences dialog is checked. either with an edit box or with a pull-down list of alternatives.Col1$. e. The imaginary number operator may be set to either i or j in the Preferences dialog although i is used in the following discussion. (You should not use _r or _i at the end of a variable name unless you are 190 . The units could also be set in the Variable Info dialog or by clicking on h in the Solution window.Col$) String variables can be used to specify the units of other variables.Row. every (non-string) EES variable is represented internally as two variables corresponding to the real and imaginary components of a complex number.Col2$.Chapter 7 Advanced Features A string variable may be used to hold the name of a Lookup file or the name of a column for use with the Interpolate or Lookup commands.Col1$=x) k=Lookup(File$. m=Interpolate(File$. The imaginary part has an appended _i.g. The real part is internally identified by appending _r to the variable name. String variables may be supplied to the Equations Window using the Diagram Window. you also enter the equation.606 < 56. Y_r and Y_i corresponding to the real and imaginary components of the variables. The angle can be entered in either degrees or radians.606 <0. If. enter omega_r=3. the angle is assumed to be in the same units as indicated for trigonometric functions in the Unit System dialog. for example. for example. For example. as well as in column headers of the Parametric Table. You could. If no designation is provided. although they will appear with these names in the Variable Info and New Parametric Table dialogs. In rectangular form. you can ensure that the angle you enter is in degrees or radians regardless of the unit system setting by appending deg or rad to the number (with no spaces). of course. X_i. you can set the value of a real or imaginary part of a complex number by entering the real or imaginary variable name on the left of an equation in the Equations window. Complex numbers can be entered in either rectangular or polar form. However. you enter the equation X=Y EES will automatically create variables X_r.9828rad The use of deg or rad to indicate the units of the angle is strongly recommended for three reasons. You will normally not have to refer to the renamed variables. However. Y=2 + 3 * i Y=3. the following equation will set the imaginary part of variable omega to 0. For example. omega = 3 in the Equations window. the value of the constant you enter will not be changed by the unit system 191 .Advanced Features Chapter 7 specifically referring to the real or imaginary component. omega_i=0 Any later attempt to set the imaginary part of omega will cause EES to display an error message. First. A complex constant can be entered in polar form by entering the magnitude (also called absolute value) of the number and the angle separated with the < symbol.31deg Y=3. The < character will be displayed in the Solution and Formatted Equations windows as ∠. the value of Y can be set to the same complex constant in any one of the following three ways. EES will present an error message when you attempt to solve because the omega=3 equation sets both the real and imaginary parts of omega and the imaginary part would have already been set. the complex number is entered using the imaginary number operator (i or j) with a multiplication symbol (*) separating the imaginary number operator from variables or constants.) If. Third. a simple way to coax EES into providing multiple solutions. Cis. if you designate the angle to be in degrees. Equations used for the real and imaginary parts are identified with (r) and (i). Internally. and Conj. procedures. One equation is used to equate the real parts of the variables whereas the second equation equates the imaginary parts. procedures. They are Real. EES creates two equations for each equation that is entered in the Equations window. and tanh functions will accept and return appropriate complex numbers. are not accessible. The output display of the number in the Solution Window can be set for degrees or radians (in polar notation) independent of how the number is entered. however. When configured in complex mode. exp. For example. There are a few built-in functions that operate only in complex number mode. ln. Entering this equation into the Equations window and solving with the default guess values will produce a solution of z=1. One limitation of the manner in which EES implements complex numbers is that EES can only return one solution. 192 . some EES functions. cos. and modules. respectively. Magnitude. the sin. such as Min and Max. Consider the problem of determining the five roots to the complex equation z5 + 9 + 9 i = 0. The actual set of equations used in complex mode is most clearly seen by viewing the Residuals window which displays the residual and blocking order for each equation.) Only the real part of a complex variable will be placed in the argument list of internal or external functions. User-written functions. Second. There is. However. you can enter complex variables in polar form with the angle in degrees yet do all calculations with the unit setting in radians which is more efficient. Imag. Setting the Solution window display to polar (degree) coordinates will produce the following solution. (Modules are currently not supported in complex mode. although two or more solutions may exist. Angle. most of the built-in functions (including the thermophysical property functions) have been modified to work with complex numbers. The display is changed by clicking the right mouse button on the value and selecting the display options from the Format Variable dialog. and external routines can be used but they will accept and return real numbers only. the degree sign will be shown with the angle in the Formatted Equations window.176+1. These functions all take one (complex number) argument and set the real part of the complex variable to the selected value.Chapter 7 Advanced Features setting. AngleDeg. AngleRad.176 i. Now. To find a different solution (without changing guess values). The Formatted Equations window and solution for this last step are shown below. 193 . This process can be repeated to find the third. and fifth roots. but there are four others. a second solution will be found. fourth.Advanced Features Chapter 7 This is a correct solution to the equation. divide the equation by the difference between z and the value of this root. The Formatted Equations window will appear as shown. For example. A range of array variables can be indicated by separating the first array index value from the last index value by two decimal points. the TableRun# function. Z[2. –. X[2]. is a unique variable name. the temperature and entropy of each state in a thermodynamic cycle can be overlaid on a T-s property diagram. See Property Plot in the Plot Menu section of Chapter 3 for details. such as X[99]. X[N. X[1]. For example.g. just as for any other variable. 3. Index arithmetic is done left to right with no operator precedence. 2.. X[5]. They provide a means of grouping variables of similar type. 4. X[2. Array variables can be plotted. array variables can be used with the DUPLICATE command and the sum and product functions to provide matrix capability and thereby significantly reduce the amount of typing needed to specify some problems. X[4].. Valid index values range between –32760 and +32760.5] can be used in place of X[1].g. EES variables may be used in the index range (e. etc. Memory is allocated only for the variables which appear in the equations. For example. X[1+2*3] will be transformed into X[9]. This shorthand notation is supported for two dimensional array variables as well. T[2]. X[1. The total length of the variable name. including zero.Chapter 7 Advanced Features Array Variables EES recognizes an array variable by placing the array index within square brackets. e. each array variable. The special requirements pertaining to array variables are: 1. X[5] as the argument list to a function.g.1.2.3]. Array Range Notation Array range notation is a shorthand notation to facilitate passing of array variables to internal and external Functions and Procedures. For example. or an algebraic expression involving these quantities with operators +. EES treats array variables in a very different manner than FORTRAN or Pascal. X[3].g.3] all within the same equation set. It is legal (but not good practice) to have EES variables names of X. Array variables can be useful in several ways. *.. Finally. In EES.M]) provided that 194 .3]. As such. The index variable for the DUPLICATE command or the sum or product functions can also be used in an expression for the array index as shown below. and /.. The guess value and bounds (along with other information) may be specified for X[99] with the Variable Info command. the temperatures at each state in a system can be written as T[1]. X[99] appears to EES just like any other variable such as ZZZ. The fact that X[99] appears in the Equations window does not cause EES to reserve memory for 99 elements. e. X[2*3+1] is a valid array variable which EES will transform into X[7]. An array index may be an integer number. including the brackets and the integer value of the index. e. Multi-dimensional array variables may also be used with the indices separated by commas... an EES variable which has been previously set to a constant value. The right bracket must be the last character in the variable name. Z[1. must not exceed 30 characters. A long argument list is not possible in any other way since EES statements must be 255 or fewer characters. The following example illustrates array range notation. 195 . The notation can be used in the arguments of function calls and CALL statements. Array range notation can be convenient when array variables are being used as arguments to internal and external functions. A maximum of 1000 arguments may be passed to a function or procedure using array range notation. However.Advanced Features Chapter 7 their values have been previously set in assignment statements. the major purpose of this notation is to allow long argument lists to be passed. in Function and Procedure statements and in $Common directives. this capability. 2. DUPLICATE is useful only when used with array variables.6. The equations which are to be duplicated are enclosed between the DUPLICATE and END command words.. The END command terminates the last opened DUPLICATE command. the DUPLICATE index variable (j in the example above) can be used in an algebraic expression for the array index. or the TableRun# function. each DUPLICATE command must use a different index variable name and each must be terminated with an END command. DUPLICATE j=i. e.Chapter 7 Advanced Features The DUPLICATE Command The DUPLICATE command provides a shorthand way of entering equations into EES. DUPLICATE commands may be nested within one another as deep as desired. The DUPLICATE index is not an EES variable.N X[j]=X[j–1]+j END are equivalent to: X[1]=1 X[2]=X[1]+2 X[3]=X[2]+3 X[4]=X[3]+4 X[5]=X[4]+5 Note that. The lower or upper limit of an internal DUPLICATE may be the index value of an external DUPLICATE. However. The lower and upper limits specified for the index variable in the DUPLICATE command must be integers.g. X[i. END. The DUPLICATE command must be on its own line in the Equations window or separated from other equations with a semicolon. For example. within the scope of the DUPLICATE command. END 4.5. EES variables previously assigned to constant values. but rather just a temporary placeholder for the integers applied in the DUPLICATE command. The special format requirements pertaining to the DUPLICATE command are as follows: 1.j] = i*j. DUPLICATE i=1. the following statements: N=5 X[1]=1 DUPLICATE j=2. 196 . 3. . by using the DUPLICATE command and the sum function.14 -1 LM10 A = −1 MM N −1 −1 3. 2nd edition. For example. 1985. However. 14 Incropera.33 −1 −1 OP −1 P 2P Q LM940584OP B = 4725 MM P N 0 PQ The equations required in EES to solve this problem are as follows: The calculated elements in the X array will appear in the Arrays window. Chapter 13 197 . consider the following radiation heat transfer problem in which [A] and [B] are given below. and [X] and [B] are vectors.P. [X] is to be determined. Fundamentals of Heat and Mass Transfer. John Wiley and Sons. and DeWitt. D. and the radiosity vector. formulated with array variables. F.P.Advanced Features Chapter 7 Matrix Capabilities Many engineering problems can be formulated into a linear system of algebraic equations of the form [A] [X] = [B] where [A] is a square matrix of coefficients. a more elegant and convenient method for solving these equations in EES is to make use of the matrix capability. EES can solve matrix equations. the matrix equation is solved to determine the elements in the vector [X] for known [A] and [B]. [X] = [A] [B] EES can directly solve the equations represented by [A] [X] = [B] by entering each equation directly into the Equations window in any format or order. In this case. Ordinarily. 198 . EES calculates the inverse matrix internally. the inverse matrix [A]-1 can be determined by setting the matrix product [A] [A]-1 equal to the identity matrix in the following manner. more importantly. make the equations easier to follow. However. the matrix capabilities in EES can significantly reduce the amount of typing required to enter the problem and. Using the DUPLICATE command along with array variables in EES is no more efficient than the alternative of entering each equation separately with non-array variable names. The two examples above provide a general procedure for determining the product of a matrix and a vector or the product of two matrices. The inverse matrix Ainv will appear in columns of the Arrays window. as needed to solve these and any other simultaneous equations.Chapter 7 Advanced Features Note that it was not necessary to determine the inverse of [A] to obtain the solution. however. Additional property data or thermodynamic state point information can be superimposed on the property plots using the Overlay Plot command in the Plot menu. The plot was prepared by first producing a P-h plot for R12 with isotherms at 10°C and 48°C with the Property Plot command and then overlaying the P[i] and h[i] arrays (plotting from the Arrays table) for the four state points in a refrigeration cycle analysis. Overlays can be plotted if array variables are used for the thermodynamic variables. T-v.70. Another benefit of using array variables is that the state property data then appear in the Arrays Table in a convenient tabular form.EES in the Examples subdirectory. The P-h plot below shows the state points for simple refrigeration cycle operating between an evaporator temperature of 10°C and a condensing temperature of 48°C with a compressor isentropic efficiency of 0. A psychrometric chart is generated if substance AirH2O is selected. or P-h diagrams for any of the fluids in the EES data base. The property plot is placed in one of the EES plot windows. The equations can be found in file REFRIG.Advanced Features Chapter 7 Using the Property Plot The Property Plot menu item in the Plot menu generates T-s. P-v. 199 . This algorithm is designed for solving combined algebraic and differential equations which result when the integrand is a complex function of other variables. tStep) or F = INTEGRAL(f. t. tStep cannot vary during the course of the integration. Table-based Integral function The table-based Integral function uses the Parametric table to provide the limits and step size of the integration variable. The format for the equationbased integral function is F = INTEGRAL(f. t2. t1 and t2 are the first and last values specified for variable t. t1. If tStep is not provided. EES will select the stepsize using an automatic stepsize adjustment algorithm. t. t. values. t. and the integration variable. The format of this function is Integral(f. the limits cannot be a function of the integration variable t or any other variable which changes during the course of the integration. t1. This form of the Integral function can be used only in conjunction with the Parametric Table. can be a variable or any implicit or explicit algebraic expression involving variables. These limits may be specified with a constant or an EES expression. Note that specification of tStep is optional. tStep is the increment EES will use for the integration variable while numerically evaluating the integral between the specified limits. Equation-based Integral function The Equation-based integral function serves the same purpose as the table-based integral function but it does not require the use of the Parametric table. t) t1 There are two basic forms of the integral function which differ in their reliance on the Parametric table. However.Chapter 7 Advanced Features Integration and Differential Equations The INTEGRAL function is used to evaluate an integral and in the solution of differential equations. t2) {automatic step size} t1 and t2 are the lower and upper limits of the integration variable. The limits on the integration variable. 200 . must be a legal variable name which has values defined in one of the columns of the Parametric table. The integration variable. f. t). The algorithm is especially suited to stiff equations. EES uses a second-order predictor-corrector algorithm for evaluating the integral. The format of the Integral function is: t2 f dt = Integral(f. The integrand. y) dx where y0 is the initial value of y. dy/dx = f(x. the differential equation. The equation-based form would appear in the EES Equations window as y = y0 + INTEGRAL(fxy. This section demonstrates two ways of solving simultaneous algebraic and differential equations using the Integral function or the TableValue function in conjunction with the Parametric Table. Method 1: Solving Differential Equations with the Table-Based Integral Function Consider the problem of determining the time–temperature history of a sphere of radius r=5 mm. This equation can be solved using either the table-based or equation-based forms of the Integral function. Any first-order differential equation can be transformed into an appropriate form by integrating both sides. Since the stepsize is not specified. A Parametric table is not required for use with this form of the Integral command. EES will use automatic stepsize selection. For example. low. The table-based form would be entered into the EES Equations Window as y = y0 + INTEGRAL(fxy. Low and high are the lower and upper limits for x. The thermophysical properties of the sphere material are: 201 . This method can only be used if the derivative can be expressed explicitly as a function of the dependent and independent variables. Chapter 5 describes a Library function included with EES in the USERLIB subdirectory which implements a 4th order Runge-Kutta algorithm. The step size is determined by the difference between the value of x in successive rows and need not be a fixed value.Advanced Features Chapter 7 EES uses the Integral function to solve initial value differential equations. To solve the equation it is necessary to create a Parametric table containing a column for variable x. x. The integral is evaluated when the Solve Table command is applied. x) where fxy is an EES variable or expression. Solving First-Order Initial Value Differential Equations Initial-value differential equations can be solved in a number of ways with EES. initially at a uniform temperature of 400°C. Values of x are entered into the Parametric table with the value in first row corresponding to the lower limit of x and the value in the last row corresponding to the upper limit. high) y0 and fxy are as defined above.y) can be equivalently written as y = y0 + ∫ f(x. The sphere is exposed to 20°C air with a convection coefficient of h=10 W/m2-K. Fundamentals of Heat and Mass Transfer. enter the following equations. Intermediate results 15 Incropera. 2nd edition. D. a Parametric Table is generated with the New Table command in the Parametrics menu. John Wiley and Sons.15 The relation between the sphere temperature and time is given by an energy balance on the sphere. Chapter 5 202 . T – T∞ = exp – h A t ρcV Ti – T∞ To solve the differential equation numerically in EES. (Note that.P. it would not be necessary to use the Parametric table. which results in the following differential equation – h A (T – T∞) = ρ c V d T dt where h is the convective heat transfer coefficient T is the uniform temperature of the sphere at any time T∞ is the temperature of the air stream = 20°C A is the surface area of the sphere = 4 π r2 V is the volume of the sphere = 4/3 π r3 t is time This differential equation has the following analytic solution which can be used to check the accuracy of the numerical solution provided by EES. F.Chapter 7 Advanced Features ρ = density = 3000 kg/m3 k = thermal conductivity = 20 W/m-K c = specific heat = 1000 J/kg-K Calculation of the Biot number will indicate that the sphere can be treated as a lumped system. if the start and stop times were provided as the third and fourth parameters for the Integral function. and therefore it may be assumed to be at a uniform temperature at any instant of time. Next. and DeWitt.P.. 1985. Time. and Texact as the three variables to include in the table. Set the drop-down list control to ‘Last Value’ and enter 1000 for the last value as shown. With a fixed timestep.) Select T. A timestep of 100 seconds has been chosen. Click the OK button. The New Table dialog window should now appear as shown below.Advanced Features Chapter 7 for times between the start and stop times could be directed to the Integral Table using the $IntegralTable directive as shown in Method 2.) The plot 203 . Now select Solve Table from the Calculate menu to calculate the numerical and analytical values of temperature corresponding to each value of Time in the table. (The format of calculated values in the Parametric Table can be set using the Preferences command in the Options menu. When the calculations are completed. Enter 11 runs which will allow a time–temperature history for 1000 seconds starting at 0 with 100 second intervals. Enter 0 for the First Value. The value of Time from 0 to 1000 will be automatically entered into the table when you click the OK button and displayed in normal type. the Parametric Table window will display the solutions. It is next necessary to enter the values of Time in the table for which the temperature T is to be calculated. the values of Time can be most easily entered by clicking on the control at the upper right of the Time column header cell. Calculated values are shown in bold. 204 .Chapter 7 Advanced Features shows that the numerically determined temperature agrees closely with the exact analytic solution. g. it must be a number . or copied to another application. EES will first check to ensure that all variables in the $IntegralTable command are used in the equations. Such information is needed if you with to know the trajectory or path of variables as well as their values at a specified time. When calculations are initiated.. as does the table-based Integral function. VarName. Array range notation. If a step size is not provided. the step size of the integration variable is specified as arguments within the Integral function. A separate column will be created in the Integral Table for each specified variable. linear regression will be used to determine the integrated quantities at the specified steps. If no errors are found. The format of the $IntegralTable directive is: $IntegralTable Time:100. an Integral Table will be created and filled with intermediate values results from the numerical integration. this number will be taken to be the output step size and integration variables will be reported in the Integral Table at the specified step size.. The colon and number following the integration variable are optional. but it of course can have any legal EES variable name. The $IntegralTable directive instructs EES to store the intermediate values in an Integral Table. 205 .not a variable. T and Texact have been selected here. e.g. EES will use automatic step size.Advanced Features Chapter 7 Method 2: Use of the $Integral Directive and the Equation-Based Integral Function In this section. e. LowerLimit. If a step size is provided. Normally. Texact where Time is the integration variable. the lower and upper limits and optionally. If the numerical integration step size and output step size are not factors. EES will select a step size. F = Integral (Integrand. The first column in the Integral Table will hold values of this variable. The values can then can be plotted. StepSize) The last argument in the Integral command is the integration step size. EES does not keep intermediate values of any variable used during the numerical integration.. If a number is supplied. we solve the same first-order differential equation described in Method 1 using the equation-based Integral function in conjunction with the $IntegralTable directive. printed. Note that the step size used to report integration results is totally independent of the step size of used in the numerical integration. Time is used here as an example. The equation-based Integral function does not employ the Parametric table to specify the values of the integration variable. This variable must appear in one or more equation-based Integral functions within the Equations window. Rather. T. UpperLimit. If a step size is not specified. X[1.5] can be used. The variables must be separated by a space or list delimiter. The remaining parameters in the $IntegralTable directive are variables in the EES program that you wish to see as a function of the integration variable. The run number control in the upper left cell of the Integral Table indicates the Parametric Table run number for which data are currently displayed. 206 . When the $IntegralTable directive is used with the Solve Table command. printed.. an Integral Table is produced for each run (i. This run number may be changed by clicking on the up/down arrows or by directly entering the run number. row) of the Parametric Table. and copied. Shown below are the Equations window and the Integral Table that is produced when the equations are solved. The data in the table will be automatically updated when the run number is changed.Chapter 7 Advanced Features Values from this table can then be plotted. Only one Integral Table can be viewed at one time.e. in exactly the same manner as for other tables. In the Euler method. Note the use of the TableRun# function to return the row number in the Parametric Table for which calculations are currently being done. The implicit method is no more difficult to implement since EES is designed to solve implicit equations. Shown below is a listing of all of the equations needed to solve this problem. With this function. in the equations shown below. ∆t is the timestep which. (In the Formatted Equations and Solution windows. T_CN is the temperature calculated by the Crank-Nicolson method.) To proceed. a Parametric table must be defined. T old is the temperature at the previous time which can be found in the previous row of the Parametric table using the TableValue function. and the TableValue function which returns the value at a specified row and column in the Parametric Table.Advanced Features Chapter 7 Method 3: Solving Differential Equations with the TableValue Function In this section. it is possible to access the values of variables calculated in previous runs during the Solve Table calculations. as in Method 1. The values of T_Euler. these variables will display as TEuler and TCN. T_CN and T_exact in the first row of the table. – h A (T – T∞) = ρ c V d T dt The differential is approximated as new old d T∼T – T dt ∆t T new is the temperature at the current time which is to be calculated. the Solve Table command is used to complete the table. is the difference of the current and previous values of the variable Time. with calculations starting at Run 2. corresponding to Time=0. are the initial conditions and their values (400°C) must be entered. the average of the previous and current temperatures is used. The Crank-Nicolson method is implicit because the current temperature is not as yet determined. T_Euler is the temperature calculated by Euler’s method. Then. Both an explicit method (Euler's method) and an implicit method (Crank-Nicolson) are used to solve this first-order differential equation and compared with the exact solution. In the Crank-Nicolson method. as described in Chapter 4. we solve the same first-order differential equation described in Method 1. only previous temperatures are used to evaluate the right-hand side of the differential equation. 207 . Most of the equations are identical to those used for Method 1. respectively. The TableValue function returns the value in the Parametric Table at a specified row and column. Improved accuracy could be obtained by reducing the time step. It is evident that Euler’s method does not provide as accurate a solution as that obtained with the Integral function (Methods 1 and 2) or the Crank-Nicolson method. Calculated values are shown in italics.Chapter 7 Advanced Features Shown below is the completed table with the numerical and analytical solutions. 208 . but this would require additional computational effort and storage space (which is not significant here). subject to aerodynamic drag.Advanced Features Chapter 7 Solving Second and Higher Order Differential Equations Higher order differential equations can also be solved by repeated use of the Integral function. The Integral Table that is produced shows how the velocity and position of the object vary with time. The Solution Window appears after the Solve command (F2) is issued. Shown below is an EES program which solves a second-order differential equation to calculate the velocity and position of a freely falling object. 209 . Chapter 7 Advanced Features Multiple-Variable Integration Multiple integration is provided by nesting calls to the Integral function. The following example performs a numerical double integration using the equationbased Integral function. Up to six levels can be nested. 210 . Using the macro file capability. When EES is started with this command.EMF. If the filename you provided already exists. Most of the EES menu commands will produce a macro instruction. it will remain hidden while it opens the macro file and executes each of the instructions in that file. are not applicable 211 . the macro file name is placed after the EES executable file name. This log file is placed in the same directory as the EES executable. Otherwise it will be blank. you would enter: C:\EES32\EES. Now as you select commands form the EES menus. when you apply the Open command. The instructions allow EES to open a file. After selecting this command. For example. To run an EES macro from the command line or from another application.EES The macro command window is editable. Creating an EES Macro File The easiest way to create an EES Macro file is to use the Build Macro command in the File menu. to start EES and have it run the commands in file myMac. such as those in the Windows menu. so that you can modify the commands that appear in this window or delete them if you wish.emf The . Some commands. the macro equivalents of the commands will be automatically entered into the macro file window. Otherwise EES will consider the file to be a normal EES file. it will be read into macro file window.emf filename extension is required. store calculated results in a file. EES will add a line to the window of the form. solve the equations. In fact. OPEN C:\myfile. EES can directly communicate with Microsoft WORD with the WORD macro commands. many of the capabilities provided with the menu commands in EES can be implemented with a macro instruction. and other functions.EXE C:\EES32\myMac. EES will prompt the user to provide a name for the macro file.emf stored in the C:\EES32 directory. create and solve a table. The filename extension for a macro file is .LOG that indicates what instructions it has completed and any error messages. For example. EES writes an ASCII log file called EESMacro. Provided that no errors are encountered. EES can be run from the Windows command line or it can be controlled from another program. either by running EES with the macro file name or by dynamic data exchange (DDE) with the calling program. all of the instructions will be executed in the order in which they appear and then EES will quit. which signifies EES Macro File. print.Advanced Features Chapter 7 Creating and Using Macro Files A macro is a set of instructions to EES that are read from an ASCII file. Then a small macro file window will appear at the bottom of the screen. In addition. The SendMessage command requires four parameters. If it is necessary to call EES repeatedly. This message is normally sent using the Windows SendMessage command. 212 .e. The final parameter is a global atom referring to 'EES'. To avoid having EES display the splash screen and wait for user input. start EES with the following command. EES macro files provide instructions to save the contents of the Solution and Parametric Table windows so that the solution can be returned to the program that called EES. when EES starts. Others.. The first should be a broadcast message to all running applications. The calling program must next send EES a series of messages according to the DDE message protocol. such as those which are used to modify plots. The first message that must be sent is the wm_DDE_initiate message.Chapter 7 Advanced Features for a macro file since EES is usually not visible while running the macro commands. Running an EES Macro File by Dynamic Data Exchange The easiest way to run an EES macro file from another application is to simply start EES and provide the macro file name (with an . See the EXCEL_EES. are not supported at this time. it normally displays its splash screen and waits for the user to click the OK button.EXE /HIDE After receiving this command EES will start in a minimized mode. i. The Build Macro command name is changed to Close Macro after you open a macro command window. select the Close Macro command to close the macro file. EES will use this handle to send message back to the calling application. The third is the handle of the calling application. This is not really a problem as EES can be started from a remote application using the Windows CreateProcess command. C:\EES32\EES. The major purpose of the macro capability is to allow an external program to use the EES solving engine. EES must be running to receive a DDE message. EES can be instructed to open an existing EES or .EMF filename extension) as a parameter on the command line. However.TXT file and solve the equations in that file. this method becomes very inefficient as EES must be repeatedly loaded into memory.xls file for an example on how Microsoft EXCEL can call EES. When you are done entering instructions. Using the macro file. supply /HIDE as a parameter on the command line. Its icon will be visible in the Windows task bar. However. so that EES knows to act on this initiate message. An alternative approach is to use dynamic data exchange (DDE) messages. The second must be wm_DDE_initiate. but the program will otherwise not be visible on the screen. the disadvantage of this method is that EES quits when the macro file commands have been executed. Shown below is a code fragment in Delphi 4 that sends the wm_DDE_initiate message to EES. lParam:longint.doInitiate(Sender: TObject). that the calling program must provide in following messages.TopicName:charString.emf').Handle. begin EESWindowHandle:=theMessage. the calling application can next send a wm_DDE_Request message to play a macro. lParam:=MakeLong(theApp.EMF filename extension. The information sent to EES includes a global atom referring to the string 'PLAY' and a character string containing the DOS filename of the macro file. end. After the wm_DDE_initiate message has been received by EES.wm_DDE_REQUEST. including the directory information and the .Command). procedure TForm1. The code fragment below shows how this is done.lParam).theTopic). SendMessage(HWND(-1). GlobalDeleteAtom(theApp). A code segment that receives the wm_DDE_Ack message may appear as shown below. PostMessage(EESWindowHandle.command:atom.wm_DDE_Initiate.lParam).wParam. lParam:=MakeLong(cfile.Advanced Features Chapter 7 procedure TForm1. 213 . end.Handle.'c:\ees32\myMacro. var cfile. end. begin theApp:=GlobalAddAtom('EES'). procedure TForm1. theTopic:=GlobalAddAtom(''). EES will respond to the wm_DDE_Initiate message by sending the application a wm_DDE_ack message.PlayMacro(Sender: TObject). GlobalDeleteAtom(theTopic). cfile:=GlobalAddAtom(CStr). Command:=GlobalAddAtom('PLAY'). var AppName. CSTR:charString. Included in this message is the handle to the EES application. var theApp. begin StrCopy(CStr. S:shortString. here called EESWindowHandle. theTopic:Atom. lParam:longInt.GetACK(var theMessage:TMessage). The complete file name should be sent. the entire table is copied}. You can specify Inc=50 instead of providing Last=550} Copy ArraysTable R1 C1:R10 C4 {Copy the specified range of the Arrays table to the clipboard. the entire table is copied} Copy ParametricTable 'Table 1' R1 C1:R10 C4 {Copy the specified range of the Parametric table named 'Table 1' to the clipboard. If no range is provided. Here's how it can be sent. lParam:=MakeLong(cformat. If no range is provided.command:atom. When EES executes a macro file. PostMessage(EESWindowHandle. Macro Command List AlterValues 'Table 1' P2 Rows=1. It will then post a WM_DDE_ACK message to inform the calling program that the calculations are completed. end. the entire table is copied} 214 . it writes results to a specified text file. begin cformat:=GlobalAddAtom('').QuitClick(Sender: TObject). Command:=GlobalAddAtom('QUIT'). The calling application can open this text file to retrieve the results.wm_DDE_REQUEST. The only other message EES will accept is the quit command which terminates EES.Handle.Chapter 7 Advanced Features After receiving this message. the entire table is copied} Copy IntegralTable R1 C1:R10 C4 {Copy the specified range of the Integral table to the clipboard. procedure TForm1. lParam:longint. var cformat..10 First=100 Last=550 {Enter values into the Parametric Table named 'Table 1' for the column holding variable P2 setting the values of rows 1 to 10 to values starting at 100 and ending at 550.lParam). EES will open the macro file and execute the instructions therein.Command). If no range is provided. } LoadLib C:\EES32\myLib. Size can be specified in cm or in} New {Clear the workspace and bring up an empty Equations window} NewLookup 'Lookup 1' Rows=24 Cols=2 'Lookup 1' with 24 rows and 2 columns} {creates a new Lookup table having name NewPlot Table=PAR2 X=P2 Y=T2 Rows=1.3]=10 {Set the value in row 2 column 3 of the Lookup table having name 'Lookup 1' to 10} ModifyAxis X Plot=1 Min=100 Max=600 Int=100 Linear Grids=on Showscale=off Size=10 Style=BoldItalic Format=A3 {Change the scaling of the X axis of plot window 1 to the specified minimum.ees OpenLookup C:\EES32\myTable. maximum and interval in linear or log coordinates. 2. The gridlines and scale can be turned on or off. Y and Z} Open C:\EES32\Examples\Regen. If the plot window number is not provided.lib} Lookup['Lookup 1'.10 Line=1 Symbol=1 Color=Red {Create a new plot window and Plot T2 vs P2 using the first 10 rows of data from table in Tab 2 of the Parametric table window} NewTable 'Table 1' Rows=10 X Y Z Create a new Parametric table having name 'Table 1' with 10 rows and columns for variables X... the command is applied to the foremost plot window. The scale numbers are shown in bold italic with fontsize 10 using automatic format.lkt {open the specified file} {open the specified Lookup file} OverlayPlot 1 Table=Par2 X=P[4] Y=Eff Rows=1. Use Y for the left Y axis and Y2 for the right Y axis} ModifyPlot 1 Width=12 cm Height=15 cm {Change the size of plot rectangle for the specified plot window.lib {Load a library file called C:\EES32\myLib.Advanced Features Chapter 7 Copy PlotWindow 3 {Copies the graphics in Plot Window 3} Copy SolutionWindow {Copies the entire contents of the Solution window in ASCII format} DeletePlot 1 {Delete Plot Window 1.10 Line=1 Symbol=4 Color=Blue Right 215 . {Save the contents of the Arrays table to a file called SaveLookup 'Lookup 1' myTable. FormattedEqns.. use Look for Lookup table.} SaveArrays myArrays.txt.} Print Diag Equ For Arr Par2 Look3 Plot1 {Print the Diagram. the Parametric table in the second tab of the Parametric Table.10 of the table in Tab 2 of the Parametric table.4]=20 {Set the value in row 1 column 4 of the Parametric table named 'Table 1' to 20} Paste Lookup 'Lookup 1' R2 C3 {Paste the contents of the clipboard into the Lookup table named 'Lookup 1' starting at row 2 column 3.} Parametric['Table 1'.txt.94 3.} SaveTable 'Table 1' myTable.txt.074 0. To plot other tables. Equations.txt {Save the contents of the Lookup table having the tab name 'Lookup 1' to a file called mytable.txt /Append {Save the contents of the table named 'Table 1' in the Parametric Table Window to an existing file called myTable. The /Append 216 . Arr for Arrays table or Int for Integral table.} Paste Parametric 'Table 1' R2 C3 {Paste the contents of the clipboard into the Parametric table named 'Table 1' starting at row 2 column 3. P[4] from data in rows 1.37 12 45 155 DoQLines {Create a TS property plot for Steam. SaveSolution mySoln.. The /Append option will allow writing to the bottom of the file without deleting the existing information.Chapter 7 Advanced Features {overlay a plot of Eff vs. all rows are solved.1.txt /Append {Save the contents of the Solution window to an existing file called mySoln. Arrays. Include 4 constant pressure lines and 6 constant entropy lines at the specified values and draw lines of constant quality} ResetGuesses {Reset the guess values of all variables to their default values} SolveTable 'Table 1' Rows=1. If no range is specified. Use the right Y-scale.10 {Solve rows 1 through 10 of the Parametric Table having the name 'Table 1'.txt.txt myArrays. the Lookup Table in the 3rd tab of the Lookup Table and Plot 1 windows} PrintSetup PRINTER='\\SEL\Sandy' Orientation=PORTRAIT Copies=1 {Set the printer specifications} PropPlot Steam TS 4 11000 5300 2100 660 6 0. } WORD. e.. and guess value for variable P as specified} WORD. Mixed units. are not supported.Advanced Features Chapter 7 option will allow writing to the bottom of the file without deleting the existing information.g. PlotWindow 2.Insert('any text here') {Insert the text contained with single quotes into the WORD document at the current position.0E-0006 {Set the Stop Criteria properties as indicated} Units C kPa MASS DEG {Set the Units as indicated.} WORD.Show {Close the communication with WORD.0E-0006 Var= 1.} WORD.} 217 .FileSaveAs('FileName') filename. can be shown in this manner} Solve {Solve as if the Solve command has been issued} StopCrit It=100 Time=3600 Res= 1. BITMAP. and ENHANCED METAFILE.PasteSpecial(formatType) {Paste the current contents of the Clipboard into WORD in the specfied format.} WORD.Quit WORD.} WORD. DEVICE INDEPENDENT BITMAP.} WORD. C and psia.} WORD.FileOpen('FileName') {Start WORD and open the specified Word file.} {Make the open WORD document visible. etc. e.DiagramWindow..} Show Equations {Bring the Equations window to the front. PICTURE.g.Hide {Save the current WORD document with the specified {Hide the open WORD document. ParametricTable.} UpdateGuesses calculated values} {Update the guess values of all variables to the last set of VarInfo P2 Lower=200 Upper=500 Guess=300 {Set the lower bound.Paste {Paste the current contents of the Clipboard into WORD.FileNew {Start WORD and create a new empty document. upper bound. The formatType can be TEXT. Any window. It is necessary to provide the complete file name. Chapter 7 Advanced Features 218 Appendix and the order in which the equations are solved.. 219 Hints for Using EES Appendix A Hints for Using E Alternatively, add a variable, Delta, such that QL = AL*Sigma*(T^4 - TL^4) QB = AH*Sigma*(TH^4 - T^4)+Delta particularly convenient if you have in following problems. 9. The arrow keys help some users move about more quickly in the Equations, Parametric and Lookup Tables. In the Equations window, the up and down arrows move the cursor up and 220 Hints for Using EES Appendix A down one line; left and right arrow move the cursor left and right one character. Home and End move to the start and end of the current line. In the tables, the arrow keys move to the next cell in the direction of the arrow. The Return and Tab keys produce the same effects as the down arrow and right arrow keys, respectively. 8. Use the Tab key in the Equations window to set off the equations for improved readability. 9. Only the high-accuracy thermodynamic property correlations, e.g., Steam_NBS, CarbonDioxide, Ammonia_ha, Methane_ha, etc. are specifically applicable in the compressed (sub-cooled) liquid range. All other real thermodynamic property relations assume that subcooled liquid is incompressible and properties are taken to be those for saturated liquid. Thus, in the subcooled region, v(T,P)=v(T,Psat), u(T,P)=u(T,Psat) and s(T,P)=s(T,Psat). To calculate the ideal work of a pump, for example, recall that h2-h1 = Wpump = ∫v dP = v*(P2-P1), since for an incompressible substance, v is independent of P.. 11.. 12. Use the $INCLUDE directive to load commonly used constants, unit conversions, or other equations into the Equations window. You won’t see them, but they’re there, available for use. You can also load library files with the $INCLUDE directive. 13... 221 Appendix A Hints for Using EES 15. If you are working in Complex Mode, use the $COMPLEX ON directive at the top of the Equations window. Its more convenient than changing the Complex Mode setting in the Preferences dialog. 16. To enter µm, hold the Alt-Key down and type 230 on the numeric keypad. Let the Alt key up and the µ should appear. Then enter m. Other useful characters are Alt-248 which displays the degree symbol ° and Alt-250 which appears as a dot (·) and is used to represent multiplication. 222 Appendix B _____________________________________________________________________________ _____________________________________________________________________________ large problems to be solved in the limited memory of a microcomputer. The efficiency and convergence properties of the solution method are further improved by the step-size alteration and implementation of the Tarjan [8] blocking algorithm which breaks the problems into a number of smaller problems which are easier to solve. Several algorithms are implemented to determine the minimum or maximum value of a specified variable [9,10]. Presented below is a summary of these methods, intended to provide users with a better understanding of the processes EES uses in obtaining its solutions. Numerical Methods Used in EES Solution to Algebraic Equations Consider the following equation in one unknown: x3 - 3.5 x2 + 2 x = 10 To apply Newton's method to the solution of this equation, it is best to rewrite the equation in terms of a residual, ε, where ε = x3 - 3.5 x2 + 2 x - 10 The function described by this equation is shown in Figure 1. There is only one real solution (i.e., value of x for which ε = 0) in the range illustrated at x = 3.69193. 20 Improved guess Initial guess 0 10 ε -10 -20 -2 -1 0 1 2 3 4 5 x Figure 1: Residual of x3 - 3.5 x2 + 2 x = 10 as a function of x 223 Appendix B Numerical Methods used in EES Newton's method requires an estimate of the total derivative of the residual, J. For this equation, the derivative is: J = dε = 3 x2 – 7 x + 2 dx To solve the equation, Newton's method proceeds as follows: 1. An initial guess is made for x (e.g., 3). 2. The value of ε is evaluated using the guess value for x. With x = 3, ε = -8.5. 3. The derivative J is evaluated. With x = 3, J = 8. 4. The change to the guess value for x, i.e., ∆x, is calculated by solving J ∆x = ε. In this example, ∆x is -1.0625. 5. A (usually) better value for x is then obtained as x - ∆x. In the example, the improved value for x is 4.0625 (which results in ε = 7.4084). Steps 2 to 5 are repeated until the absolute value of ε or ∆x becomes smaller than the specified toler following two simultaneous equations in two unknowns: x2 + x2 – 18 = 0 1 2 x1 - x2 = 0 The equations can be rewritten in terms of residuals ε1 and ε2: ε1 = x2 + x2 – 18 = 0 2 1 ε2 = x1 - x2 = 0 The Jacobian for this matrix is a 2 by 2 matrix. The first row contains the derivatives of the first equation with respect to each variable. In the example above, the derivative of ε1 with respect to x2 is 2 x2. The Jacobian matrix for this example is: J= 2⋅x1 2⋅x2 1 –1 Newton's method as stated above applies to both linear and nonlinear sets of equations. If the equations are linear, convergence is assured in one iteration, even if a "wrong" initial guess was made. Non-linear equations require iterative calculations. Consider the following initial guess: x= 2 2 224 Numerical Methods used in EES Appendix B ε = – 10 0 J= 4 4 1 –1 The values of ε and J for this initial guess are: Improved values for the x vector are obtained by solving the following matrix problem involving the Jacobian and the residual vector. 4 4 1 –1 ∆x1 = –10 ∆x2 0 Solving this linear equation results in: ∆x1 = – 1.25 – 1.25 ∆x2 Improved estimates of the x1 and x2 are obtained by subtracting ∆x1 and ∆x2, respectively, from the guess values. x1 3.25 x2 = 3.25 The correct solution to this problem is x1 = x2 = 3.0. The calculated values of x1 and x2 are closer to the correct solution than were the guess values. The calculations are now repeated using the most recently calculated values of x1 and x2 as the guess values. This process is repeated until convergence is obtained. The Jacobian matrix plays a key role in the solution of algebraic equations. The Jacobian matrix can be obtained symbolically or numerically. Symbolic evaluation of the Jacobian is more accurate, but requires more processing. Accuracy of the Jacobian, however, does not necessarily lead to more accuracy in the solution, only to (sometimes) fewer iterations. EES evaluates the Jacobian numerically. Because EES does all calculations with 96 bit precision (about 20 decimal places), numeric evaluation of the Jacobian rarely results in convergence problems from loss of precision. In most equation sets, many of the elements of the Jacobian matrix are zero. A matrix with many zero elements is called a sparse matrix. Special ordering and processing techniques make handling of sparse matrices quite efficient. In fact, without sparse matrix techniques the number of simultaneous equations which could be solved by EES would be substantially less than 6000, (10,000 in the Professional version) the current limit implemented in EES. Further references on sparsity and on how to handle sparse matrices are available in [5, 6]. A collection of routines that are designed to handle very large sparse matrices are described in [7]. Newton's method does not always work, particularly if a "bad" initial guess for the x vector is supplied. The solution obtained after applying the correction ∆x to the previous x vector should be more correct (i.e., result in a smaller maximum residual) than the solution obtained before 225 starting from a guess of x=2. EES automatically 226 . EES organizes the equations into groups (or blocks) before solving. In this case. If this is not true.5. If this does not improve the solution. EES will reevaluate the Jacobian and try again until one of the stopping criteria forces the calculations to stop. it is often possible to solve these equations in groups (sometimes one at the time) rather than all together as one set. they can be more easily solved if they are reordered and blocked. For this reason. If the resultant solution is still not better than the solution prior to the correction. However. Step halving is very helpful when a bad initial guess is provided. EES always checks for this condition. 60 40 Initial step ε 20 Initial guess Reduced step 0 Half step -20 0 1 2 3 4 5 6 Full step x Figure 2: Use step-halving for improving the convergence Blocking Equation Sets Even though you may have what looks like a set of simultaneous equations. the step is halved again (up to 20 times).Appendix B Numerical Methods used in EES the correction. for example. the following set of equations: x1 + 2 x2 + 3 x3 = 11 5 x3 = 10 3 x2 + 2 x3 = 7 These equations can be solved as one simultaneous set. It is better to re-order first. EES will halve the step ∆x and evaluate the residuals again. Figure 2 illustrates the process for the solution of the single equation in the first example. step halving works quite well. Solving equations in groups makes Newton's method work more reliably. Consider. Consider the following example with 8 linear equations in 8 unknowns: x3 x5 x1 x2 x3 x4 x1 + x6 + x7 .x6 .x7 = -8 From here and: From here: From here: and: From here: x1 = 1 x6 = 6 x5 = 5 x3 = 3 x8 = 8 x2 = 2 Block 5: Equations 1 and 6 x3 + x8 = 11 x3 .x6 x7 .x5 + x8 = 6 Block 6: Equation 5: x2 + x8 = 10 The first two blocks contain a single equation with a single variable. Finally. These parameters are determined before any solution of the remaining equations takes place. No lower and upper limits on the guesses are needed for parameters. blocking allows the equations to be solved in 6 blocks as follows: Block 1: Equation 7 x4 = 4 Block 2: Equation 2 x7 = 7 Block 3: Equations 4 and 8 x1 + x4 .x6 = -1 x1 + x6 + x7 = 14 Block 4: Equation 3 x5 . EES will recognize that equations that depend from the start on a single variable are in reality parameter or constant definitions. equation 3 can be solved for x2.x5 + x4 . Because the equations in this example are linear and they can be totally uncoupled. the process looks trivial.x7 + x8 + x8 + x8 = 11 =7 = -8 = -1 = 10 = 6 = 4 = 14 These equations and variables can be re-numbered and blocked.x6 . In the case above.Numerical Methods used in EES Appendix B recognizes that equation 2 can be solved directly for x3. These blocks simply define constants. since the values of these parameters are determined 227 . Once this is done. each with one equation and one variable which are directly solved. equation 1 can be solved for x1. Each block is solved in turn. Things can get a little more interesting if the blocks are a little less obvious. This results in three blocks of equations. the optimum is found directly. When the equations are nonlinear. otherwise later groups of equations begin iterating with totally incorrect values of earlier variables. The result is often divergence. The solution of the remaining equations is now very simple. EES is able to recognize groups of equations prior to solution by inspecting the Jacobian matrix using the Tarjan [8] algorithm.. When there are two or more degrees of freedom. but it is not essential. EES uses Brent's method repeatedly to determine the minimum or maximum along a particular direction. although it did not appear trivial at the beginning of the process.e. The user specifies the method.Appendix B Numerical Methods used in EES immediately. Grouping of equations is useful when the equations are linear. the number of variables minus the number of equations). A quadratic function is fit through these three points. The recursive quadratic approximation algorithm proceeds by determining the value of the variable which is to be optimized for three different values of the independent variable.. optimum) value of a variable when there is one to ten degrees of freedom (i. Then the quadratic function is differentiated analytically to locate an estimate of the extremum point. For problems with a single degree of freedom. This process is continued until the convergence criteria set for the minimization/maximization process are satisfied. If this is not the case. grouping of equations is nearly indispensable.10].e. See reference [6] for more details on this algorithm. If the relationship between the variable which is being optimized and the independent variable is truly quadratic. Determination of Minimum or Maximum Values EES has the capability to find the minimum or maximum (i. the variable to be optimized and an independent variable whose value will be manipulated between specified lower and upper bounds. EES can use either of two basic algorithms to find a minimum or maximum: a recursive quadratic approximation known as Brent's method or a Golden Section search [9]. 228 . The direction is determined by a direct search algorithm known as Powell's method or by the conjugate gradient method [9. the algorithm will use the newly obtained estimate of the optimum point and two (of the three) points which are closest to it to repeat the quadratic fit. The bounds for the section which contains the smaller (for minimization) or larger (for maximization) dependent variable replace the interval bounds for the next iteration.2 in the plot below are 5 and 4. The estimate integral value between 0 and 1 is the sum of the areas of the 5 sections.Numerical Methods used in EES Appendix B The Golden Section search method is a region-elimination method in which the lower and upper bounds for the independent variable specified by the user are moved closer to each other with each iteration.2 * (5+4. a plot of f versus X would be prepared. Sect i on 1 τ (1 − τ ) Sect i on 2 Figure 3: Region Elimination using the Golden Section Method Numerical Integration EES integrates functions and solves differential equations using a variant of the trapezoid rule along with a predictor-corrector algorithm. The area of the first section is then 0.4. it is helpful to compare the numerical scheme with the manner one would use to graphically determine the value of an integral. the ordinate values at 0 and 0. In graphical integration. In explaining this method. as shown in Figure 3. The area under the curve in each section is estimated as the area of a rectangle with its base equal to the width of the section and its height equal to the average ordinate value in the section. The abscissa of the plot would be divided into a number of sections as shown below. respectively. 229 .4)/2 or 0. For example. Consider the problem of graphically estimating the integral of the function f = 5 -5 X + 10 X2 for X between 0 and 1.61803 is known as the Golden Section ratio. The value of the dependent variable is determined in each section.94. Each iteration reduces the distance between the two bounds by a factor of (1-τ) where τ =0. The accuracy of this method improves as the number of sections is increased. The region between the bounds is broken into two sections. 0 8. iteration is needed.0 4. 4 X 0. 230 .0 Numerical Methods used in EES f = 5. in the example above.0.Appendix B 10. which is to be integrated. Integral(f. 2 0. The values of X entered into the table identify the width of each section. The abscissa variable. EES will repeatedly evaluate the section area using the latest estimate of f at the current value of X until convergence is obtained. X. EES does not require each section to have the same width. The procedure in which the estimate of the integral made on the first calculation is corrected with later information is referred to as a predictor-corrector algorithm.g.0 0.0 0. In some situations. 0 Figure 4: Numerical approximation of an integral Integration in EES takes place in a manner quite analogous to the graphical representation. such as in the solution of differential equations. e. f. 0 0. Further. is placed in the Parametric Table.1). the value of f may depend upon the value of the integral up to that point. is evaluated at each value of X and supplied to EES through the Integrate function. 8 1. The numerical value of the function.. the value of f may not be explicitly known at a particular value of X.0 2. In this case.X.5 X + 10 X2 6. 6 0. The value of f may depend upon the solution to non-linear algebraic equations which have not yet converged. H. 7.T. Wisconsin. Reid. R. Cambridge University Press. 8. F. 1986 Oxford Science Publications. 3. S. Press. Addison-Wesley 1984. M. Ravindran and Radsdell. 190 & ff. The University of Wisconsin. Comput. 146160. Numerical Recipes in Pascal. January 1989. Ferziger. W. Tooley. Erisman and J. pp.Numerical Methods used in EES Appendix B References 1. Acton. Wheatley. "Sparse Matrix Technology. L. Direct Methods for Sparse Matrices. Flannery and S. Department of Electrical and Computer Engineering. F. (1989) 231 . Alvarado. Numerical Methods for Engineering Application. H. Numerical Methods in Engineering Practice. A. 2. Gerald and P. Rinehart and Winston. A. "Depth-First Search and Linear Graph Algorithms. O. Harper and Row 1970. Tarjan. F. S. Wiley-Interscience 1981. 4. 135 & ff. Applied Numerical Analysis. A. C. I. Madison. John Wiley. 6. Duff. B. "The Sparse Matrix Manipulation System. (1983) 10. K. Powell's Method of Successive Quadratic Approximations. Reklaitis. Appendix B." Report ECE-89-1. Teukolsky. New York. W. Chapter 10. (1972) 9." Academic Press 1984. 5. S. Clarendon Press. W." SIAM J. Pissanetsky. J.. R. Numerical Methods that Usually Work. pp. and Vetterling. Al-Khafaji and J. Holt. Engineering Optimization. P. 1. 1986. 232 . Appendix C _____________________________________________________________________________ _____________________________________________________________________________ Adding Property Data to EES Background Information EES uses an equation of state approach rather than internal tabular data to calculate the properties of fluids. e. The Fundamental Equation of State provides highly accurate properties in all regimes. R134a_ha. For this reason.g. A number of ideal gas substances are built into EES. internal energy and entropy values based upon the equation of state and additional correlations for liquid density. However. In this case. Several equations of state are provided for water. Specific heat correlations for these gases and the ideal gas law are used to calculate the thermodynamic properties at conditions other than the reference state. 1971] to provide the enthalpy of formation and absolute entropy at a reference state of 298 K. the ideal gas law is applicable...g. as explained below. and Kell [1984]. Nitrogen) are considered to be real fluids. the letters ha are appended to fluid name. vapor 233 . e. EES employs a naming convention to distinguish ideal gas and real fluid substances. The Martin-Hou property data base is still supported in EES. For some substances and conditions.IDG files in the USERLIB folder. The external JANAF program provides thermodynamic property information for hundreds of additional substances.. Real fluids properties are implemented with several different equations of state. N2) are modeled with the ideal gas law whereas substances for which the name is spelled out (e. (Air and AirH2O are exceptions to this naming convention. It is also unable to provide properties in the subcooled region. 1 atm.g. Early versions of EES used the Martin-Hou [1955] equation of state (or variations of it) for all real fluids except water. In some cases. are implemented with both the Martin-Hou and the Fundamental Equation of State.) Ideal gas substances rely on JANAF table data [Stull. this equation of state is unable to provide accurate results for states near the critical point or at very high pressures. Thermodynamic property relations are used to determine enthalpy. properties for a fluid. Ice properties rely upon correlations developed by Hyland and Wexler [1983].g. a high accuracy equation of state has been implemented in the form of the Fundamental Equation of State (Tillner-Roth [1998]). carbon dioxide. Additional ideal gas fluid data can be added with . Substances which are represented by their chemical symbol (e. the most accurate and computationally intensive being the equation of state published by Harr.. Gallagher. [1990].pressure. Viscosity and thermal conductivity of liquids and low-pressure gases are correlated with fluid specific relations. the effect of pressure on the gas transport properties is estimated using correlations from Reid et al. Temperature alone determines the transport properties for ideal gases. For example. 234 . A modification to the Martin-Hou equation of state proposed by Bivens et al. [1977] or included in the fluid specific relations. such as the R400 refrigerant blends. [1996] allows this equation equation of state to be applied for mixtures. For real fluids. The source of all data implemented in EES can be viewed using the Fluid Info button of the Function Info dialog in the Options menu. and zero-pressure specific heat as a function of temperature. the transport properties for fluid CarbonDioxide use the transport properties of Vesovic et al. Many rely on polynomials in temperature. b9} {TRef in K} {Pref in kPa} {hform . The parameters are placed in an ASCII text file which must be located in the EES\USERLIB subdirectory.0 {a2.enthalpy of formation in kJ/kgmole at TRef} {s0 .9 in kJ/kgmole-K} 0. However. b5} {a6.1034 0. To add property information. An example file providing the parameters for CO2 is provided below.set to 0} {reserved . The following sections describe the format required for the property data files. b1} 1. b3} {a4.0 {a3.685 0 0 {Molar mass of fluid {Tn Normalizing value in K} {Lower temperature limit of Cp correlation in K} {Upper temperature limit of Cp correlation in K} 0 {a0. b0 Cp=sum(a[i]*(T/Tn)^b[i]. An equation of state is not needed since it is assumed that the fluid obeys the ideal gas equation of state.IDG filename extension. SAMPLE TESTCO2.15 100 -393520 213. The additional fluids will appear in every way identical to the built-in fluids. b6} {a7.Adding Property Data to EES Appendix C Adding Fluid Properties to EES EES has been designed to allow additional fluids to be added to the property data base.7357 30. b7} {a8. it is possible to add property information for ideal gas fluids and for fluids represented by the Martin-Hou [1949] equation of state. Ideal Gas files Ideal gas files must have a . b8} {a9. The enthalpy of formation and Third-law entropy values at 298 K and 1 bar (or 1 atm) must be supplied. EES will load all fluid files found in the EES\USERLIB subdirectory at startup. the user must supply the necessary parameters for the thermodynamic and transport property correlations.5 {a1. Currently. Fluids represented by the Fundamental Equation of State cannot be added by the user.set to 0} 235 . particular attention must be paid to the reference states if the gas is to be used in calculations involving chemical reactions. b4} {a5. b2} 2.01 100.0 250 1500 -3.Third law entropy in kJ/kgmole-K at Tref and PRef} {reserved .IDG File TestCO2 44.02420 0 0 0 0 0 0 0 0 0 0 0 0 298. The properties of ideal gas fluid can be entered by adapting the file format to the new fluid.529 -4. i=0. volume and temperature are related by the Martin-Hou equation of state in the following form. 236 .039533E-8 {v1} -2. h=Enthalpy(UserFluid. A method for obtaining the coefficients is described by Martin and Hou.Appendix C Adding Property Data to EES 200 {Lower temperature limit of gas phase viscosity correlation in K} 1000 {Upper temperature limit of gas phase viscosity correlation in K} -8. (The sample file contains the parameters used for n-butane.09519E-7 {v0 Viscosity = sum(v[i]*T^(i-1)) for i=0 to 5 in Pa/m^2} 6.3105E-11 {t3} 3.84378E-15 {v3} -1. P=P1) The fluid name will appear in alphabetical order with other fluid names in the Function Information dialog window. the first line in the sample file contains UserFluid.1368E-16 {t4} 0 {t5} 0 {Terminator .) The file consists of 75 lines.MHE is listed on the following pages illustrating the required file format.set to 0} Real Fluid Files Represented by the Martin-Hou Equation of State A pure real fluid is identified with a .8249E-11 {v2} 9. The following 74 lines each contain one number. The forms of all of the correlations except the pressure-volume-temperature relation are indicated in the XFLUID.4732E-18 {v4} 0 {v5} 200 {Lower temperature limit of gas phase thermal conductivity correlation in K} 1000 {Upper temperature limit of gas phase thermal conductivity correlation in K} -1. [1955].T=T1.1582E-3 {t0 Thermal Conductivity = sum(t[i]*T^(i-1)) for i=0 to 5 in W/m-K} 3. A sample file named XFLUID. Pressure.2396E-8 {t2} -5.9174E-5 {t1} 8.MHE (for Martin-Hou Equation) filename extension.MHE file. For example. A comment follows on the same line (after one or more spaces) to identify the number. The first line provides the name of the fluid which EES will recognize in the property function statements. The enthalpy for this substance would then be obtained as follows. 184697 { Gas constant in psia-ft3/lbm-R} 1.5259e-2 { b} Constants for Martin-Hou EOS/English_units -20.84149 { molecular weight} { not used} { a} Liquid Density=a+b*Tz^(1/3)+c*Tz^(2/3)+d*Tz+e*Tz^(4/3)+f*sqrt(Tz)+g*(Tz)^2} 33.9478e-2 { A4} 0 { B4} 0 { C4} 237 .15338 { a} Vapor pressure fit: lnP=a/T+b+cT+d(1T/Tc)^1.53317 { c} -0. Most of the correlations are linear with respect to the parameters so that they can be determined by linear regression.Adding Property Data to EES Martin-Hou Equation of State (parameters in lines 18-36) A + B2T + C2e– βT/Tc A3 + B3T + C3e– βT/Tc P= RT + 2 + 2 3 v–b v–b v–b A + B4T + C4e– βT/Tc A5 + B5T + C5e– βT/Tc A6 + B6T + C6e– βT/Tc + 4 + + 4 5 eαv(1 + C′eαv) v–b v–b Appendix C where P [=] psia. EES can be used to do these regressions.89109 { e} 0 { f} 0 { g} -6481.02582 { b} where Tz=(1-T/Tc) and Liquid Density[=]lbm/ft3 -2.6163e-3 { B2} -314.MHE File for pure fluids UserFluid 58.4550e-4 { B3} 19.0974 { C3} -1. SAMPLE XFLUID.0006874 { c} 4.28739 { d} 0 { e} 0 { not used} 0.538 { C2} 0. and v [=] ft3/lbm You may need to curve fit tabular property data or data obtained form a correlation in a different form to obtain the appropriate parameters. T [=] R.935527 { A3} -3.31880 { b} where T[=]R and P[=]psia -0. A parameter set which improves upon the fit resulting from the Martin and Hou method can be determined by non-linear regression.5+eT^2 15.589 { A2} 9.1 0 12.07982 { d} 9. 2005e3 124.39053E-3 e/T^2 6.19551 0.790619e6 5.5931e-3 -6.776919161e-1 -8.8381151e-9 0 { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { { Adding Property Data to EES A5} B5} C5} A6} B6} C6} Beta} alpha} C'} a} Cv(0 pressure) = a + b T + c T^2 + d T^3 + b} where T[=]R and Cv[=]Btu/lb-R c} d} e} href offset} sref offset} Pc [=] psia} Tc [=] R} vc [=] ft3/lbm} not used} not used} Viscosity correlation type: set to 2: do not change} Lower limit of gas viscosity correlation in K} Upper limit of gas viscosity correlation in K} A} GasViscosity*1E12=A+B*T+C*T^2+D*T^3 B} where T[=]K and GasViscosity[=]N-s/m2 C} D} Lower limit of liquid viscosity correlation in K} Upper limit of liquid viscosity correlation in K} A} Liquid Viscosity*1E6=A+B*T+C*T^2+D*T^3 B} where T[=]K and Liquid Viscosity[=]N-s/m2 C} D} Conductivity correlation type: set to 2: do not Lower limit of gas conductivity correlation in K} Upper limit of gas conductivity correlation in K} A} GasConductivity=A+B*T+C*T^2+D*T^3 B} where T[=]K and GasConductivity[=]W/m-K C} D} Lower limit of liquid conductivity correlation in K} Upper limit of liquid conductivity correlation in K} A} LiquidConductivity=A+B*T+C*T^2+D*T^3 B} where T[=]K and LiquidConductivity[=]W/m-K C} D} not used: terminator} 238 .9508e-10 115 235 2.475 0 0 -7.3698529e-2 -4.1463e-3 0 0 0 5.79677345e3 -2.45278149e-4 1.95367e-7 -2.09216279e1 5.3846e-5 3.57860101e-6 -1.88512807e-5 2 change} 250 535 7.Appendix C 0 2.1273e-10 5.3 0.33070354e-2 115 235 2.07064 0 0 2 260 535 -3.6 765.0466e-8 -1.4925e-4 9.05162697e1 5.42356586e4 -7.0956305 550.9368e-7 -5. 75 {Beta} 0 {alpha} 0 {C'} 0. since the equation of state can not provide this information.40764E+00 {A2} 3.5148 {a} Liquid density = a+b*Tz^(1/3)+c*Tz^(2/3)+d*Tz 60.5637 {b} +e*Tz^(4/3)+f*sqrt(Tz)+g*(Tz)^2} -5.1192E-02 -2.34220E+02 {C2} 1.MHE file that is used to provide property data for R410A.4382E-01 {d} 1.41972E-01 {A3} 4.3718E-05 1. al.3668E-05 {e} 0 0 {not used} 0. R410A 72.1478 {Gas constant in psia-ft3/lbm-R} 0. along with an explanation of each line in the file. Shown below is a listing of the R410A.036582 {a} Cv(0 pressure) = a + b T + c T^2 + d T^3 + e/T^2 239 .54645E-05 {A5} 1.45370E-02 {C5} 0 {A6} 0 {B6} 0 {C6} 5.88425 {e} 0 {f} 0 {g} -5.Adding Property Data to EES Appendix C Fluid Properties for Blends The Martin-Hou equation of state can be adapted for mixtures as proposed by Bivens et.06932 24.13400E-03 {A4} 0 {B4} 0 {C4} -9.84456E-06 {B3} 9.1084E-02 {c} where T[=]R and P[=]psia fit -5.5+eT^2 -2.04507 {b} lnP=a/T+b+cT+d(1-T/Tc)^1.006976 {b} Constants for Martin-Hou EOS/English_units from Bivens -6.13546E+00 {C3} -4.17310E-07 {B5} 2.584 {molecular weight Bivens and Yokozeki} 400 {Indicator for blend} 30.40372E-03 {B2} -2.9940E+03 {a} Bubble and Dew Pt Vapor pressure fit: 24.9789E+03 -5.39377 {c} where Tz=(1-T/Tc) and Liquid Density[=]lbm/ft3 55.5360815 {d} -21.5841E-01 -4. The major modifications needed to make this pure component equation of state applicable to blends is to provide separate correlations for the bubble and dew point vapor pressures and a correlation for the enthalpy of vaporization. 5 {Pc [=] psia} 621.808787E-4 {b} where T[=]R and Cv[=]Btu/lb-R from Bivens -7.6612670E-12 {d} 0 {e} 65.3407 {B} where X =(1-T/Tc)^.Appendix C Adding Property Data to EES 2.643088e-3 {A} GasConductivity=A+B*T+C*T^2+D*T^3 7.300419E6 {A} GasViscosity*1E12=A+B*T+C*T^2+D*T^3 5." 1996 Intl.652083e-5 {B} where T[=]K and GasConductivity[=]W/m-K 2. Bivens and A.39552e4 {B} where T[=]K and GasViscosity[=]N-s/m2 -1.B.144608e-9 {C} 0 {D} -999 {Lower limit of liquid conductivity correlation in K} -999 {Upper limit of liquid conductivity correlation in K} 0 {A} LiquidConductivity=A+B*T+C*T^2+D*T^3 0 {B} where T[=]K and LiquidConductivity[=]W/m-K 0 {C} 0 {D} 0 {terminator} {The forms of the correlations and in some cases the coefficients have been adapted from D. Conference on Ozone Protection Technologies Oct.75282 {C} 0 {D} 0 {E} 2 {Viscosity correlation type: set to 2: do not change} 200 {Lower limit of gas viscosity correlation in K} 500 {Upper limit of gas viscosity correlation in K} -1.5541498 {Xo} 87.831547 {href offset} -0.550729e1 {C} 0 {D} -999 {Lower limit of liquid viscosity correlation in K} -999 {Upper limit of liquid viscosity correlation in K} 0 {A} Liquid Viscosity*1E6=A+B*T+C*T^2+D*T^3 0 {B} where T[=]K and Liquid Viscosity[=]N-s/m2 0 {C} 0 {D} 2 {Conductivity correlation type: set to 2: do not change} 200 {Lower limit of gas conductivity correlation in K} 500 {Upper limit of gas conductivity correlation in K} -8. Yokozeki. 21-23.50197 {A} DeltaH_vap=A+B*X+C*X^2+D*X^3+E*X^4 Bivens 185. T in R and enthalpy in Btu/lb 13.03276 {vc [=] ft3/lbm} 0 {not used} 7 {# of coefficients which follow .used for blends} 1 {DeltaH Correlation type} 0.333-X0.082942 {sref offset} 714. Washington.} 240 .264730E-8 {c} 2. "Thermodynamics and Performance Potential of R-410a.5 {Tc [=] R} 0. DC. T. L. J.. published in CFCs: 241 .E. MD 20899. “Formulations for the Thermodynamic Properties of the Saturated Phases of H2O from 173. and Wilson. J.1. NIST Standard Reference Database 23. (1977) Shankland.. Chao. D. Fundamentals of Engineering Thermodynamics. 2. (1969) Irvine. Refrigerating and Air Conditioning Engineers. Atlanta. Downing. P. "Thermodynamics and Performance Potential of R-410a. 1:142. John Wiley.S.Prausnitz. M.. Vol.. Downing.15 K. 1984). T.K.B. and Kaye.R. R. McGrawHill. Washington. "Refrigerant Equations".. (1987) Hyland and Wexler. Atlanta.15 K to 473. American Society of Heating. G. 1993. I. "Measurement and Formulation of the Thermodynamic Properties of Refrigerants 134a and 123. (1955) McLinden. M.. Gas Tables. J. Refrigerating. Gaithersburg. and Knight. Steam and Gas Tables with Computer Equations. and Huber.. 80. Versions 4. ”Development of an Equation of State for Gases. REFPROP .. 2313. (1980) Keenan. John Wiley. J. Academic Press Inc. The Properties of Gases and Liquids. New York... R. Basu. Vol. Second Edition. NIST.C. (1989) Harr. (1989.H.S. J. 21-23.. M. McGraw-Hill. ASHRAE Transactions. J. GA ASHRAE. Howell.Paper 2793 (RP-216). R.. New York.. et al. Steam Tables. (1976) D. Paper No.S (Hemisphere. "Computer Program for Calculating Properties for the "FREON" Refrigerants.E Journal. J.O. G.. R.O.W. and Sherwood. Y.F.. Part 2A. 95. Jr." 1996 Intl. 1997). J. (1984) NBS/NRC Steam Tables.C..Ch.C. Gallagher.. ASHRAE Trans. and Buckius. Morrison. GA. No. pp.. 5." DuPont Technical Bulletin RT-52. B. 158-169. and Kell.. pt. DC. McLinden. 3rd edition.Adding Property Data to EES References Appendix C ASHRAE Handbook of Fundamentals. New York.NIST Thermodynamic Properties of Refrigerants and Refrigerant Mixtures. and Hou.M. Bivens and A. Thermophysical Properties of Refrigerants..J. J.P.H.2.R. (1984) Martin.1. Conference on Ozone Protection Technologies Oct. and 6. Washington. et al. Yokozeki. "Thermal Conductivity and Viscosity of a New Stratospherically Sate Refrigerant .1. (1983) Keenan. ASHRAE Transactions. and Air-Conditioning Engineers. and Liley. American Society of Heating.” A.I. (1974) Gallagher. (1971).. R..C.2 Tetrafluoroethane (R-134a). (1989) Reid. Hemisphere Publishing Company. .. (1990) Stull. R. No. H. John Wiley.. Symposium on Global Climate Change and Refrigerant Properties. Chem Ref. G.. (1988). Aachan. The Transport Properties of Carbon Dioxide. AIChE Spring Meeting. 1998. June. JANAF Thermochemical Tables.P.Refrigerant 134a". (1971) Reiner Tillner-Roth. Second Edition. Inc. I. U. (1989) Shankland. paper presented at the ASHRAE meeting.Appendix C Adding Property Data to EES Time of Transition. and Prophet. Verlag. National Bureau of Standards. J. R. D. (1989) 242 . Refrigeration and Air-Conditioning Engineers.S. Wilson... Canada. (1986) Vesovic et al. FL. 19. Shaker. published in CFCs: Time of Transition.J. 1990. "Transport Properties of CFC Alternatives". 3. Inc. "Fundamental Equations of State". Fundamentals of Classical Thermodynamics.. Van Wylen. and Basu... D. March. Third Edition. "Thermodynamic Properties of a New Stratospherically Safe Working Fluid . Orlando. Ontario. Vol. Phys. Ottawa. New York. American Society of Heating. and Sonntag.S.R.E. Washington. Data. Refrigeration and Air-Conditioning Engineers. American Society of Heating.R. EES.EES SUPERMKT. DRAG.EES. NLINRG.EES. user-written Procedures.EES CH1EX.EES REFRIG. DIFEQN1. REGEN.EES CONVECT. EXCEL_EES. DRAG. MATRIX2.EES. FLAMET. CH1EX.EES CAPVST.EES MATRIX. RANKINE.EES.EES.EES COPPER. STMPROPS.EES. NLINRG. RK4_TEST.EES FLAMET. REFRIG.EES NLINRG. JANAF. CH1EX.EES MATRIX.EES HEATEX.EES.EES.EES.EES DRAG. REGEN. DIAGRAM_IN_OUT. MATRIX2.EES MATRIX.EES. MATRIX2. MOODY.EES DIFEQN2.EES.EES. DIFEQN1.EES.EES MOODY. Feature Arrays EES Example Files MATRIX. CATVST. SUBSTEPS. DRAG.EES MAXPOWER.EES.EES. DIFEQN2 REGEN. RK4_TEST.EES COPPER.EES.EES. FLAMET. DIFEQN2.EES HEATEX. REFRIG.EES.EES.EES. REGEN.EES CAPVST.EES RANKINE.EES COPPER. RK4_TEST.EES.EES.EES DRAG. RANKINE.EES HEATEX.EES. NLINRG.Appendix D _______________________________________________________________________ _______________________________________________________________________ The EXAMPLES subdirectory within the EES directory contains many worked-out example problems.EES.EES. NLINRG.EES CONVECT.EES DBL_INTEG. user-written Greek symbols Integration Interpolate function JANAF table LOOKUP table Macro files Minimize or maximize Modules Overlay Plot Parametric table Plotting Procedures.EES Example Problem Information Complex numbers Comments Curve-fitting Diagram window Differential equations Differentiate function DUPLICATE command Formatted Equations Functions.EES DIAGRMW. thermodynamic Property Plot Psychrometric functions Regression Subscripted variables SUM function Systems of equations TABLEVALUE Transport properties Unit conversion 243 .EES HEATEX.STMPROPS.EES. COPPER.EES.EES. external Properties. CH1EX.EES EXCEL_EES. as indicated in the information below.EES RANKINE. MATRIX2.EES.EES. Each example problem illustrates one or more EES features.EES. DIFEQN1.EES. DIFEQN2.EES.EES.EES ABSORP.EES NLINRG.EES.EES.EES.EES COMPLEXROOTS.EES. HEATEX.EES.EES.XLS.
https://www.scribd.com/document/90814177/Ees-Manual
CC-MAIN-2019-18
refinedweb
74,602
67.25
Hello, I am working on a website that has a custom registration login area as lightbox. The forget password function is not working. [code| import wixUsers from 'wix-users'; import wixData from 'wix-data'; import wixLocation from 'wix-location'; import wixWindow from 'wix-window'; import { session } from 'wix-storage'; var userId, userEmail; $w.onReady(function () { //TODO: write your page related code here... }); export function button2_click(event, $w) { login(); } export function password_keyPress(event, $w) { if (event.key === "Enter") login(); } export async function login() { $w("#textFail").hide(); let email = $w("#email").value; let password = $w("#password").value; wixUsers.login(email, password) .then(() => { console.log("User is logged in"); wixWindow.lightbox.close(true); let siteEventPageUrl = session.getItem("siteEventPageUrl"); console.log(siteEventPageUrl); if (siteEventPageUrl) wixLocation.to(siteEventPageUrl); else wixLocation.to("/events-wix"); }) .catch((err) => { console.log(err); $w("#textFail").show(); }); } export function textForgotPassword_click(event) { //wixWindow.lightbox.close(); wixUsers.promptForgotPassword(); } export function button14_click(event) { //wixWindow.lightbox.close(); wixUsers.promptForgotPassword(); } export function close_click(event) { wixWindow.lightbox.close(false); } [/code] The site url is Does anyone know why the code is not working? Thank you in advance! Melissa Hello Melissa, It seems that you are calling that promise without resolving it so it does not finish. To fix this just simply chain a .then() to it so that it can be resolved, like so: Hope this helps, Majd Nope, I among many others are having this issue, it is not working. Here is the error message in the console: Uncaught TypeError: Cannot read property 'props' of undefined It takes us to a plain white page, I used your example above and it did not change at all. @Majd Qumseya thank you for your response. The solution you provided does not work. Please advise on how to fix this problem. Thank you. Hi Melissa, Can you please provide a link to your site and specify the name of the page so we can inspect? Roi. Hi Roi, Please note that the Client Site had to go live on 9/27/18 so I made a workaround for the forgot password. I put a white box and new blue text link to a password reset form. The form goes to me then I manually have to delete the member from the member list, send the user a message with a link to resubmit the New KindCraft Member form. The website is When a user clicks on RSVP button on home page, Log in button on footer, or Sign up button on the Get Involved page, the LOGIN lightbox opens. LOGIN Lightbox: User has to "Become a Member" and fill out a custom registration form to get their username and password. After submission of form, the site redirects to the specific eventURL that the person started from or it takes them to /events-wix main page. This redirect was working until I went live. Now on the Get Involved page when a user logs in it does not redirect to the /events-wix page. Roi, I created a copy of the site and moved the workaround so you can see that nothing happens onClick with forgot password. Thank you! Has anyone figured out a solution to wixUsers.promptForgotPassword(); not working ?? I THINK the api for the PROMPTS is broken. I had code that has been working for months that used wixUserLoginPrompt. Yesterday it stopped working. the API simply does not run! see my post: I ended up coding a workaround for my problem... @ Melissa Winebrenner I believe you have to create a members area on your site before it will work. Even if you do not require a members area you still have to create one in order for forgot password to work. @Mike Moynihan Thank you for your reply. Unfortunately, I do have a members log in. It is set to customized form and links to a lightbox. @Melissa Winebrenner To add a Member's Area: Click Add on the left side of the Editor. Click the Members tab. Click Add to Site. Has anyone figured out a solution to custom registration form and the wixUsers.promptForgotPassword(); not working?? it works it's been working on my site for the last 2 months without issue @Mike Moynihan what is your site URL? @Mike Moynihan you are right it does work! I tested my site and it works. Thank you!
https://www.wix.com/corvid/forum/community-discussion/wixusers-promptforgotpassword-not-working
CC-MAIN-2020-05
refinedweb
720
67.45
The QDBusUnixFileDescriptor class holds one Unix file descriptor. More... #include <QDBusUnixFileDescriptor> This class was introduced in Qt 4.8. The QDBusUnixFileDescriptor class holds one Unix file descriptor. The QDBusUnixFileDescriptor class is used to hold one Unix file descriptor for use with the QtDBustDBus(). Constructs a QDBusUnixFileDescriptor without a wrapped file descriptor. This is equivalent to constructing the object with an invalid file descriptor (like -1). See also fileDescriptor() and isValid(). Constructs a QDBusUnixFileDescriptor object by copying the fileDescriptor parameter. setFileDescriptor() and fileDescriptor(). Constructs a QDBusUnixFileDescriptor object by copying other. Destroys this QDBusUnixFileDescriptor object and disposes of the Unix file descriptor that it contained. Returns the Unix file descriptor contained by this QDBusUnixFileDescriptor object. An invalid file descriptor is represented by the value -1. Note that the file descriptor returned by this function is owned by the QDBusUnixFileDescriptor object and must not be stored past the lifetime of this object. It is ok to use it while this object is valid, but if one wants to store it for longer use, the file descriptor should be cloned using the Unix dup(2), dup2(2) or dup3(2) functions. See also setFileDescriptor() and isValid(). Returns true if Unix file descriptors are supported on this platform. In other words, this function returns true if this is a Unix platform. Note that QDBusUnixFileDescriptor continues to operate even if this function returns false. The only difference is that the QDBusUnixFileDescriptor objects will always be in the isValid() == false state and fileDescriptor() will always return -1. The class will not consume any operating system resources. Returns true if this Unix file descriptor is valid. A valid Unix file descriptor is not -1. See also fileDescriptor(). Sets the file descriptor that this QDBusUnixFileDescriptor object holds to a copy of fileDescriptor. isValid() and fileDescriptor(). Copies the Unix file descriptor from the other QDBusUnixFileDescriptor object. If the current object contained a file descriptor, it will be properly disposed of before.
http://doc.trolltech.com/main-snapshot/qdbusunixfiledescriptor.html
crawl-003
refinedweb
321
60.01
Opened 6 years ago Closed 6 years ago #15404 closed (wontfix) "from __future__ import unicode_literals" in "settings.py" Description good day! if: in file my_web_site/settings.py to insert line: from __future__ import unicode_literals than: command... python2.6 -m my_web_site.manage test ....showing many many many many errors (errors related to unicode) at least that errors related with parameters: - DATABASES - SECRET_KEY (this parameters no-error only in byte-strings, but not unicode) but Django-documentation say that: Django natively supports Unicode data everywhere. () thanks! Attachments (3) Change History (5) comment:1 Changed 6 years ago by comment:2 Changed 6 years ago by We natively support unicode, but we don't natively support Python 3 (at least, not yet). The {{future}} call you describe exists specifically as a Python 3 migration aid. This will become a legitimate bug when we actually claim some level of Python 3 support, but until then, I'm going to mark this wontfix. Not all of those errors are related to unicode - most of them should disappear on lastest 1.2.X version. I runned Django's full test suite with SECRET_KEYbeing unicode and DATABASEScontaining unicode keys and only errors I get are related to SECRET_KEY. IMHO, there is nothing to fix here, because SECRET_KEYshould be a byte-string - after all it's a series of random bytes. (Well, ok - maybe a docfix and a sanity check on startup). Could you provide an easy way to reproduce an error related to DATABASES setting ?
https://code.djangoproject.com/ticket/15404
CC-MAIN-2016-50
refinedweb
248
54.73
It's not the same without you Join the community to find out what other Atlassian users are discussing, debating and creating. I need to update the assignee in tickets as they transition status, but only if another field is populated in the ticket. If that other field is blank, the assignee should stay as is (or if it's easier, I can set the assignee to the reporter, which is the value it will already be anyway). The post functions in JIRA don't allow this, and the custom functions don't seem to cover it either. It's looking like this is something that a script needs to be written for. I'm fine with that, but couldn't find any examples to go off of when googling... maybe I'm searching with the wrong terminology since I'm not a JIRA expert? If it helps, here's what I'm trying to do in psuedo code... on transition from state1 to state2 if qa_resource field is not null assignee = qa_resource else do nothing, or assignee = reporter if easier Thanks in advance for any help! This is an extremely common use case for Script Runner... on your transition put the following custom script post-function FIRST: import com.atlassian.jira.component.ComponentAccessor import com.atlassian.jira.issue.MutableIssue MutableIssue issue = issue def customFieldManager = ComponentAccessor.getCustomFieldManager() def qaResourceCf = customFieldManager.getCustomFieldObjectByName("QA Resource") def qaResource = issue.getCustomFieldValue(qaResourceCf) if (qaResource) { issue.setAssigneeId(qaResource.name) } else { issue.setAssignee(issue.reporter) } (totally untested) This is a pretty standard use case for the Update issues post function from JIRA Command Line Interface (CLI) which allows you to condition whether or not the update should occur. To set a field to 2 different values based on a couple of conditions, you may need multiple post functions where the conditioning determines which update is going to occur. I've been wanting to use your CLI tool, but unfortunately the budget I was given for add-ons is $0 (for now anyway). Hopefully we'll be able to buy it in the future. You don't say if the new assignee is to be selected by the person making the transition or you want it to be decided inside JIRA somehow. Also, is the 'checked' field already set or being set. If already set you can use a condition on the workflow. If being set you'll need some kind of script. If it is already set you can do this by having 2 transitions. On with the condition of the checked field set and one with it not set. Only one will be visible. For the one with the field set just transition the issue without presenting the assignee field. On the other, present it. The new assignee is to be decided inside Jira - the new assignee should be set only if the QA Resource field is populated. If the QA Resource field is left blank, the assignee field should be left as is. The 'checked' field is already set, though it's not a required field so it's possible that the field is blank. That's why I need to check - if the field is blank, do nothing, if it's populated, update the asignee to be the user listed in the field. I don't think I can have 2 transitions, because the user should only see one transition to go forward at this point in the workflow, and the assignee should only be updated if the QA Resource field was populated, otherwise it should stay as.
https://community.atlassian.com/t5/Jira-questions/Update-assignee-on-transition-only-if-another-field-in-the/qaq-p/33756
CC-MAIN-2018-09
refinedweb
595
63.9
This topic includes the following sections: Building the rpcsimp Application This appendix contains a description of a one-client, one-server application called rpcsimp that uses TxRPC. The source files for this interactive application are distributed with the Oracle Tuxedo ATMI software, except they are not included in the RTK binary delivery. Before you can run this sample application, the Oracle Tuxedo software must be installed so that the files and commands referred to in this chapter are available. rpcsimp is a very basic Oracle Tuxedo ATMI application that uses TxRPC. It has one application client and one server. The client calls the remote procedure calls (operations) to_upper() and to_lower(), which are implemented in the server. The operation to_upper() converts a string from lowercase to uppercase and returns it to the client, while to_lower() converts a string from uppercase to lowercase and returns it to the client. When each procedure call returns, the client displays the string output on the user's screen. What follows is a procedure to build and run the example. Make a directory for rpcsimp and cd to it: mkdir rpcsimpdir cd rpcsimpdir Set and export the necessary environment variables: TUXDIR=<pathname of the Oracle Tuxedo System root directory> TUXCONFIG=<pathname of your present working directory>/TUXCONFIG PATH=$PATH:$TUXDIR/bin # SVR4, Unixware LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$TUXDIR/lib # HPUX SHLIB_PATH=$LD_LIBRARY_PATH:$TUXDIR/lib # RS6000 LIBPATH=$LD_LIBRARY_PATH:$TUXDIR/lib export TUXDIR TUXCONFIG PATH LD_LIBRARY_PATH SHLIB_PATH LIBPATH Copy the rpcsimp files to the application directory: cp $TUXDIR/apps/rpcsimp/* . You will be editing some of the files and making them executable, so it is best to begin with a copy of the files rather than the originals delivered with the software. List the files: $ ls client.c rpcsimp.mk server.c simp.idl ubbconfig wclient.def wsimpdll.def $ The files that make up the application are described in the following sections. Example A-1 simp.idl [uuid(C996A680-9FC2-110F-9AEF-930269370000), version(1.0) ] interface changecase { /* change a string to upper case */ void to_upper([in, out, string] char *str); /* change a string to lower case */ void to_lower([in, out, string] char *str); } This file defines a single interface, changecase version 1.0, with two operations, to_upper and to_lower. Each of the operations takes a NULL-terminated character string, that is both an input and output parameter. Because no ACF file is provided, status variables are not used and the client program must be able to handle exceptions. Each operation has a void return indicating that no return value is generated. simp.idl is used to generate the stub functions (see below). Example A-2 client.c #include <stdio.h> #include "simp.h" #include "atmi.h" main(argc, argv) int argc; char **argv; { idl_char str[100]; unsigned char error_text[100]; int status; if (argc > 1) {/* use command line argument if it exists */ (void) strncpy(str, argv[1], 100); str[99] = '\0'; } else (void) strcpy(str, "Hello, world"); TRY to_upper(str); (void) fprintf(stdout, "to_upper returns: %s\n", str); to_lower(str); (void) fprintf(stdout, "to_lower returns: %s\n", str); /* control flow continues after ENDTRY */ CATCH_ALL exc_report(THIS_CATCH); /* print to stderr */ (void) tpterm(); exit(1); ENDTRY (void) tpterm(); exit(0); } The header, simp.h, which is generated by the IDL compiler based on simp.idl, has the function prototypes for the two operations. The simp.h header also includes the header files for the RPC run-time functions (none appear in this example) and exception handling. The atmi.h header file is included because tpterm(3c) is called. If an argument is provided on the command line, then it is used for the conversion to uppercase and lowercase (the default being " hello world"). Exception handling is used to catch any errors. For example, exceptions are generated for unavailable servers, memory allocation failures, communication failures, and so forth. The TRY block encapsulates the two remote procedure calls. If an error occurs, the execution will jump to the CATCH_ALL block which converts the exception ( THIS_CATCH) into a string, prints it to the standard error output using exc_report, and exits. Note that in both the abnormal and normal execution, tidl(1) is called to leave the application gracefully. If this is not done, a warning is printed in the userlog(3c) for non-Workstation clients, and resources are tied up (until the connection times out, for Workstation clients). Example A-3 server.c #include <stdio.h> #include <ctype.h> #include "tx.h" #include "simp.h" int tpsvrinit(argc, argv) int argc; char **argv; { if (tx_open() != TX_OK) { (void) userlog("tx_open failed"); return(-1); } (void) userlog("tpsvrinit() succeeds."); return(1); } void to_upper(str) idl_char *str; { idl_char *p; for (p=str; *p != '\0'; p++) *p = toupper((int)*p); return; } void to_lower(str) idl_char *str; { idl_char *p; for (p=str; *p != '\0'; p++) *p = tolower((int)*p); return; } As with client.c, this file includes simp.h. It also includes tx.h because tx_open(3c) is called (as required by the X/OPEN TxRPC specification, even if no resource manager is accessed). A tpsvrinit(3c) function is provided to ensure that tx_open() is called once at boot time. On failure, -1 is returned and the server fails to boot. This is done automatically, so you may not need to supply it. The two operation functions are provided to do the application work, in this case, converting to upper and lower case. Example A-4 rpcsimp.mk CC=cc CFLAGS= TIDL=$(TUXDIR)/bin/tidl LIBTRPC=-ltrpc all: client server # Tuxedo client client: simp.h simp_cstub.o CC=$(CC) CFLAGS=$(CFLAGS) $(TUXDIR)/bin/buildclient \ -oclient -fclient.c -fsimp_cstub.o -f$(LIBTRPC) # Tuxedo server server: simp.h simp_sstub.o CC=$(CC) CFLAGS=$(CFLAGS) $(TUXDIR)/bin/buildserver \ -oserver -s changecasev1_0 -fserver.c -fsimp_sstub.o \ -f$(LIBTRPC) simp_cstub.o simp_sstub.o simp.h: simp.idl $(TIDL) -cc_cmd "$(CC) $(CFLAGS) -c" simp.idl # # THIS PART OF THE FILE DEALING WITH THE DCE GATEWAY IS OMMITTED # # Cleanup clean:: rm -f *.o server $(ALL2) ULOG.* TUXCONFIG rm -f stderr stdout *stub.c *.h simpdce.idl gwinit.c clobber: clean The makefile builds the executable client and server programs. The part of the makefile dealing with the DCE Gateway (described in Appendix B, "A DCE-Gateway Application," is omitted from the figure. The client is dependent on the simp.h header file and the client stub object file. buildclient is executed to create the output client executable, using the client.c source file, the client stub object file, and the -ltrpc RPC run-time library. The server is dependent on the simp.h header file and the server stub object file. buildserver is an output server executable, using the server.c source file, the server stub object file, and the -ltrpc RPC run-time library. The client and server stub object files and the simp.h header file are all created by running the tidl compiler on the IDL input file. The clean target removes any files that are created while building or running the application. The following is a sample ASCII configuration file. The machine name, TUXCONFIG, TUXDIR, and APPDIR must be set based on your configuration. Example A-5 ubbconfig *RESOURCES IPCKEY 187345 MODEL SHM MASTER SITE1 PERM 0660 *MACHINES <UNAME> LMID=SITE1 TUXCONFIG="<TUXCONFIG>" TUXDIR="<TUXDIR>" APPDIR="<APPDIR>" # MAXWSCLIENTS=10 *GROUPS GROUP1 LMID=SITE1 GRPNO=1 *SERVERS server SRVGRP=GROUP1 SRVID=1 #WSL SRVGRP=GROUP1 SRVID=2 RESTART=Y GRACE=0 # CLOPT="-A -- -n <address> -x 10 -m 1 -M 10 -d <device>" # # Tuxedo-to-DCE Gateway #simpgw SRVGRP=GROUP1 SRVID=2 *SERVICES *ROUTING The lines for MAXWSCLIENTS and WSL would be uncommented and are used for a Workstation configuration. The literal netaddr for the Workstation listener must be set as described in WSL(5) in the Oracle Tuxedo File Formats and Data Descriptions Reference. Edit the ASCII ubbconfig configuration file to provide location-specific information (for example, your own directory pathnames and machine name), as described in the next step. The text to be replaced is enclosed in angle brackets. You need to substitute the full pathname for TUXDIR, TUXCONFIG, and APPDIR, and the name of the machine on which you are running. The following is a summary of the required values. TUXDIR The full pathname of the root directory of the Oracle Tuxedo software, as set above. TUXCONFIG The full pathname of the binary configuration file, as set above. APPDIR The full pathname of the directory in which your application will run. UNAME The machine name of the machine on which your application will run; this is the output of the UNIX command uname -n. For a Workstation configuration, the MAXWSCLIENTS and WSL lines must be uncommented and the < address> must be set for the Workstation Listener. (See WSL(5) for further details.) Build the client and server programs by running the following: make -f rpcsimp.mk TUXDIR=$TUXDIR Load the binary TUXCONFIG configuration file by running the following: tmloadcf -y ubbconfig The native client program can be run by optionally specifying a string to be converted first to uppercase, and then to lowercase, as shown in the following: $ client HeLlO to_upper returns: HELLO to_lower returns: hello $ When running on a Workstation, set the WSNADDR environment variable to match the address specified for the WSL program. The Windows client can be run by executing: >win wclient You can monitor the RPC server using tmadmin(1). In the following example, psr and psc are used to view the information for the server program. Note that the length of the RPC service name causes it to be truncated in terse mode (indicated by the "+"); verbose mode can be used to get the full name. Example A-6 tmadmin psr and psc Output $ tmadmin > psr a.out Name Queue Name Grp Name ID RqDone Load Done Current Service ---------- ---------- -------- -- ------ --------- --------------- BBL 587345 SITE1 0 0 0 ( IDLE ) server 00001.00001 GROUP1 1 2 100 ( IDLE ) > psc Service Name Routine Name a.out Name Grp Name ID Machine # Done Status ------------ ------------ ---------- -------- -- ------- ------ ------ ADJUNCTBB ADJUNCTBB BBL SITE1 0 SITE1 0 AVAIL ADJUNCTADMIN ADJUNCTADMIN BBL SITE1 0 SITE1 0 AVAIL changecasev+ changecasev+ server GROUP1 1 SITE1 2 AVAIL > verbose Verbose now on. > psc -g GROUP1 Service Name: changecasev1_0 Service Type: USER Routine Name: changecasev1_0 a.out Name: /home/sdf/trpc/rpcsimp/server Queue Name: 00001.00001 Process ID: 8602, Machine ID: SITE1 Group ID: GROUP1, Server ID: 1 Current Load: 50 Current Priority: 50 Current Trantime: 30 Requests Done: 2 Current status: AVAILABLE > quit Shut down the application by running the following: tmshutdown -y
http://docs.oracle.com/cd/E18050_01/tuxedo/docs11gr1/tx2/txxa.htm
CC-MAIN-2016-30
refinedweb
1,742
56.15
Apache Spark is a data analysis engine based on Hadoop MapReduce, which helps in the quick processing of Big Data. It overcomes the limitations of Hadoop and is emerging as the most popular framework for analysis. With the advent of new technologies, the data generated by various sources such as social media, Web logs, IoT, etc, is proliferating in petabytes. Traditional algorithms and storage systems aren’t sophisticated enough to cope with this enormous volume of data. Hence, there is a need to address this problem efficiently. Introducing the Apache Spark engine Apache Spark is a cluster computing framework built on top of Apache Hadoop. It extends the MapReduce model and allows quick processing of large volumes of data significantly faster, as data persists in-memory. It has fault tolerance, data parallelism capabilities and supports many libraries such as GraphX (for graph processing), MLlib (for machine learning), etc. These features have led to Spark emerging as the most popular platform for Big Data analytics and it being used by the chief players in the tech industry like eBay, Amazon and Yahoo. Spark was created in 2009 by Matei Zaharia at UC Berkeley’s AMPLab as a lightning fast cluster computing framework. In 2010, it was donated to the Apache Software Foundation under a BSD licence and has since been developed by contributors throughout the world. In November 2014, Zaharia’s enterprise, Databricks, sorted a large dataset in record time by using the Spark engine. Spark 2.0.0 is the latest release, which came out on July 26, 2016. Hadoop has been widely used due to its scalability, flexibility and the MapReduce model, but it is losing its popularity to Spark since the latter is 100x faster for in-memory computations and 10x faster for disk computations. Data is stored on disk in Hadoop but in Spark, it’s stored in memory, which reduces the IO cost. Hadoop’s MapReduce can only re-use the data by writing it to an external storage and fetching it when needed again. Iterative and interactive jobs need fast responses, but MapReduce isn’t satisfactory due to its replication, disk IO and serialisation. Spark uses RDD (Resilient Distributed Dataset), which allows better fault tolerance than Hadoop, which uses replication. Though Spark is derived from Hadoop, it isn’t a modified version of it. Hadoop is a method to implement Spark, which has its own cluster management system and can run in standalone mode, hence obviating the necessity for the former. Hadoop provides only two functions to Spark—processing by MapReduce and storage using the Hadoop Distributed File System (HDFS). Spark doesn’t replace Hadoop as the two aren’t mutually exclusive. Instead, they complement each other and result in an extremely powerful model. The power of the Apache Spark engine Speed: Spark uses in-memory cluster processing, which means it reduces the I/O operations for iterative algorithms as it stores the intermediate data generated in the memory instead of writing it back to the disk. Data can be stored on the RAM of the server machine and, hence, runs 100x quicker in memory and up to 10x faster on disk as compared to Hadoop. Moreover, due to its bottom-up engineering and the usage of RDDs, the fundamental data structure of Spark allows transparent storage of data in memory and persistence to disk only when it’s needed. ‘Lazy evaluation’ is a feature that also contributes to Spark’s speed by delaying the evaluation of any expression or operation until the value is needed by another expression. This avoids repeated evaluation of the same expression, and allows the definition of control flow and potentially infinite sets. Libraries: Spark is equipped with standard built-in high-level libraries, including compatibility with SQL queries (SparkSQL), machine learning (MLlib), and streaming data and graph processing (GraphX), in addition to the simple MapReduce functionalities of the MR model. These increase the productivity of developers by allowing them to use the functionalities in fewer lines of code, yet create complex workflows. Spark is compatible with real-time processing applications. Multiple languages: Programmers have the advantage of coding in familiar languages as Spark provides stable APIs in Java, Scala, Python, R and SQL. The Spark SQL component allows the import of structured data and its integration with unstructured data from other sources. Spark has over 100 high-level operators as it is equipped with standard built-in high-level libraries, including compatibility with SQL queries (SparkSQL), machine learning (MLlib), streaming data and graph processing (GraphX) in addition to the simple MapReduce functionalities of the MR model. It can be used in real-time processing applications by applying transformations to semi-structured data with the option of allowing interactive querying within the Spark shell. This dynamic nature has led to it being more popular than Hadoop. Hadoop support: Big Data and the cloud are synergistic and Spark’s support for cloud technologies is one of its biggest advantages. It is compatible with widely used Big Data frameworks like HDFS, Apache Cassandra, Apache Hbase, Apache Mesos and Amazon S3. Spark, which doesn’t have its own storage system, enhances the Hadoop stack by implementing it in three possible ways: 1) standalone mode, 2) over YARN, or 3) SIMR (Spark in MapReduce). It can also support existing pure Hadoop ecosystems. MapReduce alternative: Spark can be used instead of MapReduce as it executes jobs in short, micro bursts of 5 seconds or less. It is a faster framework for batch processing and iterative algorithms in comparison to Hadoop-based frameworks like Twitter Storm for live processing. Configuring Apache Spark on Ubuntu It is easy to install and configure Apache Spark on Ubuntu. A native Linux system is preferred as it provides the best environment for deployment. Virtual OSs can also be used, but the performance gets compromised when compared to the native versions. Dual OSs work satisfactorily. There are options to use a standalone version or use a version pre-built for Hadoop, which utilises the existing Hadoop components such as HDFS or a version built to be deployed on YARN. The following section will explain how to get Spark 2.0.0 standalone mode running on Ubuntu 14.04 or later. Installing Java: To install and configure Spark, your machine needs Java. Use the following commands in a terminal to automatically download and update Java: $sudo apt-add-repository ppa:webupd8team/java $ sudo apt-get update $ sudo apt-get install oracle-java7-installer You can check for an existing version by typing: $ java –version Installing Scala: Spark is written in Scala; so we need it to install the former. Download version 2.10.4 or later from. Untar the file by using the following command: $ sudo tar xvf scala-2.10.4.tgz Add an entry for Scala in the file .bashrc, as follows: nano ~/.bashrc At the end of the file, add the path given below to show the location of the Scala file: export SCALA_HOME=<path-where-scala-file-is-located> export PATH=$SCALA_HOME/bin:$PATH Then we need to source the changed .bashrc file by using the command given below: source ~/.bashrc We can verify the Spark installation by using the following command: $scala -version Installing Spark: Download the standalone cluster version of Spark from its website Then extract the file by typing the following command in the terminal: $ tar xvf spark-2.0.0-bin-hadoop2.6.tgz Add entry to .bashrc by: nano ~/.bashrc Add the line specifying the location to ~/.bashrc by: export SPARK_HOME=/home/sapna/spark-2.0.0-bin-hadoop2.6/ export PATH=$PATH:$SPARK_HOME/bin Then source it by using the command below: $ source ~/.bashrc Start Spark services and the shell. Then let’s change the directory by going into Spark’s folder and manually starting the master cluster using the command shown below: cd spark-2.0.0-bin-hadoop2.6 ./sbin/start-master.sh After running this, you can view the user interface of the master node by typing the following command in the browser: You can start the slave node by giving the following command: ./sbin/start-slave.sh <name of slave node to run> To check if the nodes are running, execute the following: Jps Architecture of the Apache Spark engine Spark uses a master/worker architecture. There is a driver called the Spark Context object, which interacts with a single coordinator called the master that manages workers in which executors run. Spark is founded on two chief concepts—the RDD (Resilient Distributed Dataset) and DAG (Directed Acyclic Graph) execution engine. An RDD, a read-only immutable collection of objects, is the basic data structure of Spark. The data is partitioned, and each RDD can be computed on a different node and can be written in many languages. It stores the state of the memory as an object across the jobs and the object is shareable between those jobs. RDD can transform data by mapping or filtering it, or it can perform operations and return values. RDDs can be parallelised and are intrinsically fault-tolerant. They can be created through two methods—by taking an existing collection in your driver application and parallelising it or by creating a reference from an external storage system like HDFS, HBase, AWS, etc. The DAG helps to obviate the multi-staged model of MapReduce which offers processing advantages. Spark can be deployed in three popular ways to cater to different scenarios. The first way is to use a standalone mode. Here, Spark is placed above HDFS and allocates memory to it manually. All Spark jobs on the clusters are executed with Spark and MapReduce running simultaneously. The second way is to use a cluster management system such as Hadoop YARN (Yet Another Resource Manager), which doesn’t require any pre-installation or root access to integrate with the Hadoop stack or ecosystem. Other components can be externally added on top to increase the functionality. The third way is to use SIMR (Spark in MapReduce) which, in addition to a manager, also executes a Spark job. Spark shell can be used without any administrative authorisation. The main elements that constitute Spark are: Spark Core, MLlib, GraphX, Spark Streaming and Spark SQL. Spark Core is the basic platform engine that serves as a foundation for building other functionalities. The Spark SQL component, which provides the abstraction called SchemaRDD, which allows the loading, analysis and processing of semi-structured and structured datasets, is built on top of this. Spark Streaming allows live streaming and analysis of data loaded into RDDs as mini-batches. MLlib is an extensive library, which helps to implement machine learning methods on Big Data sets. It is created by a community of programmers from across the world. GraphX is a distributed graph-processing framework, which provides an API for expressing graph computation that can model the user-defined graphs by using the Pregel abstraction API. In addition, GraphX includes a growing collection of graph algorithms and builders to optimise graph analytics tasks. Spark applications run independently on sets of clusters that are managed by a SparkContext object in the driver program. A SparkContext instance can connect with managers such as Mesos or YARN and can allocate resources to different commodity machines for optimised performance. After allocation, the executors on each job receive the application code and tasks, which are utilised to execute the job. Each Spark application has its own executors which can do multi-threading. Data needs to be stored on external storages for different Spark applications to share it. Getting started with the Apache Spark engine The following section explores how to start the Spark engine and get the services started. It will show how to execute existing programs, how to start the client or server and how to launch the shell. Starting Spark services and the shell We will change the directory, go into Spark’s folder and manually start the master cluster by using the following command: cd spark-2.0.0-bin-hadoop2.6 ./sbin/start-master.sh After running this, you can view the user interface of the master node by typing the following command in the browser: You can start the slave node by using the following command: ./sbin/start-slave.sh <name of slave node to run> To check if nodes are running, execute the following: jps Running the Spark shell You can run the Spark shell for Scala using the command given below: $ bin/spark-shell You can run the Spark shell for Python by using the following command: $ bin/pyspark Submitting an existing application in Spark First, let us compile a file that contains the code for a program which is to be run in Spark later on: $ scalac -classpath “spark-core_2.10-2.0.0.jar:/usr/local/spark/lib/spark-assembly-2.0.0-hadoop2.6.0.jar” <file name> Then, let’s create a JAR file out of the compiled file, as follows: jar -cvf wordcount.jar SparkWordCount*.class spark-core_2.10-1.3.0.jar/usr/local/spark/lib/spark-assembly-1.4.0-hadoop2.6.0.jar Now, submit the JAR file to Spark to run the application, as follows: $ spark-submit --class <application name> --master local <jar file name> Writing and executing basic scripts in the Apache Spark engine Since we have already learnt how to start the shell and submit jobs through it after creating and compiling JAR files, let’s now write and execute a simple WordCount example in Scala to be deployed on Spark. First, create a simple input.txt file from the sentence given below and put it in the Spark application folder containing all other jar files and program code: “This is my first small word count program using Spark. I will use a simple MapReduce program made in Scala to count the frequency of each word.” Next, open the Spark shell: $ spark-shell Then make an RDD, which will read the data from our input.txt file. sc is SparkContext object, which is a manager of all the RDDs: scala> val inputfile = sc.textFile(“input.txt”) We apply transformations to the data by splitting each line into individual words. Earlier, one line was one entity but now each word is an entity. Next, let’s count the frequency of each word and then reduce it by its key, by adding the frequency of each distinct word, using the code shown below: scala> val counts = inputfile.flatMap(line => line.split(“ “)).map(word => (word, 1)).reduceByKey(_+_); We can cache the output for it to persist, as follows: scala> counts.cache() Or we can store it to an external text file, as follows: scala> counts.saveAsTextFile(“output”) We can check the output as follows: $ cd output/ $ ls -1 Print the output on the Spark screen, using the command shown below: $ cat part-00000 $ cat part-00001 Analysing Big Data using the Apache Spark engine With the advancement in technology, Web servers, machine log files, IoT, social media, user clicks, Web streaming, etc, are all generating petabytes of data, daily. Most of this is semi-structured or unstructured. This Big Data is characterised by high velocity, high volume and high variability; hence, traditional algorithms and processing technologies are unable to cope with it. MapReduce was able to process this data satisfactorily using a cluster of commodity hardware. But the ever-increasing volume of data is exceeding the capability of MapReduce due to the reasons mentioned earlier. Spark was designed as an answer to the limitations of MapReduce. It provides an abstraction of memory for sharing data and for in-memory computing. RDD can be persisted and re-used for other computations. Spark’s multi-platform support, the ability to integrate with Hadoop, and its compatibility with the cloud make it tailor-made for Big Data. In the real world, Spark is used for many applications. Banks analyse large volumes of data from sources like social media, email, complaint logs, call records, etc, to gain knowledge for credit risk assessment, customer segmentation or targeted advertising. Even credit card fraud can be checked by it. E-commerce sites use the streaming clustering algorithm to analyse real-time transactions for advertising or to recommend products to customers by gaining insights from sources like review forums, comments, social media, etc. Shopify, Alibaba and eBay use these techniques. The healthcare sector benefits from Spark as it enables quick diagnosis and filters out individuals who are at risk. The MyFitnessPal app uses Spark to process the data of all its active users. Spark is widely used in genome sequencing and DNA analysis as millions of strands of chromosomes have to be matched. This task earlier took weeks but now takes only hours. Spark is also being used by the entertainment industry (such as Pinterest, Netflix and Yahoo News) for personalisation and recommendation systems. Sample Big Data processing using the Apache Spark engine Let’s look at a simple application for beginners that can process Big Data. Let’s load the dataset of ‘Five Thirty Eight’, a popular US TV show, and perform simple aggregation functions. Download the data for the past 50 years using. Create an RDD, read the data and print the first five lines using the following code. raw_data = sc.textFile(“daily_show_guests.csv”) raw_data.take(5) Then, split each word by using a map function, as follows: daily_show = raw_data.map(lambda line: line.split(‘,’)) daily_show.take(5) Next, define a function to calculate the tally of guests each year, as shown below: tally = dict() for line in daily_show: year = line[0] if year in tally.keys(): tally[year] = tally[year] + 1 else: tally[year] = 1 Execute the function by using the Reduce transformation, as shown below: tally = daily_show.map(lambda x: (x[0], 1)) .reduceByKey(lambda x,y: x+y) print(tally) tally.take(tally.count()) Now use a filter function, which segregates according to professions to create an RDD from an existing RDD: def filter_year(line): if line[0] == ‘YEAR’: return False else: return True filtered_daily_show = daily_show.filter(lambda line: filter_year(line)) Now, execute this filter by doing reduce transformations: filtered_daily_show.filter(lambda line: line[1] != ‘’) \ .map(lambda line: (line[1].lower(), 1))\ .reduceByKey(lambda x,y: x+y) \ .take(5) This completes the overview of one of the most promising technologies in the domain of Big Data. Spark’s features and architecture give it an edge over prevailing frameworks such as Hadoop. Spark can be implemented on Hadoop, and its efficiency increases due to the use of both technologies synergistically. Due to its several integrations and adapters, Spark can be combined with other technologies as well. For example, we can use Spark, Kafka and Apache Cassandra together — Kafka can be used for streaming the data, Spark for computation and Cassandra NoSQL database to store the result data. However, Spark is still being developed. It is comparatively a less mature ecosystem and there are a lot of areas, such as security and business integration tools, which need improvement. Nevertheless, Spark is here to stay for a long time. Connect With Us
http://opensourceforu.com/2017/01/apache-spark-the-ultimate-panacea-for-the-big-data-era/
CC-MAIN-2017-04
refinedweb
3,186
52.7
IWP60 | More on Imaging Scenario Resources for WP Developers >>IMAGE code. In addition to his discussion here, you can also see Matt's Build 2013 talk in which he dives deeper into his Real World Stocks app. Build For Both: Windows and Windows Phone - Matt Hidinger Real World Stocks source (Windows & Windows Phone) One thing I've learned from talking about Build For Both is that you can never have enough samples or enough guidance. So in addition to Matt's code, Matthias Shapiro also has a "Build For Both" project build around the Philips Hue WiFi enabled lights that was also demoed at Build 2013. While the title of the talk is MVVM, the project features a complete solution for both Windows Phone and Windows. This App Is Brought to You by MVVM - Hulu Case Study - Matthias Shapiro and Zachary Pinter Hue For Both - Windows and Windows Phone Additionally, in the MVVM talk listed above Zachary Pinter from Hulu joined Matthias to talk about how Hulu created a "Build For Both" solution that shares code across projects. It is a fantastic demonstration of the power of good architecture to create apps that live on Windows and Windows Phone. As if that were not enough, Zachary also explains his techniques further in a post on the Hulu Tech Blog. Tips and Highlights From Developing Mobile Apps for Windows - Zachary Pinter Finally, if you're more interested in reading that watching, check out the July 2013 issue of MSDN Magazine, which features an article from Joel Reyes on building apps for Windows 8 and Windows Phone 8. Joel's piece is one of the most complete discussions on the topic, covering details around UX strategies, application lifecycle, tiles, background tasks, you name it. Building Apps for Windows 8 and Windows Phone 8 - Joel Reyes This code sharing is not so perfect at present but I think that in this show are explained some good tips with the default namespace and shortcuts for class files. Thanks. I don't think its really hard to figure out how to develop apps using .NET. It would be great to see more sessions on developing WP 8 applications using C++ and on the topics how to enumerate or walking thru processes list, how much each process consuming CPU and Virtual memory. Thanks Bueno, HTML es una base para empezar a programar en Windows pone 8 y Windows 8, asi que seria útil un tutorial de estos
https://channel9.msdn.com/Shows/Inside+Windows+Phone/Building-for-Windows-Phone-and-Windows-8-The-Basics?format=progressive
CC-MAIN-2018-26
refinedweb
411
59.06
> > > We in agreement that changing the URI for the namespaces to remove > 'adobe' would also be good. maybe we could provide a simple AIR tool that > performs the find and replace on a codebase for both the URI, and spark > container/controls packages. > > I think we need to think very carefully about anything that breaks > backwards compatibility for users of the SDK and if it does provide a very > clear path on how to update. There's lot of useful code on blogs, in books, > training material etc etc having that no longer work would cause a few of > issues. > > Justin I agree. Changing URI for existing namespaces would cause unnecessary hardship for users of the SDK. Moreover, we cannot assume that code will be available for search and replace operations. For example, folks using commercial/pre-packaged swc components wont have that option. Om
http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201207.mbox/%3CCACK5iZeAL7AA+_onqTYKWjvQzaLM2w4HDE8X63pzZAnmbZ2dJw@mail.gmail.com%3E
CC-MAIN-2017-09
refinedweb
145
70.53
im_grid - split a vertical image into a grid of smaller images #include <vips/vips.h> int im_grid( IMAGE *in, IMAGE *out, int tile_height, int across, int down ) im_grid(3) slices image in into a set of tiles, each the same width as in and of height tile_height and rearranges the tiles into a grid with across tiles across and down tiles down. It is useful for loading volumetric images (for example, CT or PET scans) where more than 2 dimensions need to be displayed. The current implementation is optimised for the case where image in is thin and tall and across and down are large. The function returns 0 on success and -1 on error. im_extract_area(3), im_zoom(3) Imperial College 2005 4 August 2005
http://huge-man-linux.net/man3/im_grid.html
CC-MAIN-2018-26
refinedweb
125
68.1
This article outlines an approach for using GUID values as primary keys/clustered indexes that avoids most of the normal disadvantages, adapting the COMB model for sequential GUIDs developed by Jimmy Nilsson in his article The Cost of GUIDs as Primary Keys. While that basic model has been used by a variety of libraries and frameworks (including NHibernate), most implementations seem to be specific to Microsoft SQL Server. This article attempts to adapt the approach into a flexible system that's can be used with other common database systems such as Oracle, PostgreSQL, and MySQL, and also addresses some of the eccentricities of the .NET Framework in particular. Historically, a very common model for database design has used sequential integers to identify a row of data, usually generated by the server itself when the new row is inserted. This is a simple, clean approach that's suitable for many applications. However, there are also some situations where it's not ideal. With the increasing use of Object-Relational Mapping (ORM) frameworks such as NHibernate and the ADO.NET Entity Framework, relying on the server to generate key values adds a lot of complication that most people would prefer to avoid. Likewise, replication scenarios also make it problematic to rely on a single authoritative source for key value creation -- the entire point is to minimize the role of a single authority. One tempting alternative is to use GUIDs as key values. A GUID (globally unique identifier), also known as a UUID, is a 128-bit value that carries a reasonable guarantee of being unique across all of space and time. Standards for creating GUIDs are described in RFC 4122, but most GUID-creation algorithms in common use today are either essentially a very long random number, or else combine a random-appearing component with some kind of identifying information for the local system, such as a network MAC address. GUIDs have the advantage of allowing developers to create new key values on the fly without having to check in with the server, and without having to worry that the value might already be used by someone else. At first glance, they seem to provide a good answer to the problem. So what's the issue? Well, performance. To get the best performance, most databases store rows in what's known as a clustered index, meaning that the rows in a table are actually stored on disk in a sorted order, usually based on a primary key value. This makes finding a single row as simple as doing a quick lookup in the index, but it can make adding new rows to the table very slow if their primary key doesn't fall at the end of the list. For example, consider the following data: Pretty simple so far: the rows are stored in order according to the value of the ID column. If we add a new row with an ID of 8, it's no problem: the row just gets tacked on to the end. But now suppose we want to insert a row with an ID of 5: Rows 7 and 8 have to be moved down to make room. Not such a big deal here, but when you're talking about inserting something into the middle of a table with millions of rows, it starts becoming an issue. And when you want to do it a hundred times a second, it can really, really add up. And that's the problem with GUIDs: they may or may not be truly random, but most of them look random, in the sense that they're not usually generated to have any particular kind of order. For that reason, it's generally considered a very bad practice to use a GUID value as part of a primary key in a database of any significant size. Inserts can be very slow and involve a huge amount of unnecessary disk activity. So, what's the solution? Well, the main problem with GUIDs is their lack of sequence. So, let's add a sequence. The COMB approach (which stands for COMBined GUID/timestamp) replaces a portion of the GUID with a value which is guaranteed to increase, or at least not decrease, with each new value generated. As the name implies, it does this by using a value generated from the current date and time. To illustrate, consider this list of typical GUID values: Now consider this hypothetical list of special GUID values: 00000001-a411-491d-969a-77bf40f5517500000002-d97d-4bb9-a493-cad27799936300000003-916c-4986-a363-0a9b9c95ca5200000004-f827-452b-a3be-b77a3a4c95aa 00000001-a411-491d-969a-77bf40f55175 00000002-d97d-4bb9-a493-cad277999363 00000003-916c-4986-a363-0a9b9c95ca52 00000004-f827-452b-a3be-b77a3a4c95aa The first block of digits has been replaced with an increasing sequence -- say, the number of milliseconds since the program started. Inserting a million rows of these values wouldn't be so bad, since each row would simply be appended to the end of the list and not require any reshuffling of existing data. Now that we have our basic concept, we need to get into some of the details of how GUIDs are constructed and how they're handled by different database systems. 128-bit GUIDs are composed of four main blocks, called Data1, Data2, Data3, and Data4, which you can see in the example below: 11111111-2222-3333-4444-444444444444 Data1 is four bytes, Data2 is two bytes, Data3 is two bytes, and Data4 is eight bytes (a few bits of Data3 and the first part of Data4 are reserved for version information, but that's more or less the structure). Most GUID algorithms in use today, and especially those used by the .NET Framework, are pretty much just fancy random number generators (Microsoft used to include the local machine's MAC address as part of the GUID, but discontinued that practice several years ago due to privacy concerns). This is good news for us, because it means that playing around with different parts of the value is unlikely to damage the value's uniqueness all that much. But unfortunately for us, different databases handle GUIDs in different ways. Some systems (Microsoft SQL Server, PostgreSQL) have a built-in GUID type which can store and manipulate GUIDs directly. Databases without native GUID support have different conventions on how they can be emulated. MySQL, for example, most commonly stores GUIDs by writing their string representation to a char(36) column. Oracle usually stores the raw bytes of a GUID value in a raw(16) column. It gets even more complicated, because one eccentricity of Microsoft SQL Server is that it orders GUID values according to the least significant six bytes (i.e. the last six bytes of the Data4 block). So, if we want to create a sequential GUID for use with SQL Server, we have to put the sequential portion at the end. Most other database systems will want it at the beginning. Looking at the different ways databases handle GUIDs, it's clear that there can be no one-size-fits-all algorithm for sequential GUIDs; we'll have to customize it for our particular application. After doing some experimentation, I've identified three main approaches that cover most pretty much all use cases: (Why aren't GUIDs stored as strings the same as GUIDs stored as bytes? Because of the way .NET handles GUIDs, the string representation may not be what you expect on little-endian systems, which is most machines likely to be running .NET. More on that later.) I've represented these choices in code as an enumeration: public enum SequentialGuidType { SequentialAsString, SequentialAsBinary, SequentialAtEnd } Now we can define a method to generate our GUID which accepts one of those enumeration values, and tailor the result accordingly: public Guid NewSequentialGuid(SequentialGuidType guidType) { ... } But how exactly do we create a sequential GUID? Exactly which part of it do we keep "random," and which part do we replace with a timestamp? Well, the original COMB specification, tailored for SQL Server, replaced the last six bytes of Data4 with a timestamp value. This was partially out of convenience, since those six bytes are what SQL Server uses to order GUID values, but six bytes for a timestamp is a decent enough balance. That leaves ten bytes for the random component. What makes the most sense to me is to start with a fresh random GUID. Like I just said, we need ten random bytes: var rng = new System.Security.Cryptography.RNGCryptoServiceProvider(); byte[] randomBytes = new byte[10]; rng.GetBytes(randomBytes); We use RNGCryptoServiceProvider to generate our random component because System.Random has some deficiencies that make it unsuitable for this purpose (the numbers it generates follow some identifiable patterns, for example, and will cycle after no more than 232 iterations). Since we're relying on randomness to give us as much of a guarantee of uniqueness as we can realistically have, it's in our interests to make sure our initial state is as strongly random as it can be, and RNGCryptoServiceProvider provides cryptographically strong random data. RNGCryptoServiceProvider System.Random (It's also relatively slow, however, and so if performance is critical you might want to consider another method -- simply initializing a byte array with data from Guid.NewGuid(), for example. I avoided this approach because Guid.NewGuid() itself makes no guarantees of randomness; that's just how the current implementation appears to work. So, I choose to err on the side of caution and stick with a method I know will function reliably.) Guid.NewGuid() Okay, we now have the random portion of our new value, and all that remains is to replace part of it with our timestamp. We decided on a six-byte timestamp, but what should it be based on? One obvious choice would be to use DateTime.Now (or, as Rich Andersen points out, DateTime.UtcNow for better performance) and convert it to a six-byte integer value somehow. The Ticks property is tempting: it returns the number of 100-nanosecond intervals that have elapsed since January 1, 0001 A.D. However, there are a couple hitches. DateTime.Now DateTime.UtcNow Ticks First, since Ticks returns a 64-bit integer and we only have 48 bits to play with, we'd have to chop off two bytes, and the remaining 48 bits' worth of 100-nanosecond intervals gives us less than a year before it overflows and cycles. This would ruin the sequential ordering we're trying to set up, and destroy the performance gains we're hoping for, and since many applications will be in service longer than a year, we have to use a less precise measure of time. The other difficulty is that DateTime.UtcNow has a limited resolution. According to the docs, the value might only update every 10 milliseconds. (It seems to update more frequently on some systems, but we can't rely on that.) The good news is, those two hitches sort of cancel each other out: the limited resolution means there's no point in using the entire Ticks value. So, instead of using ticks directly, we'll divide by 10,000 to give us the number of milliseconds that have elapsed since January 1, 0001, and then the least significant 48 bits of that will become our timestamp. I use milliseconds because, even though DateTime.UtcNow is currently limited to 10-millisecond resolution on some systems, it may improve in the future, and I'd like to leave room for that. Reducing the resolution of our timestamp to milliseconds also gives us until about 5800 A.D. before it overflows and cycles; hopefully this will be sufficient for most applications. Before we continue, a short footnote about this approach: using a 1-millisecond-resolution timestamp means that GUIDs generated very close together might have the same timestamp value, and so will not be sequential. This might be a common occurrence for some applications, and in fact I experimented with some alternate approaches, such as using a higher-resolution timer such as System.Diagnostics.Stopwatch, or combining the timestamp with a "counter" that would guarantee the sequence continued until the timestamp updated. However, during testing I found that this made no discernible difference at all, even when dozens or even hundreds of GUIDs were being generated within the same one-millisecond window. This is consistent with what Jimmy Nilsson encountered during his testing with COMBs as well. With that in mind, I went with the method outlined here, since it's far simpler. System.Diagnostics.Stopwatch Here's the code: long timestamp = DateTime.UtcNow.Ticks / 10000L; byte[] timestampBytes = BitConverter.GetBytes(timestamp); Now we have our timestamp. However, since we obtained the bytes from a numeric value using BitConverter, we have to account for byte order. BitConverter if (BitConverter.IsLittleEndian) { Array.Reverse(timestampBytes); } We have the bytes for the random portion of our GUID, and we have the bytes for the timestamp, so all that remains is to combine them. At this point we have to tailor the format according to to the SequentialGuidType value passed in to our method. For SequentialAsBinary and SequentialAsString types, we copy the timestamp first, followed by the random component. For SequentialAtEnd types, the opposite. SequentialGuidType SequentialAsBinary SequentialAsString SequentialAtEnd byte[] guidBytes = new byte[16]; switch (guidType) { case SequentialGuidType.SequentialAsString: case SequentialGuidType.SequentialAsBinary: Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6); Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10); break; case SequentialGuidType.SequentialAtEnd: Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10); Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6); break; } So far, so good. But now we get to one of the eccentricities of the .NET Framework: it doesn't just treat GUIDs as a sequence of bytes. For some reason, it regards a GUID as a struct containing a 32-bit integer, two 16-bit integers, and eight individual bytes. In other words, it regards the Data1 block as an Int32, the Data2 and Data3 blocks as two Int16s, and the Data4 block as a Byte[8]. Int32 Int16 Byte[8] What does this mean for us? Well, the main issue has to do with byte ordering again. Since .NET thinks it's dealing with numeric values, we have to compensate on little-endian systems -- BUT! -- only for applications that will be converting the GUID value to a string, and have the timestamp portion at the beginning of the GUID (the ones with the timestamp portion at the end don't have anything important in the "numeric" parts of the GUID, so we don't have to do anything with them). This is the reason I mentioned above for distinguishing between GUIDs that will be stored as strings and GUIDs that will be stored as binary data. For databases that store them as strings, ORM frameworks and applications will probably want to use the ToString() method to generate SQL INSERT statements, meaning we have to correct for the endianness issue. For databases that store them as binary data, they'll probably use Guid.ToByteArray() to generate the string for INSERTs, meaning no correction is necessary. So, we have one last thing to add: ToString() Guid.ToByteArray() if (guidType == SequentialGuidType.SequentialAsString && BitConverter.IsLittleEndian) { Array.Reverse(guidBytes, 0, 4); Array.Reverse(guidBytes, 4, 2); } Now we're done, and we can use our byte array to construct and return a GUID: return new Guid(guidBytes); To use our method, we first have to determine which type of GUID is best for our database and any ORM framework we're using. Here's a quick rule of thumb for some common database types, although these might vary depending on the details of your application: SequentialAsBinary BinaryGUID Here are a few examples generated by our new method. First, NewSequentialGuid(SequentialGuidType.SequentialAsString): 39babcb4-e446-4ed5-4012-2e27653a9d1339babcb4-e447-ae68-4a32-19eb8d91765d39babcb4-e44a-6c41-0fb4-21edd4697f4339babcb4-e44d-51d2-c4b0-7d8489691c70 39babcb4-e446-4ed5-4012-2e27653a9d13 39babcb4-e447-ae68-4a32-19eb8d91765d 39babcb4-e44a-6c41-0fb4-21edd4697f43 39babcb4-e44d-51d2-c4b0-7d8489691c70 As you can see, the first six bytes (the first two blocks) are in sequential order, and the remainder is random. Inserting these values into a database that stores GUIDs as strings (such as MySQL) should provide a performance gain over non-sequential values. Next, NewSequentialGuid(SequentialGuidType.SequentialAtEnd): a47ec5e3-8d62-4cc1-e132-39babcb4e47a939aa853-5dc9-4542-0064-39babcb4e47c7c06fdf6-dca2-4a1a-c3d7-39babcb4e47dc21a4d6f-407e-48cf-656c-39babcb4e480 a47ec5e3-8d62-4cc1-e132-39babcb4e47a 939aa853-5dc9-4542-0064-39babcb4e47c 7c06fdf6-dca2-4a1a-c3d7-39babcb4e47d c21a4d6f-407e-48cf-656c-39babcb4e480 As we'd expect, the last six bytes are sequential, and the rest is random. I have no idea why SQL Server orders uniqueidentifier indexes this way, but it does, and this should work well. uniqueidentifier And finally, NewSequentialGuid(SequentialGuidType.SequentialAsBinary): b4bcba39-58eb-47ce-8890-71e7867d67a5b4bcba39-5aeb-42a0-0b11-db83dd3c635bb4bcba39-6aeb-4129-a9a5-a500aac0c5cdb4bcba39-6ceb-494d-a978-c29cef95d37f b4bcba39-58eb-47ce-8890-71e7867d67a5 b4bcba39-5aeb-42a0-0b11-db83dd3c635b b4bcba39-6aeb-4129-a9a5-a500aac0c5cd b4bcba39-6ceb-494d-a978-c29cef95d37f When viewed here in the format ToString() would output, we can see that something looks wrong. The first two blocks are "jumbled" due to having all their bytes reversed (this is due to the endianness issue discussed earlier). If we were to insert these values into a text field (like they would be under MySQL), the performance would not be ideal. However, this problem is appearing because the four values in that list were generated using the ToString() method. Suppose instead that the same four GUIDs were converted into a hex string using the array returned by Guid.ToByteArray(): 39babcb4eb5847ce889071e7867d67a539babcb4eb5a42a00b11db83dd3c635b39babcb4eb6a4129a9a5a500aac0c5cd39babcb4eb6c494da978c29cef95d37f 39babcb4eb5847ce889071e7867d67a5 39babcb4eb5a42a00b11db83dd3c635b 39babcb4eb6a4129a9a5a500aac0c5cd 39babcb4eb6c494da978c29cef95d37f This is how an ORM framework would most likely generate INSERT statements for an Oracle database, for example, and you can see that, when formatted this way, the sequence is again visible. So, to recap, we now have a method that can generate sequential GUID values for any of three different database types: those that store as strings (MySQL, sometimes SQLite), those that store as binary data (Oracle, PostgreSQL), and Microsoft SQL Server, which has its own bizarre storage scheme. We could customize our method further, having it auto-detect the database type based on a value in the application settings, or we could create an overload that would accept the DbConnection we're using and determine the correct type from that, but that would depend on the details of the application and any ORM framework being used. Call it homework! DbConnection For testing, I focused on four common database systems: Microsoft SQL Server 2008, MySQL 5.5, Oracle XE 11.2, and PostgreSQL 9.1, all running under Windows 7 on my desktop. (If someone would like to run tests on more database types or under other operating systems, I'd be happy to help any way I can!) Tests were performed by using each database system's command-line tool to insert 2 millions rows into a table with a GUID primary key and a 100-character text field. One test was performed using each of the three methods described above, with a fourth test using the Guid.NewGuid() method as a control. For comparison, I also ran a fifth test inserting 2 million rows into a similar table with an integer primary key. The time (in seconds) to complete the inserts was recorded after the first million rows, and then again after the second million rows. Here are the results: For SQL Server, we would expect the SequentialAtEnd method to work best (since it was added especially for SQL Server), and things are looking good: GUID inserts using that method are only 8.4% slower than an integer primary key -- definitely acceptable. This represents a 75% improvement over the performance of a random GUID. You can also see that the SequentialAsBinary and SequentialAsString methods provide only a small benefit over a random GUID, also as we would expect. Another important indicator is that, for random GUIDs, the second millions inserts took longer than the first million, which is consistent with a lot of page-shuffling to maintain the clustered index as more rows get added in the middle, whereas for the SequentialAtEnd method, the second million took nearly the same amount of time as the first, indicating that new rows were simply being appended to the end of the table. So far, so good. As you can see, MySQL had very poor performance with non-sequential GUIDs -- so poor that I had to cut off the top of the chart to make the other bars readable (the second million rows took over half again as long as the first million). However, performance with the SequentialAsString method was almost identical to an integer primary key, which is what we'd expect since GUIDs are typically stored as char(36) fields in MySQL. Performance with the SequentialAsBinary method was also similar, probably due to the fact that, even with incorrect byte order, the values are "sort of" sequential, as a whole. Oracle is harder to get a handle on. Storing GUIDs as raw(16) columns, we would expect the SequentialAsBinary method to be the fastest, and it is, but even random GUIDs weren't too much slower than integers. Moreover, sequential GUID inserts were faster than integer inserts, which is hard to accept. While sequential GUIDs did produce measurable improvement in these benchmarks, I have to wonder if the weirdness here is due to my inexperience with writing good batch inserts for Oracle. If anyone else would like to take a stab at it, please let me know! And finally, PostgreSQL. Like Oracle, performance wasn't horrible even with random GUIDs, but the difference for sequential GUIDs was somewhat more pronounced. As expected, the SequentialAsString method was fastest, taking only 7.8% longer than an integer primary key, and nearly twice as fast as a random GUID. There are a few other things to take into consideration. A lot of emphasis has been placed on the performance of inserting sequential GUIDs, but what about the performance of creating them? How long does it take to generate a sequential GUID, compared to Guid.NewGuid()? Well, it's definitely slower: on my system, I could generate a million random GUIDs in 140 milliseconds, but sequential GUIDs took 2800 milliseconds -- twenty times slower. Some quick tests showed that the lion's share of that slowness is due to the use of RNGCryptoServiceProvider to generate our random data; switching to System.Random brought the result down to about 400 milliseconds. I still don't recommend doing this, however, since System.Random remains problematic for these purposes. However, it may be possible to use an alternate algorithm that's both faster and acceptably strong -- I don't know much about random number generators, frankly. Is the slower creation a concern? Personally, I find it acceptable. Unless your application involves very frequent inserts (in which case a GUID key may not be ideal for other reasons), the cost of occasional GUID creation will pale in comparison to the benefits of faster database operations. Another concern: replacing six bytes of the GUID with a timestamp means only ten bytes are left for random data. Does this jeopardize uniqueness? Well, it depends on the circumstances. Including a timestamp means that any two GUIDs created more than a few milliseconds apart are guaranteed to be unique -- a promise that a completely random GUID (such as those returned by Guid.NewGuid()) can't make. But what about GUIDs created very close together? Well, ten bytes of cryptographically strong randomness means 280, or 1,208,925,819,614,629,174,706,176 possible combinations. The probability of two GUIDs generated within a handful of milliseconds having the same random component is probably insignificant compared to, say, the odds of the database server and all its backups being destroyed by simultaneous wild pig attacks. One last issue is that the GUIDs generated here aren't technically compliant with the formats specified in RFC 4122 -- they lack the version number that usually occupies bits 48 through 51, for example. I don't personally think it's a big deal; I don't know of any databases that actually care about the internal structure of a GUID, and omitting the version block gives us an extra four bits of randomness. However, we could easily add it back if desired. Here's the complete version of the method. Some small changes have been made to the code given above (such as abstracting the random number generator out to a static instance, and refactoring the switch() block a bit): switch() using System; using System.Security.Cryptography; public enum SequentialGuidType { SequentialAsString, SequentialAsBinary, SequentialAtEnd } public static class SequentialGuidGenerator { private static readonly RNGCryptoServiceProvider _rng = new RNGCryptoServiceProvider(); public static Guid NewSequentialGuid(SequentialGuidType guidType) { byte[] randomBytes = new byte[10]; _rng.GetBytes(randomBytes); long timestamp = DateTime.UtcNow.Ticks / 10000L; byte[] timestampBytes = BitConverter.GetBytes(timestamp); if (BitConverter.IsLittleEndian) { Array.Reverse(timestampBytes); } byte[] guidBytes = new byte[16]; switch (guidType) { case SequentialGuidType.SequentialAsString: case SequentialGuidType.SequentialAsBinary: Buffer.BlockCopy(timestampBytes, 2, guidBytes, 0, 6); Buffer.BlockCopy(randomBytes, 0, guidBytes, 6, 10); // If formatting as a string, we have to reverse the order // of the Data1 and Data2 blocks on little-endian systems. if (guidType == SequentialGuidType.SequentialAsString && BitConverter.IsLittleEndian) { Array.Reverse(guidBytes, 0, 4); Array.Reverse(guidBytes, 4, 2); } break; case SequentialGuidType.SequentialAtEnd: Buffer.BlockCopy(randomBytes, 0, guidBytes, 0, 10); Buffer.BlockCopy(timestampBytes, 2, guidBytes, 10, 6); break; } return new Guid(guidBytes); } } Final code and a demo project can be found at[^] As I mentioned at the beginning, the general COMB approach has been used fairly heavily by various frameworks, and the general concept isn't particularly new, and certainly not original to me. My goal here was to illustrate the ways in which the approach has to be adapted to fit different database types, as well as to provide benchmark information underscoring the need for a tailored approach. With a little effort and a moderate amount of testing, it's possible to implement a consistent way of generating sequential GUIDs that can easily be used as high-performance primary keys under pretty much any database system. v1 - Wrote the thing! v1 v2 - Adopted Rich Andersen's suggestion of using DateTime.UtcNow instead of DateTime.Now, for improved performance and updated code formatting..
http://www.codeproject.com/Articles/388157/GUIDs-as-fast-primary-keys-under-multiple-database?fid=1724727&df=90&mpp=10&sort=Position&spc=None&tid=4290776
CC-MAIN-2014-41
refinedweb
4,377
52.19
We are about to switch to a new forum software. Until then we have removed the registration on this forum. Hi there, I'm working on a face detection code that will put a square around your face when its detected, but will display text or an image when no face is detected on screen. Ideally I'd like it to respond after a couple of second of no detection but anything is better than nothing! I currently have the face detection code working. But when trying to add an if clause for null faces make an action - it doesn't work when I run the code - any help is greatly appreciated. Here is the current code: import gab.opencv.*; import processing.video.*; import java.awt.Rectangle; Capture cam; OpenCV opencv; Rectangle[] faces; void setup() { size(640, 480, P2D); background (0, 0, 0); cam = new Capture( this, 640, 480, 30); cam.start(); opencv = new OpenCV(this, cam.width, cam.height); opencv.loadCascade(OpenCV.CASCADE_FRONTALFACE); } void draw() { opencv.loadImage(cam); faces = opencv.detect(); image(cam, 0, 0); if (faces!=null) { for (int i=0; i< faces.length; i++) { noFill(); stroke(255, 255, 0); strokeWeight(10); rect(faces[i].x, faces[i].y, faces[i].width, faces[i].height); } } if (faces == null) { textAlign(CENTER); fill(255, 0, 0); textSize(56); text("UNDETECTED", 100, 100); } } void captureEvent(Capture cam) { cam.read(); } Answers Edit post, highlight code, press ctrl-o to format. Please don't post duplicates. Checked and the above works and does what you need. Your check for faces having a length of less than or equal to zero (Which is already a little weird because an array won't have a negative length...) on line 31 is INSIDE the check that facesisn't null on line 23. That is, the if condition on line 31 is really checking that the facesarray is not null but is of 0 length. So which is it? If there are no faces detected, your values for faceswill be null, right? I think what you really want is an ELSE statement: A few stray comments will help your code make more sense! Always throw yourself a few hints for later! and if faces were null? @tfguy44 that code doesn't work, if you cover up face you get nothing rather than the text being displayed. This was Emily original problem. It should work right but it doesn't. edit: also i'm NOT checking line 31 inside the loop of line 23 at all. and <=0 is just habit failsafe code, of course an array cant be less than 0 but you know..it doesnt hurt in the check. @koogs if faces=null then faces.length is blatantly 0 and therefore this works. edit. i mean faces = empty aka no face. edit: faces is never null anymore thanks to faces=opencv.detect(); Apologies @koogs only my second post in the forum so got a bit confused about etiquette and how some discussions get flagged as questions and some didn't. I know for next time thanks! @ashleyjamesbrown major thank you!!! Works perfectly! If faces is null then trying to trying to access faces.length will get you a null pointer exception @ashleyjamesbrown -- re: No. Just set faces to null and see what your code does in this sketch: "Null pointer access." Or just: "Null pointer access." post edit: @koogs unless the array has been initialised. @jeremydouglas yes thats correct if you haven't called opencv to init the faces array before doing that. Both of you - My wording is incorrect about where I was referring. I meant faces = empty aka no face. If there are no faces then the array is 0. Its no longer null in the draw because its been initialised by the line faces = opencv.detect(); This is why you cant run an else or if _faces = null _ in the draw method because the array is no longer null, its just empty and therefore this statement will never evaluate.
https://forum.processing.org/two/discussion/24052/face-detection-opencv-if-clauses-to-act-when-no-face-is-detected-help-please
CC-MAIN-2019-43
refinedweb
667
84.47
Here are the meeting notes (). # PhoneGap 1.4 Release Meeting ## Attendance ## Wiki - Style guide - Roadmap - Brian would like everyone to review it - Voice interest if you want to work on a certain feature ## Cordova Website - Patrick kicked it off - Yohei is also working on it - Dividing his time between phonegap.com and Cordova ### Cordova - Open source project - Contributor focused - Contribution process ### PhoneGap - User space - App focus ## Release Script - Steve is working on it - Written in node.js - Shells out to each platform build script - Steve and Brian will be posting details on it onto the mailing-list today - Goal is to cut Apache releases with this script - Patrick requires node.js for Weinre. - He is working with Apache to get node.js on their servers for automated builds ## Upcoming Apache Release - 1.4 is too early - Bryce feels like 1.5 is a do-able timeframe for the first Apache release ## 1.4 Release - January 31, 2012 (Tentative) - Not enough time for an Apache release ## 1.5 Release - Target for Apache release - Renaming all of the code ## PhoneGap-JS - Fil could use some more resources to help with other platforms - Jesse for WP7? - Shazron for iOS? - Package namespaces is one of the largest differences between iOS and the other platforms - iOS JavaScript also have a couple "global caste" functions for native-to-javascript communication - These will need to be removed or wrapped into the ios-utils function - The goal would be to avoid dropping these functions into the global namespace - Anis for Bada? - In the next week or two, Fil and Gord will do a connect session to explain the code - Schedule a time on the mailing-list ## Android WebView Change Bug - Joe, Fil, and Anis - In Android 3/4, SDK switched from WebKit to Chrome - There is a bug where you cannot open Android assets (www/) - The fullpath is referenced in the native code, instead of a relative URL - Joe has a workaround using the Android "jail" - The side-effect is that all assets in "assets/www" would need to be moved into the "jail" on first run (at run-time) - A downfall is that run-time storage is doubled (original assets and jailed assets) - From the PhoneGap developer perspective, there is no change - The work is currently in a branch on the Android source - Bryce, Simon, Joe, Fil, and Anis should take this to the mailing list and schedule a Connect call for code-review - Based on the code-review, this feature will hit release 1.4 or 1.5 ## Getting Start Guides - Try to get these into the docs repository for 1.4 ## White-List - Has been a troublesome topic on Google Groups - Anis patched an Android bug for "*" - He proposed a consistent implementation across all platforms - Potentially follow the Opera standard for white-listing - White-listing should be documented on the docs site (Getting Started section) ## Battery API - Simon just added tests to mobile-spec for the draft of the newest APIs - Fil: Are we switching to this spec? - Simon: Keep the existing spec, but begin implementing the new draft. Tell people that the existing spec will be gradually moving away. - Fil: Would like to see the updated Battery spec for 1.5 (not 1.4) - Debate: should we include it in Plugins XML by default? - Potential performance issues if we include it by default - At the moment, there is no performance issue if you do not subscribe to the event - However, the new Battery Spec would run from the beginning - This is leading into a "Plugins Definition" discussion - Take this onto the mailing-list ## Mobile-Spec - Brian: Should we move this into cordova-js? - Fil: No, they are difficult to use as automated unit tests. We can move certain parts into the unit tests, but we should keep mobile-spec on its own. ## Git Repository Tagging - Steve: Some of the repositories in github.com/apache/* are missing tags - Bryce: Seconded. He has also noticed too - EVERYONE - please push all of the tags - `git push --tags origin` - where "origin" is the Apache GitHub and Apache Git Infra ## Documentation - For each platform, we need to document how Plugins XML works - For each platform, we need to document how to create a plugin - For each platform, we need to document how to use a plugin ## Fixing Apache Repository Naming - At 1.5 we will fix the naming - cordova-blackberry-webworks => cordova-blackberry - cordova-iphone => cordova-ios On Fri, Jan 20, 2012 at 5:53 AM, Patrick Mueller <pmuellr@gmail.com> wrote: > On Fri, Jan 20, 2012 at 05:58, Andrew Savory <asavory@apache.org> wrote: > > > It might also be useful to post times in UTC as well as your local > > timezone, and/or link to sites like > > > > > > > make it easier for people to convert to their local time. > > > > +1 on posting times/dates with a timeanddate link. I was looking around for > one of these services the other day - because I've seen other folks use > them in meeting announcements - and timeanddate seemed to be the > best/easiest, once you find the right URL. > > This is actually a better URL to use though, since it immediately shows you > relevant times, everywhere: > > > > > > -- > Patrick Mueller > >
http://mail-archives.apache.org/mod_mbox/incubator-callback-dev/201201.mbox/%3CCAP7NMPqEBPvAkegoZ_u3nc1gbss2icvK=RHmLFrAGYFtCi0EHw@mail.gmail.com%3E
CC-MAIN-2015-18
refinedweb
865
64.14
05 May 2010 23:08 [Source: ICIS news] By Ivan Lerner NEW YORK (ICIS news)--Polypropylene (PP) prices in the US and Europe would continue to decline in the long term as operating issues are resolved and imports increase, a consultant said on Wednesday. The PP pricing trend “will clearly be downward”, said Robert Bauman, director of Polymer Consulting International (PCI). “Demand growth will continue to be high in developing regions, and demand recovery will occur in developed countries as economies improve,” he added But extra capacity would be an issue, exerting “strong downward pressure on prices,” he said. “The only question is when - one month, three months, six months?” Global demand was being driven by Latin America, ?xml:namespace> A key factor for US and European PP producers would be the ability to maintain high operating rates by exporting surplus capacity, said Bauman. As the economies of developed countries improved, the severe drop in demand caused by the recession may lead to a short-term burst of demand, with growth rates reaching 5-10% for one to two years, followed by a return to the pre-recession trend of 2-4%, according to the consultant. Middle Eastern PP has had some issues regarding the quality of its PP, but those concerns “are temporary depending upon the country,” said Bauman. “Every new plant in the Not being a low-cost producer, With all the excess PP capacity coming on globally, “ “If this occurs, exports from The latest spot prices for US-based PP were 64-65 cents/lb ($1,411-1,433/tonne), and European PP was selling for €1,200-1,230/tonne, ($924-947/tonne) according to ICIS pricing.
http://www.icis.com/Articles/2010/05/05/9356603/polypropylene-prices-to-decline-long-term-consultant.html
CC-MAIN-2014-52
refinedweb
281
50.6
Ola Bini talks about a layered architecture, with a stable, typesafe, performant kernel, providing the foundation for a malleable DSL-based end-user API. To me this makes a lot of sense, at least in the context of the large codebase of existing Java applications. Language adoption in the mainstream has traditionally been evolutionary and for quite some time we will see lots of layers and wrappers being written and exposed as flexible APIs in the newer languages, over today's mainstream codebases acting as the so-called kernel. Java is still the most dominant of these forces in application development, particularly in the enterprise segment. And given the degree of penetration that Java, the language, has enjoyed over the last decade or so, coupled with the strong ecosystem that it has been able to create, it will possibly remain the most potent candidate for what Ola Bini calls the kernel layer. With more and more mindset converging towards new languages on the JVM, albeit in blogs or toy applications, I am sure many of them have already started thinking about polyglot programming paradigms. In an existing application, with the basic abstractions implemented in Java, can we use one of its newer cousins to design more dynamic APIs ? With the toolsets and libraries still in nascent state of evolution, it will be quite some time (if ever at all) that some BigCo decides to develop a complete enterprise application in JRuby or Scala or Groovy. After all, the BigCos are least excited with Ruby evals, Groovy builders or Scala type inferencing. It is the ecosystem that matters to them, it is the availability of programmers that counts for them and it is the comfort factor of their IT managers that calls the shots and decides on the development platform. Anyway, this is not an enterprise application. I tried to build a layer of Scala APIs on top of some of the utilitarian Java classes in a medium sized application. It was fun, but more importantly, it showed how better APIs evolve easily once you can work with more powerful interoperable languages on a common runtime. Consider this simplified example Java class, which has worked so faithfully for my client over the last couple of years .. // Account.java public class Account { private List<String> names; private String number; private List<Address> addresses; private BigDecimal interest; private Status status; private AccountType accountType; public Account(String name, String number, Address address) { //.. } //.. standard getters public void calculate(BigDecimal precision, Calculator c) { interest = c.calculate(this, precision); } public boolean isOpen() { return status.equals(Status.OPEN); } } Nothing complex, usual verbose stuff, encapsulating the domain model that our client has been using for years .. I thought it may be time for a facelift with some smarter APIs for the clients of this class, keeping the core logic untouched. Let us have a Scala class which will act as an adapter to the existing Java class. Later we will find out how some of the magic of Scala *implicits* enables us to use the adaptee seamlessly with the adaptor. // scala class: RichAccount.scala // takes the Java object to construct the rich Scala object class RichAccount(value: Account) { //.. } Scala collections are much richer than Java ones - hence it makes sense to expose the collection members as Scala Lists. Later we will find out how the client can use these richer data structures to cook up some more dynamic functionalities. class RichAccount(value: Account) { //.. def names = (new BufferWrapper[String] { def underlying = value.getNames() }).toList def addresses = (new BufferWrapper[Address] { def underlying = value.getAddresses() }).toList def interests = (new BufferWrapper[java.math.BigDecimal] { def underlying = value.getInterests() }).toList } Now with the properties exposed as Scala lists, we can cook up some more elegant APIs, using the added power of Scala collections and comprehensions. class RichAccount(value: Account) { //..as above // check if the account belongs to a particular name def belongsTo(name: String): boolean = { names exists (s => s == name) } } Then the client code can use these APIs as higher order functions .. // filter out all accounts belonging to debasish accounts filter(_ belongsTo "debasish") foreach(a => println(a.getName())) or for a functional variant of computing the sum of all non-zero accrued interest over all accounts .. accounts.filter(_ belongsTo "debasish") .map(_.calculateInterest(java.math.BigDecimal.valueOf(0.25))) .filter(_ != 0) .foldLeft(java.math.BigDecimal.ZERO)(_.add(_)) This style of programming, despite having chaining of function calls are very much intuitive to the reader (expression oriented programming), since it represents the way we think about the computation within our mind. I am sure your clients will love it and the best part is that, you still have your tried-and-tested Java objects doing all the heavy-lifting at the backend. Similarly, we can write some friendly methods in the Scala class that act as builder APIs .. class RichAccount(value: Account) { //..as above def <<(address: Address) = { value.addAddress(address) this } def <<(name: String) = { value.addName(name) this } } and which allows client code of the following form to build up the name and address list of an account .. acc << "shubhasis" << new Address(13, "street_1n", "700098") << "ashis" Scala Implicits for more concise API Now that we have some of the above APIs, how can we ensure that the Scala class really serves as a seamless extension (or adaptation) of the Java class. The answer is the *implicit* feature of Scala language. Implicits offer seamless conversions between types and makes it easy to extend third party libraries and frameworks. Martin Oderskey has a nice writeup on this feature in his blog. In this example we use the same feature to provide an implicit conversion function from the Java class to the Scala class .. implicit def enrichAccount(acc: Account): RichAccount = new RichAccount(acc) This defines the implicit conversion function which the complier transparently uses to convert Accountto RichAccount. So the client can now write .. // instantiate using Java class val myAccount = new Account("debasish", "100", new Address(12, "street_1", "700097")) and watch (or feel) the compiler transparently converting the Java instance to a Scala instance. He can now use all the rich APIs that the Scala class has cooked up for him .. // use the functional API of Scala on this object myAccount.names.reverse foreach(println) We can also use Scala implicits more effectively and more idiomatically to make our APIs smarter and extensible. Have a look at the Java API for calculation of interest in the Java class Account : public void calculate(BigDecimal precision, Calculator c) { interest = c.calculate(this, precision); } Here Calculatoris a Java interface, whose implementation will possibly be injected by a DI container like Spring or Guice. We can make this a smarter API in Scala and possibly do away with the requirement of using a DI container. class RichAccount(value: Account) { //..as above def calculateInterest(precision: java.math.BigDecimal) (implicit calc: Calculator): java.math.BigDecimal = { value.calculate(precision, calc) value.getInterest() } } Here we use the nice curry syntax of Scala, so that the client code can look nice, concise and intuitive .. val accounts = List[Account](..) accounts filter(_ belongsTo "debasish") foreach(a => println(a.calculateInterest(java.math.BigDecimal.valueOf(0.25)))) Note that the Calculatorparameter in calculateInterest()has been declared implicit. Hence we can optionally do away specifying it explicitly so long we have an implicit definition provided. The client code has to mention the following declaration, some place accessible to his APIs .. implicit val calc = new DefaultCalculator and we need no DI magic for this. It's all part of the language. Spice up the class with some control abstractions Finally we can use higher order functions of Scala to define some nice control abstractions for your Java objects .. class RichAccount(value: Account) { //..as above def withAccount(accountType: AccountType)(operation: => Unit) = { if (!value.isOpen()) throw new Exception("account not open") // other validations if (value.getAccountType().equals(accountType)) operation } } } The method is an equivalent of the Template Method pattern of OO languages. But using functional Scala, we have been able to templatize the variable part of the algorithm as a higher order function without the additional complexity of creating one more subclass. The client code can be as intuitive as .. a1.withAccount(AccountType.SAVINGS) { println(a1.calculateInterest(java.math.BigDecimal.valueOf(0.25))) } As I mentioned in the beginning, I think this layering approach is going to be the normal course of evolution in mainstream adoption of other JVM languages. Java is so dominant today, not without reason. Java commands the most dominant ecosystem today - the toolsets, libraries, IDEs and the much familiar curly brace syntax has contributed to the terrific growth of Java as a language. And this domination of the Java language has also led to the evolution of Java as a platform. Smalltalk may have been a great platform, but it lost out mainly because developers didn't accept Smalltalk as a mainstream programming language. Now that we have seen the evolution of so many JVM languages, it is about time we experiment with polyglot paradigms and find our way to the next big language set (yes, it need not be a single language) of application development. So long we have been using Java as the be-all and end-all language in application development. Now that we have options, we can think about using the better features of other JVM languages to offer a smarter interface to our clients. 4 comments: Interesting stuff, Debasish, but I have one request: could you use a different way to post code snippets? The way you're doing it right now forces readers to scroll horizontally back and forth to read your listings, and it's very annoying... Thanks! -- Cedric Awesome post! I'm a longtime java developer who works professionaly right now as a C# developer. These "research" languages F# and Scala have me fascinated, and I look forward to increasing my productivity with them. Really cool stuff. Posts like this one will, hopefully, be helpful to transition in a smooth way from Java to languages like Scala that can be looked at as 'layered on top of Java'. And all this without loosing the Java EcoSystem (as you name it). Thanks so much for this post! Thanks Cedric for the reminder. This was long overdue. I have now made it wider, so that code snippets can fit better. and thanks for dropping by .. - Debasish
http://debasishg.blogspot.com/2008/01/scala-can-make-your-java-objects-look.html
CC-MAIN-2014-35
refinedweb
1,727
54.63
GCSE Computer Science Paper 1 What is an algorithm? An algorithm is a sequence of steps that can be followed to complete a task 1 of 90 What is decomposition? Decomposition means breaking a problem into a number of sub-problems, so that each sub-problem accomplishes an identifiable task, which might itself be further subdivided 2 of 90 What is abstraction? Abstraction is the process of removing unnecessary detail from a problem 3 of 90 What symbol shows the start and the end of a flow diagram? The oval 4 of 90 What symbol shows a process in a flow diagram? The rectangle 5 of 90 What symbol shows input/ output in a flow diagram? The parallelogram 6 of 90 What symbol shows a decision in a flow diagram? The diamond 7 of 90 Can more than one algorithm be used to solve the same problem? Yes 8 of 90 How would you find out what an algorithm is doing? Produce a trace table 9 of 90 How does a linear search work? Start at the beginning of the array and look at every item until the one you want is found 10 of 90 How does a binary search work? Dividing the data list in half and looking at the half that could contain the required data item 11 of 90 What are the advantages of a linear search? Easy to understand the concept, memory efficient, resource efficient 12 of 90 What are the disadvantages of a linear search? The longer the list, the less efficient it is 13 of 90 What are the advantages of a binary search? Much faster, fairly simple, well known 14 of 90 What are the disadvantages of a binary search? More complicated than linear, only works on lists that have been sorted into order, won't work on lists where the data is not related 15 of 90 What is a bubble sort? Repeatedly going through a list to be sorted, comparing each pair of adjacent elements; if the elements are in the wrong order, they are swapped 16 of 90 What is a merge sort? The list is divided in half, forming two sublists, until each sublist only has 1 data piece in it 17 of 90 What are the advantages of a bubble sort? Simple to write, easy to understand, only takes a few lines of code 18 of 90 What are the disadvantages of a bubble sort? Takes a while to sort; the longer the list, the longer the time taken 19 of 90 What are the advantages of the merge sort? Always fast 20 of 90 What are the disadvantages of the merge sort? Uses a lot of memory, can slow down when attempting to sort a very large data amount 21 of 90 What is data type? Defines the type of data that will be stored at the memory locations 22 of 90 What is an identifier? A unique name given to the variable 23 of 90 What is an integer? A whole number 24 of 90 What is a real/float number? A number with a fractional 25 of 90 What is a boolean data type? True/False 26 of 90 What is a character? A single character (a,z,r) 27 of 90 What is a string? A string of characters 28 of 90 What is variable declaration? Declaring a name for a variable is saying what the data type will be and where it will be stored in memory. 29 of 90 What is constant declaration? These are sections of program code that define the names that will be used to refer to constants, and what kind of data each of them will hold. 30 of 90 What is assignment? Values are assigned t ovariables using an = sign: x = 1 31 of 90 What is iteration? When a section of code is repeated a certain number of times or until the condition is true or false 32 of 90 What is selection? In a selection structure, a question is asked, and depending on the answer, the program takes one of two courses of action, after which the program moves on to the next event. 33 of 90 What is a subroutine? A named, self-contained section of code that performs a specific task 34 of 90 What is definite iteration? Operations for a fixed number of repetitions: the for... next loop 35 of 90 What is indefinite iteration? Operations continue until the condition is true or false: the while... end while loop 36 of 90 What is an array? A list that makes groups of data easy to use 37 of 90 What are 1- dimensional arrays? One dimensional array is a list of variables of same type that are accessed by a common name. 38 of 90 What are 2- dimensional arrays? A two dimensional array is a group of lists, or arrays that are organized into one data set. 39 of 90 What are records? A record is a special type of data structure which, unlike arrays, collects a number of fields of different data types which define a particular structure such as a book, product, person and many others. 40 of 90 How do you generate a random number? import random/ print random.randint9(1,100) 41 of 90 What is the concept of subroutines? A named block of code that may be executed by simply writing its name in a program statement 42 of 90 What are the advantages of using subroutines in programs? Subroutines can be used repeatedly without having to be rewritten each time they are used. 43 of 90 What are parameters? A parameter is a special kind of variable, used in a subroutine to refer to one of the pieces of data provided as input to the subroutine. 44 of 90 What are local variables? Variables that only exist when the subroutine is executing and are only accessible within the subroutine 45 of 90 Why is it good to use local variables? It would be more specific to the subroutine, you would use less memory as it is only stored and created when needed 46 of 90 What is a range check? Checks whether a number or date is within a sensible/ allowed range 47 of 90 What is a type check? Checks whether data is the right type 48 of 90 What is a length check? Checks whether text entered is not too long or too short 49 of 90 What is a presence check? Checks that data has been entered 50 of 90 What is a format check? Checks the format of the data is appropriate 51 of 90 What is an authentication routine? Authentication routines are used to make sure the user logging in to the system is authorised to do so 52 of 90 What are the main differences between low-level and high-level languages? High level languages allow much more abstraction than low level languages. This allows algorithms and functions to be written without requiring detailed knowledge of the hardware used in the computing platform. 53 of 90 What is the difference between machine code and assembly code? Machine code is the bits and bytes that the processor executes while running its program. Assembly code is a low level symbolic representation of that machine code, making it easier to write. 54 of 90 What will all code have to be translated into? Machine code 55 of 90 What are the advantages of low-level languages? Writing code in a low-level language allows the programmer to have complete control over the code. 56 of 90 What are the disadvantages of low-level languages? Can't be read easily by humans, needs a highly skilled person to use it, takes longer to write 57 of 90 What are the advantages of high-level languages? Can be easily writtien and read by humans, less technical skill is required 58 of 90 What are the disadvantages of high-level languages? Typically only provide plain text graphics, has to be converted into machine code anyway, takes up more memory 59 of 90 What does an interpretor do? Used to translate high-level code into machine code; translates each line of code and then executes it; no object code is produced 60 of 90 What does a complier do? Translates high-level code into machine code; can result in lots of different machine codes; the person uying the software cant see the source code 61 of 90 What does an assembler do? An assembler converts assembly language into machine code; simple conversion as every assembly language instruction is translated into a single machine code instruction 62 of 90 What is source code? The code written by the programmer 63 of 90 What is object code? The machine code produced by the complier 64 of 90 What number base is decimal? 10 65 of 90 What number base is binary? 2 66 of 90 What number base is hexadecimal? 16 67 of 90 Why do computers use binary to represent all data and instructions? Because the computer is made of switches tha can only be turned on and off so the 0s and 1s represent the states of on and off 68 of 90 Why is hexadecimal often used in computer science? Easier for humans to understand 69 of 90 What is a bit? The fundemental unit of information; either 1 or 0 70 of 90 What is a byte? A group of 8 bits 71 of 90 Where can binary shifts be used? Binary shifts can be used to perform simple multiplication /division by powers of 2 72 of 90 How many characters can the 7-bit ASCII code represent? 128 73 of 90 How many characters can Unicode represent? 65,536 74 of 90 Are character codes often grouped and run in sequence when encoding tables? Yes 75 of 90 What is the purpose of unicode? To represent the characters of all languages in the world 76 of 90 What are the advantages of unicode over 7-bit ASCII? Unicode can represent more characters 77 of 90 What is a pixel? An individual dot that makes up an image 78 of 90 What is the image resolution? The width of the image x the height of the image 79 of 90 What are bitmaps made of? Pixels 80 of 90 How can the number of pixels and colour depth affect the size file of a bitmap image? A higher number of pixels and a hugher colour depth mean a bigger file size 81 of 90 What is the calculation for bitmap image file size? width x height x colour depth (/ by 8 if calculating bytes) 82 of 90 What is sound? Analogue 83 of 90 What must sound be converted into to be stored and used in a computer? Digital 84 of 90 What happens to soundwaves to create the digital version of sound? They are sampled 85 of 90 What is sampling rate? The number of samples taken in a second, measured in hertz 86 of 90 What is sample resolution? The number of bits per sample 87 of 90 How do you calculate sound file sizes? File size = sampling rate x sample resolution x number of seconds 88 of 90 What is data compression? Making a file smaller by either losing data permenantly or temporarily 89 of 90 What is the difference between lossy and lossless compression? Lossy compression is when a file is compressed by removing some of teh detail whereas lossless compression is where files are compressed but no data is lost. 90 of 90 Other cards in this set Card 2 Front What is decomposition? Back Decomposition means breaking a problem into a number of sub-problems, so that each sub-problem accomplishes an identifiable task, which might itself be further subdivided Card 3 Front What is abstraction? Back Card 4 Front What symbol shows the start and the end of a flow diagram? Back Card 5 Front What symbol shows a process in a flow diagram? Back
https://getrevising.co.uk/revision-tests/gcse-computer-science-paper-1-1?game_type=flashcards
CC-MAIN-2019-43
refinedweb
2,019
70.13
Voronoi diagram in AS3 In today's article I will introduce you my own small library for generating Voroni diagram in ActionScript 3. I used Fortune's algorithm, which is probably the fastest algorithm for solving Voronoi diagram. Voronoi library I put the whole code in a small package "net.ivank.voronoi". I just couldn't find any working implementation of Priority Queue or Heap in AS3, so I used a simple array. That's why the final complexity is $O(n^2 * log(n))$, but it is still usable for small diagrams. You can download my whole code HERE. Example import net.ivank.voronoi.*; // importing libraries import flash.geom.Point; var i:int; var edges:Vector.< VEdge >; // vector for edges var v:Voronoi = new Voronoi(); // this instance will compute the diagram // vector for sites, for which we compute a diagram var vertices:Vector.< Point> = new Vector.< Point >(); // let's add some random sites for(i = 0; i< 20; i++) { var p = new Point(Math.random() * 1000 , Math.random() * 800) vertices.push(p); } // call a method which computes a diagram, width and height limit edges = v.GetEdges(vertices, 1000, 800); // drawing a Delaunay triangulation graphics.lineStyle(3, 0x888888); for(i = 0; i< edges.length; i++) { graphics.moveTo(edges[i].left .x, edges[i].left .y); graphics.lineTo(edges[i].right.x, edges[i].right.y); } // drawing a Voronoi diagram graphics.lineStyle(5, 0x000000); for(i = 0; i< edges.length; i++) { graphics.moveTo(edges[i].start.x, edges[i].start.y); graphics.lineTo(edges[i].end .x, edges[i].end .y); } Performance test We can use an array or a heap to represent an event queue. Let's take a look at the speed of these two options. (diagram for 200 places, recounting on mouse move). Array - add event: to the end of an array; remove event: remove + move the rest one field backwards; get maximum: sort + remove the last item. Heap - adding an event, removing maximum: see definition of the heap. Hi, is it possible to get the code for the demos as well? Thanks!April 6th, 2011 No, you can only download my library and use the code above. You can create mostly anything you want.April 6th, 2011 Hey, nice work. I’ll definitely use this code. I found a bug though, a vertical line pops up somewhere on the map when you move a point to the very lower edge of the screen. Can you fix that? Keep up the good work, SimonJune 23rd, 2011 Very nice. Can you tell me how to best find all the vertices of a given polygon using your code? I’d like to be able to fill them with color.August 11th, 2011 Thank you. It’s a very good question. When programming it, I realised, that it would be a very nice feature, but I didn’t implement itAugust 11th, 2011 Now it will be the best to create a class Cell with the list of points, which define the polygon. Create a list of Cells under the list of Vertices. Now loop through the list of edges, check it’s left and right vertex and add their begin and end vertex to the cells, which are at the left and right. But then you will have to create a convex hull for each cell. This process will have complexity $n*log(n)$ (again). Better way is to edit current code.
http://blog.ivank.net/voronoi-diagram-in-as3.html
CC-MAIN-2018-26
refinedweb
571
76.93
30, 2008 11:30 PM.: Maven is a fantastic tool, the type of tool that we wish to exist in every language. It's a modular project build tool. It is able to manage dependencies, build cycle, testing, packaging and publishing your artifact in the repository. It's a project build tool, a step ahead of the normal build tools (actually the first version was a layer on top of Ant). It provides a default directory layout for your project and really nice defaults, all you need to start is choose a name for your project and the default package to create. Everything else works out-of-the-box and if you need anything different you can provide configuration in the last case you can provide a new plugin that will be managed by maven repository (the plugin is just another type of dependency and it will be download automatically after you configure in your pom). It uses convention over configuration much before rails community coined the term.: Raible also added:. Some other quotes: What do you think? Download the Free Adobe® Flex® Builder 3 Trial Adobe® Rich Internet Application Project Portal Effective Management of Static Analysis Vulnerabilities and Defects Adobe® Flash® Platform Overview PDF Ensuring Code Quality in Multi-threaded Applications Who is this "Dan" Brown taking credit for my work? ;) I am not sure if the entry barrier to try out maven is huge. Once i started using maven on my projects I use it right from creating the project structure onwards (). It is pretty straight forward once I got used to it and now I am scared to look at projects which are built using ant or any other build tool ;) Vikas Hazrati The maven issues stems from a couple of misconceptions: that it is a script system like ant (hint: it isn't), and that everybody understands perfectly the dependency management behind it (another hint: not really).. On one side I think Maven is fine and once you decide to learn its ways and follow it, you'll get an easier build. In recent months we converted two of our bigger projects into maven2 builds and are quite happy with the results. On the other side, the docs are lacking (and you never know what's up to date and what's obsolete), a company repository/proxy is really necessary (hint: apache archiva), and some plugins are really problematic.. Maven is a great tool. The only problem is: you can only use it if you know all the ins and outs of it. It's like crossing the road: you don't stop half way, you cross it or not. Maven is a complex tool that simplifies development hugely. I will never use any other build tool ever again. I admit that Maven has it's flaws too. Nothing is a 100% bug free. There are a lot of plugins from Maven 1 I would like to see ported to Maven 2 (vainstall for instance). I assume it may be your other inner self working to improve maven :-). ./alex -- .w( the_mindstorm )p. Alexandru Popescu Senior Software Eng. InfoQ Techlead/Co-founder Actually, that would help explain my intense love/mostly hate relationship with Maven... Why is it in Java world that we always build tools that let users live with XML configuration files and expect that sometime in the future a decent IDE support will be available. What's so hard to understand that the adoption will be much easier if the tool itself would provide the default application to let visually interact with it?. I agree that using Maven is not difficult. There is a learning curve with every technology you use, and the time spent learning Maven will repay itself in orders of magnitude. One of the comments in the article called out that no one could possibly remember how to properly create a new maven project. This is why Maven created Archetypes. Archetypes are project templates and can be used to quickly generate skeletons for new projects. Your project is different from all the archetypes you say? Then simply make a new archetype, What if the build configuration would be Java source code? You have autocomplete, Javadocs, you could debug your build. Part of it would be procedural, part by configuration, part convention (you could override the default by writing a method). Maven repositories could be re-used, but dependencies are Strings (no XML). Example simple build file Build.java import org.javen.*; public class Build { public static void main(String[] args) { setAppName("acme"); build(); } } There are other build tools in a similar vein. Gant for Groovy and buildr for Java (there's some others also). There's some Scala tools that are in development, such as Sant and Obi (disclaimer: I'm the creator of Obi), which will (eventually) support Scala and Java projects.. What I like to have is something written in Java. buildr is for Ruby. While Scala may replace Java in the future, it doesn't have the tools support yet. We can talk as soon as it has autocomplete in Eclipse ;-) buildr is for Ruby. Buildr is not for Ruby. It is written in Ruby to build Java projects. It uses the Maven directory structure and repositories. You should take a look at the latest versions of Gant. It tries to cover both Ant and Maven models, and so you'll have access to both words. ./alex -- .w( the_mindstorm )p. Hi Don, Please accept my apologies for the typo - I've updated the article to correct that, and your nemesis "Dan Brown" no longer has the credit. :) Thanks, Ryan Slobojan My beef against maven, besides what everyone else said, is that it's too damn rigid. If you want to do something slightly outside the prescribed build process, it's incredibly difficult. Like another blogger said, try filtering your web.xml file. Or try extracting the classes from a WAR project into a JAR project. Or creating multiple distribution units. Or ordering plugins within a phase. A lot of time in a build, the order of operations matters. :-) Every Maven customization on my projects engenders mass panic, and only the bravest venture into writing plugins, etc., and always emerge cursing at Maven. As for documentation, take a look at the assembly plugin. Every single goal has the same description: "Assemble an application bundle or distribution from an assembly descriptor." Great. Have fun everyone. Maven makes the hard things easy and the easy things hard. This is precisely why I've adopted Buildr instead of Ant or Maven. It borrows some of the ideas from Maven like a standardized directory structure and use of the public Maven repositories while still being flexible. Buildr has been a great way to learn Rake and Ruby while greatly simplifying building, packaging AND deploying projects. The reason behind this discussion is that Maven2 is hitting a critical mass. A lot of opensource projects are migrating to it - worts and all. There is an upfront cost of learning maven2 that the documentation clearly doesn't address. And there needs to be best practices around levels of dependencies, repository management, SNAPSHOTs, etc... It is very easy to run tomcat from maven using cargo plug-in. Here the link: I am in the process of upgrading our current build tool from Ant and Maven 1 to Maven 2. As a new comer to maven; it is a real pain! ? Firstly, the user interface is completely and utterly counter-intuitive. Try some of the following: You should definitely look at profiles, they are targeted for these use case. I also recommend to you take a look to the book Better Build With Maven. Indeed documentation is the key, but unfortunately Maven and its plugins are not well documented.. I looked at that and i am using profiles. But I need to pass some parameters to maven so that it could understand difference between my different environments, but without any luck so far. Unless I write all the parameters inside POM file which is a really ugly solution There are also properties in maven. Different profiles can have different values for the same property. The point is you need to write that parameters directly in the POM file. And that is not what you want to do when you have a dozen of them. I am looking for a solution to put all my properties simply in a property file for each environment and load them within profiles. I understand it can be hard to find the right documentation (if it exists). I have had good luck using the maven users mailing list. For anyone who is trying to do something in maven that seems overly difficult or awkward, try throwing it out to the list to see if there is a better way. For example, the previous author who said it is really hard to setup a new project would've quickly been informed by the users list that archetypes can make this a lot easier. You mean something like Gosling? Read more on Tim's blog. I don't get what is so difficult about Maven. It's certainly not perfect, but for average use, it's really really simple. It only gets anoying when you try to bend it to your will too much, and it is the whole point/ improvement that people stop doing that. I'm just thankful that nowadays I can just check out a project and have it building right away. What a difference from when people were using their own exotic Ant builds. Don - maybe you should take credit for "The Da Vinci Code" :-) I'm guilt of a similar mistake. The reasons that Maven is seen as a PITA are 1. The fact that it does not work well with the leading development tool in Java (Eclipse). Even if it is Eclipse's fault, it's a big turnoff for many developers. 2. The documentation is lacking in many places. 3. bugs. I think there is also the fact that Maven is a complex tool designed for complex projects. So it does feel a bit heavyweight. If I'm evaluating a project for possible use, and it is built in Maven, I kind of flinch, just because I know that although the project may be cool, it is probably not a quick study. This is not Maven's fault, in fact Maven makes the situation much better than it would be otherwise by firstly having a standard layout so you can find your way around the source, and secondly by listing all dependencies etc. in a standard place so you can find them. But, few of us love complexity for it's own sake. Thanks Ivan, I was aware of that. Unfortunately it aint help much when you'd like to use Tomcat6.. There is also profiles.xml where you should define all profile specific stuff. your evil twin? :) Waiting for the main repository is a PITA. Artifactory saved my marriage... err... builds That's it. Maybe we can add:
http://www.infoq.com/news/2008/01/maven-debate
crawl-002
refinedweb
1,851
73.47
From Documentation Book Model Overview When Spreadsheet loads an Excel file, the file is converted to Spreadsheet's data model (book model) stored in memory. The root of the data model is a book (Book) and a book contains one or more sheets (Sheet) which may contain many cells (CellData), styles (CellStyle, Color), fonts (Font), charts (Chart), and pictures (Picture). You can directly access model objects like Book or Sheet. However, you should modify data on cells (or rows and columns)via Range interface, then Spreadsheet will handle subsequent synchronization stuff for you, e.g. notify other referenced cells. A Range may represent a cell, a row, a column, or a selection of cells containing one or more contiguous blocks of cells, or a 3-D reference. [1] Because of underlying implementation is complicated, you only can obtain a Range object through a facade class named Ranges. In this section, we will introduce some commonly-used API with examples. For complete information, you can browse Javadoc under org.zkoss.zss.api.* and org.zkoss.zss.api.model.*. To understand example codes, we assume you have known what is a composer and how it work with components. If you don't, please read ZK Developer's Reference/MVC/Controller/Composer first. Load A Book Model In most cases, we create a book model by loading an Excel file instead of creating it directly. Specifying an Excel file's path in Spreadsheet component's attribute is the simplest way, and Spreadsheet will import the file and construct a book model object. You can also use Importer to construct a Book object by your own and provide it to one or more Spreadsheet components by setBook(). After Spreadsheet loads a book model, we can get it by Spreadsheet.getBook(). By Spreadsheet src Attribute The Spreadsheet's setSrc(java.lang.String) can be called to display an Excel file programmatically. Similar to src attribute, this method accepts relative file path. public class MyComposer extends SelectorComposer<Component> { @Wire Spreadsheet ss; @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); //initialize stuff here ss.setSrc("/WEB-INF/books/startzss.xlsx"); } } - Line 3: The annotation @Wire injects matched component object's reference to annotated variable according to selector syntax. In this case, ZK injects a Spreadsheet component whose id is "ss" on the ZUL page. For details, please refer to ZK Developer's Reference/MVC/Controller/Wire Components. To reload the same file, you should set src to null first and set it back to original file. By Importer In case your Excel file may not come from a static file path, importer interface along with Spreadsheet.setBook()can be used. Normally one would obtain Book instance by importing an Excel book file. Use imports() of Importer to import an Excel file. It returns Book instance which can be passed to setBook(Book) to display the imported Excel file. public class My } } Create a New Book You need to load a blank book file to create a new book instead of instantiating a Book object. Please refer to the code example. Access Sheets The Book object is the root of Spreadsheet's data model, and we can retrieve sheets from it, e.g. by index getSheetAt(), or by name getSheet(). One book object might contains one or more sheets, and we can know how many sheets it have by getNumberOfSheets(). However, Spreadsheet only displays one sheet at one time and the currently-displayed sheet is the selected sheet. We can get selected sheet via Spreadsheet.getSelectedSheet() or set it via Spreadsheet.setSelectedSheet(). The org.zkoss.zss. Switch Sheets Example Now, we present basic usage with a custom sheet switching example. Users can use the listbox with sheet name to switch the current selected sheet of the Spreadsheet. setSheet.zul <div height="100%" width="100%" apply="org.zkoss.zss. public class BookSheetComposer extends SelectorComposer<Component>{ @Wire Listbox sheetBox; @Wire Spreadsheet spreadsheet; //override @Override public void doAfterCompose(Component comp) throws Exception { super.doAfterCompose(comp); List<String> sheetNames = new ArrayList<String>(); int sheetSize = spreadsheet.getBook().getNumberOfSheets(); for (int i = 0; i < sheetSize; i++){ sheetNames.add(spreadsheet.getBook().getSheetAt(i).getSheetName()); } sheetBox.setModel(new ListModelList<String>(sheetNames)); } @Listen("onSelect = #sheetBox") public void selectSheet(SelectEvent event) { String selected = (String)event.getSelectedObjects().iterator().next(); spreadsheet.setSelectedSheet(selected); } } - Line 14,15: Get each sheet's name from Spreadsheet's book model. - Line 18: Set name list to the Listbox. - Line 21: The annotation @Listen makes selectSheet() listen onSelect event of the Listbox whose id is sheetBox. That means when a user selects a sheet in the Listbox, the method selectSheet() will be invoked.(For complete syntax, please refer to ZK Developer's Reference/MVC/Controller/Wire Event Listeners) - Line 23,24: Change Spreadsheet's selected sheet when users select a sheet. Access Cells When you want to change some data in book or sheet, you can directly access their corresponding model objects, Book or Sheet. However, there is no such a cell object for you to access. Because one cell might be referenced by other cells, accessing it may need to notify other cells. This issue can be more complicated if you select multiple cells. Hence, in order to encapsulate these complicated detail, Spreadsheet provides 2 classes, Ranges and Range (Notice that there is one more "s" in the first one's class name.).(); There are still many methods that we don't mention here. They will be introduced in later sections. Utility Class Ranges and Range provides major APIs to access cells. Because of referencing relationship among cells mentioned at the beginning of this section, we also provides utility classes, CellOperationUtil and SheetOperationUtil, to help you change cell data and styles. You can use them without knowing more details about underlying implementation, and they will handle those details for you such as synchronization and checking. We will introduce these 2 utility classes more in the later sections. - ↑. All source code listed in this book is at Github.
https://www.zkoss.org/_w/index.php?title=ZK_Spreadsheet_Essentials/Working_with_Spreadsheet/Spreadsheet_Data_Model&oldid=48759
CC-MAIN-2019-26
refinedweb
996
56.45
Handling document relationships One of the design principles that RavenDB adheres to is the idea that documents are independent, meaning all data required to process a document is stored within the document itself. However, this doesn't mean there should not be relations between objects. There are valid scenarios where we need to define relationships between objects. By doing so, we expose ourselves to one major problem: whenever we load the containing entity, we are going to need to load data from the referenced entities too (unless we are not interested in them). While the alternative of storing the whole entity in every object graph it is referenced in seems cheaper at first, this proves to be quite costly in terms of database resources and network traffic. RavenDB offers three elegant approaches to solve this problem. Each scenario will need to use one or more of them. When applied correctly, they can drastically improve performance, reduce network bandwidth and speedup development. The concepts behind this topic and other related subjects are discussed in length in the Theory section. Denormalization The easiest solution is to denormalize the data within the containing entity, forcing it to contain the actual value of the referenced entity in addition (or instead) of the foreign key. Take this JSON document for example: { // Order document with id: orders/1234 "Customer": { "Name": "Itamar", "Id": "customers/2345" }, Items: [ { "Product": { "Id": "products/1234", "Name": "Milk", "Cost": 2.3 }, "Quantity": 3 } ] } As you can see, the Order document now contains denormalized data from both the Customer and the Product documents, which are saved elsewhere in full. Note we won’t have copied all the customer properties into the order; instead we just clone the ones that we care about when displaying or processing an order. This approach is called denormalized reference. The denormalization approach avoids many cross document lookups and results in only the necessary data being transmitted over the network, but it makes other scenarios more difficult. For example, consider the following entity structure as our start point: public class Order { public string CustomerId { get; set; } public string[] SupplierIds { get; set; } public Referral Refferal { get; set; } public LineItem[] LineItems { get; set; } public double TotalPrice { get; set; } } public class Customer { public string Name { get; set; } public string Address { get; set; } public short Age { get; set; } public string HashedPassword { get; set; } } If we know that whenever we load an Order from the database we will need to know the customer's name and address, we could decide to create a denormalized Order.Customer field, and store those details in the directly in the Order object. Obviously, the password and other irrelevant details will not be denormalized: public class DenormalizedCustomer { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } } There wouldn’t be a direct reference between the Order and the Customer. Instead, Order holds a DenormalizedCustomer, which contains the interesting bits from Customer that we need whenever we process Order objects. But, what happens when the user's address is changed? We will have to perform an aggregate operation to update all orders this customer has made. And what if the customer has a lot of orders or changes their address frequently? Keeping these details in sync could become very demanding on the server. What if another process that works with orders needs a different set of customer properties? The DenormalizedCustomer will need to be expanded, possibly to the point that the majority of the customer record is cloned. Denormalization is a viable solution for rarely changing data, or for data that must remain the same despite the underlying referenced data changing over time. Includes The RavenDB "Includes" feature addresses the limitations of denormalization. Instead of one object containing copies of the properties from another object, it is only necessary to hold a reference to the second object. Then RavenDB can be instructed to pre-load the referenced document at the same time that the root object is retrieved. We can do this using: var order = session.Include<Order>(x => x.CustomerId) .Load("orders/1234"); // this will not require querying the server! var cust = session.Load<Customer>(order.CustomerId); Above we are asking RavenDB to retrieve the Order "orders/1234" and at the same time "include" the Customer referenced by the Order.CustomerId property. The second call to Load() is resolved completely client side (i.e. without a second request to the RavenDB server) because the relevant Customer object has already been retrieved (this is the full Customer object not a denormalized version). There is also a possibility to load multiple documents: var orders = session.Include<Order>(x => x.CustomerId) .Load("orders/1234", "orders/4321"); foreach (var order in orders) { // this will not require querying the server! var cust = session.Load<Customer>(order.CustomerId); } You can also use Includes with queries: var orders = session.Query<Order>() .Customize(x => x.Include<Order>(o => o.CustomerId)) .Where(x => x.TotalPrice > 100) .ToList(); foreach (var order in orders) { // this will not require querying the server! var cust = session.Load<Customer>(order.CustomerId); } Under the hood, this works because RavenDB has two channels through which it can return information in response to a load request. The first is the Results channel, through which the root object retrieved by the Load() method call is returned. The second is the Includes channel, through which any included documents are sent back to the client. Client side, those included documents are not returned from the Load() method call, but they are added to the session unit of work, and subsequent requests to load them are served directly from the session cache, without requiring any additional queries to the server. One to many includes Include can be used with a many to one relationship. In the above classes, an Order has a property SupplierIds which contains an array of references to Supplier documents. The following code will cause the suppliers to be pre-loaded: var order = session.Include<Order>(x => x.SupplierIds) .Load("orders/1234"); foreach (var supplierId in order.SupplierIds) { // this will not require querying the server! var supp = session.Load<Supplier>(supplierId); } Again, the calls to Load() within the foreach loop will not require a call to the server as the Supplier objects will already be loaded into the session cache. Multi-loads are also possible: var orders = session.Include<Order>(x => x.SupplierIds) .Load("orders/1234", "orders/4321"); foreach (var order in orders) { foreach (var supplierId in order.SupplierIds) { // this will not require querying the server! var supp = session.Load<Supplier>(supplierId); } } Secondary level includes An Include does not need to work only on the value of a top level property within a document. It can be used to load a value from a secondary level. In the classes above, the Order contains a Referral property which is of the type: public class Referral { public string CustomerId { get; set; } public double CommissionPercentage { get; set; } } This class contains an identifier for a Customer. The following code will include the document referenced by that secondary level identifier: var order = session.Include<Order>(x => x.Refferal.CustomerId) .Load("orders/1234"); // this will not require querying the server! var referrer = session.Load<Customer>(order.Refferal.CustomerId); Alternative way is to provide string based path: var order = session.Include("Refferal.CustomerId") .Load<Order>("orders/1234"); // this will not require querying the server! var referrer = session.Load<Customer>(order.Refferal.CustomerId); This secondary level include will also work with collections. The Order.LineItems property holds a collection of LineItem objects which each contain a reference to a Product: public class LineItem { public string ProductId { get; set; } public string Name { get; set; } public int Quantity { get; set; } public double Price { get; set; } } The Product documents can be included using this syntax: var order = session.Include<Order>(x => x.LineItems.Select(li => li.ProductId)) .Load("orders/1234"); foreach (var lineItem in order.LineItems) { // this will not require querying the server! var product = session.Load<Product>(lineItem.ProductId); } when you want to load multiple documents. The Select() within the Include tells RavenDB which property of secondary level objects to use as a reference. ValueType identifiers The above Include samples assume that the Id property being used to resolve a reference is a string and it contains the full identifier for the referenced document (e.g. the CustomerId property will contain a value such as "customers/5678"). Include can also work with Value Type identifiers. Given these entities: public class Order2 { public int Customer2Id { get; set; } public Guid[] Supplier2Ids { get; set; } public Referral2 Refferal2 { get; set; } public LineItem2[] LineItem2s { get; set; } public double TotalPrice { get; set; } } public class Customer2 { public int Id { get; set; } public string Name { get; set; } public string Address { get; set; } public short Age { get; set; } public string HashedPassword { get; set; } } public class Referral2 { public int Customer2Id { get; set; } public double CommissionPercentage { get; set; } } public class LineItem2 { public Guid Product2Id { get; set; } public string Name { get; set; } public int Quantity { get; set; } public double Price { get; set; } } The samples above can be re-written as follows: var order = session.Include<Order2, Customer2>(x => x.Customer2Id) .Load("orders/1234"); // this will not require querying the server! var cust2 = session.Load<Customer2>(order.Customer2Id); var orders = session.Query<Order2>() .Customize(x => x.Include<Order2, Customer2>(o => o.Customer2Id)) .Where(x => x.TotalPrice > 100) .ToList(); foreach (var order in orders) { // this will not require querying the server! var cust2 = session.Load<Customer2>(order.Customer2Id); } var order = session.Include<Order2, Supplier2>(x => x.Supplier2Ids) .Load("orders/1234"); foreach (var supplier2Id in order.Supplier2Ids) { // this will not require querying the server! var supp2 = session.Load<Supplier2>(supplier2Id); } var order = session.Include<Order2, Customer2>(x => x.Refferal2.Customer2Id) .Load("orders/1234"); // this will not require querying the server! var referrer2 = session.Load<Customer2>(order.Refferal2.Customer2Id); var order = session.Include<Order2, Product2>(x => x.LineItem2s.Select(li => li.Product2Id)) .Load("orders/1234"); foreach (var lineItem2 in order.LineItem2s) { // this will not require querying the server! var product2 = session.Load<Product2>(lineItem2.Product2Id); } The second parameter to the generic Include<T, TInclude> specifies which document collection the reference is pointing to. RavenDB will combine the name of the collection with the value of the reference property to find the full identifier of the referenced document. For example, from the first example, if the value of the Order.Customer2Id property is the integer 56, RavenDB will include the document with an Id of "customer2s/56" from the database. The Session.Load<Customer2>() method will be passed the value 56 and will look for then load the document "customer2s/56" from the session cache. Lucene Queries Same query extensions have been applied to LuceneQuery, so to include Customer by CustomerId property can be achieved in both ways: var orders = session.Advanced.LuceneQuery<Order2>() .Include(x => x.Customer2Id) .WhereGreaterThan(x => x.TotalPrice, 100) .ToList(); foreach (var order in orders) { // this will not require querying the server! var cust2 = session.Load<Customer2>(order.Customer2Id); } or var orders = session.Advanced.LuceneQuery<Order2>() .Include("CustomerId") .WhereGreaterThan(x => x.TotalPrice, 100) .ToList(); foreach (var order in orders) { // this will not require querying the server! var cust2 = session.Load<Customer2>(order.Customer2Id); } Include rules When using string-based includes like: var order = session.Include("Refferal.CustomerId") .Load<Order>("orders/1234"); // this will not require querying the server! var referrer = session.Load<Customer>(order.Refferal.CustomerId); you must remember to follow certain rules that must apply to the provided string path: - Dots are used to separate properties e.g. "Referral.CustomerId"in example above means that our Ordercontains property Referraland that property contains another property called CustomerId. - Commas are used to indicate that property is a collection type e.g. List. So if our Orderwill have a list of LineItems and each LineItemwill contain ProductIdproperty then we can create string path as follows: "LineItems.,ProductId". - Prefixes are used to indicate id prefix for non-string identifiers. e.g. if our CustomerIdproperty in "Referral.CustomerId"path is an integer then we should add customers/prefix so the final path would look like "Referral.CustomerId(customers/)"and for our collection example it would be "LineItems.,ProductId(products/)"if the ProductIdwould be a non-string type. Learning string path rules may be useful when you will want to query database using HTTP API. > curl -X GET "" Live Projections Using Includes is very powerful, but sometimes we want to do even more complex manipulation. The Live Projection feature is unique to RavenDB, and it can be thought of as the third step of the Map/Reduce operation: after having mapped all data, and it has been reduced (if the index is a Map/Reduce index), the RavenDB server can additionally transform the results into a completely different data structure and return that back instead of the original results. Using the Live Projections feature, you have more control over what to load into the result entity, and since it returns a projection of the original entity, you also get the chance to filter out properties you do not need. Let's look at an example to show how it can be used. Assuming we have many User entities and many of them are actually an alias for another user. If we wanted to display all users with their aliases using Include(), we would probably need to write something like this: // Storing a sample entity var entity = new User { Name = "Ayende" }; session.Store(entity); session.Store(new User { Name = "Oren", AliasId = entity.Id }); session.SaveChanges(); // ... // ... // Get all users, mark AliasId as a field we want to use for Including var usersWithAliases = from user in session.Query<User>().Include(x => x.AliasId) where user.AliasId != null select user; var results = new List<UserAndAlias>(); // Prepare our results list foreach (var user in usersWithAliases) { // For each user, load its associated alias based on that user Id results.Add(new UserAndAlias { UserName = user.Name, Alias = session.Load<User>(user.AliasId).Name } ); } Since we use Includes, the server will only be accessed once - which is good, but the entire object graph for each referenced document (user entity for the alias) will be returned by the server... and it's an awful lot of code to write too! Using Live Projections, we can get the same end result much more easily and with the transformation applied on the server side. This code defines an index which performs a Live Projection: public class Users_ByAlias : AbstractIndexCreationTask<User> { public Users_ByAlias() { Map = users => from user in users select new { user.AliasId }; TransformResults = (database, users) => from user in users let alias = database.Load<User>(user.AliasId) select new { Name = user.Name, Alias = alias.Name }; } } The function declared in TransformResults will be executed on the results of the query, which gives it the opportunity to modify, extend or filter those results. In this case, it lets us look at data from another document and use it to project a new return type. A Live Projection will return a projection, on which you can use the .As<> clause to convert it back to a type known by your application: var usersWithAliases = (from user in session.Query<User, Users_ByAlias>() where user.AliasId != null select user).As<UserAndAlias>(); The main benefits of using Live Projections are; not having to write as much code, they run on the server and they reduce the network bandwidth by returning only the data we are interested in. Combining Approaches It is possible to combine the above techniques. Using the DenormalizedCustomer from above and creating an order that uses it: public class Order3 { public DenormalizedCustomer Customer { get; set; } public string[] SupplierIds { get; set; } public Referral Refferal { get; set; } public LineItem[] LineItems { get; set; } public double TotalPrice { get; set; } } We have the advantages of a denormalization, a quick and simple load of an Order and the fairly static Customer details that are required for most processing. But we also have the ability to easily and efficiently load the full Customer object when necessary using: var order = session.Include<Order3, Customer2>(x => x.Customer.Id) .Load("orders/1234"); // this will not require querying the server! var fullCustomer = session.Load<Customer2>(order.Customer.Id); This combining of denormalization and Includes could also be used with a list of denormalized objects. It is possible to use Include on a query against a Live Projection. Includes are evaluated after the TransformResults has been evaluated. This opens up the possibility of implementing Tertiary Includes (i.e. retrieving documents that are referenced by documents that are referenced by the root document). Whilst RavenDB can support Tertiary Includes, before resorting to them you should re-evaluate your document model. Needing to use Tertiary Includes can be an indication that you are designing your documents along "Relational" lines. Summary There are no strict rules as to when to use which approach, but the general idea is to give it a lot of thought, and consider the implications each approach has. As an example, in an e-commerce application it might be better to denormalize product names and prices into an order line object, since you want to make sure the customer sees the same price and product title in the order history. But the customer name and addresses should probably be references, rather than denormalized into the order entity. For most cases where denormalization is not an option, Includes are probably the answer. Whenever serious processing is required after the Map/Reduce work is done, or when you need a different entity structure returned than those defined by your index - take a look at Live Projections. The comments section is for user feedback or community content. If you seek assistance or have any questions, please post them at our support forums. So, if we delete a document by some references to other documents, what happen to them? e.g. when delete a 'User', associated aliases will be deleted too? No, but you can setup something like this with the cascade deletes bundle. See here: ()[] Thanks Itamar. But another question: I have 3 entity like these: A one-to-many relationship from 'Member' to 'Info' A many-to-many from 'Member' to 'School' What about them? How can I work with them? For example, when I create a new 'Member', and do something like this: what happens really? Can I load the 'Info' later, without the 'Member' -Load-by-infoid? I think you must explain more about relationships. A single article like this one -in this page- is not really enough. I'm so excited on RavenDb, but there is not enough information and documentation about it. I hope I can learn and understand it. So thanks. The entire object graph will be saved, so he Member document will contain an Info object in an attribute callled Info. To read Info, you will need to load the Member object containing it. Just like you'd do when storing it in an in-memory collection like a Dictionary. "Relations" in RavenDB are really just a logical concept - the database doesn't know about them at all. When instead of an object you save a reference to it (it's ID, as a string attribute, e.g. string InfoId instead of Info Info) you can leverage Includes and Live Projections to make this decision more transparent. Deciding which way to go is really a matter of understanding and experience. Ping us on the mailing list and we'll be glad to give you more specific help. Thanks again. I can't find your mailing list! ): Includes You show example how to use Includes to fetch related document. Can we use this method recursively to fetch all orders - and their customers - and their favorite items - and their statistics, etc? In an application I'm working on (which I evaluate changing to RavenDB) I have some screens that I know up-front I need some data, so instead of lazy load it from the server which will generate many request and very slow experience I use custom server that I can ask it to return the entier data set, that's where the question came from. No, Includes are NOT recursive. This is by design. The sort of scenario that you are talking about can be done using a Live Projection in the index, but I would be surprised if you actually needed to do that, to be frank. Modeling the data properly will allow you to do this without needing recursive queries. Hi, Thanks for the answer. I agree that most scenarios do not require recursion. It may be side-effect of the fact that I'm using ORM behind RESTful web service which lead me to optimize the RESTful service by ensure I request a complete data structure once and not go back-and-forth for each data type. Another reason I model my data that way is because some screens need specific data which others required composition of multiple items. I do not want to get the entier data for the former screen, nor be have to do multiple requests for the later so I need to be able to query data with specific resolution. You can do that using lazy requests, includes, etc. Ayende - can Lazy requests be added to the documentation? Yes, You can follow up on that here () or look at the blog post. I'm trying to make sense of your example of "Include". Didn't you mean to have the order .Include<Customer> as opposed to .Include<Order> ? No, the syntax is correct. It is just a way to create an IRavenQueryable for an Order object - it is equivalent to .Load<Order>(id).Customize(x => x.Include(y => y.CustomerId)) The definition for the include operation is what specified within parenthesis The type parameter is not there for the RavenDB engine, it's there so that the Include is strongly typed. In that example, we're asking to load an Order together with whatever is in the included property CustomerId. So the type on the Include call is the type of x, not of x.CustomerId. Ah... I didn't digest that the CustomerID includes the collection name which is how Raven knows how to resolve it definitively. I see what you did there.... neat! :^) How can I query to get all orders that have a customer age more than 25? There is this option: Or using LoadDocument to load the customer document in the index. Note that generally, you don't search for one document based on property on a related document. It indicate a problem in your model. Does it guaranted that multiple documents retrieved through Load<T>(params string[] ids) will be in the same order that their ids?
http://ravendb.net/docs/2.5/client-api/querying/handling-document-relationships
CC-MAIN-2014-42
refinedweb
3,775
55.44
Thomas Huth <address@hidden> writes: > Delete the unused functions qemu_opt_get_number_del(), > qemu_signalfd_available(), qemu_send_full() and qemu_recv_full(). > > Signed-off-by: Thomas Huth <address@hidden> qemu_opt_get_number_del() was added in commit 782730b along with qemu_opt_get_del(), qemu_opt_get_bool_del() and qemu_opt_get_size_del(). It hasn't been used so far, but removing it makes the interface irregular. I'd rather not. Covering all four in tests/test-qemu-opts.c would be nice. qemu_send_full() and qemu_recv_full() complement qemu_write_full(). On the other hand, there's no qemu_read_full(). I don't think keeping the two unused ones hurts, but I don't object to dropping them, either. For what it's worth, glibc provides a macro to solve this problem once and for all: /* Evaluate EXPRESSION, and repeat as long as it returns -1 with `errno' set to EINTR. */ # define TEMP_FAILURE_RETRY(expression) \ (__extension__ \ ({ long int __result; \ do __result = (long int) (expression); \ while (__result == -1L && errno == EINTR); \ __result; })) #endif More elegant than writing the same old boring wrapper around everything that can fail with EINTR. qemu_signalfd_available() is unused since commit 6d32717. It's also the only user of CONFIG_SIGNALFD. If we want to drop it, I recommend dropping CONFIG_SIGNALFD as well.
https://lists.gnu.org/archive/html/qemu-devel/2015-02/msg03346.html
CC-MAIN-2020-40
refinedweb
188
58.99
QUOTACTL(2) BSD Programmer's Manual QUOTACTL(2) quotactl - manipulate filesystem quotas #include <ufs/ufs/quota.h> /* for ufs quotas */ #include <unistd.h> int quotactl(const char *path, int cmd, int id, char *addr); may turn quotas off. Q_GETQUOTA Get disk quota limits and current usage for the user or group (as determined by the command type) with identifier id. addr is a pointer to a struct dqblk structure. Q_SETQUOTA Set disk quota limits for the user or group (as determined by the command type) with identifier id. addr is a pointer to a struct dqblk structure. The usage fields of. [EACCES] Search permission is denied for a component of a path)..
http://www.mirbsd.org/htman/i386/man2/quotactl.htm
CC-MAIN-2014-49
refinedweb
112
59.7
I'm trying to do some I/O operations for some homework, but I'm stuck. I have to write a program that reads data from a text file, and store updated information in a [.dat] file. The text file reads as the following: Miller Andrew 65789.87 5 Green Sheila 75892.56 6 Sethi Amit 74900.50 6.1 Last name, first name, current salary, and pay increase. I have to read from the text file, write the [.dat] file with the last name, first name, and updated salary. Here is what I have so far, and I am completely lost. My professors husband died the first day of class, and we haven't went over I/O operations, but she still expects us to do the homework. How can I read from the text file, and write each line with the new updated salary? #include <iostream> #include <iomanip> #include <string> #include <fstream> using namespace std; int main() { string line; string firstName; string lastName; double currentSalary; double increaseVar; double updatedSalary; ifstream inData; ofstream outData; inData.open("Ch3_Ex8Data.txt"); outData.open("Ch3_Ex8Output.dat"); if(inData.is_open()) { while(!inData.eof()) { inData >> lastName >> firstName >> currentSalary >> increaseVar >> updatedSalary; getline(inData, line); } inData.close(); outData.close(); } return 0; }
http://forum.codecall.net/topic/61939-homework-help/
crawl-003
refinedweb
204
66.74
Tilt-a-Whirl Hookup Guide. Hardware Hookup There are only four pins that need to be hooked up in order to start using this sensor in a project. One for VCC, one for GND, and two data lines for outputting the photointerrupter data. For this example, we are using an Arduino Uno to show the connections. However, you can use any microcontroller you prefer with this sensor. Connections: - VCC → 5V (or 3.3V) - GND → GND - S1 → D2 - S2 → D3 Here is a Fritzing diagram showing the actual connections between the Tilt-a-Whirl and an Arduino Uno. Multiple Sensors You can connect multiple sensors to a single Arduino board, you will just need to use 2 digital pins for each sensor you would like to connect. For example, if you want to hook up two additional sensors (3 total), you would need to connect to digital pins 2, 3, 4, 5, 6, and 7 on the Arduino. Talking to the Sensor Now that the hardware is hooked up and ready to go, we need to upload code to the Arduino in order to start communicating with the sensor. You can download the example Arduino sketch here. The most up-to-date code is also available on GitHub. Feel free to take this code, and modify it for your own purposes and projects! At the beginning of the sketch, both S1 and S2 are initialized as integers, connected to pins D2 and D3 respectively. language:c int tilt_s1 = 2; int tilt_s2 = 3; This would be where you would initialize any additional sensors you would like to connect to the Arduino. Each additional pin would need to be defined as an integer and would need to be assigned to a digital pin that is still available. Moving on to the set up loop, pins D2 and D3 are set as inputs, and serial communication is initialized at 9600 bps. language:c void setup() { pinMode(tilt_s1, INPUT); pinMode(tilt_s2, INPUT); Serial.begin(9600); } Keep in mind, if you add in additional sensors, you will need to define the pinMode for each additional sensor pin as an input. You can also change the serial communication speed if necessary for your particular application. Within the function loop, we simply use two functions. First, the function getTiltPosition() is called, which digitally reads the input from the two sensor pins. The received data is then processed using bitwise math, and returned to the main loop. language:c int getTiltPosition() { int s1 = digitalRead(tilt_s1); int s2 = digitalRead(tilt_s2); return (s1 << 1) | s2; //bitwise math to combine the values } The function loop then assigns the data to the variable ‘position’, which is then printed out over the serial connection. language:c void loop() { int position = getTiltPosition(); Serial.println(position); delay(200); //only here to slow down the serial output } The sensor data will then be displayed every 2 milliseconds on the serial display. That’s it! It really is that simple to get communication with your sensor started. Resources and Going Further Now that you know how to communicate with the Tilt-a-Whirl sensor, it’s time to go out and apply this to your own project! Check out the additional resources below if you need, otherwise, feel free to leave us feedback on this tutorial, or let us know how you apply this in your projects.
https://learn.sparkfun.com/tutorials/tilt-a-whirl-hookup-guide
CC-MAIN-2016-36
refinedweb
559
61.26
On Fri, Mar 2, 2018 at 8:55 AM, Jeff Law <l...@redhat.com> wrote: > On 03/02/2018 09:38 AM, Thomas Schwinge wrote: >> Hi! >> >> On Fri, 26 Jan 2018 16:24:48 +0100, Martin Liška <mli...@suse.cz> wrote: >>> This fixes detection of ifunc target capability. >>> I'm going to install the patch. >> >> You could also just have approved the patch I had sent two months before: >> <>. >> ;-) >> >> One remark: >> >>> --- a/gcc/testsuite/lib/target-supports.exp >>> +++ b/gcc/testsuite/lib/target-supports.exp >>> @@ -449,7 +449,7 @@ proc check_ifunc_available { } { >>> extern "C" { >>> #endif >>> typedef void F (void); >>> - F* g (void) {} >>> + F* g (void) { return 0; } >>> void f () __attribute__ ((ifunc ("g"))); >>> #ifdef __cplusplus >>> } >> >> Is it OK to "return 0" from this ifunc handler, or might some analysis in >> GCC trip over that (at some later point)? In my patch, I returned the >> address of an "extern" function. > ISTM the question is whether or not ifuncs are ever allowed to return > NULL. Maybe ping the glibc folks since that's where the extension started? No, ifunc selector should never return NULL. -- H.J.
https://www.mail-archive.com/gcc-patches@gcc.gnu.org/msg185514.html
CC-MAIN-2018-39
refinedweb
182
75.3
- February 25 2007 == The PostgreSQL fund at SPI this month funded David Fetter's travel to Consili in Brazil where he delivered a conference keynote, and Neil Conway's next two months of patch review work for PostgreSQL 8.3. A Lively Discussion(TM) is going on on -hackers on the subject of source code management. The Seventh Framework Programme (FP7) is open for proposals. EU PostgreSQL organizations, consider sending in a proposal :) You can now use search.postgresql.org as a firefox search box plugin. == PostgreSQL Product News == Cybertek of Austria has announced a synchronous multi-master replication product for PostgreSQL. PGCluster-1.5.0rc15 and 1.7.0rc4 released. ==. The Italian PostgreSQL community is looking for sponsors for its PostgreSQL day in Prato, Italy this summer. Check the link below to participate. == PostgreSQL in the News == Microsoft Technet publishes PostgreSQL HOWTO:... OmniTI case study published:;413111662;fp;4194304;... Planet PostgreSQL: General Bits, Archives and occasional new articles: PostgreSQL Weekly News is brought to you this week by David Fetter, Josh Berkus and Devrim GUNDUZ. To get your submission into the upcoming issue, get it to david@fetter.org by Sunday at 3:00pm Pacific Time. == Applied Patches == Andrew Dunstan committed: - Allow pltcl args to spi_prepare and plpython args to plpy.prepare to be standard type aliases as well as those known in pg_type. Similar to recent change in plperl. Peter Eisentraut committed: - Bernd Helmle's patch which identifies the schema of inherited tables in psql \d when necessary. - Add missing OIDs from xml support to pg_proc, bump catversion. Bruce Momjian committed: - Move test for BLCKSZ < 1024 to guc.c. - Spelling fix in Solaris FAQ. - Update Solaris FAQ per Peter Eisentraut. - Updated FAQ on upgrading. - Zdenek Kotala's patch to the Solaris FAQ. - Chad Wagner's patch to psql which adds \prompt capability. - Remove extra tab from pgsql/doc/src/sgml/ref/psql-ref.sgml. - Remove tabs from SGML reference files so their addition can be detected in the future. - Update message wording in FAQ. - Update new optional VACUUM FULL hint for translations, per Alvaro Herrera. - Simon Riggs's patch which moves increase FSM warning to after lazy_truncate_heap() because the function might reduce the number of free pages in the table. Recommend VACUUM FULL only if 20% free. - Heikki Linnakangas's patch to clean up the btree source code. - Update FAQ about minor updates. - Jun Kuwamura's update to the Japanese FAQ. - Update URL in German FAQ for bug form, per Schima, Fabian - Daojing Zhou's update of the Chinese FAQs to have two versions, a traditional Chinese version (Taiwan) and a Simplified version (China (PRC)). Backpatch to 8.2.X. - Update minor release text in FAQ. - Add configure --enable-profiling to enable GCC profiling. Patches from Korry Douglas and Nikhil S - Update upgrade text in FAQ. - Update URL for set-returning functions in FAQ. - Add URL for "Allow row and record variables to be set to NULL constants, and allow NULL tests on such variables" in the TODO list. - Prevent BLCKSZ < 1024, and have initdb test shared buffers based on the BLCKSZ value. - Add to TODO: "Consider decreasing the amount of memory used by PrivateRefCount." - Fix markup in pgsql/doc/src/sgml/information_schema.sgml. - Change $(CC) to $(COMPILER) on Solaris gcc so -m64 is passed into the shared link line. - Add to TODO: "Increase locking when DROPing objects so dependent objects cannot get dropped while the DROP operation is happening." - Add URL for "Allow UPDATE/DELETE WHERE CURRENT OF cursor" in TODO list. - Add to TODO: "Add missing operators for geometric data types. Some geometric types do not have the full suite of geometric operators, e.g. box @> point." - Update "encode" documentation to mention that 'escape' only changes null bytes and backslashes, remove "ASCII" mention. Backpatch to 8.2.X. - Update pgpass Win32 wording. - Update information_schema documentation to match system tables. Backpatch to 8.2.X. - Improve wording on Julian dates in pgsql/doc/src/sgml/func.sgml. - More clearly document that most PostgreSQL utilities support libpq environment variables. Backpatch to 8.2.X. - Remove from TODO for Win32: "Check .pgpass file permissions." It is not needed. - In pgsql/src/interfaces/libpq/fe-connect.c, add comment that on Win32, we don't need to check the .pgpass file permission, per Magnus Hagander. - Add to TODO for Win32: "Check .pgpass file permissions." - Update array slice documentation to be clearer. - Add to TODO: "Fix IS OF so it matches the ISO specification, and add documentation." - Comment-out documentation for IS OF because it doesn't conform to the ISO SQL behavior. Backpatch removal to 8.2.X. - Remove TODO item: "ARRAY[[1,2],[3,4]])[1] should return the same values as ARRAY[[1,2],[3,4]])[1:1]." It actually shouldn't. - Add text about Makefile.custom to FAQ_DEV. - Document that to_char('J'/Julian) is midnight-based, per report that Julian technically is noon to noon. - Improve wording in isodow documentation. - Update PQfree() documentation to be clearer, backpatch to 8.2.X. - Add to TODO: "Allow user configuration of TOAST thresholds." - Add newlines to TODO. - Add to TODO: "Allow UPDATEs on only non-referential integrity columns not to conflict with referential integrity locks." - Add to TODO: "Allow INSERT/UPDATE ... RETURNING inside a SELECT 'FROM' clause." - Clarify documentation that initdb -A or editing pg_hba.conf is required if you do not trust local users. - Clarify documentation for "day of the week" handling for to_char() and EXTRACT(). - Mark TODO as done: "Add ISO day of week format 'ID' to to_char() where Monday = 1." - Add "isodow" option to EXTRACT() and date_part() where Sunday = 7. - Mark TODO as done: "Add a field 'isoyear' to extract(), based on the ISO week." - Mark TODO as done: "Add long file support for binary pg_dump output." Magnus Hagander committed: - In pgsql/src/tools/msvc/Solution.pm, revert changes to process pg_proc.h entries without OIDs. We're not supposed to have such entries, and want to be notified when we do... Leave the plain bug fix in genbki. - Fix pg_dump on Win32 so that it properly dumps files larger than 2GB when using binary dump formats. - Parse pg_proc.h with entries without OIDs for the MSVC build. Tom Lane committed: - Update 7.x variant horology files to match the new US DST rules. It seems likely that anyone wanting to run the regression tests in the future will have up-to-date system timezone files, so this is more likely to work than the old contents. - Put back copyObject() call I removed in a fit of brain fade. This one is still needed despite cleanups in setrefs.c, because the point is to let the inserted Result node compute a different tlist than its input node does. Per example from Jeremy Drake. -. - Change Agg and Group nodes so that Vars contained in their targetlists and quals have varno OUTER, rather than zero, to indicate a reference to an output of their lefttree subplan. This is consistent with the way that every other upper-level node type does it, and allows some simplifications in setrefs.c and EXPLAIN. - Fix bug I introduced in recent patch to make hash joins discard null tuples immediately: ExecHashGetHashValue failed to restore the caller's memory context before taking the failure exit. -. - Adjust user-facing documentation to explain why we don't check pgpass file permissions on Windows. -. - Get rid of some old and crufty global variables in the planner. When this code was last gone over, there wasn't really any alternative to globals because we didn't have the PlannerInfo struct being passed all through the planner code. Now that we do, we can restructure things to avoid non-reentrancy. I'm fooling with this because otherwise I'd have had to add another global variable for the planned compact range table list. == Rejected Patches (for now) == Mateo Beccati's patch which gets PostgreSQL to compile on Irix 6.5, but the patch would break most Linux machines. == Pending Patches == Zoltan Boszormenyi sent in two more iterations of his IDENTITY/GENERATED patch. Pavan Deolasee sent in two more versions of his work-in-progress HOT patch. Gregory Stark sent in a patch to shorten varlena headers. Guillaume Smet sent in a first implementation of GIN for pg_trgm. Nikolay Samokhvalov sent in a patch to implement xpath_array with namespaces support. Darcy Buskermolen sent in a patch which provides for logging in the event that -k is unable to clean up an old WAL file and makes the "failed to remove file" error message consistent for the trigger file. Greg Sabino Mullane sent in a documentation patch which warns about some strange behavior in LISTEN/NOTIFY. Pavel Stehule sent in a patch to add timestamp support for XSD-type timestamps. Simon Riggs sent in another version of his patch to avoid deadlocks in pg_dump. Joachim Wieland sent in a patch which makes GUC values fall back to their default values when they got removed (or commented) from the configuration file. Kris Jurka sent in a patch which implements lo_truncate for truncating large objects to a given length. This is required for implementing Blob.truncate in the JDBC driver and rounds out filesystem like functionality for large objects. Simon Riggs sent a bug fix for his recent optimization of COPY-after-truncate. ---------------------------(end of broadcast)--------------------------- -To unsubscribe from this list, send an email to: pgsql-announce-unsubscribe@postgresql.org Linux is a registered trademark of Linus Torvalds
http://lwn.net/Articles/223770/
CC-MAIN-2013-48
refinedweb
1,574
60.01
Even 🙁 #if <token> … #endif #ifcommentfalse fore. I think it is good to delete the code when the business logic that it is performing is no more in use. That is true, lot of commented code creates confusion. Just as a standard, having a change log at the top of the module can sort out the problems. As abhinaba said, we can always go to source control and get the prior version. I agree with you! No source files should ever be checked into source control with commented-out code. Unfortunately, it is too easy to forget, because commenting out code during development is pretty helpful. I also like the IDE feature that comments out code. I tend to see more commented out code in projects that use source code control less effectively or not at all. In a way, it’s a sign of timidity on the part of the developer, to leave the old code around. "Just as a standard, having a change log at the top of the module can sort out the problems." Personally, I favor changelogs in CVS comments. If they’re in the source file itself, it’s 1) just something else to maintain and 2) something else to scroll past to get to your code. (I think looking at change history is less common than looking at code, and I like to optimize for the common case.) This reminds me. Conditionally compiled code has some of the same problems as commented code. I’ve found it useful to do this, where it can be used: #ifdef SOME_COMPILER_FLAG enum { SOME_COMPILER_FLAG_CODE = true }; #else enum { SOME_COMPILER_FLAG_CODE = false }; #endif … later, in a source file … if (SOME_COMPILER_FLAG_CODE) { // whatever… } This has the benefit that the possibly disabled code is always compiled, and always syntax checked. It makes it easier to avoid bit-rot, in the case you have to have conditional compilation. Also, A decent optimizing compiler will detect the constant conditional guard and eliminate the code. I always surround commented-out code that I’m not willing to nuke yet in a region. Methods that are commented out go into a region at the end of a file. #region Depreciated /* for(this.IsCodeThat is BeingReplaced) { ButIMayNeed.It = InFuture; } */ #endregion Amen! If you are using source-control software (and you should be), then there is NEVER a reason for commented out code. If you have a feature that might come back, then drop a label on the version that had the code and add a comment in the code that specifies the label. If you ABSOLUTELY must comment out code, do it with an if (false) { } block around it (not an #if FALSE block) so the code is still syntax-checked with later changes, otherwise when you do restore the code it may not compile, or code it needed may have been factored away. I comment out code when my project manager insists on a change that I know is wrong. I also date it and add his name and his reasoning. Eventually he’ll wonder why a feature has been removed and I’ll show him the commented out code. Then I uncomment it and put it back to how I had it originally. If I’m commenting out code to try something, I’ll use //? or //% or anythign like that to make it easier to find and delete later. I really don’t like the use of #if false #endif to comment out a block of code. The nice thing of using real comments is that the code will in most editors show up with the color for a comment even if you’re viewing the middle of the comment and the start/end points are off screen. Most editors I’ve used, VS included, do not signify that a piece of code is unreachable because it’s #if false’ed out. Makes for plenty of fun when reading the code later. This is of course complicated by the fact preprocessor directives get automatically untabbed so they’re on the far left, if you’re looking at code that been indented a few times you may not notice the #if false on the left, or heck be scrolled to the right enough that its not even visible. Jody its time you upgraded your VS 🙂 I’m not too sure about VS 2003, but VS 2005 does colorize #if false marked code to indicate its unreachable. The code copy pasted above is from VS 2005 and its showing grayed out code. If VIM shows it that way Should we care that much it’s not like it’s done all the time from what you’re saying and perhaps the commented code could be looked at for future referance. To be honist I’m supprised you spent time writing all this! Suppose hate is such a strong word to use and I think developers need more flexibility on things rather that being told how they should do it because of how you hate it. Signle line comments are cool because you can just Ctrl+K+C (Comment) and Ctrl+K+U (Uncomment) a selection of code. If deisnged well you can run different test senarios in one class if that’s your fancy for a system you’re making. I’m more learned to surrounding with a region however… sometimes that can get messy to though. Personally, I find Commented out code generally arrives from one programmer doing a job one way, and another replacing it with a better way, but in case that something was overlooked, the old code is left in, so that the code can be reverted at a later date. My feeling is that since source control should do it’s job here, and a comment such as "// Inefficient calculation code removed 12/12/2009 view Source control for previous version" That means, that should it be discovered that the old code had a required side-effect, then it could be retrieved at a later date from source safe.
https://blogs.msdn.microsoft.com/abhinaba/2005/11/22/c-i-hate-commented-out-code/
CC-MAIN-2017-22
refinedweb
1,004
68.4
Shapeless is a type class and dependent type based generic programming library for Scala. It is an Open Source project under the Apache License v2, hosted on github. Well, simply put, it is a well known library for generic programming in scala. Earlier, reflection APIs were used to write generic programs. However, since reflection is usually done in runtime, it sacrifices type-safety, and introduces runtime failures. But luckily, Shapeless is there to solve problems during compilation where they would normally be tackled in runtime. Shapeless aims to give you confidence that if a piece of code compiles, it will run as well. Using Shapeless: To include the Shapeless in your SBT project for scala 2.11.8 you should add the following in your SBT build, libraryDependencies ++= Seq( "com.chuusai" %% "shapeless" % "2.3.1" ) Shapeless has a wide range of features. Lets have a look at two of them where Scala did not join hands with us. Polymorphic function values Before that, lets understand what a monomorphic and a polymorphic function is: Monomorphic methods can only be applied to arguments of the fixed types specified in their signatures and their subtypes. For eg. def findSize(s: String): Int = s.length However, polymorphic methods can be applied to arguments of any types which correspond to acceptable choices for their type parameters. For eg. def findSize[T](l: List[T]): Int = l.length Scala allows both monomorphic as well as the polymorphic methods. The real problem arises with function values. In Scala, we cannot achieve polymorphic function values and therefore it produces some lack of expressiveness. Try assigning function to a val(Eta expansion): scala> def monomorphicListToSet(l: List[Int]): Set[Int]= l.toSet monomorphicListToSet: (l: List[Int])Set[Int] scala> val a = monomorphicListToSet _ a: List[Int] => Set[Int] = <function1> Have a look at the definition of the above function that transforms the List[Int] into a Set[Int]. The type Int is restricted here. But Scala syntax doesn’t allow to define something similar for polymorphic functions. scala> def polymorphicListToSet[T](l: List[T]): Set[T] = l.toSet polymorphicListToSet: [T](l: List[T])Set[T] scala> val sadlyMonomorphic = polymorphicListToSet _ sadlyMonomorphic: List[Nothing] => Set[Nothing] = <function1> this is where the compiler goes wrong, it says the list contained type is Nothing. Here Shapeless comes to our rescue. It provides an encoding of polymorphic function values. It supports natural transformations, First of them has the following notation: import shapeless.poly._ scala> val polyOptionToList = new (Option ~> List){ | def apply[T](f: Option[T]): List[T]= | f.toList | } polyOptionToList: shapeless.poly.~>[Option,List] = $anon$1@1e731f50 scala> val result = polyOptionToList(Option(2)) result: List[Int] = List(2) The other possible notation consists of defining the function behavior based on cases, where in we can define the function only for Int, String and Boolean by adding a case for each data type or as the need arises. import shapeless.Poly1 scala>object size extends Poly1 { | implicit def caseInt = at[Int](x ⇒ 1) | implicit def caseString = at[String](_.length) | implicit def caseTuple[T, U](implicit st: Case.Aux[T, Int], su: Case.Aux[U, Int]) = | at[(T, U)](t ⇒ size(t._1) + size(t._2)) | } defined object size scala> size(23) res0: Int = 1 scala> size("foobar") res1: Int = 6 scala> size((23, "foobar")) res2: Int = 7 scala> size(((23, "foobar"), 13)) res3: Int = 8 Another promising feature of Shapeless is the support for HLists. HLists (short for Heterogeneous Lists) are lists of objects of arbitrary types, where the type information for each object is kept. In fact, in Scala, we may do: s cala> val l ist = 10 :: " anyString " :: 1.0 :: Nil list: List[Any] = List(10, anyString, 1.0) as you can see the type of list is List[Any], beacuse the common supertype of all the elements is Any. However an HList is declared in the same way: scala> val h List = 10 :: " anyString " :: 1.0 :: H Nil hList: shapeless.::[Int,shapeless.::[String,shapeless.:[Double,shapeless.HNil]]] = 10 :: anyString :: 1.0 :: HNil except for the terminator HNil. But the type of hList is actually Int::String::Double::HNil An HList stores the type of every element in the list. This way we know the type of the first element, the type of the second element, and so forth. As you can see, no type information is lost. Well you might wonder, why Hlists over Lists ?? lets have an example to prove it. scala> list.tail.head.toUpperCase // error: value toUpperCase is not a member of Any scala> hList.tail.head.toUpperCase res6: String = ANYSTRING Why should you really use HLists? - HLists can be used in all conditions where a tuple would work, but without the 22- element limitation. - Also the above two are convertible to each other via ‘tupled’ and ‘productElements’ methods. For other promising features of Shapeless, you can have a look at the below link: Happy Reading 🙂 6 thoughts on “Introduction to Shapeless !4 min read” Reblogged this on deeptibhblog. Reblogged this on himaniarora1. Reblogged this on Prabhat Kashyap – Scala-Trek. Reblogged this on kunalkapoor. variable name `polyListToSet ` is a bit confusing. Probable should be renamed to `polyOptionToList`. Thanks for the article. Thanks for pointing it out 🙂
https://blog.knoldus.com/introduction-to-shapeless/
CC-MAIN-2021-43
refinedweb
870
67.35
[…] I have taken your PY code and have tried to make it work for values other the 8 primes and Wheel Size 30, by changing the value 8 to NP and the value 30 to NX. Also some additional changes such as changing the I <>3 shifts to division by 8 or NP in t=my modified code) . The I & 7, I change to I % NP. I aslo made a few simple changes to print some intermediate information. I have included my PY code in this email. It works OK when I set the values of NP = 8 and NX = 30. However, when I try to extend the code to consider additional primes beyond 31, to 37 and 41 – changing NP = 10 and NX= 30 and also changing “gaps” and “ndxs” to account for the additional primes, it fails miserably—see the code below. I get many additional values that are not prime and miss a few that are. I believe the issue is in the code fragment: buf[c::p8] = [0] * ((lmtbf – c) // p8 + 1) In the case where NP = 10 the p8 value would be p*NP. I can’t figure it out. If you find a bug or two I wouldn’t be surprised. You seem to be an expert on the sieving processes, maybe you can help? My PY code— #!/usr/bin/python def primes235(limit) : print “\nlimit %20d\n” % limit #yield 2; yield 3; yield 5 if limit limit+1 : break #for i in xrange(lmtbf – 6 + (ndxs[(limit – 7) % 30])): # adjust for extras # if buf[i]: yield (30 * (i >> 3) + modPrms[i & 7]) #print “buf[i] %20d\n” % buf[i] return [2,3,5] + [(NX * (i//NP) + modPrms[i % NP]) | 1 for i in xrange(lmtbf – 6 + (ndxs[(limit – 7) % NX])) if buf[i]] “””*************************************************************************************** A test driver. ***************************************************************************************””” if __name__ == ‘__main__’ : #for p in primes235(1000000000) : # if p > 999999900 and p < 1000000000: print(p) p = primes235(2310) print "\n" print p print "\n\n Prime count: %d\n" % len(p) k = 1; for i in range (len(p)) : print k, p[i] k = k + 1 @Peter: You don’t seem to understand how a prime wheel works. A 2,3,5-wheel uses the totatives of 2*3*5=30 to determine the stops of the wheel. The next larger wheel is not 37 or 41, it’s a 2,3,5,7-wheel with a circumference of 2*3*5*7=210. To learn more about prime wheels, look at my Wheel Factorization exercise. @Peter, as programmingpraxis says, you don’t seem to understand factorization wheels. For the 2,3,5,7 wheel, “modPrms” will be the totients from 11 up to 220 excluding those numbers evenly divisible by 2,3,5, or 7 for a total of 48 entries, “gaps” will be two times 48 elements long, and “ndxs” will be 210 elements long; these can be auto generated by little programs. The resulting program needs adjustment for almost every line as to the factors of 48 and 210 rather than 8 and 30, and the resulting program won’t gain as much performance as expected because there will need to be divisions by 48 rather than just right shifts by 3 to effect the division by 8. For large ranges, this wouldn’t be the way to write this anyway, as using the “one large buffer array” won’t be very efficient and a page segmented approach would be much better, also would not require a fixed upper limit bound, although the resulting program would be a little more complex.
https://programmingpraxis.com/2012/01/06/pritchards-wheel-sieve/?like=1&source=post_flair&_wpnonce=fb311db3f8
CC-MAIN-2018-13
refinedweb
598
71.99
This class is an implementation of the abstract POE::Loop interface. It follows POE::Loop's public interface exactly. Therefore, please see POE::Loop for its documentation....KARASIK/POE-Loop-Prima-1.03 - 08 Jun 2015 10:26:41 GMT - Search in distribution The FAQ covers various topics around Prima, such as distribution, compilation, installation, and programming....KARASIK/Prima-1.49 5 (3 reviews) - 27 Sep 2016 13:33.13 5 (4 reviews) - 17 Sep 2016 02:34:50 GMT - Search in distribution This task contains all distributions under the POE namespace....APOCAL/Task-POE-All-1.102 - 09 Nov 2014 11:07:41 POE::Loop::AnyEvent replaces POE's default select() event loop with AnyEvent. This allows POE programs to transparently use most of the event loops AnyEvent can provide. POE::Loop::AnyEvent changes POE's internal implementation without altering its A...BINGOS/POE-Loop-AnyEvent-0.004 - 05 Jun 2013 20:46:23 GMT - Search in distribution VIKAS/App-financeta-0.10 - 08 Sep 2014 17:46:17
https://metacpan.org/search?q=POE-Loop-Prima
CC-MAIN-2016-44
refinedweb
170
51.75
From: Richard Smith (richard_at_[hidden]) Date: 2006-11-18 10:14:34 Tobias Schwinger wrote: > Further: none of the reviewers (except Doug Gregor, who > was talking about the issue in the very specific context > of merger with another library) did answer the following > question: > > What's wrong with the tag types (other than personal > taste) in the first place? Having just read your other email, I think I now better understand why you want tags -- and why you don't want to go the traits route that I suggested. What I don't like about the current interface is that it seems to use an odd mixture of traits and tags. Let me try to explain. The library is supplying an interface to manipulate function types (and function pointer, function reference and member function pointer types). The two most obvious parts of a function type are the return type and the parameter types. These are queried via traits: result_type< Fn >::type mpl::at_c< parameter_types< Fn >, N >::type However, on top of this, there are other aspects: calling convention and variadic-ness (both of which are probably relatively rarely required), and cv-quals for member functions (which might be more frequently needed). These are all handled by the tags mechanism. is_callable_builtin< Fn, variadic >::value (I'm assuming that is_callable_builtin returns true for functions, references, pointers and members.) Finally, there's exactly what sort of function type we're dealing with -- function, reference, pointer or member. These are handled by separate traits: is_function_reference< Fn >::value is_member_function_pointer< Fn >::value That's three (or four if you include the at_c usage to get the nth parameter, but let's not go there again) subtly different interfaces. I'm not concerned about the difference between ::type and ::value -- as I can put ::type in both cases and get a true_type or false_type. But that still leaves two different interfaces, which IMO is one too many. My traits suggestion removed one interface by ditching the tags, but it wasn't the tag interface that I disliked /per se/ -- it was the inconsistency. What if you went the other way and used an exclusively tag-based interface: namespace bft = boost::function_types; bft::get< int (), result_type >::type // int bft::get< int (), parameter_types >::type // an empty MPL sequence bft::get< void (int*, float), parameter_types >::type // an MPL sequence containing (int*, float) bft::get< void (int*, float), parameter_type<0> >::type // int* -- optional syntactic sugar bft::get< void (...), is_variadic >::type // true_type bft::get< void (...), is_variadic >::value // true bft::get< void (), is_default_cc >::type // true_type bft::get< void (*)(), is_pointer >::type // true_type etc... This is not very dissimilar to the existing is_callable_scalar metafunction, but with addition is_pointer, is_reference, etc... tags folded in. > A "reject" vote for a matter of personal taste is pretty > tough, IMO. But sadly it wouldn't surprise me much after > reading some of the material from the GIL review... Hey! I've never said I'm voting to reject ;-) I said in my original review | Although most of my comments are negative, I like this | library, and would like to see it in Boost. I would | prefer to see some modifications made first, but even in | the absense of these, I'd still like to see it added. ... and I still feel this way. Just to avoid any doubt, my vote is to ACCEPT. -- Richard Smith 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/2006/11/113423.php
CC-MAIN-2021-31
refinedweb
578
61.06
Introduction: DIY ARDUINO SKATEBOARD Runner Up in the Wheels Contest 2017 This is our attempt at making a arduino controlled electric skateboard. Step 1: MATERIAL NEEDED For this project we need a brushless motor, a ESC that controlls the motor and capable of handling high currents, several LED´s, Arduino Uno board, two 3S LiPo batteries connected in series (22,2V), cables, and soldering material. First of all, you need to know which motor to buy. In our case we have the Turnigy 245KV which is ideal for us as its a very powerfull motor that can handle our weight. Second of all, we need a controller for the motor. We have a YEP 120A ESC to controll the motor. We also need a power source, which are our 2x 3S Lipo Batteries 5000mAh. This batteries are the most used on DIY electric skateboard projects as they las very long and also produce a large amount of energy which we need for our motor. YEP ESC 120A -... Turnigy 245Kv -... LiPo 3S 5000mAh -... Step 2: LEDS AND BUTTONS CONNECTIONS First of all we are going to try the LED´s of the indicators for our Skate. Each led need a resistor which is connected to one leg of the LED, and the other leg to a pin in the Arduino board. We want 3 LEDS on each side to be activated by a Push Button. We then connect the buttons for each led series. Our buttons are not regular push buttons which means they can only cut or let current pass. So, weve created a Loop which is always doing the same pattern, and when we press our button the leds light up, and when we unpress it, the leds turn off. Were basically cutting the ground port and uncutting it again and again. One leg of the pusbutton goes to the Arduino ground port, and the other leg goes to the PCB connected to all the LEDS. Once we check that everything works, we solder solder each component to a PCB. Step 3: BATTERIES Our batteries need to be connected in series, so for this we create a connection for them. We need to connect the positive of one battery to the negative of the other one. And later, with the extra cables we have at each battery, both of them connected to the positive and negative cables of the ESC. You can try to power up the ESC first with a font if you prefer just to test it out as you dont want be using your batteries 100% of the time when experimenting with arduino. Step 4: ESC CONNECTION AND MOTOR Once we have the batteries connected, we need to connect them to the ESC which also goes to the motor connections. The ESC has 3 cables, Red, Orange and Brown. We need to connect the orange cable to port 9 (or any digital port), and the brown cable to a ground pin. DO NOT connect the center cable. Step 5: 3D PRINTED PARTS Ok, so now we have all the connections settled. We now need to make a support for the motor and also the gears for the wheel. We design the parts in solidworks and later on we send it to our 3D printer to start printing. We have measured our own trucks and wheels which may vary from skate to skate. Our dimensions may not work for everyone. Step 6: THE BUILD With everything in place, we proceed to make the build in the skateboard. We use double sided velcro to fix the batteries, esc and arduino board into place. First we used blue sellotape to adjust everything in place, and later on we used the velcro. Step 7: CODE // PROJECTS 1 ARDUINO PROJECT // // Creators: Mauro Gonzalez & Pere Serrat// #include <Servo.h> //Including the servo library Servo esc; //Including the esc int throttlePin = 0; //Creating the throttlePin variable void setup() { esc.attach(9); //ESC is attached to digital pin 9 // LEDS // //Defining each port for each LED, and putting them as an output pinMode(7, OUTPUT); pinMode(6, OUTPUT); pinMode(5, OUTPUT); pinMode(4, OUTPUT); pinMode(3, OUTPUT); pinMode(2, OUTPUT); } void loop() { // POTENTIOMETER// int sensorValue = analogRead(A0); // Analog pin of the potentiometer into arduino A0 pin Serial.println(sensorValue); //Print us the value int throttle = analogRead(throttlePin); //Giving it the throttle value throttle = map(throttle, 0, 1023, 0, 179); //Mapping the MIN and MAX of the potentiometer with its rotation angle esc.write(throttle); //Giving the ESC the signal of the potentiometer to regulate the power that it provides to the motor // LEDS // digitalWrite(7, HIGH); digitalWrite(4, HIGH); // turn the LED on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(7, LOW); digitalWrite(4, LOW); // turn the LED off by making the voltage LOW delay(30); digitalWrite(6, HIGH); digitalWrite(3, HIGH); // turn the LED on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(6, LOW); digitalWrite(3, LOW);// turn the LED off by making the voltage LOW delay(30); digitalWrite(5, HIGH); digitalWrite(2, HIGH); // turn the LED on (HIGH is the voltage level) delay(100); // wait for a second digitalWrite(5, LOW); digitalWrite(2, LOW); // turn the LED off by making the voltage LOW delay(30); } Recommendations We have a be nice policy. Please be positive and constructive. 6 Comments Sad it didn't make it ti the Top. It was one of the best projects of the Wheels Contest Nice WOOW What an amazing project! OMG I admire u!!!! ; ) Thanks for the feedback OscarO54!! Great build! but can you give links to the materials too? like where you got the esc from etc That looks really cool. You should enter this into the Arduino contest that is running.
http://www.instructables.com/id/DIY-ARDUINO-SKATEBOARD/
CC-MAIN-2018-13
refinedweb
966
68.81
On Aug 8, 12:13 pm, Luis Alberto Zarrabeitia Gomez <ky... at uh.cu> wrote: > Quoting Robert Dailey <rcdai... at gmail.com>: > > > Hey, > > > I have a class that I want to have a different base class depending on > > a parameter that I pass to its __init__method. For example > > (pseudocode): > > 1- Are you sure that you want that behavior? Given that in python, a class is > just a particular case of invocable object, you could just write a function > instead, and the code may be more robust. > > 2- If you are /sure/ that is the behavior you want, take a look at the __new__ > method. The __new__ can decide which instance to return (you could even define a > new class inside of it, instantiate it, and return the instance). > > 3- You may want to take a look at metaclasses. But without more details about > why you want it, I can't give you more precise answers. One could accomplish this using methods 2 and 3, but it would go against so many common expectations I have to recommend never doing it. If you call a type, it should return an object of that type (or, at worst, a subtype or "null" type) or raise an exception. The factory function is the way to do this. Another alternative is to forego inheritance and simply call method on the passed "base" object. Given that the OP posted code that almost literally works in that case, this might be the best way to go for his case. So instead of this hypothetical code: class MyDerived(self.base): def __init__(self,base) self.base = base # MyDerived inherits a_method() from self.base He could go with this real code: class MyClass(object): def __init__(self,base) self.base = base def a_method(self): return self.base.a_method() where, instead of inheriting self.base's a_method, it simply defines a_method() to call self.base.a_method() directly. Carl Banks
https://mail.python.org/pipermail/python-list/2009-August/547101.html
CC-MAIN-2016-44
refinedweb
320
73.98
This proposal seeks to add language support for move semantics to C++. This. This proposal has the potential to introduce a fundamental new concept into the C++ language. And yet the concept is not new to C++ programmers. Move semantics in various forms has been discussed in C++ forums (most notably comp.lang.c++.moderated) for years. However sweeping, this proposal seeks to minimize changes to the existing language. An additional goal of this proposal is to not break any existing (working) C++ program. This proposal has also been designed to be 100% compatible with "perfect forwarding" as presented in N1385=020043. That is, the language changes proposed herein solve both move semantics and the forwarding problem. Move semantics is mostly about performance optimization: the ability to move an expensive object from one address in memory to another, while pilfering resources of the source in order to construct the target with minimum expense. Move semantics already exists in the current language and library to a certain extent: All of these operations involve transferring resources from one object (location) to another (at least conceptually). What is lacking is uniform syntax and semantics to enable generic code to move arbitrary objects (just as generic code today can copy arbitrary objects). There are several places in the standard library that would greatly benefit from the ability to move objects instead of copy them (to be discussed in depth below). C and C++ are built on copy semantics. This is a Good Thing. Move semantics is not an attempt to supplant copy semantics, nor undermine it in any way. Rather this proposal seeks to augment copy semantics. A general user defined class might be both copyable and movable, one or the other, PODs, move and copy are identical operations (right down to the machine instruction level). Why can not move semantics be a pure library proposal? Can't we just adopt a convention in the library that means move? This almost works. But it falls flat in two very important cases: To help solve these problems, this paper proposes the introduction of a new type of reference that will bind to an rvalue: struct A {/*...*/}; void foo(A&& i); The '&&' is the token which identifies the reference as an "rvalue reference" (bindable to an rvalue) and distinguishes it from our current reference syntax. Bjarne in his excellent text "The Design and Evolution of C++" discusses the motivation for prohibiting the binding of an rvalue to a non-const reference in section 3.7. The following example is shown: void incr(int& rr) {rr++;} void g() { double ss = 1; incr(ss); } ss is not incremented, as a temporary int must be created to pass to incr(). The authors want to say right up front that we agree with this analysis 100%. Howard was even bitten by this "bug" once with an early compiler. It took him forever to track down what was going on (in that case it was an implicit conversion from float to double that created the temporary). Having said that, we would like to add: You don't ever want to bind a temporary to a non-const reference ... except when you do. A non-const reference is not always intended to be an "out" parameter. Consider: template <class T> class auto_ptr { public: auto_ptr(auto_ptr& a); ... }; The "copy" constructor takes a non-const reference named "a". But the modification of "a" is not the primary goal of this function. The primary goal is to construct a new auto_ptr by pilfering "a". If "a" happens to refer to an rvalue, this is not a logical error! This is what the A&& (rvalue reference) is about. Sometimes you really do want to allow a temporary to bind to a non-const reference. The new reference type introduces syntax for allowing that functionality without changing the meaning of any existing code. Thus auto_ptr can be reformulated without auto_ptr_ref. However, the rvalue reference and move semantics are about a lot more than just auto_ptr. The auto_ptr class is used here just to establish a common point of reference. The rvalue reference is a new type, distinct from the current (lvalue) reference. Functions can be overloaded on A& and A&&, requiring such functions to have distinct signatures. The most common overload set anticipated is: void foo(const A& t); // #1 void foo(A&& t); // #2 The rules for overload resolution are (in addition to the current rules): rvalues will prefer rvalue references. lvalues will. Even though named rvalue references can bind to an rvalue, they are treated as lvalues when used. For example: struct A {}; void h(const A&); void h(A&&); void g(const A&); void g(A&&); void f(A&& a) { g(a); // calls g(const A&) h(a); // calls h(const A&) } Although an rvalue can bind to the "a" parameter of f(), once bound, a is now treated as an lvalue. In particular, calls to the overloaded functions g() and h() resolve to the const A& (lvalue) overloads. Treating "a" as an rvalue within f would lead to error prone code: First the "move version" of g() would be called, which would likely pilfer "a", and then the pilfered "a" would be sent to the move overload of h(). In a sense, the rvalue reference is already used in C++ when dealing with the implicit object parameter as discussed in section 13.3 (Overload resolution). A temporary is allowed to bind to the implicit object parameter which is said to be of type "reference to cv X" (see 13.3.1/4). Introduction of the "rvalue reference" allows for the exception relating to temporaries and the implicit object parameter to be removed from the language (section 13.3.3.1.4 / 3). Instead, the implicit object parameter can simply be of type cv X&&. Remember: you really do not want to bind a temporary to a non-const reference ... except when you do! An auto_ptr-like class can be introduced (lets call it move_ptr) which is movable, but not copyable. Client code might look like: template <class T> move_ptr<T> source(); ... move_ptr<int> p(new int(1)); move_ptr<int> q = source<int>(); p = source<int>(); The move_ptr class is constructible and assignable from rvalues. However, one can not copy construct nor assign from lvalues of move_ptr. The following client code will generate compile time errors: move_ptr<int> r = p; // error: can't copy from lvalue p = q; // error: can't assign from lvalue The refusal to move from lvalues using copy syntax is key to the safety of move_ptr. Later it will be shown that move_ptr can be safely put into a move-aware container such as vector or map with no chance of accidental transfer of ownership into or out of the container. The move_ptr has an accessible constructor and assignment taking non-const rvalues, but traditional copy semantics has been disabled by making the copy constructor and copy assignment private: template<class X> class move_ptr { public: typedef X value_type; explicit move_ptr(X* p = 0) throw() : ptr_(p) {} move_ptr(move_ptr&& a) throw() : ptr_(a.release()) {} template<class Y> move_ptr(move_ptr<Y>&& a) throw() : ptr_(a.release()) {} ~move_ptr() throw() {delete ptr_;} move_ptr& operator=(move_ptr&& a) throw() {reset(a.release()); return *this;} template<class Y> move_ptr& operator=(move_ptr<Y>&& a) throw() {reset(a.release()); return *this;} X& operator*() const throw() {return *ptr_;} X* operator->() const throw() {return ptr_;} X* get() const throw() {return ptr_;} X* release() throw() {X* tmp = ptr_; ptr_ = 0; return tmp;} void reset(X* p = 0) throw() {if (ptr_ != p) {delete ptr_; ptr_ = p;}} private: X* ptr_; move_ptr(const move_ptr& a); template<class Y> move_ptr(const move_ptr<Y>& a); move_ptr& operator=(const move_ptr& a); template<class Y> move_ptr& operator=(const move_ptr<Y>& a); }; The move constructor is not a special member. It is like any other constructor and not like the copy constructor in this regard. Introduction of a move constructor does not supplant the copy constructor, or inhibit the implicit definition of a copy constructor. The move constructor overloads the copy constructor, whether the copy constructor is implicit or not. Similarly for the move assignment. Move constructors and move assignment are also not implicitly defined by the compiler should the class author not include them. Thus no current C++ classes are movable. The class author must explicitly provide move semantics for his class. So far so good. The combination of the const A& and the A&& makes it easy for the everyday class designer to put copy semantics and/or move semantics into his class. Move semantics will automatically come into play when given rvalue arguments. This is perfectly safe because moving resources from an rvalue can not be noticed by the rest of the program (nobody else has a reference to the rvalue in order to detect a difference). The client of a movable object might decide that he wants to move from an object even though that object is an lvalue. There are many situations when such a need might arise. One common example is when you have a full dynamic array of objects and you want to add to it. You must allocate a larger array and move the objects from the old buffer to the new. The objects in the array are obviously not rvalues. And yet there is no reason to copy them to the new array if moving can be accomplished much faster. Thus this paper proposes the ability to cast from an lvalue type T to an rvalue: move_ptr<int> p, q; ... p = static_cast<move_ptr<int>&&>(q); // ok The right hand side is considered to be an rvalue after the cast. Thus the move_ptr assignment works via the move assignment operator. Note that this amounts to a request to move, not a demand to move. Had move_ptr been a class that supported copy assignment, but not move assignment, the above assignment from q to p would still have worked since you can always assign from an rvalue using a copy assignment (unless the type explicitly forbids copy semantics like move_ptr). The "request to move" semantics turn out to be very handy in generic code. One can request that a type move itself without having to know whether or not the type is really movable. If the type is movable it will move, else if the type is copyable, it will copy, else you will get a compile-time error. A classic example of where this could come in handy is swap: template <class T> void swap(T& a, T& b) { T tmp(static_cast<T&&>(a)); a = static_cast<T&&>(b); b = static_cast<T&&>(tmp); } If T is movable, then move construction and move assignment will be used to perform the swap. If T is not movable, but is copyable, then copy semantics will handily perform the swap. Otherwise the swap function will fail at compile time. Swapping using move semantics (when available) can produce code that is as efficient, or nearly as efficient (constant complexity) as a custom swap. The static_cast<A&&> syntax is admittedly ugly. This is not necessarily a bad thing as you want to clearly call out when you are doing something as dangerous (and useful!) as moving from an lvalue. But the cast can become so ugly as to be unreadable when the type A is a long complicated identifier. Earlier this paper proposed that: Named rvalue references are treated as lvalues. This thought will now be completed: Unnamed rvalue references are treated as rvalues. An example of an unnamed rvalue reference would be returning such a type from a function. Consider: template <class T> inline T&& move(T&& x) { return static_cast<T&&>(x); } Now calling move(x) is a synonym for casting x to an rvalue. Thus swap can be made more readable: template <class T> void swap(T& a, T& b) { T tmp(move(a)); a = move(b); b = move(tmp); } Treating unnamed rvalue references as rvalues is consistent, at least syntactically with treating the result of static_cast<A&&> as an rvalue. This behavior is also beneficial (performance wise) to the string+string example shown later. Here are several examples that serve to summarize the binding rules in one place: struct A {}; void foo(const A&); // #1 void foo(A&&); // #2 A source_rvalue(); A& source_ref(); A&& source_rvalue_ref(); const A source_const_rvalue(); const A& source_const_ref(); const A&& source_const_rvalue_ref(); int main() { A a; A& ra = a; A&& rra = a; const A ca; const A& rca = ca; const A&& rrca = ca; foo(a); // #1 foo(ra); // #1 foo(rra); // #1 foo(ca); // #1 foo(rca); // #1 foo(rrca); // #1 foo(source_rvalue()); // #2 foo(source_ref()); // #1 foo(source_rvalue_ref()); // #2 foo(source_const_rvalue()); // #1 foo(source_const_ref()); // #1 foo(source_const_rvalue_ref()); // #1 } lvalues, both const and non-const bind to foo(const A&). Named references, both lvalue and rvalue, all bind to foo(const A&). Non-const rvalues and unnamed rvalue references bind to foo(A&&). Const rvalues and const rvalue references bind to foo(const A&). Had there been a foo(const A&&) available, they would have bound to that. The lvalue references bind to foo(const A&). Like any other class, std::basic_string can be given both move and copy constructors, and move and copy assignment, just as previously discussed. For example: class string { public: // copy semantics string(const string& s) : data_(new char[s.size_]), size_(s.size_) {memcpy(data_, s.data_, size_);} string& operator=(const string& s) {if (this != &s) { if (size_ < s.size_) // get sufficient data buffer size_ = s.size_; memcpy(data_, s.data_, size_); } return *this;} // move semantics string(string&& s) : data_(s.data_), size_(s.size_) {s.data_ = 0; s.size_ = 0;} string& operator=(string&& s) {swap(s); return *this;} // ... private: char* data_; size_t size_; // ... }; The move constructor and move assignment will be automatically called when given rvalues, and client code can explicitly cast to rvalue if moving from an lvalue is desired. So far so good. But there is more fun to be had. Consider: string s1("12345678901234567890"); string s0 = s1 + "a" + "b" + "cd"; Even with NRVO implemented in operator+(string, string), and even with a short string optimization (holding say less than 20 characters), the expression to form s0 will typically allocate memory at least once per operator+() for a total of 3 accesses to the heap. The reason is that operator+(string, string) will typically look something like: string operator+(const string& x, const string& y) { string result; result.reserve(x.size() + y.size()); result = x; result += y; return result; } For each +operation, a new string is created with sufficient capacity for the result and that is returned. With move semantics the expression for s0 can be much more efficient, going to the heap only once (or maybe twice depending on some string implementation details). This is made possible by overloading operator+ for rvalues as one or both of the arguments. If one of the arguments is an rvalue, it is much more efficient to simply append to the rvalue, rather than make a whole new string. It is quite possible that the existing capacity in the rvalue is already sufficient so that the append operation need not go to the heap at all. string&& operator+(string&& x, const string& y) { return x += y; } string&& operator+(const string& x, string&& y) { return y.insert(0, x); } string&& operator+(string&& x, string&& y) { return x += y; } Note that an rvalue reference to the rvalue argument can be returned. This is further motivation for the rule that unnamed rvalue references are treated as rvalues. The return type of string+string must be regarded as an rvalue. The rvalue overloads of string+string could return by value, but this would not be as efficient as returning by reference, even with a move constructor helping out. This proposal has been partially implemented in Metrowerks CodeWarrior, and indeed, the code to form s0 above only goes to the heap once during s1 + "a". The temporary created in that first operation happens to have sufficient capacity for the next two concatenations. If NRVO is not operational, move semantics further aids by move constructing s0 from the rvalue generated by the expression. A further language refinement can be made at this point. When returning a non-cv-qualified object with automatic storage from a function, there should be an implicit cast to rvalue: string operator+(const string& x, const string& y) { string result; result.reserve(x.size() + y.size()); result = x; result += y; return result; // as if return static_cast<string&&>(result); } The logic resulting from this implicit cast results in an automatic hierarchy of "move semantics" from best to worst: With this language feature in place, move/copy elision, although still important, is no longer critical. There are some functions where NRVO is allowed, but can be exceedingly difficult to implement. For example: A f(bool b) { A a1, a2; // ... return b ? a1 : a2; } It is somewhere between difficult and impossible to decide whether to construct a1 or a2 in the caller's preferred location. Using A's move constructor (instead of copy constructor) to send a1 or a2 back to the caller is the best solution. We could require that the author of operator+ explicitly request the move semantics. But what would be the point? The current language already allows for the elision of this copy, so the coder already can not rely on destruction order of the local, nor can he rely on the copy constructor being called. The auto-local is about to be conceptually destructed anyway, so it is very "rvalue-like". The move is not detectable except by measuring performance, or counting copies (which may be elided anyway). Note that this language addition permits movable, but non-copyable objects (such as move_ptr) to be returned by value, since a move constructor is found and used (or elided) instead of the inaccessible copy constructor. As discussed in Core Defect 106, and in the forwarding proposal, it is important to consider what happens when references to references are formed. To summarize from N1385=020043, the reference collapsing rules are: (cv qualifications are unioned as discussed in cw 106 and N1385=020043). This behavior is not only critical for perfect forwarding, but for move as well. Consider for example a container such as boost::compressed_pair that is able to hold references. The move constructor for such an object will look like: compressed_pair<T1, T2>::compressed_pair(compressed_pair&& x) : first_ (static_cast<T1&&>(x.first_)), second_(static_cast<T2&&>(x.second_)) {} That is, each data member from the source will be cast to rvalue in order to invoke the move constructor for the target data member. But what if T1 is a reference: A& ? The static_cast<T1&&> is casting a reference type to an rvalue. The result can not be an rvalue, or it would not bind to first_, which is itself a reference. (rvalues can not bind to non-const references). But expanding out the types manually (static_cast<A& &&>(), and using the reference collapsing rules, the expression simplifies to static_cast<A&>. That is, when T1 is a reference type, the call behaves in a copy-like manner, and when T1 is not a reference type, the call behaves in move-like manner. Exactly what is needed! This final language proposal is not strictly needed for move, but it is needed for perfect forwarding. It is briefly summarized here for completeness, and to assure the gentle reader that this behavior is 100% compatible with this move proposal. When deducing a function template type using an lvalue argument matching to an rvalue reference, the type is deduced as an lvalue reference type. When deduction is given an rvalue argument, type deduction proceeds just as with other types. For example: template <typename T> void f(T&& t); ... struct A {}; void g() { f(A()); // calls f<A>(A&& t) A a; f(a); // calls f<A&>(A& && t) -> f<A&>(A& t) } This behavior is key to "perfect forwarding". A forwarding function can exactly replicate both the cv qualifiers and the l/r-valueness of the argument it receives so that the forwarded-to function sees the exact same argument. With these few basic (but closely related) language tools, this proposal has already shown significant potential enhancements to both the standard library, and to code in general: The above summary is all that this proposal asks for. We believe that these potential benefits alone should justify this incremental (and fully backwards compatible) change in the language. But these benefits are just the tip of the iceberg. The remainder of the proposal consists of further motivation, clarifications, and alternative designs (for move). Like <string>, <vector> can be made movable by implementing a move constructor and move assignment. But as vector is a container for a general type T, significant optimizations can take place if T itself is movable (string doesn't have this issue because its value_type is assumed to be a POD). For pods moving and copying are the same thing. The most significant impact move has (or can have) on vector is in the implementation of its erase and insert functions. During a vector::insert one of two things can happen: In either case, if T can be moved instead of copied, the performance benefits are clear. Consider vector<string>. In the sufficient capacity case if copy semantics are used, then every string assignment or copy construction to move the existing elements out of the way is at the very least going to be doing a memcpy for each string's data buffer. And the worst case is that each of those copies will also involve a buffer reallocation as well (those strings constructed past the current capacity will definitely require a buffer allocation). Thus just the act of scooting strings down to make a hole in the middle of the vector for the new strings can be a significant expense. But if the vector moves the existing strings to make room for the newly inserted strings, then there are no memcpy's of the string's data buffer. There are no buffer allocations, not even for the strings which are moved beyond the current capacity. The expense of making the "hole" is approximately the same as if you just had a vector<POD> with sizeof(POD) being somewhere between one and two times as big as sizeof(string) (not string::size()!). In the insufficient capacity case, a new buffer is allocated. If copy semantics are used, then copies of the elements are then created in the new buffer, with each copy requiring a data buffer allocation and a memcpy of the data, then a deallocation of the old data buffer. If move semantics are used, each move is a simple pointer transfer. Not only is this much faster, it uses half the memory as there is no point during the process where each element has a duplicate data buffer. Move semantics has been partially implemented in the Metrowerks CodeWarrior compiler, and in the accompanying std::vector and std::string. The std::string used is based on the short string optimization, but the strings used in the following experiments are beyond the short string limit: #include <vector> #include <string> #include "Timer.h" int main() { std::string s(20, ' '); std::vector<std::string> v(10, s); Timer t("insert"); v.insert(v.begin(), s); } The insert function is 60% faster with move semantics in this example. Raising the vector size to 100 increases the advantage of move semantics to 3 times. And an initial vector size of 1000 results in the insert function with move semantics performing at 9 times the speed of the copy semantics version. Essentially, the move semantics is changing the complexity of the insert and erase functions of vector<string> from an O(N*M) process to an O(N) process. The more expensive it is to copy the vector's element, or the more elements there are, the greater the advantage of move semantics over copy semantics. Thus arbitrarily impressive examples can be built: #include <vector> #include <string> #include "Timer.h" int main() { std::string s(1000, ' '); std::vector<std::string> v(1000, s); Timer t("insert"); v.insert(v.begin(), s); } This example runs nearly 80 times faster with move semantics turned on. Similar results are observed with vector<string>::erase. Similar results are also observed with vector<vector<int> >. Note that client code using vector<string> can remain blissfully ignorant of move semantics. The only thing they will notice is that the vector<string> performance is rather snappy! vector's interface can also be augmented with move semantics (beyond the move constructor and assignment). Any member function taking a single const T& to be inserted into the vector can also take a T&& which will be move constructed into the vector. Such a function will be called automatically if the argument is an rvalue, or client code can explicitly request the move into the vector via the cast to rvalue. template <typename T, class Allocator = allocator<T> > class vector { ... vector(vector&& x); vector& operator=(vector&& x) void push_back(value_type&& x); iterator insert(iterator position, value_type&& x); void swap(vector&& x); ... } With such a vector that is not only movable, but fully move aware, one can construct vector<move_ptr<T> > (see earlier move_ptr description). Here is a vector of smart pointers that has behavior much like vector<auto_ptr<T> > but is safe. The overhead of move_ptr is the same as auto_ptr, and the semantics of only the vector owning the pointers is preserved. No move_ptr can accidentally transfer ownership out of the vector! Client code would have to explicitly request such a transfer: vector<move_ptr<T> > v; v.push_back(move_ptr<T>(new T)); // ok move_ptr<T> p; v[0] = p; // error! can't assign from lvalue v[0] = move_ptr<T>(); // ok move_ptr<T> tmp = v[0]; // error! can't copy move_ptr move_ptr<T> tmp = move(v[0]); // ok v.insert(v.begin(), move_ptr<T>(new T)); // ok The vector will use move_ptr's move semantics internally when scooting elements around, so the vector's integrity is preserved while inserting and erasing elements. Such a vector will not be copyable nor assignable: a compile-time error will result if attempted. But the vector is otherwise fully functional. And the vector is move constructible and move assignable. Thus, ownership of the raw pointer is secure, well defined, well documented in the code, and has the absolute minimum overhead (stores just the pointer itself). Two helper algorithms analogous to std::copy and std::copy_backward can be created: template <class InputIterator, class OutputIterator> OutputIterator move(InputIterator first, InputIterator last, OutputIterator result) { for (; first != last; ++first, ++result) *result = move(*first); return result; } template <class BidirectionalIterator1, class BidirectionalIterator2> BidirectionalIterator2 move_backward(BidirectionalIterator1 first, BidirectionalIterator1 last, BidirectionalIterator2 result) { while (last != first) *--result = move(*--last); return result; } These algorithms could be specialized to use memcpy, memmove when dealing with pointers to pods (just like copy and copy_backward). The vast performance optimizations provided by move semantics are available to non-node-based containers such as vector and deque. It will also be implemented in the Metrowerks extension container cdeque which is a circular buffer. Node based containers have no need to move elements around internally, thus move semantics are not required. However, even node based containers can benefit in their interface by offering move constructors and move assignment to make the container itself movable. This would make (for example) vector<list<T> > very efficient. And node based containers can also benefit by providing move overloads of push_front/back and insert so that heavy weight and/or non-copyable elements can be moved into the container instead of copied into the container. Several of the std::algorithms can benefit from move semantics. For example those algorithms that benefit from temporary buffers (stable_partition, stable_sort, inplace_merge) can use move construction to move elements into the temporary buffer, and move assignment to move the elements back into the original range. For vector<T> to use T's move semantics without changing its exception guarantees, T's move constructor, if it exists, must have the nothrow guarantee. This fact must be documented as part of the container's interface, similar to 17.4.3.6, paragraph 2 which documents that destructors in client code may not throw exceptions without causing undefined behavior. Consider vector<T>::reserve(size_type), which must have no effect if an exception is thrown (strong guarantee). When the new size exceeds the current capacity(), elements in the old data buffer must be moved to the new data buffer. Once a single element is moved from the old buffer to the new, the original vector is modified. If an exception is thrown while moving the second element of the vector, neither the old buffer nor the new one can be used to represent the vector's original state, and an exception might equally well be thrown while trying to restore the original buffer. Thus, move constructors used with the standard library must not throw exceptions. Almost any class should be able to create a nothrow move assignment operator. Often this can be simply and efficiently implemented as a swap. However, a nothrow move constructor can be problematic for some classes. In order to have a nothrow move constructor a class must have a valid resourceless state. If the type T has no valid resourceless state, then during a move construction a resource must be obtained to leave in the source after it has transferred all of its resources to the target. If the acquisition of that resource could fail, then the move constructor might throw, and thus could not be put into a container such as vector. For example, consider a simple string class with no reference counting and no short string optimization. An invariant of this simple string class is that it always has at least a one character data buffer allocated from the heap so that it can store the terminating null. Even this class's default constructor allocates memory for the terminating null. Such a class would not be capable of a nothrow move constructor. Once the data buffer was transferred from source to target, the source would have to acquire a new buffer to hold its terminating null. The solution for such a class is to simply not define move semantics for it. It can still have valid copy semantics, and can still be put into a move-aware vector. It just won't be as efficient as a movable string class. It will only be as efficient as our current (move-ignorant) vector<string>. Note that this simple string is just an example. Obviously it could be made movable by implementing the short string optimization for at least the terminating null (or by several other methods of preallocating resources, e.g. pointing to statically allocated "null buffer"). Other classes may or may not have alternative designs that can be made movable. Move semantics as defined above works well with class hierarchies. A derived class's move constructor need only trigger the base class's move constructor by casting the appropriate data to rvalue when initializing the base class: struct Base { Base(Base&& b); }; struct Derived : Base { Derived(Derived&& d) : Base(move(d)) {} }; Base classes are moved from source to target first. This leaves derived sources temporarily in a state where the derived part of the source may have resources while the base part of the source does not. But as the base must have a valid resourceless state anyway, this does not pose any difficulty. On the target side, resources will be added first in the base, and then in the derived parts, just as in a normal copy construction. Significant effort was put into designing move semantics that did not require any language changes. One of the most promising proposals (by John Maddock) involved setting up a tag type that would store a reference to an object (much like auto_ptr_ref): template <class T> class move_t { const T& t; public: move_t(const T& a) : t(a) {} operator T&(){ return t; } }; A move constructor (for example) for some class A could then be written as taking a move_t<A>. A helper function named move would create a move_t<A> and wrap move's argument in it. This did almost everything that was necessary. The only thing we were not able to do with this approach was to allow moving from rvalues while disallowing moving from const. It also did not "automatically" move from rvalues which is a really nice feature of the current proposal. This allows completely safe move semantics to come into client code with absolutely no code changes for the client (e.g. the string+string examples). There is significant desire among C++ programmers for what we call destructive move semantics. This is similar to that outlined above, but the source object is left destructed instead of in a valid constructed state. The biggest advantage of a destructive move constructor is that one can program such an operation for a class that does not have a valid resourceless state. For example, the simple string class that always holds at least a one character buffer could have a destructive move constructor. One simply transfers the pointer to the data buffer to the new object and declares the source destructed. This has an initial appeal both in simplicity and efficiency. The simplicity appeal is short lived however. When dealing with class hierarchies, destructive move semantics becomes problematic. If you move the base first, then the source has a constructed derived part and a destructed base part. If you move the derived part first then the target has a constructed derived part and a not-yet-constructed base part. Neither option seems viable. Several solutions to this dilemma have been explored. One possible solution is to define a lame duck state for an object in mid-move: A lame duck object is an object that you can reference data members, but not base objects, nor member functions whether derived or not. As soon as any member of an object (base or direct member) is moved, then that object is a lame duck. Violating the access rules of a lame duck object results in undefined behavior (no diagnostic required). The complications become significant. The potential for misuse is very real, with little hope for the compiler being able to guard against the misuse. The cost just looks too high. Another solution is to just declare that an object can not have a destructive move constructor unless all of its base classes and members have a non-destructive move constructor. Thus the destructive move constructor can non-destructively move construct the bases and members before destructively move constructing itself. This solves the hierarchy problem, at least for a restricted set of classes. But more dangers arise. Using a destructive move construct must be done with the same care as using explicit destructor call. One can not destructively move an auto object, nor a static object. Only objects with dynamic storage duration can be destructively moved. And the syntax for these semantics would likely require more language support, perhaps a destructor with a void* argument for example. In the end, we simply gave up on this as too much pain for not enough gain. However the current proposal does not prohibit destructive move semantics in the future. It could be done in addition to the non-destructive move semantics outlined in this proposal should someone wish to carry that torch. Howard was initially convinced that compile time detection of whether or not a type supported move semantics would be absolutely necessary in order to build a move aware container such as vector (while remaining exception safe). Somehow the container would have to decide whether to use move semantics or copy semantics on the type. David Abrahams suggested that algorithms use the "move if you have it, else copy" pattern. At the time Howard argued that the structure of algorithms using move, and those using copy would not necessarily be the same. Thus fundamentally different algorithms needed to be called. And to do this, move detection was necessary. In the end Howard found it easier to rework vector::insert and vector::push_back so that the copy and move versions of the algorithm were structurally similar, rather than invent move detection! Dave, you got the last word! :-) That is not to say that move detection would not be useful, we're sure it would be. But it is not proposed here in the interest of minimizing required language changes. A general purpose compile-time class introspection facility would be most interesting, but is a separate issue. This proposal is the result of the work of many people over an extended period of time. We did not sit down by ourselves one day and "invent" move semantics. Andrew Koenig first got Howard interested in move semantics, although he had been reading about the concept in the newsgroups for a couple of years by then. Andy was also the first one to point out how swap could use move. Others, both on the std::reflectors and on boost have been immensely helpful in discussions about move semantics, including Greg Colvin, Rainer Deyke, Dave Harris, Hamish Mackenzie, John Maddock and Sean Parent. Special thanks to the EDG team: Stephen Adamczyk, John Spicer and Daveed Vandevoorde. It was John who suggested the A&& syntax. And finally, this proposal could not have gotten off the ground (with a prototype implementation and running code examples) without the generous help of the senior compiler engineer at Metrowerks: Andreas Hommel. Everyone should be so lucky as to have an Andreas to work with!
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2002/n1377.htm
crawl-001
refinedweb
6,277
53.1
Is it possible to convert a selection to proper case? i.e. First letters of each word to uppercase? Thanks! If you get the PowerUser plugin then it is by default the binding I have for it is alt+k,t but u can change it to whatever you want. Edit the *Default.sublime-keymap *file in the PowerUser folder If you don't feel like downloading the whole plugin and use all of its goodies then here's the code for that command only) Awesome, thanks a lot! That was the only thing keeping me from using Sublime Text. On more quick question. I'm new with Sublime, so forgive my stupid questions. You have the default keymap as alt+k,t...how does that translate into what I press? Alt k, then release and press t or something different. I can't seem to figure that side of things out.!! Your welcome I was lazy, I just added this class in Packages/Default/Transform.py class CapitalizeCaseCommand (sublimeplugin.TextCommand): def run (self, view, args): transformSelectionText (string.capwords, view)
https://forum.sublimetext.com/t/proper-case/615
CC-MAIN-2016-22
refinedweb
180
77.33
On Mon, Mar 06, 2006 at 12:36:01PM -0800, Ashley Yakeley wrote: > 3. Making Functor and Foldable superclasses of Traversable, and getting > rid of fmapDefault and foldMapDefault. If you have the superclasses, the defaults are more useful, for people who only want to define Traversable. > You might also consider: > > 4. Adding a method to "class Traversable t" (with a default implementation): > > toList :: t a -> [a] It's in Data.Foldable, but as a function, not a method: toList :: Foldable t => t a -> [a] #ifdef __GLASGOW_HASKELL__ toList t = build (\ c n -> foldr c n t) #else toList = foldr (:) [] #endif > 5. Renaming pure as returnA and <*> as apA. Only it looks like your > Arrows stole returnA. I rather like <*>, which comes from Doaitse Swierstra's parsing combinators. > If Functor is a superclass of Traversable, is it better to have traverse > and mapM as the methods, or sequence and sequenceA? sequence(A) would be the categorical way, but it's often more efficient to define traverse/mapM, particularly for non-regular types. > What's your "instance Applicative []"? Does it use repeat and zapp, or > is it the "list of successes" (which would be compatible with "instance > Monad []")? It matches the monad instance. There's a newtype ZipList for the other one.
http://www.haskell.org/pipermail/libraries/2006-March/005022.html
CC-MAIN-2014-23
refinedweb
209
66.54
Represent images of one or more planes of Ts. More... #include "vil3d_image_view.h" #include <vcl_cstring.h> #include <vcl_string.h> #include <vcl_cassert.h> #include <vcl_ostream.h> #include <vcl_algorithm.h> #include <vil/vil_pixel_format.h> Go to the source code of this file. Represent images of one or more planes of Ts. Note: To keep down size of vil3d_image_view Please think carefully before adding any new methods. In particular any methods that provide new views (e.g. vil3d_slice) will be more usefully provided as external functions. - IMS. In that case, use the "relates" keyword of Doxygen to link the documentation of that function to the vil3d_image_view class. Definition in file vil3d_image_view.txx. VCL_DEFINE_SPECIALIZATION vcl_string vil3d_image_view<T >::is_a() const \ { return vcl_string("vil3d_image_view<" #T ">"); } \ template class vil3d_image_view<T >; \ template bool vil3d_image_view_deep_equality(const vil3d_image_view<T >&, \ const vil3d_image_view<T >&) Definition at line 380 of file vil3d_image_view.txx. Definition at line 3 of file vil3d_image_view.txx. True if the actual images are identical. The data may be formatted differently in each memory chunk. O(size). Definition at line 362 of file vil3d_image_view.txx.
http://public.kitware.com/vxl/doc/release/contrib/mul/vil3d/html/vil3d__image__view_8txx.html
crawl-003
refinedweb
175
63.15
Problem Statement. Issues that Need to be Addressed in this Rework One: OperatorPlan has far too many operations. It has 29 public methods. This needs to be paired down to a minimal set of operators that are well defined. Two: Currently, relational operators (Join, Sort, etc.) and expression operators (add, equals, etc.) are both LogicalOperators. Operators such as Cogroup that contain expressions have OperatorPlans that contain these expressions. This was done for two reasons: - To make it easier for visitors to visit both types of operators (that is, visitors didn't have to have separate logic to handle expressions). - To better handle the ambiguous nature of inner plans in Foreach. However, it has led to visitors and graphs that are hard to understand. Both of the above concerns can be handled while breaking this binding so that relational and expression operators are separate types. Three: Related to the issue of relational and expression operators sharing a type is that inner plans have connections to outer plans. Take for example a script like A = load 'file1' as (x, y); B = load 'file2' as (u, v); C = cogroup A by x, B by u D = filter C by A.x > 0; In this case the cogroup will have two inner plans, one of which will be a project of A.x and the other a project B.u. The !LOProject objects representing these projections will hold actual references to the !LOLoad operators for A and B. This makes disconnecting and rearranging nodes in the plan much more difficult. Consider if the optimizer wants to move the filter in D above C. Now it has to not only change connections in the outer plan between load, cogroup, and filter; it also has to change connections in the first inner plan of C, because this now needs to point to the !LOFilter for D rather than the !LOLoad for A. Four: The work done on Operator and OperatorPlan to support the original rules for the optimizer had two main problems: - The set of primitives chosen were not the correct ones. - The operations chosen were put on the generic super classes (Operator) rather than further down on the specific classes that would know how to implement them. Five: At a number of points efforts were made to keep the logical plan close to the physical plan. For example, !LOProject represents all of the same operations that !POProject does. While this is convenient in translation, it is not convenient when trying to optimize the plan. The LogicalPlan needs to focus on representing the logic of the script in a way that is easy for semantic checkers (such as TypeChecker) and the optimizer to work with. Six: The rule of one operation per operator was violated. !LOProject handles three separate roles (converting from a relational to an expression operator, actually projecting, and converting from an expression to a relational operator). This makes coding much more complex for the optimizer because when it encounters an !LOProject it must first determine which of these three roles it is playing before it can understand how to work with it. The following proposal will address all of these issues. Proposed Methodology Fixing these issues will require extensive changes, including a complete rewrite of Operator, OperatorPlan, PlanVisitor, LogicalOperator, LogicalPlan, LogicalPlanVisitor, every current subclass of LogicalOperator, and all existing optimizer rules. It will also require extensive changes, though not complete rewrites, in existing subclasses of LogicalTransformer. To avoid destabilizing the entire codebase during this operation, this will be done in a new set of packages as a totally separate set of classes. Linkage code will be written to translate the current LogicalPlan to the new experimental LogicalPlan class. A new LogicalToPhysicalTranslator will also be written to translate this new LogicalPlan to a PhysicalPlan. This code path will only be taken if some type of command line switch or property is set, thus insulating current developers and users from this work. This has the added advantage that it is easy to build a prototype first. Given that our first implementation now needs rewriting, prototyping first will help us explore whether we solved the problem correctly this time. The Actual Proposal Changes to Plans In general, the top level plan classes will be changing in a couple of important ways: One, they will be made much simpler. The goal will be to find a minimal set of operations that will enable all desired plan features. Two, they will no longer be generics. While nice in theory, this led to several observed issues. One, each class had so many parameters that in practice developers have worked around rather than used the features of the generics. That is, parameterizing the classes seemed to get in developers way, rather than help them. Two, since we propose to break relational and expression operators into different types, it will no longer be possible for a single visitor to span both types. But we do not wish to prohibit this in all cases. In the following code major members and methods of each class are shown. Getters and setters are not shown unless they include functionality beyond simply getting and setting a value. New Operator class. Note that the function which was previously called visit has been renamed accept to avoid confusion with the visit method in PlanVisitor. package org.apache.pig.experimental.plan; public abstract class Operator { protected String name; protected OperatorPlan plan; // plan that contains this operator protected Map<String, Object> annotations; public Operator(String n, OperatorPlan p) { ... } /** * Accept a visitor at this node in the graph. * @param v Visitor to accept. * @throws IOException */ public abstract void accept(PlanVisitor v) throws IOException; /** * Add an annotation to a node in the plan. * @param key string name of this annotation * @param val value, as an Object */ public void annotate(String key, Object val) { ... } /** * Look to see if a node is annotated. * @param key string name of annotation to look for * @return value of the annotation, as an Object, or null if the key is * not present in the map. */ public Object getAnnotation(String key) { ... } } New OperatorPlan interface. It has been made an interface so that different implementations can be used for representing actual plans and sub-graphs of plans inside the optimizer. Note the severe paring down of the number of operations. Only simple add, remove, connect, disconnect. All all operations are left to subclasses to implement what makes sense for their plans. package org.apache.pig.experimental.plan; public interface OperatorPlan { /** * Get number of nodes in the plan. */ public int size(); /** * Get all operators in the plan that have no predecessors. * @return all operators in the plan that have no predecessors, or * an empty list if the plan is empty. */ public List<Operator> getRoots(); /** * Get all operators in the plan that have no successors. * @return all operators in the plan that have no successors, or * an empty list if the plan is empty. */ public List<Operator> getLeaves(); /** * For a given operator, get all operators immediately before it in the * plan. * @param op operator to fetch predecessors of * @return list of all operators immediately before op, or an empty list * if op is a root. * @throws IOException if op is not in the plan. */ public List<Operator> getPredecessors(Operator op) throws IOException; /** * For a given operator, get all operators immediately after it. * @param op operator to fetch successors of * @return list of all operators immediately after op, or an empty list * if op is a leaf. * @throws IOException if op is not in the plan. */ public List<Operator> getSuccessors(Operator op) throws IOException; /** * Add a new operator to the plan. It will not be connected to any * existing operators. * @param op operator to add */ public void add(Operator op); /** * Remove an operator from the plan. * @param op Operator to be removed * @throws IOException if the remove operation attempts to * remove an operator that is still connected to other operators. */ public void remove(Operator op) throws IOException; /** * Connect two operators in the plan, controlling which position in the * edge lists that the from and to edges are placed. * @param from Operator edge will come from * @param fromPos Position in the array for the from edge * @param to Operator edge will go to * @param toPos Position in the array for the to edge */ public void connect(Operator from, int fromPos, Operator to, int toPos); /** * Connect two operators in the plan. * @param from Operator edge will come from * @param to Operator edge will go to */ public void connect(Operator from, Operator to); /** * Disconnect two operators in the plan. * @param from Operator edge is coming from * @param to Operator edge is going to * @return pair of positions, indicating the position in the from and * to arrays. * @throws IOException if the two operators aren't connected. */ public Pair<Integer, Integer> disconnect(Operator from, Operator to) throws IOException; /** * Get an iterator of all operators in this plan * @return an iterator of all operators in this plan */ public Iterator<Operator> getOperators(); } There are no significant changes to PlanVisitor and PlanWalker other than the removal of generics. With the change that only LOForeach now has inner plans, it isn't clear whether the pushWalker and popWalker methods in PlanVisitor are really useful anymore or not. These may be removed. Changes to Logical Operators There will be a number of important changes to LogicalOperators. First, as mentioned above relational operators will be split into two disparate groups, relational and expression. Second, inner plans and expression plans will no longer hold any explicit references to outer plans. At most, they will reference the operator which contains the inner plan. Third, operators will represent exactly one operation. Fourth, only LOForeach will have inner plans. All other relational operators will only have expressions. Fifth, a new operator, LOInnerLoad will be introduced. The sole purpose of this operator will be to act as a root in foreach's inner plans. So, given a script like: A = load 'input'; B = group A by $0; C = foreach B { C1 = B.$1; C2 = distinct C1; generate group, COUNT(C2); } the foreach's inner plan will have two LOInnerLoad operators, one for $0 and one for $1. This will allow the C1 !LOGenerate operator to connect to another relational operator. Sixth, in the past expression operators were used at places in inner plans, such as the C1 = B1.$0; above. Relational operators will always be used in these places now. LOGenerate (or perhaps a new operator if necessary) will be used in the place of these assignment operations instead. Seventh, in the past !LOForeach had multiple inner plans, one for each of its outputs. That will no longer be the case. !LOForeach will always have exactly one inner plan, which must terminate with a !LOGenerate. That !LOGenerate will have expressions for each of its outputs. All logical operators will have a schema. This schema represents the format of the output for that operator. The schema can be null, which indicates that the format of the output for that operator is unknown. In general the notion of unknownness in a schema will be contagious. Take for example: A = load 'file1' as (x: int, y: float); B = load 'file2'; C = cogroup A by x, B by $0; D = foreach C generate flatten(A), flatten(B); A will have a schema, since one is specified for it. B will not have a schema, since one is not specified. C will have a schema, because the schema of (co)group is always known. Note however that in C's schema, the bag A will have a schema, and the bag B will not. This means that D will not have schema, because the output of flatten(B) is not known. If D is changed to be D = foreach C generate flatten(A); then D will have a schema, since the format of flatten(A) is known. LogicalPlan will contain add and removeLogical operations specifically designed for manipulating logical plans. These will be the only operations supported on the plan. package org.apache.pig.experimental.logical.relational; /** * LogicalPlan is the logical view of relational operations Pig will execute * for a given script. Note that it contains only realtional operations. * All expressions will be contained in LogicalExpressionPlans inside * each relational operator. LogicalPlan provides operations for * removing and adding LogicalRelationalOperators. These will handle doing * all of the necessary add, remove, connect, and disconnect calls in * OperatorPlan. They will not handle patching up individual relational * operators. That will be handle by the various Patchers. * */ public class LogicalPlan extends BaseOperatorPlan { /** * Add a relational operation outputs to the plan. * @param before operators that will be before the new operator. These * operator should already be in the plan. * inputs operators that will be after the new operator. These * operator should already be in the plan. * @throws IOException if add is already in the plan, or before or after * are not in the plan. */ public void add(LogicalRelationalOperator before, LogicalRelationalOperator newOper, LogicalRelationalOperator[] after) throws IOException { ... } /** * Add a relational operation to the plan when the caller wants to control * how the nodes are connected in the graph. * @param before operator that will be before the new operator. This * operator should already be in the plan. before should not be null. * the new operator will be a root. * @param beforeToPos Position in before's edges to connect newOper at. * @param beforeFromPos Position in newOps's edges to connect before at. * @param newOper new operator to add. This operator should not already * be in the plan. * @param afterToPos Position in after's edges to connect newOper at. * @param afterFromPos Position in newOps's edges to connect after at. * , int beforeToPos, int beforeFromPos, LogicalRelationalOperator newOper, int afterToPos, int afterFromPos, LogicalRelationalOperator after) throws IOException { ... } /** * Remove an operator from the logical plan. This call will take care * of disconnecting the operator, connecting the predecessor(s) and * successor(s) and patching up the plan. * @param op operator to be removed. * @throws IOException If the operator is not in the plan. */ public void removeLogical(LogicalRelationalOperator op) throws IOException { ... } } A LogicalRelationalOperator will be the logical representation of a relational operator (join, sort, etc.). package org.apache.pig.experimental.logical.relational; /** * Logical representation of relational operators. Relational operators have * a schema. */ abstract public class LogicalRelationalOperator extends Operator { protected LogicalSchema schema; protected int requestedParallelism; protected String alias; // Needed only for error messages, not used in optimizer protected int lineNum; // Needed only for error messages, not used in optimizer /** * * @param name of this operator * @param plan this operator is in */ public LogicalRelationalOperator(String name, OperatorPlan plan) { ... } /** * * @param name of this operator * @param plan this operator is in * @param rp requested parallelism */ public LogicalRelationalOperator(String name, OperatorPlan plan, int rp) { ... } /** * Get the schema for the output of this relational operator. This does * not merely return the schema variable. If schema is not yet set, this * will attempt to construct it. Therefore it is abstract since each * operator will need to construct its schema differently. * @return the schema */ abstract public LogicalSchema getSchema(); /** * Reset the schema to null so that the next time getSchema is called * the schema will be regenerated from scratch. */ public void resetSchema() { ... } } LogicalSchema will be based on the existing Schema class. It is hoped that this class can be greatly simplified. LogicalExpressionPlan will extend OperatorPlan and contain LogicalExpressionOperators. Often expression trees are built with the expressions themselves containing references to the next expression in the tree. For example, a common implementation would be something like: abstract class BinaryExpression { Expression leftHandSide; Expression rightHandSide; } class Plus extends BinaryExpression { ... } Since we already have a plan structure we will have a LogicalExpressionPlan. This has the advantage that PlanVisitors will work with expression trees and we do not need to invent a separate visitor hierarchy. LogicalExpressionOperators will have a data type (the type they return) and a unique identifier (uid). The point of the uid is to allow the optimizer to track how expressions flow through the tree. So projection expressions will have the same uid as the expression they are projecting. All other expressions will create a new uid, since they are changing the value of the expression. (Cast probably does not conform to this statement. In general casts are movable like projects. We need to think further about how casts fit into this system.) package org.apache.pig.experimental.logical.expression; /** * Logical representation of expression operators. Expression operators have * a data type and a uid. Uid is a unique id for each expression. * */ public abstract class LogicalExpression extends Operator { protected byte type; protected long uid = -1; static public long getNextUid() { ... } /** * * @param name of the operator * @param plan LogicalExpressionPlan this is part of * @param b datatype of this expression */ public LogicalExpression(String name, OperatorPlan plan, byte b) { ... } /** * Set the uid. For most expressions this will get a new uid. * ProjectExpression needs to override this and find its uid from its * predecessor. * @param currentOp Current LogicalRelationalOperator that this expression operator * is attached to. Passed so that projection operators can determine their uid. * @throws IOException */ public void setUid(LogicalRelationalOperator currentOp) throws IOException { ... } } Consider the following example: A = load 'file1' as (x:int, y:int); B = filter A by x > 0 and y > 0; C = foreach A generate x + y; In this case x and y will be assigned uids in load, where they first enter the script. The output of filter will maintain these same uids since filter does not alter the format of its input. But the output of foreach will have a different uid, since this creates a new value in the script. Hopefully an example will make all of this somewhat clearer. Consider the following script: A = load 'input1' as (x: int, y: chararray); B = load 'input2' as (u: int, v: float); C = filter A by x is not null; D = filter B by u is not null and v > 0.0; E = join C on x, D on u; F = group E on x; G = foreach F { H = E.y; I = distinct H; J = order E by v; generate group, COUNT(I), CUMULATIVE(J); } store G into 'output'; That script will produce a logical plan that looks like the following: The !LOFilter for D will have an expression plan that looks like: Changes to the Optimizer The following changes will be made to the optimizer: - Currently all rules are handed to the optimizer at once, and it iterates over them until none of the rules trigger or it reaches the maximum number of iterations. This will be changed so that rules are collected into sets. The optimizer will then iterate over rules in each set until none of the rules trigger or it reaches the maximum number of iterations. The reason for this change will be made clear below. Currently the plan itself has the knowledge of how to patch itself up after it is rearranged. (For example, how to reconstruct schemas after a plan is changed.) This will be changed so that instead the optimizer can register a number of listeners on the plan. These listeners will then be invoked after each rule that modifies the plan. In this way the plans themselves need not understand how to patch up changes made by an optimization rule. Also as we expand the plans and they record more information, it is easy to add new listeners without having to interact with existing functionality. The Rule class will be merged with the existing RuleMatcher class so that Rule takes on the functionality of matching. This match routine will be written once in Rule and extensions of rule need not re-implement it. The rewritten Rule class: package org.apache.pig.experimental.plan.optimizer; /** * Rules describe a pattern of operators. They also reference a Transformer. * If the pattern of operators is found one or more times in the provided plan, * then the optimizer will use the associated Transformer to transform the * plan. * */ public abstract class Rule { protected String name = null; protected OperatorPlan pattern; transient protected OperatorPlan currentPlan; /** * Create this rule by using the default pattern that this rule provided * @param n Name of this rule */ public Rule(String n) { .. } /** * @param n Name of this rule * @param p Pattern to look for. */ public Rule(String n, OperatorPlan p) { ... } /** * Build the pattern that this rule will look for * @return the pattern to look for by this rule */ abstract protected OperatorPlan buildPattern(); /** * Get the transformer for this rule. Abstract because the rule * may want to choose how to instantiate the transformer. * This should never return a cached transformer, it should * always return a fresh one with no state. * @return Transformer to use with this rule */ abstract public Transformer getNewTransformer(); /** * Search for all the sub-plans that matches the pattern * defined by this rule. * @return A list of all matched sub-plans. The returned plans are * partial views of the original OperatorPlan. Each is a * sub-set of the original plan and represents the same * topology as the pattern, but operators in the returned plan * are the same objects as the original plan. Therefore, * a call getPlan() from any node in the return plan would * return the original plan. * * @param plan the OperatorPlan to look for matches to the pattern */ public List<OperatorPlan> match(OperatorPlan plan) {... } } The mostly unchanged Transformer class: package org.apache.pig.experimental.plan.optimizer; public abstract class Transformer { /** * check if the transform should be done. If this is being called then * the pattern matches, but there may be other criteria that must be met * as well. * @param matched the sub-set of the plan that matches the pattern. This * subset has the same graph as the pattern, but the operators * point to the same objects as the plan to be matched. * @return true if the transform should be done. * @throws IOException */ public abstract boolean check(OperatorPlan matched) throws IOException; /** * Transform the tree * @param matched the sub-set of the plan that matches the pattern. This * subset has the same graph as the pattern, but the operators * point to the same objects as the plan to be matched. * @throws IOException */ public abstract void transform(OperatorPlan matched) throws IOException; /** * Report what parts of the tree were transformed. This is so that * listeners can know which part of the tree to visit and modify * schemas, annotations, etc. So any nodes that were removed need * will not be in this plan, only nodes that were added or moved. * @return OperatorPlan that describes just the changed nodes. */ public abstract OperatorPlan reportChanges(); } The new PlanTransformListener interface: package org.apache.pig.experimental.plan.optimizer; /** * A listener class that patches up plans after they have been transformed. */ public interface PlanTransformListener { /** * the listener that is notified after a plan is transformed * @param fp the full plan that has been transformed * @param tp a plan containing only the operators that have been transformed * @throws IOException */ public void transformed(OperatorPlan fp, OperatorPlan tp) throws IOException; } The goal in the above changes is to radically simplify writing optimizer rules. Consider a rule to push a filter above a join. A = load 'file1' as (x, y); B = load 'file2' as (u, v); C = join A by x, B by u; D = filter C by (y > 0 or v > 0) and x > 0 and u > 0 and y > v; In the current design, to push this filter, a rule must know how to split filters, how to push the parts that pushable, and reconstruct the filters of the parts that are not. In the new proposal we can instead create three rules. Rule 1 will only know how split filters. Rule 2 will only know how to push them. And Rule 3 will only know how to reconstitute them. These rules can then be placed in separate sets, so that they do not interfere with each other. So in this example, after Rule 1 has run, the script will conceptually look like A = load 'file1' as (x, y); B = load 'file2' as (u, v); C = join A by x, B by u; D1 = filter C by (y > 0 or v > 0); D2 = filter D1 by x > 0; D3 = filter D2 by u > 0; D = filter D3 by y > v; Since Rule 1 will be run repeatedly it need not manage entirely splitting the filter. It can be written to simply split one and, allowing the next iteration to split any subsequents ands. After Rule 2, the script will look like: A = load 'file1' as (x, y); D2 = filter A by x > 0; B = load 'file2' as (u, v); D3 = filter B by u > 0; C = join D2 by x, D3 by u; D1 = filter C by (y > 0 or v > 0); D = filter D1 by y > v; And finally, after Rule 3 has run, the script will look like: A = load 'file1' as (x, y); D2 = filter A by x > 0; B = load 'file2' as (u, v); D3 = filter B by u > 0; C = join D2 by x, D3 by u; D = filter C by (y > 0 or v > 0) and y > v; Writing each of these rules will be much simpler than writing one large rule that must handle all three cases. After each of these rules modify the tree, listeners will be notified that the tree has changed. The currently known listeners are one to reconstruct schemas based on the changes and one to reconnect projections to the proper field in their predecessor. After each run of a rule and operations by attached listeners the plan will be in a functionally correct state. We have identified three operations we would like to prototype. The first is pushing filters past joins. The second pushing filters after foreach with a flatten. These were chosen because both involve schema altering operations where the rules have to decide when they can and cannot push and where the listeners have real work to do to rewrite schemas and projections after a rule is run. The third operation is pruning unnecessary fields from the load. That is, if five fields are loaded but only three are used, the other two will be pruned out. This was chosen because it proved to be particularly difficult in the current framework and we wish to investigate whether it is doable in the proposed framework.
https://wiki.apache.org/pig/PigLogicalPlanOptimizerRewrite
CC-MAIN-2017-17
refinedweb
4,347
54.83
Date handling is one of the web’s inevitables. Almost any web application you write is going to include some form of date-bound hacking. Whether it’s capturing user input via a web form, calculating the difference between two times, or fetching data via a date range, time and the web are closely linked. Luckily for us, Rails make handling dates and times, like everything else, fairly trivial; that is, once you have an idea of how everything works. I recently rewrote the section of our admin site in Rails that handles the creation of back issues. Since I had to hunt all over the web for a complete package of documentation to finalize this small task I thought it might be a good idea to share my experience. In the interest of time we’ll assume you have a Rails app up and running and have controllers and models in place that you’re looking to add date-handling code to. Form Helpers Let’s start with data capture via a simple web form. When storing a back issue in the database the most important data we need to capture is its print date. As far as our back issues are concerned, print date is just a month and a year. To accomplish this, Rails provides a few FormHelpers for picking dates that we’ll use in our view. /app/view/back_issues/new.rhtml <%= error_messages_for :back_issue %> <% form_for :back_issue do |f| %> Print Month: <%= select_month(Date.today, :field_name => "print_month") %> Print Year: <%= select_year(Date.today, :start_year => 1999, :field_name => "print_year") %> <%= submit_tag value='Create Backissue' %> <% end %> select_month() and select_year() generate pulldown menus for picking the issue’s month and year. Pay special attention the :field_name option. It’s not documented well in the Rails API proper and will come in handy when you need to change the name of these select boxes to something other than the default of date[month] and date[year]; necessary if you are using multiple instances of these helpers in a single form. :field_name date[month] date[year] For still greater control over a date submitted via a form, you might want to take look at select_datetime, which provides a pulldown for each element of a timestamp. Or for something a little more user friendly, check out the really nice Protoype-based Calendar Date Select. Storing the Data There’s no real reason for us to store the values from these two fields in separate database columns. Rather we’ll use the month and year values to construct a date in the controller and store the result in a single datetime field called print_date. print_date /app/controllers/back_issue_controller.rb class BackIssuesController < ApplicationController def new @back_issue = BackIssue.new(params[:back_issue]) return unless request.post? @back_issue.print_date = Date.new(params[:date]['print_year'].to_i, params[:date]['print_month'].to_i) @back_issue.save! flash[:notice] = "New back issue created." redirect_to "/covers/new?bi=" + @back_issue.id.to_s # In the event our validations fail rescue ActiveRecord::RecordInvalid render :action => 'new' end end Ok, that should do it. Once we’ve created an instance of @back_issue with the parameters from the form, we have access to print_date and can give it a newly constructed datetime with Date.new(). @back_issue Date.new() Date.new() can take three parameters (year, month, day). We’re taking the default of 1 on the day parameter by not passing anything to the method. In this example, we’re really only concerned with the month and year so the default is fine. In reality, the new() method on our BackIssuesController is actually a bit more complex than this– hence the params[:back_issue] — but for the sake of simplicity, we’re just showing how to push a new date into the publish_date column from pulldown menus. new() params[:back_issue] publish_date The redirect_to in this case point to our cover upload form, but you can point it to whatever destination you like following a successful save!. redirect_to save! Manipulating Dates We don’t actually need to modify the date after it’s submitted to our controller, but if we did, Ruby has a few operators for quickly adjusting a Date object. Pretty simple stuff. To demonstrate, let’s take these operators for a spin on the console. console >> d = Date.new(2007, 8, 23) => # >> d.to_s => "2007-08-23" >> yesterday = d-1 => # >> yesterday.to_s => "2007-08-22" >> tomorrow = d+1 => # >> tomorrow.to_s => "2007-08-24" >> lastmonth = d<<1 => # >> lastmonth.to_s => "2007-07-23" >> nextmonth = d>>1 => # >> nextmonth.to_s => "2007-09-23" Displaying Dates Alright, now that we’ve written our back issue date to the database, all that’s left to do is display it in a view. We probably don’t want to display the date formatted as it’s stored: ‘YYYY-MM-DD’. Rather we want something like the current back issue page that displays the full month name and the year. To accomplish this we’ll use strftime(). strftime() If you’re familiar with PHP’s date() method, strftime() is similar, you pass the method a format string that defines how you want the date output. The difference is that while you pass PHP’s date() both a format and a timestamp, strftime() is a method that operates on a Date object. And everything in Rails is an object. date() Date Rails automatically knows to treat our datetime columns in the database as Date objects, so, after you’ve fetched the back issue data from the database in the controller, formatting the date in the view is as simple as: <%= @back_issue.print_date.strftime('%B %Y') %> Which will print something like “January 2007″ to the screen. For a full list of format codes for strftime(), see the table below. Rails Magic Wishlist And that’s about it. Not too difficult but it’s actually a little more work that I’d like to do. Frankly, I wish there was some Rails magic that did the date handling in the controller for me. Creating a new date and casting parameters in the controller isn’t how I’d like this to function — ultimately it doesn’t strike me as terribly DRY. Rather, I would like to have the option of passing the form fields to the controller as back_issue[print_date_month] and back_issue[print_date_year] and have Rails realize that these are components of my print_date field and compile these elements into a date for me. But all-in-all the solution we have here is reasonably clean and maybe I can build some of that magic into a plugin or helper at a later date. back_issue[print_date_month] back_issue[print_date_year]
http://www.linux-mag.com/id/4070/
CC-MAIN-2015-06
refinedweb
1,094
61.77
go to bug id or search bugs for Functions strtolower() & strtoupper() does not change UTF-8 strings. I try Russian (0x042F, 0x044F) and German (0x00DC, 0x00FC) characters. Example: <? $str = "testЯ"; $loc = "UTF-8"; putenv("LANG=$loc"); $loc = setlocale(LC_ALL, $loc); $strU = strtoupper($str); $strL = strtolower($str); ?> <PRE> loc = '<? echo $loc; ?>' str = '<? echo $str; ?>' strU = '<? echo $strU; ?>' strL = '<? echo $strL; ?>' </PRE> Add a Patch Add a Pull Request Please try using this CVS snapshot: For Windows: I can't reproduce this with PHP 4.3.0-dev. I did backport of strtolower() & strtoupper() from the latest string.c (rev.1.290). The fuctions still does not work: loc = 'UTF-8' str = 'Test?' strU = 'TEST?' strL = 'test?' Since I am not sure that you entered the UTF-8 symbols correctly, here's a modified version of the code that creates the desired test string: <? $str = "Test".utf8_encode("\xFC"); $loc = "UTF-8"; putenv("LANG=$loc"); $loc = setlocale(LC_ALL, $loc); $strU = strtoupper($str); $strL = strtolower($str); ?> <PRE> loc = '<? echo $loc; ?>' str = '<? echo $str; ?>' strU = '<? echo $strU; ?>' strL = '<? echo $strL; ?>' </PRE> Output: str = 'Testü' strU = 'TESTü' strL = 'test??' Don't try to patch..you're not doing it right anyway. Just pull the snapshot and try with it. > Don't try to patch..you're not doing it right anyway. :) > Just pull the snapshot and try with it. Ok PHP: 20020307 PHP Extension: 20020429 Zend Extension: 20020903 Output: loc = 'UTF-8' str = 'Test?' strU = 'TEST?' strL = 'test?' The functions do not work in PHP 4.2.3 and latest snapshot. BTW, here is my configuration: ./configure \ --with-apxs=/usr/sbin/apxs \ --enable-track-vars \ --enable-safe-mode \ --with-config-file-path=/etc/httpd \ --with-zlib \ --enable-magic-quotes \ --with-regex=system \ --without-mysql \ --without-xml \ --without-gd \ --with-pgsql=shared \ --with-imap \ --with-iconv \ --enable-mbstring \ --with-xml \ --with-kerberos php.ini has 'default_charset=utf-8'. Exactly what distribution do you have? How are LANG/LANGUAGE/LC_ALL etc. environment variables set in your system (before starting Apache)..? And please, try with the stock php.ini-dist too. > Exactly what distribution do you have? Mandrake 8.1 with following RPMs installed: locales-2.3.1.2-4mdk locales-en-2.3.1.2-4mdk locales-ru-2.3.1.2-4mdk locales-de-2.3.1.2-4mdk > How are LANG/LANGUAGE/LC_ALL etc. environment variables > set in your system (before starting Apache)..? All environment variables set to 'UTF-8'. > And please, try with the stock php.ini-dist too. Same result. BTW, in the php.ini-dist there should be a semi-colon instead of colon in the line 98: ": is doing." -> "; is doing." Could you tell me your settings so that I can try them out? I didn't know UTF-8 is a locale.. I tried setting LANG/LC_ALL to that and it indeed didn't work. When I set those to "en_US" it works just fine. > I tried setting LANG/LC_ALL to that and it indeed > didn't work. When I set those to "en_US" it works just fine. What you mean "works just fine"? Did it convert 0xC39C ('?' in UTF-8 encoding) into 0xC3BC ('?' in UTF-8 encoding)? Or 0xD0AF (Russian capital "ya" in UTF-8 encoding) into 0xD18F (Russian lowercase "ya" in UTF-8 encoding)? So you didn't try it..? I only tried your test script and got the expected result. Whatever the characters are..I've no idea of them anyway.. btw. AFAIK, setting LANG / LC_ALL to UTF-8 is not correct way to do it.. tml According to that HOWTO, it should be something like ru_RU.UTF-8 (and only if you really have UTF-8 locales) I'm bogusing this since it really isn't anything PHP can affect.. > So you didn't try it..? Yes, I set LC_ALL/LANG to 'en_US' and try it. > I only tried your test script and got the expected result. > Whatever the characters are.. I've no idea of them anyway.. I think your confused by looking on the result of test script with encoding set to 'ISO-8859-x' instead of 'UTF-8'. In this case it looks as some characters changed to lower/upper case. BUT they are not UTF-8 lower/upper case characters: 1) 0xC39C changed to 0xE39C, should be 0xC3BC 2) 0xD0AF changed to 0xF0AF, should be 0xD18F As result we have not UTF-8 string but a garbage. If you really like test this issue you should set 'default_charset=utf-8' in php.ini or set encoding to 'UTF-8' in your browser. > btw. AFAIK, setting LANG / LC_ALL to UTF-8 is not correct > way to do it.. > According to that HOWTO, it should be something like > ru_RU.UTF-8 (and only if you really have UTF-8 locales) I try en_US.UTF-8, de_DE.UTF-8, ru_RU.UTF-8 - no lack. > I'm bogusing this since it really isn't anything PHP can > affect.. So, no way in PHP convert UTF-8 string to lower/upper case? This is not a bug in PHP; it's down to whether your system can support this and has the appropriate locales installed. A quick and dirty example might look this this in C: #include <ctype.h> main() { char buff[1024]; while(fgets(buff, sizeof(buff), stdin)) { int i, l; l = strlen(buff); for (i = 0; i < l; i++) buff[i] = toupper(buff[i]); puts(buff); } } If that little program works, your system supports this conversion. If it doesn't, then PHP doesn't either. I forgot to add that you should feed your utf8 data to the input of that little program. As I understand toupper()/tolower() are working only for one byte encodings. So right way is to use 'wide' versions of toupper()/tolower() - towupper()/towlower(). Example: #include <stdio.h> #include <wctype.h> #include <locale.h> int main() { printf("locale set to '%s'\n", setlocale(LC_ALL, "UTF-8")); printf("0x00DC C='%C'\n", towlower(0x00DC)); printf("0x042F C='%C'\n", towlower(0x042F)); return(0); } And it's working fine for UCS2 (UTF-16). In PHP I can convert UTF-8 to UTF-16 by using iconv(). But PHP has not 'wide' version of strtolower()/strtoupper(). So, what can I do? I've added a new function to the mbstring extension in CVS. This function will be in PHP 4.3. I would appreciate your feedback. Try a snapshot from dated after this message. usage: proto string mb_convert_case(string str, int mode [, string encoding]); mode can be one of MB_CASE_UPPER, MB_CASE_LOWER or MB_CASE_TITLE. encoding specifies the encoding of str; if omitted, the mbstring.internal_encoding value will be used. The return value is str with the appropriate case folding applied. The function works by internally converting the string into UCS-4 format and applying php_unicode_to(upper|lower|title) to each unicode character, and then converts the string back into the original encoding. The code for your test case would look like this (and works for me): <? $str = "Test".utf8_encode("\xFC"); $strU = mb_convert_case($str, MB_CASE_UPPER, "utf-8"); $strL = mb_convert_case($str, MB_CASE_LOWER, "utf-8"); ?> <PRE> str = '<? echo $str; ?>' strU = '<? echo $strU; ?>' strL = '<? echo $strL; ?>' </PRE> Works fine for German and Russian characters. Thans!
https://bugs.php.net/bug.php?id=19257&edit=3
CC-MAIN-2020-10
refinedweb
1,195
69.07
Important: Please read the Qt Code of Conduct - No idea how to manage QWidget Hi Folks! I have two question, because I can't find the answer in documentation. First of all I created QWidget using Qt Wizard. In one word: normal windows application. Then I wanted to add new child window. I did it by writing it: @ QWidget *now = new QWidget(); now->show();@ but it's hard do design something by this way. So I created new window with Qt wizard and I added it into project. But now I have problem: how to show it, for example, after button clicked() singal? In Design section, on the right panel we can see all the properties of ours items. So, let's say we have only one basic window, and it's name is wnd. When I type: @wnd->close();@ nothing happens, compilator can't recognize the variable. So how I can manage QWidgets? Via Qt Designer you create not widgets itself, but their description. You should instantiate them via new keyword. If you have created only ui file without c++ class than you can load this file via QUiLoader. hmm...ok but when I created new whole project under class name "something" there are something.ui file (where I'm designing) and something.h which consist of: @#ifndef SOMETHING_H #define SOMETHING_H #include <QWidget> namespace Ui { class something; } class something: public QWidget { Q_OBJECT public: explicit something(QWidget *parent = 0); ~something(); private: Ui::something*ui; private slots: void on_pushButton_clicked(); }; #endif // SOMETHING_H@ So, according what you wrote I have class. How I can "do things" in "something" window by coding it, not designing? I tried @ ui->something-> no help so I'm stuck @ also: @ ui->Ui_Something->...nothing @ Any suggestions, or I'm doing it completely wrong? Yes, you have a class. You can now instantiate it using @ something somethingObj = new something; @ and you will have this widget to show it. If you want to add it to another widget as its part you should pass this widget as parameter to constructor of something. You can access containtments of your designed widget by using ui pointer. For example if you have a label at your widget named myLabel you can access it using ui->myLabel. bq. You can access containtments of your designed widget by using ui pointer. For example if you have a label at your widget named myLabel you can access it using ui->myLabel.bq. Yep, I know about this, but I created it like you said, and try basic things like: @ something *somethingObj = new something; somethingObj->show(); @ after click, new, exactly the same windows appears. @ something *somethingObj = new something; somethingObj->resize(10,13); @ nothing happens? So I still don't know how to manage designed window by code of lines. Can you explain it to me again? Or recommend some documentation? I think that you simply forgot to include show() in second sample of code, but used it in your sources. If not, try to add this. Also each widget has size hints and size policies (you can read about them in assistant), they defines how widget can be resized. Maybe you have minimum size for you widget equal to current size, so it cannot be resized smaller? bq. I think that you simply forgot to include show() in second sample of code, but used it in your sources. If not, try to add this.bq. Yes! It's working. Sorry Denis but still one thing is nagging me all the time, and I'm can't find proper answer in net. I should start topic from this example: Imagine situation: I have parent widget which consist only lineedit and button. After button click new window(widget) should appear with another lineedit and button. User is typing something in lineedit, clicking button and then child widget is destroyed and it's passing variable to the basic widget and the first lineedit. So? How to do that? It will be something with "coinnect" and "slot" mechanism? - tobias.hunger Moderators last edited by Luka: These questions of yours are pretty well covered in any introductory Qt book I have read so far. Maybe you could save some time by just grabbing a book and working through it? After all it must kill your productivity to sit and wait for answers here in the forum. Or you might try some of the free tutorials available on the net? Signals and slots are really well covered there as well. yes, you're right Tobias, I was trying to follow the line of least resistance. My fault!
https://forum.qt.io/topic/548/no-idea-how-to-manage-qwidget/7
CC-MAIN-2021-39
refinedweb
763
65.42
Question 1 : A union cannot be nested in a structure Question 2 : Nested unions are allowed Question 3 : Bit fields CANNOT be used in union. The following is the example program to explain "using bit fields inside an union". #include < stdio.h > union Point { unsigned int x:4; unsigned int y:4; int res; }; int main() { union Point pt; pt.x = 2; pt.y = 3; pt.res = pt.y; printf("\n The value of res = %d" , pt.res); return 0; } // Output: The value of res = 3 Question 4 : one of elements of a structure can be a pointer to the same structure. Question 5 : A structure can be nested inside another structure.
http://www.indiaparinam.com/c-programming-language-question-answer-structures-unions-enums/true-false-questions
CC-MAIN-2019-18
refinedweb
112
75.3
Abstract base class for camera nodes. More... #include <Inventor/nodes/SoCamera.h> Abstract base class for camera nodes. This is the abstract base class for all camera nodes. It defines the common methods and fields that all cameras have. Cameras are used to view a scene. When a camera is encountered during rendering, it sets the projection and viewing matrices and viewport appropriately; it does not draw geometry. Cameras should be placed before any shape nodes or light nodes in a scene graph; otherwise, those shapes or lights cannot be rendered properly. Cameras are affected by the current transformation, so you can position a camera by placing a transformation node before it in the scene graph. The default position and orientation of a camera is at (0,0,1) looking along the negative z-axis. You can also use a node kit to create a camera; see the reference page for SoCameraKit. Useful algorithms for manipulating a camera are provided in the SoCameraInteractor class. Compute the current view vector or up vector. SoCamera* camera . . . const SbRotation& orientation = camera->orientation.getValue(); SbVec3f upVec; orientation.multVec( SbVec3f(0,1,0), upVec ); SbVec3f vwVec; orientation.multVec( SbVec3f(0,0,-1), vwVec ); Shortcut to get the current view vector or up vector. Compute the current focal point. SoOrthographicCamera, SoPerspectiveCamera, SoCameraKit, SoCameraInteractor Stereo mode. Viewport mapping. Allows the camera to render in stereo. Default value is TRUE. Reimplemented in SoStereoCamera. Queries the parallax balance. Returns the type identifier for this class. Reimplemented from SoNode. Reimplemented in SoOrthographicCamera, SoPerspectiveCamera, and SoStereoCamera. Queries the stereo absolute adjustment state. Queries the stereo offset. Queries the stereo mode. Returns the type identifier for this specific instance. Reimplemented from SoNode. Reimplemented in SoOrthographicCamera, SoPerspectiveCamera, and SoStereoCamera. Returns the viewport region this camera would use to render into the given viewport region, accounting for cropping. Computes a view volume from the given parameters. Implemented in SoOrthographicCamera, and SoPerspectiveCamera. Returns a view volume object, based on the camera's viewing parameters. This object can be used, for example, to get the view and projection matrices, to project 2D screen coordinates into 3D space and to project 3D coordinates into screen space. If the useAspectRatio parameter is 0.0 (the default), the camera uses the current value of the aspectRatio field to compute the view volume. NOTE: In ADJUST_CAMERA mode (the default), the view volume returned when useAspectRatio = 0, is not (in general) the actual view volume used for rendering. Using this view volume to project points will not (in general) produce the correct results. This is because, in ADJUST_CAMERA mode, Inventor automatically modifies the view volume to match the aspect ratio of the current viewport. This avoids the distortion that would be caused by "stretching" the view volume when it is mapped into the viewport. However the view volume values are not changed, only the values passed to OpenGL. In order to get the modified values (i.e., the actual view volume used for rendering) you must pass the actual viewport aspect ratio to getViewVolume. You can get the current viewport from the renderArea or viewer object that contains the Open Inventor window. Also note that in ADJUST_CAMERA mode, when the viewport aspect ratio is less than 1, Open Inventor automatically scales the actual rendering view volume by the inverse of the aspect ratio (i.e. 1/aspect). The getViewVolume method does not automatically apply this adjustment. So a correct query of the actual rendering view volume can be done like this: // Given a viewer object, get the actual rendering view volume float aspect = viewer->getViewportRegion().getViewportAspectRatio(); SoCamera* camera = viewer->getCamera(); SbViewVolume viewVol = camera->getViewVolume( aspect ); if (aspect < 1) viewVol.scale( 1 / aspect ); Implemented in SoOrthographicCamera, and SoPerspectiveCamera. Returns TRUE if the stereo balance adjustement is defined as a fraction of the camera near distance. Sets the orientation of the camera so that it points toward the given target point while keeping the "up" direction of the camera parallel to the positive y-axis. If this is not possible, it uses the positive z-axis as "up." Scales the height of the camera. Perspective cameras scale their heightAngle fields, and orthographic cameras scale their height fields. Implemented in SoOrthographicCamera, and SoPerspectiveCamera. Sets the stereo balance (the position of the zero parallax plane) and specifies whether the balance value is defined as a fraction of the camera near distance. Note: Since the projection matrix always depends on the camera's near plane, in some cases it may be necessary to detect changes to the camera near plane and adjust by setting a new stereo balance value. Open Inventor will make these adjustments automatically if the nearFrac parameter is set to TRUE. In this case the stereo balance value is defined as a fraction of the camera near distance. Default balance is 1.0. The default can be set using the OIV_STEREO_BALANCE environment variable. Default nearFrac is FALSE. The default can be set using the OIV_STEREO_BALANCE_NEAR_FRAC environment variable. Reimplemented in SoStereoCamera. Specifies if stereo adjustments are absolute. FALSE by default. The default non-absolute mode allows the stereo settings to be valid over a range of different view volume settings. If you chose absolute mode, you are responsible for modifying the stereo settings (if necessary) when the view volume changes. When absolute mode is TRUE, stereo offset and balance are used as shown in the following pseudo-code for the right eye view: StereoCameraOffset = getStereoAdjustment(); FrustumAsymmetry = getBalanceAdjustment(); glTranslated (-StereoCameraOffset, 0, 0); glFrustum (FrustumLeft + FrustumAsymmetry, FrustumRight + FrustumAsymmetry, FrustumBottom, FrustumTop, NearClipDistance, FarClipDistance); The left eye view is symmetric. When absolute mode is FALSE, stereo offset and balance are used as shown in the following pseudo-code for the right eye view: Xrange is right minus left (i.e., first two arguments of glFrustum) and multiply that difference by the ratio of the distance to the desired plane of zero parallax to the near clipping plane distance. StereoCameraOffset = Xrange * 0.035 * getStereoAdjustment(); FrustumAsymmetry = -StereoCameraOffset * getBalanceAdjustment(); ZeroParallaxDistance = (NearClipDistance + FarClipDistance)/0.5; FrustumAsymmetry *= NearClipDistance / ZeroParallaxDistance; glTranslated (-StereoCameraOffset, 0, 0); glFrustum (FrustumLeft + FrustumAsymmetry, FrustumRight + FrustumAsymmetry, FrustumBottom, FrustumTop, NearClipDistance, FarClipDistance); The left eye view is symmetric. Not virtual pure for compatiblity reasons. Reimplemented in SoStereoCamera. Sets the stereo offset (the distance of each eye from the camera position). The right eye is moved plus offset and the left eye is moved minus offset. Default is 0.7. The default can be set using OIV_STEREO_OFFSET environment variable. Reimplemented in SoStereoCamera. Sets the camera to view the region defined by the given bounding box. The near and far clipping planes will be positioned the radius of the bounding sphere away from the bounding box's center. See note about bounding boxes in the sceneRoot version of this method. Sets the camera to view the scene defined by the given path. The near and far clipping planes will be positioned slack bounding sphere radii away from the bounding box's center. A value of 1.0 will make the near and far clipping planes the tightest around the bounding sphere. See note about bounding boxes in the sceneRoot version of this method. Sets the camera to view the scene rooted by the given node. The near and far clipping planes will be positioned slack bounding sphere radii away from the bounding box's center. A value of 1.0 will make the near and far clipping planes the tightest around the bounding sphere. The node. Warning: The SoGetBoundingBoxAction will call ref() and unref() on the specified node. If the node's reference count before calling viewAll() is zero (the default), the call to unref() will cause the node to be destroyed. The ratio of camera viewing width to height. This value must be greater than 0.0. There are several standard camera aspect ratios defined in SoCamera.h. The distance from the camera viewpoint to the far clipping plane. The distance from the viewpoint to the point of focus. This is typically ignored during rendering, but may be used by some viewers to define a point of interest. The distance from the camera viewpoint to the near clipping plane. The orientation of the camera viewpoint, defined as a rotation of the viewing direction from its default (0,0,-1) vector. The location of the camera viewpoint. Defines how to map the rendered image into the current viewport, when the aspect ratio of the camera differs from that of the viewport. Use enum ViewportMapping. Default is ADJUST_CAMERA.
https://developer.openinventor.com/refmans/latest/RefManCpp/class_so_camera.html
CC-MAIN-2021-25
refinedweb
1,402
50.43
C++ Tutorial Multi-Threaded Programming II Part A Native Thread for Win32 - 2017 Microsoft Windows operating system's support for multithreaded programming.Let's look at the simple example. The main thread spawns a new thread to increment the myCounter inside myThread function, while the main thread keeps waiting for a character input (getchar()) from the user, and prints out counter value whenever we type other than 'q' character: To use Windows multithreading functions, we must include <windows.h> in our program. To create a thread, the Windows API supplies the CreateThread( ) function. Each thread has its own stack (see thread vs processes). You can specify the size of the new thread's stack in bytes using the stackSize parameter which is the 2nd argument of CreateThread( ) function in the example below. If this integer value is zero, then the thread will be given a stack that is the same size as the creating thread. #include <windows.h> #include <iostream> DWORD WINAPI myThread(LPVOID lpParameter) { unsigned int& myCounter = *((unsigned int*)lpParameter); while(myCounter < 0xFFFFFFFF) ++myCounter; return 0; } int main(int argc, char* argv[]) { using namespace std; unsigned int myCounter = 0; DWORD myThreadID; HANDLE myHandle = CreateThread(0, 0, myThread, &myCounter;, 0, &myThreadID;); char myChar = ' '; while(myChar != 'q') { cout << myCounter << endl; myChar = getchar(); } CloseHandle(myHandle); return 0; } The output is: 0 868171493 1177338657 3782005161 4294967295 4294967295 ... Each thread of execution begins with a call to a function, called the thread function, within the creating process. The 3rd argument of CreateThread( ) function, myThread is that thread function. Execution of the thread continues until the thread function returns. The address of this function (that is, the entry point to the thread) is specified in threadFunc. By typing a character 'q', we can end the program. The most basic Windows applications start with a single thread. The function call we use to create a child thread is CreateThread(). The following syntax shows the parameters passed to CreateThread(). HANDLE WINAPI CreateThread( _ );. - lpStartAddress [in] A pointer to the application-defined function to be executed by the thread. This pointer represents the starting address of the thread. -. The return value from the function call is a handler for the thread, which is a different construct than the thread ID. When the call was unsuccessful, it returns 0. With the exception of the address of the function to execute, all of the parameters will take default values if they are provided the null. The following code shows how to create a child thread using the CreateThread(). The call to GetCurrentThreadId() returns an integer ID for the calling thread. It also captures the ID of the created thread. The threadID is not very useful since most functions take the thread handle as a parameter. #include <Windows.h> #include <stdio.h> DWORD WINAPI mythread(__in LPVOID lpParameter) { printf("Thread inside %d \n", GetCurrentThreadId()); return 0; } int main(int argc, char* argv[]) { HANDLE myhandle; DWORD mythreadid; myhandle = CreateThread(0, 0, mythread, 0, 0, &mythreadid;); printf("Thread after %d \n", mythreadid); getchar(); return 0; } Output is: Thread after 6784 Thread inside 6784 CreateThread() tells the OS to make a new thread. But it does not set up the thread to work with the libraries provided by the developer environment. In other words, though Windows creates the thread and returns a handle to that thread, the runtime libraries haven't set up the thread-local data structures that they need. So, instead of calling CreateThread(), we should use the calls by the runtime libraries. The two recommended ways of creating a thread are the calls _beginthread() and _beginthreadex(). When using _beginthread() and _beginthreadex(), we must remember to link in the multithreaded library. This will vary from compiler to compiler. These two functions take different parameters: uintptr_t _beginthread( void( *start_address )( void * ), unsigned stack_size, void *arglist ); uintptr_t _beginthreadex( void *security, unsigned stack_size, unsigned ( *start_address )( void * ), void *arglist, unsigned initflag, unsigned *thrdaddr ); Parameters - start_address Start address of a routine that begins execution of a new thread. For _beginthread, the calling convention is either __cdecl or __clrcall; for _beginthreadex, it is either __stdcall or __clrcall. - stack_size Stack size for a new thread or 0. - arglist Argument list to be passed to a new thread or NULL. - security Pointer to a SECURITY_ATTRIBUTES structure that determines whether the returned handle can be inherited by child processes. If NULL, the handle cannot be inherited. - initflag Initial state of a new thread (0 for running or CREATE_SUSPENDED for suspended); use ResumeThread to execute the thread. - thrdaddr Points to a 32-bit variable that receives the thread identifier. Might be NULL, in which case it is not used. There is another difference between these two functions other than the parameters they take. A thread created by _beginthread() will close the handle to the thread when the thread exits, while the handle returned by _beginthreadex() will have to be explicitly closed by calling CloseHandle(), which is a similar to the detached thread in POSIX. As we see in the description of the two functions above, they are also differ by the type of function that the thread execute: _beginthread() is a void function and uses the default calling convention __cdecl, while _beginthreadex() returns an unsigned int and uses the __stdcall calling convention. The _beginthread() and _beginthreadex() functions return handles to the newly created threads. But the actual return type of the function call is uintptr_t which has to be type cast to a HANDLE before it can be used in function calls that expect an object handle. The following example creates threads using the three different ways: #include <Windows.h> #include <process.h> #include <stdio.h> DWORD WINAPI mythreadA(__in LPVOID lpParameter) { printf("CreateThread %d \n", GetCurrentThreadId()); return 0; } unsigned int __stdcall mythreadB(void* data) { printf("_beginthreadex %d \n", GetCurrentThreadId()); return 0; } void mythreadC(void* data) { printf("_beginthread %d \n", GetCurrentThreadId()); } int main(int argc, char* argv[]) { HANDLE myhandleA, myhandleB, myhandleC; myhandleA = CreateThread(0, 0, mythreadA, 0, 0, 0); myhandleB = (HANDLE)_beginthreadex(0, 0, &mythreadB;, 0, 0, 0); WaitForSingleObject(myhandleB, INFINITE); myhandleC = (HANDLE)_beginthread(&mythreadC;, 0, 0); getchar(); return 0; } Output is: _beginthreadex 5256 CreateThread 5924 _beginthread 4292 The call to WaitForSingleObject() waits for an object to signal its readiness. In other words, the routine passes the handle to a thread and waits for that thread to terminate. Threads created in main() will not continue to run after the main thread exits. So, the main thread must wait for the threads it created to complete before it exits the main() function. It does this by calling function WaitForMultipleObjects(). Calling _beginthread() looks more convenient because it takes fewer parameters and clean up the handle after the thread exits, however, it is better to use _beginthreadex(). Calling _beginthreadex() avoids a difficulty with _beginthread(). If the thread terminates, the handle returned by the call to _beginthread() will be invalid or even reused. Therefore, it is impossible to query the status of the thread or even be confident that the handle to the thread is a handle to the same thread to which is originally pointed. The following example demonstrates this issue: #include <Windows.h> #include <process.h> #include <stdio.h> void mythreadA(void* data) { printf("mythreadA %d \n", GetCurrentThreadId()); } void mythreadB(void* data) { volatile int i; // Most compiler won't eliminate the loop // since i is volatile for (i = 0; i < 100000; i++) {} printf("mythreadB %d \n", GetCurrentThreadId()); } int main(int argc, char* argv[]) { HANDLE myhandleA, myhandleB; myhandleA = (HANDLE)_beginthread(&mythreadA;, 0, 0); myhandleB = (HANDLE)_beginthread(&mythreadB;, 0, 0); WaitForSingleObject(myhandleA, INFINITE); WaitForSingleObject(myhandleB, INFINITE); return 0; } Output is: mythreadA 5912 mythreadB 3092 The mythreadA() terminates quickly and may have already terminated by the time that the main thread reaches the call to create the second thread. If the first thread has terminated, the handle to the first thread may be reused as the handle to the second thread. Queries using the handle of the first thread might succeed, but they will work on the wrong thread. The calls to WaitForSingleObject() may not be using a correct or valid handle for either of the threads depending on the completion time of the threads. Though it is not clear from the output, still, there is a potential for things not going to work as we expect. The following example for using _beginthreadex() is equivalent to the previous code. Thread created by _beginthreadex() need to be cleaned up by calling CloseHandle(). So, the calls to WaitForSingleObject() are certain to get the correct handles: #include <Windows.h> #include <process.h> unsigned int __stdcall mythreadA(void* data) { return 0; } unsigned int __stdcall mythreadB(void* data) { volatile int i; // Most compiler won't eliminate the loop // since i is volatile for (i = 0; i < 100000; i++) {} return 0; } int main(int argc, char* argv[]) { HANDLE myhandleA, myhandleB; myhandleA = (HANDLE)_beginthreadex(0, 0, &mythreadA;, 0, 0, 0); myhandleB = (HANDLE)_beginthreadex(0, 0, &mythreadB;, 0, 0, 0); WaitForSingleObject(myhandleA, INFINITE); WaitForSingleObject(myhandleB, INFINITE); CloseHandle(myhandleA); CloseHandle(myhandleB); return 0; } And the output: mythreadA 5860 mythreadB 5312 There are several ways to make a thread to terminate. But the recommended way is for the thread to exit the function that it was instructed to run. In the following example, the thread will print out its ID and then exit: DWORD WINAPI mythreadA(__in LPVOID lpParameter) { printf("CreateThread %d \n", GetCurrentThreadId()); return 0; } It is also possible to make threads to terminate using the ExitThread() or TerminateThread(). - But these function calls are not recommended since they may leave the application in an unspecified state. The thread does not get the chance to release any held mutexes or free any other allocated resources. - They also don't give the run-time libraries the opportunity to clean up any resources that they have allocated for the thread. A thread may terminate with a call to _endthread() or _endthreadex(), as long as care is taken to ensure that resources the thread has acquired are appropriately freed. This call (_endthread() or _endthreadex()) needs to match the call that was used to create the thread. If the thread exits with a call to _endthreadex(), the handle to the thread still needs to be closed by another thread calling cloaseHandle(). For a fork-join type model, there will be a master thread that creates multiple worker threads and then waits for the worker threads to exit. There are two routines that the master thread can use to wait for the worker to complete: WaitForSingleObject() or WaitForMultipleObjects(). These two functions will wait either for the completion of a single thread or for the completion of an array of threads. The routines take the handle of the thread as a parameter together with a timeout value that indicates how long the master thread should wait for the worker thread to complete. Usually, the value INFINITE will be appropriate. The following code demonstrates the code necessary to wait for a single thread to complete: ForSingleObject(myhandle[0], INFINITE); WaitForSingleObject(myhandle[1], INFINITE); CloseHandle(myhandle[0]); CloseHandle(myhandle[1]); getchar(); return 0; } Output from the run is: Thread 4360 Thread 1368 The following code is equivalent to the previous one. But this example is using WaitForMultipleObjects(). - The first parameter to the function call is the number of threads that are to be waited for. - The second parameter is a pointer to the array of handles to these threads. - The third parameter is a boolean. If true, it indicates that the function should return when all the threads are complete. If false, it indicates the function should return on the completion of the first worker thread. - The last parameter is the length of time that the master thread should wait before returning anyway. ForMultipleObjects(2, myhandle, true, INFINITE); CloseHandle(myhandle[0]); CloseHandle(myhandle[1]); getchar(); return 0; } Output is: Thread 4712 Thread 4244 Even after a thread created by calling _beginthreadex has exited, it will continue to hold resources. These resources need to be freed by calling the CloseHandle() function on the handle to the thread. The following example demonstrates the complete sequence of creating a thread, waiting for it to complete, and then freeing its resources: , 0, 0); WaitForSingleObject(myhandle, INFINITE); CloseHandle(myhandle); return 0; } Output is: Thread 4272 A suspended thread is the one that is not currently running. Threads can be created in the suspended state and then started later. If a thread is in the suspended state, then the call to start the thread executing is ResumeThread(). It takes the handle of the thread as a parameter. There is a SuspendThread() call that will cause a running thread to be suspended. This call is expected to be used only by tools such as debugger. Suspending a running thread may lead to problems if the thread currently holds resources such as mutexes. The following code demonstrates the creation of a suspended thread and then calling ResumeThread() on that thread. The code uses a call to getchar(), which waits for the enter key to be pressed, to separate the creation of the thread from the act of resuming thread: , CREATE_SUSPENDED, 0); getchar(); ResumeThread(myhandle); getchar(); WaitForSingleObject(myhandle, INFINITE); CloseHandle(myhandle); return 0; } Output we get after we hit the return key: (hit Return key) Thread 4580 The suspended state of the thread is handled as a counter, so multiple calls to SuspendThread() need to be matched with multiple calls to ResumeThread(). Each thread of execution has associated with it a suspend count.( ). Many of the Windows API functions return handles. As we saw from the earlier discussion of type casting, these are really just unsigned integers. However, they have a particular purpose. Windows API calls that return handles have actually caused a resource to be created within the kernel space. The handle is just an index for that resource. When the application has finished with the resource, the call to CloseHandle() enables the kernel to free the associated kernel space resources. Resources with handles can be shared between processes. Once a resource exists, other processes can open a handle to that resource or duplicate an existing handle to the resource. It is important to know that the handle of a kernel resource makes sense only within the context of the process that has access to the resource. Passing the value of the handle to another process does not enable the other process to get access to the resource. The kernel needs to enable access to the resource and provide a new handle for the existing resource in the new process. Some functions do not return a handle. For these functions, there is no associated kernel resource. So, it is not necessary to call CloseHandle() once the resource is no longer needed. Threading with QT5: - QThreads - Introduction - QThreads - Creating Threads - QThreads - Priority - QThreads - QMutex - QThreads - GuiThread - QThreads - wait() - QTcpServer - Client and Server using MultiThreading - QTcpServer - Client and Server using QThreadPool - Asynchronous QTcpServer - Client and Server using QThreadPool
http://www.bogotobogo.com/cplusplus/multithreading_win32A.php
CC-MAIN-2017-26
refinedweb
2,472
51.89
I'm still very wet behind the ears with C++, please bear with.I'm still very wet behind the ears with C++, please bear with.Code:#include <iostream> using namespace std; float dividethesenumbers(int x, int y){ return x/y; } int main() { int x; int y; cout << "2 numbers to be divided. \n First number: "; cin >> x; cout << "Second number: "; cin >> y; cout << dividethesenumbers(x,y) << endl; system("pause"); return 0; } I was going over function prototypes, to further remember the syntax, and came accross something I can't quite figure out. Using the above code, I compiled and used 22 for x and 7 for y. (Pi) Instead of getting 3.14......, I got 3. dividethesenumbers is supposed to return a float, right? I know I used integers for x and y as input but I thought the function would return the type I told it to. I know the fix is to replace the int x, int y with float x, float y (as well as in main()) but I don't understand why my function won't return the type I ask.
https://cboard.cprogramming.com/cplusplus-programming/65628-supposed-return-float-but-doesnt.html
CC-MAIN-2017-09
refinedweb
186
79.4
The Arab Fall. Will there finally be a true Arab Spring. Blame not the Religion or Faith, a criminal does not need a reason A desire to fight. We all just have to accept that some folks have it. The situation in Syria is escalating. Jihadists are ending up with more weapons. Hillary just took the blame for what a President should accept and a counter strike is eminent. Over toward Alleppo bad things are a foot. And that stinks. Think about though, it is not a them against us problem. The problem is with lack of responsibility withing these areas. These are criminals perpetuating these acts. And then Hillary comes along and takes responsibility instead of our president. Not good and here is why:. In order to make more clear this violence of the Arab Fall let us look inside to the threat that is there, not Just Muslim and American but universal. When I was young and playing in the school playground we would start a game. Whoever felt tough would draw a line in the dirt. And then say to someone “I dare you to cross that line”. Somebody had to do it. Maybe a grudge, maybe competition or maybe to move up in the social order. In my youth we fought a lot. I can hold my nose down flat, the bones to keep it rigid were busted so often they did not fully develop. Of course legitimate football and basketball and wrestling added their own. With childhood friends we count and reminisce over our scars. Many wounds have scars worse than they needed to be, cause we hid them from adults so as not to get in trouble. That is what Hillary did and ultimately it will make matters worse. We wanted to fight so we would make up reasons. As we got older injuries became more severe so we generally stop doing it. Plus our coaches would get plenty pissed off if we were hurt for game. So by about the time of mustaches and drinking and girls we found better things to do. Fighting just was not the same and so we moved on other things. Fighting just lost the appeal. When will terrorism loose its appeal. What down right get on our knees thankful we should be that we are not sick. Please do not understand illness to ever be associated with faith. It is the antagonist of illness. I saw awhile back that a supposedly Christian minister of some sort got people all excited and burned some books. They were not pornography, they were not illegal and from what I could tell they were not immoral. My understanding is that they were another religion’s books of faith. That sounds doggone near normal these days. But still the notion is disgusting and anti-Christ as it could be. Man I have trouble keeping up with just reading all the books, I definitely don’t have time to go burn them in order to hurt another human soul. Now fervent religious belief is a good thing. As long as the belief system does not go haywire and start preaching anti belief. My beliefs are my own. I have places to worship that fit my faith. I do some preaching. And I never shy from a good argument about my belief. My beliefs are strong. But there is nothing in my belief that allows me to hurt another with a different belief, because of their belief. My vision of God is what we call “Omnipotent”. If God wanted to He could tell me to hate and be hurtful. So just what God is telling these folks to be violent toward one another? People who profess a Muslim faith have just violently killed and otherwise seriously hurt people they did not know and they claim faith. It just does not rub well with me. Something is out of synchronization. How does one justify violence? My previous story of fighting was meant to work as a metaphor. Some folks just like to fight and do mean vicious things to others. I tell you as a child I did. Sometimes there is something worth fighting for. Many a time I had good reason to fight, I just can’t remember a single one ;) Most adults contain the fight or flight reaction in constructive ways. But some just can’t. Man is not a cattle. Through faith they cannot be led to do wrong, but through weakness they can. Silver linings abound, but not if we buy into nutcases having a reason to commit atrocities Our brethren who hide out and rise to the surface only to do damage are extremely violent. I wonder if they have a passage that includes going forth and raping. That is some sick behavior. No, I think we all have to conclude that there is no faith that commands people to act in such a manner. We have to conclude that there is sickness that lies within and stop looking for reason from without. If you ask a scorpion why he stings things he will say “because I am a scorpion”. If you ask these people seriously why they do what they do, the only true answer is because they are sick. If they blame it on a religion or faith that is coming from the inside out and not from faith to within. A good thing to remember as horrible violence comes from within a man, it is also true that tremendous Love also comes from within. Popular Common sense is so uncommon because common sense is so uncommon. Hate begets hate, violence begets violence and indifference begets indifference. It is a sad fact that, as long as these atrocities are allowed to go on, they will go on and escalate. The masses that KNOW these things happening are wrong need to stand up against these bullies. People sit by idly refusing to do anything about it. This only encourages the bullies (and those who are so unaccepting of others beliefs) to continue doing as they have always done. We as a country and as a people are so busy apologizing for everything, making sure no one gets their feelings hurt and trying to be politically correct. The elephant in the room is this: apologizing for everything, not hurting anyone's feelings occasionally and being politically correct are all INCORRECT! America used to have a pair. Now we have a government that wants us to "lose our superpower status gracefully like England did". Will we fix it before it's too late? I doubt it. THANKS FOR TAKING UP THE CHALLENGE TO REFLECT ON A CHALLENGING TOPIC. The potential for all kinds of behavior does rests inside each of us, and as long as we can take ownership of all our potential, then the probability for acting out diminishes. When I split off from all of who I am, and I do that by labeling some parts of myself as good and some parts as bad, then the war begins. I think it is an excellent idea for us, as so-called Christians, to continue to reflect on all the crazy ass crimes we have perpetrated on non-Christians for thousands of years. We are no better than any other sect or group who seems to support violence as a way to resolve religious differences. I think it is equally excellent, as so-called Christians, to reflect on the crazy ass crimes we have perpetrated on other Christians as well. It is all NUTS. It represents the splitting of self into good and bad parts which we do so well and have done so well from the beginning of time. I am not sure what purpose that splitting serves, but it definitely does not promote an inidividual or a group being accountable or taking responsibility for the way the individual or the group treat other people either alike or different. Again, thank you for giving me an opportunity to think and reflect. Great hub Vern Marvelous, both the Hub and the conversation. Mr. Happy (I call him White Wolf) is one of my favorite and greatly respected Hubbers. I am so pleased to see the two of you engaged in such good and deep conversation. Coming back again later to comment properly when I have more time. :) Theresa - Haha!! I am glad You enjoyed my rant, Mr. Eric Dierker ... no holds barred with me (lol!). "But let us be fair, you and I spend countless hours forming a position that is correct and justifiable. Some are incapable."- So, is that it? We just need to sit everyone down to some private and concentrated thinking? Why are some people incapable to see common sense? Why is common sense not so common? What would You say? And thank You for the discussion and the article. "Many a time I had good reason to fight, I just can’t remember a single one." - I do not think fighting is bad. I think it depends on the intent. I practiced marital arts for several years. I attended competitions. I have taken a kick to the head and I have given some in return (lol). I have no issue with two people who decide for whatever reason that they want to fight, as long as they do not directly affect and/or involve others. We have boxing as a sport too, no? I do not stand bullies for example and so, there have been times in my life where I put myself in between bullies and their targets, simply stating that: "To get to him, You first get by me." End of the conversation. No fight in any of those cases but I was ready to; I am pretty sure that is why bullies back-off too. I even witnessed a police officer push a protester around, several months back and I had a word with that police officer's Sergent and told him too that if he wants to start pushing, we can certainly get the pushing going but that is not what I was there for and I did not think that he wanted matters to escalate either: the pushing stopped ... I don't really know what to say. I consider myself a pacifist. We can sit down and smoke the pipe but when someone gets pushy, disrespectful and/or abusive then, the tone will change and the ugly wolf comes out. Some people of the First Nations say that we are like a mirror to one another. Thus, if You are kind to me, You will receive love and kindness but if You bring violence and hatred to me, as the saying goes: "You live by the gun, You die by the gun". I do not believe in turning the other cheek. I believe in mistakes and so I believe in forgiveness. Turning the other cheek is too extreme for me - some people will take You for a punching bag if You keep turning the cheek ... it all depends on each circumstance, I suppose. Violence over beliefs is not warranted in my opinion. Or insults ... insult me all You want and ask me if I care after ... I think some people should try to build a thicker skin, while other people should try to respect the wishes and beliefs of others a little more. If we each give-in a little, perhaps we can meet in the middle. All the best! 10
https://hubpages.com/religion-philosophy/The-Arab-Fall-Muslim-versus-American-The-threat-is-within-each-of-us
CC-MAIN-2018-39
refinedweb
1,920
74.19
Objective In this article, I am going to show you 1. How to insert an image from ASP.Net application to SQL Server using LINQ to SQL. 2. How to retrieve image from SQL Server data base using LINQ to SQL and display to an Image control. Block Diagram of solution Description of table For my purpose, I have created a table called ImageTable. 1. Id is primary key. 2. Name column will contain name of the image file. 3. FileSource column will contain binary of image. Type of this column is image. Create ASP.Net Web Application Open visual studio and from File menu select New Project and then from Web tab select new web application. Give meaningful name to your web application. Create DBML file using LINQ to SQL class. For detail description on how to use LINQ to SQL class read HERE 1. Right click on the project and select add new item. 2. From DATA tab select LINQ to SQL Class. 3. On design surface select server explorer. 4. In server explorer and add new connection. 5. Give database server name and select database. 6. Dragged the table on the design surface. Once all the steps done, you will have a dbml file created. Design the page 1. I have dragged one FileUpload control and a button for upload purpose. 2. One text box. In this text box user will enter Id of the image to be fetched. 3. One button to fetch the image from database. 4. One Image control to display image from database. Default.aspx Saving image in table On click event of Button 1 Image upload will be done. In this code 1. First checking whether FileUplad control contains file or not. 2. Saving the file name in a string variable. 3. Reading file content in Byte array. 4. Then converting Byte array in Binary Object. 5. Creating instance of data context class. 6. Creating instance of ImageTable class using object initializer. Passing Id as hard coded value. Name as file name and FileSource as binary object. Retrieving Image from table On click event of button2 Image will be fetched of a particular Id. Image Id will be given by user in text box. In above code, I am calling a generic HTTP handler. As query string value from textbox1 is appended to the URL of HTTP handler. To add HTTP handler, right click on project and add new item. Then select generic handler from web tab. In above code, 1. Reading query string in a variable. 2. Calling a function returning ShowEmpImage returning Stream. 3. In ShowEmpImage , creating object DataContext class . 4. Using LINQ fetching a particular raw from table of a particular ID. 5. Converting image column in memory stream. In this case FileSource column is containing image. 6. Converting stream into byte array. 7. Reading byte array in series of integer. 8. Using Output stream writing the integer sequence. Running application For your reference entire source code is given below , Default.aspx.cs 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.Web.UI; 6 using System.Web.UI.WebControls; 7 using System.Data.Linq; 8 using System.IO; 9 10 namespace uploadingImageusingLInqtoSQl 11 { 12 public partial class _Default : System.Web.UI.Page 13 { 14 protected void Page_Load(object sender, EventArgs e) 15 { 16 17 } 18 19 protected void Button1_Click(object sender, EventArgs e) 20 { 21 if (FileUpload1.HasFile && FileUpload1.PostedFile.ContentLength > 0) 22 { 23 string fileName = FileUpload1.FileName; 24 25 byte[] fileByte = FileUpload1.FileBytes; 26 Binary binaryObj = new Binary(fileByte); 27 DataClasses1DataContext context = new DataClasses1DataContext(); 28 context.ImageTables.InsertOnSubmit( 29 new ImageTable { Id = “xyz”, 30 Name = fileName, 31 FileSource = binaryObj }); 32 context.SubmitChanges(); 33 34 35 } 36 } 37 38 protected void Button2_Click(object sender, EventArgs e) 39 { 40 41 42 Image1.ImageUrl = “~/MyPhoto.ashx?Id=”+TextBox1.Text; 43 44 } 45 46 47 } 48 } 49 MyPhoto.ashx.cs 1 using System; 2 using System.Collections.Generic; 3 using System.Linq; 4 using System.Web; 5 using System.IO; 6 using System.Web.UI; 7 using System.Web.UI.WebControls; 8 9 10 namespace uploadingImageusingLInqtoSQl 11 { 12 /// <summary> 13 /// Summary description for MyPhoto 14 /// </summary> 15 public class MyPhoto : IHttpHandler 16 { 17 18 public void ProcessRequest(HttpContext context) 19 { 20 21 string id = context.Request.QueryString[“Id”]; 22 context.Response.ContentType = “image/jpeg”; 23 Stream strm = ShowEmpImage(id); 24 byte[] buffer = new byte[4096]; 25 int byteSeq = strm.Read(buffer, 0, 4096); 26 while (byteSeq > 0) 27 { 28 context.Response.OutputStream.Write(buffer, 0, byteSeq); 29 byteSeq = strm.Read(buffer, 0, 4096); 30 } 31 } 32 33 public Stream ShowEmpImage(string id) 34 { 35 DataClasses1DataContext context1 = new DataClasses1DataContext(); 36 var r = (from a in context1.ImageTables where a.Id == id select a).First(); 37 return new MemoryStream(r.FileSource.ToArray()); 38 39 } 40 public bool IsReusable 41 { 42 get 43 { 44 return false; 45 } 46 } 47 } 48 } Thanks for reading. I hope this post is useful. Happy Coding. 31 thoughts on “Inserting and Retrieving Image using LINQ to SQL from ASP.Net Application” Hello Dhananjay Kumar, Thanq Dude Working Fine And Good Thanq So Much It is really usefull to the beginners Thank you, this helpful for me . pls send me code in .net 2010 using silverlight that how to store the images in folder. my email is mistryjayendra96@yahoo.com very nice BOSS…….. Good Luck…….. nice sir..thax a lot…..i m facing prob to retrive image..hope this can do my work easy Hello! Thank you very much for this code. Unfortunately, I always get the following error: String or binary data would be truncated.\r\nThe statement has been terminated. I tried smaller images and the problem remains. Please advise! My e-mailaddress: jangroven@gmail.com (The problem occurs at: context.SubmitChanges(); (line 32 on Default.aspx.cs) THANKS A LOT.;……..SIL This code is good,can you please explain how we can alter the image? Great Example !!! Thanks a Lot I did the same example and it works fine, no error cach, nothing. But I never get the Image on the Image control. Any idea?, please I will be very grateful. Thanks Dhanyawad. thanks alot.. i want to resize image size ?????? thankyou this is helpfl for me……….. Nice Article. thanks dhananjay very good post Glad it is useful. Thanks DJ Everyone loves what you guys are up too. This sort of clever work and exposure! Keep up the great works guys I’ve added you guys to my own blogroll. I every time spent my half an hour to read this web site’s content everyday along with a cup of coffee. thanks thanks so much ^^ thanks a lot ……… After exploring a number of the articles on your blog, I honestly like your technique of blogging. I book marked it to my bookmark site list and will be checking back in the near future. Take a look at my web site too and let me know what you think. Ashley and grow your sociable existence. Ashley can considerably improve your relevance in addition to believability. Clients can easily Ashley via dozens of affordable providers. Really userfull article nice job… thanks a lot Is this Code Works For u…. because Binary() doesnt take parameters…..
https://debugmode.net/2010/05/10/inserting-and-retrieving-image-using-linq-to-sql-from-asp-net-application/
CC-MAIN-2016-36
refinedweb
1,216
62.04
,416 core java,JDBC,JSP and servlet related material to prepare thoroughly. Thanx in advance Sir/Madam, I need Core java, J2EE interview questions. I am in java and j2ee field since last 2 years. Thanks. Kindly do the needful. Regards, Ashvini Sir, I need J2EE interview questions. I am in java and j2ee field since last 3 years. Thanks plz send me java/j2ee/servlets/hibernate/spring/webwork questions. Hi, please send me interview questions in core java,jdbc,servlet,jsp,struts The saddest part of all these feedback(s) are most of the respondents are simply asking "send me Java* ... questions for n+ yrs".They are not actually adding anything other than that the list goes on increasing. I think they should ask some pertinent questions based on the areas they are working OR intending to work.One way of learning things is by asking Questions to oneself.Experts/Gurus may help us find answers or show us different aspects of things.Should they feed us with the Questions? Regards, please send java/j2ee questions for 2 yrs exp. please send j2ee,struts,hibernate,ejb,xml JDBC interview questions for 2 year exp. Hi, please send me interview questions in core java,jdbc,servlet,jsp,struts which is generally asked for 2+ years experience Hi, please send me interview questions in core java,jdbc,servlet,jsp,struts which is generally asked for 2+ years experience and aslo ibm,satyam interview questions. Hello Sir, Pls send me Java 2+ year Questions. Thank You i need structs question&answer paper Hi, please send me interview questions in core java,jdbc,servlet,jsp,struts which is generally asked for 2+ years experience. Hi, Please send the interview questions from CoreJava,Jsp,Servlets,JDBC,Struts which are generally being asked with 2 years experience. It will be a great help.Can u do this for me. Need interview questions on Javascript Another gripe that I have with this blog is that the indentation of the Main.java source file that I just submitted is completely lost. All lines appear without any leading whitespace, even though there *IS* leading whitespace in lines of my source file. I have some some suggestions for improving the answer for Q6. Please refer to the attached source file, and read the comments at the top for all of the gory details. // Main.java // dennis bednar 2006-07-14 // // Lessons: // While researching this topic (question #6 of 30 from this article): // // // // superclass type, // the casting is performed automatically. //----------------------------------------------------------- // // Definition: // RHS = Right Hand Side of an = sign of an assignment statement. // LHS = Left Hand Side of an = sign of an assignment statement. // // ---------------------------------------------------------- // // MORE INFO regarding A (answer) THAT THE ABOVE ARTICLE DOES NOT SAY: // // (A minor issue): // First of all, the above snippet won't even compile, due to a lack // of assigning any value to a. The RHS a gets a compile time error // on the "b = (Customer) a;" assignment. // This problem is illustrated in Simple1.java file and is fixed // in the Simple2.java file. // The simplest way to fix this problem, and what the Yakov article should // have said is this: // Object a = null; Customer b; b = (Customer) a; // // (A Major issue): // Furthermore, when you do the // b = (Customer) a;" // the a on RHS (right hand side) being cast has to be a null OR a // reference to a Customer object or an object which is a sub-class of Customer, // otherwise you will get a ClassCastException at run-time. // (exception happens when a != null, but a references // an object that is not a Customer nor a sub-class of Customer). // Please note that the Main.java code will compile fine, though. // // For example, in test1() is okay at run-time, but test2() gets // a ClassCastException. // // In test3() we test with RHS being a null to show that no // ClassCastException problem will occur like in test2(). // // In test4() we try a variant of test1(), where we use a sub-class of // Person, by using the Professor class (Person -> Professor, where // Base -> Derived). // // // ------------------------------------------------------------- // // SHORT REVISED SUMMARY ANSWER (what Yakov should have answered) // // A. If you assign a superclass object to a variable of a subclass's // data type, you need to do explicit casting. For example: // Object a = null; Customer b; b = (Customer) a; // When you assign a subclass to a variable having a superclass type, // the casting is performed automatically. // // Furthermore, in order to be able to do the assignment, the RHS (a) // must be either a null, a reference to a Customer object, or a // reference to an object which is a sub-class of Customer. Otherwise // at run-time, you will get a ClassCastException. // (exception happens when a != null, but a references // an object that is not a Customer nor a sub-class of Customer). // public class Main { public static void main( String[] argv ) { // NB: we call test3() *before* test1() because if we called // test3() last, we would never get there, since // test2() would halt the program with an Exception // We added test3() last, and I didn't want to revise // any comments. // // Historically, while writing this module, I wrote // test1..test4 in that order. // Similarly, we call test4() before test1() for similar // reasons. test3(); test4(); test1(); test2(); } // test1 runs okay without any problems // no problems casting (no ClassCastException at run time) private static void test1() { Object root = new Object(); Person p = new Person(); // will print ok, since p ISA person System.out.println( "test1A: Person: " + p ); root = p; // okay to assign subclass to superclass wo cast // p = root; // COMMENT_OUT: cuz compile time error wo cast // but to assign super to sub, requires a cast // *and* root must be a Person or sub-class of Person, // otherwise ClassCastException // Now, since root ISA Person, this is okay. p = (Person) root; System.out.println( "test1B: cast test: " + p ); } // Test2() gets a ClassCastException. // In test2(), root is an Object, so "p = (Person) root" will get // ClassCastException at run-time. This proves that Java does // a run-time sanity check to prevent garbage references from // being assigned into variables (this helps to prevent other // future run-time errors ahead of time, which is a very good // feature of Java). // private static void test2() { Object root = new Object(); Person p = new Person(); // will print OK, since p ISA person System.out.println( "test2A: Person: " + p ); p = (Person) root; // ClassCastException, even with cast // won't even get here, so no way to try this experiment! //System.out.println( p ); // exception since p !ISA person } // test3 executes OK. It is based on test2() except that // we assign RHS of root and p variables with null instead // of calling new(). Unlike test2(), there is // no ClassCastException because the RHS (root) of this statement: // p = (Person) root; // is null. private static void test3() { Object root = null; Person p = null; // will print OK (as null), since p ISA null value System.out.println( "test3A: Person: " + p ); p = (Person) root; // !ClassCastException since root==null // we will now get here, so we can try this experiment System.out.println( "test3B:" + p ); // prints null } // test4 runs okay. // variant of test1, except that p is a Profess (a sub-class of Person) private static void test4() { Object root = new Object(); Person p = new Professor(); // will print ok, since p ISA Person System.out.println( "test4A: Person: " + p ); // but to assign super to sub, requires a cast // *and* root must be a Person or sub-class of Person, // otherwise ClassCastException // since root ISA Person, this is okay p = (Person) root; System.out.println( "test4B: cast test: " + p ); } } // Person: a simple empty class without any instance vars" class Person { public String toString() { return "PERSON(SIMPLE)"; } } // a sub-class of Person, used for test4(). class Professor extends Person { } Strange: 2 posts earlier, when I pasted my entire source file this blog erased part of the code that I had submitted. The (generics style declaration of: <, Integer, > (without commas) strings were translated into nothing mysteriously. This is the required for List, ArrayList, and LinkedList. Here are what 2 of the lines should read: List{Integer} al = new ArrayList{Integer}(); List{Integer} ll = new LinkedList{Integer}(); In the above, change the { (left brace) to < (less than) In the above, change the } (right brace) to > (greater than). There is something wacky about this web site that is preventing me from submitting EXACTLY what I typed (less than, Integer, greater than). The preview engine is doing some mysterious translation on text input that begins with a < sign and ends with a > sign. PS: here's the output of running the Main.java program for my previous post (which I forgot to include): C:\temp\java\ArrayListVsLinkList>del *.class C:\temp\java\ArrayListVsLinkList>javac -cp . -Xlint:unchecked -source 1.5 Main.java C:\temp\java\ArrayListVsLinkList>java -cp . Main ArrayList=[5, 7, 9, 11] LinkList =[5, 7, 9, 11] ArrayList[0]=5 ArrayList[1]=7 ArrayList[2]=9 ArrayList[3]=11 LinkedList[0]=5 LinkedList[1]=7 LinkedList[2]=9 LinkedList[3]=11 ArrayList=[5, 77, 9, 11] LinkList =[5, 99, 9, 11] I think the answer to Q26 can be either ArrayList or LinkedList, since both support indexed operations. List is the interface and both ArrayList and LinkedList are concrete classes of the List interface. Proof (compile with JDK 1.5 for Generics): import java.lang.Integer; import java.util.List; import java.util.ArrayList; import java.util.LinkedList; public class Main { public static void main( String[] argv ) { List al = new ArrayList(); List ll = new LinkedList(); for (int i = 5; i < 13; i += 2 ) { // wrapper integer Integer wi = new Integer( i ); al.add( wi ); // add to end of ArrayList ll.add( wi ); // add to end of LinkedList } // print out both collections System.out.printf("ArrayList=%s\n", al ); System.out.printf("LinkList =%s\n", ll ); // now access them using an array[index] style for (int inx = 0; inx < al.size(); ++inx) { System.out.printf( "ArrayList[%d]=%d\n", inx, al.get(inx) ); } // access them using an array style of index for (int inx = 0; inx < al.size(); ++inx) { System.out.printf( "LinkedList[%d]=%d\n", inx, ll.get(inx) ); } // change ArrayList[1] = 77 // change LinkedList[1] = 99 al.set(1, new Integer( 77) ); ll.set(1, new Integer( 99) ); // print out both collections after modification System.out.printf("ArrayList=%s\n", al ); System.out.printf("LinkList =%s\n", ll ); } } Hi, Immediately I want Java&J2ee Interview Questions in 2 yrs of experience level. Thank U. J.T., I've answered your post over here:... please send j2ee,struts,hibernate,ejb,xml JDBC interview questions for 2 year exp. I found a coupe of questions quite unclear or misleading. Q1: We punish developers who use system out for general classes. Most java programs do not use a console and you reduce the reusability. The logging framework coming with the JDK is exactly designed for this purpose. Or use any other logging framework. Q6: Do you mean primitive data types or object types. It's like the question I once read. "How fast is a CD ROM? If I drive around with it most likely over 100km/h. Or do you mean the interface performance? The maximum read performance? The performance factor on the box? Q10: You can not call a constructor! You can use it but not call it. This is a major difference between a method and a constructor. And your answer implies that you mean the constructor of a parent class not a general call. Q12: This is again misleading. You do not change the OS environment. If you define an environment variable like classpath it simply does not work on Windows environments. What you do is adding it to the known classes of the runtime environment. Q14: Again a question like "What would you use for cutting?". The anser has to be, "It depends on what you want to cut". Better ask for the difference between == and equals. Q16: I simply do not understand. Is it an English sentence? Q28: Ths first part is really misleading because the first part is simply not true. You still nead the garbage collection to get rid of your objects. The only way to minimise is to avoid object creation. Q29: Give a hint that you want two ansers and that you think about threads. It is a nice collection of questions. Regards Haug Don't you think people should already know the answers to those questions before applying for a job? You've given kids with no experience but a faked resume a prime source to cram questions and answers to trick themselves into jobs by writing this, thank you very much for making programmers as a group look bad (by making it possible for even more unqualified people to get programming jobs). hi, I need the type of questions asked in an interview for a job in java/j2ee with about 2 years experience. pls forward the list of questions that can be asked for 2+ years exp in java(core,advanced and j2ee) Hi, please send me 1.5+ year exp java/j2ee,jsp/servlets ,JDBC questions for the interview. Hello Any body out there who can help in getting the objective questions(with answers)for whole java (core and advace and jsp servlet struts ejb) i need objective question for jsp,servlet,xml J2ee Please note : question no [3] is actually [3]is the following a valid statement in java I had actually given the complete URL of this page, the page optimized this to [visit link]. Please interpret this to be the whole URL. Thank you very much. Great Questions set{}!!! ___________________________________________ Would you please consider these questions [1]. is println() of System.out a synchronized method? [2].How are the two following statements different as to the nature of '+' (a)int a=0,b=1; int c = a+b; (b)System.out.println(a+b); (c)System.out.println(""+a+b); [3]is the following a valid statement in java [4]Is it a good practice to return null or should we return a 'zero-length array'? [5]What is the type of null ? [6]When can we throw a new Exception but not explicitly catch it.Is it possible? [7]What is a root-set in Garbage Collection [8]I'm iterating over an iterator drawn from a Vector object.However,meanwhile I remove an element from the same Vector object. Will iteration still be continued, or what will happen? [9].Does Inheritance breaks Encapsulation? [10].Is there any instance/situation in Java, when circular reference is actually is used? If you are planning to hit the job market, you may need to refresh some of the Java basic terms and techniques to prepare yourself for a technical interview. JDJ Enterprise Editor Yakov Fain here offers thirty of the core Java questions that you might expect during the interviews, 20 for mid-level developers and the final ten for senior-level developers. Why not try them and see how well you do? please send java/j2ee,jsp/servlets ,ejb,xml JDBC interview questions for 2 year exp. please send me 1.5+ year exp java/j2ee,jsp/servlets ,JDBC questions for the interview. Hi, I have 1.5 years exp in java. plz send me java/j2ee/servlets/jsp/struts/hibernate questions. Tell me about technical questions regarding real time project in Trading,banking,telecom domain.. And also suggest some of the books related to Interview questions on Java projects,Struts,EJB.. Thank You sir, Tell me some questions regarding core java that are important for interviews and also suggest me about the books of core java. Hi. I have 1 years of experience.I need the type of questions asked in interviews on java .could u plz help me. Thank you very much. Hi. I have 3 years of experiance.I need the type of questions asked in interviews on java/j2ee.could u plz help me. Thanking very mutch. please send me 1+ year exp java/j2ee,jsp/servlets questions for the interview. Plz send me objective question for Servlet, JSP, Structs and JMS Hi, Please send me some questions from core java. and some important questions from jsp,servlets,struts It will help for my career. Please give me some core java and swing interview question. thank you hi i need interview questions for java, j2ee of 2yrs experience. thank u bye I need help with Java/J2EE interview questions for 5 years experience.Thank you in advance for your help. Hi, I need to become a professional in Java/J2EE for this I need some help. I am a software engineer working in Application Development department using Java technology. I need the type of questions asked in an interview for a job in java/j2ee with about 2 years.
http://news.sys-con.com/node/48839?page=1
CC-MAIN-2018-17
refinedweb
2,803
66.33
This project is mirrored from. Pull mirroring updated . - 11 Feb, 2020 1 commit - John Ericson authored (cherry picked from commit e9ceb851) (cherry picked from commit da57caff) - 03 Nov, 2019 1 commit - - 23 Oct, 2019 1 commit - - 08 Oct, 2019 1 commit Hopefully this will guard against regressions around quasiquotes, TH quotes, and TH splices. - 07 Oct, 2019 3 commits Previously, this input would crash Haddock. It is possible to fail to extract an HIE ast. This is however not a reason to produce _no_ output - we should still make a colorized HTML page. - - 01 Oct, 2019 1 commit - Alexis King authored The `ignore-exports` option has been broken since #688, as mentioned in. This PR fixes it. - 20 Sep, 2019 1 commit Tentatively for the 2.23 release: * updated Travis CI to work again * tweaked bounds in the `.cabal` files * adjusted `extra-source-files` to properly identify test files - 04 Jun, 2019 1 commit - 26 May, 2019 4 commits Tentatively adjust bounds and changelogs for the release to be bundled with GHC 8.8.1. When possible, associated types with promoted lists should use the promoted list literal syntax (instead of repeated applications of ': and '[]). This was fixed in 2122de54. Closes #466, At this point, Haddock depended on Cabal-the-library solely for a verbosity parser (which misleadingly accepts all sorts of verbosity options that Haddock never uses). Now, the only dependency on Cabal is for `haddock-test` (which uses Cabal to locate the Haddock interface files of a couple boot libraries). - 17 May, 2019 2 commits The only other change in html/hoogle/hyperlinker output for the boot libraries that this caused is a fix to some Hoogle output for implicit params. ``` $ diff -r _build/docs/ old_docs diff -r _build/docs/html/libraries/base/base.txt old_docs/html/libraries/base/base.txt 13296c13296 < assertError :: (?callStack :: CallStack) => Bool -> a -> a --- > assertError :: ?callStack :: CallStack => Bool -> a -> a ``` `fail` is no longer part of `Monad`. - 13 May, 2019 4 commits Now that GHC is hosted on Gitlab, the arcanist files don't make sense anymore. The STYLE file contains nothing more than a dead link too. The `.ghci` files are actively annoying when trying to `cabal v2-repl`. As for the `scripts`, the distribution workflow is completely different. - 05 May, 2019 2 commits - 29 Mar, 2019 3 commits - Ben Gamari authored - Alan Zimmerman authored (cherry picked from commit 3ee6526d) Before LLVM 6.0.1 (or 10.0 on Apple LLVM), there was a bug where lines that started with an octothorpe but turned out not to lex like pragmas would have an extra line added after them. Since this bug has been fixed upstream and that it doesn't have dire consequences anyways, the workaround is not really worth it anymore - we can just tell people to update their clang version (or re-structure their pragma code). - 09 Mar, 2019 4 commits After this commit, we can run with `--latex` on all boot libraries without crashing (although the generated LaTeX still fails to compile in a handful of larger packages like `ghc` and `base`). * Add newlines after all block elements in LaTeX. This is important to prevent the final output from being more an more indented. See the `latext-test/src/Example` test case for a sample of this. * Support associated types in class declarations (but not yet defaults) * Several small issues for producing compiling LaTeX; - avoid empy `\haddockbeginargs` lists (ex: `type family Any`) - properly escape identifiers depending on context (ex: `Int#`) - add `vbox` around `itemize`/`enumerate` (so they can be in tables) * Several spacing fixes: - limit the width of `Pretty`-arranged monospaced code - cut out extra space characters in export lists - only escape spaces if there are _multiple_ spaces - allow type signatures to be multiline (even without docs) * Remove uninteresting and repetitive `main.tex`/`haddock.sty` files from `latex-test` test reference output. Fixes #935, #929 (LaTeX docs for `text` build & compile) Fixes #727, #930 (I think both are really about type families...) `markupWarning` often processes inputs which span across paragraphs. Unfortunately, LaTeX's `emph` is not made to handle this (and will crash). Fixes #936. * default methods now get rendered differently * default associated types get rendered * fix a forgotten `s/TypeSig/ClassOpSig/` refactor in LaTeX backend * LaTeX backend now renders default method signatures NB: there is still no way to document default class members and the NB: LaTeX backend still crashes on associated types Fixes #1030. - 03 Mar, 2019 1 commit - 01 Mar, 2019 1 commit This is to address the concern that, on less nice and older screens, some of the shades of grey blend in too easily with the white background. * darken the font slightly * darken slightly the grey behind type signatures and such * add a border and round the corners on code blocks * knock the font down by one point - 28 Feb, 2019 2 commits Fixes #864. - Xia Li-yao authored Adds a menu item (like "Quick Jump") for options related to displaying instances. This provides functionality for: * expanding/collapsing all instances on the currently opened page * controlling whether instances are expanded/collapsed by default * controlling whether the state of instances should be "remembered" This new functionality is implemented in Typescript in `details-helper`. The built-in-themes style switcher also got a revamp so that all three of QuickJump, the style switcher, and instance preferences now have the same style and implementation structure. See also: Fixes #698. Co-authored-by: Lysxia <lysxia@gmail.com> Co-authored-by: Nathan Collins <conathan@galois.com> - 27 Feb, 2019 1 commit This avoids a situation in which an identifier would get defaulted to a completely different identifier. Prior to this commit, the 'Bug1035' test case would hyperlink 'Foo' into 'Bar'! Fixes #1035. - 26 Feb, 2019 1 commit Docs on standalone deriving decls for classes with associated types should be associated with the class instance, not the associated type instance. Fixes #1033 - 25 Feb, 2019 2 commits * '(<|>)' and '`elem`' now get parsed and rendered properly as links * 'DbModule'/'DbUnitId' now properly get split apart into two links * tuple names now get parsed properly * some more small niceties... The identifier parsing code is more precise and more efficient (although to be fair: it is also longer and in its own module). On the rendering side, we need to pipe through information about backticks/parens/neither all the way through from renaming to the backends. In terms of impact: a total of 35 modules in the entirety of the bootlib + ghc lib docs change. The only "regression" is things like '\0'. These should be changed to @\\0@ (the path by which this previously worked seems accidental). Identifier links can be prefixed with a 'v' or 't' to indicate the value or type namespace of the desired identifier. For example: -- | Some link to a value: v'Data.Functor.Identity' -- -- Some link to a type: t'Data.Functor.Identity' The default is still the type (with a warning about the ambiguity) - 04 Feb, 2019 3 commits The central trick in this patch is to use `dataConUserTyVars` instead of `univ_tvs ++ ex_tvs`, which displays the foralls in a GADT constructor in a way that's more faithful to how the user originally wrote it. Fixes #1015. The second example is interesting. If there's a list directly after the header, and that list has deeper structure, the parser is confused: It finds two lists: - One with the first nested element, - everything after it I'm not trying to fix this, as I'm not even sure this is a bug, and not a feature. Now that Haddock is moving towards working entirely over `.hi` and `.hie` files, all declarations and types are going to be synthesized via the `Convert` module. In preparation for this change, here are a bunch of fixes to this module: * Add kind annotations to type variables in `forall`'s whose kind is not `Type`, unless the kind can be inferred from some later use of the variable. See `implicitForAll` and `noKindTyVars` in particular if you wish to dive into this. * Properly detect `HsQualTy` in `synifyType`. This is done by following suit with what GHC's `toIfaceTypeX` does and checking the first argument of `FunTy{} :: Type` to see if it classified as a given/wanted in the typechecker (see `isPredTy`). * Beef up the logic around figuring out when an explicit `forall` is needed. This includes: observing if any of the type variables will need kind signatures, if the inferred type variable order _without_ a forall will still match the one GHC claims, and some other small things. * Add some (not yet used) functionality for default levity polymorphic type signatures. This functionality similar to `fprint-explicit-runtime-reps`. Couple other smaller fixes only worth mentioning: * Show the family result signature only when it isn't `Type` * Fix rendering of implicit parameters in the LaTeX and Hoogle backends * Better handling of the return kind of polykinded H98 data declarations * Class decls produced by `tyThingToLHsDecl` now contain associated type defaults and default method signatures when appropriate * Filter out more `forall`'s in pattern synonyms
https://gitlab.haskell.org/ghc/haddock/-/commits/wip/jg-merged-backpack-stuff
CC-MAIN-2020-34
refinedweb
1,507
51.28
This fix is relevant to you if you had a library on webpack4 or webpack3 that exported a function and after update to webpack5 in apps that import this library you started to see: TypeError: <library_name>__WEBPACK_IMPORTED_MODULE_<somenumber>___default() is not a function This happened for one of my packages and library user created an issue about TypeError. I spent some time investigating it and it turned out that now webpack started to wrap the exported function in the object. So my previous builds of library worked fine with the next syntax: import Painterro from 'painterro' And now the only way to make it work was: import { Painterro } from 'painterro' This way is called named import, not so bad actually, there are a lot of advantages comparing to my previous export default method. But for a library that already has 50k downloads on npm without fallback to previous behavior would be the road to pain: Yes, it is possible to explain the change in npm notice, add bold text in Readme, bump the minor number according to semver, but anyway, we would find users which will start asking why it is not working. Other users will just drop away the idea to use the library once face this issue. So I created a minimal reproducible example and issue on webpack repo and the project member quickly explained what happened: Because it was bug in v4 and now it is fixed, using library: 'P2',means module.exports.P2 = {}, but if you don't need it, just remove library: 'P2',and keep libraryTarget: 'commonjs2' Thing is that I indeed had a library: 'Painterro', in module.exports.output in webpack.config.js : module.exports = { output: { path: path.resolve(__dirname, 'build'), // folder where library will be placed filename: 'painterro.commonjs2.js', // filename of the library library: 'Painterro', // ⏪ this is the issue libraryTarget: 'commonjs2', }, .... } So what I did is just removed library: 'Painterro' and previous behavior returned back!
https://hinty.io/devforth/fix-webpack-imported-module-is-not-a-function-for-webpack5/
CC-MAIN-2021-21
refinedweb
323
54.05
One Web services interoperability issue that I have been investigating recently has to do with using null DateTime values between .NET and Java. Here’s the problem: System.DateTime in the CLR is considered a value type, where as the equivalent in Java (java.util.Calendar) is not. In .NET, value types, including int, double, short etc. cannot be assigned to null. This applies equally to DateTime: For example, the following command in C# will not compile. System.DateTime myDate = null; (In VB.NET you may think you can do this, but really you can’t <g>) In Java, java.util.Calendar can be assigned to null – which introduces a couple of problems when you consider passing dates and times over Web Services between the two: 1) How do I send a null DateTime from .NET to Java? 2) What happens if Java sends me a null DateTime? For #1, this is really up to how you want to handle it (and this is easier to spot as the problem will normally be detected at compile time). Here are some options: – Both the client and the Web service agree a certain date (e.g. 01/01/0001 12:00:00 AM) as a null date. – Make the interface expose a string and pass the date that way instead. From experience, if you were to do this, I would pass an empty string to indicate a null date. – Create a XSD complexType that contains a DateTime value and pass this instead. Set the value of this complexType to null to indicate a null date. (this would be my recommended approach as it get’s you into the habit of passing messages between the two, instead of primitives <g>). #2 is a little more tricky because if .NET receives a null DateTime from a Java Web Service, it will throw a System.FormatException – which you won’t catch at compile time. Again, the options above are equally applicable on the Java side. Which option you choose will depend on your particular situation – and may also be based on whether you are using Web services internally or externally. The good news is that we are working on a set of guidance for this and other similar issues. Catch any my talks, visit the Web services interoperability booth at TechEd or watch this space to find out more… public class Foo { public Nullable<DateTime> Time { get; set; } } 😉 *bangs head on desk* Web Service! public class Foo : WebService { [WebMethod] [return:XmlElement("Time", DataType="time")] public Nullable<DateTime> Time { get; set; } } will it work? Sean, according to Don’s post will ASMX for whidbey support Nullable<T> For more info: Good info, thanks. [ Via C# Items ]WS Interoperability Tip of the Week. Null dates. One Web services interoperability issue that I have been investigating recently has to do with using null DateTime values between .NET and Java. Here’s the problem:System.DateTime in the CLR is considered a value… I think this is an issue that the developer needs to be aware of, but if s/he follows good practices, there will be no terrible problems. Starting from a WSDL that specifies a field in a complexType as xsd:date, the .NET client-side proxy or server-side skeleton that is generated employs the (little-known?) feature in XML Serialization that: when you have a value-type property of name Xxxx and an additional field of name XxxxSpecified, which is a bool, and is decorated with [XmlIgnore] …then, the value of the bool indicates whether the value type is "null" or not. In other words, in case #1, you just set XxxSpecified to false, and you will send a "nil" xsd:date to your Java counterpart. In case #2, just check XxxSpecified for false before evaluating the value of the property. This works with any value type, including DateTime. See for the doc on this (look for the discussion on propertyNameSpecified). Ahh, I think I have misunderstood the issue. If the interface specifies minOccurs=1, then a null date will actually appear in the XML message as something like <Date xsi:nil=’1’/>. This is the thing that causes .NET to choke with a FormatException. You can mitigate the problem without changing the server interface or implementation – in other words just by doing some special handling on the client side. De-serialize as a string and set a hidden DateTime field behind it. Eg, rather than public class MyType { public System.DateTime DateTimeField; } you caneTimeField { set { if ((value!=null) && (value != "")) { internal_DateTimeField= System.DateTime.ParseExact(value, formatString, CInfo); DateTimeFieldIsNull= false; } else DateTimeFieldIsNull= true; } get { return (DateTimeFieldIsNull) ? null : internal_DateTimeField.ToString(formatString) ; } } } Actualmente, existem várias abordagens que podemos usar para desenvolver serviços. Destacam-se duas:… Actualmente existem várias abordagens que podemos usar para desenvolver serviços. Destacam-se duas: …
https://blogs.msdn.microsoft.com/smguest/2004/05/07/ws-interoperability-tip-of-the-week-null-dates/
CC-MAIN-2016-44
refinedweb
800
57.06
Important: Please read the Qt Code of Conduct - [Solved] COM interface to CANoe Hello, I try to program a COM interface to the COM-Server from CANoe. So the Qt project works as Client. Here is my code so far: 3com_interface.pro @ Add more folders to ship with the application, here folder_01.source = qml/3com_interface folder_01.target = qml DEPLOYMENTFOLDERS = folder_01 Additional import path used to resolve QML modules in Creator's code model QML_IMPORT_PATH = If your application uses the Qt Mobility libraries, uncomment the following lines and add the respective components to the MOBILITY variable. CONFIG += mobility MOBILITY += The .cpp file which was generated for your project. Feel free to hack it. SOURCES += main.cpp interface.cpp Installation path target.path = Please do not modify the following two lines. Required for deployment. include(qtquick2applicationviewer/qtquick2applicationviewer.pri) qtcAddDeployment() HEADERS += CANoe.h interface.h CONFIG += qaxcontainer @ interface.cpp @ #include "interface.h" #include <QDebug> #include "objbase.h" #include "CANoe.h" #include "windows.h" #include "winnls.h" #include "shobjidl.h" #include "objidl.h" #include "shlguid.h" #include "strsafe.h" Interface::Interface(QObject *parent) : QObject(parent) { } void Interface::trigger_slot(const QString &msg) {"; } } @ I get the following error: undefined reference to '_GUID const&_mingw_uuidof<IApplication>()' (line 37) I think the compiler has problems with the __uuidof operator. Are there other ways to get the IID of the CANoe COM interface? Or does someone have any experience or hints how to get access to a COM interface in Qt? I searched for hours in the Internet but doesn't find an example for Qt. Only some examples for Visual Studio with ATL. But I can't use ATL in Qt. Or are there any possibilities to use it in Qt? Thank you very much for all answers! according to "__uuidof Operator": you should compile with ole32.lib you can use something like: @canoeAxObj = new QAxObject("CANoe.Application"); CANoe::IApplication canoeapp = (CANoe::IApplication)canoeAxObj->querySubObject("Application"); canoeapp->SetVisible(false);@ where CANoe::IApplication comes from a header file generated with "dumpcpp tool": with .tlb libid (from registry): i.e. D:\Qt\Qt5.1.1-MSVC2010\5.1.1\msvc2010_opengl\bin>dumpcpp input {7F31DEB0-5BCC-11 d3-8562-00105A3E017B} this will generate a qt canoe.h (warning: different of canoe.h from CANoe installation), which you should add to your project; then with the code above is straight forward Hello NicuPopescu, thank you for your answer. I've searched in the dcomcnfg after the IID of the CANoe interface. So I deleted line 37 of my code (see above) and added the following code: @ IID IID_IApplication = {0x7F31DEB2-0x11d3-0x8562-0x00105A3E017B} @ I think the result will be the same as your suggestion with the new header file? However I can start the program and CANoe starts automatically. So I think there is successfully a connection between CANoe and my Qt program. But in line 41 I have an if query whether the connection was successful. Unfortunately the program doesn't print "Connection established" Why is an error saved in HRESULT result? Does anybody has an idea? bq. So I deleted line 37 of my code (see above) and added the following code: IID IID_IApplication = {0x7F31DEB2-0x11d3-0x8562-0x00105A3E017B} this is not safe, your app will not work with other CANoe package/version ... why not to link against ole32.lib abd use __uuidof()? check for possible CoCreateInstance() results as described in msdn ... loading CANoe application does not neccessarely mean you have got a pointer to its COM interface! I only can guess that pIApp is NULL, so no COM connection yet ... How can I link to ole32.lib in Qt? I doesn't find it on my PC. Only the ole32.dll.... What do you mean with the possible CoCreateInstance() results? Do you mean the error code saved in HRESULT result? bq. How can I link to ole32.lib in Qt? I doesn’t find it on my PC. Only the ole32.dll…. i.e. here is in C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib\ better to copy it locally to your project in a "lib" folder and have in .pro file @LIBS += ../lib/ole32.lib@ bq. What do you mean with the possible CoCreateInstance() results? Do you mean the error code saved in HRESULT result? yes L.E. I checked your initial code and it works ... [quote author="NicuPopescu" date="1386863709"]i.e. here is in C:\Program Files\Microsoft SDKs\Windows\v7.0A\Lib\ better to copy it locally to your project in a "lib" folder and have in .pro file [/quote] I tried to add the library to my project: I copied the Ole32.Lib out of the Microsoft SDK folder to my project directory Then I added the following code to my pro file: @ LIBS += C:/QtProject/3com_interface/libs/Ole32.Lib @ But I get actually the same error: "undefined reference to '_GUID const& __mingw_uuidof<IApplication>()' Do I need some files more, for example the Ole32.dll? But I'm wondering that my code works correctly in your project. Could you post your code or your project so I can search for the differences? Any ideas? I have still the same problem: How can I get the IID of a COM-Application to create the COM interface? There are two possibilities: - Is there an alternative to __uuidof() to get the IID of the object? - What do I need to add to my project, so I can use __uuidof() and how can I add this? Thank you for all answers so far! bq. Do I need some files more, for example the Ole32.dll? dll will be found in system32, so no worry I don't know why it is so difficult for you to get the project compiled; just in case I paste exactly what I have in main window project: .pro file: @#------------------------------------------------- Project created by QtCreator 2013-12-13T16:39:39 #------------------------------------------------- QT += core gui greaterThan(QT_MAJOR_VERSION, 4): QT += widgets TARGET = TestCANoeCOM TEMPLATE = app SOURCES += main.cpp mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui LIBS += ../TestCANoeCOM/lib/ole32.lib@ path in LIBS depends on your projetc build directory in QtCreator's Projects panel in mainwindow.cpp @#include "mainwindow.h" #include "ui_mainwindow.h" #include <QDebug> #include "C:\Program Files\Vector CANoe 7.5\Exec32\COMdev\canoe.h" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this);"; } } MainWindow::~MainWindow() { delete ui; } @ nothing different to your first code ... bq. How can I get the IID of a COM-Application to create the COM interface? in registry HKEY_CLASSES_ROOT->PID (i.e CANoe.Application)->CLSID(Value) and in HKEY_CLASSES_ROOT->CLSID->Value(found above)->InprocServer32 , you can find more info on COM server registration like: LocalServer32=path to exe, ocx, dll into which your COM implementation resides hope it helps! :) Hello NicuPopescu, I've found my mistake. Thank you for posting your code. You've helped me a lot! you're welcome! :) hope the answers help other fellows here ... HI This post is deleted! I want to call a function from QT application in facet this function exist a CAPL script runing in Canalyzer I am using COM to get access to the function here my exemple but it doesnt work where is the problem any help plz this my code: ICAPL *pcapl; ICAPLFunction *fn ; IApplication* pIApp; HRESULT result,result1,result2, hresult,result3,result4,hr; IDispatch*CaplDisp,*CaplFn; WCHAR * szMember = L"Multiply"; DISPID dispid; DISPPARAMS dispparams = {NULL, NULL, 0, 0}; EXCEPINFO excepinfo; UINT nArgErr; CLSID clsid; result = CLSIDFromProgID(L"CANalyzer.Application", &clsid); const IID IID_CAPL =__uuidof(ICAPL); const IID IID_CAPLFUNCTION =__uuidof(ICAPLFunction); const IID IID_IApplication =__uuidof(IApplication); result = CoCreateInstance(clsid, NULL, CLSCTX_LOCAL_SERVER, IID_IApplication, (void**) &pIApp); result1=pIApp->get_CAPL(&CaplDisp); qDebug() << "Result_get_CAPL "<<result1 ; result2=CaplDisp->QueryInterface(IID_CAPL,(void**)&pcapl); qDebug() << "result2 "<<result2 ; VARIANT varResult; hr = CaplDisp->GetIDsOfNames(IID_CAPLFUNCTION, &szMember, 1, CLSCTX_LOCAL_SERVER, &dispid); qDebug() << "hr"<<hr ; if (SUCCEEDED(hr)) { hr = CaplDisp->Invoke(1,IID_CAPL, CLSCTX_LOCAL_SERVER,DISPATCH_METHOD,&dispparams, &varResult, NULL, NULL); }
https://forum.qt.io/topic/35324/solved-com-interface-to-canoe/13
CC-MAIN-2021-04
refinedweb
1,310
51.55
2: - 아마도 기능을 갖 설명합니다. 객체 참조 얻기¶ 모든 :ref:`객체 <class_Object>에 있어, 객체를 참조하는. 참조 객 노드와 리소스를 : extends Object { //. # Compiled scripts in final binary do not include assert statements assert prop. #, dynamic lookup with dynamic NodePath. public void Method1() { GD.Print(GetNode(NodePath("Child"))); } // Fastest. Lookup node and cache for future access. // Doesn't break if node moves later. public Node Child; public void _Ready() { Child = GetNode(NodePath("Child")); } public void Method2() {. - Note that this happens even for non-legal symbol names such as in the case of TileSet's "1/tile_name" property. This refers to the name of the tile with ID 1, i.e. TileSet.tile_get_name(1). extends Node { public FuncRef FN = null; public void MyMethod() { Debug.Assert(FN != null); FN.CallFunc(); } } // Parent.cs public class Parent extends.
https://docs.godotengine.org/ko/latest/getting_started/workflow/best_practices/godot_interfaces.html
CC-MAIN-2019-47
refinedweb
133
71
Keystore.swift makes it easy to extract private keys from Ethereum keystore files and generate keystore files from existing private keys. This library belongs to our Swift Crypto suite. For a pure Swift Ethereum Web3 library check out Web3.swift! Check the usage below or look through the repositories tests. Keystore is available through CocoaPods. To install it, simply add the following line to your Podfile: pod 'Keystore' Keystore is compatible with Carthage, a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To install it, simply add the following line to your Cartfile: github "Boilertalk/Keystore.swift" You will also have to install the dependencies, which can be found in our Cartfile. Keystore is compatible with Swift Package Manager v4 (Swift 4 and above). Simply add it to the dependencies in your Package.swift. dependencies: [ .package(url: "", from: "0.2.0") ] And then add it to your target dependencies: targets: [ .target( name: "MyProject", dependencies: ["Keystore"]), .testTarget( name: "MyProjectTests", dependencies: ["MyProject"]) ] After the installation you can import Keystore in your .swift files. import Keystore To extract a private key from an existing keystore file, just do the following. import Keystore let decoder = JSONDecoder() let keystoreData: Data = ... // Load keystore data from file? let keystore = try decoder.decode(Keystore.self, from: keystoreData) let password = "your_super_secret_password" let privateKey = try keystore.privateKey(password: password) print(privateKey) // Your decrypted private key And to generate a keystore file from an existing private key, your code should look a little bit like the following. let privateKey: [UInt8] = ... // Get your private key as a byte array let password = "your_super_secret_password" let keystore = try Keystore(privateKey: privateKey, password: password) let keystoreJson = try JSONEncoder().encode(keystore) print(String(data: keystoreJson, encoding: .utf8)) // Your encrypted keystore as a json string The awesome guys at Boilertalk :alembic: ...and even more awesome members from the community :purple_heart: Keystore is available under the MIT license. See the LICENSE file for more info. Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API
https://swiftpack.co/package/Boilertalk/Keystore.swift
CC-MAIN-2021-21
refinedweb
331
51.24
#include <assert.h> #include <limits.h> #include <stddef.h> #include <stdio.h> #include <stdlib.h> #include <string.h> #include <sys/types.h> #include <algorithm> #include <optional> #include "decimal.h" #include "field_types.h" #include "lex_string.h" #include "libbinlogevents/export/binary_log_funcs.h" #include "m_ctype.h" #include "my_alloc.h" #include "my_base.h" #include "my_bitmap.h" #include "my_dbug.h" #include "my_double2ulonglong.h" #include "my_inttypes.h" #include "my_sys.h" #include "my_time.h" #include "mysql/udf_registration_types.h" #include "mysql_com.h" #include "mysql_time.h" #include "mysqld_error.h" #include "sql/dd/types/column.h" #include "sql/field_common_properties.h" #include "sql/gis/srid.h" #include "sql/sql_bitmap.h" #include "sql/sql_const.h" #include "sql/sql_error.h" #include "sql/table.h" #include "sql_string.h" #include "template_utils.h" Go to the source code of this file. Status when storing a value in a field or converting from one datatype to another. The values should be listed in order of increasing seriousness so that if two type_conversion_status variables are compared, the bigger one is most serious. Enum to indicate source for which value generator is used. This is needed while unpacking value generator expression and pre-validating the expression for generated column, default expression or check constraint. Return the appropriate MYSQL_TYPE_X_BLOB value based on the pack_length. Calculate key length for field from its type, length and other attributes. TODO: Get rid of this function as its code is redundant with Field::key_length() code. However creation of Field object using make_field() just to call Field::key_length() is probably overkill. Calculate the length of the in-memory representation of the column from information which can be retrieved from dd::Column or Ha_fk_column_type describing it. This function calculates the amount of memory necessary to store values in the record buffer. It is used in cases when we want to calculate this value from the description of column in the form compatible with dd::Column without constructing full-blown Field object. Copies an integer value to a format comparable with memcmp(). The format is characterized by the following: The function template can be instantiated to copy from little or big endian values. Copy the value in "from" (assumed to be non-NULL) to "to", doing any required conversions in the process. Note that you should only call this if fields_are_memcpyable() is false, since it does an actual conversion on the slow path (and it is not properly tested whether it gives the correct result in all cases if fields_are_memcpyable() is true). You should never call this with to == from, as they are no-ops. Check if one can copy from “from” to “to” with a simple memcpy(), with pack_length() as the length. This is the case if the types of the two fields are the same and we don't have special copying rules for the type (e.g., blobs, which require allocation, or time functions that require checking for special SQL modes). You should never call this with to == from, as such copies are no-ops and memcpy() has undefined behavior with overlapping memory areas. Generate a Create_field from an Item. This function generates a Create_field from an Item by first creating a temporary table Field from the Item, and then creating the Create_field from this Field (there is currently no way to go directly from Item to Create_field). It is used several places: Tests if field real type is temporal, i.e. represents all existing implementations of DATE, TIME, DATETIME or TIMESTAMP types in SQL. Instantiates a Field object without a record buffer. Instantiates a Field object with the given name and record buffer values. Instantiates a Field object with the given record buffer values. This function should only be called from legacy code. Perform per item-type checks to determine if the expression is allowed for a generated column, default value expression, a functional index or a check constraint. Note that validation of the specific function is done later in procedures open_table_from_share and fix_value_generator_fields. Convert temporal real types as returned by field->real_type() to field type as returned by field->type(). Tests if field real type can have "DEFAULT CURRENT_TIMESTAMP", i.e. represents TIMESTAMP types in SQL. Tests if field real type can have "ON UPDATE CURRENT_TIMESTAMP", i.e. represents TIMESTAMP types in SQL. The following piece of code is run for the case when a BLOB column that has value NULL is queried with GROUP BY NULL and the result is inserted into a some table's column declared having primitive type (e.g. INT) and NOT NULL. For example, the following test case will hit this piece of code: CREATE TABLE t1 (a BLOB); CREATE TABLE t2 (a INT NOT NULL); INSERT t1 VALUES (NULL); INSERT INTO t2(a) SELECT a FROM t1 GROUP BY NULL; <<== Hit here In general, when set_field_to_null() is called a Field has to be either declared as NULL-able or be marked as temporary NULL-able. But in case of INSERT SELECT from a BLOB field and when GROUP BY NULL is specified the Field object for a destination column doesn't set neither NULL-able nor temporary NULL-able (see setup_copy_fields()). Set field to NULL or TIMESTAMP or to next auto_increment number. Convert warnings returned from str_to_time() and str_to_datetime() to their corresponding type_conversion_status codes.
https://dev.mysql.com/doc/dev/mysql-server/latest/sql_2field_8h.html
CC-MAIN-2022-40
refinedweb
869
60.51
How to set TinyMCE as default editor for current users Purpose This howto will show you how you can set the default editor to TinyMCE for all current users. Prerequisities This howto assumes you have basic knowledge of Zope and writing Python scripts. Step by step To convert all the users you have to write a Python script. Because the script contains trusted code you can't simply add a python script in the ZMI but have to use for example an external method. The script looks as follows: def Kupu2TinyMCE(self): pm = self.portal_membership for memberId in pm.listMemberIds(): member = pm.getMemberById(memberId) editor = member.getProperty('wysiwyg_editor', None) if editor == 'TinyMCE': print('%s: TinyMCE already selected, leaving alone' % memberId) else: member.setMemberProperties({'wysiwyg_editor': 'TinyMCE'}) print('%s: TinyMCE has been set' % memberId) return Once the script is created you'll have to run it after which all users will have TinyMCE set as wysiwyg editor. If you want to revert your actions and switch back to Kupu, you can simply change 'TinyMCE' to 'Kupu' and re-run the script. Thanks to kcraig for providing the script.
http://plone.org/products/tinymce/documentation/how-to/how-to-set-tinymce-as-default-editor-for-current-users/
crawl-003
refinedweb
186
56.96
In this. package { import flash.display.MovieClip public class Main extends MovieClip { public function Main():void { trace(. import com.doitflash.text.TextArea; Then remove the hello world trace function and enter the following instead. var _textArea:TextArea = new TextArea(); _textArea.wordWrap= true; _textArea.multiline = true; _textArea.htmlText = "Initialize TextArea just like you used to initialize TextField."; this.addChild(_textArea);": <?xml version="1.0" encoding="UTF-8"?> <data> <![CDATA[ <p align="left"><font face="Tahoma" size="13" color="#333333"> Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Nam cursus. Morbi ut mi. Nullam enim leo, egestas id, condimentum at, laoreet mattis, massa. </font></p> ]]> </data> (So that XML contains HTML in a CDATA section.) Now get back to your Main.as, which should look like the following: package { import flash.display.MovieClip import com.doitflash.text.TextArea; public class Main extends MovieClip { public function Main():void { var _textArea:TextArea = new TextArea(); _textArea.wordWrap = true; _textArea.multiline = true; _textArea.htmlText = "Initialize TextArea just like you used to initialize TextField."; this.addChild(_textArea); } } } Add the required imports for xml loading process. import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; Then replace the whole Main() function with this. public function Main():void {.wordWrap = true; _textArea.multiline = true; _textArea.width = 400; _textArea.height = 200; _textArea.condenseWhite = true; _textArea.htmlText = xml.text(); addChild(_textArea); } } method for sending text scripts into the instance rather than using the classic htmlText. The fmlText method will parse scripts using a different approach than htmlText; it stands for Flash Markup Language Text. So, in your test project, replace htmlText with fmlText like below. _textArea.fmlText = xml.text();. public function funcOnOver():void { trace("rollOver"); } public function funcOnOut():void { trace("rollOut"); } You should also set some settings while initializing the TextArea instance. Add these lines just after you initialize); Also add the following line to the beginning of the Main() function. var refToThis:Object = this; To make sure you have written the code in Main.as correctly, below is how your file should look up to now. package { import flash.display.MovieClip import com.doitflash.text.TextArea; import flash.events.Event; import flash.net.URLLoader; import flash.net.URLRequest; public class Main extends MovieClip { public function Main():void { var refToThis:Object = this;); _textArea.wordWrap = true; _textArea.multiline = true; _textArea.width = 400; _textArea.height = 200; _textArea.condenseWhite = true; _textArea.fmlText = xml.text(); addChild(_textArea); } } public function funcOnOver():void { trace("rollOver"); } public function funcOnOut():void { trace("rollOut"); } } } by: Here's a <u><a href='onMouseOver:funcOnOver();onMouseOut:funcOnOut()'>SAMPLE LINK</a></u>.: <u><a href='event:func1()'>SIMPLE CALL</a></u>.<br /> <u><a href='event:func2(some string)'>SEND STRING</a></u>.<br /> <u><a href='event:func3([0,1,2,3,4])'>SEND ARRAY</a></u>.<br /> <u><a href='event:func4({var1:val1;var2:val2})'>SEND OBJECT</a></u>.<br /> <u><a href='event:func5(string,[0,1,2],{var1:val1;var2:val2})'>SEND MIXED ARGUMENTS</a></u>.<br />: public function func1():void { trace("no arguments sent"); } public function func2($str:String):void { trace("arguments >> " + $str); } public function func3($arr:Array):void { trace("arguments >> " + $arr); } public function func4($obj:Object):void { trace("arguments >> " + $obj); } public function func5($str:String, $arr:Array, $obj:Object):void { trace("arguments >> " + $str); trace("arguments >> " + $arr); trace("arguments >> " + $obj); } Now you have the calls in XML and the functions are also available in the AS3 project; all that's left is to give the usage permission to the TextArea instance. Modify the allowedFunctions method of TextArea as so: _textArea.allowedFunctions(funcOnOver, funcOnOut, func1, func2, func3, func4, func5);! Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/easily-create-souped-up-flash-text-fields-with-textarea--active-10456
CC-MAIN-2018-22
refinedweb
613
55.1
#include <sys/mman.h> void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *start, size_t length); void *mmap(void *start, size_t length, int prot, int flags, int fd, off_t offset); int munmap(void *start, size_t length); The prot argument describes the desired memory protection (and must not conflict with the open mode of the file). It is either PROT_NONE or is the bitwise OR of one or more of the other PROT_* flags. The above three flags are described in POSIX.1-2001. Linux also knows about the following non-standard flags: fd should be a valid file descriptor, unless MAP_ANONYMOUS is set. If MAP_ANONYMOUS is set, then fd is ignored on Linux. However, some implementations require fd to be -1 if MAP_ANONYMOUS (or MAP_ANON) is specified, and portable applications should ensure this. offset should be a multiple of the page size as returned by getpagesize. In kernels before 2.6.7, the MAP_POPULATE flag only has effect if prot is specified as PROT_NONE. getpagesize (2) mincore (2) mlock (2) mmap2 (2) mremap (2) msync (2) remap_file_pages (2) setrlimit (2) Advertisements
http://www.tutorialspoint.com/unix_system_calls/mmap.htm
CC-MAIN-2014-41
refinedweb
189
70.33
Using an armature from swcjonasfunkj Feb 8, 2010 5:52 AM Hello, I have build an armature in Flash CS4, and exporting it in a swc. All works fine when building the swf from the Flash IDE, but I cannot use seem to be able to use it in Flash Builder. When tracing (IKManager.numArmatures) I keep getting 0. I have set the armature to runtime, and remembered to listen for the FRAME_CONSTRUCTED event. Since the same code will run in Flash, and not in Flash Builder, I thought there might be known issue with this, or something I am forgetting? Below is a simplified version of the code: package { import fl.ik.*; import flash.display.*; import flash.events.*; public class Rig extends MovieClip { public function Rig() { addEventListener(Event.FRAME_CONSTRUCTED, bodyReady); } private function bodyReady(e:Event):void { removeEventListener(Event.FRAME_CONSTRUCTED, bodyReady); IKManager.trackAllArmatures(true); trace(IKManager.numArmatures); var tree:IKArmature=IKManager.getArmatureAt(0); } }} 1. Re: Using an armature from swcJason San Jose Feb 8, 2010 11:11 AM (in response to jonasfunkj) Are the Flash CS4 SWCs in your Flash Builder project's library path? C:\Program Files\Adobe Flash CS4\Common\Configuration\ActionScript 3.0\libs. Jason San Jose Quality Engineer, Flash Builder 2. Re: Using an armature from swcjonasfunkj Feb 8, 2010 12:43 PM (in response to Jason San Jose) Thank you for your answer Jason. I have tried including them, but still no success. 3. Re: Using an armature from swcJason San Jose Feb 8, 2010 1:25 PM (in response to jonasfunkj) Sorry, I misunderstood the original question. I'll try from the beginning. Is your project a FLA-based project or is it ActionScript only? You'll need to use Flash CS4's compiler if you're using referencing symbols that are on the stage. Flash Builder Beta 2 does not compile FLA files. Jason 4. Re: Using an armature from swcjonasfunkj Feb 8, 2010 1:38 PM (in response to Jason San Jose) My project is Actionscript based. I create a bunch of symbols in Flash CS4 and export them in a swc. They're no symbols on the stage - just in the library. I reference the swc in Flash Builder, just like you suggested before. I have done several projects this way, but this time I have run into problems with the use of armatures. 5. Re: Using an armature from swcTareq AlJaber Feb 8, 2010 3:52 PM (in response to jonasfunkj) This is a known issue. Runtime IK puts code on the main timeline. When you bring your symbol in as a component, the main timeline code is not included. So no work around without major changes to the way runtime IK works. thanks, tareq 6. Re: Using an armature from swcjonasfunkj Feb 8, 2010 11:33 PM (in response to Tareq AlJaber) Ok, I see. Well, then I have to find some other way of doing it. Maybe loading it from a swf instead. 7. Re: Using an armature from swcTareq AlJaber Feb 10, 2010 1:59 PM (in response to jonasfunkj) Should have mentioned that this bug is going to be fixed in the next version of Flash Authoring. thanks, tareq 8. Re: Using an armature from swcjonasfunkj Feb 11, 2010 5:06 AM (in response to Tareq AlJaber) Appreciate your help. Looking forward to the next version. 9. Re: Using an armature from swcJasonKingWork Mar 2, 2010 4:31 PM (in response to jonasfunkj) I saw this link which may help you...
https://forums.adobe.com/thread/572410
CC-MAIN-2018-09
refinedweb
585
74.29
Working with XML is a pain in the ass! but unfortunately this format is far from being put into disuse. While we still have to deal with API's that provide data only in XML format, the solution is to count on the help of various Python packages that do this kind of work. I've worked with many of them including the famous BeautifulSoap, ElementTree and xml.minidom. Among those mentioned, what I like most is the xml.minidom, cause it is simple and is available in the standard library, however when there is a need to "wipe" XML structures in search of specific data one of the best ways is the XPATH and in this case both the ElementTree as BeautifulSoap has good support. A few weeks ago I started a project in Django to query a sporting results API and write the returned data in to models in the database to feed an app for real time blogging. When I began to analyze the structure of XML and the amount of XPATH that would have to write , I thought "I would like to work only with JSON because it is the data format of the modern web", so I went to google and typed "convert xml 2 dict" and to my surprise I found this great tool! That's why Python Rocks! This week I notice that it has been updated allowing unparse of dicts to xml. Turning it in to my preferred module to deal with XMLs. xmltodict xmltodict is a Python module that makes working with XML feel like you are working with JSON, as in this "spec": >>> doc = xmltodict.parse(""" ... <mydocument has="an attribute"> ... <and> ... <many>elements</many> ... <many>more elements</many> ... </and> ... <plus a="complex"> ... element as well ... </plus> ... </mydocument> ... """) >>> >>> doc['mydocument']['@has'] u'an attribute' >>> doc['mydocument']['and']['many'] [u'elements', u'more elements'] >>> doc['mydocument']['plus']['@a'] u'complex' >>> doc['mydocument']['plus']['#text'] u'element as well' It's very fast (Expat-based) and has a streaming mode with a small memory footprint, suitable for big XML dumps like Discogs or Wikipedia: >>> def handle_artist(_, artist): ... print artist['name'] >>> >>> xmltodict.parse(GzipFile('discogs_artists.xml.gz'), ... item_depth=2, item_callback=handle_artist) A Perfect Circle Fantômas King Crimson Chris Potter ... It can also be used from the command line to pipe objects to a script like this: myscript.py import sys, marshal while True: _, article = marshal.load(sys.stdin) print article['title'] sh $ cat enwiki-pages-articles.xml.bz2 | bunzip2 | xmltodict.py 2 | myscript.py AccessibleComputing Anarchism AfghanistanHistory AfghanistanGeography AfghanistanPeople AfghanistanCommunications Autism ... Or just cache the dicts so you don't have to parse that big XML file again. You do this only once: $ cat enwiki-pages-articles.xml.bz2 | bunzip2 | xmltodict.py 2 | gzip > enwiki.dicts.gz And you reuse the dicts with every script that needs them: $ cat enwiki.dicts.gz | gunzip | script1.py $ cat enwiki.dicts.gz | gunzip | script2.py ... You can also convert in the other direction, using the unparse() method: python >>> mydict = { ... 'page': { ... 'title': 'King Crimson', ... 'ns': 0, ... 'revision': { ... 'id': 547909091, ... } ... } ... } >>> print unparse(mydict) <?xml version="1.0" encoding="utf-8"?> <page><ns>0</ns><revision><id>547909091</id></revision><title>King Crimson</title></page> Ok, how do I get it? You just need to $ pip install xmltodict There is an official Fedora package for xmltodict. If you are on Fedora or RHEL, you can do: $ sudo yum install python-xmltodict Donate If you love xmltodict, consider supporting the author on Gittip. Note: I am not involved in the project, I am just disseminating because it is one of the most useful lib I've ever encountered in the Pythonic ecosystem. KISS: Use the built in sum() instead of reduce to aggregate over a list comprehension This post is the beginning of a KISS tag, a place where I will put all the "over complications" I find on codes that I work on, or even to comment on my own mistakes. WTF? Today I was working on a Django reports app and I saw this code: result = reduce(lambda x, y: x + y, \ [i.thing.price for i in \ ModelObject.objects.filter(created_at__gte=date)]) At the first look, specially because of the use of reduce I thought it was a complicated issue to solve. 2 seconds after I realized. Why using reduce for sum when Python already has the built in sum function? result = sum([i.thing.price for i in ModelObject.objects.filter(created_at__gte=date)]) Well Python gives us powerful builtins so just use this! The other problem here is the memory usage of the above solution, it will first get the objects list from filter() and after that it will iterate one by one, doing a field lookup to take the price and return a new list with values to sum. It can kill your server! On this case things can be done in a better way! we are talking about Django! and even I am being a Django ORM hater I know that it has some cool things like this one: Django ORM aggregations from django.db.models import Count queryset = ModelObject.objects.filter(created_at__gte=date) aggregation = queryset.aggregate(price=Sum('thing__price')) result = aggregation.get('price', 0) On the above code, the aggregation Sum will translate in to a SQL command and the sum will be performed on the database side! much better I really do not like the Django ORM syntax, also I hate the way I bind the objects, maybe because I am used to use the wonderful DAL I prefer to refer to data as data, I mean, data as Rows not data as objects. But in cases I am working with Django, I think the best is to use its powerful tools! Keep It Simple Stupid! Django ListField e SeparetedValuesField Revisiting this with a ListField type you can use. But it makes a few of assumptions, such as the fact that you're not storing complex types in your list. For this reason I used ast.literal_eval() to enforce that only simple, built-in types can be stored as members in a ListField: from django.db import models import ast class ListField(models.TextField): __metaclass__ = models.SubfieldBase description = "Stores a python list" def __init__(self, *args, **kwargs): super(ListField, self).__init__(*args, **kwargs) def to_python(self, value): if not value: value = [] if isinstance(value, list): return value return ast.literal_eval(value) def get_prep_value(self, value): if value is None: return value return unicode(value) def value_to_string(self, obj): value = self._get_val_from_obj(obj) return self.get_db_prep_value(value) class Dummy(models.Model): mylist = ListField() Taking it for a spin: >>> from foo.models import Dummy, ListField >>> d = Dummy() >>> d.mylist [] >>> d.mylist = [3,4,5,6,7,8] >>> d.mylist [3, 4, 5, 6, 7, 8] >>> f = ListField() >>> f.get_prep_value(d.numbers) u'[3, 4, 5, 6, 7, 8]' There you have it that a list is stored in the database as a unicode string, and when pulled back out it is run through ast.literal_eval(). Previously I suggested this solution from this blog post about Custom Fields in Django:) Add a counter on Django admin home page Recently I tried many ways to add a simple record counter on Django admin home page, I needed it to look like this: I have tried django admin tools, overwriting the _meta on admin.py but the probleam with admin tools is that it installed a lot of aditional stuff I did not like to use, and the problem with other approaches was because I needed it to be dynamic. Overwriting the __meta seemed to be the right way but is binded only one time, and no updates done until the app restarts. My friend Fernando Macedo did it the right way! specialize the string type to add your desired dynamic behavior from django.db import models class VerboseName(str): def __init__(self, func): self.func = func def decode(self, encoding, erros): return self.func().decode(encoding, erros) class UsedCoupons(models.Model): name = models.CharField(max_length=10) class Meta: verbose_name_plural = VerboseName(lambda: u"Used Coupons (%d)" % UsedCoupons.objects.count()) And this gives us a lesson, try to solve your problems in pure Python before looking for tricks or ready solutions. (wow it is a dynamic language!) Programmatically check if Django South has migrations to run Programmatically check if South has migrations to run. from south import migration from south.models import MigrationHistory apps = list(migration.all_migrations()) applied_migrations = MigrationHistory.objects.filter(app_name__in=[app.app_label() for app in apps]) applied_migrations = ['%s.%s' % (mi.app_name,mi.migration) for mi in applied_migrations] num_new_migrations = 0 for app in apps: for migration in app: if migration.app_label() + "." + migration.name() not in applied_migrations: num_new_migrations = num_new_migrations + 1 return num_new_migrations It can be wrapped in to a function and can be used to monitor South state in admin. Based on south.management.commands.migrate and some C/P from stack overflow Using Python to get all the external links from a webpage Based on the Mark Pilgrim - Dive in to Python book Define the url lister from sgmllib import SGMLParser class URLLister(SGMLParser): def reset(self): SGMLParser.reset(self) self.urls = [] def start_a(self, attrs): href = [v for k, v in attrs if k=='href'] if href: self.urls.extend(href) Now The function which receives an URL, read that url and list all href attrs def get_urls_from(url): url_list = [] import urllib usock = urllib.urlopen(url) parser = URLLister() parser.feed(usock.read()) usock.close() parser.close() map(url_list.append, [item for item in parser.urls \ if item.startswith(('http', 'ftp', 'www'))]) return url_list Ok, Now you can call this: from pprint import pprint pprint(get_urls_from("")) and you get: ['', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', '', ''] That was based on some examples from DiveIntoPython book
http://brunorocha.org/python/django/
CC-MAIN-2017-47
refinedweb
1,622
57.06
QtSql test application Hi, As a lab rat, I'm afraid of starting a new thread, however, Qt forum is so huge I can't even get started finding a similar problem to mine. I've seen several "Symbol(s) not found..." thread, but none of them related to what I'm trying to do, which is to compile the following very basic program, just to test Qt's connectivity with SQL. @ #include "mainwindow.h" #include "ui_mainwindow.h" #include "stdio.h" #include "QtSql/QSqlDatabase" MainWindow::MainWindow(QWidget *parent) : QMainWindow(parent), ui(new Ui::MainWindow) { ui->setupUi(this); } MainWindow::~MainWindow() { printf( "Runs like a charm\n" ); delete ui; } int dbConnect(){ printf( "rodou\n" ); QSqlDatabase db = QSqlDatabase::addDatabase("QPSQL"); db.setHostName("localhost"); db.setDatabaseName("pinsard"); db.setUserName("pinsard"); db.setPassword("pgsvcpwd"); bool ok = db.open(); printf( "Conexão com banco de dados: %\n", ok ); return 0; } @ As you'll promptly recognize, the first part of the code was generated by Qt. I added the dbConnect() function to isolate my test code, just that. And then, it stopped compiling, with the compiler emiting the dreaded two messages: ":-1: error: symbol(s) not found for architecture x86_64" ":-1: error: collect2: ld returned 1 exit status" I'm running Qt Creator 4.7.4 on Lion 10.7.2. Any hints would be more than a help for me now. Thanks Gustavo Pinsard Have you linked your SQL module with Qt? Welcome to DevNet and the forums. Don't hesitate to open a new thread (especially if you indicate that you've searched already). Everyone is friendly here and we take a strong focus on a good atmosphere without flamewars or similar habits that makes people go away. Regarding your actual problem, can you also post the contents of your .pro file please. And it would be good to know if you use some precompiled Qt (either the libs package or from the SDK) or some manually compiled Qt. Then, in Qt Creator, go to the compiler output tab (the 4th on the bottom), there you find some additional infos regarding the error, including the method names/symbols that are missing. Additionally, did you install the PostgreSQL libs from a package or did you build it yourself? Oh... and just to clean up some confusion: It's most likely Qt Creator 2.3.1 and Qt libs 4.7.4 - both are independent software packages :-) Wow. Thanks Volker. That was a complete and guiding help. My .pro file (no pun intended) is as follows: @ QT += core gui TARGET = dbTst TEMPLATE = app SOURCES += main.cpp mainwindow.cpp HEADERS += mainwindow.h FORMS += mainwindow.ui @ I guess I'm lost in regard to how Qt suggests me to use QtSql. It was my understanding that whenever I #included "QtSql", the linker/compiler would automatically grab internal libs (since there is a "QPSQL" qualifier). I didn't "install" any PostgreSQL libs, explicit, but I do have PG server running on the machine. I'll transfer pqlib. Let me experiment more with the Compile Output. Thanks Well, I can be very wrong, but this message from the compiler should clarify a lot... ../QtSDK/Desktop/Qt/474/gcc/include/QtCore/qglobal.h:320:6: warning: #warning "This version of Mac OS X is unsupported" mainwindow.cpp: In destructor 'virtual MainWindow::~MainWindow()': Doh! Will install Qt for Windows and see how it goes on. You will at least have to add "sql" to your QT variable: @ QT += core gui sql @ This adds the QtSql library to the link step. Qt is organized in modules, each module that you use must be named in the QT variable of the .pro file. Lion is still relatively new in respect to Qt, the upcoming 4.8 release should contain full support. For the time being, I think you can ignore the warning. The error message you received ("symbol(s) not found for architecture x86_64") usually indicates that you link against a library that does not contain all necessary architecture variants for your application. On Mac OS X a binary (application executable or library) usually contains code for more than one architecture. On Lion this usually includes i386 (Intel 32 bit) and x86_64 (Intel 64 bit). On older OS X versions you can also have ppc (PowerPC 32 bit) and ppc64 (PowerPC 64bit). Qt itself, when installed from the prebuilt libs or the SDK, only contains x86_64 code. This is what you are building your application against. If you use external libs (like the PostgreSQL libs) that do not contain x86_64 code, your link step will fail. In that case you have two choices: First you can either install a x86_64 version of the external lib or build that yourself. Second you rebuild Qt manually and include at least the i386 architecture. You have to exclude the x86_64 part from your application then. The warning message about the Mac Os version being unsupported is not related to the linker error. To get rid of it, specify the Mac Os target SDK as 10.6 as described here:
https://forum.qt.io/topic/11473/qtsql-test-application
CC-MAIN-2017-39
refinedweb
840
65.73
AWS Open Source Blog Deploy OpenFaaS on Amazon EKS >>IMAGE around 13k stars and 130 contributors on GitHub. Running OpenFaaS on Amazon EKS allows you to co-locate all of your workloads, from functions to containerized microservices, allowing you to utilize all of the resources available.. Once installed, we can deploy serverless functions to Kubernetes using the OpenFaaS CLI from the community Function Store, or build our own using popular languages like Golang. Set Up CLI Tooling A CLI tool called eksctl from Weaveworks will help us automate the task of creating the cluster. Several other CLI tools will also be required for the setup. Here are the steps: - Install the eksctl CLI. - Install the AWS CLI. - You will also need to have the AWS CLI installed and your AWS credentials available in the .awsfolder or via environmental variables. You’ll find instructions for this in the AWS documentation. - Install the Kubernetes CLI (if you haven’t already). - Install the Helm CLI tool. - Install the OpenFaaS CLI. Create the Cluster with eksctl Create a Kubernetes cluster with two worker nodes in the us-west-2 region. The config file for kubectl will be saved into a separate file in ~/.kube/eksctl/clusters/openfaas-eks. eksctl create cluster --name=openfaas-eks --nodes=2 --auto-kubeconfig --region=us-west-2 The cluster may take 10-15 minutes to provision but, once it’s ready, we will be able to list the nodes, specifying the alternative kubeconfig file for kubectl: $ export KUBECONFIG=~/.kube/eksctl/clusters/openfaas-eks $ kubectl get nodes NAME STATUS ROLES AGE VERSION ip-192-168-121-190.us-west-2.compute.internal Ready <none> 8m v1.10.3 ip-192-168-233-148.us-west-2.compute.internal Ready <none> 8m v1.10.3 If you get an error about missing heptio-authenticator-aws, follow the instructions to configure kubectl for Amazon EKS. Install Helm Many open source projects can be installed on Kubernetes by using the Helm tool. Helm consists of server (Tiller) and client (Helm) components. We installed the Helm CLI earlier; now it’s time to install the server component into the cluster. First, create a Kubernetes service account for the server component of Helm called Tiller: kubectl -n kube-system create sa tiller kubectl create clusterrolebinding tiller-cluster-rule \ --clusterrole=cluster-admin \ --serviceaccount=kube-system:tiller Now deploy Tiller into the cluster: helm init --upgrade --service-account tiller Create Kubernetes Namespaces for OpenFaaS To make management easier, the core OpenFaaS services will be deployed to the (openfaas) namespace, and any functions will be deployed to a separate namespace (openfaas-fn). Create the namespaces below: kubectl apply -f Prepare Authentication for OpenFaaS You should always enable authentication for OpenFaaS, even in development and testing environments, so that only users with credentials can deploy and manage functions. Generate a random password by reading random bytes, then create a hash: PASSWORD=$(head -c 12 /dev/urandom | shasum | cut -d' ' -f1) Your password will be a hash and will look similar to this: 783987b5cb9c4ae45a780b81b7538b44e660c700 This command creates a secret in Kubernetes, you can change the username from admin to something else if you want to customise it: kubectl -n openfaas create secret generic basic-auth \ --from-literal=basic-auth-user=admin \ --from-literal=basic-auth-password=$PASSWORD OpenFaaS architecture In OpenFaaS, any binary, process, or container can be packaged as a serverless function using the well-known Docker image format. At a technical level, every function deployed to OpenFaaS causes Kubernetes to create a Deployment and a Service API object. The Deployment object will have a minimum scale defaulting to one replica, meaning we have one Pod ready to serve traffic at all times. This can be configured, and we will read more about it in the final section. In the diagram below we see the OpenFaaS operator, which is accessible via kubectl or via the faas-cli using an AWS LoadBalancer. Image provided by Stefan Prodan You can read more on the OpenFaaS Architecture in the official documentation. Deploy OpenFaaS with Helm You can pick the classic OpenFaaS Kubernetes controller called faas-netes or the CRD-based controller called OpenFaaS-Operator by passing the flag operator.create=true. Read more on the differences in Introducing the OpenFaaS Operator for Serverless on Kubernetes. Add the OpenFaaS Helm chart repo: helm repo add openfaas If you already have the repo listed, you can use helm repo update to synchronise with the latest chart. We can now install OpenFaaS with authentication enabled by default using Helm: helm upgrade openfaas --install openfaas/openfaas \ --namespace openfaas \ --set functionNamespace=openfaas-fn \ --set serviceType=LoadBalancer \ --set basic_auth=true \ --set operator.create=true \ --set gateway.replicas=2 \ --set queueWorker.replicas=2 The settings above mean that functions will be installed into a separate namespace for easier management, a LoadBalancer will be created (read below), basic authentication will be used to protect the gateway UI, and then we are opting to use the OpenFaaS Operator to manage the cluster with operator.create=true. We set two replicas of the gateway to be available so that there is high availability, and two queue-workers for high availability and increased concurrent processing. Run the following command until you see all services showing Available as at least “1:” kubectl --namespace=openfaas get deployments -l "release=openfaas, app=openfaas" A LoadBalancer will be created for your OpenFaaS Gateway. It may take 10-15 minutes for this to be provisioned, then the public IP address can be found with this command: kubectl get svc -n openfaas -o wide When the EXTERNAL-IP field shows an address, you can save the value into an environmental variable for use with the CLI and the rest of the tutorial: export OPENFAAS_URL=$(kubectl get svc -n openfaas gateway-external -o jsonpath='{.status.loadBalancer.ingress[*].hostname}'):8080 \ && echo Your gateway URL is: $OPENFAAS_URL Use the OpenFaaS CLI to save your login credentials (they will be written to ~/.openfaas/config.yaml): echo $PASSWORD | faas-cli login --username admin --password-stdin In a follow-up post we will cover how to install HTTPS certificates with Let’s Encrypt and Kubernetes Ingress. Deploy Your First Function The first function we will deploy will come from the built-in OpenFaaS Function Store, a collection of project- and user-created functions designed to help new users experience functions. You can see all available functions via faas-cli store list Let’s deploy a machine-learning function called inception which can take a URL of an image as an input and return a JSON structure showing what objects it was able to detect: faas-cli store deploy inception The function will be made available from the OpenFaaS API Gateway via the following default route: $OPENFAAS_URL/function/inception You can invoke the function using the OpenFaaS UI, the faas-cli via faas-cli invoke or by using an API-testing tool such as Postman. Find an image with a Creative Commons License from a website such as Wikipedia.com; search for your favourite animal (such as a bear) to test out the function. Here’s a bear image I found. Now invoke the function using one of the methods shown above: curl -i $OPENFAAS_URL/function/inception --data Make sure you surround any URLS with quotes when using curl. You should see the results appear in one or two seconds, depending on the size and specification of the machines picked to run the EKS cluster. { "name": "brown bear", "score": 0.767388105392456 }, { "name": "ice bear", "score": 0.006604922469705343 }, { "name": "bottlecap", "score": 0.003021928481757641 }, { "name": "reel", "score": 0.0026519917882978916 }, { "name": "American black bear", "score": 0.0018049173522740602 } ] With my sample image, you can see a score of 76% for a brown bear which shows a positive match. You could use this function or one of the several similar functions to create new features for your existing applications by invoking the function through the API Gateway. Working with Events Functions can also be invoked via events such as Webhooks over HTTP/S, AWS SNS, CloudEvents, Kafka, and RabbitMQ. In a follow-up post, we will cover how to combine events with AWS services to create an event-driven pipeline. If you’d like to read more about events, see the OpenFaaS documentation. To invoke a function asynchronously, just change the route from /function/ to /async-function. You can even provide a callback URL where the result will be published once complete. This would be a useful combination with machine-learning functions which can take several seconds per invocation to execute. This is especially important when working with events and webhooks. Webhook producers such as GitHub require a response within 10 seconds (though it’s common to see as responses as fast as 1-2 seconds). De-coupling event from execution enables you to work around this restriction. To use this with inception, you can set up a temporary HTTP receiver with RequestBin and then use that URL as the callback URL to see a response. Visit RequestBin and click Create, then enter the URL in the command below. After one or two seconds you can refresh the page, and you’ll see the same data we received above transmitted to the endpoint. curl -i $OPENFAAS_URL/async-function/inception -H “X-Callback-Url:” --data You can also chain functions together by picking another function as the callback URL. Write Your Own Function You can write your own function in one of the supported languages, or add your own template. An OpenFaaS template consists of a Dockerfile and an entrypoint (hidden from the user). The user sees a way to specify packages, and writes code in the handler file. You can explore the official OpenFaaS templates to find your preferred language. Let’s pull down the latest images from GitHub and then list what’s available: faas-cli template pull faas-cli new --list The faas-cli new command can be used to scaffold a function. All functions are built into immutable Docker images so that the function works the same way on your local machine as on your production cluster. That means we need to add a prefix to the function specifying your Docker Hub account name or the address of your private Docker registry as an Amazon Container Registry (ACR) address. The function’s image will need to be prefixed with the account name or remote registry address (for example, alexellis2/hello-golang). Use the --prefix flag or edit the YAML file at any time. faas-cli new --lang go hello-golang --prefix=alexellis2 This creates the following files: ./hello-golang.yml ./hello-golang/ ./hello-golang/handler.go Edit handler.go: package function import ( "fmt" ) // Handle a serverless request func Handle(req []byte) string { return fmt.Sprintf("Hello, Go. You said: %s", string(req)) } Now edit the message, and then run the following command: faas-cli up -f hello-golang.yml If you rename an OpenFaaS YAML stack file stack.yml, the CLI will attempt to load it first if it is in the current working directory. The up command saves typing and corresponds to the following commands, one by one: faas-cli build && \ faas-cli push && \ faas-cli deploy You can now invoke your new function in the same way we did with the inception function, or navigate to the OpenFaaS UI to manage your functions. Note: If you need to add additional dependencies to your Golang function, you can use the dep tool and vendoring. You can also use the OpenFaaS UI to deploy functions from the Function Store, which gives you a chance to explore how to use them and find their source code. Monitoring with the Grafana Dashboard The OpenFaaS Gateway collects metrics on how many replicas of your functions exist, how often they are invoked, their HTTP codes (success/failure) and the latency of each request. You can view this data in the OpenFaaS UI, or via faas-cli list, but the most effective way to monitor the data is through a dashboard using Grafana. Stefan Prodan has pre-packed the OpenFaaS dashboard in a Docker image which we can run on the cluster and then view using kubectl. kubectl -n openfaas run --image=stefanprodan/faas-grafana:4.6.3 --port=3000 grafana kubectl expose deploy/grafana --type ClusterIP -n openfaas --port 3000 Now use kubectl port-forward to access the service without having to expose it over the Internet: kubectl port-forward -n openfaas svc/grafana 3000:3000 Open in a browser: Navigate to the dashboard, where you will see the invocations we made to your custom function and the inception function. The credentials are admin/admin, and can also be changed through this page. Trigger Auto-Scaling Auto-scaling in OpenFaaS can be managed through the built-in Prometheus metrics, with AlertManager firing alerts when thresholds on requests per second are met; functions can scale up and down depending on demand, even to zero. Note: Kubernetes’ own auto-scaling HPAv2 can also be used with OpenFaaS. For a detailed overview on auto-scaling options, see the OpenFaaS documentation. I’ll demonstrate by triggering auto-scaling with a function from the OpenFaaS store, then monitoring the scaling in Grafana. Create a new directory and deploy a store function: $ mkdir -p openfaas-eks-scaling $ cd openfaas-eks-scaling $ faas-cli store deploy figlet --label com.openfaas.scale.min=2 --label com.openfaas.scale.max=8 Deployed. 202 Accepted. URL: This will deploy the function named “figlet” that generates ASCII text logos (which I hope will be more entertaining than seeing “hello world” repeated several thousand times). Now generate some load (just enough to trigger the scaling alert): for i in {1..10000} ; do echo $i | faas-cli invoke figlet done How fast you generate load will depend on how close you are to your chosen AWS region. If you are unable to trigger the scaling, open several Terminal windows and paste the command into each. Make sure you set the OPENFAAS_URL variable in any new terminal windows. Here we see the function’s invocation rate in the top left quadrant increasing dramatically as I generate load. The replicas of the figlet function increased in steps from 2 to 7, which would have continued to the upper limit. Then when I stopped the traffic another alert was fired off which caused the figlet function to scale back to its lower limit. This type of scaling allows us to make use of all of the nodes in the EKS cluster. Summary In this post we deployed a Kubernetes cluster to AWS using EKS, deployed OpenFaaS with authentication enabled, then deployed a machine learning function and invoked it both synchronously and asynchronously. We also wrote a custom Golang function, deployed that to the cluster, and monitored it with a Grafana dashboard. In upcoming posts in this series, we will explore how to enable TLS using Let’s Encrypt and CertManager and AWS Route53 to manage DNS entries. We will then create an event-driven pipeline for Optical Character Recognition (OCR) using AWS services and events such as S3 and SNS. Stay tuned, and subscribe to the OpenFaaS blog for more tutorials!
https://aws.amazon.com/blogs/opensource/deploy-openfaas-aws-eks/
CC-MAIN-2019-26
refinedweb
2,523
59.43
Realtime applications are generally applications that produce time sensitive data or updates that requires immediate attention or consumption. From flight management software to following up with the score line and commentary when your favorite football team is playing. We’ll be building a realtime application that will show live updates on reviews about the next movie users want to watch at the cinema. All that juicy reviews from fans, viewers and critics around the world, and I’ll want them in real time. Let’s call it Rotten pepper. The application will contain a form that allows users to fill in their review easily and will also display a table showing reviews left by users world wide in realtime. This part of the application will be built with Next.js The other important part of this application is the API, where reviews posted by the user will go to. We’ll build this using Express and Node. Pusher would be the glue that sticks both ends together. We’ll be using the following tools to help build this quickly. Please ensure you have Node and npm installed before starting the tutorial. No knowledge of React is required, but a basic understanding of JavaScript may be helpful. Let’s get building. If you have no idea about Next.js, I recommend you take a look here. It’s pretty easy and in less than an hour, you’ll be able to build real applications using it. Let’s create the directory where our app will sit: # make directory and cd into it mkdir movie-listing-next && cd movie-listing-next # make pages, components and css directory mkdir pages mkdir components mkdir css Now we can go ahead to install dependencies needed by our application. I’ll be using Yarn for my dependency management, but feel free to use npm also. Install dependencies using Yarn: # initilize project with yarn yarn init -y # add dependencies with yarn yarn add @zeit/next-css axios next pusher-js react react-dom react-table Let’s add the following to the script field in our package.json and save. This makes running commands for our app more easier. // package.json { "scripts": { "dev": "next", "server": "node server.js" } } For users to submit their reviews, they’ll need a form where they can input their name, review and rating. This is a snippet from [components/form.js]() , which is a simple React form that takes the name, review and rating. You’ll need to create yours in the components directory. Snippets from [components/form.js](): export default class Form extends React.Component { .... render () { return ( <form onSubmit={this.handleSubmit}> <div> <label> Name: <br /> <input type='text' value={this.state.name} onChange={this.handleChange.bind(this, 'name')} /> </label> </div> <div> <label> Review: <br /> <textarea rows='4' cols='50' type='text' value={this.state.review} onChange={this.handleChange.bind(this, 'review')} /> </label> </div> <div> <label> Rating: <br /> <input type='text' value={this.state.rating} onChange={this.handleChange.bind(this, 'rating')} /> </label> </div> <input type='submit' value='Submit' /> </form> ) } } If you’re a React developer, you should feel right at home here. On form submission, the data is being passed down to this.props.handleFormSubmit(this.state). This props is passed down from a different component as we’ll soon see. Now we have our form, but we still need a page to list all the reviews submitted by users. The size of our reviews could grow rapidly and we still want this in realtime, so it’s best to consider pagination from the outset. That’s why we’ll be using react-table, as highlighted above this is lightweight and will give us pagination out of the box. The snippet below is from our index page, which you’ll need to create here [pages/index.js]() . // pages/index.js import React from 'react' import axios from 'axios' import ReactTable from 'react-table' import 'react-table/react-table.css' import '../css/table.css' import Form from '../components/form' import Pusher from 'pusher-js' Here we import our dependencies which include axios for making http calls, our styles from table.css and the form component we created earlier on. // pages/index.js const columns = [ { Header: 'Name', accessor: 'name' }, { Header: 'Review', accessor: 'review' }, { Header: 'Rating', accessor: 'rating' } ] const data = [ { name: 'Stan Lee', review: 'This movie was awesome', rating: '9.5' } ] React-table, which is pretty easy to set up needs a data and columns props to work. There’s a pretty easy example here if you want to learn more. We’re adding a sample review to data to have at least one review when we start our app. // pages/index.js const pusher = new Pusher('app-key', { cluster: 'cluster-location', encrypted: true }) const channel = pusher.subscribe('rotten-pepper') export default class Index extends React.Component { constructor (props) { super(props) this.state = { data: data } } render () { return ( <div> <h1>Rotten <strike>tomatoes</strike> pepper</h1> <strong>Movie: Infinity wars </strong> <Form handleFormSubmit={this.handleFormSubmit.bind(this)} /> <ReactTable data={this.state.data} columns={columns} defaultPageSize={10} /> </div> ) } } Here, we created our React component and initialize Pusher and subscribe to the rotten-pepper channel. Kindly get your app-id from your Pusher dashboard and if you don’t have an account, kindly create one here. The state value this.data is initialized with the sample data created above and our render method renders both or form and our table. At this point, we’re still missing a few vital parts. Pusher has been initialized, but it’s currently not pulling any new reviews and updating our table. To fix that, add the following to your react component in pages/index.js // pages/index.js componentDidMount () { this.receiveUpdateFromPusher() } receiveUpdateFromPusher () { channel.bind('new-movie-review', data => { this.setState({ data: [...this.state.data, data] }) }) } handleFormSubmit (data) { axios.post('', data) .then(res => { console.log('received by server') }) .catch(error => { throw error }) } In componentDidMount, we’re calling the method receiveUpdateFromPusher which would receive new reviews submitted by users and update our table. We’re calling receiveUpdateFromPusher in componentDidMount so this only get called once. The handleFormSubmit method is responsible for sending the review submitted by users down to your endpoint. This is passed as a props to the the form component as mentioned before. // next.config.js const withCSS = require('@zeit/next-css') module.exports = withCSS() This should be placed in a file called next.config.js in your root directory movie-listing-next. It’s responsible for loading all .css files which contains our styles on app startup. Now that our app can load .css properly, create the file css/form.css which is needed by components/form.js to style our app’s form: form { margin: 30px 0; } form div { margin: 10px 0; } To keep the content of our review table center aligned, create the file css/table.css and add the following style snippet. .rt-td { text-align: center; } To set the root structure of our app, we create pages/_document.js. This is where the rest of our app will sit. // pages/_document.js import Document, { Head, Main, NextScript } from 'next/document' export default class MyDocument extends Document { render () { return ( <html> <Head> <title>Movie listing</title> <link rel='stylesheet' href='/_next/static/style.css' /> </Head> <body> <Main /> <NextScript /> </body> </html> ) } } Now, let’s setup the endpoint where all reviews submitted will be received. This is where all the magic happens. When a review gets submitted, we’ll want other users to be aware of the new data and this is where Pusher shines. Create a file server.js at the root of your application and add the following snippet as it’s content. Remember to visit your Pusher dashboard to get your appId, appKey, appSecret. // server.js const pusher = new Pusher({ appId: 'appId', key: 'appKey', secret: 'appSecret', cluster: 'cluster', encrypted: true }) app.post('/add-review', function (req, res) { pusher.trigger('rotten-pepper', 'new-movie-review', req.body) res.sendStatus(200) }) From above, once the user hits /add-review we trigger an event new-movie-review with pusher which clients are currently listening on. We pass it the new review that was submitted and the connected clients update themselves. The values for appId, appSecret and appKey should be replaced with actual credentials. This can be gotten from your app dashboard on Pusher, and if you don’t have an account simply head down to and create an account. Let’s add dependencies need by our app: # add dependencies needed by server.js yarn add body-parser cors express pusher At this point, the dependencies field in our package.json should contain the following below: "dependencies": { "@zeit/next-css": "^0.1.5", "axios": "^0.18.0", "body-parser": "^1.18.2", "cors": "^2.8.4", "express": "^4.16.3", "next": "^5.1.0", "pusher": "^1.5.1", "pusher-js": "^4.2.2", "react": "^16.3.2", "react-dom": "^16.3.2", "react-table": "^6.8.2" } if not, simply replace the contents of the dependencies field in your package.json and run # install dependencies from package.json yarn The entire content of server.js is right below. The line const port = process.env.PORT || 8080 simply picks up the preferred port to run our app and app.listen(port, function () {} starts our app on that port. // server.js const express = require('express') const app = express() const bodyParser = require('body-parser') const cors = require('cors') const Pusher = require('pusher') app.use(cors()) app.use(bodyParser.urlencoded({ extended: true })) app.use(bodyParser.json()) const port = process.env.PORT || 8080 const pusher = new Pusher({ appId: 'appId', key: 'appKey', secret: 'appSecret', cluster: 'cluster', encrypted: true }) app.post('/add-review', function (req, res) { pusher.trigger('rotten-pepper', 'new-movie-review', req.body) res.sendStatus(200) }) app.listen(port, function () { console.log('Node app is running at localhost:' + port) }) Now let’s see if what we’ve done so far works. In one bash window: # start next app yarn run dev and for our endpoint simply run in a new bash window: # start api server yarn run server You can open []() in as many tabs as possible and see if a review posted in one tab gets to the others. Building a realtime application can be super easy with the right tools. Pusher takes all that socket and connection work out of the way and allow us focus on the app we’re building. Now I can sit back and watch reviews come :-) The repo where this was done can be found here. Feel free to fork and improve. Obviously this needs some more styling. How do you think we could improve this more? Happy hacking!! Pusher Limited is a company registered in England and Wales (No. 07489873) whose registered office is at 160 Old Street, London, EC1V 9BW.
https://www.pusher.com/tutorials/realtime-tables-nextjs
CC-MAIN-2019-18
refinedweb
1,793
59.7
In most of the web development projects you might want to automate file generation, like for example placeorder confirmation receipts, payment receipts, that can be based on a template you are using. The library we will be using is Weasyprint. WeasyPrint is to combine multiple pieces of information into an HTML template and then converting it to a PDF document. The supported version are Python 2.7, 3.3+ WeasyPrint has lot of dependencies, So this can be install it with pip. pip install Weasyprint Once you have installed WeasyPrint, you should have a weasyprint executable. This can be as simple: weasyprint --version This will Print WeasyPrint's version number you have installed. weasyprint <Your_Website_URL> <Your_path_to_save_this_PDF> Eg: weasyprint ./test.pdf Here i have converted "" site to an test.pdf.Let we write sample PDF Generation: from weasyprint import HTML, CSS HTML('').write_pdf('/localdirectory/test.pdf', stylesheets=[CSS(string='body { font-size: 10px }')]) This will also converts the page in to PDF, Here the change is we are writting custom stylesheet(CSS) for the body to change the font size using the "string" argument. You can also pass the CSS File, This can be done using: from django.conf import settings CSS(settings.STATIC_ROOT + 'css/main.css') Ex: HTML('').write_pdf('/localdirectory/test.pdf', stylesheets=[CSS(settings.STATIC_ROOT + 'css/main.css')]) You can also pass multiple css files to this stylesheets arrayGenerating PDF Using Template: Let we create a basic HTML file, that we will use as a template to generate PDF: templates/home_page.html <html> <head> Home Page </head> <body> <h1>Hello !!!</h1> <p>First Pdf Generation using Weasyprint.</p> </body> </html> Lets write a django function to render this template in a PDF: from weasyprint import HTML, CSS from django.template.loader import get_template from django.http import HttpResponse def pdf_generation(request): html_template = get_template('templates/home_page.html') pdf_file = HTML(string=html_template).write_pdf() response = HttpResponse(pdf_file, content_type='application/pdf') response['Content-Disposition'] = 'filename="home_page.pdf"' return response Here, we have used the get_template() function to fetch the HTML template file in the static root. Finally, You can download your home_page.pdf
https://micropyramid.com/blog/generate-pdf-files-from-html-in-django-using-weasyprint/
CC-MAIN-2017-30
refinedweb
350
58.89
Learn what to expect in the new updates The object underlying all of the matplotlib.patch objects is the Path, which supports the standard set of moveto, lineto, curveto commands to draw simple and compound outlines consisting of line segments and splines. The Path is instantiated with a (N,2) array of (x,y) vertices, and a N-length array of path codes. For example to draw the unit rectangle from (0,0) to (1,1), we could use this code import matplotlib.pyplot as plt from matplotlib.path import Path import matplotlib.patches as patches verts = [ (0., 0.), # left, bottom (0., 1.), # left, top (1., 1.), # right, top (1., 0.), # right, bottom (0., 0.), # ignored ] codes = [Path.MOVETO, Path.LINETO, Path.LINETO, Path.LINETO, Path.CLOSEPOLY, ] path = Path(verts, codes) fig = curve with one control point and one end point, and CURVE4 has three vertices for the two control points and the end point. The example below shows a CURVE4 Bézier spline – the bézier curve will be contained in the convex hull of the start point, the two control points, and the end) patch = patches.PathPatch(path, facecolor='none', lw=2) ax.add_patch(patch) xs, ys = zip(*verts) ax.plot(xs, ys, 'x--', lw=2, color='black', ms=10) ax.text(-0.05, -0.05, 'P0') ax.text(0.15, 1.05, 'P1') ax.text(1.05, 0.85, 'P2') ax.text(0.85, -0.05, 'P3') ax.set_xlim(-0.1, 1.1) ax.set_ylim(-0.1, 1.1) plt.show() (Source code, png, hires.png, pdf) All of the simple patch primitives in matplotlib, Rectangle, Circle, Polygon, etc, are implemented with simple path. Plotting functions like hist() and bar(), which create a number of primitives, e.g.,., you are creating an animated bar plot. We will make the histogram chart by creating a series of rectangles for each histogram bar: the rectangle width is the bin width and the rectangle height is the number of datapoints in that bin. First we’ll create some random normally distributed data and compute the histogram. Because numpy returns the bin edges and not centers, the length of bins is 1 greater than the length of n in the example below: # histogram our data with numpy data = np.random.randn(1000) n, bins = np.histogram(data, 100) We’ll now extract the corners of the rectangles. Each of the left, bottom, etc, arrays below is len(n), where n is the array of counts for each histogram bar: # get the corners of the rectangles for the histogram left = np.array(bins[:-1]) right = np.array(bins[1:]) bottom = np.zeros(len(left)) top = bottom + n Now we have to construct our compound path, which will consist of a series of MOVETO, LINETO and CLOSEPOLY for each rectangle. For each rectangle, we need 5 vertices: 1 for the MOVETO, 3 for the LINETO, and 1 for the CLOSEPOLY. As indicated in the table above, the vertex for the closepoly is ignored but we still need it to keep the codes aligned with the vertices: All that remains is to create the path, attach it to a PathPatch, and add it to our axes: barpath = path.Path(verts, codes) patch = patches.PathPatch(barpath, facecolor='green', edgecolor='yellow', alpha=0.5) ax.add_patch(patch) Here is the result (Source code, png, hires.png, pdf)
http://matplotlib.org/users/path_tutorial.html
CC-MAIN-2016-18
refinedweb
559
67.55
Odoo Help This community is for beginners and experts willing to share their Odoo knowledge. It's not a forum to discuss ideas, but a knowledge base of questions and their answers. how to refer to actual user in a transition condition how to refer to actual user in a transition condition. For example: In the flow hr.wkf.holidays we have a transition from the confirm state to the first_validate where the condition is double_validation and the required group is HHRR/Director, which is fine. But we need to state that the approver should actually be the director of the requesting employee and not a general director. So we wanted to change the condition this way: double validation and (employee_id.parent_id.user_id == user.id) i.e. that the one who will liberate is the director of the requesting employee, but I got the error that the "user" object is not known. So the question is how to refer to the actual user in a condition? Hello, the only way to do it is to add a function to validate your transition in the workflow. In your case, the function should be something like : def is_officer_director(self, cr, uid, ids, *args): for leave in self.browse(cr, uid, ids): if uid==leave.employee_id.parent_id.user_id.id: return True else: return False You can find a step-by-step procedure in the question #27239 "Prevent HR Managers from approving their own leave requests". Marc. PS: please vote if you find!
https://www.odoo.com/forum/help-1/question/how-to-refer-to-actual-user-in-a-transition-condition-16252
CC-MAIN-2016-50
refinedweb
249
54.73
Sendmail introduced a new API beginning with version 8.10 - libmilter. Sendmail 8.12 officially released libmilter. Version 8.12 seems to be more robust, and includes new privilege separation features to enhance security. Even better, sendmail 8.13 supports socket maps, which makes pysrs much more efficient and secure. Sendmail 8.14 finally supports modifying MAIL FROM via the milter API, and a data callback allowing spam to be rejected before beginning the DATA phase (even after accepting some recipients). You may be required to register your user nickname (nick) and identify with that nick. Otherwise, you may not be able to join or be heard on the IRC channel. There is a page describing how to register your nick at freenode.net. SRS SES spf gossip DNS At the lowest level, the milter module provides a thin wrapper around the sendmail libmilter API. This API lets you register callbacks for a number of events in the process of sendmail receiving a message via SMTP. These events include the initial connection from a MTA, the envelope sender and recipients, the top level mail headers, and the message body. There are options to mangle all of these components of the message as it passes through the milter. milter At the next level, the Milter module (note the case difference) provides a Python friendly object oriented wrapper for the low level API. To use the Milter module, an application registers a 'factory' to create an object for each connection from a MTA to sendmail. These connection objects must provide methods corresponding to the libmilter callback events. Milter Each event method returns a code to tell sendmail whether to proceed with processing the message. This is a big advantage of milters over other mail filtering systems. Unwanted mail can be stopped in its tracks at the earliest possible point. The Milter.Milter class provides default implementations for event methods that do nothing, and also provides wrappers for the libmilter methods to mutate the message. Milter.Milter The mime module provides a wrapper for the Python email package that fixes some bugs, and simplifies modifying selected parts of a MIME message. mime Finally, the bms.py application is both a sample of how to use the Milter and spf modules, and the beginnings of a general purpose SPAM filtering, wiretapping, SPF checking, and Win32 virus protecting milter. It can make use of the pysrs package when available for SRS/SES checking and the pydspam package for Bayesian content filtering. SPF checking requires pydns. Configuration documentation is currently included as comments in the sample config file for the bms.py milter. See also the HOWTO and Milter Log Message Tags. Python milter is under GPL. The authors can probably be convinced to change this to LGPL if needed. The Python milter package includes a sample milter that replaces dangerous attachments with a warning message, discards mail addressed to MAILER-DAEMON, and demonstrates several SPAM abatement strategies. The MimeMessage class to do this used to be based on the mimetools and multifile standard python packages. As of milter version 0.6.0, it is based on the email standard python packages, which were derived from the mimelib project. The MimeMessage class patches several bugs in the email package, and provides some backward compatibility. mimetools multifile The "defang" function of the sample milter was inspired by MIMEDefang, a Perl milter with flexible attachment processing options. The latest version of MIMEDefang uses an apache style process pool to avoid reloading the Perl interpreter for each message. This makes it fast enough for production without using Perl threading. mailchecker is a Python project to provide flexible attachment processing for mail. I will be looking at plugging mailchecker into a milter. TMDA is a Python project to require confirmation the first time someone tries to send to your mailbox. This would be a nice feature to have in a milter. For example, the HTML parsing feature to remove scripts from HTML attachments is rather CPU intensive in pure python. Using the C replacement for sgmllib greatly speeds things up. ~/.forwarders [wiretap] To Bcc a message, call self.add_recipient(rcpt) in envfrom after determining whether you want to copy (e.g. whether the sender is local). For example, self.add_recipient(rcpt) def envfrom(... ... if len(t) == 2: self.rejectvirus = t[1] in reject_virus_from if t[0] in wiretap_users.get(t[1],()): self.add_recipient(wiretap_dest) if t[1] == 'mydomain.com': self.add_recipient('<copy-%s>' % t[0]) ... To make this a generic feature requires thinking about how the configuration would look. Feel free to make specific suggestions about config file entries. Be sure to handle both Bcc and file copies, and designating what mail should be copied. How should "outgoing" be defined? Implementing it is easy once the configuration is designed.
https://pythonhosted.org/milter/
CC-MAIN-2020-29
refinedweb
799
57.57
This article demonstrates a multi-serial port terminal with a plug-in architecture to allow different views. This started off as an internal project by myself for our company Pi Logic. I thought that it might be useful to others who do serial port development. The source zip file contains one Visual Studio 2005 solution with three projects. This is the actual program, it is very simplistic because most of the important stuff happens in the support libraries. This implements the core functionality of the terminal program. This was separated out into a DLL so that the plugins can reference this one without having the program's code cluttering up things. This is a simple implementation of a plug-in viewer, it derives from PortWindow which has some basic controls to support adding ports, etc. and parses data (with no error handling) to plot a graph of the values. PortWindow To see this in action, send it two double values in the range 0-10 separated by a comma and it will plot the value as it receives it. One driver which I have found invaluable in this project and in others is com0com which is a null-modem emulator. Basically it creates two virtual COM ports and maps the input and output of each one to the output and input of the other respectively, resulting in a software COM port for testing stuff. Docking has been accomplished through Weifen Luo's Dock Panel Suite. The GraphWindow demo was accomplished using ZedGraph. GraphWindow The file associations are managed by Bredan Grant's System File Association classes, with the namespace changed for ease of use. Sorry the article is so short. Hopefully when I get some time, I shall update it to include more code snippets and more detailed explanations of how things operate. Please let me know of any bugs as this was written overnight from an existing code-base (Terminal 2 by coincidence) so I haven't fully tested it. This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL) mjkuwp94 wrote:Anyway, my question is whether you have any updates to this code beyond what you uploaded years back. mjkuwp94 wrote:Anyway, thanks for the quick reply and have fun with the low level stuff. Seeing you are into FPGA then you obviously are far beyond Arduino/AVR level already. General News Suggestion Question Bug Answer Joke Rant Admin Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.
http://www.codeproject.com/Articles/19081/Terminal
CC-MAIN-2014-52
refinedweb
430
61.06
Hi David, On Mon, 2004-10-04 at 01:01, David Holmes wrote: > I think you will find that all the Java specifications are protected by a > similar license (which basically preserves the namespace usage and requires > complete conformance from an implementation). It got worse the last years. Specs, or at least draft specs would be published publicly without having any click-through license to which people have to consent. There are also some nice counter examples though of expert groups doing everything publicly (JSR133 about the memory model, JSR166 about concurrency util classes). Besides, the terms/claims in these click-through documents seems to change over time, so if we really need to accept them to be used as primary source of information when working on GNU Classpath then we need to (re)check each time. > Even specs that get printed > will have a license included in the book. Only third party books that > describe an API will not have such a license, but nor are they definitive > sources of information on an API specification. There is a lot of case law about using publicly published information from printed books. So books (with a normal ISBN number) are always prefered to use as authorative source. If that means not having the "definitive source" then so be it. Programmers will use published books or publicly published articles to write their programs, so we better make sure we are at least compatible with what they use/expect. > Best get this cleared through FSF legal ASAP. It is pretty clear. Use public documentation, which doesn't need you to consent to any additional click-through terms, as primary source when working on GNU Classpath, preferably books. For anything else we (FSF Legal) needs to look at the specific terms. Since as noticed above the terms are not always the same. FSF Legal will always advise not to take any unnessecary risks that might endanger the (perceived) free software status of a GNU project. (If we might need to go to court to proof that what we did was OK, then don't!) Cheers, Mark signature.asc Description: This is a digitally signed message part
http://lists.gnu.org/archive/html/classpath/2004-10/msg00014.html
CC-MAIN-2019-22
refinedweb
362
62.17
The dpopen() library function is used to open db files. #include <depot.h> DB * dpopen(const char * filename, int omode, int bnum); The first argument is the name of the file to use for the database.[4] The omode specifies how the file should be accessed, and should be DP_OREADER or DP_OWRITER, depending on whether the program wants read or write access to the database. By default, the database is locked to allow multiple programs read access or a single program write access. If the application does not want qdbm to perform any locking, DP_ONOLCK may be bitwise OR'ed with omode. [4] Unlike some database libraries that use multiple files, commonly ending with .pag and .dir,the Depot library uses a single file. When applications are creating new databases, they should also bitwise OR DP_CREAT to tell qdbm to create a new file if it does not already exist. The DP_OTRUNC flag causes whatever contents filename originally contained to be erased and replaced with an empty database. The final parameter for dpopen(), bnum, tells qdbm how many buckets to use in the hash array. The lower this number is, the smaller the database; the larger it is, the faster it is, due to reducing the number of hash collisions. The qdbm documentation recommends that this number be anywhere from half to four times the number of items that are expected to be in the database.[5] If you are not sure what number to use, zero gives a default value.[6] [5] For a good introduction to hash tables, see [Cormen, 1992]. [6] This value can be changed only by optimizing the database with dpoptimize(), which is documented on the qdbm Web site. dpopen() returns a pointer to a DEPOT structure, which is passed into the rest of the Depot functions. If an error occurs, dpopen() returns NULL and sets dpecode. Database files are closed through dpclose(). int dpclose(DEPOT * depot); The dpclose() function returns zero on success, and nonzero if it fails, which can occur if the database's buffers cannot be flushed for any reason. Here is an example program that opens a database file in the current directory and immediately closes it: 1: /* qdbmsimple.c */ 2: 3: #include <depot.h> 4: #include <errno.h> 5: #include <fcntl.h> 6: #include <stdio.h> 7: 8: int main(void) { 9: DEPOT * dp; 10: 11: dp = dpopen("test.db", DP_OWRITER | DP_OCREAT, 0); 12: if (!dp) { 13: printf("error: %s\n", dperrmsg(dpecode)); 14: return 1; 15: } 16: 17: dpclose(dp); 18: 19: return 0; 20: } While qdbm provides automatic locking, some programs may wish to substitute their own locking logic. To enable this, qdbm provides access to the file descriptor that refers to the database. int dpfdesc(DEPOT * depot); This function returns the file descriptor the database referred to by depot.[7] [7] While qdbm makes the file descriptor available, be careful how you use it. All reading and writing to the file should be done through the qdbm library; operations that do not modify the data of the file, such as locking or setting the close-on-exec flag are acceptable. Qdbm caches data in RAM to provide faster database access, and the Linux kernel caches disk writes for low-latency write() calls. An application can ensure that the on-disk database is consistent with the buffered structures by syncing the database. When a database is synced, qdbm flushes all its internal buffers and calls fsync() on the file descriptor. int dpsync(DEPOT * depot);
https://flylib.com/books/en/1.381.1.145/1/
CC-MAIN-2021-39
refinedweb
586
63.8
On 2/27/2012 5:24 PM, Daniel Reicher wrote: > I've seen pockets of discussion regarding component creation but nothing > formalized (it seems) and I think it might be useful to have some process > in place - even a loose one. For the purpose of opening a discussion, I'll > use a mythical ProgressBar component... As I understand it; the Apache way is that "if it didn't happen on the list, it didn't happen." I expect most "new" component development will be done by people who have an "Itch to scratch." and do something, then donate it. It doesn't have to be a huge thing with tons of discussion before or after. I don't think we need a huge central repository of pre-development docs; although I do believe it is important to have documentation. > Is there a list tag for discussing implementation/architecture for a > specific component or piece of functionality? not explicitly, and I'm not sure if I would recommend creating / using one. > Is the current "group think" to continue the component, MXML Spark Skin, > code-based/optimized Mobile Skin architecture? Lots of people are all over the place on this. There has been some talk about building a whole new component architecture designed from the ground up for deployment to multiple platforms (Such as HTML/JS). > How closely should a Spark component that has an mx equivalent adhere to > the functionality of the mx component? It doesn't matter. But if you feel something is missing in one or the other you are welcome to make updates and submit them. > Should spark components have clean separation from the mx namespace? I thought they did? > Should components be "allowed" to be mobile-only or desktop-only or should > everything be available in both scenarios unless there is an extremely > overwhelming rationale not to? We already have mobile only components; and "non-mobile" only components. I think the answer of "Should this be allowed" is already addressed; because that is the way it is. When you build a new component, build it for what you need. IT can later be ported over to mobile or non-mobile at your discretion. -- Jeffry Houser Technical Entrepreneur 203-379-0773 -- UI Flex Components: Tested! Supported! Ready! -- -- Part of the DotComIt Brain Trust
http://mail-archives.apache.org/mod_mbox/incubator-flex-dev/201202.mbox/%3C4F4C254E.7030002@dot-com-it.com%3E
CC-MAIN-2017-22
refinedweb
385
64.61