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 |
|---|---|---|---|---|---|
All of dW
-----------------
AIX and UNIX
Information Mgmt
Lotus
Rational
Tivoli
WebSphere
-----------------
Java technology
Linux
Open source
SOA & Web services
Web development
XML
-----------------
dW forums
-----------------
alphaWorks
-----------------
All of IBM
Python development using the Eclipse IDE and Apache Ant build tool
Document options requiring JavaScript are not displayed
Sample code
Connect to your technical community
Help us improve this content
Level: Intermediate
Ron Smith (ron.smith@rpstechnologies.net), Principal, RPS Technologies, Inc
15 Jun 2004
Python is a flexible and powerful dynamic scripting language with full object-oriented features. Its many proponents say that the Python language allows them to express their intentions more directly and efficiently than other languages. But newcomers to Python from the Java technology™ or Microsoft® .NET world may find themselves missing their feature-rich and polished IDEs and development tools. Those developers can look to familiar Java tools for a solution. This article highlights the use of the popular Java technology-based Eclipse and Apache Ant development tools for Python development.
Introduction
There has been a good deal of cross pollination between the Java language and Python camps over the years. Probably the most prominent example of this is Jython, the pure Java implementation of the Python runtime. In that tradition, you will explore the use of the Eclipse IDE and the Ant build and deployment tool for use in Python development. Eclipse and Ant are extremely popular, feature-rich, extensible, and open source; qualities shared with Python. What makes it possible to use these Java tools for Python development are the PyDev and PyAntTasks extensions to Eclipse and Ant, respectively. This article will start with pointers on downloading and installing the required tools and extensions. I'll use a working example of Python code which reads RSS feeds in order to demonstrate the use of Eclipse and Ant for Python development.
This article won't get into the details of Eclipse, Ant, or Python. See the links in the Resources section for in-depth coverage of these.
Flavors of Python supported
The software covered in this article has been tested against CPython 2.3. With some exceptions, it should also work with Jython. Specifically, the PyDev debugger does not currently support Jython. Another difference is that scripts executed via Jython go into interactive mode after being run from within PyDev, forcing you to have to kill them manually. The PyDev editor works for Jython source code, and the Python Ant tasks work with Jython with the exception of the py-doc task.
Using Eclipse for Python development
Overview of Eclipse
Eclipse is a Java technology integrated development environment that was developed and open sourced by IBM. It is the basis for IBM's commercial WebSphere Application Development environment, and various other tools. Eclipse has an extremely active community of developers who develop Eclipse itself and the large number of plug-ins available for it. See the Resources section for links to the Eclipse and Eclipse plug-ins Web sites. Although traditionally a tool for Java development, several plug-ins exist for developing with other languages within Eclipse, including C/C++, Python, and Perl.
Within Eclipse, source code is organized into projects. Projects may be loaded, unloaded, and imported. The Eclipse user interface is structured into views and editors. Examples of views and editors include the source code outline view, Java source editor, Python source editor, and filesystem navigator view. One of the key metaphors within the Eclipse user interface is the perspective. Perspectives are an organization of views that would typically be used together when carrying out some type of activity. The perspectives that are standard with Eclipse are: Debug, Java Browsing, Java, Java Type Hierarchy, Plug-in Development, CVS Repository Exploring, Resource, and the Install/Update perspective. A separate Python perspective does not currently exist. When doing Python development, I typically use the Resource perspective and Debug perspective.
Installing PyDev
To get started, download and install Eclipse from the Eclipse Web site (see link in Resources section), following the installation instructions appropriate for your platform.
The Eclipse update facility makes it easy to install the PyDev plug-in. From within Eclipse, select Help > Software Updates > Update Manager to start the Install/Update perspective. In the Feature Updates view at the bottom left, add the PyDev plug-in update site as a new Site Bookmark under the folder "Sites to Visit". The Eclipse update site URL for PyDev is. "PyDev" should now be displayed as a feature in the Feature Updates editor. In the Feature Updates editor, expand PyDev > Other, and select the PyDev feature which is displayed (should be at least 0.4.1). Then select "Install Now" to install the feature. Eclipse will download the PyDev plug-in and install it into Eclipse.
Importing the sample project
To access the sample code used within this project, download the zip file (see Resources section), expand the zip file into your filesystem, and then import the contained project into Eclipse. To import the project, switch into the Resource perspective, select File > Import, select "Existing Project into Workspace", and select the location where you expanded the zip file. The feedParserTest project should now appear in the Navigator view.
For the sample project, I've included the Feed Parser universal feed parser library, which is distributed under the Python open source license. See the Resources section for a link to the Feed Parser project Web site.
A tour of PyDev
You'll now learn how to use the imported project to explore PyDev's features. PyDev is a work in progress, but is already a very effective development environment for Python development. The current list of PyDev features includes:
PyDev preferences window
The PyDev preferences can be reached via Window > Preferences and selecting Pydev (see Figure 1). The first set of preferences lets you change settings on how PyDev treats tabs within source code, and to change syntax coloring.
Setting the Python interpreter
The PyDev Debug preferences let you choose the Python interpreter that PyDev will use to execute your Python code. If PyDev is not able to find your Python interpreter, or if you want to use a different one, configure it here (see Figure 2).
Working with source code
I do most of my Python work within the Resource perspective. Switch into the Resource perspective, and in the Navigator view at the top left, double click on the file feedParserTest/src/feedparserTest/FeedparserTest.py. The Python editor opens the file, parsing the Python syntax for syntax coloring and syntax checking (see Figure 3).
If any errors are found in the source, they are displayed in the Tasks view at the bottom right. Double clicking on an error in the Tasks view will take you to the offending line of code.
The Outline view at the bottom left displays a browsable structure of the file currently being edited. Imports, classes, and functions are displayed, and may be navigated to by clicking on the item in the Outline view. PyDev re-parses the Python file as it is being edited, and updates the Outline view, performs syntax checking, and syntax coloring.
Editor features
The PyDev 0.4 release added a function and import hyperlink feature to the Python source editor. If you hold down the control key while hovering over an import or a function call that is on the PYTHONPATH, PyDev will display a hyperlink, allowing you to navigate to the source of the import or function. Note that in order for this to work for your source code across modules (linking from one module to another), you'll have to change your PYTHONPATH environment variable to include those modules so that PyDev can find them.
PYTHONPATH
Some nice-to-have source editing features have started being added to PyDev in the latest release, including block comment/uncomment, and shift code right/left (see Figure 4).
Running a Python script
An IDE isn't very useful if you're not able to execute code. To execute Python code, select the feedparser.py file within the Navigator view, right click, and select Python > Run. The Python launch configuration window will be displayed (see Figure 5).
The Python launch configuration window gives you the ability to specify the current working directory from which the script will be executed, arguments to pass to the script, and what Python interpreter should be used to run the script. feedparser.py takes an RSS URL as an argument, so fill one in the arguments field, such as. The rest of the default options are fine, so click Run.
The script is executed and the output is displayed in the Console window. If any errors occurred, a stack trace is displayed in the Console window and the lines within the stack trace are hyperlinks to the Python source code.
Python the navigator view, right click and select "Python > Debug..." A launch configuration similar to before will be displayed. Click Debug to enter the Debug perspective and to launch the debugger.
The Debug view in the top left shows the processes and threads that are currently executing, the Variables view in the top right displays variables that are currently in scope, the Python editor shows at which line of code the debugger is currently stopped, and any output is displayed in the Console view. The debugger can be controlled via the buttons at the top of the Debug view or via the Run menu.
Other Eclipse features
Eclipse and its plug-ins have many other features which are applicable to Python development, including XML editors, UML editors (although most are Java code-centric), and source control plug-ins. Currently, almost 500 plug-ins are listed on the Eclipse plug-ins site (see link in the Resources section). Without going into detail, I'll highlight one plug-in in particular that would be useful to many Python developers: the CVS plug-in which is included as a part of the Eclipse distribution.
Eclipse includes a very feature-rich integration with CVS:
Support for other source control systems such as ClearCase, Subversion, and Visual SourceSafe is provided by other plug-ins.
Using the Python interactive shell within Eclipse
The Python interpreter supports interactive execution of Python code. This can be very handy for trying out pieces of code without putting them into a Python script and executing the script. And the Python interpreter interactive mode can be very easily integrated into Eclipse.
To add support for interactive execution of Python, add an External Tool launcher via Run > External Tools > External Tools. This will bring up the External Tools launcher configuration window. Create a new configuration by selecting "Program" in the Configurations list, and click "New". Name the configuration something like "pythonInteractive", set the Location to point to your Python interpreter, and pass "-i" as the single argument (see Figure 7).
Under the Common tab, check the box to display this configuration in the External Tools favorites menu.
To run the launcher you just created from within Eclipse, select Run > External Tools > pythonInterpreter. The Python interpreter output is displayed in the Console view. Python commands may be typed into the Console and executed just as they are when executing Python from the command line. In order to import and use your modules within Python in interactive mode, you'll need to add the location of your modules to the PYTHONPATH environment variable.
The one difference in executing Python within the Eclipse Console from when executing on the command line is that the command history feature (accessible via the up arrow and down arrow) isn't enabled because the Eclipse Console interprets these keys itself.
Using Ant for Python development
Python automatically compiles modules when it needs to. This means that Python developers don't typically have to explicitly compile modules. Nonetheless, there are cases when it’s useful to manually compile Python code, and there are many other aspects of the build and deployment process that could be automated. This is what build tools are for.
I'll highlight a build tool from the Java programming world, Apache Ant, which is largely applicable to Python development. Apache Ant is the de-facto standard build tool within the Java programming world. It was created as a more portable and Java technology-friendly alternative to other build tools. Ant will run on any platform that supports Java programming language. Although most of what was required was already provided by Ant, there were some key Python-specific features that were needed if Ant was going to serve as a Python build tool. I've developed some custom Ant plug-ins (tasks in Ant lingo) which provide Python-specific features needed to do Python builds.
Ant uses XML as its format for describing builds. A build file is organized into targets to be carried out. Each target may depend on other targets. Ant will execute whatever targets necessary based on the target you request be executed, and the set of depended-upon targets. Each target may contain any number of Ant tasks which actually carry out the work of the target. Ant has many built-in tasks for things such as compiling Java code, generating documentation, manipulating files and directories, and there are many add-on tasks provided by third parties.
Installing the Python Ant library
I'll introduce the basics of an Ant build script and the Python Ant tasks by working through creating a build script for the feedparser test project. In order to use the Python Ant tasks, you'll need to download and install the Java library that contains these tasks. First, download the Python Ant tasks library (pyAntTasks.jar) from the URL listed in the Resources section. Then, copy the JAR file into the lib directory of the Ant plug-in within Eclipse. Under your Eclipse install directory, it should be in a directory like plugins/org.apache.ant_1.5.3.
Once you've copied in the Python Ant tasks library, it must be enabled within Eclipse. Select Window > Preferences, and thenAnt > Runtime. Expand out the Ant Home Entries to see the list of libraries (JAR files) that Eclipse uses. Add the Python Ant JAR file you just copied by selecting "Add JARs" and selecting the Python Ant JAR file within the Eclipse Ant plug-ins lib directory (see Figure 8).
You should now be able to create and run Ant build scripts that contain the Python tasks. So onto creating the build script!
Creating the build script
I'll step through the creation of a simple Python build script (see Listing 1). The complete build script, build.xml, can be found in the top directory of the feedParserTest project.
<project name="feedParserTest" default="compile">
<taskdef resource="pyAntTasks.properties"/>
<property name="src.dir" value="src"/>
<target name="compile">
<py-compile
</target>
</project>
Let's start with a build script that just compiles the example Python code. The <project> tag is always the root tag of the build script. The <taskdef> tag declares the Python tasks you'll be using throughout the build script. Near the bottom of the build script, you will define the compile target. Inside of the target element are the tasks that are carried out when compile is run. In particular, the py-compile task is used to compile all Python code starting in the src directory. The task will recursively go into any subdirectories and compile any Python modules. Rather than hard-coding the path to the src directory everywhere it will be needed, you've defined it as a property called src.dir within the build script. Then, wherever it is needed, it can be referred to via ${src.dir}.
compile
${src.dir}
To run the build script, open the build script within Eclipse. Eclipse has built-in support for editing and navigating Ant build scripts. The Outline view should display the structure of the build script. In the Navigator view, select the build script, right click and select "Run Ant...". Select the compile target, and click on "Run". The output of the build script execution should be displayed on the Console view, showing a successful run.
Python script execution task
Next, you'll add a target to the build script to execute a Python script (see Listing 2). In this case, you'll execute the feedparser.py script, which takes an RSS URL as an argument.
<target name="run.feedparser" depends="compile">
<py-run
<arg value="">
</py-run>
</target>
The above target executes the feedparser.py script, passing the RSS URL as the single argument. The target is declared to depend on the compile target, so it will be executed first. This actually isn't really necessary because Python will automatically compile the source code if needed. If you execute the run.feedparser target, the feedparser.py script should run, outputting the RSS content to the Console.
run.feedparser
Python documentation task
Python has an API documentation facility similar to Java technology’s JavaDoc system, called PyDoc. The following snippet of XML in Listing 3 added to your build script will generate PyDocs for all of your Python modules.
1: <property name="pydoc.dir" value="pydoc"/>
2:
3: <target name="init">
4: <mkdir dir="${pydoc.dir}"/>
5: </target>
6:
7: <target name="pydoc" depends="init,compile">
8: <py-doc
9: <fileset dir="${src.dir}">
10: <include name="**/*"/>
11: </fileset>
12: </py-doc>
13: </target>
Deconstructing the pydoc target above, line 7 declares the target name, and indicates it depends on the init and compile targets. This means that prior to running the pydoc target, Ant will make sure that the init and compile targets have already been run, and will run them if not.
pydoc
init
The init target, which the pydoc target depends on, is defined in lines 3-5. The init target simply creates a directory to hold PyDoc API documentation files. As before, you've defined a property, named pydoc.dir, for the location of the generated documentation.
Line 8 is the start of the py-doc task. As before, you pass the PYTHONPATH you want to use in generating the pydocs. The destdir attribute tells the py-doc task where to output the generated HTML documentation.
destdir
Lines 9-11 specify what Python source files should be processed when generating documentation. The fileset is a common construct in Ant scripts, used to specify a collection of files to operate on. This is a powerful feature allowing you to use naming patterns, boolean logic, and file attributes to select what files to operate on. This is fully documented in the Ant documentation. In this case, you're recursively selecting all files starting with the 'src' directory.
Python unit test task
Python comes standard with a unit testing framework (as of Python 2.3. In Python 2.2, it was an optional module), much like the Java jUnit framework. Test cases are structured in the same manner as jUnit. Each class/module to be tested would typically have its own test class. The test class contains test fixtures, which are initialized in a setUp function. Each test is written as a separate test function within the test class. The unittest framework will cycle through the test functions, calling setUp, the test function, then tearDown for each test function. See Listing 4 for an example.
setUp
tearDown
import unittest
from pprint import pprint
import feedparser
class FeedparserTest(unittest.TestCase):
"""
A test class for the feedparser module.
"""
def setUp(self):
"""
set up data used in the tests.
setUp is called before each test function execution.
"""
self.developerWorksUrl = "testData/developerworks.rss"
def testParse09Rss(self):
"""
Test a successful run of the parse function for a
0.91 RSS feed.
"""
print "FeedparserTest.testParse09RSS()"
result = feedparser.parse(self.developerWorksUrl)
pprint(result)
self.assertEqual(0, result['bozo'])
self.assert_(result is not None)
channel = result['channel']
self.assert_(channel is not None)
chanDesc = channel['description']
self.assertEqual(u'The latest content from IBM developerWorks',
chanDesc)
items = result['items']
self.assert_(items is not None)
self.assert_(len(items)> 3)
firstItem = items[0]
title = firstItem['title']
self.assertEqual(u'Build installation packages with
solution installation and deployment technologies',
title)
def tearDown(self):
"""
tear down any data used in tests
tearDown is called after each test function execution.
"""
pass
if __name__ == '__main__':
unittest.main()
The above listing is a test class which performs basic tests on the feedparser module. The complete test class can be found in the feedParserTest project under src/feedparserTest/FeedparserTest.py. The setUp function prepares the test fixtures used throughout the tests, in this case just the path to the test RSS file you'll parse in the test function. testParse09Rss is the actual test function. This function calls the feedparser.parse function with the test RSS file, outputs the parsed results, and performs some basic checks via the TestCase class assert functions. If any assertion does not evaluate to true, or if any exceptions are thrown as a part of processing, unittest will report it as a test failure or error. Finally, the two lines at the bottom allow you to run the tests within this test class by simply running this module.
testParse09Rss
To run this test class by itself, run the FeedparserTest.py module in the same manner as before. Select the FeedparserTest.py module in the Eclipse Navigator view, and run via Python > Run. The launch configuration window will be displayed. The default values are fine except for the Base directory. The Base directory has to be the feedParserTest project directory, so that the RSS file (testData/developerworks.rss) can be found from the current directory. Change the base directory setting and click 'Run'. The output will be displayed on the Console.
You'd like any unit tests we write to be executed automatically as a part of the build. The following build fragment in Listing 5, added to your build script, will do just that.
1: <target name="tests" depends="compile">
2: <py-test
3: <fileset dir="${src.dir}">
4: <include name="**/*Test.py"/>
5: </fileset>
6: </py-test>
7: </target>
The first line is the target declaration, the same as the others. Lines 2 through 6 invoke the py-test task. These lines will run any tests found anywhere under the 'src' directory, looking for any files that end in 'Test.py'. The PYTHONPATH will be set to 'src', and the tests will be executed with the current working directory set to the current directory ('.').
To run the target, run the build script, and select the 'tests' target to execute. The target will run all test cases that end with 'Test.py', in this case just FeedparserTest.py.
Summary
The combination of Eclipse and the PyDev plug-in, and Apache Ant along with the Python Ant tasks provide a complete integrated development environment and build/deployment tool for Python development. These tools are undergoing development, so check for updates periodically, and if you feel an itch for a feature you'd like to see, consider rolling up your sleeves and pitching in.
Download
Resources
About the author
Ron Smith is founder of RPS Technologies, Inc, a software development and software consulting company based in the Chicago area. Ron Smith consults for clients developing J2EE-based enterprise applications and develops software products within RPS Technologies. You can contact Ron at ron.smith@rpstechnologies.net.
Rate this page
Please take a moment to complete this form to help us better serve you.
Did the information help you to achieve your goal?
Please provide us with comments to help improve this page:
How useful is the information? | http://www.ibm.com/developerworks/opensource/library/os-ecant/ | crawl-002 | refinedweb | 3,927 | 55.64 |
Home >> 8m pole 60w solar led street lamps for sale.
mr universal lighting 60w solar street light. r884.00 . view offer. mr universal lighting solar street light 60w gry woodland scenics just plug n scale street lights wooden pole. just plug woodland scenics n scale street lights wooden pole yetaha 20pcs model railway train model street lights led dual lampposts ho oo scale leds dualaiwan 60w 8m solar street light find details about 60w solar street light, 60w 8m solar street light, solar road light, solar lighting from taiwan street light supplier luckwell co., ltd.).
if you want to buy cheap solar street light, choose solar street light from banggood . it endeavors to provide the products that you want, offering the best bang for your buck. whatever solar street light styles you want, can be easily bought here..
60w all in one solar power street light led street light price list (smln 60w), us $ 200 750 / set, solar street light, smln 60w, ip67.source from jinhua sunmaster solar lighting co., ltd. on . delight 60w high power solar led street light with high quality wholesale, leading delight 60w high power solar led street light manufacturers & suppliers, find delight 60w high power solar led street light factory&exporters, delight 60w high power solar led street light for sale.
various types of 60w led street lamp street solar light, us $ 120 360 / set, dc12/24v, 6000, 75.source from jiangsu shixin landscape lighting co., ltd. on .
china 120w solar led street light hot dip galvanizing ploe, find details about china led light pole, led lamps from 120w solar led street light hot dip galvanizing ploe jiangsu shixin landscape lighting
solar, solar light, solar street light manufacturer / supplier in china, offering 8m 60w solar street light for outdoor lighting, 12v 100w semi flexible solar panel for rv caravan motorhome, high efficiency semi flexible sunpower 100w solar panel and so on.
led street light f1 for 20 60w. more info. led street light f2 for 60 120w. more info. led street light f3 for 90 180w. more info .. lm led grow light solar power systems lighting energy management contracting intelligent lighting control system. contact kaich. email [email protected] .
solar street light, solar street lights, solar street lighting manufacturer / supplier in china, offering baode lights 8m 60w led solar street light, outdoor lights 9m pole 60w configuration solar street lighting with lithium battery, prices of 6m 32w rising sun soalr street light controller and so on.
60w led lamps, find complete details about 60w led lamps, 60w led lamps, 60w led street lights, 60w led street lamp yangzhou bright solar solutions co., ltd.
import quality solar street light pole supplied by experienced manufacturers at global sources .. cetc 30w/40w/50w/60w street light solar power lamp with 8m pole for highway road, garden light us$ 100 140 / set all in one solar power street light for 8m height pole led solar lighting with microwave senor us$ 280 / piece; 1 piece (min
buy quality cree solar led street light and source cree solar led street light from reliable global cree solar led street light suppliers. find quality cree solar led street light at lights & lighting, sample house and more on m.alibaba.
at greenshine new energy, we offer three state of the art systems perfect for solar street lighting. in our supera, brighta, and lumina series , you ll find high quality led fixtures that couple with solar panels for maximum efficiency and savings.
read garden wall lights 60w reviews and garden wall lights 60w ratings buy garden wall lights 60w with confidence on aliexpress charge controller with lamp lamp mount pole home to the streets for garden light bulb on the lamp street lighting mount for led lighting pole solar lamp outdoor street the batteries solar motion street lantern
this solar powered 60w led light would be an excellent addition to any street or parking lot area that is in need of an efficient and effective way of brightening up an area. this street and parking lot light is a 60w solar powered led light that will give off great light to wherever it may be placed. this light has bluetooth capabilities which would allow for lighting modes to be modified to | http://arllen.cz/2001/8m-pole-60w-solar-led-street-lamps-for-sale.html | CC-MAIN-2021-04 | refinedweb | 705 | 63.12 |
Hi Guys,
I have a data loaded to wix-storage session.
I have no problem loading the data from the storage, with the code below.
import {session} from 'wix-storage'; $w.onReady(function () { let productid = session.getItem('productid'); $w('#productidinput').value = productid; });
The problem I am facing is that the data can only be loaded to the first slide on my Slider, but not the third slide where i want it to be.
How can i fix this ?
Thank you in advance.
Hi,
To which slider you were referring? I'm not sure that I fully understand the scenario. Can you please add a screencast of the issue so that we can better understand what you were referring? Simply recreate the issue while recording the steps and add the screencast.com URL to your response.
Thanks,
Tal.
Hi Tal,
Thanks for your reply.
I've recorded a video, sorry for the audio volume, it's kinda low.
Heres the problem im facing. I hope you can help. Thank you in advance.
Anyone ? Need help.
Thanks.
Hi,
You should check if it's the last slide of the slider, and if so - set the value to the relevant element. It should be something similar to this:
Moreover, I recommend checking out our Gift Quiz example, which has a similar scenario.
Good luck,
Tal.
Hi Tal,
Thank you for taking your time helping. I used your code and have succeeded adding the productID to my text field located in the last slide. However, when the form is submitted, the value is not submitted into the backend database, (it shows up blank in the table). It is only submitted when the code is inside $w.onReady . which works only (on the first slide when the page is loaded). Not working for the third slide. Any ideas?
Thank you in advance Tal.
Hi,
I don't know how you've inserted the information to the collection. You can use the insert function for that purpose. Should the issue persists, please share with us the code you've written.
Tal. | https://www.wix.com/corvid/forum/community-discussion/wix-session-storage-data-loading-to-a-slider-s-3rd-slide | CC-MAIN-2019-47 | refinedweb | 345 | 77.33 |
12
May
Posted by Derek@TheDailyLinux in Programming » 23 Comments »
Grab Raw Keyboard Input from Event Device Node (/dev/input/event)
The following is a quick c program that will capture raw keyboard data from the event device node such as /dev/input/event1. Simply compile and run with the specific device node as an argument. ie.
./keyboard_key_capture /dev/input/event1.
#include <stdio.h> #include <stdlib.h> #include <string.h> #include <unistd.h> #include <errno.h> #include <fcntl.h> #include <dirent.h> #include <linux/input.h> #include <sys/types.h> #include <sys/stat.h> #include <sys/select.h> #include <sys/time.h> #include <termios.h> #include <signal.h> void handler (int sig) { printf ("nexiting...(%d)n", sig); exit (0); } void perror_exit (char *error) { perror (error); handler (9); } int main (int argc, char *argv[]) { struct input_event ev[64]; int fd, rd, value, size = sizeof (struct input_event); char name[256] = "Unknown"; char *device = NULL; //Setup check if (argv[1] == NULL){ printf("Please specify (on the command line) the path to the dev event interface devicen"); exit (0); } if ((getuid ()) != 0) printf ("You are not root! This may not work...n"); if (argc > 1) device = argv[1]; //Open Device if ((fd = open (device, O_RDONLY)) == -1) printf ("%s is not a vaild device.n", device); //Print Device Name ioctl (fd, EVIOCGNAME (sizeof (name)), name); printf ("Reading From : %s (%s)n", device, name); while (1){ if ((rd = read (fd, ev, size * 64)) < size) perror_exit ("read()"); value = ev[0].value; if (value != ' ' && ev[1].value == 1 && ev[1].type == 1){ // Only read the key press event printf ("Code[%d]n", (ev[1].code)); } } return 0; }
Here is an example output from running the above command. Notice that
Code[] is printed before the key that was pressed.
# ./keyb_key_cap_x86 /dev/input/by-id/usb-Dell_Dell_USB_Keyboard-event-kbd Reading From : /dev/input/by-id/usb-Dell_Dell_USB_Keyboard-event-kbd (Dell Dell USB Keyboard) Code[30] aCode[48] bCode[46] cCode[32] dCode[18] eCode[33] fCode[34] gCode[35] hCode[23] iCode[36] jCode[37] kCode[38] lCode[50] mCode[49] nCode[24] oCode[25] pCode[16] qCode[19] rCode[31] sCode[20] tCode[22] uCode[47] vCode[17] wCode[45] xCode[21] yCode[44] zCode[2] 1Code[3] 2Code[4] 3Code[5] 4Code[6] 5Code[7] 6Code[8] 7Code[9] 8Code[10] 9Code[11] 0
This is only an example program that I picked up from work. I hope it will be of use to somebody out there so it can quickly help you get started with your project.
Feel free to donate if this post prevented any headaches! Another way to show your appreciation is to take a gander at these relative ads that you may be interested in:
Here are some similar posts that you may be interested in:
There's 23 Comments So Far
August 12th, 2010 at 9:54 am
What license are you posting this under?
I’m including it in an keyboard monitoring app I wrote (nealy verbatim), and you
never specified a license.
August 12th, 2010 at 10:57 am
Good question. Anything I post on this site is open game to everybody. I wouldn’t say there is any license, but if I were to give it one I suppose it would fall under the BSD License which allows everyone to use and redistribute the program as they wish.
Just don’t use it for evil.
August 12th, 2010 at 2:29 pm
“Just don’t use it for evil. ;-)”
Decide yourself
The project is at
It is (in it’s slightly modified form) in “src/kbd-demo.c”
December 22nd, 2010 at 4:25 am
Hi, thank you very much for this program! I just wonder why did you skip ev[0]? it was not working for me. I have modified it in a such way:
instead of this code:
if (value != ‘ ‘ && ev[1].value == 1 && ev[1].type == 1){ // Only read the key press event
printf (“Code[%d]n”, (ev[1].code));
}
i used this:
if (ev[0].value == 1 && ev[0].type == EV_KEY) // Only read the key press event
printf (“Code[%d]n”, (ev[0].code));
December 22nd, 2010 at 8:05 am
It was more of a throw-it-together program for testing purposes. I’m happy to hear that 1) you’ve found it useful and 2) you have brought an improvement to the table! Thank you!
December 27th, 2010 at 3:37 am
Thank you for posting this. I’ve been working on the same thing for about a day now and while I can read the output from event(x) I was having a difficult time figuring out its format, especially since I haven’t had much practice with UTF. After digging through the Linux kernel device drivers I got lucky finding your included headers and got pointed in the right direction. Thanks a ton!
February 9th, 2011 at 1:22 pm
is it possible to have the ((rd = read (fd, ev, size * 64)) < size) non blocking (if no key is pressed) ?
February 9th, 2011 at 1:53 pm
hum found
sorry
O_RDONLY | O_NONBLOCK
February 15th, 2011 at 5:03 am
Thank you for this good example!
July 18th, 2011 at 6:27 am
Hi all,
I have a problem with reading USB keyboard event file. I can read this file using this program but the problem is that some characters that I type are read multiple times(2 or 3 times). Like I type on my keyboard some number, for example code(73) and my application reads this thing often 2 times, or 3 times. I’ve been looking for this all over the Internet and I didn’t find anything useable to solve this problem yet. Could anyone help me with this?
Or could anyone explain me if the keyboard event file is somehow buffered and if there is any way to clean this file after every reading from this file? Maybe this could solve my problem that some characters are read multiple – 2 or 3 times.
October 24th, 2011 at 6:40 am
Thanks man. It was really helpful
March 10th, 2012 at 9:44 am
Does not work for me? I gets stuck on the first message and then do not show any key pressed
Still works on Linux 3.x versions? Thank you
September 27th, 2012 at 8:28 am
Good, worked for me.
Note only that the \n became escaped ( “Code[%d]n” instead of “Code[%d]\n” ) on this post, and due to terminals buffering, the pressed key may be printed only after several keys are pressed (using fflush() on stdout would be safer).
December 18th, 2012 at 8:01 am
Thanks for the code. I played with it on Raspberry Pi (simple cross-compiling) and it works fine :-).
February 6th, 2013 at 10:00 am
Using this as a base for getting a cuecat working on a raspberry pi. thanks!
February 9th, 2013 at 6:44 pm
Thanks for the nice example! Was struggling to get it working on the raspberry pi – I kept getting the message “device temporary unavailable”. This error was triggered by the read() function and causes the program to exit. Seems this is not a fatal error, so I removed the perror_exit so the code now reads:
while (1){
rd = read (fd, ev, size * 64);
value = ev[0].value;
……
It now ignores errors on read() – maybe not the best way to do it – but will continue testing the device for the event. That seems to work fine and does what I want! Thanks a lot!
Rob
March 27th, 2013 at 4:36 pm
Your code reads up to 64 events at a time, but you only ever look at the first event. Why?
May 12th, 2013 at 9:36 am
Unfortunately, the /dev/input directory is full of at least 12 files matching your filespec (ubuntu 12.04):
me@ubuntu:~$ ls -la /dev/input
total 0
drwxr-xr-x 4 root root 380 May 11 21:18 .
drwxr-xr-x 18 root root 4300 May 11 21:36 ..
drwxr-xr-x 2 root root 100 May 11 21:18 by-id
drwxr-xr-x 2 root root 140 May 11 21:18 by-path
crw-r—– 1 root root 13, 64 May 11 21:18 event0
crw-r—– 1 root root 13, 65 May 11 21:18 event1
crw-r—– 1 root root 13, 74 May 11 21:18 event10
crw-r—– 1 root root 13, 75 May 11 21:18 event11
crw-r—– 1 root root 13, 66 May 11 21:18 event2
crw-r—– 1 root root 13, 67 May 11 21:18 event3
crw-r—– 1 root root 13, 68 May 11 21:18 event4
crw-r—– 1 root root 13, 69 May 11 21:18 event5
crw-r—– 1 root root 13, 70 May 11 21:18 event6
crw-r—– 1 root root 13, 71 May 11 21:18 event7
crw-r—– 1 root root 13, 72 May 11 21:18 event8
crw-r—– 1 root root 13, 73 May 11 21:18 event9
crw-r–r– 1 root root 13, 0 May 11 21:18 js0
crw-r—– 1 root root 13, 63 May 11 21:18 mice
crw-r—– 1 root root 13, 32 May 11 21:18 mouse0
So, I guess the better question would be how to determine which event device is theone that controls the active keyboard (there is usually only going to be one). Otherwise, this program is useful, but in a very restrictive, unportable way.
Who Linked To This Post?
Share your thoughts, leave a comment! | http://www.thelinuxdaily.com/2010/05/grab-raw-keyboard-input-from-event-device-node-devinputevent/ | CC-MAIN-2014-15 | refinedweb | 1,605 | 71.55 |
Island World API
If you want and need you can use Island World API in your plugins.
First, you need to insert IslandWorld.jar into your workspace as external library and import it in your project:
import pl.islandworld.api.IslandWorldApi;
also remember to add "depends" into your plugin.yml, your plugin must be loaded after IslandWorld.
You need to check if IslandWorld plugin is loaded and initialized correctly and you can use API methods:
if (IslandWorldApi.isInitialized()) { // do stuff }
if everything is ok, you can use all API methods.
To check what functions are available check our javadocs available on:
right now API have only few basic functions, if you need smth special please give me know. | https://dev.bukkit.org/projects/islandworld/pages/api | CC-MAIN-2020-29 | refinedweb | 118 | 65.73 |
Windows Forms Controls
Topics in This Chapter:
- Introduction: A class hierarchy diagram offers a natural way to group Windows Forms controls by their functionality.
- Button Controls: The Button, CheckBox, and RadioButton controls are designed to permit users to make one or more selections on a form.
- PictureBox and TextBoxt Controls: The PictureBox control is used to display and scale images; the TextBox control can be used to easily display and edit single or multiple lines of text.
- List Controls: The ListBox, ComboBox, and CheckListBox offer different interfaces for displaying and manipulating data in a list format.
- ListView and TreeView Controls: The ListView offers multiple views for displaying data items and their associated icons. The TreeView presents hierarchical information in an easy-to-navigate tree structure.
- Timer and Progress Bar Controls: A timer can be used to control when an event is invoked, a ProgressBar to visually monitor the progress of an operation.
- Building a User Control: When no control meets an application's needs, a custom one can be crafted by combining multiple controls or adding features to an existing one.
- Moving Data Between Controls: Drag and drop provides an easy way for users to copy or move an item from one control to another. .NET offers a variety of classes and events required to implement this feature.
- Using Resources: Resources required by a program, such as title, descriptive labels, and images, can be embedded within an application's assembly or stored in a satellite assembly. This is particularly useful for developing international applications.
The previous chapter introduced the Control class and the methods, properties, and events it defines for all controls. This chapter moves beyond that to examine the specific features of individual controls. It begins with a survey of the more important .NET controls, before taking an in-depth look at how to implement controls such as the TextBox, ListBox, TreeView, and ListView. Also included is a discussion of the .NET drag-and-drop features that are used to move or copy data from one control to another.
Windows Forms (WinForms) are not restricted to using the standard built-in controls. Custom GUI controls can be created by extending an existing control, building a totally new control, or fashioning a user control from a set of related widgets. Examples illustrate how to extend a control and construct a user control. The chapter concludes with a look at resource files and how they are used to create GUI applications that support users from multiple countries and cultures.
7.1 A Survey of .NET Windows Forms Controls
The System.Windows.Forms namespace contains a large family of controls that add both form and function to a Windows-based user interface. Each control inherits a common set of members from the Control class. To these, it adds the methods, properties, and events that give the control its own distinctive behavior and appearance.
Figure 7-1: Windows Forms control hierarchy
Figure 7-1 shows the inheritance hierarchy of the Windows Forms controls. The controls marked by an asterisk (*) exist primarily to provide backward compatibility between .NET 2.0 and .NET 1.x. Specifically, the DataGrid has been superseded by the DataGridView, the StatusBar by the StatusStrip, and the ToolBar by the ToolStrip. Table 7-1 provides a summary of the more frequently used controls in this hierarchy.
Table 7-1: Selected Windows Forms Controls
This chapter lacks the space to provide a detailed look at each control. Instead, it takes a selective approach that attempts to provide a flavor of the controls and feaures that most benefit the GUI developer. Notable omissions are the DataGridView control, which is included in the discussion of data binding in Chapter 12, "Data Binding with Windows Forms Controls," and the menu controls that were discussed in Chapter 6, "Building Windows Forms Applications."
There are no comments yet. Be the first to comment! | http://www.codeguru.com/csharp/sample_chapter/article.php/c11213/Windows-Forms-Controls.htm | CC-MAIN-2015-11 | refinedweb | 646 | 53.81 |
Provided by: allegro4-doc_4.4.2-13_all
NAME
adjust_sample - Alters the parameters of a sample while it is playing. Allegro game programming library.
SYNOPSIS
#include <allegro.h> void adjust_sample(const SAMPLE *spl, int vol, int pan, int freq, int loop);
DESCRIPTION
Alters the parameters of a sample while it is playing (useful for manipulating looped sounds). You can alter the volume, pan, and frequency, and can also clear the loop flag, which will stop the sample when it next reaches the end of its loop. The values of the parameters are just like those of play_sample(). If there are several copies of the same sample playing, this will adjust the first one it comes across. If the sample is not playing it has no effect.
SEE ALSO
play_sample(3alleg4), exsample(3alleg4) | http://manpages.ubuntu.com/manpages/eoan/man3/adjust_sample.3alleg4.html | CC-MAIN-2019-35 | refinedweb | 131 | 67.45 |
SQL Abstraction layer written in Python 3.2 for use in lower level applications, such as tkinter.
Project description
All SQL modules written in python follows a standard DB-API 2.0.
Thus all connections attributes and methods can be used for different SQL engines.
An abstract class, “Database” was created in order for sub classes that inherit this class to re-implement the __init__ method in order to set a connection.
Since connections is loaded differently for each SQL engine.
Attribute Connection was made private in order not to change it from a different layer and to keep the connection consistent.
Python 3.2 required
Example:
from Databases.SQLite import SQLiteDatabase
db = SQLiteDatabase(None, ‘test.db’)
results = db.select(‘table_name’, [‘name’, ‘id’])
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/python-sql-abstraction/ | CC-MAIN-2020-40 | refinedweb | 152 | 59.5 |
Network Working Group J. Galbraith
Request for Comments: 4819 J. Van Dyke
Category: Standards Track VanDyke Software
J. Bright
Silicon Circus
March 2007
Secure Shell Public Key Subsystem
Secure Shell defines a user . . . . . . . . . . . . . . . . . . . . . . . . . 3
2. Terminology . . . . . . . . . . . . . . . . . . . . . . . . . 3
3. Public Key Subsystem Overview . . . . . . . . . . . . . . . . 3
3.1. Opening the Public Key Subsystem . . . . . . . . . . . . . 4
3.2. Requests and Responses . . . . . . . . . . . . . . . . . . 5
3.3. The Status Message . . . . . . . . . . . . . . . . . . . . 5
3.3.1. Status Codes . . . . . . . . . . . . . . . . . . . . . 5
3.4. The Version Packet . . . . . . . . . . . . . . . . . . . . 6
4. Public Key Subsystem Operations . . . . . . . . . . . . . . . 7
4.1. Adding a Public Key . . . . . . . . . . . . . . . . . . . 7
4.2. Removing a Public Key . . . . . . . . . . . . . . . . . . 10
4.3. Listing Public Keys . . . . . . . . . . . . . . . . . . . 10
4.4. Listing Server Capabilities . . . . . . . . . . . . . . . 10
5. Security Considerations . . . . . . . . . . . . . . . . . . . 11
6. IANA Considerations . . . . . . . . . . . . . . . . . . . . . 12
6.1. Registrations . . . . . . . . . . . . . . . . . . . . . . 12
6.2. Names . . . . . . . . . . . . . . . . . . . . . . . . . . 12
6.2.1. Conventions for Names . . . . . . . . . . . . . . . . 12
6.2.2. Future Assignments of Names . . . . . . . . . . . . . 13
6.3. Public Key Subsystem Request Names . . . . . . . . . . . . 13
6.4. Public Key Subsystem Response Names . . . . . . . . . . . 13
6.5. Public Key Subsystem Attribute Names . . . . . . . . . . . 13
6.6. Public Key Subsystem Status Codes . . . . . . . . . . . . 14
6.6.1. Conventions . . . . . . . . . . . . . . . . . . . . . 14
6.6.2. Initial Assignments . . . . . . . . . . . . . . . . . 14
6.6.3. Future Assignments . . . . . . . . . . . . . . . . . . 15
7. References . . . . . . . . . . . . . . . . . . . . . . . . . . 15
7.1. Normative References . . . . . . . . . . . . . . . . . . . 15
7.2. Informative References . . . . . . . . . . . . . . . . . . 15
8. Acknowledgements . . . . . . . . . . . . . . . . . . . . . . . 16
1. Introduction
Secure Shell (SSH) is a protocol for secure remote login and other
secure network services over an insecure network. Secure Shell
defines a user Public Key Infrastructure
for X.509 Certificates 4, are a description of the 'name' field and the data part
of the packet.
3.3. The Status Message
A request is acknowledged by sending a status packet. If there is
data in response to the request, the status packet is sent after all
data has been sent.
string "status"
uint32 status code
string description [7]
string language tag [6]
A status message MUST be sent for any unrecognized packets, and the
request SHOULD NOT close the subsystem..
3.4. The Version Packet
Both sides MUST start a connection by sending a version packet that
indicates the version of the protocol they are using.
string "version"
uint32 protocol-version-number
This document describes version 2 of the protocol. Version 1 was
used by an early draft of this document. The version number was
incremented after changes in the handling of status packets..
4.1. Adding a Public Key
If the client wishes to add a public key, the client sends:
string "add"
string public key algorithm name
string public key blob
boolean overwrite
uint32 attribute-count
string attrib-name
string attrib-value
bool critical critical
attribute, it MUST fail the add, with the status code
SSH_PUBLICKEY_ATTRIBUTE_NOT_SUPPORTED. For the purposes of a
critical [7].
The comment field is useful so the user can identify the key without
resorting to comparing its fingerprint. This attribute SHOULD NOT be
critical.
"comment-language"
If this attribute is specified, it MUST immediately follow a
"comment" attribute and specify the language for that attribute [6].
The client MAY specify more than one comment if it additionally
specifies a different language for each of those comments. The
server SHOULD attempt to store each comment with its language
attribute. This attribute SHOULD NOT be critical.
"subsystem"
"subsystem" specifies a comma-separated list of subsystems that may
be started (using a "subsystem" request) when this key is in use.
This attribute SHOULD be critical.
"shell"
"shell" specifies that session channel "shell" requests should be
denied when this key is in use. The attribute-value field SHOULD be
empty for this attribute. This attribute SHOULD be critical.
"exec"
"exec" specifies that session channel "exec" requests should be
denied when this key is in use. The attribute-value field SHOULD be
empty for this attribute. This attribute SHOULD be critical.
"agent"
"agent" specifies that session channel "auth-agent-req" requests
should be denied when this key is in use. The attribute-value field
SHOULD be empty for this attribute. This attribute SHOULD be
critical.
"env"
"env" specifies that session channel "env" requests should be denied
when this key is in use. The attribute-value field SHOULD be empty
for this attribute. This attribute SHOULD be. For IP-based networks, it is anticipated that each element
of the "from" parameter will take the form of a specific IP address
or hostname.
critical.
In addition to the attributes specified by the client, the server MAY
provide a method for administrators to enforce certain attributes
compulsorily.
There is no requirement that the responses be in any particular
order. Whilst some server implementations may send the responses in
some order, client implementations should not rely on responses being
in any order.
Following the last "publickey" response, a status packet MUST be
sent.
Implementations SHOULD support this request..
6. IANA Considerations
This section contains conventions used in naming the namespaces, the
initial state of the registry, and instructions for future
assignments.
6.1. Registrations
Consistent with Section 4.9.5 of [8], this document makes the
following registration:
The subsystem name "publickey".
6.2. Names
In the following sections, the values for the namespaces are textual.
The conventions and instructions to the IANA for future assignments
are given in this section. The initial assignments are given in
their respective sections.
preceding [10] controlled by the person or organization defining
the name. Names are case-sensitive, and MUST NOT be longer than 64
characters. It is up to each domain how it manages its local
namespace. It has been noted that these names resemble STD 11 [9]
nothing to do with STD 11 [9]. An example of a locally defined name
is "our-attribute@example.com" (without the double quotes).
6.2.2. Future Assignments of Names
Requests for assignments of new Names MUST be done through the IETF
Consensus method as described in [11].
6.3. Public Key Subsystem Request Names
The following table lists the initial assignments of Public Key
Subsystem Request names.
Request Name
-------------
version
add
remove
list
listattributes
6.4. Public Key Subsystem Response Names
The following table lists the initial assignments of Public Key
Subsystem Response names.
Response Name
--------------
version
status
publickey
attribute
6.5. Public Key Subsystem Attribute Names
Attributes are used to define properties or restrictions for public
keys. The following table lists the initial assignments of Public
Key Subsystem Attribute names.
Attribute Name
---------------
comment
comment-language
command-override
subsystem
x11
shell
exec
agent
env
from
port-forward
reverse-forward
6.6. Public Key Subsystem Status Codes
The status code is a byte value, describing the status of a request.
6.6.1. Conventions
Status responses have status codes in the range 0 to 255. These
numbers are allocated as follows. Of these, the range 192 to 255 is
reserved for use by local, private extensions.
6.6.2. Initial Assignments
The following table identifies the initial assignments of the Public
Key Subsystem
6.6.3. Future Assignments
Requests for assignments of new status codes in the range of 0 to 191
MUST be done through the Standards Action method as described in
[11].
The IANA will not control the status code range of 192 through 255.
This range is for private use.
7. References] Phillips, A. and M. Davis, "Tags for Identifying Languages",
BCP 47, RFC 4646, September 2006.
[7] Yergeau, F., "UTF-8, a transformation format of ISO 10646",
STD 63, RFC 3629, November 2003.
7.2. Informative References
[8] Lehtinen, S. and C. Lonvick, "The Secure Shell (SSH) Protocol
Assigned Numbers", RFC 4250, January 2006.
[9] Crocker, D., "Standard for the format of ARPA Internet text
messages", STD 11, RFC 822, August 1982.
[10] Mockapetris, P., "Domain names - concepts and facilities",
STD 13, RFC 1034, November 1987.
[11] Narten, T. and H. Alvestrand, "Guidelines for Writing an IANA
Considerations Section in RFCs", BCP 26, RFC 2434,
October 1998.
8. Acknowledgements
Brent McClure contributed to the writing of this document.
Authors' Addresses
Joseph Galbraith
VanDyke Software
4848 Tramway Ridge Blvd
Suite 101
Albuquerque, NM 87111
US
Phone: +1 505 332 5700
Jeff P. Van Dyke
VanDyke Software
4848 Tramway Ridge Blvd
Suite 101
Albuquerque, NM 87111
US
Phone: +1 505 332 5700
Jon Bright
Silicon Circus
24 Jubilee Road
Chichester, West Sussex PO19 7XB
UK
Phone: +49 172 524 0518 - RADIUS Delegated-IPv6-Prefix Attribute
Next: RFC 4820 - Padding Chunk and Parameter for the Stream Control Transmission Protocol (SCTP) | http://www.faqs.org/rfcs/rfc4819.html | CC-MAIN-2022-33 | refinedweb | 1,378 | 58.38 |
Not…
Well, what Java web framework should I use?
*shrug*, beats me. All the revenue generating projects I’ve worked on in the past few years are all still chugging along on Struts 1.2, and there is little reason to upgrade at this point. Sure, Rick Hightower’s Developerworks series convinced me that Java Server Faces does make some sense, but investing the time it takes to become an expert and train others in Faces still doesn’t sound like an efficient use of time. I anticipate that the path of least resistance for most is going to be the next version of the Struts Action Framework (read WebWork), but good luck trying to figure out what is happening over at the Struts project. Is it Struts Ti, Struts Titanium, Struts Action 2……err…why not just call it WebWork??
Maybe the set of components being developed in MyFaces will convince me to go with Faces - Tomahawk and Tobago look like they could become promising component libraries. Rife looks interesting, but that’s about as far as I’m willing to play at the moment. Shale’s been around long enough, but I have yet to hear anyone tell me how great it was to work with. Then there is Seam, Seam is a reaction to Rails, and Fleury admits as much without really admitting it in this eWeek article. But, don’t let me leave out Stripes and Wicket. Or, how about Spring MVC, or Tapestry, or Turbine. Hey wait a minute why not use Cocoon. Or, how about sticking with Struts but using Strecks for Java 5 compatibility.
Confused yet? You should be. None of these options has emerged as the logical choice, they all have various advantages and disadvantages. Most of these frameworks have to work with the Spring framework in some way. Of course, they all have to support AJAX. Some of them are open-source/no-agenda and some of them are open-source/corporate-agenda projects. A lot of them are duplicative. Many of them have very vocal, high-profile consultant bloggers that produce a series of hype-driven press releases (sorry I mean blog entries). It is getting very difficult to identify the next logical step. (Hey, have you checked out Rails yet?)
Too many architects in the kitchen
…Struts 1.x will never go away.
An entrenched base of trained Struts developers coupled with this anarchy of open-source innovation translates to something of a stalemate. Even though it is widely acknowledged that Struts 1.x has some serious limitations, it is less risk for an organization to stick with what it knows. We’ve got “Corporate-sponsored Open Source” (read Marketing) hyping everything from JBoss Seam to Java Server Faces. The only real constant in this game is that Rails continues to set the bar higher and higher. The Republic of Rails has succeeded in focusing innovation on rails as a common web-delivery platform, and rails provides an active community and an easy way to extend via plugins. The Java web development community loses this game, and it responds by trying to make Java web development easier. Just when we think we’ve found a good web framework in Java that approximates the ease of Rails, something new comes out - like RJS templates, and seven Java architects jump to approximate its Ruby genius.
Java Developers Dabbling in Rails
Those few organizations that have decided to dabble in Ruby on Rails are quickly learning that it’s ease of implementation is intoxicating. I’ve spoken to many who work for organizations that have permanently sworn off Java for web application development forever in favor of Rails. But, on the other hand, I know more than a few organizations that are happy as can be with a very modular J2EE architecture and a web delivery stack that consists of some old Struts 1.x applications. Rails is perfect for some projects, but isn’t appropriate for others. Maybe it is an elearning system that needs to be distributed to thousands of clients or maybe you are working on a system that utilizes some super-sophisticated grid computing platform that only has bindings to Java. My own experience is that Rails is a hands-down winner if a project is self-contained and limited in scope. The second it starts having to rely upon shared code or interface with an existing database schema, I jump for Java.
Rails is great, but sometimes you really do need to wield the heavy 3-tiered application architecture. Sometimes an organization benefits from the structure the J2EE provides (imposes). If anything, the great majority of Java web software projects are still using the (now ancient) Struts 1.x framework. Average Java web developer Joe Java, might just now be considering whether it makes sense to move to another framework. A minority of them have dabbled with Rails, some of those have been convinced by it, but Javaland is still waiting.
Future == Integrating Rails and Java
Maybe a winner will emerge, maybe we’ll all be using Seam or MyFaces in three years? Honestly, anything can happen, as Struts 1.x proved, it isn’t the best technology that wins, it is the one that people end up using. :-) But, I doubt it. Rails continues to improve and it has a core community that excels at communicating it’s compelling ease of use.
JRuby will mature, Rails will run on JRuby and there will be various plugins that expose something like Hibernate or some Spring managed fanciness as something similar to ActiveRecord. Think Rails on JRuby accessing some Spring-managed beans that provide the functionality of ActiveRecord over JDBC. This way we can stop arguing over who’s got the better ride and we can start making some real progress.
Stripes is a contender on quality and ease of use, and imho beats all the other mvc frameworks out there in these two areas. It is polished and well documented as well. This should be enough to convince anyone who enjoys the luxury of JDK5 to check it out.
All the other mvc frameworks are either outdated (struts), too verbose (spring mvc), missed their window of opportunity (webwork), or imitators (vraptor, strecks). The only other solution remotely as radical as stripes is Seam, but it is a lot more heavyweight.
*sigh*
Just what we needed. Yet another cheerleading article for Rails. I'll admit it is less hysterical than some, but none the less... it is tiring. The article appears even-handed, but the bias is woven in deftly.
RoR has its uses, sure. But, as you bemoan all the shortcomings of other frameworks you gloss right over the fact that RoR has lots of problems itself.
I also see the same old "java developers who used Rails swear they'll never touch java again because blah blah blah". Maybe the problem isn't java but the developers in question just aren't that good and ended up with poorly designed applications( as a classic example, take the infamous Pet Store by Sun with the horribly overblown EJB approach ).
There is nothing magical about RoR. Everything RoR does can, and has been done already in java. Using the ActiveRecord pattern suddenly makes it new? Been done. Auto-generating code? Been done. Rapid development? So you can scaffold up some canned stuff in 5 minutes. Now you can get busy tying your code to your imposed DB schema, and let it reach right into your HTML. I'll code up an app in a week that adheres to good design, thanks. Ad nauseam....
Hey, RoR is a decent framework and I'm sure it is a great solution for many, but I and others can and do write powerful, lightweight, flexible java applications that have far more going for them than RoR can offer at this time. Will this change? I'm sure RoR will evolve, just like everything else. But all this pooh-poohing of java smacks of bandwagon evangelism from people who never really bothered to learn much about writing good software.
Again, RoR has a lot going for it and I'm glad to see other ideas and approaches being tried, but it is no contender to Java yet.
for those who are transitioning from struts or the traditional request/response models, stripes is definitely worth the look. it's elegant and well documented.
re: El Guapo
Sorry, I didn't realize that you "..and others can and do write powerful, lightweight, flexible java applications that have far more going for them than RoR can offer at this time". That and I also didn't realize that "Everything RoR does can, and has been done already in java."
Re: Ray and Renaud, I don't doubt that Stripes makes perfect sense, the important question is, is there a vibrant community not just of developers but of users and a supporting documentation infrstructure? Are there a wealth of plug-ins? can I look up problems in upteenmillion blogs?
This is what keeps on drawing me back to Rails for front-end development. Someone took the energy and focus out of Java web development, although there are some good alternatives, I just get the sense that few are paying attention.
Tim,
I did not fail to note the word Opinion next to your name at the article heading. You should realize that an opinion article with an opportunity to provide comments will likely result in someone disagreeing, and perhaps even poking at, your viewpoint.
Did my somewhat harsh reponse to your article come off as a troll?
When you write things like:
"Just when we think we've found a good web framework in Java that approximates the ease of Rails, something new comes out - like RJS templates, and seven Java architects jump to approximate its Ruby genius."
It takes away from an otherwise decent commentary on the state of web frameworks, and steps into the realm of RoR fandom that many are frankly sick of.
Btw, the intended sarcasm of your reply misses the point, but hey, it's an opinion article so what does it matter. People can draw there own conclusions. Hopefully, they'll see that most of the time, it isn't the toll that is flawed, but the wielder.
I have also forgot to mention I've written up on some of the ideas regarding rails in java here:
re: El Guapo,
Seriously though, you mentioned RJS, so let's see what's going on with RJS. Follow this, the guy who created Prototype decided to work on RJS templates - have you used them yet? It's pretty compelling. You end up being able to update multiple DOM elements in a single compact piece of ruby code. So get this, instead of using link_to_remote to update a single DIV, you end up being able to script multiple element replacements in one place, and that's not even the most compelling thing, did you know that you can....
...sorry, you already said you were sick of reading more Rails fan mail. So, I'll stop for now, and you can wait until somoene like Gavin King or a Struts developer decides to learn RJS and try to approximate it on top of the J2EE framework.
Hear me now, or believe me later. Contrary to what you might think, there is a subtle shift happening. Rails is innovating first, and Java is playing catch up. Phase Two of the Great Inversion is well under way.
Note that I too use Java to create "lightweight, flexible, and synergistic" web applications. But, the problem I find is that I usually end up trying to approximate what's possible with the Rails framework. And, sure it forces you into some decisions regarding your database schema, but don't tell me Hibernate hasn't had occasion to dictate database structure? Egad, I mean the last few Java applications I wrote baby sat a database, and guess what, the object model had a striking similarity to the database structure. I mean the column names were almost the same as the property names. Yikes, my database was right there affecting my presentation layer. Who knows? maybe I should've just changed my model to make it more Java (read, difficult for the sake of being elegant)
You say you are sick of reading more Rails praise. But, I'm seeing that a lot of Java developers still have this "I'm sticking my fingers in my ears" reaction to Rails. As if it isn't even worth considering because it's got to be all hype.
The Rails Cheerleader
Guapo, you have a plethora (of opinions, most of which I agree with.) Ruby on Rails is not the desert topping and floor polish that everyone makes it out to be. Fun, but not what I'd recommend for a large application at the end of the day.
I don't think that there is as much confusion in the community as you might suggest. I don't think that we should mistake competition amongst Java frameworks as a lack of enthusiasm or following on the part of any one of them.
For example, but my cursory look at the struts community shows me that they are very active, and for the most part very excited about the integration with WebWork, and, trolling aside, all behind the Struts 2.x releases as the future of the product.
What framework will win? IMHO, I think that there is a huge following in the Struts community that will just pick up the next version because of the ease of knowledge transition... that's what I would do :)
Again, just another opinion.
re: Hefe, Hefe is right, Struts Ti (Titanium) will probably be the next ruler of the Java web application, but should it win? That's the more interesting question. Hightower makes a really compelling sales pitch for Faces in the Developerworks series linked to above.
Well, that is an interesting question. I think that in a meritocracy, the best framework would win. What makes a framework the best?
The ease of development and maintenance for the far-sighted crowd costs less and therefore is most beneficial. For each organization, that merit may be found in any one of the frameworks mentioned, due to the ease of development due to elegance of design, ample documentation, easy development semantics, or sheer knowledge of the platform.
Familiarity is a strong argument for ease, and there are a lot of Java devs and architects out there that will find that the "best" framework is the one they know the best.
Which framework has the most merit? It depends on you, your knowledge, your organization, and most importantly, your customer's needs. For me and my current projects, I'd probably go with Struts. But, unlike the techno-vangelists out there, I don't think that everyone has to convert to my favorite web app framework.
re: Hefe,
Agree with a lot of what you said, I'd argue that the concept of "best" framework doesn't exist - this is a mostly subjective judgement call informed by specific situations.
> But, unlike the techno-vangelists out there, I don't think
> that everyone has to convert to my favorite web app framework.
No, clearly. Popularity of a framework doesn't correlate to quality - again Struts 1.x was (still is) the ruler of Java web applications. It is far from ideal, and it got to where it was because of real absence of MVC solutions back in 2000-2001.
Not everyone has to flock to your framework of choice.....but, if they do, you'd benefit from healthy dynamic community. You'd be able to hire people that knew how to write apps in framework "X", and you would be constantly benefiting from people writing how-tos and documentation. There would be a really huge collection of plugins available, and you'd be able to gain from the experience of others.
Sure, you could go ahead and use a framework that no one else uses, but as soon as you do that, you stop benefitting from the network effect of community. That's my central point - at this point, there are so many choices in the Java web landscape, it is difficult for me to direct an organization to "the community" that is going to succeed. I think the jury is still out on Struts.
Bummer. What looked like a good summary, or breaking news article about Java Frameworks (as it's from OnJava: The independant source for enterprise JAVA), becomes a bloody sales pitch for Ruby. The subject should have read "What Web Application framework should you use? Ruby. Read why ..." Then, I could have ignored the article, and gone back to doing work for which I can invoice.
I think the big looser here in OnJava, as I'm a bit less likely to believe any future articles are going to be anything more than a waste of time. Perhaps I'll just get rid of my RSS feed. (Anyone know of a better source for Java news?)
You might wanna take a look at RSF. We tried to use JSF a couple of times and kept hitting brick walls, so in typical java fashion we created yet another framework. It really is quite nice though; RSF stands for Reasonable Server Faces and that's what it sets out to be: Reasonable, because if there was one thing that JSF is it's unreasonable.
1. RSF is based on Spring, and has Spring as it's container. It's IOC from the start.
2. RSF has a pure HTML templating system, (You need to mark rsf:id's in the template, but it's much purer than Tapestry or the like; the db won't leak up to the HTML.)
3. RSF has been built to obey the HTTP standard: GETs and POSTs mean different things
4. It's been designed to reduce Server load, so by default there is no server state. It does this without closing the door to such but it doesn't force you to do so. (unlike JSF!)
and more... ()
If you use RSF you need never see another HTTPServletRequest, or another HTML tag in your code. Your Business Logic will be free of framework dependency (No more damned JSF DataModel!)
It's also fast.
re: cyklyzt,
How is integrating Rails with Java via JRuby any different than "coding a web service with Groovy" or "Integrating JPython with Spring". Maybe the difference here is that there is something about Ruby on Rails winning the web dev fight that just gets under your skin. If there is one thing I've noticed lately, it's that "Enterprise Java Developers" get bothered whenever someone brings up Rails. I think there's a good reason for this - it's a threat to an entrench power structure. :-)
re: Andrew Thorton, intriguing....RSF - that's the first interesting thing I've read all day. Well that and the relatively positive posts about Stripes.
The (probably) best webframwork ever? Does it exist? Since I tried Google's new webtoolkit I am convinced that GWT is the way to go. That's probably the big winner. Even Ruby on Rails looks outdated if you ask me. In fact the Google Webtoolkit makes any other webframework look like a Neanderthal-webframework. Additionally GWT brings Swing- or desktop-developer to the table.
Tim, stop hyping RoR and start hyping GWT. I mean your guys need a new hype every month, right?
This looks like a revolution to you? I find it incredibly non-compelling. I might as well be coding in pure JSP.
re: Ulrich Weber,
Did you reall say, "Additionally GWT brings Swing- or desktop-developer to the table."
Swing? Wait a minute, it brings Swing to the table. Maybe it's time to bring poll functionality back to the O'Reilly network, but I'm pretty certain that the answer to the question: "Should web development be more like Swing?" would be a resounding no.
GWT, "it's as easy as Swing".
re: Ivan,
Sure, go ahead and code all of your Javascript straight in JSP - that's what Java developers end up doing anyway (except if they've decided to learn about the newer MyFaces components)
Here's an idea Ivan. Maybe you could write a Java API that abstracts a given page. Then you could wirte some methods that let you do things like insert HTML or markup into certain locations, replace DIVs etc. Then, you could write some sort of translation layer that takes calls to this abstraction and translates it to JavaScript. On the Javascript side, you would just need something that can execute that arbitrary Javascript against a given page.
So, Ivan, this way, you would be writing all of your page manipulation logic in Java. Everything would be separated - no Javascript or Java in your JSPs. That should solve the problem. Good separation of concerns, modular approach to the problem.
But, guess what? That's exactly what RJS does. :-)
If Rails is your thing but you can't quite drop java, you could look at Grails, the Rails port to Groovy. Coding by convention coupled with access to your java libs. I've had a play with it and though I'm nt sure it provides everything Rails has, it provides similar light-bulb moments.
Just thought I'd weigh in with a few words with RSF, since this "frameworks" issue is perpetually interesting.
RSF takes the view that "every framework is an insult to its users", and therefore tries to be the smallest possible insult. I wrote it primarily because I got extremely fed up with frameworks perpetually getting in the way of my writing code, and found that Spring was the first framework that had the conceptual coherence to get out of the way fast enough.
That said, I found there were a few genuinely new and productive ideas in JSF that had been missed by other frameworks - in particular I find SpringMVC problematic since although it is sensible so far as it goes, it is the way it is because it is designed to cater to the "lowest common denominator" of webapp frameworks, which is currently very low. RSF is what a Spring webapp framework would be, if one abandoned the Spring credo of "working with what is there already" and started from the ground up.
Given the current conversations about Rails and ORM solutions, I think RSF's approach to ORM (nicknamed "OTP") is very interesting - you might think of it as a little analogous to Rails since it aims to make access to storage idiomatic and transparent, but goes further in that it not an "implementation" and only an "idiom" - hence it can be layered on top of whatever ORM you happen to like using at the moment. What most people like using at the moment in the Java world is Hibernate, so RSF ORM enables you to use Hibernate ORM without seeing any Hibernate dependence in your code.
Similarly RSF enables you to write a portlet without seeing any portlet code, or indeed an "X" without any "X" code in general - for want of a better label this is the "Spring" philosophy of "invisible frameworks", but RSF takes traditional IoC further by allowing request-scope IoC using a lightweight Spring clone, RSAC to "clean the areas Spring cannot reach". I think request-scope IoC is one of the great ideas in (web) programming that is simply waiting for enough people to have experience of it - note that request scoping has been slipped into the upcoming Spring 2.0 release (as of RC4) but the implementation will probably be too slow to be practical.
Much like Spring itself, request-scope IoC is one of those things that you just have to take the plunge on in order to appreciate the kinds of problems that it solves, but it is key to RSF's easy and transparent portability and integration (Hibernate, Coccoon, JSR-168, Sakai). I'm also planning a SpringMVC integration in the next couple of weeks, but largely for "philosophical" purposes...
In terms of the "next years" I think 3 years is far too short a time for this mess to be sorted out, but I hope (actually I'm sure) that no such heavyweight JSF-based or JSF-alike (read Seam, Shale &c) will gather hearts & minds because anything based on the heavy clay of JSF is just going to crumble.
In terms of Rails itself, I think it is a fundamentally wrongly-arranged solution to its problem (loosely-speaking, that of ORM) since it tips a design on its head to be based on its storage (read, schema), rather than simply "allowing" storage to be one of the functional possibilities. This TSS article I think makes the key point by asking the question (in Rails) "What fields does this object have? You have to look at the database schema". This is the wrong answer to such a question.
Just a final word re AJAX - since RSF features pure (that is REALLY pure, not just "generally parsing pure" as in Tapestry) HTML templating, any existing AJAX/HTML component, with just the lightest packaging, is automatically an RSF component. It's this that I see key to RSF's adoption in the long-term, since peddlers of Java frameworks (especially Sun) fail to see that Java frameworks as a whole, let alone their particular framework, are *always* going to be a very small part of the complete web programming community, and so the "interoperability" promised by swapping "components" for their framework amongst their developers and users is always going to be proportionally tiny. Java is a reasonably good language, but developers have to appreciate that they will *always* be inhabiting a world with other sorts of technology, and there's no arena that more regularly rubs one's nose in this than web programming. If you follow my RSF thread on TSS I explain there why Wicket and other "heavy component" frameworks are improper inhabitants of this heterogeneous community.
As for Stripes, it is based on JSPs. 'Nuff said.
Here's my opinion:
re: Antranig Basman,
Awesome. Great comment, your response to this blog entry actually adds something to the debate. Clearly RSF is something much more interesting that "just another web application framework", and the separation of idiom and implementation comments re: ORM are reasons enough to investigate.
The one point I'd disagree is that, for maybe 95% of the applications I've worked on the answer to "What's properties are in the Object?" is very similar to "What's columns are in the Table?" Sure there are execeptions, but they are few and far between.
Antranig Basman:
"As for Stripes, it is based on JSPs. 'Nuff said."
If you're going to sling mud, at least please be accurate. All the Stripes examples use JSP because it is by far and away the most widely known templating/view technology in Java. But Stripes works equally well with Freemarker (several people are already using Stripes+Freemarker), and can work with any view technology.
Honestly, I think anyone who is still bashing JSP in this day and age needs to go and get a refresher. JSP 2.0 has come a long way. Even proponents of alternative templating languages tend to now admit that it's quite a resonable and viable alternative, even if it is still rather little verbose. Will you refuse to use EJB3.0 or JPA persistence because EJB 1.x and 2.x were a debacle?
Personally, I am really tired of all this RSF bashing Wicket. If you read the thread on TSS you will see Antranig is preaching "objects are nothing, dependency is everything" - I find it really funny that a person who thinks that way uses a language that emphasizes OO which just happens to be about...well...objects. Take a look at this RSF wiki page:
The two biggest failings of wicket listed are:
[quote]Server-heavy - Wicket components (the controller layer) are "heavy" in that they have both behaviour and state...[/quote] OH NO!!! BOTH BEHAVIOR AND STRATE!!! NO!!! That must be SUPER BAD!!! Oh wait, isn't that what OOP is all about? Hmm...what was the definition of an object again...? Wicket has succeeded, where others have failed, in bring true OOP model to the web frameworks area. Tapestry comes pretty close, but you still have to take extra care in marking what state is and how it should be saved. In wicket you can create a component using the java extends keyword (you remember that one dont you guys? the one used to create new classes...).
[quote]Devoid of IoC - this is probably the most serious failing[/quote] Uhmm... I missed the lecture where it was proven that all frameworks must be based on IOC and not doing so will earn you a failing grade. Wicket is a web ui framework, not the kitchen sink. It doesnt force spring, or any other ioc container, on you whether you want it or not. Integrate it with whatever you want: spring, ejb3, hivemind, blah blah blah.
What have java web developers turned into? Drones who chant "ioc ioc ioc" and dont know the first thing about OOP because that skill has been lost in this space? Its really sad.
Sorry to vent here Timothy, but I think this needed to be said.
To Tim - Apologies, I get annoyed enough with people who criticise aspects of RSF from only a cursory glance at its website, so sorry if I may have done the same. To be fair to myself I don't find any mention of Freemarker or Velocity on your site, so perhaps I could be forgiven for believing these are not "first class" idioms in Stripes? Every example on your site is in JSPs.
I have also to say that I am not bashing JSPs and EJBs primarily because they are "old" but primarily because they are "bad". (Not that I had bashed EJBs yet in this thread but would be happy to do so :P). In particular what I see in Stripes is use of either taglibs or (given you mention Freemarker) "front-led" templating systems, i.e. ones which encode view logic in the template structure, which is undesirable coupling. Your view layer should really be full of pure view - in RSF, HTML templates can simply be handed to any designer armed with Dreamweaver, with the worst results possible that they hand back something that doesn't display all parts of the view, rather than one which can corrupt state. OR WORSE, a template which needs to be modified when the business model of your app changes. Of the "other" web frameworks out there, currently only Wicket allows this, with RIFE allowed as a bare outsider assuming you have designers happy to be told "don't mess with these strange-looking comments before and after significant things".
The other aspect which marks Stripes as an "old-generation" framework is the intrusion of framework dependencies such as "ActionBean" and "ActionBeanContext" on what should be the business level of the app. RSF preserves from JSF the system of pure "value bindings" and "method bindings" which promised to return your business model to being *your* business model, rather than some fake mockup of your business model invented to satisfy some blasted framework. Unfortunately in JSF through various serious structural problems (not least its handling of tables) this promise couldn't be realised.
>Sorry to vent here Timothy, but I think this needed to be said.
No need to apologize, finally a good discussion of relative merits. (outside of the bitchfest that is TSS :-) )
Two things:
1. No one has broached the topic of IoC overload. I think that Javaland has been on a heavy diet of Spring lately, and while it's a good thing (I haven't seen a Singleton in about two years), it is also creating a situation whereby people tend to knee jerk IoC - interface plus single implementation pattern far too often. Not that Spring is bad, please don't take that the wrong way
2. A criticism of everything that requires code. (re: server-heavy)
Just a quick point - my previous comment was to Tim F., not to Tim O'B (probably clear), and now to Tim O'B "people tend to knee jerk IoC - interface plus single implementation pattern far too often", actually one of the key points behind Spring is that it enables interface-free IoC, without which it really wouldn't be much good (cf. Avalon and other older-generation IoC).
Antranig:
You're right that the Stripes site doesn't mention Freemarker, Velocity et al - there's only so much time in the day and the large majority of developers these days are happy with JSP2.0. Those who want Freemarker or Velocity tend to know the tool well enough to know the 2-3 steps necessary to substitute it in.
[quote]The other aspect which marks Stripes as an "old-generation" framework is the intrusion of framework dependencies such as "ActionBean" and "ActionBeanContext"[/quote]
Well, if things like having a couple of framework classes in your import statement bother you, I guess you're right. Stripes is developed with simplicity and ease of use forefront. For example, implementing the ActionBean interface (with two trivial methods) means that the framework can auto-discover and auto-configure all the beans (backing beans, actions, whatever you want to call them). Unless you have another way of identifying said classes (without a code dependency such as an interface or annotation) you can't do this, which means you have to configure more stuff.
I'm not going to argue what the "best architecture" for a web framework, which seems to be where you want to go. For me the best is simple what helps me put together an application the quickets and doesn't cause maintenance problems etc. If you're business model is such that you can invoke it directly from the framework without any glue code (which appears to be what you're suggesting), then really all you have is a tight coupling that is completely undocumented. Are you not then imposing structural patterns or conventions on your "business model" that are specific to your presentation tier? To me that's more problematic.
But I'll also say that I don't know that I've ever developed an application which fits into the "80% of application which just read/write objects from a database" which everyone seems to talk about. Almost everything I've every done is a complex business app, where there is nothing like a direct mapping between persistence tier and screens, so maybe that's coloring my perspective.
@Tim O:
ioc: I love spring, I think its the kind of framework that solves real problems, but most importantly imo its the best of breed in its niche. What troubles me is that a lot of developers out there are zealots: everything must be a bean, everything must be based on ioc, separate state from implementation, blah blah. Why is it bad to use the new keyword to instantiate an object yourself? If you ask them that they have no good answer, they just spew ioc slogans in your face failing to make sense or produce a valid argument. Taking wicket for example: we have a great way to integrate with spring:
class UserLabel extends Label { @SpringBean private UserManager um; ...}
Now whevenever you create a UserLabel the user manager dependency will be injected for you from the spring context by a mechanism built into wicket. This is all it takes, easy right? Apparently not, there are plenty of discussions on our mailing list saying that this is not "true" ioc and therefore not a good solution. Why isnt it? Well, its because the component is not a bean, because it doesnt have setters for dependencies, because it is not the container itself performing the injection, because, because, because. Sad. We have a great solution that works very well and people are whining because it doesnt follow some idiom to the letter.
code: Dont even get me started on this one. My favorite so far has been the pageflow argument: wicket is adhoc because navigation is performed in code and not via externalized xml pageflow definition. Some people freak out because wicket doesnt require any xml, they dont even know how to begin to approach it because they are so used to those thousand line xml files they have in struts, etc. Of course the big argument is that it is not configurable between deployments - another example of zealotism. How many times was there an actual requirement to have pages be configurable between deployments? Does it apply to ALL the pages in your application? If there is a specific requirement that that minor portion of the configuration be externalized, but if not WHY DO IT FOR EVERYTHING? Just for the sake of it? What a waste of time.
What attracted me to wicket was the fact that it concentrated on code instead of configuration. I am a java developer, I like and am payed to write java code. I dont like configuration unless there is a requirement to have functionality configurable, I dont like following idioms to the letter if it sacrifices code style and functionality. Am I alone?
To Tim F:
What you say is quite true, that no insulation can come completely "for free". The RSF goals were to make the framework as easy as possible to use *subject to* making no unnecessary compromises on the insulation levels between model, view and controller. In little projects a lack of insulation just looks like a "a couple of import statements" but as architectures grow larger becomes a fatal flaw which can bring down the whole edifice.
In terms of "structural patterns and conventions on the business model" RSF imposes nothing beyond what Spring does - it should consist of a set of (configured) beans with some kind of sensible dependence structure. In fact with the use of request-scope IoC, RSF actually considerably *relaxes* Spring conventions in that it allows you to do (formerly) wacky things like addressing Hibernate-managed entities directly as part of the business model.
There is indeed a (semantic) coupling there, but it is as light as it could possibly be, and certainly better than a physical one. This actually arose not *entirely* by initial plan, but actually from the sheer necessity of accommodating Hibernate's slightly "wacked" conception of what POJO semantics were :P
In terms of the general context of the discussion, yes, I accept Tim O'B's initial point that Java frameworks, in usability, are still playing "catchup" to people across the fence, and in fact the RSF "Hibernate Cookbook" sample app was directly stolen from the equivalent "Rolling with Ruby on Rails" version primarily to prove that all of this stuff just needn't be so hard :P There is an "all-XML" version of the app that is *entirely code-free* (which is primarily suitable for auto-generation strategies that we are working on - much like the Ruby "scaffold" system it would be attractive to just drop in a .hbm file, turn the handle and get out a basic CRUD app for free, but unattractive initially to generate this app as Java), and also a Java-only version which I argue is as straightforward a CRUD app as anything out there (especially for one using Hibernate), and considerably more straightforward than many.
To catch up on a back-point of Tim O'B who said "for maybe 95% of the applications I've worked on the answer to "What's properties are in the Object?" is very similar to "What's columns are in the Table?"" yes, this is quite true, but I don't think it's sufficient argument to invert your architecture, even if were true for 99% of cases :P Actually RSF aims to solve this problem via tools rather than through "convention". The basic workflow I envisage is
i) design your app schema in whatever design tool you like (we actually use Enterprise Architect which spits out a .xmi file)
ii) Convert this schema into a .hbm file (using an XSL we have written)
iii) Run the standard Hibernate hbm2java task to create a standard set of POJOs mirroring the schema
iv) Point RSF at the resulting SessionFactory, and there you go. Your entire data model is exported as an EL-addressible namespace of beans.
The end result is a data model that is "in sync" with an arbitrarily bulky schema, but, like the equivalent Rails model didn't force you to go through the drudgery of fiddling with it by hand. And further, with a completely transparent process under your control to explain where it came from. For, as you say Tim, the 5% of cases where you have state not directly (or obviously) derivable from the schema you can lightly season the model with a few hand-crafted classes.
The further point is that your schema is defined in an environment suitably rich, yet portable enough to hold it (hbm/xmi as opposed to SQL). And yet not in an environment "too rich" as to allow virtually anything (i.e. Java). The key is everywhere to use the appropriate receptacle for the appropriate ball...
I think what is missed historically is that more than anything the success of Java is owing to the extremely rich *tool chain* that it has allowed to grow up around it (generally as a result of its fairly straightforward structure), more than any particular merits it has as an O-O language, and I think (hope) this is key to its direction of future growth. Unless Java continues to capitalise on its strengths of being a tool-friendly environment we will indeed start to fall behind the folks over the fence.
I'm with you Tim. I think that Rails will see a huge bump in usage when there is a clean integration of Rails and Java. Certainly today you could write a very clean Rails app that taps into a Java backend via web services, but if you don't need to add the complexity/overhead of adding a web service, you might not want to.
Rails alone is perfect and awesome if you are building a new web-based product. But it is hard to bring Rails into an existing corporate environment where Java is pervasive. Corporate environments tend to be slow moving; developing and deploying Java apps is currently a known beast.
The current cauldron of Java web frameworks is indeed overwhelming and frustrating. Competition is healthy, for example the Netbeans vs. Eclipse battle is a great thing; both products have improved tremendously, and that probably would not have happened if they didn't have each other to compete against. If we just had the "standard" way to do things, JSF, vs. the alternate way to do things, Tapestry for example, things would be a lot easier. But the current JSF(and its many implementations) vs. Tapestry vs. Stripes vs. Wicket vs. Spring MVC vs. Struts/Shale/Struts Action vs. Rife vs. Seam vs. Rails-knockoffs-such-as-Grails-and-Trails hurts my head and makes me want to chug the Rails Kool-Aid ( I'll be at RailsConf BTW :) ).
Like many programmers, I like new toys. Every new project is a chance to be blown away by the smartness of a fellow programmer. I like Ruby a lot, though I wouldn't use it on large projects just because it is a scripting language and it has a lot of immaturities that Java doesn't have. But after letting RoR sink in a bit... Well, it has a bunch of neat tricks which everyone that makes a framework can learn from. But at the end of the day, it doesn't have the qualities that would make me happy as a coder. Besides letting you do the trick, a framework - just like a language - should provide for some elegance in that too. I just don't see a lot of elegance in RoR besides that the code is short. GWT is an example of a framework that is innovative, helps you do the job and also seems elegant in its use.
I haven't used Rails, so will offer that disclaimer up front. However, it strikes me as one-eyed to complain about changing to another java framework ("investing the time it takes to become an expert and train others in Faces still doesn't sound like an efficient use of time") but to not state the same drawback of learning _an_entire_new_language_. Yes, I have dabbled in Ruby, it is nice, it is clean, but it is still a new language. The APIs I know and use daily need to be relearnt, and from a professional viewpoint (as opposed to someone interested in learning a new toy), I am a long way off from using Ruby based solely on the fact that finding Java Developers is a _lot_ easier than finding Ruby developers.
One Java framework that I'm looking into atm is Stripes - it is a very easy transition from struts, but removes many of the pains that we know in struts. I am still looking, and like all the new frameworks it is still under development, but it shows a lot of promise and is advanced enough to use for production use in its current state.
all the Java guyzz should understand that for WEB solutions go PHP...
You didn't mention WebObjects. WebObjects is even better than Rails and it is pure Java. It doesn't have the buzz word popularity of other technologies, but it is really one of the best web application frameworks out there.
I consider Stripes to be the best Java based web framework available today. We have looked at many other frameworks, but Stripes excels in its lightweight, great documentation, reduction of boilerplate code, easy of use, and cleanliness. Things that required you to jump through hoops in Struts are handled with incredible simplicity with Stripes. Plus, as opposed to mostly all of the other frameworks, Stripes requires no XML files to be configured, which can become a pain in the neck to modify for big projects.
well,
spring and spring mvc meets my need... RoR was fun... RoR made my development really simple... but i can produce managable code only in java project... it is fact in my case...
There is a lot of discussion here about Java & Rails, and which framework is best and which is usable. A point that I would like to raise is which framework is being adopted(or experiemented with) the most at the enterprise level (Note "enterprise level", and not "open-source based projects"). That is a point often missed. I'm talking about co-existence with legacy, existing apps, ERP's, EAI's, and so on..
Struts was the predominant framework when it came to enterprise adoption. What next? I have seen JSF and Webwork(along with Spring & Hibernate), as the technologies most used in the current applications being built in the enterprise.
What frameworks are being adopted in other places? Does rails have a place in the enterprise? (Remember co-existence with legacy, existing apps, ERP's, EAI's, and so on..)
- Yogi
Excellent discussion!
Thank you, Tim O'B, Tim F, Antranig, et al, for a very lively and informative discussion. I've been surveying all frameworks, all languages, for the past few months, and this is one of the best discussion/overviews I've seen. I'm about to begin building a new n-faced app (web + mobile), and I want to be sure I've looked high and low for the "best" framework/language combination before I start. I'll most likely have to live with any messes I make for the next few years, so really need to avoid any serious mistakes. Anything I work on will be built using typically-chaotic XP methods, so the base platform has to promote code that is maintainable, reliable, reusable, very flexible. My clients generally don't care what technologies I use, as long as it does what they want, is rock-solid stable, and it's easy/fast to make changes.
I've been a Java developer for 10 years now, so Java is "home" these days, just as C++ and C were "home" in the years before that. As a professional developer (and consultant) I have an obligation (to myself and to my clients) to remain open-minded, pondering whether it's time to abandon Java. If I stagnate, then I deserve the professional death that will surely follow. (Hopefully I'll get rich soon, and I can stop holding onto this tiger's tail!)
There are certainly some viable alternative languages (Python, Ruby, PHP, Groovy, to name a few) and they each have fairly good platforms (e.g., Zope/Plone, Rails, PHP-Nuke), so they deserve to be examined carefully. Each has it's strengths and weaknesses, and the same can be said for every Java-based solution I've seen or worked with. My job is to stay informed about the best-of-breed in every class of solution, and choose the right tools/methods when starting on a new project.
My current thinking is that I'll go with a hybrid solution that includes a little of everything. For the system plumbing it's pretty hard to beat JBoss. The built-in features provide a solid, feature-rich framework that handles scaling from laptop-dev, to simple two-tier, to small clusters, to massive multi-DC farms. I could go with other app-server platforms, of course, but a JBoss backbone is reasonably mature, at least as stable as it's commercial competitors, and the price/TCO are pretty hard to beat. That takes care of the plumbing, persistence (Hibernate or EJB3), and gives me a good place to hang my business logic.
The real fun starts when I look at the presentation tier, which is what most of this discussion has been about. Given that I'll be building on a Java foundation, the most obvious choice would be a Java web framework (e.g., Struts, SpringMVC, Stripes, etc.). Alternatively, the Java-based scripting environments like Jython and Groovy (maybe BSF or JRuby), along with their attendant frameworks, are definitely worth considering carefully. That would give me easy integration with the back-end, as well as the dev-time flexibility of a scripting environment. (The lack of deep integration with the Java plumbing make it pretty hard to justify PHP or Ruby.)
For page-generation, the reality is that I want it all - ease-of-use, power, flexibility, and a rich component set. I guess what I want is a flexible portal-like framework with:
easy page/sub-page layout/skinning/themes
a minimum of archane markup
AJAX-style user interaction and display refresh
very loose inter-component coupling (but enough that it can be done!)
quick-turn component development with little or no framework dependency
enough maturity that it's not brittle (I'm a rambunctuous guy)
FYI - I've looked at most of the Java-based portal frameworks out there (Jetspeed2, LifeRay, JBoss Portal, etc.), and they don't pass the last test yet. There are other webapp frameworks, obviously, but they tend to lack the flexibility I'm looking for.
A lot to ask for, I know, but it's what I want. Anyone have any opinions or suggestions? :::grabbing umbrella:::
Its funny with all this talk of web frameworks no one even
thinks to mention asp.net. Its a framework that is flexable,easy to use, but expandable if needed into 3 tier. I know everyone has been on a hate fest with Microsoft but come on. There .NET framework is a great piece of technology. Plus you can do it all in C#. Which is very close to java. Plus they have there very easy to use Atlas framework for AJAX enabling your site. If your running your site on Apache its no big deal. Just use Mono to run it on any Linux distro. I just cann't believe it hasn't come up. Why mess with these other languages that aren't fully OOP or take to long to master. I think the .NET Framework is the best bang for your buck.
I've actually seriously considered using .NET, for precisely the reasons you've cited. I'm not a religious zealot, and I consider Windows XP to be a perfectly adequate OS. It's my primarly desktop OS, and I find it to be at least as stable as it's competitors. I just need to avoid creating OS-specific dependencies in my code, primarily because many of my clients aren't as open-minded as I am. They tend to specify Linux for their production platform, so that's what I give them.
It's really nice to be able to develop on Windows XP and MacOS (my desktops and laptops), and then deploy to any of the available server platforms (Win, Mac, Xnix) with little or no platform-dependency. I can get that from Java, Python, Perl, PHP, Ruby, etc., but I'm not aware of any fully-compatibile .NET implementations for MacOS, Linux, or Unix. (Admittedly, I have not looked very hard.)
- ks
ASP.NET? Give us a break please. I thought it was good until I actually did projects with it. Now I would rather seek another employer than having to use VS and ASP.NET again. It's heavy, buggy, limited, I regularly had to fall back on a text editor because VS couldn't handle the preview, viewstate vs page properties are confusing, the 'HTML' is an incredible mess of tag soup (just like JSF), etc, etc, etc.
I've given ASP.NET a chance lately. In fact, I purchased a professional copy of VS.NET - it's a good product, the framework is well thought out, and there is a lot going for the .NET framework and C# if your organization has standardized on running Windows in production. I will have to say that the .NET reporting services is a great piece of code, very easy to create reports, etc. .NET has a great take on things like display tables of data, and once ou've sunk the time it takes to learn ADO.NET, you can do great things with ASP.NET.
But, I'm unwilling to use a platform that dictates OS selection in my production network - period. I don't trust the Mono project to run my .NET applications, and, even if I did, it alwasy feels like Mono is a little bit behind Microsoft in terms of the latest greatest.
All of that being said, if your organization can suffer through a 100% Microsoft platform, then ASP.NET makes a lot of sense, but, at least for all of the projects I work on, Windows in the production network is a non-starter (and I agree with that decision).
What an enlightment this has been. The diversification of POV and experiences that have be ratified is intoxicating as it is informative. Thank you for cracking opening such an important topic. Considering my limited knowledge of web frameworks and all, this dicussion has been a real eye opener and has made me think alot more about the constant irregularlity over what is considered best of breed web frameworks v's the [quote] With great knowledge comes and great power and with great power comes great responsiblity [/quote]. In a nutshell what I meant to say is; if we dont stop to smell the roses once in a while we may all end up in serious trouble in the future of the internet. I suspect that small and large corporate giants that rely on these frameworks to generate income should be under no illusions that one day, there will be a web framework bubble burst where far too many disparant technologies will exist and be glued together, which will cause a massive technology overload and gridlock etc... and the people who long started these technologies will be long gone and probably dead. What then? The programmers of the day will have to clean up the mess and continue to tack on bits and peices etc. From all my proding around web forums, blogs, podcasts and so on it looks to me like we need a 'Universal Standard Common Web Language' platform etc. Like Adobe has for PDF, as has HTML for the Web etc. Please don't misunderstand what I am trying to get at here. Whilst there are so many great things and some bad ones going on right now in this domain,. May be I am rambling on too much here and trying to be a visionary or something, but please for godsake stop back stabbing each other about which is the best of the best and start thinking about what we build now is to shape the world in the years to come...
Again I must say that this is one of the most important discussions on this side of the web I have seen a very long time. Only the efforts of you and others will make this a truly wonderfull place to work. Let the future be now!
Despite some of your critics on this one Tim, I thought this was a very well written article. As much as some don't want to hear it, you are right in that Ruby IS innovating first and Java is following. I think the question of integrating Rails and Java is a good one for many organizations, but at some point, I see organizations migrating completely off of Java.
re: Anonymous
."
uhhhhh... dude, are you okay? It's just code, man, take it easy.
What are the criteria for choosing a framework? What are the comparative advantages and disadvantages you alluded to?
I wish there was a repository of frameworks each having talking points to consistent criteria... Then we can begin to compare apples with apples and choose the best framework for our application development needs...
Hi,
If you plan to develop a "back office" web application like callcenter, CRM, trobel ticket system,..than Open-jACOB is the right tool.
see on: Open-jACOB
greetings
Andreas
I need to use xml tag to apply for any of the vb script
Tim, is it possible to use RoR for front end and Java for back end?
Visit Ehr Implementation
Visit Nyc Subway Map
Visit Pyromania
Visit Ancient Egyptian Hieroglyphics
Visit Leann Rimes Life Goes On
Visit Free Wicca Spells
Visit Free Wicca Spells
Not much on my mind right now, but it's not important. I've just been letting everything happen without me. I just don't have anything to say right now.
For those who hate programming and database designing, Nenest () might be a good choice.
What about Hamlets? Hamlets is the name of an open source system (BSD license) for generating dynamic web pages. A Hamlet is a servlet extension that reads XHTML template files containing presentation using SAX and dynamically adds content on the fly to those places in the template which are marked with special tags and IDs using a small set of callback functions. A template compiler can be used to accelerate Hamlets. Hamlets provide an easy-to-use, easy-to-understand (less than 1/2 hour), lightweight, small-footprint, servlet-based content creation framework that facilitates the development of web-based applications. The Hamlets framework not only supports but also enforces the separation of content and presentation. With Hamlets you write your web applications in Java, so you can leverage your entire Java skills.
What a relief that someone out there in Javaland is acknowledging the confusing array of java web dev stuff out there. Lots of great stuff (...I think) but what to use and how to bundle together all of the pieces that you'll need? Making them actually work together just for your classic HelloWorld ... arrrg! Man, I'd love to have it any other way, but the bar to entry is raised so darned high that it is no wonder that folks run back in droves to IIS and ASP.Net.
@Ken, I don't see people running away from Java to ASP.NET because of an abundance of choice. I see the reverse.
I've just found the CLICK framework a week ago and have been playing with it for a week now. It's open source at sourceforge.
to date this is the simplest/lightest framework I've come across. I've used struts and tapestry over the years and am currently using JSF. I was able to migrate one of my project tracking tool, I worked on in the past, to CLICK in a week.
I like it because it uses plain java and velocity which are both mature technologies.
I am going to use CLICK from now on.
web site is
anyways just my 2 cents.
Take a look at ztemplates on
* new and unique action processing module
* clean, technology agnostic urls
* fully JSP, Velocity and AJAX compatible
* state-free
* invisible to the web-client
* convention over configuration
* extensible
* small and modular
hfhdjfh jdfsh dfh | http://www.oreillynet.com/onjava/blog/2006/06/isnt_rails_supposed_to_change.html | crawl-002 | refinedweb | 10,304 | 69.62 |
Hello there.
I wrote this little piece of code:
#include <immintrin.h>
#include <stdio.h>
typedef struct quaternion {
double a;
double i;
double j;
double k;
} quaternion;
int main(void) {
struct quaternion n1 = (struct quaternion){3.141592, -2.72192, -6.28384, -9.478};
__m256d n1_t = *(__m256d *)&n1;
// 0b00011011
n1_t = _mm256_shuffle_pd(n1_t, n1_t, _MM_SHUFFLE(0,1,2,3));
*(__m256d *)&n1 = n1_t;
printf("\t%lf %lf %lf %lf\n", n1.a, n1.i, n1.j, n1.k);
return 0;
}
P.S. Explanation of what should be in place a mask I have not found, so as to use SSE* way.
I expected see this result: 3.141592 -2.721920 -6.283840 -9.478000
But i got this: -2.721920 -2.721920 -6.283840 -9.478000
I have only two possible reasons:
1) The mask is defined in another way
2) Error in Intel® Software Development Emulator | https://software.intel.com/en-us/forums/topic/472435 | CC-MAIN-2015-32 | refinedweb | 144 | 75.4 |
(previous gdb posts: how does gdb work? (2016) and three things you can do with gdb (2014))
I discovered this week that you can call C functions from gdb! I thought this was cool because I’d previously thought of gdb as mostly a read-only debugging tool.
I was really surprised by that (how does that WORK??). As I often do, I asked on Twitter how that even works, and I got a lot of really useful answers! My favorite answer was Evan Klitzke’s example C code showing a way to do it. Code that works is very exciting!
I believe (through some stracing & experiments) that that example C code is different from how gdb actually calls functions, so I’ll talk about what I’ve figured out about what gdb does in this post and how I’ve figured it out.
There is a lot I still don’t know about how gdb calls functions, and very likely some things in here are wrong.
What does it mean to call a C function from gdb?
Before I get into how this works, let’s talk quickly about why I found it surprising / nonobvious.
So, you have a running C program (the “target program”). You want to run a function from it. To do that, you need to basically:
- pause the program (because it is already running code!)
- find the address of the function you want to call (using the symbol table)
- convince the program (the “target program”) to jump to that address
- when the function returns, restore the instruction pointer and registers to what they were before
Using the symbol table to figure out the address of the function you want to call is pretty
straightforward – here’s some sketchy (but working!) Rust code that I’ve been using on Linux to do that. This code uses the elf crate.
If I wanted to find the address of the
foo function in PID 2345, I’d run
elf_symbol_value("/proc/2345/exe", "foo").
fn elf_symbol_value(file_name: &str, symbol_name: &str) -> Result<u64, Box<std::error::Error>> { // open the ELF file let file = elf::File::open_path(file_name).ok().ok_or("parse error")?; // loop over all the sections & symbols until you find the right one! let sections = &file.sections; for s in sections { for sym in file.get_symbols(&s).ok().ok_or("parse error")? { if sym.name == symbol_name { return Ok(sym.value); } } } None.ok_or("No symbol found")? }
This won’t totally work on its own, you also need to look at the memory maps of the file and
add the symbol offset to the start of the place that file is mapped. But finding the memory maps
isn’t so hard, they’re in
/proc/PID/maps.
Anyway, this is all to say that finding the address of the function to call seemed straightforward to me but that the rest of it (change the instruction pointer? restore the registers? what else?) didn’t seem so obvious!
You can’t just jump
I kind of said this already but – you can’t just find the address of the function you want to run
and then jump to that address. I tried that in gdb (
jump foo) and the program segfaulted. Makes
sense!
How you can call C functions from gdb
First, let’s see that this is possible. I wrote a tiny C program that sleeps for 1000 seconds and
called it
test.c:
#include <unistd.h> int foo() { return 3; } int main() { sleep(1000); }
Next, compile and run it:
$ gcc -o test test.c $ ./test
Finally, let’s attach to the
test program with gdb:
$ sudo gdb -p $(pgrep -f test) (gdb) p foo() $1 = 3 (gdb) quit
So I ran
p foo() and it ran the function! That’s fun.
Why is this useful?
a few possible uses for this:
- it lets you treat gdb a little bit like a C REPL, which is fun and I imagine could be useful for development
- utility functions to display / navigate complex data structures quickly while debugging in gdb (thanks @invalidop)
- set an arbitrary process’s namespace while it’s running (featuring a not-so-surprising appearance from my colleague nelhage!)
- probably more that I don’t know about
How it works
I got a variety of useful answers on Twitter when I asked how calling functions from gdb works! A lot of them were like “well you get the address of the function from the symbol table” but that is not the whole story!!
One person pointed me to this nice 2 part series on how gdb works that they’d written: Debugging with the natives, part 1 and Debugging with the natives, part 2. Part 1 explains approximately how calling functions works (or could work – figuring out what gdb actually does isn’t trivial, but I’ll try my best!).
The steps outlined there are:
- Stop the process
- Create a new stack frame (far away from the actual stack)
- Save all the registers
- Set the registers to the arguments you want to call your function with
- Set the stack pointer to the new stack frame
- Put a trap instruction somewhere in memory
- Set the return address to that trap instruction
- Set the instruction pointer register to the address of the function you want to call
- Start the process again!
I’m not going to go through how gdb does all of these (I don’t know!) but here are a few things I’ve learned about the various pieces this evening.
Create a stack frame
If you’re going to run a C function, most likely it needs a stack to store variables on! You definitely don’t want it to clobber your current stack. Concretely – before gdb calls your function (by setting the instruction pointer to it and letting it go), it needs to set the stack pointer to… something.
There was some speculation on Twitter about how this works:
i think it constructs a new stack frame for the call right on top of the stack where you’re sitting!
and:
Are you certain it does that? It could allocate a pseudo stack, then temporarily change sp value to that location. You could try, put a breakpoint there and look at the sp register address, see if it’s contiguous to your current program register?
I did an experiment where (inside gdb) I ran:`
(gdb) p $rsp $7 = (void *) 0x7ffea3d0bca8 (gdb) break foo Breakpoint 1 at 0x40052a (gdb) p foo() Breakpoint 1, 0x000000000040052a in foo () (gdb) p $rsp $8 = (void *) 0x7ffea3d0bc00
This seems in line with the “gdb constructs a new stack frame for the call right on top of the stack
where you’re sitting” theory, since the stack pointer (
$rsp) goes from being
...bca8 to
..bc00
– stack pointers grow downward, so a
bc00 stack pointer is after a
bca8 pointer.
Interesting!
So it seems like gdb just creates the new stack frames right where you are. That’s a bit surprising to me!
change the instruction pointer
Let’s see whether gdb changes the instruction pointer!
(gdb) p $rip $1 = (void (*)()) 0x7fae7d29a2f0 <__nanosleep_nocancel+7> (gdb) b foo Breakpoint 1 at 0x40052a (gdb) p foo() Breakpoint 1, 0x000000000040052a in foo () (gdb) p $rip $3 = (void (*)()) 0x40052a <foo+4>
It does! The instruction pointer changes from
0x7fae7d29a2f0 to
0x40052a (the address of the
foo function).
I stared at the strace output and I still don’t understand how it changes, but that’s okay.
aside: how breakpoints are set!!
Above I wrote
break foo. I straced gdb while running all of this and understood almost nothing but
I found ONE THING that makes sense to me!!
Here are some of the system calls that gdb uses to set a breakpoint. It’s really simple! It replaces
one instruction with
cc (which tells me means
int3
which means
send SIGTRAP), and then once the program is interrupted, it puts the instruction back
the way it was.
I was putting a breakpoint on a function
foo with the address
0x400528.
This
PTRACE_POKEDATA is how gdb changes the code of running programs.
// change the 0x400528 instructions 25622 ptrace(PTRACE_PEEKTEXT, 25618, 0x400528, [0x5d00000003b8e589]) = 0 25622 ptrace(PTRACE_POKEDATA, 25618, 0x400528, 0x5d00000003cce589) = 0 // start the program running 25622 ptrace(PTRACE_CONT, 25618, 0x1, SIG_0) = 0 // get a signal when it hits the breakpoint 25622 ptrace(PTRACE_GETSIGINFO, 25618, NULL, {si_signo=SIGTRAP, si_code=SI_KERNEL, si_value={int=-1447215360, ptr=0x7ffda9bd3f00}}) = 0 // change the 0x400528 instructions back to what they were before 25622 ptrace(PTRACE_PEEKTEXT, 25618, 0x400528, [0x5d00000003cce589]) = 0 25622 ptrace(PTRACE_POKEDATA, 25618, 0x400528, 0x5d00000003b8e589) = 0
put a trap instruction somewhere
When gdb runs a function, it also puts trap instructions in a bunch of places! Here’s one of
them (per strace). It’s basically replacing one instruction with
cc (
int3).
5908 ptrace(PTRACE_PEEKTEXT, 5810, 0x7f6fa7c0b260, [0x48f389fd89485355]) = 0 5908 ptrace(PTRACE_PEEKTEXT, 5810, 0x7f6fa7c0b260, [0x48f389fd89485355]) = 0 5908 ptrace(PTRACE_POKEDATA, 5810, 0x7f6fa7c0b260, 0x48f389fd894853cc) = 0
What’s
0x7f6fa7c0b260? Well, I looked in the process’s memory maps, and it turns it’s somewhere in
/lib/x86_64-linux-gnu/libc-2.23.so. That’s weird! Why is gdb putting trap instructions in libc?
Well, let’s see what function that’s in. It turns out it’s
__libc_siglongjmp. The other functions
gdb is putting traps in are
__longjmp,
____longjmp_chk,
dl_main, and
_dl_close_worker.
Why? I don’t know! Maybe for some reason when our function
foo() returns, it’s calling
longjmp,
and that is how gdb gets control back? I’m not sure.
how gdb calls functions is complicated!
I’m going to stop there (it’s 1am!), but now I know a little more!
It seems like the answer to “how does gdb call a function?” is definitely not that simple. I found it interesting to try to figure a little bit of it out and hopefully you have too!
I still have a lot of unanswered questions about how exactly gdb does all of these things, but that’s okay. I don’t really need to know the details of how this works and I’m happy to have a slightly improved understanding. | https://jvns.ca/blog/2018/01/04/how-does-gdb-call-functions/ | CC-MAIN-2022-21 | refinedweb | 1,680 | 70.33 |
SYNOPSIS
svn2cl [OPTION]... [PATH]...
DESCRIPTION
svn2cl generates a classic GNU-style ChangeLog from the log messages in
a subversion repository. It acts as a wrapper around the 'svn log'
command, parsing the XML output with an XSLT stylesheet. Alternatively
it can generate HTML output intended for use with the svn2html.css
style sheet that comes with svn2cl.
In addition to its own options, it accepts and passes along most svn
log options; see 'svn help log' for a list of those and their
documentation. If PATH is not given, svn2cl will run svn log on the
current directory, so it should do the right thing when run from the
top of a subversion checkout of the project.
--strip-prefix=NAME
Strip NAME from the first part of all file names (e.g.
project/trunk). By defaults the current path inside the
repository is stripped.
--linelen=NUM
Wrap lines at NUM characters. By default, lines are wrapped at
75 characters. This option is ignored when the --html option is
specified.
--group-by-day
This option causes all commit messages to be grouped by day, as
long as all the changes are by the same author. By default each
message is listed separately with its own timestamp.
--separate-daylogs
Include a blank line between log entries when they are grouped
by day. Only useful with the --group-by-day option. This
option is ignored when the --html option is specified, edit
svn2html.css to tune the layout.
-i, --include-rev
Include the subversion revision number in the ChangeLog. If the
--html option is specified this is implied, edit svn2html.css to
turn it off.
-a, --include-actions
Add action labels [ADD], [DEL] and [CPY] tags to files to show
the operation that is performned on the files.
--title=NAME
If outputting an HTML file the NAME is used as the title. This
option is ignored for normal text output.
--revision-link=NAME
This option is used to generate links from the revision numbers
in the generated HTML file. If NAME contains two hashes '##'
that part will be replaced by the revision number, otherwise the
revision number will be appended to NAME. Only the first
occurrence of '##' will be replaced.
This option is ignored for normal text output.
--ignore-message-starting=STRING
Any log messages that start with the specified STRING are
ignored and will not show up in the output. The STRING
comparison is case sensitive.
-o, -f, --output=FILE, --file=FILE
Output ChangeLog to FILE instead of the default ChangeLog (or
ChangeLog.html for HTML output).
--stdout
Output ChangeLog to stdout instead of to a file.
--authors=FILE
The FILE is used to map author names as exported by svn to full
names. See the section on AUTHORS FILES below for more
information.
Note that the --authors option can have poor performance in some
cases.
--html Generate an HTML file containing a ChangeLog instead of the
default text ChangeLog file. This feature is still
experimental. The svn2html.css file that is included in the
distribution can be used to format the HTML.
-h, --help
Show short summary of options.
-V, --version
Show version of program.
Optional PATH arguments and the following options are passed directly
to the 'svn --xml log' command: -r, --revision, --targets,
--stop-on-copy, --username, --password, --no-auth-cache,
</authors>
svn2cl searches for <author> tags with the specified uid attribute.
The content from the author tag is substituted for the author name.
The <author> tag may also contain XML child tags which can be useful
for embedding HTML into the result. For this to work namespace
information should be included for HTML output:
<?xml version="1.0" encoding="utf-8"?>
<authors xmlns:
<author uid="arthur">
Arthur de Jong <<html:b>arthur@ch.tudelft.nl</html:b>>
</author>
</authors>
The svn2cl distribution contains a sample authors.xml file.
As a bonus a plain text authors file that looks like the following is
automatically converted to the XML representation:
arthur:Arthur de Jong <arthur@ch.tudelft.nl>
NOTES
Note that the default revison range for svn log is BASE:1. This means
that svn2cl will not always include the most recent revisons of the
repository. Either run 'svn update' before running svn2cl or pass '-r
HEAD:1'.
EXAMPLES
Run svn log recursively on the current directory and generate a text
ChangeLog file in the current directory for the entire log history:
svn2cl
Output the changes from the last week, while including revision numbers
in the ChangeLog:
svn2cl -i -r "HEAD:{`date -d '7 days ago' '+%F %T'`}"
(actually subversion will include the first revision before the
specified period)
Generate an HTML changelog for svn://svn.example.com/project/trunk,
removing "project/trunk" from the file names in the changelog. Group
all commits per day into one ChangeLog entry and only include changes
from 2005:
svn2cl --html --strip-prefix=project/trunk --group-by-day \
-r '{2006-01-01}:{2005-01-01}' \
svn://svn.example.com/project/trunk
SEE ALSO
'svn help log' | http://www.linux-directory.com/man1/svn2cl.shtml | crawl-003 | refinedweb | 831 | 57.47 |
Co-chair
I've asked Tim Bray to co-chair
the IETF working group, and optimistically updated the
draft charter
on the wiki.
It’s just data
I've asked Tim Bray to co-chair
the IETF working group, and optimistically updated the
draft charter
on the wiki.
Take this in the spirit intended, which is just a suggestion/concern Sam, but shouldn't you consider opening this selection up, based on the fact that Atom is community driven? And also, would it perhaps not be better to have someone who is not affiliated with a major computer company as a co-chair? You're IBM, Tim's now Sun.
It's just that so many of these efforts end up being driven by HP, Sun, IBM, or Microsoft or other major vendor. Now, perhaps the people working for these companies in 'researcher mode' are the only ones paid to be part of this effort, but it seems as if there's only about ten major players in the world on these efforts, and they just circle around from group to group.
I may not be making my point well, and I imagine others working on Atom will agree with Tim being co-chair. It just seems a bit exclusive.Posted by Shelley at
I don't like this. You and Tim have almost always been on the same side of every discussion. What's the point of having a co-chair if you're both on the same side?
(I'd also like there to be be people actually working at one end or the other of syndication involved in the process, but I'm naive like that. You choose who you like)Posted by Graham Parks at
Shelley, I posted the draft IETF charter on the wiki, and announced it here. To date, I have received no feedback on the choice of chairs.
Sometimes the best way to attract feedback is to make a proposal.Posted by Sam Ruby at
"To date, I have received no feedback on the choice of chairs"
See above.
(Sorry to sound bitter, but you're running this process in an absolutely absurd manner - Announcing major new information at random presentations rather than to the group working with you on it, for instance)Posted by Graham Parks at
I was going to write a parody
, but I see Shelley's already done it for real. It'd go something like:
"Oh yeah, Sam, can you be any more obvious? Tim Bray goes to work for Sun one day, the next day you name him co-chair. All those denials of BigCo control are ringing pretty hollow now!"Posted by Aaron Swartz at
Both directors have ample experience writing specs and discerning consensus, even when it contradicts their own opinions.
That they are both employed by the Usual Suspects is perhaps unfortunate, but it's hard to see how it would matter. If Atom turns out less friendly to small developers than RSS, it will fail.
Corporate affiliation is not a good reason to go with less experienced directors.Posted by Robert Sayre at
I would suggest that you get one or more aggregator authors involved in the ietf specification process. Experience with specs is useful; I suspect that experience dealing with specs in the real world would be more useful still.....Posted by James Robertson at?
The only thing of interest to me is that the news reports claim that Tim Bray will be involved in RSS and now Sam is trying to get him roped into Atom. Sounds to me like Sam is trying to force Sun's hand in choosing sides.
Ahhh, I love the smell of politics in the morning.Message from Dare Obasanjo at
Don't hit me immediately, but if you're viewing this from a political perspective, a good idea would be to invite ... dare I say it ... Dave Winer?Posted by Stefan Tilkov at
"I would suggest that you get one or more aggregator authors involved in the ietf specification process."
Us aggregator writers are annoyed that Atom exists in the first place. More parsers == more potential for bugs. Why would we support the effort to make us do more work and have more bugs with no benefits?Posted by Dan at
SemanticContext(*Formal)
Following on the comments of Mr. Tilkov and "Dan", I would suggest there's something to be said for merging the standards effort, and getting it back down to (roughly) two. (For an example, perhaps RSS .91?/2.0/3.0 and RDF 1.0.)
Furthermore, I'm somewhat incredulous that people would complain about what Mr. Ruby is doing, considering that Mr. Rod Smith (VP of "Emergent" Technology) and Mr. Jonathan Swartz (iirc, and don't know title) are discussing how to carve up the marketplace. And who makes money and who doesn't make money. Although I agree it would have been less conspicuous if this offer had been made prior to Mr. Bray's working at Sun and showing interest in RSS2.
"I don't understand what this BigCo hubbub is supposed to mean." There's a knee-jerk reaction by too many people. These people often being the same one's that ask, "How can we get this technology out to the MASSES", for some odd reason. I believe the bias against "BigCo" comes from people who actually believe the tripe of "radical decentralization", meaning they're not going to be satisfied unless THEY are the co-chair.
Sarcasm(*ON)
All we gotta do is just pretend EVERYBODY CAN BE THE CO-CHAIR...!
Sarcasm(*OFF)
I agree with:
"(I'd also like there to be be people actually working at one end or the other of syndication involved in the process, but I'm naive like that. You choose who you like)" as well as:
"I would suggest that you get one or more aggregator authors involved in the ... specification process. Experience with specs is useful; I suspect that experience dealing with specs in the real world would be more useful still....."
I would extend these further, and suggest that people that have 2 or 3 decades actual direct experience in Business Transformation would be useful, though hard to find. But they have experience in transforming manual processes to computer, which few of lesser experience have. (Of course, I'm not saying that only those who have decades of experience actually implementing systems can contribute good input, however.)
"Both directors have ample experience writing specs and discerning consensus, even when it contradicts their own opinions." This would illustrate the principle that good design can be negotiated better than it can be found by trial-and-error. There's room for both, but I don't have any question about which is more effective, which is the latter.
"Most web standards are written by the same small pool of professional standards people..."
And I think this is the largest part of the problem. It's not BigCo, but it's that people who are "tenured" with either a company or an academic institution will, invariably, negotiate a different design than those who have to actually implement the (sometimes Rube-Golberg-like...;-) theory on a timeline, in order to eat.Posted by JayT at
"Us aggregator writers are annoyed that Atom exists"
Speak for yourself. I aggregator writer am annoyed RSS continues to exist in non-deprecated form.Posted by Graham Parks at
Graham,
That's interesting. Besides renaming some tags and adding the usual suspects when it comes to web standards to the author section of the spec what makes Atom better than RSS? If anything needs deprecating it's the entire broken model that pretends that date + title + content is the only significant information worth syndicating.
I've been working with RSS for about a year now and have followed the Atom discussions since they started. I haven't seen any major benefit of Atom, for every little nicety (adding a modified date) some cruft comes along with it (adding a created date) so at the end it's just another quirky, confused syndication format with too little in the core.Message from Dare Obasanjo at
1. It requires dates. Having to rely on when an item is first seen by the software is really shoddy.
2. It has identifiers (remember one of the biggest issues to sorting out your synchronization format was how to identify items?)
3. It defines what one might find between the title and description tags. HTML, text, mixture of both?
4. It differentiates summaries and contents.
5. People are actually thinking about the issues re: standardizing content and syndicating, which was never done for RSS. Granted, not much has come from this yet, but at least the intention is there.
I came into the RSS scene quite late (May 2003), and had to put up with all sorts of confused specs, shocking flaws and being told Shrook wasn't displaying feeds "correctly" (when there's no such thing). When the Atom project came along, I assumed everyone else shared my frustrations and would be keen to sweep the whole RSS mess under the carpet and start again. Unfortunately some RSS backers took it personally, and some didn't see the benefits, which brings us to now. I still think one way or another RSS 0.9, 1.0 and 2.0 aren't long for this world - and Atom is currently the best bet.Posted by Graham Parks at
(btw I think I might agree that there's more to syndication than "date + title + content". What do you mean exactly?)Posted by Graham Parks at
SemanticStyle(*Informal)
1. It requires dates. Having to rely on when an item is first seen by the software is really shoddy.
If the authoring tool provides suitable dates, what does it matter. Iow, that sure appears to be a problem with the tools, rather than the spec. As far as I know, the RSS spec doesn't prevent these new dates either.
2. It has identifiers (remember one of the biggest issues to sorting out your synchronization format was how to identify items?)
I'll defer to others. I haven't seen what I think is a good design for items, so far.
3. It defines what one might find between the title and description tags. HTML, text, mixture of both?
That's an improvement, but not an innovation worth breaking all existing code for, in my opinion/observation (imo/o).
4. It differentiates summaries and contents.
People still seem confused about that, but it's a none-issue as I posted to RSS-User list. That's a PBKAC (problem between keyboard-and-chair), as it's a problem that people (authors and readers) do not see eye-to-eye on.
5. People are actually thinking about the issues re: standardizing content and syndicating, which was never done for RSS. Granted, not much has come from this yet, but at least the intention is there.
According to info (from John Patrick, iirc, but I believe anyway) IBM has somewhere around 20% of CMS market, so there's been at least some thought to this for a while.
But, more to the point, a lot of the thinking so far has been on how to kill off, or at least slow down, RSS acceptance. So the Atom effort has been a decidedly mixed-bag, to say the least imo/o.
RSS isn't long for the world?!? It has barely been started and shipped 500,000,000 Disney files, from what I hear tell. Glad you're anxious to have Disney, CNN, Yahoo, Nokia and all the other bit players they should scrap working code, Mr. Parks! But I wouldn't be, m'self.
I posted, 1/11/02 on TYR and Userland lists, iirc, to the effect that Radio/RSS could be lightweight replacement for browser, but even Scoble missed that one. (Wasn't on a blog, which are only things Robert finds suitable to read I guess...;-) I wuz optimistic, at the time.Posted by JayT at
What the heck is wrong with you folks? Tim did a good job with XML and I can trust him to do the same for Atom. If you are questioning his ability to remain objective, do that to his face instead of complaining about how the 'picture' looks. Since when did engineers become art critics?
Although I did more than my share of ragging on XML specs he had his hand on, I want him to co-chair Atom because I know nothing will prevent him from saying what must be said at the right time. Not even sunspots.Posted by Don Park at
1. It requires dates. Having to rely on when an item is first seen by the software is really shoddy.
Like I said this is a nicety, in reality most feeds have dates.
This could easily be spec cleanup in a subsequent version of RSS.
2. It has identifiers (remember one of the biggest issues to sorting out your synchronization format was how to identify items?)
Again, a nicety. None of my users care about the fact that in the average RSS feed there is no global unique identifier for an item.
This is another thing that could be spec cleanup in a subsequent version of RSS or in an RSS profile.
3. It defines what one might find between the title and description tags. HTML, text, mixture of both?
It defines that they can be anything as long as it has a valid MIME type then there's the weird escaping vs. unescaped vs. embedded binary gunk. I also like the fasct that folks think that simply tagging some element's content as application/xhtml+xml means they're actually providing valid XHTML content (Yes, I'm refering to the boobs at Blogger). As far as I'm aware, the W3C never figured out how to spec how embedding XHTML in other markup formats was supposed to work and I haven't seen anyone in the Atom 'community' provide any rigorous definition either.
The spec is currently extremely ambiguous when it comes to providing content in a feed. If you haven't observed this then I guess you either haven't seriously read the spec nor have you written a fully featured implementation. Of course, I haven't done the latter either.
4. It differentiates summaries and contents.
This is useful. Although we already have this in RSS with description vs. content:encoded.
5. People are actually thinking about the issues re: standardizing content and syndicating, which was never done for RSS. Granted, not much has come from this yet, but at least the intention is there.
So they haven't made any progress or any significant headway but they should be commended because no one thought about the issues when RSS was being developed? I find that very insulting to the various folks who've been involved in the various RSS efforts from RSS 0.91 to 1.0 and 2.0.Posted by Dare Obasanjo at
<I>This could easily be spec cleanup in a subsequent version of RSS.</I>
I know it's technically fixible, but "the RSS spec is, for all practical purposes, frozen at version 2.0.1". Every initiative to fix RSS has gone nowhere. I think Atom is the nearest we're going to get.
<I>None of my users care about the fact that in the average RSS feed there is no global unique identifier for an item</I>
But they care that features like synchronization aren't commonplace, or don't work reliably? And that sometimes items show up twice when typos are corrected?
<I>we already have this in RSS with description vs. content:encoded</I>
Do we? It's totally informal. I don't think I could right a feature that relied on knowing whether I had summary or full content without Atom (obviously Atom won't be 100% reliable, but I'm sure it will be better).
I agree the Atom 0.3 spec is ambiguous and incomplete, and so do the people that wrote it.Posted by Graham Parks at
Graham,
Thanks for explaining your perspective. The author of the RSS spec doesn't want to make some optional elements mandatory so the solution is to create an alternate protocol. I wonder how much progress the Internet and World Wide Web would have made if this was how decisions commonly made when replacing communication protocols and data formats.
Anyway, I've already gone over my monthly quota of posts about Atom/RSS/syndication technology. See you guys next month. :)Posted by Dare Obasanjo at
The author doesn't want to fix any problems with his spec, or even acknowledge that there are problems, or these days even acknowledge that he is the author. I'd actually rather we just fixed RSS but Atom seems like the only way to do it.Posted by Graham Parks at
Well, let's all bear in mind that the IETF hasn't actually welcomed us with open arms yet, but I'm willing to give it a shot.Posted by Tim Bray at
Tim Bray (on co-chair):
but I'm willing to give it a shot.
Well, at the very least we have the two of the best helmsmen steering the ship. That's a great start on the way to IETF. Thanks for accepting the offer.Posted by Isofarro at
After I wrote the comment, I realized it was a done deal -- Sam was co-chair, he asked Tim, we assume Tim would say yes, end of story.
Dare:
?"
I'm not sure if you're also indulging in parody with this statement, Dare, but yes I do believe it does make a difference. The whole point of Atom was it was not driven by a few strong people who dominate the process; that it was community driven.
However, in the end it is becoming somewhat business as usual.Posted by Shelley at
There's no reason why this cannot continue to be a community driven process. In fact the IETF process actively encourages this by requiring people to reach a rough consensus. The products of the group will not be ratified by the IESG if it is overwhelmed by a few strong people without the support of other members. Anyone with an e-mail address and an informed opinion can be involved in an IETF working group. Having said that, it does often take a few strong people to drive through new standards so that the whole thing doesn't get mired in 'designed by committee' problems.
In fact, it often helps if the chairs of the group are not particularly active participants in the general discussion so that they can stand off somewhat and intervene with perspective as necessary for specific issues.Posted by Adrian Bateman at
Let me remind everybody that the charter is still draft, and has neither been reviewed nor approved by the IETF. Furthermore, there are clearly defined roles, checks and balances, and processes for ensuring that everybody who wishes to constructively contribute gets an opportunity to do so.Posted by Sam Ruby at
Sam, you've agreed to move forward on Dave Winer's point #3 for the unification of RSS and Atom under the IEFT. Is this sudden move to the IETF a way to make good on that commitment or a way of doing an end run around Dave so that he is forced to eventually join your already existing group?Posted by Jeremy at
Sudden?
10 Feb: Where are we going?
17 Feb: Draft Atom IETF charterPosted by Sam Ruby at
Shelley,
Interesting perspective. In the few years I've worked on software both Open Source and for large corporations I've never seen a successful development process that wasn't dominated by a few strong people. The ones that weren't ending up spinning their wheels since everyone had differing opinions and no one backed down or would listen to the others.
Based on watching the Atom process it has swung on both ends, anarchic then dominated by the familiar faces. At the end the usual suspects are bubbling to the top with some up and comers like Joe Gregorio also dominating the direction.
In the end it's just another syndication format. Slightly better than RSS in some regards, slighty worse in others. Whatever ends up happening RSS will be the Napster of online syndication, whether Atom can supersede it and become the FastTrack of online syndication will be seen. I suspect that Atom will end up being the Gnutella protocol of online syndication at best.
The reinventing syndication discussions aren't going to be over this year or next year. The fundamental concepts at the core of all the options are too short sighted and too limited to last that long. Of course, I might be wrong and people will just hack around them as Netscape hacked cookies into HTTP and Javascript into HTML.Message from Dare Obasanjo at
I don't feel paranoia about both Sam and Tim working for Big Companies or being on the same side in many arguments. They both seem very skilled at cat herding, and appear willing to listen to the community, the majority, minority anyone. If anything, the Big Company angle is positive - they both appear to be attracting attention towards Atom from their companies, which has to be a good thing. I'm not sure it's accurate to talk of anyone 'dominating' either, I don't think that's part of their job description as chairs (and I believe they'll stick to that description), beyond generally trying to move things forward.
I think it's great that they've volunteered. Bravo!
btw, I certainly don't share Dare's slightly pessimistic viewpoint, to quote Alan Kay: "The best way to predict the future is to invent it."Posted by Danny at
I am not paranoid about both of them being co-chairs -- but I think there might have been some options that might have more easily opened the door with the RSS community. Perhaps I am mistaken and the RSS community will be delighted to see Sam and Tim as co-chairs of an effort that was supposed to unite these two disparate projects.
But yes, I would like to see new faces in these committees, and I'd like to see other strong but not as well known or as highly connected people involved in these efforts. Spread the wealth and exposure you might say. But if no one volunteered, then I can understand. Personally, I didn't even know this was going on until I saw this post, but I don't stay as involved as I used to. I imagine others did know and weren't interested. That's cool.
I think it's great that they've volunteered, especially if they don't get paid for this effort (i.e. not done as part of their jobs at IBM or Sun). It is not an easy job, keeping the project directed but still open.
Dare, I think where we're seeing this from two different directions is that I hoped this would be a unification process, but I think you're seeing two separate specs, two different directions. I'll have to admit, I probably did misread the IETF effort. If it is pure Atom, then it makes a lot more sense with Tim.
Did want to say that this is not a disparagement of Tim. I've seen Tim's efforts elsewhere with other spec efforts, and he is experienced, that's for sure. It was just me hoping to see some new faces, maybe some folks who have been on the more 'applied' side.Posted by Shelley at
Shelley,
I haven't seen any indication that Atom is an attempt to unify the various flavors of RSS (the two main branches being the RDF branch and Dave Winer's family of specs). There has been no discussion about this on the mailing list nor has there been any wiki proposals on this to the best of my knowledge. Granted Atom has dropped of my radar but I still subscribe to the "Formerly Echo" feed.
Atom is yet another syndication format but this time it is backed by big name companies and has the web standards usual suspects on the authors column of the spec. I don't expect anything innovative to come out of this, just a formalizing of known best practices for the more popular scenarios in RSS.
What I'd like to see is inovations that make syndication more useful and palatable to the general populace but design by committee is never where you want to do that especially not with the web standards usual suspects.Message from Dare Obasanjo at
Shelley, Let me repeat: the charter is still draft, and has neither been reviewed nor approved by the IETF.Posted by Sam Ruby at
I, for one, am looking forward to Dare's paradigm-shattering innovations in this area.Posted by Mark at
Mark,
Sarcasm aside, Sam uses one of them. wfw:commentRss. Chris Sells called me, we talked and he blogged about what we came up with. Since then SharpReader has adopted as have the major .NET based blogging tools. Lots of my users love the fact that they can read the comments to a post directly from their aggregator.
Of course, if you don't use SharpReader or RSS Bandit you probably don't realize features like this are even possible.
Enjoy.Message from Dare Obasanjo at
That feature is a good one, and the capability is listed as a goal in the Atom charter on the wiki.Posted by Robert Sayre at
FWIW, I agree with Tim Bray that standards have nothing to do with innovation.Posted by Sam Ruby at
Damn, Dare, warn a girl next time when you're going to shatter a paradigm. My ears are still ringing ;-)
Sam, agree with you on standards having nothing to do with innovation. And when you repeat the info about the charter, does that mean we can indulge in juicy subversive wiki tactics?
(That sounds like a good conference presentation -- Juicy Subversive Wiki Tactics.)Posted by Shelley at
This site already supports using the Atom API to post comments. Atom feeds can point to the appropriate URI to POST to using [link rel="service.post" type="application/atom+xml" href="..."] within an atom:entry. The person who invented the Comment API is now the primary author of the Atom API spec; he views his earlier Comment API as "one to learn from and throw away".
People who wish I were ignorant are often disappointed.Posted by Mark at
Shelley: let me put it this way, I don't expect to be talking to either Ted or Scott for at least a week. Even when I do, the they may require that a BOF be held before creating the working group. Or they may have their own ideas as to who would make suitable chairs or other input on the charter. Even if and when the working group is created, the charter can be always be modified.
Dare, Mark: I've added the appropriate link tags to my atom feed.Posted by Sam Ruby at
I blogged on the subject: [link]
But more help is needed. Two chairs is plenty, but two editors is, in my opinion, maybe not enough for two specs of this size. I'd be happy (and I assume Joe & Mnot would agree) to see some co-editorships. But only from people who can really put some cycles in. -TimPosted by Tim Bray at
Tim Bray, one of the XML founders, has joined Sun as a Technology Director. He writes about the choices he had, and on why he decided to join Sun, a move that some people have been surprised about. On his first day he explained that "Parts of .NET...Excerpt from Zinoblog at
This site already supports using the Atom API to post comments.
Cool!
Anyone want to volunteer to write an Atom API-enabled spambot?Posted by Jacques Distler at
Reading old RSS debates, this one from Dave Winer: Here's how Microsoft is going to f*** all of us. Their blogging tool will support RSS 2.0. Basic stuff like title, link, description, and maybe to be nice, a few extras like guid, category, and generator. Then they're going to define a namespace with poorly documented stuff the rest of us don't understand. Some of us will support Microsoft's extensions, others won't. Either way it won't matter. They'll be able to......
[more]
Trackback from Eric Hanson
Anyone want to volunteer to write an Atom API-enabled spambot?
This site has supported the Comment API for a long time, and there are no Comment API-based bots, unless you count Dare.Posted by Mark at
This site has supported the Comment API for a long time, and there are no Comment API-based bots, unless you count Dare.
Ah, but there is actually a hope that the Atom API might be adopted by more than 3 websites in the known universe.
Once there are more than a handful of blogs to spam with the Atom API, it becomes worth writing a 'bot to do so.
Perhaps a Reference Implementation in Python would be in order ...Posted by Jacques Distler at | http://www.intertwingly.net/blog/1739.html | crawl-002 | refinedweb | 4,946 | 71.34 |
.
It works but is does this code contain bad practice?
Nevermind. It doesn’t work. I’m blind and didn’t notice it was dropping the .2
Yes, a few bad practices.
1) determineAnswer() is too vague of a name to be useful. Determine answer of what?
2) When you do your comparisons against the char values, don’t use 43, 45, 42, etc… Those are magic numbers. Use character literals: ‘+’, ‘-‘, etc…
3) It’s a little weird for determineAnswer() to ask the user for the operation. Shouldn’t you do that before you determine the answer?
But overall, not too far off the mark.
Question 2.h
int16_t? how did your civilization cope with the Y0x8K bug?
Great course, btw. Great to find a resource like this that is still being updated 10 years down the line with such frequent input from author in comments. Much respect.
Just like civilization ended the first time with y2k. 🙂
Hi, first off I would like to say thanks a lot for this site. Now for the 4th question how can i prevent this from printing that the ball is on the ground multiple times if it is on the ground after like 2 seconds. My code is below. I tried doing an ifndef def type thing, and it did the same thing so I’m assuming i don’t understand it quite well yet.
Also the last cin in main is just to stop it from dissapearing after the code runs so it waits for my input. Is there a better way of doing this?
main
functions
You can’t use preprocessor commands for runtime conditional behavior because those are processed at compile time.
The nature of the code here doesn’t really lend itself well to not printing “The ball is on the ground” a bunch of times. In future lessons, when you learn how to do loops, we’ll revisit this example using a loop, where you can print heights as many times as needed until the ball is on the ground, and then stop.
The best way to get the program to pause at the end is to use an input statement, but not like you’ve done it. I show a better method in lesson 0.7.
My main problem with the Quizzes seems to be not reading them closely enough! In quiz 4, I didn’t notice the requirement for putting the const in a header file. The programs runs fine by just putting const double gravity{9.8}; as a global. But that doesn’t help in learning a better way. :wallbash:
I also used a loop when we haven’t covered method yet! I’m too impatient, which probably explains the ‘not reading close enough’ problem. :rolleyes: Since there is usually very little movement at "0 seconds", I started the loop at 1. "Efficiency" at it’s worst!
I also added some if/else if statements to control the last "s" in seconds. "1 seconds" gets my goat! :blush:
Still, I can’t complain about your instruction methods of the quizzes!
#include<iostream>
using namespace std;
int main()
{ cout<<"enter initial height :"<<endl;
double initialHeight;
cin>>initialHeight;
const double gravity=9.8;
double distanceFallen;
double height;
for(int sec=0;sec<=5;sec++)
{
if(sec<5)
{
distanceFallen=(gravity*(sec*sec))/2;
height=initialHeight-distanceFallen;
cout<<"At "<<sec<<" seconds, "<<"the ball is at height : "<<height<<" meter "<<endl;
}
else
{
cout<<"At "<<sec<<" seconds, "<<"the ball is on the ground "<<endl;
}
}
return 0;
}
I cheated a bit and googled raising to a power in C++ and discovered the <cmath> header and used.
instead of
is this good practice? or should i do my math "manually".
It’s not a good practice to use this function for integer exponentiation, since it returns a floating type value. Due to precision issues, you may not get the answer you expect.
I show an example of an efficient pow function for integers at the start of chapter 3. You can just include that function in your programs that need integer exponentiation.
But really, if you’re only doing squares, you might as well just do x*x.
do it manually as far as possible to learn it from the scratch
I have added in my own extra feature which stops the program running, once the ball is on the ground. Otherwise if the ball stops after 2 seconds, you will have 3 more lines of "The ball is on the ground". Here is the function:
I am not sure how I can have the calculation and printing in two different functions, though, because I’m using a for loop.
My code above is wrong! I just realised my error, I was re-assigning the variable h every second, whereas h should have been a constant as the height of the tower is constant. I have now corrected the code:
To anyone having hard time solving #4, apply this lesson: "1.10b — How to design your first programs"
From what I understand we could use const for every variable and parameters in both question, why aren’t we doing it? For example in question 3 we know x, y and op won’t change because we only ask for one operation, shouldn’t we use const there? and for the function calculateHeight() shouldn’t we use const for the parameters since initialHeight and seconds won’t change in the function?
You totally could. It’s more correct to make all of these const than not, since technically they are const and this helps enlist the compiler’s help in ensuring the function doesn’t accidentally change the parameter values.
However, because this is of such minor benefit, it’s extremely common for people not to make parameters passed by value const. It’s a good habit to get into, but if you’re not in the habit, your energy and focus may be better applied elsewhere.
Hey Alex.
I don’t have trouble completing question 3, but there’s something I don’t get.
It says "The user is asked to enter 2 floating point numbers (use doubles)" but then in your example, the user enters 5 and 7, which aren’t floating point numbers. Why?
Uuh, eer… I’m not sure. I updated the example to use at least one floating point number. Thanks for pointing out the oddness.
I just feel like such a complete moron. Couldn’t figure out the last question to save my life, and after reading the solution and trying to puzzle it out, my brain just turned to clay. Guess programming just isn’t for me after all. If I can’t comprehend something that everyone else can do so easily, there’s really no point.
Who says it’s easy for everyone else? If you can’t figure something out, you have a couple of options:
1) Come back later when you’re rested any try again.
2) Ask someone to explain it.
3) Move on, then come back later, and something else you’ve learned may have caused it to click.
Getting stuck is frustrating, no doubt, but I wouldn’t give up based on getting stuck once. Only if you’re consistently and regularly struggling, you might then consider your other options.
Hi,
I’ve tried question 3 by myself first, and it’s not clean or the best, because I didn’t separate my functions, but in any case it should work and it does for ‘+’ but not for ‘/’…. the error is that "Run-Time Check Failure #3 - The variable ‘answer’ is being used without being initialized."
How come? I’ve tried to debug it with a watch on ‘answer’ variable but couldn’t see where I’m wrong…
Thanks!
An if statement can only have one statement after it. You have two. To make your program work, you need to put your statements in curly braces, like this:
For question 2 part f, why not use int32_t instead of long? In the question, you state that "If the answer is an integer, pick either int or a a [typo btw] specific fixed-width integer type."
I’ve updated the quiz question to indicate long is okay too. A specific fixed width type isn’t necessary here, since long is guaranteed to be 4 bytes (holding a maximum value of just above 2 billion), which is more than enough to hold the value.
Isn’t your formula wrong? The order of operations would have the exponents handled first, so seconds * seconds should be in its own set of parentheses.
It’s not wrong -- seconds * seconds being evaluated first doesn’t change the result. However, it does make the code slightly more clear to understand, and it’s useful for that reason.
Hey Alex! I was looking ahead and used a while loop for my answer to question 4. The weird thing is my constants.h file won’t work for the gravity constant anymore. Here’s all the code.
The constants.h file
And the .cpp file
Also I realize that in the constants.h file there wasn’t a space between #define and CONSTANTS_H. I fixed that but it still doesn’t work. When I put in myConstants::gravity it says “name followed by ‘::’ must be a class or namespace name.
Your constants.h header guard is wrong -- it should be #ifndef, not #ifdef
Thanks Alex! Haha, I had a feeling it was something small like that.
well everyone else seems to have posted their code.
here is mine =P .
Thanks Alex. you’re a great teacher.
stuff in the constants.h was too simple and short to post.
Hello Alex! Could you check my code for question 4 please? it is quite shorter than yours, but results are the same.
constants.h:
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace myConstants
{
const double gravity(9.8); // m/s^2 gravity value
}
#endif
main.cpp
#include "stdafx.h"
#include<iostream>
#include "constants.h"
double heightOfTower() // getting the height of tower
{
std::cout << "Enter the initial height of the tower in meters: ";
double x;
std::cin>> x;
return x;
}
void printHeightOfBall(int sec,double towerHeight)
{
double y;
y = towerHeight-(myConstants::gravity*(sec*sec) / 2);
if (y>0.0)
std::cout << "At " << sec << " seconds, the ball is at height : " << y << "meters" << ‘n’;
else std::cout << "At " << sec << " the ball is on the ground" << ‘n’;
}
int main()
{
const double towerHeight = heightOfTower();
printHeightOfBall(0, towerHeight);
printHeightOfBall(1, towerHeight);
printHeightOfBall(2, towerHeight);
printHeightOfBall(3, towerHeight);
printHeightOfBall(4, towerHeight);
printHeightOfBall(5, towerHeight);
return 0;
}
Seems fine, though you could initialize y instead of assigning a value to it.
2.4a says "int should be preferred when the size of the integer doesn’t matter. For example, if you’re asking the user to enter their age, or counting from 1 to 10, it doesn’t matter whether int is 16 or 32 bits (the numbers will fit either way). This will cover the vast majority of the cases you’re likely to run across."
The quick review says "Use fixed-width integers instead of the variable size integers", and the #2 quiz solution specifically says to store someone’s age as int16_t .
Feels pretty inconsistent and somewhat confusing tbh, had to double-check that I read 2.4a right
Thanks for bringing this up. I updated the recommendations in the fixed-width integers article based on excellent user feedback, and neglected to update them here as well. This article has now been updated.
this one works too..
This is the "complete" version of the question 4 ,right?
I still feel that I can improve something though…
double distance_fallen(double x, double y)
{
double distance_fallen;
distance_fallen = x * y * y / 2;
return distance_fallen;
}
int main()
{
//heightOfTower();
std::cout << "please enter the height of the tower in meters: " ;
double z;
std::cin >> z;
std::cout << "At 0 seconds, the ball is at height " << z - distance_fallen(gravity, 0) << std::endl;
//
std::cout << "At 1 seconds, the ball is at height " << z - distance_fallen(gravity, 1) << std::endl;
//
std::cout << "At 2 seconds, the ball is at height " << z - distance_fallen(gravity, 2) << std::endl;
//
std::cout << "At 3 seconds, the ball is at height " << z - distance_fallen(gravity, 3) << std::endl;
//
std::cout << "At 4 seconds, the ball is at height " << z - distance_fallen(gravity, 4) << std::endl;
//
std::cout << "At 5 seconds, the ball is at the ground " << std::endl;
//std::cout << "At 5 seconds, the ball is at the ground " << z - distance_fallen(gravity, 5) << std::endl;
return 0;
}
HEY ALEX!
ANSWER OF QUESTION NO.3
IS CAN BE LIKE THIS
IT IS RIGHT
YOUR ANSWER WAS TOO LONG
THAN MINE.
/
#include<iostream>
using namespace std;
int main()
{
double a;
double b;
cout << "enter a double value: ";
cin >> a;
cout <<"enter a double value: ";
cin >>b;
cout <<endl<<"Enter one of the following: +, -, *, or /: ";
char x;
cin >> x;
if(x==’+’)
cout<< a+b;
if(x==’-‘)
cout<<a-b;
if(x==’*’)
cout<< a*b;
if(x==’/’)
cout<<a/b;
}
It can (because this program is so simple) but you’re not really exercising what you’ve learned if you do it this way.
Ok thanks i will try to what i had learn
I will go ahead and share mine here. 🙂
I will have to admit, I struggled with the gravity part, so I stole the code for that because I’m rusty on my physics!
I’m normally a Java/C# developer with experience in Unity, but I want to try out Unreal Engine so I’m using this fantastic guide to brush up on my C++! Thank you so much for all your hard work and love for helping people and this language.
Constants.h
Main.cpp
Drop.cpp
Question 4 is basically like:
In school: what is 1 + 2?
On exam: calculate the speed at which the earth is orbiting the sun
Is it ok to have a function call itself as below, or am I asking for trouble? Also, is there anyway to include more than one statement after “else”?
I used the same method on the second question as well. Is updateHeight() doing too much in my solution?
Seems okay to me. You even have a reasonable base case to ensure it terminates properly.
You need to be really careful when having a function call itself. This is called recursion, and I talk about recursion more in chapter 7. For now, you should avoid it.
You can associate multiple statements with an if or else by putting them inside a block ({ }). e.g.
Awesome! Thank you very much for the tutorial and help.
Hey, can you help me with this?
I’m having a problem with this code whenever I have a number that is below 0 for the variable hf. For example, when I enter 400 for h and 400 for s, the debugger shows hf as 784000, so I never get hf to be less than or equal to 0…
hf is telling you how far the ball moved from the initial position, which will always be a positive number.
#include <iostream>
#include "constants.h"
using namespace std;
void func(int trent)
{
double distance;
for (int i = 0; i <= 5; i++)
{
distance = (double)(myconstants::g/2)*i*i;
if ((trent - distance) < 0)
{
cout << "Hited the ground" << endl;
}
else
{
cout << "The distance at " << i << " seconds is: " << trent - distance << endl;
}
}
}
int main() {
cout << "Enter a height of the tower: ";
int height;
cin >> height;
func(height);
}
I did this with a for loop.
Well since I like to complicate there goes my solution ><
Btw your guide is the best I’ve seen ever, seriously good job covering the parts that makes one go like wtf is that?!
Thank you for this content!
Extending program and making them more complicated is a great way to learn. Keep it up!
#pragma once
#ifndef CONSTANTS_H
#define CONSTANTS_H
namespace constants
{
const double gravity(9.8);
PCH Warning: header stop cannot be in a macro or #if block // I received this error when trying to make
a namespace to have the symbolic constant. pragma once was a suggested solution, but I would like to know
why the problem occurs and what the best solution is.
#endif
What compiler are you using? Some older versions of Visual Studio have a bug with this.
I am using Visual Studios 2010.
I think that’s one of the versions that had that bug. Upgrade to a newer version.
Name (required)
Website | http://www.learncpp.com/cpp-tutorial/210-comprehensive-quiz/comment-page-6/ | CC-MAIN-2018-05 | refinedweb | 2,749 | 72.05 |
19 February 2010 16:06 [Source: ICIS news]
TORONTO (ICIS news)--Honeywell is confident that it will perform well this year as economies recover, the diversified global technology company said on Friday as it affirmred its 2010 sales target of around $31.3bn-$32.2bn (€22.8bn-€23.5bn).
"The outlook for Honeywell is bright," said CEO Dave Cote.
"We performed well in the last recovery, well in the recession and will perform even better in this recovery,” he said.
Honeywell's 2010 outlook compares with its sales performance of $30.9bn in 2009 and $36.5bn in 2008.
For the 2010 first quarter ending on 31 March, sales were expected to come in at around $7.2bn-$7.6bn, Honeywell said. This compares with sales of $8.1bn Honeywell recorded in the recent 2009 fourth quarter.
?xml:namespace>
Honeywell’s range of chemical products includes ammonium nitrate, chemical intermediates such as caprolactam, as well as nylon 6 advanced fibres and refrigerants, among others.
In addition to chemicals and specialty materials, Honeywell is focused on aerospace, automation and control and transportation systems.
($1 = €0.73) | http://www.icis.com/Articles/2010/02/19/9336398/honeywell-bullish-on-2010-outlook-affirms-targets.html | CC-MAIN-2014-42 | refinedweb | 185 | 57.37 |
Eric has developed everything from data reduction software for particle bombardment experiments to software for travel agencies. He can be contacted at [email protected] comcast.net.
From the 1970s to 2004, microprocessor execution speed increased at an amazing ratefrom kilohertz to megahertz to gigahertz. But starting in 2004, CPU speeds have been increasing at a much slower pace. The main speed bumps are power and heat. Faster clock rates require more power, extra power creates more heat, and keeping the CPU from melting requires increasingly elaborate and expensive cooling mechanisms. CPU manufacturers are shifting their focus from increasing clock rates to improving the performance of multithreaded code. For instance, Intel's HyperThreading technology lets an individual Pentium 4 CPU appear as two CPUs to Windows XP and other operating systems. Although a HyperThreaded CPU is still a single processor, HyperThreading can speed up multithreaded code up to 25 percent. Intel, AMD, and other manufacturers are also shipping multicore CPUs, which are simply multiple CPUs on the same chip. Multithreading is often the only way to achieve maximum performance from parallel CPU architectures. In this article, I show how to reliably multithread .NET applications. I include File Search (available electronically; see "Resource Center," page 3), which I wrote to examine .NET multithreading. File Search was developed and tested with Visual Studio 2003/.NET 1.1 and Visual C# Express 2005/.NET 2.0 beta 2.
.NET provides two main threading mechanismsthe Thread class and asynchronous methods. Listing One shows how to explicitly manage threads. In the Main method, two Thread objects are instantiated with ThreadStart delegates as constructor parameters. When their Start methods are called, the methods pointed to by the ThreadStart delegates start running. These methods, HelloWorld1 and HelloWorld2, must be void and take no parameters. Calling the Join methods causes the program to block until the methods finish. The program exits after both HelloWorld1 and HelloWorld2 have finished. If the Join statements were removed, the program would still wait for the threads to complete because thread1 and thread2 are foreground threads. If the threads were changed to be background threads (by setting the IsBackground property to True), and if the Join statements were removed, the program would exit before the threads finished running. Thread objects are easy to configure. For example, you can change a thread's priority by assigning a new value to its Priority property.
Unlike Threads, asynchronous method calls (Listing Two) can have parameters. In the Main method workDelegate refers to a method (Work) that takes a string parameter. Each workDelegate.BeginInvoke call returns immediately. After each BeginInvoke call, the Work method is run on its own background thread. BeginInvoke returns an IAsyncResult object. The IAsyncResult.AsyncWaitHandle object can be used to block until the method returns. The WaitHandle.WaitAll method waits until both asynchronous method calls have finished. Asynchronous methods run on threads managed by the ThreadPool class. The ThreadPool class maintains a set of worker threads (25 per CPU, 50 per Hyperthreaded CPU), and creates and destroys threads as necessary. Asynchronous methods don't let you directly manipulate the threads running the methods, but an asynchronous method can manipulate its thread once it's running, by accessing Thread.CurrentThread.
I decided to use asynchronous methods in File Search rather than explicit Thread objects because asynchronous methods can be parameterized. File Search (Figure 1) uses asynchronous methods to simultaneously search multiple drives. For example, if the user searches the C: and F: drives in parallel, one asynchronous method searches the C:\ drive, another searches F:\.
To install File Search, navigate to the Setup folder and double-click filesearch.zip. If you use WinZip, you can automatically install by clicking the Install toolbar button. Otherwise, you may need to extract the .zip file to a hard disk folder and run setup.exe. To build File Search, extract the source code to a hard disk folder and load the .sln file into Visual Studio. After you've installed or built File Search, run it. Select the Settings! menu item. The number of CPUs on your system is displayed. HyperThreaded CPUs count as 2. Make sure that the Multithreaded search checkbox is checked, then press OK. Enter the file types to search, and optional search text. Select the Text or Regular Expression radio button. Then specify the drives to search by checking the drive letter checkboxes. Click the Browse button to specify individual folders and network drives. Then click the Search Now button. When the search begins, the Results tab automatically displays (Figure 2). Click a file in the ListView to display its contents and search for specific text. Notice the 4 and 5 on the right of the status bar. The number to the left, 4, is the number of completed asynchronous method calls. The number to the right, 5, is the total number of asynchronous method calls.
Asynchronous Method Call Lifecycle
When you click the Search Now button the Search.SearchAllFolders method is called (Listing Three). The actual searches are performed by the SearchFolders method. The SearchFoldersDelegate variable is used to call SearchFolders asynchronously. The AsyncCallback delegate points to the SearchCallback method. SearchCallback is automatically called each time an asynchronous method finishes running. The SearchFoldersDelegate.BeginInvoke calls return immediately. After the BeginInvoke calls have been made, the SearchFolders method is called from a pooled thread. If a pooled thread is available, it is used; otherwise, a new thread is created and added to the pool.
The call to CreateDriveHashtable creates a Hashtable with a key for each drive being searched. The value corresponding to each key is an ArrayList of the folders in the drive to search. Once the Hashtable has been created, it's used to call the asynchronous methods. For each key (drive) in the Hashtable, the SearchFolders method is called asynchronously with an array of folders to search. Because each drive is searched by only one asynchronous method, searching the drive will not slow down due to thrashing. The last parameter (drive) in the BeginInvoke call is automatically sent to the SearchCallback method after the method finishes. It is available via the IAsyncResult.AsyncState property.
SearchFolders calls FileUtils.GetFiles to navigate through folders and search for files. As GetFiles runs, it periodically checks the SearchInfo.Cancelled property. If users press the Stop Search button, the Cancelled property is set to True and GetFiles returns. The thread running GetFiles could be terminated by calling Thread.Abort, but I don't recommend it. Thread.Abort attempts to terminate a thread by throwing a ThreadAbortException. This is a dangerous thing to do without knowing exactly where the thread is in its processing. Additionally, calling Abort on a suspended thread deadlocks the thread and the application.
When SearchFolders returns, the SearchCallback method is automatically called (Listing Four). The SearchInfo.remainingSearches counter is decremented because one of the parallel searches has just finished. SearchCallback needs to update the status bar and the progress bar, but it must not directly call MainForm.UpdateStatusBar and MainForm.UpdateProgressBar. Manipulating GUI components derived from the Control class (forms, labels, status bars, progress bars, and the like) must only be done on the GUI thread that created the component. Because SearchCallback is called from a different worker thread, the MainForm methods are called indirectly by the Control.Invoke method (the Form class is derived from Control). Control.Invoke takes two parameters, a delegate to the method being called, and an object array containing the method's parameters. Control.Invoke calls the method on the thread that created the Control. Visual Studio 2003's debugger does not notify you when your code manipulates Controls in a worker thread unless you put Debug.Assert(!InvokeRequired); statements in GUI code that is callable by worker threads. However, Visual Studio 2005's debugger automatically reports these threading bugs.
Race Conditions and Synchronization
In multithreaded applications, variables can be accessed and updated simultaneously by multiple threads. This can cause race conditions (timing-dependent bugs) and data corruption issues that are notoriously difficult to debug. For example, consider the UnsafeCounter property:
private int unsafeCounter;
public int UnsafeCounter
{
[MethodImpl(MethodImplOptions.
Synchronized)]
get { return unsafeCounter; }
[MethodImpl(MethodImplOptions
.Synchronized)]
set { unsafeCounter = value; }
}
The Synchronized attribute ensures that the get and set methods are only called by one thread at a time. This prevents one thread from assigning a value at the same time that another thread is reading it. But this is not sufficient to avoid a race condition. When a thread executes the UnsafeCounter++ statement, these native CPU instructions are executed:
// UnsafeCounter++;
mov esi,ebx
mov ecx,ebx
// Call the get method
call dword ptr ds:[0BFF63D8h]
mov edi,eax
// Increment value
inc edi
mov edx,edi
mov ecx,esi
// Call the set method to store the result
call FFB91C23
Consider what happens if the UnsafeCounter has a value of 0 and two threads are about to increment the counter with the ++ operator. Here's one possible outcome:
- Thread 1 calls the get method, retrieves value (0).
- Thread 1 increments the value to 1.
The operating system switches to Thread 2.
- Thread 2 calls the get method, retrieves value (0).
- Thread 2 increments the value to 1.
- Thread 2 calls the set method to store result (1).
The operating system switches back to Thread 2.
- Thread 1 calls the set method to store result (1).
In this case, the counter started with a value of 0, was incremented twice, and ended up with an incorrect value of 1. And this is only one of many erroneous outcomes that could be caused by the race condition.
I wrote a ThreadSafeCounter class to prevent this race condition (Listing Five). The ThreadSafeCounter class uses the Interlocked class to increment and decrement counters atomically. It also uses the Synchronized attribute to ensure that the get and set methods are not called by multiple threads simultaneously. The ThreadSafeCounter is limited to 32-bit integer values. .NET 2.0 lets the Interlocked class manipulate 64-bit integers, but this can cause race conditions on 32-bit CPUs. The Interlocked class is ideal for synchronizing access to integers. The lock statement is a more general-purpose synchronization mechanism:
lock ( {expression} )
{
{statements}
}
The lock statement waits until no other thread is holding a lock on the expression. Then the expression is locked and the statements are executed. After the statements are finished, the lock is released and another thread can acquire a lock on the expression. The expression must be a reference type. Typically code locks on this to lock an entire object. To acquire locks in a static method, use the typeof operator to lock on the method's class. See the lock statement in updateStaticMembers below:
public class LockDemo
{
int w, x;
static int y, z;
public void updateMembers()
{
lock(this)
{
w = w * 2; x = w * 4;
}
}
public static void updateStaticMembers()
{
lock (typeof(LockDemo))
{
y = 33; z = z * 2 + y;
}
}
}
Applications must synchronize access to any variable that can potentially be accessed by multiple threads. The Interlocked class is a high-performance option for integer variables. The lock mechanism and Monitor class are slower than the Interlocked class, but they can synchronize access to any type, not just integers.
Performance
One of the main reasons for developing a multithreaded application is to improve performance. But even multithreaded apps can have performance problems. For example, creating too many threads can slow down an application. Every thread uses memory to store its stack and other state information. And it takes time for the operating system to context switch from one thread to a different thread. More threads mean more memory consumption and more context switches. For some applications you may want to make the number of threads proportional to the number of available CPUs. The NUMBER_OF_PROCESSORS environment variable specifies the number of CPUs (HyperThreaded processors count as 2). You can access this variable programmatically, see SettingsForm.cs (available electronically) for the details.
The Synchronized attribute is a convenient way to make an entire method mutually exclusive, but if only a subset of the method's code requires mutual exclusion, it's better to put only that subset in one or more lock statements. Make sure each lock is held only as long as necessary. You can use Monitor.TryEnter method to acquire a lock only if it's available:
if (Monitor.TryEnter(this))
{
lock(this)
{
}
}
This works because the lock uses the Monitor class internally. The lock statement calls Monitor.Enter before executing the statements in its body, and calls Monitor.Exit after the statements have been executed. Another way to reduce lock contention is to use the [ThreadStatic] attribute. When the [ThreadStatic] attribute is placed above a member variable, a separate instance of that variable is available to each thread. If synchronizing a member variable is slowing your application down, you may be able to mark it as [ThreadStatic] and remove the synchronization. For example, File Search's asynchronous method uses a Regex member variable for regular expression searching. The member variable, FileUtils.regularExpression, is marked as [ThreadStatic] so there's no need to synchronize it.
Run perfmon to determine if your app is slowing down due to lock contention. Press the + toolbar button and select the .NET CLR LocksAndThreads performance object. Select the All Counters and Select Instances From List radio buttons. Highlight your program in the listbox and press Add and Close. Click on the View Report toolbar button and monitor the Contention Rate/sec and Total # of Contentions counters.
Searching files for text is I/O-bound rather than CPU-bound. Consequently, searching multiple drives with simultaneously executing asynchronous methods is a major performance enhancement. For example, when I searched two local drives and four network shares, the multithreaded search was about 3.7 times faster than the single-threaded search. This dramatic speedup is not surprising. While one thread is blocked waiting for file I/O, another thread can search for text. Multithreading a CPU-bound program typically results in a more modest speedup.
Debugging and Testing Multithreaded Apps
Debugging a multithreaded application full of race conditions is a nightmare. Here are some testing tips to make testing more effective and reduce the likelihood of race conditions. If you're developing a Windows Forms application, test it with the Visual Studio 2005 debugger. Unlike previous versions, the 2005 debugger automatically detects when a control is manipulated by a worker thread. Unit testing software like NUnit is extremely useful for multithreaded code. NUnit (Figure 3) is able to detect the multithreaded increment bug mentioned earlier. To see NUnit in action, download it from. Run the NUnit-Gui program. Select File/Open and open the FileSearchNUnitTests.nunit project file from the FileSearchNUnitTests project. Press Run and NUnit detects the race condition if it happens during the test run. NUnit test cases are synchronous. If you call asynchronous methods in NUnit, use WaitHandle.WaitAll to force the test case to wait for the asynchronous methods to complete. If your code uses Thread objects, force the test code to wait by calling Thread.Join. See NUnitTests.cs (available electronically) for sample multithreaded NUnit test cases.
It's worthwhile to test on a variety of machines with different performance characteristics. Some race conditions only show up on true multiprocessor machines. If your customers will be running your software on multicore or SMP machines, your test matrix needs to include multiprocessor machines.
Conclusion
Moore's Law hasn't been repealed. CPU manufacturers are still able to double the transistor count on a given area of silicon every 18 months or so. What has changed is the rate at which the performance of single-threaded applications can be improved. For at least the next few years, single-threaded applications will not speed up dramatically as customers upgrade their machines. But multithreaded applications will speed up if they take advantage of the parallel processing capabilities of newer HyperThreaded and multicore CPUs. Perhaps in the future, compilers will automatically parallelize .NET code and distribute processing across multiple CPUs. But for now, multithreading is the way to harness the parallelism of today's computers. Asynchronous method calls are a convenient way to call parameterized methods on multiple threads. Just be sure to synchronize access to variables. Debug your Windows Forms code with Visual Studio 2005 and you'll automatically find Windows Forms threading bugs. Finally, put NUnit to work testing your multithreaded code. Detecting any bugs, especially threading issues, during unit testing is much less expensive than finding them later in the development process or at a customer's site.
DDJ
class ThreadTest { const int iterations = 100; public void HelloWorld1() { for (int i = 1; i <= iterations; i++) { Console.WriteLine("Hello World1 {0}", i); } Console.WriteLine("\nHello World1 finished\n"); } public void HelloWorld2() { for (int i = 1; i <= iterations; i++) { Console.WriteLine("Hello World2 {0}", i); } Console.WriteLine("\nHello World2 finished\n"); } [STAThread] static void Main(string[] args) { ThreadTest threadTest = new ThreadTest(); // Create the threads. The ThreadStart delegate must // refer to a void method with no parameters. Thread thread1 = new Thread(new ThreadStart(threadTest.HelloWorld1)); Thread thread2 = new Thread(new ThreadStart(threadTest.HelloWorld2)); // Start the threads. thread1.Start(); thread2.Start(); // Wait for threads to complete. Doesn't matter which thread finishes first. thread1.Join(); thread2.Join(); Console.WriteLine("Main finished"); } }Back to article
Listing Two
class AsynchMethodTest { const int iterations = 100; private delegate void WorkDelegate(string message); private void Work(string message) { for (int i = 1; i <= iterations; i++) { Console.WriteLine(message + " " + i); } Console.WriteLine("\n" + message + " finished\n"); } static void Main(string[] args) { AsynchMethodTest test = new AsynchMethodTest(); WorkDelegate workDelegate = new WorkDelegate(test.Work); WaitHandle[] waitHandles = new WaitHandle[2]; waitHandles[0] = workDelegate.BeginInvoke("Hello World1", null, null).AsyncWaitHandle; waitHandles[1] = workDelegate.BeginInvoke("Hello World2", null, null).AsyncWaitHandle; // Asynchrononous methods are run on background threads by default. // Wait for them to complete before letting the main thread exit. WaitHandle.WaitAll(waitHandles); Console.WriteLine("Main finished"); } }Back to article
Listing Three
public static void SearchAllFolders(string[] allFolders, string searchPattern, string containingText, bool regularExpression, bool caseSensitive) { SearchInfo.StartTime = DateTime.Now; SearchFoldersDelegate searchFoldersDelegate = new SearchFoldersDelegate(SearchFolders); AsyncCallback asyncCallback = new AsyncCallback(SearchCallback); SearchInfo.Cancelled = false; SearchInfo.InProgress = true; // If user requested a multithreaded search... if (SerializeConfiguration.Settings.MultithreadedSearch) { // Don't want to thrash hard drives and optical drives. // Ensure that each drive is only accessed by one thread. Hashtable drives = CreateDriveHashtable(allFolders); // Keep track of how many searches will be done. SearchInfo.totalSearches.Set(drives.Keys.Count); SearchInfo.remainingSearches.Set(drives.Keys.Count); // For each drive being searched... foreach (string drive in drives.Keys) { // Get the folders on the drive to be searched. ArrayList foldersArrayList = (ArrayList) drives[drive]; // Convert ArrayList of folders to a string array. string[] folders = (string[]) foldersArrayList.ToArray(typeof(string)); // Call the asynchronous method with all the search parameters. searchFoldersDelegate.BeginInvoke(folders, searchPattern, containingText, regularExpression,caseSensitive, asyncCallback, drive); } } else // If user requested a single-threaded search... { SearchInfo.totalSearches.Set(1); SearchInfo.remainingSearches.Set(1); searchFoldersDelegate.BeginInvoke(allFolders, searchPattern, containingText, regularExpression, caseSensitive, asyncCallback, "all folders"); } // It's OK to directly manipulate the status bar because // this method was called from the GUI thread. Globals.mainForm.UpdateStatusBar("Searching..."); }Back to article
Listing Four
delegate void UpdateStatusBarDelegate(String Text); ... delegate void UpdateProgressBarDelegate(); private static void SearchCallback(IAsyncResult asynchResult) { // One parallel search just completed, so decrement // the number of remaining searches. int remainingSearches = SearchInfo.remainingSearches.Decrement(); UpdateStatusBarDelegate USBD = new UpdateStatusBarDelegate(Globals.mainForm.UpdateStatusBar); // If the search was not cancelled... if (!SearchInfo.Cancelled) { string message = string.Format("Finished searching {0}", asynchResult.AsyncState); // Update the status bar with a progress message. Globals.mainForm.Invoke(USBD, new object[] { message } ); } // If the last asynchronous method finished searching... if (remainingSearches == 0) { TimeSpan elapsedTime = DateTime.Now - SearchInfo.StartTime; // Update status bar to display total search time. Globals.mainForm.Invoke(USBD, new object[] { SearchInfo.Cancelled ? "Search cancelled" : "Search completed." + " Elapsed time: " + elapsedTime.ToString() }); SearchInfo.InProgress = false; } // Update the progress bar. UpdateProgressBarDelegate UPD = new UpdateProgressBarDelegate(Globals.mainForm.UpdateProgressBar); // You don't need to pass an object array to Invoke when the // method (UpdateProgressBar) does not have any parameters. Globals.mainForm.Invoke(UPD); }Back to article
Listing Five
// A ThreadSafeCounter contains an integer value that can be read, written, // incremented and decremented from multiple threads without data corruption // issues caused by race conditions. public sealed class ThreadSafeCounter { private int intValue; public ThreadSafeCounter() { intValue = 0; } public ThreadSafeCounter(int intValue) { this.intValue = intValue; } [MethodImpl(MethodImplOptions.Synchronized)] public int Get() { return intValue; } [MethodImpl(MethodImplOptions.Synchronized)] public int Set(int newValue) { int result = intValue; intValue = newValue; return result; } public int Increment() { return Interlocked.Increment(ref intValue); } public int Decrement() { return Interlocked.Decrement(ref intValue); } }Back to article | http://www.drdobbs.com/windows/multithreading-net-apps-for-optimal-perf/184406245 | CC-MAIN-2018-51 | refinedweb | 3,423 | 50.43 |
by Oliver Nybroe
How to create an IntelliJ plugin — let’s build a simple dictionary finder
Most of us developers use IntelliJ platforms, either IDEA, PHPStorm, WebStorm, Android Studio, PyCharm and the list goes on and on. However sometimes when we use it, we find that a feature is missing, but we have no idea how to actually add that feature and eventually just live without it.
In this article I will cover how we can create a simple plugin for all of the IntelliJ IDEs so when you add a
project.dic file, it will automatically add it as one of your dictionaries. It will also search for the file in packages, so packages can add custom words to the dictionary. A
.dic file is a simple dictionary where each line is a word in the dictionary.
The project is just a sample to get you started on developing your own plugins. But it’s actually also a feature I have been missing, as when I develop a custom package with my own words in it, I hate that I have to add them each time in the project level dictionary.
Creating the project
When creating plugins for IntelliJ, we have to option to do it in either Java or Kotlin. I will do it in Java as most users are familiar with that. As this is a Java project, we will use IntelliJ IDEA as our IDE.
According to the development guide, the recommended way to create a project is by using Gradle. We start by opening up
preferences and check if
Gradle and
Plugin DevKit plugins are installed.
After installing the plugins and restarting the IDE, we go to the new projects flow and under
Gradle. In here there is now an option called
IntelliJ Platform Plugin which is the one we need.
Then go through the rest of the project creation flow as normal — in this project I choose the following configuration.
Setting up
plugin.xml
Now that we have a project, we have to setup our
plugin.xml file and
build.gradle. The
plugin.xml file is a file used by IntelliJ which defines all the information about the plugin. This includes the name, dependencies, what actions it should add or if it should extend something in IntelliJ. Basically this file defines everything your plugin should do and is the root of your project. In our
build.gradle file we can define some of the values from
plugin.xml, and information like which version of IntelliJ we want to test our plugin on when building with gradle.
Let’s start by defining our
plugin.xml file. You can find the file in
src/main/resources/META-INF/plugin.xml. We want our plugin to be available on all IntelliJ IDE’s so we set our
dependencies to
com.intellij.modules.lang. Right now our file looks like this:
<idea-plugin> <id>dk.lost_world.Dictionary</id> <name>Dictionary</name> <vendor email="[email protected]" url="">GitHub</vendor> <depends>com.intellij.modules.lang</depends></idea-plugin>
However right now this does not have any logic, and we do not register anything to the IntelliJ platform.
As this project will find
project.dic files inside a project and register them as dictionaries in that project, we will have to register a Project level component. This component will be called when a project is opened and closed. Let’s create a class and implement the
ProjectComponent interface. When we hover over the class name it tells us that the component is not registered.
We can then call the action called
Register Project Component and it will register it for us in the
plugin.xml file.
If we open
plugin.xml the following code should be added. If it wasn’t added when calling the action, then just add it manually.
<project-components> <component> <implementation-class>dk.lost_world.dictionary.DictionaryProjectComponent</implementation-class> </component></project-components>
IntelliJ Filesystem
When working with files in IntelliJ, we use a Virtual File System (VFS). The VFS gives us a universal API to talk with files, without us having to think about if they are from FTP, an HTTP server or just on the local disk.
As our plugin looks for files called
project.dic it will of course need to talk with the Virtual File System. All files in the VFS are Virtual Files. This can sound a little intimidating, but in reality it is just an API for a filesystem and for a file. The way to think about it is just that the Virtual File System is your file system interface and the Virtual Files are your files.
Spell Checker Settings
As IntelliJ already has support for
.dic files and spell checking in general, the only thing we need to do is register our
project.dic files in the spell checkers settings.
All the settings for the spell checker are saved in a class called
com.intellij.spellchecker.settings.SpellCheckerSettings. To get an instance of it, simply call the
getInstance method (most of the IntelliJ classes got a
getInstance method which uses IntelliJ’s
ServiceManager underneath).
The settings class got a method called
getCustomDictionariesPaths which returns all of the paths to dictionaries which are installed by the user.
When looking at the method signature, we also see an annotation called
AvailableSince. We will later use the value in this annotation to specify the minimum required version for our plugin to work.
As the method returns a list, we can simply call
add on the method to add in a new path to a dictionary.
Running Our Plugin (build.gradle)
As we now know how to add a dictionary to the spell checker, let’s add a small code example in our
DictionaryProjectComponent class for doing this.
public class DictionaryProjectComponent implements ProjectComponent { private Project project; public DictionaryProjectComponent(Project project) { this.project = project; } @Override public void projectOpened() { SpellCheckerSettings .getInstance(project) .getCustomDictionariesPaths() .add("./project.dic"); }}
This code will register a
project.dic file from the root of our project whenever the project is opened.
To test out our little example, we need to update our
build.gradle file. In the
intellij section of the gradle file we add in what version of IntelliJ we want to use. This version number is the one from the
AvailableSince annotation on the
SpellCheckerSettings class.
plugins { id 'java' id 'org.jetbrains.intellij' version '0.4.4'}group 'dk.lost_world'version '1.0-SNAPSHOT'sourceCompatibility = 1.8repositories { mavenCentral()}dependencies { testCompile group: 'junit', name: 'junit', version: '4.12'}// See { pluginName 'Dictionary' version '181.2784.17' type 'IC' downloadSources true}
Running the
runIde command from gradle will start up an instance of IntelliJ of the specific version. After starting up the testing IDE our plugin should have been run. If we open up
preferences > Editor > Spelling > Dictionaries we can see under custom dictionaries that the path we specified in our example is now added.
We are now able to test our plugin, so now it is time to build it out correctly so it finds the
project.dic files and registers them for us.
In the
DictionaryProjectComponent::projectOpened method, we need to first find all files called
project.dic and register them and also add a file listener so when new
project.dic files are added, they are registered automatically.
Dictionary Class
We will have a class called
Dictionary, this class will contain the logic for us to register and remove files from the dictionary. The class will have the following public methods:
void registerAndNotify(Collection<VirtualFile> files)
void registerAndNotify(VirtualFile file)
void removeAndNotify(VirtualFile file)
void moveAndNotify(VirtualFile oldFile, VirtualFile newFile)
These methods will also create a notification about what happened, so the end user knows what changed with the custom dictionaries. The end file for this will look the following way:
Finding all dictionary files
For finding all the dictionary files in the project called
project.dic we use the class
FilenameIndex. The file is in the namespace
com.intellij.psi.search.FilenameIndex, it has a method
getVirtualFilesByName which we can use to find our
project.dic files.
FilenameIndex.getVirtualFilesByName( project, "project.dic", false, GlobalSearchScope.allScope(project))
This call will return all Virtual Files which matches the search criteria. We then put the return result into the Dictionary class method
registerAndNotify.
@Overridepublic void projectOpened() { Dictionary dictionary = new Dictionary(project); dictionary.registerAndNotify( FilenameIndex.getVirtualFilesByName( project, "project.dic", false, GlobalSearchScope.allScope(project) ) );}
Our code is now able to find
project.dic files at start up and register them, if they are not already registered. It will also notify about the newly registered files.
Adding a Virtual File Listener
The next part is for us to listen for changes in virtual files. To do this we need a listener. For this we need the
com.intellij.openapi.vfs.VirtualFileListener.
In the docblock for the listener class we can see that to register it we can use
VirtualFilemanager#addVirtualFileListener.
Let’s create a class named
DictionaryFileListener and implement the methods which we need for our project.
Then we update our
projectOpened class to also add the
VirtualFileListener.
@Overridepublic void projectOpened() { Dictionary dictionary = new Dictionary(project); dictionary.registerAndNotify( FilenameIndex.getVirtualFilesByName( project, "project.dic", false, GlobalSearchScope.allScope(project) ) ); VirtualFileManager.getInstance().addVirtualFileListener( new DictionaryFileListener(dictionary) );}
Our plugin is now able to find our dictionary files at startup, but also listen for if a dictionary file is added later on. The next thing we need is to add information for our plugin listing.
Adding plugin information
To add information about the plugin, we open the
build.gradle file and edit the object
patchPluginXml. In here we need to specify which build version is required for the plugin, version of the plugin, description and change notes.
patchPluginXml { sinceBuild intellij.version untilBuild null version project.version pluginDescription """Plugin for having a shared dictionary for all members of your project. <br><br>It will automatically find any <code>project.dic</code> files and add themto the list of dictionaries. <br><br>It will also search packages for dictionary files and add them to our list of dictionaries. """ changeNotes """<p>0.2</p><ul> <li>Added support for listening for when a <code>project.dic</code> file is added, moved, deleted, copied.</li></ul><p>0.1</p><ul> <li>First edition of the plugin.</li></ul> """}
We also update the
version property to
'0.2'of the gradle project itself. The plugin can now run on all versions since the method for registering custom dictionaries was added.
To test if it generates the desired output, we can run the gradle task
patchPluginXml and under
build/patchedPluginXmlFiles our generated
plugin.xml file will be there.
Since IntelliJ version
2019.1, all plugins supports icons. As this is fairly new a lot of plugins do not have an icon, and your plugin can stand out a lot by having one. The naming convention is
pluginIcon.svg as the default icon and
pluginIcon_dark.svg for the darcula theme.
The plugin icons should be listed together with the
plugin.xml file in the path
resources/META-INF.
Building for distribution
The plugin is now ready to be built and shipped. To do this we run the gradle task
buildPlugin. Under
build/distributions a zip file will appear which you can distribute and install manually in your IDE. Add this zip file as a release under your github repo, so users have the option to download it manually from you repo.
Publishing a plugin
To publish our plugin so it can be downloaded directly from IntelliJ’s plugin repository, we need to login on our JetBrains account on the Plugin Repository website. When in here, a dropdown from your profile name shows an option to upload a plugin.
Input all the information in the dialog (you have to add a license, but that is pretty straightforward with Github). Here we add the distribution zip file.
When you submit the form, you can now see your plugin in the plugin repository. However other users do not have access to it before IntelliJ has approved it. Approving your plugin normally takes 2–3 days.
Updating your plugin via Gradle
After the plugin has been created, we can update it programmatically. To do this the best practice is to create a token. Open up jetbrains hub and go to the authentification tab. From here press
New token... and add the scope
Plugin Repository.
When pressing create you get a token. Create a file called
gradle.properties and add the token under the key
intellijPublishToken (remember to git ignore this file).
In our
build.gradle file, we simply add the following:
publishPlugin { token intellijPublishToken}
And we can now run the gradle task
publishPlugin for publishing our new version. All versions numbers have to be unique or else it will fail updating. When an update is created, you have to wait 2–3 days again for them to approve the update.
After waiting some days our plugin has now been approved and can now be found in the plugin marketplace by searching for dictionary!
Conclusion
I hope this article has given you more courage to start developing your own plugins. One of the biggest problems I had while developing it was to find out which classes to use. IntelliJ has an extensive guide which I would recommend that you read from start to end, however a lot of classes are not mentioned in there. In cases where you get stuck, they have a Gitter chat which is really helpful and there are people from IntelliJ on there to help also.
The source code for this project can be found on Github and the plugin we created is in the JetBrains marketplace. | https://www.freecodecamp.org/news/how-to-create-an-intellij-plugin-lets-build-a-simple-dictionary-finder-6c5192b449c/ | CC-MAIN-2019-43 | refinedweb | 2,279 | 57.98 |
While a lot of effort has gone into making it difficult or impossible to crash the Python interpreter in normal usage, there are lots fairly easy ways to crash the interpreter. The BDFL pronounced recently on the python-dev mailing list:
I'm not saying it's uncrashable. I'm saying that if you crash it, it's a bug unless proven harebrained.
I thought it might be worthwhile to document some ways the interpreter can be crashed -- although most of these are very unlikely to crop up in real code.
There is also a directory in SVN repository that demonstrates known ways to crash Python.
ctypes
def crash(): '''\ crash the Python interpreter... ''' i = ctypes.c_char('a') j = ctypes.pointer(i) c = 0 while 1: j[c] = 'a' c += 1 j
Bogus Input
Through Python 2.4 you could crash the interpreter by redirecting stdin from a directory:
% python2.4 -c 'import sys ; print sys.version' 2.4.1 (#3, Jul 28 2005, 22:08:40) [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] % python2.4 < . Bus error
Starting with 2.5 the interpreter notices and aborts:
% python2.5 -c 'import sys ; print sys.version' 2.5a0 (41847M, Dec 29 2005, 22:21:03) [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] % python2.5 < . Fatal Python error: <stdin> is a directory Abort trap
Some modules also do not perform rigorous checking of data they operate on. The marshal module can cause it to crash the interpreter when given certain strings:
$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import os, marshal >>> while 1: ... try: ... marshal.loads(os.urandom(16)) ... except: ... pass ... Segmentation fault
Executing random code, since the interpreter does not verify the well-formed-ness of the code object (invalids opcodes, wrong stack size, etc.). The following code is known to crashing python 2.4.3 on Windows XP as well as on Linux.
from types import CodeType as code exec code(0, 5, 8, 0, "hello moshe", (), (), (), "", "", 0, "")
Exhausting Resources
There are a number of areas where resource exhaustion can crash the interpreter. Here's one fairly easy to demonstrate way to do it though:
% python Python 2.5a0 (41847M, Dec 29 2005, 22:21:03) [GCC 3.3 20030304 (Apple Computer, Inc. build 1671)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> import sys >>> sys.setrecursionlimit(1<<30) >>> f = lambda f:f(f) >>> f(f) Segmentation fault
A slightly subtler example involves getting the interpreter to exhaust some resource internally while performing a single operation:
$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> f = lambda: None >>> for i in xrange(1000000): ... f = f.__call__ ... >>> del f Segmentation fault
GC/weakref interaction
Interaction between these two systems has historically been a sticky point for CPython. There is still at least one problem in Python 2.4.2:
$ python Python 2.4.2 (#2, Sep 30 2005, 21:19:01) [GCC 4.0.2 20050808 (prerelease) (Ubuntu 4.0.1-4ubuntu8)] on linux2 Type "help", "copyright", "credits" or "license" for more information. >>> import weakref >>> ref = None >>> class Target: ... def __del__(self): ... global ref ... ref = weakref.ref(self) ... >>> def g(): ... w = Target() ... w = None ... print ref() ... >>> g() Segmentation fault
Dangerous Modules
Some modules are designed to allow programmers access to the guts of things. Naturally, they also give programmers the opportunity to shoot themselves in the foot. Here are a few.
The new module allows you to construct various types of objects that normally can't be explicitly created from the interpreter. You can, for example, create code objects and give them arbitrary strings as their "bytecode". There's no telling how successfully the interpreter will handle such abuses.
The dl module is available on many Unix systems. It provides an interpreter-level interface to the dlopen() function, giving you dynamic access to the functions in arbitrary shared libraries. No checks are performed on the arguments to the functions you call. Hilarity can thus ensue. (The ctypes module, under consideration for inclusion in Python 2.5, provides similar functionality.)
The buffer builtin can also be dangerous, since it notionally claims a reference to a range of memory, but does so without going through a Python object or using the standard Python refcount system. This is visible when, for example, constructing a buffer from an array.array, then resizing the array such that it internally realloc()s its storage, moving the memory in the process. The buffer will now refer to an invalid pointer.
The gc module can be manipulated to give access to partially constructed object, accessing fields of which can cause crashes.
I`ve got another way:
I have written a Tkinter GUI editor [called "GWiz"] to help me create and maintain Tk GUIs for my own projects. [The editor itself is a GWiz project, too.] On several occasions, I have forgotten to close the GWiz-created GUI before exiting I.D.L.E., and Python [always?] crashes on exit with an "application requested an abnormal termination" error requester. When I remember to close my app before closing I.D.L.E., everything goes away cleanly. I should add code to GWiz to do sys.atexit() clean-up, but I do not know how to UNregister atexit callbacks; it would be easy enough to fix, but it would require that the atexit module`s call-back registration return the item added to the call-back list, and the addition of another function to remove items from the call-back list. I can post modifications to the library module, if someone will tell me where to post them.
python2.5 -c 'lambda((x)): x'
Also causes segmentation fault on some systems (Archlinux, MacOSX, Windows)
-- glen_quagmire
EditText (last edited 2009-01-28 00:00:11 by PoorYorick) | http://wiki.python.org/moin/CrashingPython | crawl-002 | refinedweb | 1,013 | 67.55 |
A UI widget subject functionality. More...
#include <SubjectiveUserWidget.h>
A UI widget subject functionality.
Called when the subject handle is despawned.
This method should basically self-destruct the subjective or finalize it somehow.
This method should never fail or raise any assertions.
If the self-destruction is not possible or not available for the subjective class, just silently exit the routine.
By default the top-level implementation of the method calls the respective blueprint event and exits silently.
Reimplemented from ISubjective.
The list of details.
The flagmark of the subjective.
An optional preferred belt for the subject to be placed in.
The list of traits. | https://turbanov.ru/toolworks/apparatus/docs/api/class_u_subjective_user_widget.html | CC-MAIN-2022-21 | refinedweb | 105 | 54.49 |
Most people would return Bools as follows:
bananas(color) { return (color = "yellow") }
and not as literal expressions; that is, not this way:
bananas(color) { if (color = "yellow") return true else return false }
However, in the discussion at wiki.c2.com Jim Perry said that if a method involve complex logic, the latter approach might be better.
In more realistic contexts the coder might well anticipate that the
isBiggermethod might eventually involve more complex logic than a simple compare of two variables.
Could you provide an example of what he talked about?
The only thing which came to my mind is something like this:
somefunction(...) { // you need to read the whole line to figure out // that the return value is Bool. // But it won't take much time (about 2 seconds, I suppose), // and so I don't think this is what Jim mean. return (var1 = "foo" && var2 = "bar" && var3 > var4) }
somefunction(...) { // you don't need to read the whole line to figure out // that the return value is Bool. if (var1 = "foo" && var2 = "bar" && var3 > var4) return true else return false }
| https://proxies-free.com/coding-style-the-cases-where-returning-bools-as-literal-expressions-is-a-better-option/ | CC-MAIN-2020-40 | refinedweb | 181 | 70.73 |
Simple video player in QML
Introduction
Video playing is one of the most important requirement now a days in applications, be it playing a video player by storing the whole video file in the phone storage system or simply streaming a video.
This application takes the first use case, second will be explained in one of the coming articles.
Playing Video files in Qt
There are lots of option if one needs to play video files in Qt for Symbian or MeeGo devices.
First one can store the video file in phone storage system and then open phone's native video player using Qt::OpenUrlExternally function of Qt, this can be directly used with QML code.
Second you can use QMediaPlayer and QVideoWidget APIs to play Videos from Qt C++.
Third is using QMLs Video element which is nothing else but a QML Plugin class for QMediaPlayer and QVideoWidget.
First one works pretty smooth with some simple hacks, second and third approach are generally used if you require an video player of your self within your application context.
This article shows how to play videos using QML Video Element.
QML Video Element
QML Video Element is basically part if Qt Multimedia 1.1 package for Qt Mobility Framework. Its a simple QML component where you just need to give the source of Video along with the size you need to keep for this element.
This Component is still Buggy if you Load the video element in your main QML file at the Launch of the application then it crashes with Symbian native WSERV 10 Panic.
To Over come this Bug you need to Load the Video Element as and when required instead of just Loading it at the start of the application.
Code Snippet Below Will Show how that can be done with the simple Video Player Component.
Video Player Component
Component Below is a simple Video Player component, This component file has three main important Functions:
- playVideo
- stopVideo
- pauseVideo
QML Video Element has lots of properties using which we can get maximum of the metadata of a particulat video file, which has a lot of usage too.
import QtQuick 1.0
import QtMultimediaKit 1.1 // do not forgot to import this
Item {
id: videoPlayerItem
property bool isVideoPlaying: videoPlayer.hasVideo // property to know if videoPlaying id ongoing or not
/*
Functions Which starts Video Playing
*/
function playVideo(){
videoPlayer.play()
}
/*
Function Which Stops Video Playing
*/
function stopVideo(){
videoPlayer.stop()
}
/*
Function Which Stops Video Playing
*/
function pauseVideo(){
videoPlayer.pause()
}
/*
Actual QML based Video Component
*/
Video{
id:videoPlayer
anchors.fill: videoPlayerItem // never forget to mention the size and position
source: "Video/Bear.wmv"
focus: true
}
}
How To Use this Component
Following code snippet shows how to use the above developed QML VideoPlayer Component in other QML file, The important thing we need to keep in mind that, as mentioned above, we can load the Video Component at the start of the application, instead we need to load the Video Element as and when required. For this task a simple Loader element has been used.
To Accomplish this task , a simple toolbar component has been designed which contains three buttons play, pause and stop.
When user Clicks the play button the Loader Components Loads the VideoPlayer QML file and then call the playVideo Function to play the video.
When Stop Button is clicked first stopVideo function is called and then Loader unloads the VideoPlayer QML File.
Please have a look at this QML code to get a idea of how the things have been done.
import QtQuick 1.0
Rectangle {
id: mainRect
width: 360
height: 640
color: "black"
TopTitleBar{
id:topTopTitleBar
x:mainRect.x; y:mainRect.y
width: mainRect.width; height: mainRect.height/20+10
}
Rectangle{
id:videoRect
x:mainRect.x; y:topTopTitleBar.y+topTopTitleBar.height
width: mainRect.width; height: mainRect.height-topTopTitleBar.height-70
color: "black"
/*
Simple Loader is placed inside the Rect which will help to load the videoPlayer Component when
user clicks the play button
*/
Loader{
id:videoLoader
anchors.fill: videoRect
}
}
/*
Simple Toolbar Item which has play, pause and stop button
*/
ToolBar{
id:toolBar
x: videoRect.x; y:topTopTitleBar.y+topTopTitleBar.height+videoRect.height;
width: videoRect.width; height: mainRect.height-videoRect.height-topTopTitleBar.height
onPlayButtonClicked: {
console.log("Play Button Clicked")
videoLoader.source = "VideoPlayer.qml" // sets the Loader to load our VideoPlayer Component
videoLoader.item.playVideo()// starts the video
}
onStopButtonClicked: {
console.log("Video Stopped"+videoLoader.source)
videoLoader.item.stopVideo() // stops the video
videoLoader.source = "" // unloads the QML Video Element component
Qt.quit() // exits the application
}
onPauseButtonClicked: {
console.log("Pause Suceessful"+videoLoader.source)
videoLoader.item.pauseVideo()// pause the video
}
}
}
Sample Application
A Sample Application has been developed to show case the usability of QML Video Component. Screenshots for the application are showed at the bottom.
Where One can see the code of Toolbar and the ToolBarButton Components designed, these can be used in any other application too.
Source Code: File:VideoPlayer.zip | http://developer.nokia.com/community/wiki/index.php?title=Simple_video_player_in_QML&direction=next&oldid=152229 | CC-MAIN-2014-10 | refinedweb | 818 | 56.66 |
Java - How to Create a Binary Search Tree
Java - How to Create a Binary Search Tree
Join the DZone community and get the full member experience.Join For Free
This article represents the high level concept and code samples which could be used to create a binary search tree in Java. Please feel free to comment/suggest if I missed to mention one or more important points. Also, sorry for the typos.
Following are the key points described later in this article:
- What is a binary search tree?
- What are different kind of traversals?
- Code Samples
What is a binary search tree?
A binary search tree is a binary tree in which every node contains a key that satisfies following criteria:
- The key in left child is less than the key in the parent node
- The key in the right child is more than the parent node
- The left and right child are again binary search trees.
Following diagram represents a binary search tree:
What are different kind of traversals?
Following are three different kind of traversals:
- Preorder traversal: In preorder traversal, the node is visted first and then, left and right sub-trees.
- Inorder traversal: In inorder traversal, the node is visited between left and right sub-tree.
- Postorder traversal: In postorder traversal, the node is visited after left and right subtrees.
Code Sample – How to Create a Binary Search Tree
If the numbers such as {20, 15, 200, 25, -5, 0, 100, 20, 12, 126, 1000, -150} are to be stored in a BinaryTree (represented by code below), following would get printed using different kind of traversal mechanism:
//Preorder traversal 20, 15, -5, -150, 0, 12, 200, 25, 20, 100, 126, 1000 // Inorder traversal -150, -5, 0, 12, 15, 20, 20, 25, 100, 126, 200, 1000 //Postorder traversal -150, 12, 0, -5, 15, 20, 126, 100, 25, 1000, 200, 20
Following is the code for creating binary tree that uses following BinaryTree class and traversals:
BinaryTree tree = new BinaryTree( 20 ); int[] nums = {15, 200, 25, -5, 0, 100, 20, 12, 126, 1000, -150}; for(int i : nums ) { tree.addNode( i ); } tree.traversePreOrder(); tree.traverseInOrder(); tree.traversePostOrder();
Following is the code for BinaryTree class:
public class BinaryTree { private int data; private BinaryTree left; private BinaryTree right; public BinaryTree(int num) { this.data = num; this.left = null; this.right = null; } // As a convention, if the key to be inserted is less than the key of root node, then key is inserted in // left sub-tree; If key is greater, it is inserted in right sub-tree. If it is equal, as a convention, it // is inserted in right sub-tree public void addNode(int num) { if (num < this.data) { if (this.left != null) { this.left.addNode(num); } else { this.left = new BinaryTree(num); } } else { if (this.right != null) { this.right.addNode(num); } else { this.right = new BinaryTree(num); } } } // Visit the node first, then left and right sub-trees public void traversePreOrder() { System.out.println( this.data ); if( this.left != null ) { this.left.traversePreOrder(); } if( this.right != null ) { this.right.traversePreOrder(); } } // Visit left sub-tree, then node and then, right sub-tree public void traverseInOrder() { if( this.left != null ) { this.left.traverseInOrder(); } System.out.println( this.data ); if( this.right != null ) { this.right.traverseInOrder(); } } // Visit left sub-tree, then right sub-tree and then the node public void traversePostOrder() { if( this.left != null ) { this.left.traversePostOrder(); } if( this.right != null ) { this.right.traversePostOrder(); } System.out.println( this.data ); } } }} | https://dzone.com/articles/java-how-create-binary-search | CC-MAIN-2020-24 | refinedweb | 577 | 54.02 |
(In reply to Nicholas Nethercote [:njn] from Bug 1297300 comment #0) > nsIURI.getSpec is fallible, but plenty of call sites don't check the return > value. Adding [must_use] to the IDL will identify those call sites. > > See bug 1290350 comment 6 for an example of how this can cause problems.
Aleth, if you have time, could you get me the full list of compilation errors on Mac. I've just done a push that will show me some at least. Of course I can also look through DXR. Many times we check the return value, but some times we don't.
In this case dxr is easier and faster than a compile log:(+ext%3Acpp+path%3Amailnews&redirect=true
I'll be very curious to see if this helps with some of our OOM | large crashes, which I was just looking at a few days ago.
Created attachment 8789917 [details] [diff] [review] First attempt. I went through in DXR and looks for "Getspec()" without checking the return value. Some where in #ifdef DEBUG ... #endif and I put a (void) in front. Some weren't used, so I remove them. Some functions calling Getspec() were void or bool, so I returned or returned the "default" value. I don't claim I found them all. This can currently not be tested since the M-C part hasn't landed. If I do a push with [must_use] as an M-C patch, I'm afraid that M-C won't compile since bug 1301607 isn't done yet. So we could land this now and hope that we don't get bustage later or at least very little. Or we wait and land this as a bustage fix later.
Comment on attachment 8789917 [details] [diff] [review] First attempt. Review of attachment 8789917 [details] [diff] [review]: ----------------------------------------------------------------- ::: mailnews/imap/src/nsImapMailFolder.cpp @@ +5212,5 @@ > if (session) > session->IsFolderOpenInWindow(this, &folderOpen); > #ifdef DEBUG_bienvenu1 > nsCString urlSpec; > + (void) aUrl->GetSpec(getter_Copies(urlSpec)); this wasn't the way to fix these... but it's ifdef bienvenue1 so you might want to remove all of the ifdef block ::: mailnews/imap/src/nsImapProtocol.cpp @@ +2128,5 @@ > if (aURL) > { > #ifdef DEBUG_bienvenu > nsAutoCString urlSpec; > + (void) aURL->GetSpec(urlSpec); same here ::: mailnews/mime/src/mimedrft.cpp @@ +143,5 @@ > > if ( tmp->m_url ) > { > nsAutoCString spec; > + (void) tmp->m_url->GetSpec(spec); shouldn't you use the "Unused" thing?
Yes, in the #ifdef DEBUG_bienvenu1 I was slack ;-) The one in mimedrft.cpp is in #ifdef NS_DEBUG extern "C" void mime_dump_attachments ( nsMsgAttachmentData *attachData ) but the patch context doesn't show that. The «"Unused" thing» and (void) are actually equivalent, only that (quoting from dev-platform): cast-to-void is commonly suggested as an alternative to an explicit unused marking, and it is something that I wanted to use originally. Unfortunately, we have not been able to make that work: this is primarily because compilers often remove the cast-to-void as part of the parsing phase, so it's not visible in the parse tree for static checkers. In debug I think (void) is the way to go.
I think that'll be confusing when someone's looking at code. I wonder if anyone ever uses the NS_DEBUG portions and such though...
If you want to remove the debug sections, I can remove them. I find them useful as an indication where D/B used to have his debug. And I personally wouldn't remove mime_dump_attachments(). I don't want to #include "mozilla/Unused.h" conditionally only to use it in debug. I also don't see which confusion you're talking about. So what do you want to do: Remove, use "unused" or can we leave the (void)?
One of the (void)s is in #ifdef PR_LOGGING.
(In reply to Jorg K (GMT+2, PTO during summer) from comment #9) > One of the (void)s is in #ifdef PR_LOGGING. iirc that's enabled in debug builds.
I'd say you can include "mozilla/Unused.h" unconditionally and use Unused where needed, even in ifdef blocks. It's confusing (kind of a trap) to have code that's wrong "just because it's in the debug section and we don't care".
Feel free to take that as a r+ once sorted out.
(In reply to Magnus Melin from comment #11) > It's confusing (kind of a trap) to have code that's wrong "just because it's > in the debug section and we don't care". It's not wrong. It's 100% fine only that "static checkers" don't like it. But guess what: They'll never see it since it's debug only.
Created attachment 8789943 [details] [diff] [review] Second attempt. r+ as per comment #12. In the #ifdef DEBUG_bienvenu I put a comment so no one gets confused. In mime_dump_attachments() which is C code the Unused can't be used, so I added another comment. In the file with #ifdef PR_LOGGING I included "mozilla/Unused.h" conditionally. I hope everyone is satisfied this way. I'll do a try run tomorrow when bug 1300152 is backed out from M-C because currently there are so many X failures that I can't see the forest for the trees :-(
Created attachment 8789982 [details] [diff] [review] Third attempt. I found the solution that will make all the purists happy ;-) GetSpecOrDefault() can be used for debugging or printing purposes. It's infallible. Use interdiff to see it. While I was there, I removed some more (void)s found elsewhere in debug.
No additional failures on try: Landed: Let's leave this bug open for a few days so I can check DXR again after it refreshed. Perhaps M-C make the return value check mandatory in the meantime.
Created attachment 8790034 [details] [diff] [review] Follow up. On second thought, the URL is pretty much optional here, so let's just kick on if it can't be retrieved instead of skipping the attachment. Do you agree?
Created attachment 8790037 [details] [diff] [review] Follow up (v1b). (changed comment.)
Created attachment 8790059 [details] [diff] [review] Follow up (v2a). OK, DXR has refreshed now and I missed three cases. These are included here together with the change in mimemoz2.cpp where I'd like to ignore the error.
Created attachment 8790077 [details] [diff] [review] Follow up (v2b). More clean-up.
Landed follow-up: I believe it's all covered now. Should there still be bustage when M-C adds must_use to the IDL, we can reopen this bug or open a new one after the next branch date Sept. 19th, 2016. | https://bugzilla.mozilla.org/show_bug.cgi?id=1301706 | CC-MAIN-2017-17 | refinedweb | 1,090 | 74.9 |
libssh2_scp_send_ex - Send a file via SCP
#include <libssh2.h> LIBSSH2_CHANNEL * libssh2_scp_send_ex(LIBSSH2_SESSION *session, const char *path, int mode, size_t size, long mtime, long atime);
This function has been deemed deprecated since libssh2 1.2.6. See libssh2_scp_send64(3). session - Session instance as returned by libssh2_session_init_ex(3) path - Full path and filename of file to transfer to. That is the remote file name. mode - File access mode to create file with size - Size of file being transmitted (Must be known ahead of time precisely) mtime - mtime to assign to file being created atime - atime to assign to file being created (Set this and mtime to zero to instruct remote host to use current time). Send a file to the remote host via SCP.
Pointer to a newly allocated LIBSSH2_CHANNEL instance, or NULL on errors.
LIBSSH2_ERROR_ALLOC - An internal memory allocation call failed. LIBSSH2_ERROR_SOCKET_SEND - Unable to send data on socket. LIBSSH2_ERROR_SCP_PROTOCOL - LIBSSH2_ERROR_EAGAIN - Marked for non-blocking I/O but the call would block.
This function was marked deprecated in libssh2 1.2.6 as libssh2_scp_send64(3) has been introduced to replace this function.
libssh2_channel_open_ex(3) | http://huge-man-linux.net/man3/libssh2_scp_send_ex.html | CC-MAIN-2018-05 | refinedweb | 182 | 65.52 |
I want to install matplotlib on OS X. If possible, using homebrew.
I installed Python 2.7.1 using brew install python, I modified my path to use it
I installed pip using brew install pip
I installed numpy 1.5.1 using pip install numpy
I installed scipy 0.8.0 using pip install scipy
brew install python
brew install pip
pip install numpy
pip install scipy
This is where it gets hairy. pip install matplotlib will fetch the wrong version of matplotlib, which is incompatible with the recent version of numpy.
pip install matplotlib
The solution is to fetch the correct version of matplotlib manually:
pip install -f matplotlib
But, that version fails to compile since it can't find the freetype headers:
In file included from src/ft2font.cpp:1:
src/ft2font.h:14:22: error: ft2build.h: No such file or directory
In file included from src/ft2font.cpp:1:
src/ft2font.h:14:22: error: ft2build.h: No such file or directory
These headers are actually installed in /usr/X11/include as part of the X11 developer tools.
/usr/X11/include
So, how can I make matplotlib use these headers?
This question came from our site for professional and enthusiast programmers.
brew install freetype
The problem is that when the C extensions are compiled, required headers files aren't in the search path, and when they're being linked, shared libraries aren't in the search path either.
The following worked for me:
export LDFLAGS="-L/usr/X11/lib"
export CFLAGS="-I/usr/X11/include -I/usr/X11/include/freetype2 -I/usr/X11/include/libpng12"
pip install matplotlib-1.0.1.tar.gz
The simple answer is: You need to have pkg-info installed or else setup.py won't be able to find installed libraries.
pkg-info
setup.py
brew install pkg-info
pkg-config
brew install pkg-config
brew link
I followed this page's instructions. I got stuck at
pip install -e git+
Then I did:
git clone
cd matplotlib
python setup.py build
python setup.py install
Checked my installation by typing in terminal:
python
import matplotlib
print matplotlib.__version__
print matplotlib.__file__
I got version 1.1.0 (as of this writing) and path /usr/local/Cellar/...
Altneratively, you could use MacPorts or Fink. With MacPorts this would be
sudo port install py27-matplotlib
which resolves the dependencies automatically.
Personally I used Macports to install python2.7 with matplotlib and it seems to works fine on 10.7. Fink is in the process of upgrading their internals to work with the new 10.7 build system.
The answer is, there's no freetype library. just simply brew it:
brew install freetype
libpng
Same problem using macports. Fixed with:
sudo port install pkgconfig
as noio suggested for brew above.
I found this to work flawlessly on OS X 10.8.3
I wrote this reply here but I think it can be of some interest in this discussion.
I got to install matplotlib on OSX 10.10 reading.
This is not a solution for pip users; just a way to install matplotlib on my mac waiting for a fix.
I downloaded sources for matplotlib 1.4.2,
changed line 960 in setupext.py as described in :
'freetype2', 'ft2build.h',
becames
'freetype2', 'freetype2/ft2build.h'
and then compiled and installed with:
python setup.py build
python setup.py install
These days, the easiest way is probably conda install matplotlib, using the conda package manager by continuum analytics.
conda install matplotlib
conda
Note that you can install and use conda without having to use the full Anaconda distribution. Just pip install conda, conda init, and you're good to go.
pip install conda
conda init
with OS X 10.10.3 I fixed it with this commands
brew install freetype libpng pkg-config
brew install freetype libpng pkg-config
pkg-config fixed the issue!
After reading this issue I manage to fix it
By posting your answer, you agree to the privacy policy and terms of service.
asked
4 years ago
viewed
16599 times
active
3 months ago | http://superuser.com/questions/242190/how-to-install-matplotlib-on-os-x/242191 | CC-MAIN-2015-40 | refinedweb | 685 | 68.06 |
|
My Account
More Articles
Excerpt from Professional C# 2005
The first version of the .NET Framework (1.0) was released in 2002 to much enthusiasm. The latest version, the .NET Framework 2.0, was introduced in 2005 and is considered a major release of the framework.
With each release of the framework, Microsoft has always tried to ensure that there were minimal breaking changes to code developed. Thus far, they have been very successful at this goal.
Make sure that you create a staging server to completely test the upgrade of your applications to the .NET Framework 2.0 as opposed to just upgrading a live application.
The following details some of the changes that are new to the .NET Framework 2.0 as well as new additions to Visual Studio 2005 — the development environment for the .NET Framework 2.0.
After a long wait, the latest version of SQL Server has finally been released. This version, SQL Server 2005, is quite special in so many ways. Most importantly for the .NET developer is that SQL Server 2005 is now hosting the CLR. Microsoft has developed their .NET offering for developers so that the .NET Framework 2.0, Visual Studio 2005 and SQL Server 2005 are all now tied together — meaning that these three products are now released in unison. This is quite important as it is rather well known that most applications built use all three of these pieces and that they all need to be upgraded together in such a way that they work with each other in a seamless manner.
Due to the fact that SQL Server 2005 now hosts the CLR, this means that you can now avoid building database aspects of your application using the T-SQL programming language. Instead, you can now build items such as your stored procedures, triggers and even data types in any of the .NET-compliant languages, such as C#.
SQL Server Express is the 2005 version of SQL Server that replaces MSDE. This version doesn't have the strict limitations MSDE had.
Most programming today is done on 32-bit machines. It was a monumental leap forward in application development when computers went from 16-bit to 32-bit. More and more enterprises are moving to the latest and greatest 64-bit servers from companies such as Intel (Itanium chips) and AMD (x64 chips) and the .NET Framework 2.0 has now been 64-bit enabled for this great migration.
Microsoft has been working hard to make sure that everything you build in the 32-bit world of .NET will run in the 64-bit world. This means that everything you do with SQL Server 2005 or ASP.NET will not be affected by moving to 64-bit. Microsoft themselves made a lot of changes to the CLR in order to get a 64-bit version of .NET to work. Changes where made to things such as garbage collection (to handle larger amounts of data), the JIT compilation process, exception handling, and more.
Moving to 64-bit gives you some powerful additions. The most important (and most obvious reason) is that 64-bit servers give you a larger address space. Going to 64-bit also allows for things like larger primitive types. For instance, an integer value of 2^32 will give you 4,294,967,296 — while an integer value of 2^64 will give you 18,446,744,073,709,551,616. This comes in quite handy for those applications that need to calculate things such as the U.S. debt or other high numbers.
Companies such as Microsoft and IBM are pushing their customers to take a look at 64-bit. One of the main areas of focus are on database and virtual storage capabilities as this is seen as an area in which it makes a lot of sense to move to 64-bit for.
Visual Studio 2005 can install and run on a 64-bit computer. This IDE has both 32-bit and 64-bit compilers on it. One final caveat is that the 64-bit .NET Framework is meant only for Windows Server 2003 SP1 or better as well as other 64-bit Microsoft operating systems that might come our way.
When you build your applications in Visual Studio 2005, you can change the build properties of your application so that it compiles specifically for 64-bit computers. To find this setting, you will need to pull up your application's properties and click on the Build tab from within the Properties page. On the Build page, click on the Advanced button and this will pull up the Advanced Compiler Setting dialog. From this dialog, you can change the target CPU from the bottom of the dialog. From here, you can establish your application to be built for either an Intel 64-bit computer or an AMD 64-bit computer. This is shown here in Figure 1.
In order to make collections a more powerful feature and also increase their efficiency and usability, generics were introduced to the .NET Framework 2.0. This introduction to the underlying framework means that languages such as C# and Visual Basic 2005 can now build applications that use generic types. The idea of generics is nothing new. They look similar to C++ templates but are a bit different. You can also find generics in other languages, such as Java. Their introduction into the .NET Framework 2.0 languages is a huge benefit for the user.
Generics enable you to make a generic collection that is still strongly typed — providing fewer chances for errors (because they occur at runtime), increasing performance, and giving you Intellisense features when you are working with the collections.
To utilize generics in your code, you will need to make reference to the System.Collections.Generic namespace. This will give you access to generic versions of the Stack, Dictionary, SortedDictionary, List and Queue classes. The following demonstrates the use of a generic version of the Stack class:
System.Collections.Generic
Stack
Dictionary
SortedDictionary
List
Queue
void Page_Load(object sender, EventArgs e)
{
System.Collections.Generic.Stack<string> myStack =
New System.Collections.Generic.Stack<string>();
myStack.Push("St. Louis Rams");
myStack.Push("Indianapolis Colts");
myStack.Push("Minnesota Vikings");
Array myArray;
myArray = myStack.ToArray();
foreach(string item in myArray)
{
Label1.Text += item + "<br />";
}
}
In the above example, the Stack class is explicitly cast to be of type string. Here, you specify the collection type with the use of brackets. This example, casts the Stack class to type string using Stack<string>. If you wanted to cast it to something other than a Stack class of type string (for instance, int), then you would specify Stack<int>.
string
Stack<string>
int
Stack<int>
Because the collection of items in the Stack class is cast to a specific type immediately as the Stack class is created, the Stack class no longer casts everything to type object and then later (in the foreach loop) to type string. This process is called boxing, and it is expensive. Because this code is specifying the types up front, the performance is increased for working with the collection.
object
foreach
Anonymous methods enable you to put programming steps within a delegate that you can then later execute instead of creating an entirely new method. For instance, if you were not using anonymous methods, you would use delegates in a manner similar to the following:
public partial class Default_aspx
{
void Page_Load(object sender, EventArgs e)
{
this.Button1.Click += ButtonWork;
}
void ButtonWork(object sender, EventArgs e)
{
Label1.Text = "You clicked the button!";
}
}
But using anonymous methods, you can now put these actions directly in the delegate as shown here in the following example:
public partial class Default_aspx
{
void Page_Load(object sender, EventArgs e)
{
this.Button1.Click += delegate(object
myDelSender, EventArgs myDelEventArgs)
{
Label1.Text = "You clicked the button!";
};
}
}
When using anonymous methods, there is no need to create a separate method. Instead you place the necessary code directly after the delegate declaration. The statements and steps to be executed by the delegate are placed between curly braces and closed with a semicolon.
Due to the fact that generics has been introduced into the underlying .NET Framework 2.0, it is now possible to create nullable value types — using System.Nullable<T>. This is ideal for situations such as creating sets of nullable items of type int. Before this, it was always difficult to create an int with a null value from the get-go or to later assign null values to an int.
System.Nullable<T>
To create a nullable type of type int, you would use the following syntax:
System.Nullable<int> x = new System.Nullable<int>;
There is a new type modifier that you can also use to create a type as nullable. This is shown in the following example:
int? salary = 800000
This ability to create nullable types is not a C#-only item as this ability was built into .NET Framework itself and, as stated, is there due to the existence of the new generics feature in .NET. For this reason, you will also find nullable types in Visual Basic 2005 as well.
Iterators enable you to use foreach loops on your own custom types. To accomplish this, you need to have your class implement the IEnumerable interface as shown here:
IEnumerable
using System;
using Systm.Collections;
public class myList
{
internal object[] elements;
internal int count;
public IEnumerator GetEnumerator()
{
yield return "St. Louis Rams";
yield return "Indianapolis Colts";
yield return "Minnesota Vikiings";
}
}
In order to use the IEnumerator interface, you will need to make a reference to the System.Collections namespace. With this all in place, you can then iterate through the custom class as shown here:
IEnumerator
System.Collections
void Page_Load(object sender, EventArgs e)
{
myList IteratorList = new myList();
foreach(string item in IteratorList)
{
Response.Write(item.ToString() + "<br />");
}
}
Partial classes are a new feature to the .NET Framework 2.0 and again C# takes advantage of this addition. Partial classes allow you to divide up a single class into multiple class files, which are later combined into a single class when compiled.
To create a partial class, you simply need to use the partial keyword for any classes that are to be joined together with a different class. The partial keyword precedes the class keyword for the classes that are to be combined with the original class. For instance, you might have a simple class called Calculator as shown here:
partial
class
Calculator
public class Calculator
{
public int Add(int a, int b)
{
return a + b;
}
}
From here, you can create a second class that attaches itself to this first class as shown here in the following example:
public partial class Calculator
{
public int Subtract(int a, int b)
{
return a - b;
}
}
When compiled, these classes will be brought together into a single Calculator class instance as if they were built together to begin with.
In one sense, C# can be seen as being the same thing to programming languages as .NET is to the Windows environment. Just as Microsoft has been adding more and more features to Windows and the Windows API over the past decade, Visual Basic 2005 and C++ have undergone expansion. Although Visual Basic and C++ have ended up as hugely powerful languages as a result of this, both languages also suffer from problems due to the legacies of how they have evolved.
In the case of Visual Basic 6 and earlier versions, the main strength of the language was the fact that it was simple to understand and didn't make many programming tasks easy, largely hiding the details of the Windows API and the COM component infrastructure from the developer. The downside to this was that Visual Basic was never truly object-oriented, so that large applications quickly became disorganized and hard to maintain. As well, because Visual Basic's syntax was inherited from early versions of BASIC (which, in turn, was designed to be intuitively simple for beginning programmers to understand, rather than to write large commercial applications), it didn't really lend itself to well-structured or object-oriented programs.
C++, on the other hand, has its roots in the ANSI C++ language definition. It isn't completely ANSI-compliant for the simple reason that Microsoft first wrote its C++ compiler before the ANSI definition had become official, but it comes close. Unfortunately, this has led to two problems. First, ANSI C++ has its roots in a decade-old state of technology, and this shows up in a lack of support for modern concepts (such as Unicode strings and generating XML documentation), and for some archaic syntax structures designed for the compilers of yesteryear (such as the separation of declaration from definition of member functions). Second, Microsoft has been simultaneously trying to evolve C++ into a language that is designed for high-performance tasks on Windows, and in order to achieve that they've.
char*
LPTSTR
CString
wchar_t*
OLECHAR*
Now enter .NET —a completely new environment that is going to involve new extensions to both languages. Microsoft has gotten around this by adding yet more Microsoft-specific keywords to C++, and by completely revamping Visual Basic into Visual Basic .NET into Visual Basic 2005, a language that retains some of the basic VB syntax but that is so different in design that we can consider it to be, for all practical purposes, a new language.
It's in this context that Microsoft has decided to give developers an alternative — a language designed specifically for .NET, and designed with a clean slate. Visual C# 2005 is the result. Officially, Microsoft describes C# as a "simple, modern, object-oriented, and type-safe programming language derived from C and C++." Most independent observers would probably change that to "derived from C, C++, and Java." Such descriptions are technically accurate but do little to convey the beauty or elegance of the language. Syntactically, C# is very similar to both C++ and Java, to such an extent that many keywords are the same, and C# also shares the same block structure with braces ({}) to mark blocks of code, and semicolons to separate statements. The first impression of a piece of C# code is that it looks quite like C++ or Java code. Beyond that initial similarity, however, C# is a lot easier to learn than C++, and of comparable difficulty to Java. Its design is more in tune with modern developer tools than both of those other languages, and it has been designed to give us, simultaneously, the ease of use of Visual Basic, and the high-performance, low-level memory access of C++ if required. Some of the features of C# are:
Most of the above statements, it should be pointed out, do also apply to Visual Basic 2005 and Managed C++. The fact that C# is designed from the start to work with .NET, however, means that its support for the features of .NET is both more complete, and offered within the context of a more suitable syntax than for those other languages. While the C# language itself is very similar to Java, there are some improvements, in particular, Java is not designed to work with the .NET environment.
Before we leave the subject, we should point out a couple of limitations of C#. The one area the language is not designed for is time-critical or extremely high performance code — the kind where you really are worried about whether a loop takes 1,000 or 1,050 machine cycles to run through, and you need to clean up your resources the millisecond they are no longer needed. C++ is likely to continue to reign supreme among low-level languages in this area. C# lacks certain key facilities needed for extremely high performance apps, including the ability to specify inline functions and destructors that are guaranteed to run at particular points in the code. However, the proportions of applications that fall into this category are very low. | http://www.wrox.com/WileyCDA/Section/id-290323.html | crawl-001 | refinedweb | 2,671 | 63.39 |
Are you all aware of CWrap? It goes a long way to generating pxd files for a C libary. It can, for example, generate valid pxd files for the whole of the Intel IPP library. This would likely be a good launching point for a GSOC project, unless you really want to start from scratch. It's BSD licensed. On Thu, Mar 29, 2012 at 5:10 AM, mark florisson <markflorisson88 at gmail.com>wrote: > > > > > > > Nice. But please use 4 spaces (see PEP 8) :-) > > > > More ideas for project proposal: > > > >. > > I think the current GCC plugin support doesn't allow you to do much > with te preprocessor, it operates entirely after the C preprocessor > has run. So to support macros we have to consider that for this to > work the gcc plugin may have to be extended, which uses C to extend > GCC and Python, so it also requires knowledge of the CPython C API. > David, would you mind elaborating why C was used for this project and > not (partially) Cython, and would it be possible to extend the plugin > with Cython? > > > Then what happens if you have > > > > #ifdef FOO > > #define BAR 3 > > #else > > #define BAR 4 > > #endif > > > > ?? I'm not saying it is hard, but perhaps no longer completely trivial > :-) > > > > And like Robert hinted at, supporting all the aspects of C++ might take a > > little more work, there's just so much different syntax in C++, and > there's > > several C++ features Cython just does not support and must be either > ignored > > or hacked around (e.g., "const"). > > > > Supporting stuff like > > > > #define MACRO(x) ((x)->field*2) > > > > probably belongs in the category of "must be done manually". > > > > > >> > >>.) > > > > Dag > > > > _______________________________________________ > > cython-devel mailing list > > cython-devel at python.org > > > _______________________________________________ > cython-devel mailing list > cython-devel at python.org > > -------------- next part -------------- An HTML attachment was scrubbed... URL: <> | https://mail.python.org/pipermail/cython-devel/2012-March/002159.html | CC-MAIN-2017-17 | refinedweb | 306 | 70.13 |
shell program
shell scripts
Login to Discuss or Reply to this Discussion in Our Community
Thread Tools
Search this Thread
Top Forums
Shell Programming and Scripting
shell program
#
1
11-17-2005
rameshparsa
Registered User
6,
0
Join Date: Nov 2005
Last Activity: 18 November 2005, 4:33 AM EST
Posts: 6
Thanks Given: 0
Thanked 0 Times in 0 Posts
shell program
How to write a shell script which takes 3 strings as positional parameters,first and second are file names and third is a directory.if the two files exist in `pwd` and they contain a specific pattern and their size is greater than 32 bytes,moves these files into directory?
rameshparsa
View Public Profile for rameshparsa
Find all posts by rameshparsa
#
2
11-17-2005
dangral
Registered User
723,
4
Join Date: Oct 2002
Last Activity: 31 July 2013, 6:52 PM EDT
Posts: 723
Thanks Given: 3
Thanked 4 Times in 4 Posts
Please see rule #6
here
for some guidance.
dangral
View Public Profile for dangral
Find all posts by dangral
Login or Register to Ask a Question
Previous Thread
|
Next Thread
10 More Discussions You Might Find Interesting
1.
Homework & Coursework Questions
C shell program
1. I've have to write a shell program that accepts Ctrl+T (in linux os in c language) and should print out the current time and date to the screen. I've written the following code but i've to type ^T individual rather than pressing ctrl+T(^T) to get the output. : 2. How do i make the shell...
(2 Replies)
Discussion started by: zorro_phu
2 Replies
2.
Homework & Coursework Questions
Shell program in C
Hi all, I have an assignment from school to write a shell program in linux. the idea is to exercise fork() and execv() functions.. the shell program is supposed to be the master and every command that the user prints will run in a new process. we also need to try running the command in every...
(1 Reply)
Discussion started by: r3vive
1 Replies
3.
Shell Programming and Scripting
Shell Program , need help!!
Hi all, I am trying to get a file from an ftp server and i have the list of files which needs to be get from the ftp server. grep unix_prg*.* log.txt > log1.txt log1.txt (which has the list of files) 06-29-09 00:00AM 3550258 unix_prg090629 06-28-09 07:00PM ...
(7 Replies)
Discussion started by: raghav1982
7 Replies
4.
Shell Programming and Scripting
shell program
Iam having file 1 as wc -l file1 is 8 QWEERTYUU|7927836357398398398913 yuyuyu uyiuyuyuyuy yuiyuiyuyuyy FDHGFSHAJK|1476887897877777777771 iopwiiwpoi e . . . . I Need to read the abouve line in file1 so iam using the command as tail -n 8...
(8 Replies)
Discussion started by: nivas
8 Replies
5.
Shell Programming and Scripting
help with shell program
I want to print the value of variables a1, a2, a3 in for loop in the following program: a1=this a2=is a3=printed for((i=1;i<4;i++)) do var=a$i #w=`echo $var` e=${var} echo $e done But actually I get a1,a2,a3 as the output not the "this is printed" So the main question is if I...
(3 Replies)
Discussion started by: adgarg
3 Replies
6.
Shell Programming and Scripting
very first shell program.
in the beginners book i have it gives an exercise to try. saying to make a script that examines the time. it should keep examining every second or so and say some sort of message. Can anyone help me get going. Thanks
(3 Replies)
Discussion started by: bebop1111116
3 Replies
7.
Shell Programming and Scripting
shell program
hello, i have problem in awk filter in shell to concatenate two string plz send me a solution as soon as possible from jyoti ardeshana
(4 Replies)
Discussion started by: jyotiardeshana
4 Replies
8.
Programming
Shell Program
I am programming the following simple shell program. It works for the most part, things like 'ls' and 'ps' work just fine. However when I add options, (example, ls -l) it does not execute the command. Also, I've been trying to add an "exit" command, so that I don't have to use the iterrupt; but...
(3 Replies)
Discussion started by: TexasGuy
3 Replies
9.
Shell Programming and Scripting
C shell Program
Hellow every body I am trying to write a very simple script in an executable file as following if ($?PWD) then echo "OK" else echo "No" endif but I am getting error during execution in c shell as synthax error at line 4 , unexpected end of file Please advise
(2 Replies)
Discussion started by: Reza Nazarian
2 Replies
10.
Shell Programming and Scripting
Help me with this Shell Program
Now, am in a very tight situation here. I really dont expect anyone to understand but please, try your best. am trying to right a program that goes back to the previous entry to correct a mistake. heres what am trying to do. i write a program like this Name : James Holgston...
(1 Reply)
Discussion started by: TRUEST
1 Replies
Login or Register to Ask a Question
Member Badges and Information Modal
×
Featured Tech Videos | https://www.unix.com/shell-programming-and-scripting/23167-shell-program.html?s=7a5d9a9c3f09b13aa6ac6d6f37627f69 | CC-MAIN-2022-33 | refinedweb | 867 | 68.91 |
Hi guys. I have a script which cycles through a directory and adds 4band data. It works like a charm. The problem is that the customer wants the results UNcompressed. By default, all of the resulting files are compressed and so I have to manually open each file and then simply export data/raster to raster/compression set to zero. That works, but it's tedious and unnecessarily expensive in time.
I have looked everywhere I can to find out how to do the export process with zero compression by script. No luck, so I figured I'd try here.
Below is the currently functioning script.
----------------------------------------------------
import os,arcpy,glob
rasterpath = r"filepath-source"
outFolder = r"filepath-end"
arcpy.env.workspace = rasterpath
for rasterFile in arcpy.ListRasters("*.tif"):
oName, oExt = os.path.splitext(rasterFile)
outRaster = os.path.join(outFolder, oName+ ".tif")
arcpy.CopyRaster_management(rasterFile,outRaster,"DEFAULTS","255","255","","","8_BIT_UNSIGNED")
-------------------------------------------------------
I know that the process of adding the band data creates pyramids, but my attempts to add zero compression to the environment on this script fails. What I'm looking for help with:
* the command line which will simply resave the data as-is but with no compression.
Compression is not an option for arcpy.CopyRaster_management in tiff format that I can find. There has to be a way to automate this. I'll be shooting myself if I have to manually open and resave hundreds of ortho images per object just for that single variable. I hope you guys can help! Thanks.
Compression (Environment setting)—Geoprocessing | ArcGIS Desktop
Is an environment setting, so I suppose you tried setting it to None
compression_type (Required) NONE—No compression will occur.
I did try that:
arcpy.env.compression = "NONE"
The results are still compressed with LZW.
Copy Raster—Data Management toolbox | ArcGIS Desktop
well it is supposed to honor Compression
out_rasterdataset When storing a raster dataset to a JPEG file, JPEG 2000 file, TIFF file, or geodatabase, you can specify a compression type and compression quality.
HOWEVER!
Raster file formats—ArcGIS Pro | ArcGIS Desktop
Depends on your tif
Big no for
Do you know how I would set that? I've seen that, but there are no examples I can copy.
I'm changing this line:
arcpy.CopyRaster_management(rasterFile,outRaster,"DEFAULTS","255","255","","","8_BIT_UNSIGNED")
to:
arcpy.CopyRaster_management(rasterFile,outRaster\\none,"DEFAULTS","255","255","","","8_BIT_UNSIGNED")
I'm using the 8-bit unsigned, so that appears to have the option at least.
Thanks for the suggestions Dan! I'll keep looking.
Sondra, you set the environment parameter as you had before within the script before copyraster
I ran a test to check to see if it did anything. If it isn't set it defaults to 'LZ77' but I don't trust that capitalized NONE thing
arcpy.env.compression = None arcpy.env['compression'] 'LZ77' arcpy.env.compression = "NONE" arcpy.env['compression'] 'NONE' # returned value
Any luck?
Nope. none at all. still looking to save a raster without compression.
I did do a verification through print(arcpy.env.compression) that the compression environment was successfully set to None, both before and after the loop. It was came back with the correct setting, but still getting the compression.
Interestingly, the compression is actually LZW, not the default LZ77. I found a reference to "How To: Change the default compression format for output TIFF files" but the file this article mentions doesn't exist on the machine I'm using.
This seems to work ok in 10.6.1 and Pro 2.2
import arcpy outFolder = r"C:\temp\data\results" arcpy.env.workspace = r"c:\temp\data" arcpy.env.compression = "NONE" for rasterFile in arcpy.ListRasters("*", "TIF"): outName, outExtension = arcpy.os.path.splitext(rasterFile) outRaster = arcpy.os.path.join(outFolder, ''.join([outName, "_u", outExtension])) arcpy.CopyRaster_management(rasterFile, outRaster) | https://community.esri.com/t5/python-questions/export-data-arcpy-command-line-to-save-tiff-raster/td-p/278382 | CC-MAIN-2022-27 | refinedweb | 631 | 52.36 |
Redux vs. The React Context API
Dave Ceddia
Originally published at
daveceddia.com
on
・14 min read
React 16.3 added a new Context API – new in the sense that the old context API was a behind-the-scenes feature that most people either didn’t know about, or avoided using because the docs said to avoid using it.
Now, though, the Context API is a first-class citizen in React, open to all (not that it wasn’t before, but it’s, like, official now).
As soon as React 16.3 came out there were articles all across the web proclaiming the death of Redux because of this new Context API. If you asked Redux, though, I think it would say “the reports of my death are greatly exaggerated.”
In this post I want to cover how the new Context API works, how it is similar to Redux, when you might want to use Context instead of Redux, and why Context doesn’t replace the need for Redux in every case.
A Motivating Example
I’m going to assume you’ve got the basics of React down pat (props & state), but if you don’t, I have a free 5-day course to help you learn react here.
Let’s look at an example that would cause most people to reach for Redux. We’ll start with a plain React version, and then see what it looks like in Redux, and finally with Context.
This app has the user’s information displayed in two places: in the nav bar at the top-right, and in the sidebar next to the main content.
The component structure looks like this:
With pure React (just regular props), we need to store the user’s info high enough in the tree that it can be passed down to the components that need it. In this case, the keeper of user info has to be
App.
Then, in order to get the user info down to the components that need it, App needs to pass it along to Nav and Body. They, in turn, need to pass it down again, to UserAvatar (hooray!) and Sidebar. Finally, Sidebar has to pass it down to UserStats.
Let’s look at how this works in code (I’m putting everything in one file to make it easier to read, but in reality these would probably be split out into separate files).
import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; const UserAvatar = ({ user, size }) => ( <img className={`user-avatar ${size || ""}`} <div> <UserAvatar user={user} /> {user.name} </div> <div className="stats"> <div>{user.followers} Followers</div> <div>Following {user.following}</div> </div> </div> ); const Nav = ({ user }) => ( <div className="nav"> <UserAvatar user={user} </div> ); const Content = () => <div className="content">main content here</div>; const Sidebar = ({ user }) => ( <div className="sidebar"> <UserStats user={user} /> </div> ); const Body = ({ user }) => ( <div className="body"> <Sidebar user={user} /> <Content user={user} /> </div> ); class App extends React.Component { state = { user: { avatar: "", name: "Dave", followers: 1234, following: 123 } }; render() { const { user } = this.state; return ( <div className="app"> <Nav user={user} /> <Body user={user} /> </div> ); } } ReactDOM.render(<App />, document.querySelector("#root"));
Here’s a working example on CodeSandbox.
Now, this isn’t terrible. It works just fine. But it’s a bit annoying to write. And it gets more annoying when you have to pass down a lot of props (instead of just one).
There’s a bigger downside to this “prop drilling” strategy though: it creates coupling between components that would otherwise be decoupled. In the example above,
Nav needs to accept a “user” prop and pass it down to
UserAvatar, even though Nav does not have any need for the
user otherwise.
Tightly-coupled components (like ones that forward props down to their children) are more difficult to reuse, because you’ve gotta wire them up with their new parents whenever you plop one down in a new location.
Let’s look at how we might improve it with Redux.
Using Redux to Improve Data Flow
I’m going to go through the Redux example quickly so we can look more deeply at how Context works, so if you are fuzzy on Redux, read this intro to Redux first (or watch the video).
Here’s the React app from above, refactored to use Redux. The
user info has been moved to the Redux store, which means we can use react-redux’s
connect function to directly inject the
user prop into components that need it.
This is a big win in terms of decoupling. Take a look at
Nav,
Body, and
Sidebar and you’ll see that they’re no longer accepting and passing dow the
user prop. No more playing hot potato with props. No more needless coupling.
import React from "react"; import ReactDOM from "react-dom"; // We need createStore, connect, and Provider: import { createStore } from "redux"; import { connect, Provider } from "react-redux"; // Create a reducer with an empty initial state const initialState = {}; function reducer(state = initialState, action) { switch (action.type) { // Respond to the SET_USER action and update // the state accordingly case "SET_USER": return { ...state, user: action.user }; default: return state; } } // Create the store with the reducer const store = createStore(reducer); // Dispatch an action to set the user // (since initial state is empty) store.dispatch({ type: "SET_USER", user: { avatar: "", name: "Dave", followers: 1234, following: 123 } }); // This mapStateToProps function extracts a single // key from state (user) and passes it as the `user` prop const mapStateToProps = state => ({ user: state.user }); // connect() UserAvatar so it receives the `user` directly, // without having to receive it from a component above // could also split this up into 2 variables: // const UserAvatarAtom = ({ user, size }) => ( ... ) // const UserAvatar = connect(mapStateToProps)(UserAvatarAtom); const UserAvatar = connect(mapStateToProps)(({ user, size }) => ( <img className={`user-avatar ${size || ""}`} <div> <UserAvatar user={user} /> {user.name} </div> <div className="stats"> <div>{user.followers} Followers</div> <div>Following {user.following}</div> </div> </div> )); // Nav doesn't need to know about `user` anymore const Nav = () => ( <div className="nav"> <UserAvatar size="small" /> </div> ); const Content = () => ( <div className="content">main content here</div> ); // Sidebar doesn't need to know about `user` anymore const Sidebar = () => ( <div className="sidebar"> <UserStats /> </div> ); // Body doesn't need to know about `user` anymore const Body = () => ( <div className="body"> <Sidebar /> <Content /> </div> ); // App doesn't hold state anymore, so it can be // a stateless function const App = () => ( <div className="app"> <Nav /> <Body /> </div> ); // Wrap the whole app in Provider so that connect() // has access to the store ReactDOM.render( <Provider store={store}> <App /> </Provider>, document.querySelector("#root") );
Here’s the Redux example on CodeSandbox.
Now you might be wondering how Redux achieves this magic. It’s a good thing to wonder. How is it that React doesn’t support passing props down multiple levels, but Redux is able to do it?
The answer is, Redux uses React’s context feature. Not the modern Context API (not yet) – the old one. The one the React docs said not to use unless you were writing a library or knew what you were doing.
Context is like an electrical bus running behind every component: to receive the power (data) passing through it, you need only plug in. And (React-)Redux’s
connect function does just that.
This feature of Redux is just the tip of the iceberg, though. Passing data around all over the place is just the most apparent of Redux’s features. Here are a few other benefits you get out of the box:
connect is pure
connect automatically makes connected components “pure,” meaning they will only re-render when their props change – a.k.a. when their slice of the Redux state changes. This prevents needless re-renders and keeps your app running fast. DIY method: Create a class that extends
PureComponent, or implement
shouldComponentUpdate yourself.
Easy Debugging with Redux
The ceremony of writing actions and reducers is balanced by the awesome debugging power it affords you.
With the Redux DevTools extension you get an automatic log of every action your app performed. At any time you can pop it open and see which actions fired, what their payload was, and the state before and after the action occurred.
Another great feature the Redux DevTools enable is time travel debugging a.k.a. you can click on any past action and jump to that point in time, basically replaying every action up to and including that one (but no further). The reason this can work is because each action immutably update’s the state, so you can take a list of recorded state updates and replay them, with no ill effects, and end up where you expect.
Then there are tools like LogRocket that basically give you an always-on Redux DevTools in production for every one of your users. Got a bug report? Sweet. Look up that user’s session in LogRocket and you can see a replay of what they did, and exactly which actions fired. That all works by tapping into Redux’s stream of actions.
Customize Redux with Middleware
Redux supports the concept of middleware, which is a fancy word for “a function that runs every time an action is dispatched.” Writing your own middleware isn’t as hard as it might seem, and it enables some powerful stuff.
For instance…
- Want to kick off an API request every time an action name starts with
FETCH_? You could do that with middleware.
- Want a centralized place to log events to your analytics software? Middleware is a good place for that.
- Want to prevent certain actions from firing at certain times? You can do that with middleware, transparent to the rest of your app.
- Want to intercept actions that have a JWT token and save them to localStorage, automatically? Yep, middleware.
Here’s a good article with some examples of how to write Redux middleware.
How to Use the React Context API
But hey, maybe you don’t need all those fancy features of Redux. Maybe you don’t care about the easy debugging, the customization, or the automatic performance improvements – all you want to do is pass data around easily. Maybe your app is small, or you just need to get something working and address the fancy stuff later.
React’s new Context API will probably fit the bill. Let’s see how it works.
I published a quick Context API lesson on Egghead if you’d rather watch than read (3:43):
There are 3 important pieces to the context API:
- The
React.createContextfunction which creates the context
- The
Provider(returned by
createContext) which establishes the “electrical bus” running through a component tree
- The
Consumer(also returned by
createContext) which taps into the “electrical bus” to extract the data
The
Provider is very similar to React-Redux’s
Provider. It accepts a
value prop which can be whatever you want (it could even be a Redux store… but that’d be silly). It’ll most likely be an object containing your data and any actions you want to be able to perform on the data.
The
Consumer works a little bit like React-Redux’s
connect function, tapping into the data and making it available to the component that uses it.
Here are the highlights:
// Up top, we create a new context // This is an object with 2 properties: { Provider, Consumer } // Note that it's named with UpperCase, not camelCase // This is important because we'll use it as a component later // and Component Names must start with a Capital Letter const UserContext = React.createContext(); // Components that need the data tap into the context // by using its Consumer property. Consumer uses the // "render props" pattern. const UserAvatar = ({ size }) => ( <UserContext.Consumer> {user => ( <img className={`user-avatar ${size || ""}`} <div> <UserAvatar user={user} /> {user.name} </div> <div className="stats"> <div>{user.followers} Followers</div> <div>Following {user.following}</div> </div> </div> )} </UserContext.Consumer> ); // ... all those other components go here ... // ... (the ones that no longer need to know or care about `user`) // At the bottom, inside App, we pass the context down // through the tree using the Provider class App extends React.Component { state = { user: { avatar: "", name: "Dave", followers: 1234, following: 123 } }; render() { return ( <div className="app"> <UserContext.Provider value={this.state.user}> <Nav /> <Body /> </UserContext.Provider> </div> ); } }
Here’s the full code in a CodeSandbox.
Let’s go over how this works.
Remember there’s 3 pieces: the context itself (created with
React.createContext), and the two components that talk to it (
Provider and
Consumer).
Provider and Consumer are a Pair
The Provider and Consumer are bound together. Inseperable. And they only know how to talk to each other. If you created two separate contexts, say “Context1” and “Context2”, then Context1’s Provider and Consumer would not be able to communicate with Context2’s Provider and Consumer.
Context Holds No State
Notice how the context does not have its own state. It is merely a conduit for your data. You have to pass a value to the
Provider, and that exact value gets passed down to any
Consumers that know how to look for it (Consumers that are bound to the same context as the Provider).
When you create the context, you can pass in a “default value” like this:
const Ctx = React.createContext(yourDefaultValue);
This default value is what the
Consumer will receive when it is placed in a tree with no
Provider above it. If you don’t pass one, the value will just be
undefined. Note, though, that this is a default value, not an initial value. A context doesn’t retain anything; it merely distributes the data you pass in.
Consumer Uses the Render Props Pattern
Redux’s
connect function is a higher-order component (or HoC for short). It wraps another component and passes props into it.
The context
Consumer, by contrast, expects the child component to be a function. It then calls that function at render time, passing in the value that it got from the
Provider somewhere above it (or the context’s default value, or
undefined if you didn’t pass a default).
Provider Accepts One Value
Just a single value, as the
value prop. But remember that the value can be anything. In practice, if you want to pass multiple values down, you’d create an object with all the values and pass that object down.
That’s pretty much the nuts and bolts of the Context API.
Context API is Flexible
Since creating a context gives us two components to work with (Provider and Consumer), we’re free to use them however we want. Here are a couple ideas.
Turn the Consumer into a Higher-Order Component
Not fond of the idea of adding the
UserContext.Consumer around every place that needs it? Well, it’s your code! You can do what you want. You’re an adult.
If you’d rather receive the value as a prop, you could write a little wrapper around the
Consumer like this:
function withUser(Component) { return function ConnectedComponent(props) { return ( <UserContext.Consumer> {user => <Component {...props} user={user}/>} </UserContext.Consumer> ); } }
And then you could rewrite, say,
UserAvatar to use this new
withUser function:
const UserAvatar = withUser(({ size, user }) => ( <img className={`user-avatar ${size || ""}`} alt="user avatar" src={user.avatar} /> ));
And BOOM, context can work just like Redux’s
connect. Minus the automatic purity.
Here’s an example CodeSandbox with this higher-order component.
Hold State in the Provider
The context’s Provider is just a conduit, remember. It doesn’t retain any data. But that doesn’t stop you from making your own wrapper to hold the data.
In the example above, I left
App holding the data, so that the only new thing you’d need to understand was the Provider + Consumer components. But maybe you want to make your own “store”, of sorts. You could create a component to hold the state and pass them through context:
class UserStore extends React.Component { state = { user: { avatar: "", name: "Dave", followers: 1234, following: 123 } }; render() { return ( <UserContext.Provider value={this.state.user}> {this.props.children} </UserContext.Provider> ); } } // ... skip the middle stuff ... const App = () => ( <div className="app"> <Nav /> <Body /> </div> ); ReactDOM.render( <UserStore> <App /> </UserStore>, document.querySelector("#root") );
Now your user data is nicely contained in its own component whose sole concern is user data. Awesome.
App can be stateless once again. I think it looks a little cleaner, too.
Here’s an example CodeSandbox with this UserStore.
Pass Actions Down Through Context
Rememeber that the object being passed down through the
Provider can contain whatever you want. Which means it can contain functions. You might even call them “actions.”
Here’s a new example: a simple Room with a lightswitch to toggle the background color – err, I mean lights.
The state is kept in the store, which also has a function to toggle the light. Both the state and the function are passed down through context.
import React from "react"; import ReactDOM from "react-dom"; import "./styles.css"; // Plain empty context const RoomContext = React.createContext(); // A component whose sole job is to manage // the state of the Room class RoomStore extends React.Component { state = { isLit: false }; toggleLight = () => { this.setState(state => ({ isLit: !state.isLit })); }; render() { // Pass down the state and the onToggleLight action return ( <RoomContext.Provider value={{ isLit: this.state.isLit, onToggleLight: this.toggleLight }} > {this.props.children} </RoomContext.Provider> ); } } // Receive the state of the light, and the function to // toggle the light, from RoomContext const Room = () => ( <RoomContext.Consumer> {({ isLit, onToggleLight }) => ( <div className={`room ${isLit ? "lit" : "dark"}`}> The room is {isLit ? "lit" : "dark"}. <br /> <button onClick={onToggleLight}>Flip</button> </div> )} </RoomContext.Consumer> ); const App = () => ( <div className="app"> <Room /> </div> ); // Wrap the whole app in the RoomStore // this would work just as well inside `App` ReactDOM.render( <RoomStore> <App /> </RoomStore>, document.querySelector("#root") );
Here’s the full working example in CodeSandbox.
Should You Use Context, or Redux?
Now that you’ve seen both ways – which one should you use? Well, if there’s one thing that will make your apps better and more fun to write, it’s taking control of making the decisions. I know you might just want “The Answer,” but I’m sorry to have to tell you, “it depends.”
It depends on things like how big your app is, or will grow to be. How many people will work on it – just you, or a larger team? How experienced are you or your team with functional concepts (the ones Redux relies upon, like immutability and pure functions).
One big pernicious fallacy that pervades the JavaScript ecosystem is the idea of competition. The idea that every choice is a zero-sum game: if you use Library A, you must not use its competitor Library B. The idea that when a new library comes out that’s better in some way, that it must supplant an existing one. There’s a perception that everything must be either/or, that you must either choose The Best Most Recent or be relegated to the back room with the developers of yesteryear.
A better approach is to look at this wonderful array of choices like a toolbox. It’s like the choice between using a screwdriver or an impact driver. For 80% of the jobs, the impact driver is gonna put the screw in faster than the screwdriver. But for that other 20%, the screwdriver is actually the better choice – maybe because the space is tight, or the item is delicate. When I got an impact driver I didn’t immediately throw away my screwdriver, or even my non-impact drill. The impact driver didn’t replace them, it simply gave me another option. Another way to solve a problem.
Context doesn’t “replace” Redux any more than React “replaced” Angular or jQuery. Heck, I still use jQuery when I need to do something quick. I still sometimes use server-rendered EJS templates instead of spinning up a whole React app. Sometimes React is more than you need for the task at hand. Sometimes Redux is more than you need.
Today, when Redux is more than you need, you can reach for Context.
Redux vs. The React Context API was originally published by Dave Ceddia at Dave Ceddia on July 17, 2018.
🎩 JavaScript Enhanced Scss mixins! 🎩 concepts explained
In the next post we are going to explore CSS @apply to supercharge what we talk about here....
I found explanations to be quite easy to digest, as you were explaining basics (of Context API) first and moved onto more advanced examples as you did in your Pure React book 📕 (which is where I learned most about React).
Thanks! Glad to hear you got a lot out of Pure React too :)
Great article Dave. Well explained. Thanks!
Great article. The examples of Context API usage are very well thought, they really help building the mental bridge between new Context and Redux. | https://practicaldev-herokuapp-com.global.ssl.fastly.net/dceddia/redux-vs-the-react-context-api-1nof | CC-MAIN-2020-24 | refinedweb | 3,472 | 64.41 |
Introduction to PostgreSQL JDBC Driver
While creating a database based application and using any of the databases in your java application, you will need to follow certain steps to use the JDBC (Java Database Connectivity) which is an API i.e Application Programming Interface that helps us to communicate between our java application and our database. The database can be any database like MySQL, PostgreSQL, etc. In this article, we will learn how we can connect our java application with our PostgreSQL database with the help of the JDBC driver.
Pre-requisites
While creating a database-based java application, it is required to have few things installed in your system which are as follows –
- Java JDK toolkit
It can be checked by typing the command java -version in your command which will provide you with the output specifying the version of java available in your system like following.
java -version
If not present, you should firstly install java. Here, we used java version “1.8.0_201”.
- PostgreSQL and psql should be installed on your machine that can be checked by typing the command psql -V that should give output as follows –
psql -V
If not available install it before proceeding with JDBC driver installation. Mine is psql (PostgreSQL) 12.2 (Ubuntu 12.2-2.pgdg18.04+1).
- The last thing is the JDBC driver for PostgreSQL jar file which can be downloaded from the link. We will use it further while establishing the JDBC connection.
Steps for JDBC initialization
- We first need to import JDBC using the import statement –
import java.sql.*;
You should be careful here, you should not import org.postgresql package in your application as doing so will confuse the javac for compiling the source file.
- The second step is where you will need to load your JDBC driver. This can be done in two ways. One by using Class.forName() method and other by passing your driver as a parameter to the JVM while initializing. The second step is more preferable as in case if in your future your application needs to change its database server then it can be done without changing the connection related code easily.
In the first method, we will use the Class.forName() method in the following way –
Class.forName("org.postgresql.Driver");
where org.postgresql.Driver specifies your PostgreSQL JDBC driver usage. This method can give ClassNotFoundException if our driver is not found. This method is most often used in JDBC applications.
The second method consists of passing your JDBC driver as a parameter to the initialization string using -D option as follows –
java -Djdbc.drivers=org.postgresql.Driver example.ImageViewer
- Now is the time to connect to the database. The database is represented by a URL (Uniform Resource Locator) in JDBC applications which can be in either of the three forms while using the PostgreSQL database.
jdbc:postgresql:databaseName
jdbc:postgresql://hostName/databaseName
jdbc:postgresql://hostName:portNumber/databaseName
where
the hostName is localhost by default and if remote is the Ipv6 address of the machine.
portNumber is socket/port address which is by default 5432 for PostgreSQL.
DatabaseName is the name of the database you want to connect to for your JDBC application.
Finally, you can now connect using the statement
Connection dbConnectionObject= DriverManager.getConnection(url, username, password);
- The last step is closing your JDBC connection once you are done with performing all your database related manipulations which can simply be done by closing your Connection object as follows –
dbConnectionObject.close();
Example of PostgreSQL JDBC Driver
Let us consider one example of a JDBC application with PostgreSQL. For this, We will firstly need to create a database in our PostgreSQL database server. We will create a database named educba and will connect to it using our JDBC program in java.
createdb educba;
psql
\l
Create a new file named EducbaJdbcExample.java which will contain program like this –
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
public class EducbaJdbcExample {
public static void main(String[] args) {
try (Connection myConnection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/educba", "postgres", "a")) {
if (myConnection != null) {
System.out.println("Successfully connected to educba database!");
} else {
System.out.println("Sorry!Failed to establish JDBC connection");
}
} catch (SQLException e) {
System.err.format("Current SQL status: %s\n%s", e.getSQLState(), e.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
}
}
The first three statements in our program are for importing the packages required for using the JDBC related methods. The next thing is that we are trying to establish the connection with our PostgreSQL using the following statement –
Connection myConnection = DriverManager.getConnection(
"jdbc:postgresql://127.0.0.1:5432/educba", "postgres", "a")
where 127.0.0.1 stands for localhost i.e same machine address and 5432 is the PostgreSQL port and we want to connect to educba database name and our username and password are ‘a’ and ‘a’ respectively. Here, we have inserted this statement in try because if any exception arises while establishing the connection it will give an immediate exception and display the message related to the exception. If the connection is established then the message saying “Successfully connected to educba database!” will get displayed else “Sorry! Failed to establish the JDBC connection” message will be displayed.
After saving, compiling and running the application if it gives the exception like following –
In case, if you are using Eclipse IDE and create a java class file for your program and the by right-clicking your file ->Run As -> Java application option you can run your program. In that case, it will give the following output. This is because there is no JDBC driver file of PostgreSQL which has downloaded present in our current project.
This is because the JDBC driver is not loaded. In such applications, we will need to load our JDBC driver manually using cp. For this, it is required that your program EducbaJdbcExample .java and the downloaded jar file of JDBC driver for PostgreSQL are stored in the same path if you are running through command line or you have imported jar file in your current project if you are using Eclipse IDE as follows –
Then you can run your application as java application if you are using eclipse –
As can be seen the message on the console is now “Successfully connected to educba database!”. So, we are connected to our database now.
Conclusion
We can connect with our PostgreSQL database from our java application by following all the above steps in a proper manner.
Recommended Articles
This is a guide to PostgreSQL JDBC Driver. Here we discuss the example of PostgreSQL JDBC Driver along with the Steps for JDBC initialization and Pre-requisites. You may also have a look at the following articles to learn more – | https://www.educba.com/postgresql-jdbc-driver/?source=leftnav | CC-MAIN-2020-50 | refinedweb | 1,128 | 55.84 |
While our framework borrows from some design patterns, we feel that games are a very expressive medium. We want you, the reader of this book, to think outside that proverbial, over-used box. While design pattern ideas lend them selves to all manner of application development, we don’t want you to feel hemmed in to using any one set of ideas for creating their games. Our framework gives structure to the overall flow of a game but does not dictate how to code the actual game logic.
Exploring the Framework
The game framework is housed in a reusable package structure. A package structure at its very basic is an organized set of folders that will contain reusable classes. All of the standard class files for using the framwork will be in this package structure. We will update and extend this structure as we proceed through this book. Let’s start by giving you an idea of what classes we will be creating for the framework.
The GameFrameWork.as class
The GameFrameWork.as class is the foundation of the framework. It contains a simple state machine and a basic game loop timer. Our state machine is a simple construct containing a set of state constants to switch the framework between states. States are handled by state functions inside the GameFrameWork.as file. We will employ a variable to reference the current state function. The game timer will use this refernce to call the current state function on each frame tick. We will create states for such things as the title screen, instructions screen, game play, game over, and more. When we create a new game our document class will be an instance of GameFrameWork called Main.as. This Main.as will have an init (short for “initialization”) function that will set up the framework for use. This Main.as class will also act as a sort of message gateway between the game and the framework classes. If you are confused, don’t worry; we’ll be explaining this in greater detail soon.
The FrameWorkStates.as class
This FrameWorkStates.as class will simply contain a set of constant integer values representing the state machine states. When we first create the framework we will have 10 different state constants. All will begin with the STATE_SYSTEM designation. For example, we will have a state that displays the title screen. The state constant for this will be STATE_SYSTEM_TITLE. More states will be added as we progress through the chapters in this book.
The BasicScreen class and SimpleBlitButton helper class
The BasicScreen class will be used to display very simple game state screens. These screens can have a basic background color with transparency (if needed), as well as some text centered on the screen. Each screen can also have a button that needs to be clicked to move to a new state in the state machine. This class is so simple that it will probably never be used without major modification in your own commercial games. We present it here, in its very simple form, for utility purposes. The SimpleBlitButton helper class is used to create a clickable button with rollover and off states. The button is created completely in code with a simple color background for the over and off states to be sed in the BasicScreen class. We do this for simplicity and to demonstrate some Sprite blitting techniques (much more on these later in the book) using a set of BitmapData instances for the background color change of the button on rollover.
The ScoreBoard class and SideBySideScoreElement helper class
The ScoreBoard class displays information for the user during game play. Data such as the current game score, time remaining, and other useful information can be displayed to the user with a very basic look and feel by using this class. It can be used as is, but when you start to make your own commercial games, you might find it useful to extend this class with more functionality. This very basic class is used inside the framework to demonstrate how to use events from a Game instance to update a game score board. The SideBySideScoreElement helper class is used to display a text label and corresponding dynamic text field as a pair side by side on the screen. For example, it can be implemented by the ScoreBoard class to display the word Score followed by the user’s current score.
The Game class
The Game class is a stub style class that all games in the framework will inherit from. It contains the basic variables and functions needed to work with the GameFrameWork class.
The Custom event classes
The framework makes use of events to communicate between classes. The instances of the Game class will use events to communicate with the ScoreBoard and the Main classes. We will create a custom Main.as class for each game. This Main class will be a sub-class (or child) of the GameFrameWork class. Some of the events we will use will be simple events. These are instances of the standard Flash Event class used for basic communication. By this, we mean events that don’t need to send any data along with them. For example, instances of the Game.as framework class will have a constant variable called GAME_OVER. This constant will be used as the name of a simple Event instance that is fired off with the standard dispatchEvent function call. This example GAME_OVER event wil be used to tell the Main.as to move to the game over (STATE_SYSTEM_GAME_OVER) state in the main state loop when the current game has completed. We will also be creating three distinct custom event classes as part of the framework. These will be used to send specific data from the Game class instance to the Main.as (GameFrameWork.as instance) class. The Main.as will act on the data sent and if needed, pass the data to other framework classes. By doing this, we are using Main.as as a sort of message gateway.
The CustomEventButtonId.as class
This custom event will have the ability to pass an identification integer value to the listening function. It is used for cases where multiple buttons share the same listener function. It will be used in the framework (specifically in the GameFrameWork instance, Main.as) to allow BasicScreen instances to each share the same listener functions if they employ a SimpleBlitButton. You will see this when we examine the GameFrameWork class file. It can also be used for any game or application that needs to send a basic integer id along with an Event instance.
The CustomEventLevelScreenUpdate.as class
This custom event will be used by the Game.as class instance to send data to a BasicScreen instance we will create called levelInScreen. The levelInScreen will have the ability to display custom text between each level. The event listnener for this event will change this text with a value passed when the event is fired off. The Main.as (GameFrameWork.as sub-class) will listen for this event and pass the data to the levelInScreen.
The CustomEventScoreBoardUpdate.as class
This custom event will be used by the the Game.as class instance to update the values on the ScoreBoard class instance. The Main.as class will listen to for this event and pass the data on to the ScoreBoard.as class instance.
The framework package structure
We will be organizing all of the code we will create into a package structure. The reusable framework classes will be in one package, and the games we will create will be in a separate package. Let’s to create these two package structures now.
The source folder
Choose a spot on your disk drive of choice, and create a folder called source. This will be the root or base level for all of the code and games we will create in this book.
The classes package
The reusable framework classes will be in a package called classes. Create a folder called classes inside the source folder from the previous step. You should now have a folder structure that looks a little like this: [source] [classes] Next, we will create the actual package that will contain all of the source code for the reusable framework classes. We will name this package com.efg.framework. To create this, you must first create a folder inside the classes folder called com, then a folder called efg inside the com folder, and finally a framework folder inside the efg folder. By the way, the “efg” is an abbreviation for the book title, Essential Flash Games. You should now have a folder structure that looks like this: [source] [classes] [com] [efg] [framework] When we start to create all of the class files necessary for the framework, they will all go into the framework folder. You will see that when we create these classes, the package name will look like this: package com.efg.framework {
The projects package
The second package we will create is called the projects package. You can start this right away by creating a folder inside the root source folder called projects. The projects folder is not going to be a straight package structure like the classes folder. It is organized in a manner to allow individual custom game development using the framework. Inside this projects folder, we are going to create a unique folder for each game in the book. The first game we are going to create is called stubgame. A stub is usually a function or class that contains very little (if any) usable code but is instead a simple placeholder. Our game will be slightly more than a placeholder but not much more. It will be used to demonstrate the basic functionality of the framework. Go ahead and create a folder called stubgame in the projects folder. You should have a projects set of folders that look like this:
[source] [classes] ... [projects] [stubgame] Next, we are going to create two folders, each to hold a different version of our game. Why are we going to do this? This book is meant to support Flash game development with a variety of tools. There are many popular methods to create Flash games with an assortment of tools and code integrated development environments (IDEs). We are going to focus on two such tools in this book: the Flash IDE (the one with the library, timelines, drawing tools, and so on all combined into a single tool) and Flash Develop (a very popular, free IDE made specifically for ActionScript development). You can use any tool with this book, but you will need to follow the documentation specific to your own tool when setting up projects. You will need to pay careful attention to linking the reusable code package structure to your games, because linking may vary depending on the Flash code editor environment you are using. Linking the package to a game is actually a very simple process, but it differs between the various code IDE versions. Jeff does most of his Flash game development Flash Develop using the free Flex SDK that Adobe provides. Steve, on the other-hand, uses the Flash IDE almost exclusively. We have combined our efforts on all of the chapter games to bring you code that will work with both a Flex SDK project and a Flash IDE project.
On that note, the next two folders you will create inside the stubgame folder are called flashIDE and flexSDK. You don’t have to create both for any project. You just need to create the one that works with the tools you are going to use to create Flash games. Each is set up differently, so pay attention to the specifics of the one you will be using the most.
You should now have a projects folder that looks like this:
[projects] [stubgame] [flashIDE] [flexSDK]
The Flash IDE package structure
The Flash IDE package structure begins right inside the flashIDE folder. The package name is very similar to the classes package you saw in the last section. The package structure will be com.efg.games.[game name]. For instance, with the stub game we are going to create in this chapter, the package name will be com.efg.games.stubgame. Go ahead and create those folders now. You should have this package structure when you are complete: [projects] [stubgame] [flashIDE] [com] [efg] [games] [stubgame] [flexSDK]
The Flex SDK package structure
The Flex SDK package structure is very similar to the Flash IDE package structure with one small difference. Flash Develop and other Flex tools use a specific set of folders for organizing their own project structures. To accommodate these and still have a common package structure for our games, we must add the Flash Develop created src folder to the flexSDK folder. You will not have to create the src folder or the package structure by hand, as Flash Develop will create it automatically for you when you start a new project. In the section called “Setting up the game in Flash Develop,” we will go into the details. For now, here is the way the structure will be laid out (including the Flash Develop specific folders such as bin, obj, and lib. If you have used Flash Develop to create a Flex SDK project, you will recognize the following structure: [projects] [stubgame] [flexSDK] [bin] [obj] [lib] [src] [com] [efg] [games] [stubgame] Notice that we have created the exact same package structure inside the src folder as we will use with the Flash IDE. The package name for our game will be com.efg.games.stubgame. The package name in the code for classes in both the Flash IDE and Flex SDK will be the same:
package com.efg.games.stubgame {
The Main.as and StubGame.as files
When we start to add files to the subgame package we will be creating two subclasses (or children) of framework classes that will be unique to our game. The Main.as will be created as a subclass (or child) of GameFrameWork.as framework class. The StubGame.as class will be a subclass (or child) of the Game.as framework class.
Starting a project using the framework packages
You have just seen the basic package structure for both the framework reusable classes and the projects we are going to create. Let’s make use of this right away by creating a project for the stub game. The stub game will be very similar to the Chapter 1 game where the player is tasked with clicking the mouse ten times.
Creating the stub game project in the Flash IDE
Follow these steps to set up stub game using the Flash IDE:
- Start up your version of Flash. I am using CS3, but this will work exactly the same in CS4 and CS5.
- Create a .fla file in the /source/projects/stubgame/flashIDE/ folder called stubgame.
- In the /source/projects/stubgame/flashIDE/ folder, create the following package structure for your game: /com/efg/games/stubgame/
- Set the frame rate of the Flash movie to 30 FPS. Set the width and height both to 400.
- Set the document class to com.efg.games.stubgame.Main
- We have not yet created the Main.as class so you will see a warning. We are going to create this later in this chapter.
- Add the framework reusable class package to the class path for the .fla file
- In the publish settings, select [Flash] -> [ActionScript 3 Setting].
- Click the Browse to Path button and find the /source folder we created earlier for the package structure. Select the classes folder, and click the choose button. Now the com.efg.framework package will be available for use when we begin to create our game. We have not created the framework class files yet, but we will be doing this very shortly.
And these are the steps to create the same project using Flash Develop:
- Create a folder inside the [source][projects][stubgame] folder called [flexSDK] (if you have not already done so).
- Start Flash Develop, and create a new project:
- Select Flex 3 Project.
- Give the project the name stubgame.
- The location should be the /source/projects/stubgame/flexSDK folder.
- The package should be com.efg.games.stubgame.
- Do not have Flash Develop create a project folder automatically. Make sure the Create Folder For Project box is unchecked.
- Click the OK button to create the project.
- Add the class path to the framework to the project:
- Go to the [project] -> [properties] -> [classpaths] menu item.
- Click the add class path button.
- Find the /source folder we created earlier, and select the classes subfolder.
- Click the ok button and then the apply button.
Here are a couple of things to note: For Flex Builder, Flash Builder, or other IDEs, please refer to the documentation provided for that product to create a new project and set the default compile class.
A common method of Flash development is to use the Flash IDE for assets and organization and Flash Develop for code editing. If this is your workflow of choice, you will want to follow the Flash IDE folder and package structure rather than the Flex SDK folder structure.
Creating game timers
There are two basic methods that most Flash developers implement when creating a frame-based game timer. By “frame-based,” we mean a timer that uses the idea of a segment of time broken up into logical slices (or frames) to manage game logic. There are other types of methods for timing game updates, but we will make extensive use of time-slice or frame-based timers in this book. The basic game timer we will use most of the games will attempt to squeeze all processing and screen updates into each segment or frame. We will also explore a time-step timer and a sleep-based timer in chapter 11. The first timer method is the Event.ENTER_FRAME event timer. The standard Event.ENTER_FRAME event handler will attempt to run the game loop at the .swf file’s set frame rate. This very handy game loop timer has been in use for a number of years. The second standard game loop timer method makes use of the Timer class. The Timer class is used to call the game loop at millisecond intervals specified by a delay interval. For example, if the millisecond delay interval is set to 100, the Timer instance would run ten times a second (there are 1,000 milliseconds in a single second). Our framework will begin by using this Timer instance game loop timer. We will do this so we can make use of the TimerEvent.TIMER updateAfterEvent function. As you will see, this function will help smooth out screen updates.
Defining “frame timer tick”
You will see the phrases “frame timer tick,” “timer tick,” and “frame tick” used in this book. When we refer to a “tick” or a “frame tick,” we simply mean one frame’s worth of processing. When we run a game at 30 frames per second, we have 30 ticks or 30 frame ticks. This also means that we only have 33.33 milliseconds (or 1,000/30) inside each tick to do all of our processing.
State Machines
A traditional state machine at its very basic is a mechanism that controls the state, or current actions a system can perform. Sometimes this is called a finite state machine. Finite state machines have traditionally been used to model complex mathematical computations and more recently artificial intelligence. The “finite” in the name refers to the fact that the system can only be in a single state at any one time. Our game framework is built on a simple state machine pattern that employs a separate code function or method for each state. There are many other styles of state machines; some use entire classes for each individual state (sometimes called an object-oriented state machine) and some use a simple switch:case statement block called on each frame tick to control state. We will use a third type that borrows from these two. We call our state machine pattern a function reference pattern. Unlike the object-oriented state machine, our machine will contain a separate method or function for each state inside a single framework class. Each of these state functions will control elements in the framework such as instances of the BasicScreen and Game classes. We will use a switch:case statement to move between states. Unlike the afore mentioned very simple switch/case state machine structures that call this switch/state control structure on each frame tick, we only need to call it when we are switching states. The switch:case we call will simply change the function reference we call on each frame tick. The GameFrameWork.as will contain the state machine that controls overall game flow. This will move our game system between states defined in the FrameWorkStates.as file.
Each individual game package we create will contain a Main.as (in the game’s own package structure) that will extend GameFrameWork.as. We will also create a unique Game.as child class for each game. The Game class children that we create can also employ their own internal state machines based on the function reference pattern when needed.
Richard (Squize) Myles of was one of the first to offer the idea of a function reference state machine for ActionScript 3 on his well-respected blog.
The FrameWorkStates.as class file
This class file is a simple collection of constants that will define the states for the game framework. They will be consumed by the GameFrameWork.as class file. The following code listing shows the entire code for this file; you will want to create this file according to the package structure in the previous section: package com.efg.framework { /** * ... * @author Jeff and Steve Fulton * */ public class FrameWorkStates {; } } The first thing you should notice about this class is the package name in the first line. It conforms to the file system structure we created earlier. No matter if you are using a version of Flash, Flex Builder, Flash Builder, Flash Develop, TextMate, or even plain old Notepad, this package name will be the same. The package name is not depended on the code development environment but the chosen file structure for organizing the code. Save this file in the location we created previously. /source/classes/com/efg/framework/FrameWorkStates.as
The state variables
The state variables are constants that the game loop state machine will use to move between game states. We have set up the most common basic states in this sample file, but you will be able to create as many as you need. As we progress through the chapters, more will be added as necessary.
- STATE_SYSTEM_TITLE: This state is used to display a basic title screen with an OK button for the user to click to move on. Once the instructions are on the screen, the state will change to the next state.
- STATE_SYSTEM_WAIT_FOR_CLOSE: This one waits until the OK button is clicked for any instance of the BasicScreen class.
- STATE_SYSTEM_INSTRUCTIONS: This state is used to display basic instructions with the same OK button as in the SYSTEM_TITLE state. It also changes to the STATE_SYSTEM_WAIT_FOR_CLOSE state until the OK button is clicked.
- STATE_SYSTEM_NEW_GAME: This state will call the game logic class and fire off its game.newGame() function. It does not wait but moves on to the NEW_LEVEL state right away.
- STATE_SYSTEM_NEW_LEVEL: With this state, we can call the game.newLevel() function to set up a new level for the given game.
- STATE_SYSTEM_LEVEL_IN: This state is used to display some basic information, if needed, for the beginning of a level. In this basic game, we simply display the level screen and wait a few seconds before moving on. The wait is accomplished by changing state to the STATE_SYSTEM_WAIT state for the specified number of frame ticks.
- STATE_SYSTEM_GAME_PLAY: This one simply calls the game logic class’s runGame function repeatedly and lets the game take care of its own logic and states.
- STATE_SYSTEM_GAME_OVER: The game over state displays the basic game over screen and waits for the OK button to be clicked before moving back to the instructions screen. It quickly changes state to the STATE_SYSTEM_WAIT_FOR_CLOSE until the OK button is clicked.
- STATE_SYSTEM_WAIT: This state waits for a specified number of frames and then fires off a simple custom event constant called WAIT_COMPLETE.
The GameFrameWork.as will be that parent of our game’s document class. Main.as (the game’s document class) for our games will extend this class and call functions to modify the framework for each unique game. The entire code listing is provided at the end of this section. We will explore it in detail once your have had a chance to type in the code. The location for this file in the package structure is /source/classes/com/efg/framework/GameFrameWork.as
The GameFrameWork.as will be the parent class to the Main.as class we will use for our games, and it’s shown in the following listing. In later chapters, we will add some functions to this file and even create one that uses a completely different timer. The Main.as will subclass this class with the extends syntax and override the blank stub init function we are about to create. This class will also contain all of the state functions that coincide with the state variables in the FrameWorkStates class. All of the functions in the GameFrameWork.as are public so all can be overridden by the Main.as if needed. In this way, we can customize the behavior of the state functions if we need to.
For example, in later chapters, we will want to play music on the title screen. The function call to play the music will need to be added to the systemTitle state function. Not all games will need this though, so we will not add it to the GameFrameWork.as file’s systemTitleFunction. Instead, we will create a new version of the function in Main.as to override the one in GameFrameWork.as. The new one will play the sound needed and then call the systemTitle function inside GameFrameWork.as with the super.systemTitle() function call.
Source Listing 1
The class imports
The class import section contains the necessary Flash core classes needed for the Main class. Notice the package name coincides with the package structure we created earlier in the chapter for the framework: package com.efg.framework {
We also must import all of the classes needed for the framework to run. You will see this put to use shortly.
The variable definitions
The variable definition section defines all of the global scope variables for the class. These include all of the variables needed for the state machine, screens, and the game timer. We will make use of constants to define the current state and a set of variables to hold the state information. These have been be defined on the FrameWorkStates.as file we created in the last section. More states can be added to the basic ones, but these will be sufficient for many games that we will create in this book. There are two special states that are used for the system and wait for button clicks or things like animations to complete. These are the STATE_SYSTEM_WAIT_FOR_CLOSE and STATE_SYSTEM_WAIT respectively. We will also make use of a generic function called systemFunction that will hold the current state function to call in our game loop. Combined with this, we use a set of integer variables to hold the value of the current state (currentSystemState), the last state (lastSystemState) and the next state (nextSystemState) for processing purposes. These states should not be confused with an actual game pause function. This will be handled in a different manner and added to the framework in Chapter 11.
If you are using the Flash IDE and have any assets in the library that need to be exported in the first frame, you must extend MovieClip and not Sprite even if you don’t plan to use the main time line for anything else. We have extended MovieClip for the GameFrameWork so it will work with both Flex SDK and Flash IDE projects.
The state control variables
The control variables keep the system functioning within the context of the current state. The main control variable is an instance of the Function class called systemFunction. This function holds a reference to the current function that will be repeatedly called on each frame tick. This saves us from having to evaluate a switch:case statement on each frame to decide which function to call. The function is changed to a new reference by called the switchSystemState() function and passing a new constant that represents the new state. Optimization! switchSystemState() is the first of many optimizations we will make to the game framework. All of these optimizations will make the Flash games run much more efficiently. These efficiencies in the game framework will allow the actual game code to perform more complex operations and still run with a reasonable frame rate. The currentSystemState integer variable holds a number representing the constant of the current state the system is running. The nextSystemState contains the constant integer value for the state to transition to after this state is complete. The lastSystemState variable holds the integer constant of the previous system state. This is used in the rare occurrence that the game loop needs to return to the previous system state. The lastSystemState variable will become useful when we use a shared state such as STATE_SYSTEM_WAIT. The STATE_SYSTEM_LEVEL_IN state will implement a 30-millisecond delay before moving on to the STATE_SYSTEM_GAME_PLAY state. The nextSystemState will be STATE_SYSTEM_WAIT and the lastSystemState will be STATE_SYSTEM_LEVEL_IN. When the 30-millisecond wait time has expired, the waitCompleteListener function will be called. It will use the lastSystemState to determine where the processing was before the wait was started. You’ll see this in detail later in this chapter when we examine the waitCompleteListener function.
The background fill variables
All Flash applications have a background color of some type. No matter what game we are going to be creating, the framework can control this background color. You should never rely on the background color setting in HTML for your Flash application’s background color. This leaves the HTML embed code with control over major aspect of your application. If you are creating a viral game to be placed on game portals, you will lose control of your game’s background color, and it will default to what ever the game portal operators have selected as the standard background color in their embed code. The framework allows you to override the HTML settings here by placing a simple colored Bitmap behind the entire application. We will simply define a BitmapData object called appBackBitmapData and a Bitmap object called appBackBitmap that will be used to place the BitmapData onto the displayList. We will not define the background in the GameFrameWork.as file, but rather the Main.as subclass of the GameFrameWork will set the background if needed in its init function override.
The timer variables
The timer will control the frame rate of the game and help smooth out the display by employing the TimerEvent.updateAfterEvent method. The frameRate variable will be defined in Main.as as the number of frame ticks per second we want our game timer to run. The most important thing to note is that we are making use of the built-in Timer class (gameTimer). We are not using the standard EnterFrame event. This allows us to create our own frame rate for the game and specify it in the frameRate variable. By doing this, we can control game timer tick rate independent of the .swf file’s frame rate (FPS). The .swf file can have a frame rate setting of 25 (for example), but the game can run at a 30 frame ticks a second. To do this, we first set the frameRate to the desired number of frame update ticks we want per second (30). When Main.as calls the startTimer function (described in detail when we get to the section on the init function), the gameTimer is put into action. First, we will calculate the timerPeriod value as 1000 / frameRate. With the updateAfterEvent function call (in the runGame function), we help to smooth out the render of the screen by asking the Flash display engine to update at the rate of the Timer, not the frame rate set in the .swf. So, going back to our example, if the game SWF is set to run at 25 FPS, and the frameRate is set to 30 ticks, the updateAfterEvent will help to smooth out the rendering of the screen by asking the Flash display engine to update at the timer tick rate (30), not the .swf file’s FPS setting (25).
The timerPeriod will be passed into the Timer instance and the game will attempt to run at this rate. We say “attempt” because if the game includes too many on screen moving objects or more logic than can be computed inside the timerPeriod number of milliseconds (or a combination of both), then there will be a noticable slowdown in the game screen updates. In later chapters, we will add functionality to the runGame function to mitigate some of these issues.
The screen definition variables
The screen definition variables create instances of our BasicScreen class. This is a rather simple class that allows a single positional text box and an OK button on the screen. We will use this simple screen for the title, instructions, level, and game over screens. We will customize each screen when we create the init function override in our game’s Main.as class. Note that the levelInText is a special variable. Setting this string to a default value will allow the leveInScreen to display some default text along on each new level. This text can be combined with dynamic text to create a screen that says something like Level 1 with the word “Level” being the default text and the number “1” being the dynamic text. public var titleScreen:BasicScreen; public var gameOverScreen:BasicScreen; public var instructionsScreen:BasicScreen; public var levelInScreen:BasicScreen; public var levelInText:String; public var screenTextFormat:TextFormat; public var screenButtonFormat:TextFormat; We also create two TextFormat objects that will be used for defining the format of the text on the screens and the format of the button text.
The ScoreBoard variables
The scoreBoard instance of the ScoreBoard class will handle a simple heads up display (HUD) for the user with information such as the current score. It is a simple framework class that will be customized in the init function override in each game’s Main.as class. The changes will depend on the game that is to be created. We also define a TextFormatObject for the basic look of the text for our scoreboard text: scoreBoardTextFormat.
The Game object variable
The Game object, represented by the variable simply named game, is an instance of the Game class. The Main.as class’s init function override will inistantiate this. For example, the StubGame.as we will create for the game in this chapter will be a child of the Game.as base class. It will override some of the Game.as base classes and hold the custom logic for the game. //Game is our custom class to hold all logic for the game. private var game:Game;
The wait variables
These variables are used for the simple wait period in the STATE_SYSTEM_WAIT state. waitTime can be set to a different value each time it is used. 30 is the default. We have set the frame rate for our application framework to 30 frames per second, so this would be a one second wait time. 30 frame ticks equals 1 second of time in our game timer if the frame rate is set to 30. waitCount is incremented each frame when a wait is occurring. When waitCount==waitTime, the control moves to the next state. //waitTime is used in conjunction with the STATE_SYSTEM_WAIT state // it suspends the game and allows animation or other processing to //finish private var waitTime:int = 30; private var waitCount:int=0;
The constructor function definition
The constructor for GameFrameWork.as does not contain any code. It is simply a placeholder. We will subclass GameFrameWork.as to create the unique Main.as for each game. The Main.as constructor will contain code to call the init function override. public function GameFrameWork() {}
The init function definition
The init() function is simply a stub to be overridden by the Main.as subclass of GameFrameWork.as.
The setApplicationBackGround function definition
This function accepts in parameters to create a basic back ground for the game. The width, height, transparency Boolean, and color values for the back ground are passed and used to instantiate the appBackBitmapData and place it on to the display list.
The startTimer function definition
This function will be called by the Main.as subclass inside its init function. It will use the frameRate variable to create the timerPeriod. Since the timerPeriod must be expressed in milliseconds (1,000/1 of a second equals a timerPeriod of 1000 or a single second), we simply divide the frameRate into 1,000 to get the number of times per second that the timer must run. In the case of a frameRate that is set to 30 ticks for example, the timerPeriod would be 33.33.
The runGame function definition
The runGame function is the core of the state machine. Once the systemFunction has been set with the switchSystemState (discussed next) function call, the runGame function will call it repeatedly at the set timerPeriod rate every 33 milliseconds (or so) for or frame rate of 30. public function runGame(e:TimerEvent):void { systemFunction(); e.updateAfterEvent(); } The e.updateAfterEvent() function call tells the Flash player to make an extra screen update after the frame tick is over, rather than waiting for the next system frame update to occur. System frame update events happen based on the SWF’s stage frame rate. If we don’t call e.updateAfterEvent here, the screen would not be updated until an actual system frame update event occurs. By using this, we smooth out the look of the screen updates to coincide with out selected gameTimer delay value.
The switchSystemState function definition
While the runGame function is the core of the timer, the switchSystemState() function is the core of the simplified state machine. It is passed a constant value for the state. Using that value, it switches the systemFunction reference accordingly. The switchSystemState function is used to change the current systemFunction of the timer for the next frame timer tick. A reference to one of the state constants is passed into the function, and it acts on it to change the systemState variable. It also changes the lastSystemState and nextSystemState variables. As a refresher, here are the constants from the variable definition section of this FrameWorkStates.as class:; We first set lastSystemState = currentSystemState, so we can have a reference if needed to switch back to previous state. This might occur in circumstances where we need to jump to the STATE_SYSTEM_WAIT state for a period of time and then jump back to the state we were in before the wait. The systemLevelIn function is a good example of this. Once we get to the systemLevelIn function, we want to wait a specified number of milliseconds before removing the levelInScreen from the display. Once the wait is over, the WAIT_COMPLETE event is fired off. The waitCompleteListener function will need to know what the previous systemState was before the wait so it can determine what to do next. We then set currentSystemState = stateval. The stateval was passed when we called the switchSytemState function. This forces the switch/case statement to set the current systemFunction to the function we want to repeatedly call in our loop. We will now start with the first function state the loop calls, the systemTitle function.
The systemTitle function definition
The systemTitle function sets up the display of the title screen and then jumps to a common state used for all button clicks that close the BasicScreen windows STATE_SYSTEM_WAIT_FOR_CLOSE We have not looked at the set of functions that control the STATE_SYSTEM_TITLE, STATE_SYSTEM_INSTRUCTIONS, SYSTEM_LEVEL_IN, and STATE_SYSTEM_GAME_OVER states in detail yet, so let’s do that now. There are two basic screen types represented:
- Those that wait for a click of the OK button: titleScreen, instructionsScreen, and gameOverScreen
- Those that wait a predefined time to display the screen before moving on: levenInScreen
titleScreen.addEventListener(CustomEventButtonId.BUTTON_ID, okButtonClickListener,false, 0, true);
All of the BasicScreen instances share the same okButtonClickListener function. The custom event passes the id value of the BasicScreen instance to this listening function. The id value is used to determine which screen the button was on and then moves the state machine to a new state based on this evaluation.
The systemTitle, systemInstructions, and systemGameOver functions all look very similar. We’ll take a look at those in a bit. First, let’s examine the waitForclose and okButtonClickListener functions.
The systemWaitForClose function definition
The systemWaitForClose() function is associated with the STATE_SYSTEM_WAIT_FOR_CLOSE state. It simply does nothing until the OK button on a screen is clicked. This is the simplest function that you will encounter in this book. It does absolutely nothing! It is just a placeholder that the game loop can call while waiting for the OK button to be clicked.
The okButtonClickListener function definition
The okButtonClickListener function is used to determine what to do when an OK button on one of the various BasicScreen instances is clicked. It switches to the nextSystemState when complete. This “listener” function is only fired off when it receives a CustomEventButtonId.BUTTON_ID event.
No matter which OK button was clicked (on any of the three screens that we will define with them), we remove the event listener before we change state. Even though the same listener is used for both the title and the instructions screens (for example), and we remove it from the title screen before adding it again in the systemInstructions function. We do this to be sure we never have extra listeners hanging around. Unused listeners waste memory and can slow down processing. This function shows how we can share a single listener for the OK button click on three different screens (title, instructions, and game over). We switch on the id value passed from CUSTOMEVENT_OK_CLICKED.
No matter which screen we were on, the last line of the function calls the switchSystemState function and passes in the nextSystemState variable.
The systemInstructions function definition
The systemInstructions function is used to display the instructions screen to the user. It is associated with the STATE_SYSTEM_INSTRUCTIONS state. It is called a single time and then processing is passed to the STATE_SYSYEM_WAIT_FOR_CLOSE state. The systemInstructions function is very similar to the systemTitle function. In fact, they are almost identical with a few minor changes. We first add the systemInstructionsScreen to the displayList with an addChild call.
We also setup a listener for the same CustomEvent that the titleScreen used and we switch to the STATE_SYSTEM_WAIT_FOR_CLOSE state. Again, this state does nothing but let the system wait for the CustomEventButtonId.BUTTON_ID on an instance of the BasicScreen class. Finally, we switch to the STATE_SYSYEM_WAIT_FOR_CLOSE on to wait for the OK button to be clicked. We also set the nextSystemState to be evaluated and used once the OK button is clicked.
The systemGameOver function definition
The systemGameOver function displays the gameOverScreen. It is associated with the STATE_SYSTEM_GAMEOVER state and waits for the OK button click shared with the other BasicScreen instances. We take a look at the systemGameover function now, because it uses the BasicScreen instance gameOverScreen in a similar manner as the titleScreen and instructionsScreen instances. The systemGameOver state is set in Main when the Game class instance sends out the simple custom event called GAME_OVER. In the next section, we will see the Main class set up to listen for this event from the Game class.
The sytemGameOver function follows the exact same format as the systemTitle and systemInstructions functions. There is one difference though: it takes care of removing the Game class instance, game, from the display list with a call to the removeChild function.
The systemNewGame function definition
The systemNewGame function is associated with the STATE_SYSTEM_NEW_GAME state. It is called one time and then moves on to the STATE_SYSTEM_NEW_LEVEL state. Its purpose is to add all of the event listeners for communication between the Game class and some other framework classes (such as the ScoreBoard class). It also calls the game.newGame function to allow the Game instance to do its own internal new game related processing. When setting up a new game, we first add our Game class instance (game) to the display list with the addChild function call. This will display the Game.as Sprite (or MovieClip) on the screen. Next, we set up some basic communication between the Game.as and the Main.as classes. We do this by creating four event lsteners. The first two we set up are custom event class instances (classes we will discuss in detail later in the chapter).
The CustomeEventLevelScreenUpdate class allows the passing of a text String instance with the event. The String is used in the Game class to pass the level number (or any text) back to the Main.as class. The Main.as class updates the levelInString variable with the passed in text. We will see this listener function shortly.
The CustomEventScoreBoardUpdate class is used to update the ScoreBoard (another class we will discuss later in this chapter). This event passes data back to the scoreBoadUpdateListener indicating which field on the ScoreBoard to update and what the new value will be. For example: If we wanted to update the player’s score, we would pass back the name of the score field (probably “score”) and the value of the player’s score (example, 5000).
We also create two simple event constants called GAME_OVER and NEW_LEVEL. These will not pass any data back to the listening functions so they will be fired by passing the GAME_OVER or NEW_LEVEL constant into the dispatchEvent function. We do not need custom classes for these types of events.
The systemNewLevel function definition
The systemNewLevel function is associated with the STATE_SYSTEM_NEW_LEVEL state. Its purpose is to call the game.newLevel function and allow the game to start its own internal new level processing. The systemNewLevel function doesn’t do much inside Main. It is merely there to call the Game classes’ newLevel function. This function will be demonstrated when we get to the simple stub game example. It is used to initialize variables and difficulty for the new level. When it is complete, it switches the system state to STATE_SYSTEM_LEVEL_IN.
The systemLevelIn function definition
The systemLevelIn() function is associated with the STATE_SYSTEM_LEVEL_IN state. It displays a new level message for 30 frame ticks and then moves processing on to the STATE_SYSTEM_GAME_PLAY state. Using systemLevelIn is by no means the only method of forcing the state machine to wait. There are a number of third party custom classes and tools such as TweenMax that can be used for the synchronization of clips and tweens between screens and states. We have added this simple wait state to the state machine for it to be complete framework. The state machine is designed to be easily updated with new states and system functions. Feel free to implement any custom or third-party library or tools that will make your job easier.
The systemLevelIn function is used to allow the developer to display some sort of special text or animation as a precursor to each game level. It employs the use of the STATE_SYSTEM_WAIT state. It is set right after the levelInScreen is added to the display list. The levelInScreen is a BasicScreen instance that does not use the OK button. Instead, it simply waits for the specified waitTime (30 frame ticks in this example) and then fires off the WAIT_COMPLETE simple custom event. The Main class listens for this event and calls the associated listener function. The text on this screen is a combination of the levelInText variable we created in the variable definition section and text passed through the CustomeEventLevelScreenUpdate event. The levelIntext can be set in the init function override of the Main.as (GameFrameWork.as child class). It will be combined with the text passed from the event to create the text on the levelInScreen. We will examine the listener function that does this shortly.
The systemWait function definition
The levelInscreen is very similar to the instructionsScreen, but instead of using the STATE_SYSTEM_WAIT_FOR_CLOSE state, it uses the STATE_SYSTEM_WAIT state. What’s the difference? The STATE_SYSTEM_WAIT state calls a function that counts for a specified number of frame ticks before moving on to the nextSystemFunction rather than waiting for the click of the OK button. When the systemState is switched to the STATE_SYSTEM_WAIT state, it calls the systemWait function repeatedly (on each frame tick) until the waitCount is greater than the waitTime set in the systemLevelIn function. When the waitCount is reached, we dispatch a WAIT_COMPLETE event that calls the waitCompleteListener (see the next section). Currently, there is only one systemState that uses the systemWait function, so there is only one item in the case statement. We could add many states that use this systemWait function though, so we have it set up for later expansion. The waitCompleteListener function definition The waitCompleteListener function is triggered when the WAIT_COMPLETE event is fired off from the levelInScreen. It can be used for more screens by updating the switch:case statement.
Once the waitCompleteListener fires off, it switches on the lastSystemState because the currentSystemState is now the STATE_SYSTEM_WAIT. This allows us to share a single listener function for all uses of the WAIT_COMPLETE event. It then switches state to the nextSystemState when it calls switchSystemState(nextSystemState). In this example, the nextSystemState is systemGameplay.
The systemGameplay() function definition
The systemGameplay function is the heart of the gameTimer. It is associated with the STATE_SYSTEM_GAME_PLAY state. The game.runGame function is called on each frame tick when systemGamePlay is the systemFunction reference. The Game class instance (game) will handle all of the game’s processing within the game.runGame function. private function systemGameplay():void { game.runGame(); }
The custom event listener functions
The last four functions inside GameFrameWork.as are listener functions for simple and complex custom events that are needed by the Game instance class to communicate with Main class, as well as the levelInScreen and scoreBoard class instances. We’ll briefly explain each here so you have a complete version of all the Main.as code in one place. Their use inside those classes will be examined later as we go through the Game->ScoreBoard, and CustomEvent classes.
The scoreBoardUpdateListener function definition for Main.as
The scoreBoardUpdateListener receives updates from the Game class instance that are passed to the ScoreBoard through a CustomEventScoreBoardUpdate instance. The scoreBoardUpdateListener passes data, represented by a simple key/value pair of String object class instances to the ScoreBoard class instance. The element variable will contain a string value representing a constant that we will define in the Main.as (GameFrameWork.as child class). The constant will be the id string name of the element on the scoreBoard to update. The value variable passed will be a string representing the value to show on the scoreBoard for the corresponding TextField. It’s constructed to allow the Game class instance and its associated classes to update the ScoreBoard class instance without having to maintain a reference to it. This allows the Game and its associated classes to remain decoupled from the Main.as and the basic framework classes. We will see the same thing with the levelInScreen a little later. Why is the ScoreBoard part of the framework and not part of the Game class? We wanted to have the ScoreBoard be part of the Main class game framework because the Game class instance is not the only object that might interact with the ScoreBoard. We do not implement it in this simple example, but the Main might have other data such as a system-held high score, links out, or even a frame counter in the ScoreBoard.
Why decouple the scoreboard from the game class instance? It is true that we could make calls directly to the ScoreBoard from Game by using the root or parent attribute of the Game class. While this is certainly possible, if we decouple the Game class from the ScoreBoard class, then the Game class will be reusable across multiple frameworks (even your own) with no need to use our framework. The new framework would just need its own ScoreBoard or the Game would need to implement its own.
The levelScreenUpdateListener function definition for Main.as
The levelScreenUpdateListener allows the Game class to update the text on the levelInScreen. Like the scoreBoardUpdateListener, the levelScreenUpdateListener function is used to pass data from the Game class instance to the levelInScreen. When the Game class updates the level value using its own newLevel function, the levelInScreen must also update its text so the correct level number will be shown on the screen during the systemLevelIn function. The predefined default String variable, levelIntext will be combined with the passed in value:
levelInScreen.setDisplayText(levelInText + e.text);
The gameOverListener function definition for Main.as
The gameOverListener listens for the Game.GAME_OVER simple custom event and then changes the framework state accordingly. When the Game class instance fires off the GAME_OVER simple custom event, the Main listens for it and runs this function. It cleans up all of the game-related listeners by removing them and then changes state to the STATE_SYSTEM_GAME_OVER state which was discussed earlier
The newLevelListener function definition for Main.as
The newLevelListener listens for the Game.NEW_LEVEL simple custom event and changes the state accordingly. The newLevelListener listens for the Game class instance to fire off the simple custom event, NEW_LEVEL. It then changes the systemState to the STATE_SYSTEM_NEW_LEVEL state.
Framework classes beyond Main
The framework does not rely on FrameWorkStates and the GameFrameWork classes alone. We are now going to define and explain the classes that make up the BasicScreen (and its helper classes), ScoreBoard, and the custom event classes. We have discussed all each of these briefly in the GameFrameWork.as class description. Now, we take a look at each in greater detail.
The BasicScreen class
All of the simple screens in this basic game framework are created using a very simplified BasicScreen class. The BasicScreen class can become a parent class for more elaborate screens, but in the basic framework, it is very simple. Each screen contains some text positioned on the screen, an OK button if needed and a background color. That is all. If the OK button is needed, there is an event inside the BasicScreen class that is fired off, and it, in turn, fires off its own event to tell GameFrameWork class that it has been clicked. This makes use of a custom event class instance (okButtonClickListener) that we will create in the next section. You should save this class file in the folder structure we created earlier in the chapter to correspond to the framework package.
/source/classes/com/efg/framework/BasicScreen.as
Here is entire code listing for this class.
Class import and variable definition section for BasicScreen
The class import section imports the necessary core Flash classes we will see in action shortly. The one custom class the BasicScreen class makes use of is the CustomEventButtonId class. We will dissect this class in detail later in the chapter, but for now, know that we dispatch an instance of it if the OK button is clicked on any of the instances of this BasicScreen.
The variable definition section of the BasicScreen class creates variables to hold data for the three optional pieces of the BasicScreen:
- The background color BackGroundBitmapData, which is associated BackGroundBimap
- The text to display on the screen, displayText
- The button that will fire off the CustomEventButtonId when clicked, which is an instance of another framework custom class we will create called SimpleBlitButton
The final variable we need is the id integer. This is passed into the BasicScreen instance from Main. It is used in the switch:case inside the GameFrameWork classes’ okButtonClickListener function to change state based on the screen whose OK button was clicked.
Class constructor function definition
The constructor for the BasicScreen class accepts in the basic information needed to set up a screen for display. A screen needs an id value passed in as an integer, as well as the information needed to create the background color for the screen. This is done by passing values needed to customize the backGroundBitmapData variable that was created in the variable definition section. A BitmapData instance needs these four pieces of data passed:
- A width
- A height
- A Boolean (true/false) value to indicate whether or not the BitmapData will use transparency
- A color represented as an unsigned integer (uint).
The first actual line of code might be a little cryptic:
textformat1.align = flash.text.textFormayAlign.CENTER
When we set up the textFormat1 variable, we didn’t set the alignment to center because not all uses of it will be centered. We can change the alignment on the fly, and we do so here before we apply it to the displayText field as its defaultTextFormat. Then, we simply add the text to the screen. In the first init call, there is no text to actually add to the screen. It is added with the setDisplytext function described next. The setDisplayText function is public and is called by the Main class when the BasicScreen instances (title, instruction, game over, and so on) are placed on the display list. This allows the text for the screen to be customized for each showing.
The createDisplayText function definition
By calling the createDisplayText function on a BasicScreen instance, we can turn on a | http://www.gamedev.net/page/resources/_/technical/game-programming/the-essential-guide-to-flash-games-chapter-2-r2751?st=120 | CC-MAIN-2016-30 | refinedweb | 9,713 | 71.75 |
Uniform Initialization and Delegating Constructors
In modern C++, you can use brace initialization for any type, without the equals sign. Also, you can use delegating constructors to simplify your code when you have multiple constructors that perform similar work.
Brace Initialization
You can use brace initialization for any class, struct, or union. If a type has a default constructor, either implicitly or explicitly declared, you can use default brace initialization (with empty braces). For example, the following class may be initialized by using both default and non-default brace initialization:
#include <string> using namespace std; class class_a { public: class_a() {} class_a(string str) : m_string{ str } {} class_a(string str, double dbl) : m_string{ str }, m_double{ dbl } {} double m_double; string m_string; }; int main() { class_a c1{}; class_a c1_1; class_a c2{ "ww" }; class_a c2_1("xx"); // order of parameters is the same as the constructor class_a c3{ "yy", 4.4 }; class_a c3_1("zz", 5.5); }
If a class has non-default constructors, the order in which class members appear in the brace initializer is the order in which the corresponding parameters appear in the constructor, not the order in which the members are declared (as with
class_a in the previous example). Otherwise, if the type has no declared constructor, the order in which the members appear in the brace initializer is the same as the order in which they are declared; in this case, you can initialize as many of the public members as you wish, but you cannot skip any member. The following example shows the order that's used in brace initialization when there is no declared constructor:
class class_d { public: float m_float; string m_string; wchar_t m_char; }; int main() { class_d d1{}; class_d d1{ 4.5 }; class_d d2{ 4.5, "string" }; class_d d3{ 4.5, "string", 'c' }; class_d d4{ "string", 'c' }; // compiler error class_d d5("string", 'c', 2.0 }; // compiler error }
If the default constructor is explicitly declared but marked as deleted, default brace initialization cannot be used:
class class_f { public: class_f() = delete; class_f(string x): m_string { x } {} string m_string; }; int main() { class_f cf{ "hello" }; class_f cf1{}; // compiler error C2280: attempting to reference a deleted function }
You can use brace initialization anywhere you would typically do initialization—for example, as a function parameter or a return value, or with the new keyword:
class_d* cf = new class_d{4.5}; kr->add_d({ 4.5 }); return { 4.5 };
initializer_list Constructors
The initializer_list Class represents a list of objects of a specified type that can be used in a constructor, and in other contexts. You can construct an initializer_list by using brace initialization:
initializer_list<int> int_list{5, 6, 7};
Important
To use this class, you must include the <initializer_list> header.
An
initializer_list can be copied. In this case, the members of the new list are references to the members of the original list:
initializer_list<int> ilist1{ 5, 6, 7 }; initializer_list<int> ilist2( ilist1 ); if (ilist1.begin() == ilist2.begin()) cout << "yes" << endl; // expect "yes"
The standard library container classes, and also
string,
wstring, and
regex, have
initializer_list constructors. The following examples show how to do brace initialization with these constructors:
vector<int> v1{ 9, 10, 11 }; map<int, string> m1{ {1, "a"}, {2, "b"} }; string s{ 'a', 'b', 'c' }; regex rgx{'x', 'y', 'z'};
Delegating Constructors
Many classes have multiple constructors that do similar things—for example, validate parameters:
class class_c { public: int max; int min; int middle; class_c() {} class_c(int my_max) { max = my_max > 0 ? my_max : 10; } class_c(int my_max, int my_min) { max = my_max > 0 ? my_max : 10; min = my_min > 0 && my_min < max ? my_min : 1; } class_c(int my_max, int my_min, int my_middle) { max = my_max > 0 ? my_max : 10; min = my_min > 0 && my_min < max ? my_min : 1; middle = my_middle < max && my_middle > min ? my_middle : 5; } };
You could reduce the repetitive code by adding a function that does all of the validation, but the code for
class_c would be easier to understand and maintain if one constructor could delegate some of the work to another one. To add delegating constructors, use the
constructor (. . .) : constructor (. . .) syntax:
class class_c { public: int max; int min; int middle; class_c(int my_max) { max = my_max > 0 ? my_max : 10; } class_c(int my_max, int my_min) : class_c(my_max) { min = my_min > 0 && my_min < max ? my_min : 1; } class_c(int my_max, int my_min, int my_middle) : class_c (my_max, my_min){ middle = my_middle < max && my_middle > min ? my_middle : 5; } }; int main() { class_c c1{ 1, 3, 2 }; }
As you step through the previous example, notice that the constructor
class_c(int, int, int) first calls the constructor
class_c(int, int), which in turn calls
class_c(int). Each of the constructors performs only the work that is not performed by the other constructors.
The first constructor that's called initializes the object so that all of its members are initialized at that point. You can’t do member initialization in a constructor that delegates to another constructor, as shown here:
class class_a { public: class_a() {} // member initialization here, no delegate class_a(string str) : m_string{ str } {} //can’t do member initialization here // error C3511: a call to a delegating constructor shall be the only member-initializer class_a(string str, double dbl) : class_a(str) , m_double{ dbl } {} // only member assignment class_a(string str, double dbl) : class_a(str) { m_double = dbl; } double m_double{ 1.0 }; string m_string; };
The next example shows the use of non-static data-member initializers. Notice that if a constructor also initializes a given data member, the member initializer is overridden:
class class_a { public: class_a() {} class_a(string str) : m_string{ str } {} class_a(string str, double dbl) : class_a(str) { m_double = dbl; } double m_double{ 1.0 }; string m_string{ m_double < 10.0 ? "alpha" : "beta" }; }; int main() { class_a a{ "hello", 2.0 }; //expect a.m_double == 2.0, a.m_string == "hello" int y = 4; }
The constructor delegation syntax doesn't prevent the accidental creation of constructor recursion—Constructor1 calls Constructor2 which calls Constructor1—and no errors are thrown until there is a stack overflow. It's your responsibility to avoid cycles.
class class_f{ public: int max; int min; // don't do this class_f() : class_f(6, 3){ } class_f(int my_max, int my_min) : class_f() { } };
Feedback
Send feedback about: | https://docs.microsoft.com/en-us/cpp/cpp/uniform-initialization-and-delegating-constructors?view=vs-2019 | CC-MAIN-2019-22 | refinedweb | 992 | 58.11 |
I have a table similar to the following
MY_TABLE(
COL1 VARCHAR,
COL2 VARCHAR,
COL3 VARCHAR,
COL4 VARCHAR,
PRIMARY KEY(COL1, COL2, COL3)
)
where there is a composite primary key mad up of columns COL1, COL2, COL3.
I have the following class structure (none, some non-pertinent code is left out)
@Embeddable
public class MyTablePK implements Serializable
{
public MyTablePK(String COL1, String COL2, String COL3)
{...}
public String getCOL1();
public String setCOL1(String s);
public String getCOL2();
public String setCOL2(String s);
public String getCOL3();
public String setCOL3(String s);
public equals(Object o);
public int hashCode();
}
@Entity
@Table(name = "MY_TABLE")
public class MyTable
{
@EmbeddedId
public MyTablePK getID();
protected void setID(MyTablePK id)
@Column(name = "COL4")
public getCOL4();
public setCOL4(String COL4);
}
I can create one of these and persist it using em.persist and that works fine. Now assume I know I have a row in the DB where COL1 = 'val1', COL2 = 'val2', and COL3 = 'val3'. When I try to then create a PK with those valuse and then use the EnittyManager to find it using the find method it returns null:
MyTablePK pk = new MyTablePK("val1", "val2", "val3");
// return null
MyTable mt = entityManager.find(MyTable.class, pk);
However when I use a Query I can find the object in the following manner:
MyTable mt = entityManager.createQuery("from MyTable m where m.ID.COL1 = ?1 and m.ID.COL2 = ?2 and m.ID.COL3 = ?3")
.setParameter(1, "val1")
.setParameter(2, "val2")
.setParameter(3, "val3).getSingleResult();
the entity is returned properly. Then if I take the returned entity and do the following it works:
// now returns proper value
MyTable mt2 = entityManager.find(MyTable.class, mt.getID());
I have compared the primary key that I manually composed and the one that is returned from mt.getID and they appear to be the same ( when comparing them with the equals method it returns true and their hash codes are the same), so how come the manually created one does not work in the find method?? Is this a bug or am I doing something wrong?? | https://developer.jboss.org/message/357442?tstart=0 | CC-MAIN-2019-09 | refinedweb | 341 | 59.13 |
Opened 5 years ago
Closed 5 years ago
#17010 closed Uncategorized (invalid)
unittest2 conflicted with nosetest
Description (last modified by russellm)
I use nosetest version 1.0.0. I have to change the source code of Django to make nosetest run:
C:\Python25\Lib\site-packages\django\test\testcases.py line 243 changed to :
import unittest class TransactionTestCase(unittest.TestCase):
Change History (1)
comment:1 Changed 5 years ago by russellm
Note: See TracTickets for help on using tickets.
Marking invalid, because you have proposed a solution without describing the actual problem. On top of that, the solution you propose will break other features in Django, because importing unittest as you suggest won't return the library required.
Feel free to reopen this ticket if you want to provide a clear set of instructions for reproducing the problem you are seeing. If you want to propose a solution, that's fine, but we aren't going to apply a patch without a clear understanding of what it is the patch is trying to achieve, and why. | https://code.djangoproject.com/ticket/17010 | CC-MAIN-2016-30 | refinedweb | 176 | 59.64 |
Getting Started with Silverlight UI Automation
When thinking about Silverlight applications and automated testing, there are a couple of different approaches that come to mind:
To get started, let's use a simple application and demo some basic automation scenarios like button click and set text. Then we will expand into more advanced topics and scenarios. Let's take the following simple Silverlight application that contains a button and a text box. When you click the button, it simply displays hello in a text block on the canvas. The application looks like this:
To automate the application above to set the text, click the button and then verify the hello text in Telerik Testing Framework, we can simply write the following code using the Silverlight Extension (which resides under ArtOfTest.WebAii.Silverlight).
[TestMethod] public void SLDemo() { //Enable Silverlight Settings.Current.Web.EnableSilverlight = true; // Launch a browser instance Manager.LaunchNewBrowser(); // Navigate to the page ActiveBrowser.NavigateTo(""); // Get an instance of our Silverlight app. SilverlightApp app = ActiveBrowser.SilverlightApps()[0]; // Set the text of the text box app.FindName<TextBox>("myName").Text = "Telerik"; // Click the button app.FindName<Button>("myBtn").User.Click(); // Verify the text Assert.IsTrue(app.Find.ByTextContent("p:Hello").TextContent.Equals("Hello Telerik")); }
<TestMethod> _ Public Sub SampleWebAiiTest() 'Enable Silverlight Settings.Current.Web.EnableSilverlight = True ' Launch a browser instance Manager.LaunchNewBrowser() ' Navigate to the page ActiveBrowser.NavigateTo("") ' Get an instance of our Silverlight app. Dim app As SilverlightApp = ActiveBrowser.SilverlightApps()(0) ' Set the text of the text box app.FindName(Of TextBox)("myName").Text = "Telerik" ' Click the button app.FindName(Of Button)("myBtn").User.Click() ' Verify the text Assert.IsTrue(app.Find.ByTextContent("p:Hello").TextContent.Equals("Hello Telerik")) End Sub
Let's take a closer look at the code above line by line:
Line 8-12
This is basic code that launches the browser and navigates to a specific page.
Line 14 (SilverlightApp app = ActiveBrowser.SilverlightApps()[0];)
As soon as you include the Silverlight extension namespace in your test, (ArtOfTest.WebAii.Silverlight), the 'SilverlightApps()' extension method is added to the ActiveBrowser. The extension method offers you a list of all Silverlight applications found on that page. The extension method returns a list that has two accessors. An index accessor that takes an int (as shown above) and a string accessor that takes a hostid [The ID of the HTML element that contains the
Line 17 (app.FindName
("myName").Text = "Telerik";)
As soon as you have an instance of a SilverlightApp, you now have full access to the application including the entire VisualTree. The app offers a short-cut method 'FindName', that can be used to search the application using an element name. In the above sample, given that the TextBox has a name associated with it, we can use FindName to locate it. The SilverlightApp object offers two versions of 'FindName': The first is a generic method that can return a strongly-typed object of the element (As shown above , i.e. a Button, a TextBox, a Grid, etc). The second is simpler and returns the base FrameworkElement object. We will discuss the strongly-typed object model offered in Silverlight Extension later.
To go back to the line above, we are simply accessing the TextBox that has a name 'myName' and then setting its Text property to "Telerik". Note that given we are accessing a property on the element, this is analogous to SetText on a DOM element in Telerik Testing Framework automation. You are not really typing the text in the textbox but rather setting the Text property inside the application to that text. Our extension enables you to access and set properties directly against any FrameworkElement. If we wanted to simulate real typing of the text we would have written code like this:
app.FindName
("myName").User.TypeText("Telerik", 50);
Line 20 (app.FindName<Button>("myBtn").User.Click();)
Same as above in terms of accessing the button. The difference here is that we are using the 'User' object to click the button. The User object is present on all elements that inherit from FrameworkElement and offers real user interactions with Silverlight elements. So a click using the 'User' object will actually move the mouse over that button and click it. That is exactly what this line does.
Line 23 (Assert.IsTrue(app.Find.ByTextContent("p:Hello").TextContent.Equals("Hello Telerik"));)
Now that the button is clicked, we need to verify that the message is correct. The difference here is that we can't really use FindName to locate the TextBlock because the TextBlock doesn't really have a name. The SilverlightApp object offers extensive search support within the VisualTree beyond FindName() by utilizing similar approach to the Find object off the ActiveBrowser (that is used for HTML DOM searches) but adapted to specific XAML search scenarios.
In our code above, we are searching for a TextBlock (All Find.xxText() routines return TextBlocks) that partially contains 'Hello', hence 'p:Hello' (Similar to Find.ByContent in HTML search). Once we find the TextBlock, we then verify that the Text of that label is actually 'Hello Telerik' using the Assert.IsTrue.
Now that we understand this sample, let's dig into some of the key objects available in the Silverlight Extension.
There is a new Setting.EnableSilverlight flag that needs to be set to enable WebAii to connect to Silverlight applications. By default this setting is not on. Setting this flag will activate the built-in proxy that we use to detect Silverlight applications.
Limitations:
On Vista, if you are automating an external website, then make sure to add the URL to your Trusted Websites list in IE.
Our automation supports Silverlight 2.0 (and above). We do not support any previous versions.
The automation only supports the XAP deployment method. EnableHtmlAccess needs to be set to 'True' on your application.
There are known issues with Silverlight applications that attempt to perform web service calls within the application.
EnableHtmlAccess needs to be set to 'True' on your application.
The application needs to be running off http:// not C:...
When using localhost as your server name, it must end with a trailing '.' character e.g.. | http://docs.telerik.com/teststudio/testing-framework/write-tests-in-code/silverlight-wpf-automation-wtc/silverlight-ui-automation | CC-MAIN-2016-18 | refinedweb | 1,024 | 57.77 |
From: David Abrahams (dave_at_[hidden])
Date: 2005-08-19 11:02:02
"Marcin Kalicinski" <kalita_at_[hidden]> writes:
>> I can't speak for all of these, but some of them are libraries that
>> don't have their own namespace (e.g. enable_if). As long as enable_if
>> is directly in namespace boost, it makes sense that its detail is in
>> boost::detail.
>
> I don't subscribe to that. I think details of every distinct library should
> be in a separate namespace.
I agree, but until enable_if is moved out of namespace boost and
the boost "utility library" umbrella, it isn't a distinct library.
That's a separate (though real) problem.
> The reason is detail stuff is not documented and changes frequently,
> so no library writer can actually add safely any new name to
> boost::detail. This means that boost::detail should not exist at
> all, unless it is used only by 1 library.
That leaves common implementation facilities that don't "belong" to
any one library (e.g. detail/indirect_traits.hpp) out in the cold.
> Detail name clashes can be very frustrating because they only
> manifest when certain header file combinations are included into one
> translation unit.
In theory. We haven't actually had a problem with it that I've noticed.
> While libraries residing in boost::libraryname can use
> boost::libraryname::detail, the ones that are in boost namespace
> directly could safely use someting like boost::libraryname_detail.
Sure. But should anything really be in the boost namespace directly?
I don't think very much should. I don't mind the idea of bringing
some things in with using declarations, though.
-- Dave Abrahams Boost Consulting
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/2005/08/92231.php | CC-MAIN-2019-43 | refinedweb | 296 | 66.54 |
Re: Open source C# namespace to convert many audio formats
From: Daniel O'Connell [C# MVP] (onyxkirx_at_--NOSPAM--comcast.net)
Date: 09/20/04
- ]
Date: Mon, 20 Sep 2004 13:04:54 -0500
"gilad" <gilad@discussions.microsoft.com> wrote in message
news:8FE33174-B74A-4B54-941A-95C2072FE547@microsoft.com...
> "Daniel O'Connell [C# MVP]" wrote:
>
>> I will say you probably will not get away with it. Personally I would
>> *not*
>> use your library simply because its naming conventions are so at odds
>> with
>> those I am used to. It makes the library seem written by someone who
>> does'nt
>> know what he's doing.
>
> But if you were a programmer who seriously needed the functionality of the
> library, would you still balk at the style? It doesn't seem likely. You'd
Not if it was vital, though I would probably fire off a courtesy email to
the maintainer suggesting he learns proper naming conventions.
However, except in the rare case that a library is the only available that
supports something, I certainly would turn it down in favor of a competitor
that followed conventions.
> probably shrug your shoulders and shake your head, and use it. And as for
> it
> having the appearance of being "written by someone who does'nt know what
> he's doing", isn't the actual code logic going to tell this rather than
> the
> style? If I'm doing everything correctly as far as interfacing the DLLs,
> construction of objects, etc, and yet decide to use a slightly different
> naming convention (because it is style we're talking about here isn't
> it?),
> doesn't that say whether or not I "know what I'm doing"? Breaking a style
> convention could also be considered being a 'rebel'.
>
It could be considered a rebellion, but more times than not its simply
"Damn, this guy didn't even bother reading the most basic document". If you
couldn't be bothered to read a styles document, why should I think you took
the time to learn initalization, property, and event patterns?
For the record, I know you have read it, but that is the appearance that is
often taken from code that is not named along with standard style.
>> While I understand you are used to perl's naming conventions, those *are*
>> perl's naming conventions and are not a very good choice in a platform
>> that
>> doesn't use them.
>
> Like I said, I was influenced by this style convention, not using it
> explicitly. And I have alternated the Perl style in my own projects when
> it
> suited me. Only when I have submitted to a repository like CPAN have I
> conformed entirely. (Largely because the hue and cry that rang out from
> there
> when I didn't.)
>
Within your own code, its one thing, but for open source projects
especially, you should look into using standard conventions. 90%+ of users
are going to expect those conventions, meaning some potential contributers
aren't going to contribute due to style alone(if its bad enough, I won't
even bother tryign to dechiper it).
>> Anyway, while I can see you're worried about shift key, a good number of
>> characters you have to use commonly in C# code require shift, inclufing
>> _.
>> Whats the difference in typing
>>
>> something_else and somethingElse? Same number of shift presses, after
>> all.
>
> You got me there. I do use underscores. But I only do it where I need to
> separate words for clarity (what I consider clarity anyway), so a lot of
> my
> variables were pretty short and without the underscore (which seems to
> draw a
> lot of criticism too; see below). The convention of C# uses long names
> most
> times, and at least have one shift operation for every named thing.
>
One of the many code clarity guidelines: Use variables that mean something.
LOL. Its just an expectation of good code.
Personally, I use short, but complete variable names. When I'm dealing with
just one array or somesuch, I will use just
int index;
or
int count; (depending). But if the method has a couple of indexers or loops,
I'll do
int charIndex;
int stringIndex;
int charCount;
int stringCount;
or what have you.
Parameters should be fairly clear, but I don't think they should be too
long. XML docs should be the primary source of information about a
parameter, not its name.
>> You classes should be clearer too, ;). Avoid using abbreviations when you
>> can avoid it.
>
> Sigh. I like abbreviations. So short, so succinct... Okay, thanks for the
Yes, very short...but when I don't know what they mean, they become a
difficult issue for me. So using abbreviations for uncommon terms is a bad
idea. You have to remember that your user isn't going to know everything
about audio and they do not want to have to refer back to docments every
time they run across an abbreviation they don't know off hand.
- ] | http://www.tech-archive.net/Archive/DotNet/microsoft.public.dotnet.languages.csharp/2004-09/4949.html | crawl-002 | refinedweb | 828 | 71.55 |
The 45th international undergraduate Programming Competition (ICPC) Asian regional competition (Kunming)
We only did H, water..
Author's evaluation and partial solution How to evaluate the ICPC Kunming division in 2021?
Partial solution ICPC Kunming travel notes (2021.4.3)
B Chessboard upper and lower bounds minimum cost maximum flow
Title address B Chessboard
Main idea of the title: for an n*m chessboard, you can put black chessboard or white chessboard on it. If you put black chessboard in position (i, j), you will get s b i j sb_{ij} sbij{score, place white pieces and you will get s w i j sw_{ij} swij{score. Only one chess piece can be placed in a grid. We use b i b_i bi represents the number of black pieces in line i, B i B_i Bi = number of black pieces in column i, w i w_i wi indicates the number of white pieces in line i, W i W_i Wi indicates the number of white chessmen in column i. conditions are given
For any line i, b i − w i ϵ [ l i , r i ] b_i-w_i\epsilon[l_i,r_i] bi−wiϵ[li,ri]
For any column j, B j − W j ϵ [ L i , R i ] B_j-W_j\epsilon[L_i,R_i] Bj−Wjϵ[Li,Ri]
Find the minimum score that can be obtained by satisfying the conditions.
The content of network flow is not something that we can solve. Let's put it aside first
Reference blog 2021 ICPC Kunming Regional Competition B. chess board (upper and lower bounds, minimum cost, maximum flow)
C cities interval dp
Title address C cities
Give an array of length n a i ∈ [ 1 , n ] a_i\in[1,n] ai ∈ [1,n] and no element has appeared more than 15 times,
Now you can change the same interval of a number into another number at a time. Ask, how many times do you operate at least so that there is only one number left in array a.
Idea: reference articles 2021 icpc Kunming C. cities (section dp)
It is an obvious problem of interval dp, but direct dp is not feasible. We need to consider how to reduce the number of enumerations.
definition f [ i ] [ j ] f[i][j] f[i][j] indicates [ i , j ] [i,j] [i,j] minimum number of operations to dye one color
f [ i ] [ j ] = m i n ( f [ i ] [ j − 1 ] , f [ i + 1 ] [ j ] ) + 1 f[i][j]=min(f[i][j-1],f[i+1][j])+1 f[i][j]=min(f[i][j−1],f[i+1][j])+1
But when both ends are equal, we can save one operation
f [ i ] [ j ] = m i n ( f [ i ] [ k ] + f [ k + 1 ] [ j ] ) f[i][j]=min(f[i][k]+f[k+1][j]) f[i][j]=min(f[i][k]+f[k+1][j])
This needs to be met a [ k ] = = a [ j ] a[k]==a[j] a[k]==a[j], dye the left into color K and the right into color j
The title is guaranteed k no more than 15 times
So at first, shrink the dots with the same color, and then transfer them
AC Code:
#include <bits/stdc++.h> using namespace std; const int maxn = 5009; int t,n,a[maxn],col[maxn],f[maxn][maxn],top,nxt; int pre[maxn],las[maxn]; int main() { cin >> t; while( t-- ) { cin >> n; top = 0; for(int i=1;i<=n;i++) cin >> a[i]; for(int i=2;i<=n;i++) { if( a[i]==a[i-1] ) continue; else col[++top] = a[i-1]; } memset( pre,0,sizeof pre ); memset( las,0,sizeof las ); col[++top] = a[n]; for(int i=1;i<=top;i++) pre[i] = las[col[i]],las[col[i]] = i; memset( f,20,sizeof f ); for(int i=1;i<=top;i++) f[i][i] = 0; for(int l=2;l<=top;l++) for(int i=1;i+l-1<=top;i++) { int j = i+l-1; f[i][j] = min( f[i+1][j],f[i][j-1] )+1; for(int k=pre[j];k>=i;k=pre[k]) f[i][j] = min( f[i][j],f[i][k]+f[k+1][j]); } cout << f[1][top] << endl; } }
H Hard Calculation simple question
The team leader said there was no need to tidy up. I said no. how can such a difficult problem be incomplete?
Title address H Hard Calculation
The first ICPC held in 2021 will be held once a year, and the nth will be held in that year.
Idea:....
AC Code:
#include <bits/stdc++.h> #define ll long long #define INF 0x3f3f3f3f using namespace std; int main() { int n; cin >> n; cout << 2020+n << endl; return 0; }
I Mr. Main and Windmills computational geometry
Title address I Mr. Main and Windmills
Mr.Main went from s to t by train and passed many windmills.
The train runs in a straight line.
With the running of the train, the position of the windmill will change relatively in the field of vision of Mr.Main.
Now give the coordinates of the windmills. Please find the coordinates of the train when the relative position of the h windmill and other windmills changes k times.
Idea: just take the intersection of the line between two windmill coordinates and the s to t line segment, and then sort it. But we didn't find the intersection of the line and the line segment at that time..
AC Code:
#include<bits/stdc++.h> using namespace std; const int maxn=1010; const double eps=1e-8; int n,m; double xs,ys,xt,yt; int sgn (double x) { if (fabs(x)<eps) return 0; else if (x<0) return -1; else return 1; } double x[maxn],y[maxn]; vector<pair<double,double> > p[maxn]; //The intersection of the line formed by each point and all remaining points with the bus pair<double,double> jd (double x1,double y1,double x2,double y2,double x3,double y3,double x4,double y4) { if (x1==x2&&y1==y2) return make_pair(1e18,1e18); //Intersection of the straight line composed of (x1,y1),(x2,y2) and the straight line composed of (x3,y3),(x4,y4) double k1=(x1==x2?1e18:(y1-y2)/(x1-x2)); double k2=(y1==y2?1e18:(y3-y4)/(x3-x4)); if (sgn(k1-k2)==0) return make_pair(1e18,1e18); //k1 is 1e18, k2 is not. The answer is x1*k2+b2 if (k1==1e18) { return make_pair(x1,x1*k2+y3-k2*x3); } else if (k2==1e18) { return make_pair(x2,x2*k1+y1-k1*x1); } double b1=y1-k1*x1; double b2=y3-k2*x3; double x=(b2-b1)/(k1-k2); double y=k1*x+b1; return make_pair(x,y); } int cmp (pair<double,double> x,pair<double,double> y) { if (sgn(x.first-y.first)!=0) { return sgn(x.first-y.first)<0; } else { return sgn(x.second-y.second)<0; } } int main () { scanf("%d%d",&n,&m); scanf("%lf%lf%lf%lf",&xs,&ys,&xt,&yt); for (int i=1;i<=n;i++) scanf("%lf%lf",x+i,y+i); for (int i=1;i<=n;i++) { for (int j=1;j<=n;j++) { if (i==j) continue; pair<double,double> it=jd(x[i],y[i],x[j],y[j],xs,ys,xt,yt); if (it.first==1e18) continue;//No intersection if (sgn(it.first-min(xs,xt))<0||sgn(it.first-max(xs,xt))>0||sgn(it.second-min(ys,yt))<0||sgn(it.second-max(ys,yt))>0) continue;//The intersection is outside the line segment p[i].push_back(it); } if (xs<xt) sort(p[i].begin(),p[i].end(),cmp); else if (xs>xt) sort(p[i].rbegin(),p[i].rend(),cmp); else if (ys<yt) sort(p[i].begin(),p[i].end(),cmp); else sort(p[i].rbegin(),p[i].rend(),cmp); } while (m--) { int h,t; scanf("%d%d",&h,&t); //printf("%d\n",p[h].size()); if (t>p[h].size()) { printf("-1\n"); continue; } printf("%.10f %.10f\n",p[h][t-1].first,p[h][t-1].second); } } | https://programmer.group/61963717f07b0.html | CC-MAIN-2022-40 | refinedweb | 1,358 | 60.55 |
#include <deal.II/lac/chunk_sparsity_pattern.h>
Structure representing the sparsity pattern of a sparse matrix. This class is an example of the "static" type of Sparsity patterns. It uses the compressed row storage (CSR) format to store data.
The use of this class is demonstrated in step-51.
Definition at line 247 of file chunk_sparsity_pattern.h.
Declare the type for container size.
Definition at line 253 of file chunk_sparsity_pattern.h.
Typedef an iterator class that allows to walk over all nonzero elements of a sparsity pattern.
Definition at line 258 of file chunk_sparsity_pattern.h.
Typedef an iterator class that allows to walk over all nonzero elements of a sparsity pattern.
Since the iterator does not allow to modify the sparsity pattern, this type is the same as that for
const_iterator.
Definition at line 267 of file chunk_sparsity_pattern.h.
Initialize the matrix empty, that is with no memory allocated. This is useful if you want such objects as member variables in other classes. You can make the structure usable by calling the reinit() function.
Definition at line 25 of file chunk ChunkSparsityPattern in a container, e.g., to write such statements like
v.push_back (ChunkSparsityPattern());, with
v a vector of ChunkSparsityPattern objects.
Usually, it is sufficient to use the explicit keyword to disallow unwanted temporaries, but this does not work for
std::vector. Since copying a structure like this is not useful anyway because multiple matrices can use the same sparsity structure, copies are only allowed for empty objects, as described above.
Definition at line 32 of file chunk_sparsity_pattern.cc.
Initialize a rectangular matrix.
Definition at line 48 of file chunk_sparsity_pattern.cc.
Initialize a rectangular matrix.
Definition at line 60 of file chunk_sparsity_pattern.cc.
Initialize a quadratic matrix of dimension
n with at most
max_per_row nonzero entries per row.
This constructor automatically enables optimized storage of diagonal elements. To avoid this, use the constructor taking row and column numbers separately.
Definition at line 73 of file chunk_sparsity_pattern.cc.
Initialize a quadratic matrix.
Definition at line 82 of file chunk_sparsity_pattern.cc.
Destructor.
Copy operator. For this the same holds as for the copy constructor: it is declared, defined and fine to be called, but the latter only for empty objects.
Definition at line 95 of file chunk_sparsity_pattern.cc.
Reallocate memory and set up data structures for a new matrix with
m rows and
n columns, with at most
max_per_row nonzero entries per row.
This function simply maps its operations to the other
reinit function.
Definition at line 116 of file chunk_sparsity_pattern.cc.
Reallocate memory for a matrix of size
m x n. The number of entries for each row is taken from the array
row_lengths which has to give this number of each row
i=1...
If the number of rows equals the number of columns then diagonal elements are stored first in each row to allow optimized access in relaxation methods of SparseMatrix.
Definition at line 260 of file chunk_sparsity_pattern.cc.
Same as above, but with an ArrayView argument instead.
Definition at line 131 of file chunk ChunkSparsityPattern objects they are initialized with to be compressed, to reduce memory requirements.
Definition at line 174 of file chunk integer as column index and a value of arbitrary type (such a type would be used if we wanted to describe a sparse matrix with one such object), or simply an integer (if we only wanted to describe a sparsity pattern). The function is able to determine itself whether an integers and a value, the first of which we take as column index. As previously, the outer
std::vector could be replaced by
std::list, and the inner
std::map<size_type,double> could be replaced by
std::vector<std::pair<size_type,double> >, or a list or set of such pairs, as they all return iterators that point to such pairs.
Copy data from an object of type DynamicSparsityPattern. Previous content of this object is lost, and the sparsity pattern is in compressed mode afterwards.
Definition at line 183 of file chunk_sparsity_pattern.cc.
Take a full matrix and use its nonzero entries to generate a sparse matrix entry pattern for this object.
Previous content of this object is lost, and the sparsity pattern is in compressed mode afterwards.
Definition at line 225 of file chunk_sparsity_pattern.cc.
Set the sparsity pattern of the chunk sparsity pattern to be given by
chunk_size*chunksize blocks of the sparsity pattern for chunks specified. Note that the final number of rows
m of the sparsity pattern will be approximately
sparsity_pattern_for_chunks.n_rows() * chunk_size (modulo padding elements in the last chunk) and similarly for the number of columns
n.
This is a special initialization option in case you can tell the position of the chunk already from the beginning without generating the sparsity pattern using
make_sparsity_pattern calls. This bypasses the search for chunks but of course needs to be handled with care in order to give a correct sparsity pattern.
Previous content of this object is lost, and the sparsity pattern is in compressed mode afterwards.
Definition at line 295 of file chunk_sparsity_pattern.cc.
Return whether the object is empty. It is empty if no memory is allocated, which is the same as that both dimensions are zero.
Definition at line 320 of file chunk_sparsity_pattern.cc.
Return the chunk size given as argument when constructing this object.
Return the maximum number of entries per row. Before compression, this equals the number given to the constructor, while after compression, it equals the maximum number of entries actually allocated by the user.
Definition at line 328 of file chunk_sparsity_pattern.cc.
Add a nonzero entry to the matrix. This function may only be called for non-compressed sparsity patterns.
If the entry already exists, nothing bad happens.
Definition at line 336 of file chunk_sparsity_pattern.cc.
Make the sparsity pattern symmetric by adding the sparsity pattern of the transpose object.
This function throws an exception if the sparsity pattern does not represent a quadratic matrix.
Definition at line 357 of file chunk_sparsity_pattern.cc.
Return number of rows of this matrix, which equals the dimension of the image space.
Return number of columns of this matrix, which equals the dimension of the range space.
Check if a value at a certain position may be non-zero.
Definition at line 346 of file chunk_sparsity_pattern.cc.
Number of entries in a specific row.
Definition at line 370 of file chunk\}\).
Definition at line 520 of file chunk.
Definition at line 398 of file chunk_sparsity_pattern.cc.
Return whether the structure is compressed or not.
Return whether this object stores only those entries that have been added explicitly, or if the sparsity pattern contains elements that have been added through other means (implicitly) while building it. For the current class, the result is true.
Definition at line 535 of file chunk_sparsity_pattern.cc.
Iterator starting at the first entry of the matrix. The resulting iterator can be used to walk over all nonzero entries of the sparsity pattern..
Write the data of this object en bloc to a file. This is done in a binary mode, so the output is neither readable by humans nor (probably) by other computers using a different operating system of number format.
The purpose of this function is that you can swap out matrices and sparsity pattern if you are short of memory, want to communicate between different programs, or allow objects to be persistent across different runs of the program.
Definition at line 546 of file chunk 562 of file chunk_sparsity_pattern.cc.
Print the sparsity of the matrix. The output consists of one line per row of the format
[i,j1,j2,j3,...]. i is the row number and jn are the allocated columns in this row.
Definition at line 455 of file chunk 486 of file chunk_sparsity_pattern.cc.
Determine an estimate for the memory consumption (in bytes) of this object. See MemoryConsumption.
Definition at line 588 of file chunk_sparsity_pattern.cc. 283 of file chunk_sparsity_pattern.h.
Number of rows that this sparsity structure shall represent.
Definition at line 837 of file chunk_sparsity_pattern.h.
Number of columns that this sparsity structure shall represent.
Definition at line 842 of file chunk_sparsity_pattern.h.
The size of chunks.
Definition at line 847 of file chunk_sparsity_pattern.h.
The reduced sparsity pattern. We store only which chunks exist, with each chunk a block in the matrix of size chunk_size by chunk_size.
Definition at line 853 of file chunk_sparsity_pattern.h. | https://www.dealii.org/developer/doxygen/deal.II/classChunkSparsityPattern.html | CC-MAIN-2019-47 | refinedweb | 1,397 | 50.12 |
0
hello, so im designing a simple prgram which calculates the cost of a ticket you buy. there are only 3 ticket options, namely a b and c.
here is my code.
#include <iostream> using namespace std; const int PRICE = 3; int find(int [PRICE]); int main() { int nums[PRICE] = {2, 3 ,4}; int ticket; cout<<"select a ticket"<<endl; cin>>ticket; switch (ticket) { case 'A' : cout<<"cost is"<<nums[0]<<endl; break; case 'B' : cout<<"cost is"<<nums[1]<<endl; break; case 'C' : cout<<"cost is"<<nums[2]<<endl; break; default: cout<<"wrong ticket"<<endl; } system("pause"); return 0; }
however for whichever letter i put in i always get 'wrong ticket' any help would be appreciated thanks.
simply if i input 'A' it should output 'cost is 2', if i input 'B' it should output 'cost is 3' etc
Edited by Nick Evan: Fixed starting CODE-tag | https://www.daniweb.com/programming/software-development/threads/320864/help-with-array-calling-switch | CC-MAIN-2018-43 | refinedweb | 148 | 54.15 |
Hi, I have exposed my site menus and now i want to fetch the menu in my front end.
My menu is exposed at
How to fetch Menu from wordpress?
Hi, I have exposed my site menus and now i want to fetch the menu in my front end.
Hey @aeyzazkhan, welcome to the community
What plugin are you using to expose the menus?
I am not using any plugin but exposing using custom code in theme functions.php
You can create a custom handler to fetch the content of that endpoint and assign that data to a name to access it later, for example
"primaryMenu".
Something like:
libraries.source.handlers.push({ name: "primaryMenu", priority: 10, // This pattern is the name you can later use in "actions.source.fetch" // to fetch the content or "state.source.get" to get the data. pattern: "primaryMenu", // This is the function triggered when you use: // actions.source.fetch("primaryMenu"); func: async ({ state, libraries }) => { // Fetch endpoint. const response = await libraries.source.api.get({ endpoint: "menu/primary" }); // Extract data from response object. const data = await response.json(); // Assign data to be consumed later. // This is the data returned when you use: // state.source.get("primaryMenu"); Object.assign(state.source.data["primaryMenu"], { data, isMenu: true, }); } });
You should add that handler in both
beforeSSR and
beforeCSR:
const before = ({ libraries }) => { libraries.source.handlers.push(menuHandler); }; export default () => ({ state: { ... }, actions: { beforeSSR: before, beforeCSR: before, }, });
Finally, fetch it. If you are going to need it on each route, you can fetch it in the
before action:
const before = async ({ libraries, actions }) => { libraries.source.handlers.push(menuHandler); // This will wait until the primaryMenu data is fetched. await actions.source.fetch("primaryMenu"); };
That will ensure that the
primaryMenu data is available before the React rendering.
You can consume it like this in your React components:
const Menu = ({ state }) => { // Use "state.source.get" to access the data: const { data } = state.source.get("primaryMenu"); return ( <div>{... use `data` somehow ...}</div> ); } export default connect(Menu);
By the way, we will add support for WP menus once this plugin is merged with the core:
Hi @luisherranz thanks for your awesome project! I’m just checking this out and playing with the mars and 2019 themes to see if Frontity would fit for my client’s needs. The first thing my client would ask for is if they can change the menu so I’m trying to figure out where to implement this code inside the theme structure to make this possible. I’m using the menu plugin you’ve linked ().
Regards from Tallinn,
Kris
These are our plans for wp-source:
- Phase 0 (finished): custom handlers support
- Phase 1 (finished): default handlers for common WP urls (home, categories, tags, posts, pages)
- Phase 2 (in progress, almost finished): handlers for other URLs (custom post types, custom taxonomies) and settings for common WP configurations (subdirectory, page as homepage…). These things need to be configured in the
frontity.settings.jsfile.
- Phase 3 (not started): handlers for non-URL data, like menus, comments, attachments, widgets…
Our idea for the design of phase 3 is that non-URL data work with the same APIs than the URL data. It just doesn’t start with “/”.
For example, comments will be something like:
// Fetch comments for post 123: actions.source.fetch("comments/123") // Get data for those comments const data = state.source.get("comments/123") // Iterate over the comments data.items.map(item => { const comment = state.source.comments[item.id] // Do stuff })
Similar for menus, with something like:
// Fetch all menus actions.source.fetch("menus") // Fetch specific menu actions.source.fetch("menus/my-top-menu")
We will open a RFC (request for comments) here in the forum to gather feedback before the final implementation.
In the meantime, you can create your own custom handler to get your menus using any name you want linked to an API endpoint as explained here in this topic. And if you have any question let us know and we’ll help you out
Thanks for the in-depth explanation!
@luisherranz, I am very interested in this method and tried myself to implement menu on mars theme. But it’s not working. When fetching, it returns null object. I think it is due to the api endpoint.
Can you please let me know how to set endpoint to get menu? For instance, I am going to get all menus and REST API entrypoint is:. Then how should I set the endpoint.
I hope to get response from you asap.
Regards,
My case is that I have bilingual site (czech, english). Default language is czech I have a frontpage handler ( “/” ) and other handlers ("/:slug"). These pages read from state.lang = “cs” and fetch everything according to this setting.
I bumped into a trouble when user goes for routes “/en/” or “/en/:slug”. Where this time handlers change state.lang property to “en”. But my navigation (menu) stays prefetched in czech language.
How can I fetch the menu from WITHIN a component (navigation.js), which is loaded from index.js > header.js ?
This is what I have now:
This is what I would like to have, but it does not work that way:
What PHP plugin are you using? | https://community.frontity.org/t/how-to-fetch-menu-from-wordpress/415 | CC-MAIN-2019-43 | refinedweb | 868 | 67.35 |
-----Original Message-----Dear webware community
From: jose@cybergalvez.com [mailto:jose@cybergalvez.com]
Sent: Sunday, June 29, 2003 5:56 PM
To: webware-devel
Subject: [Webware-devel] __init__ context requirment
a recent email by Lothar Scholz, points out an interesting question/problem which has bitten me at least a few times. when you make a new context, if you fortet to add the required __init__.py file to it the context will fail to load correctly. This can cause problems especially for folks new to webkit if they do not realise that a context is loaded like a standart python module. To correct this I added the folloing code my the addContext function in the application.py file:
orginal code:
def addContext(self, name, dir):
if self._contexts.has_key(name):
print 'WARNING: Overwriting context %s (=%s) with %s' % (
repr(name), repr(self._contexts[name]), repr(dir))
__contextInitialized = 1 # Assume already initialized.
else:
__contextInitialized = 0
.....
Modified code:
def addContext(self, name, dir):
# Code added by Jose
# __init__ check file code
# this code will check for the __init__ file and add it if necessary
if not os.path.exists(os.path.join(dir, '__init__.py')):
# __init__.py file is missing creat it
print '__init__ file is missing, creating __init__ file now'
init = file(os.path.join(dir, '__init__.py'), 'w')
init.write('# Auto generated __init__ file\n')
init.close()
# end __init__ file check code
# end Code added by Jose
if self._contexts.has_key(name):
print 'WARNING: Overwriting context %s (=%s) with %s' % (
repr(name), repr(self._contexts[name]), repr(dir))
__contextInitialized = 1 # Assume already initialized.
else:
__contextInitialized = 0
......
Note that I am not doing anything special other then checking to see if the file is present proir to your loading the context, if it is present I do nothing, otherwise I make one with a single comment line in the file. I think its a nice feature to add as we move to 0.9
Jose
------------------------------------------------------- This SF.Net email sponsored by: Free pre-built ASP.NET sites including Data Reports, E-commerce, Portals, and Forums are available now. Download today and enter to win an XBOX or Visual Studio .NET.;at.asp_061203_01/01 _______________________________________________ Webware-devel mailing list Webware-devel@lists.sourceforge.net | http://sourceforge.net/p/webware/mailman/attachment/61957B071FF421419E567A28A45C7FE59AF50D@mailbox.nameconnector.com/1/ | CC-MAIN-2014-15 | refinedweb | 372 | 58.79 |
Hi,
I am working on a project in which we are currently evaluating and
trying to make some prototypes using different BPEL engines in
conjunction with JBI, and ODE and ServiceMix have risen to the top as
our best options.
So we are trying to create a sample BPEL process running inside of
ServiceMix which does the following:
1) Exposes an external "composite" web service for clients to call.
2) Calls in turn one or more "core" web services or other JBI
components.
I am close to having an example of this sort working following the
documentation on apache.org and the examples in $ODE_HOME/examples/.
Here is my problem:
On the page under the Getting
Started -> In JBI section, there is a section called "JBI Endpoints".
This section references a "deployment descriptor" based on the namespace
"". This appears to
be the deployment descriptor which will allow one to expose internal JBI
components to the BPEL engine to be invoked from it. However, on the
rest of this page, there are many more references to a "deployment
descriptor, "deploy.xml", based on the
"" namespace which contains
information about the BPEL Partner Links but doesnt seem to have any
references to the "endpoint-refs" of the first schema.
So my questions are:
1) Can someone clear up the confusion with the deployment descriptors?
Are 2 deployment descriptors necessary. If so, can someone point me to
an example using the
"" based deployment
descriptor?
2) What is the proper way to call a JBI endpoint from a BPEL process? I
have seen plenty of examples of calling a BPEL process from a SOAP/HTTP
endpoint, but not the other way around. Any examples available?
Thanks for any help!
David
-
David McWhorter, Software Engineer, SAIC | http://mail-archives.eu.apache.org/mod_mbox/ode-user/200807.mbox/%3C1216073145.6923.14.camel@localhost%3E | CC-MAIN-2019-35 | refinedweb | 291 | 63.8 |
Pandas'Learning Notes
Pandas'Learning Notes
Several conventions
The full text uses 1 to 3 well numbers, corresponding to the first, second and third titles of the book.
To represent notes at different levels, four well numbers are used to record formal notes.
Article directory
- Getting Started
- Intro to data structure
- Series
- pandas to numpy narray
- Judging whether label exists
- Number calling Series
- Vectorization and label alignment
- The name attribute of Series
- DataFrame
Getting Started
Intro to data structure
Fundamental Doctrine: Data is [essentially] aligned
Unless you do this manually, the connection between tags and data will not be disconnected.
Series
The Method of Establishing Series
s = pd.Series(data, index = index)
The data here can be dict, ndarray, scalar
import pandas as pd import numpy as np s = pd.Series(np.random.randn(5), index = list('abcde')) d = dict(b = 1, a = 0, c = 2) c = pd.Series(d) e = pd.Series(5. , index = list('abcde'))
The use of Series is similar to that of ndarray.
Pay attention to this usage
# After an attempt, this method can only be used in the array s of Siries and numpy of pandas, but not list. s[[4, 3, 1]]
pandas to numpy narray
>>> e.to_numpy() # Function to_numpy array([0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. ]) >>> e.values # Attribute values array([0. , 0.2, 0.4, 0.6, 0.8, 1. , 1.2, 1.4, 1.6, 1.8, 2. ])
Judging whether label exists
>>> 'e' in e True >>> 'l' in e
Number calling Series
s.get('f') #If there is no'f', return None s.get('f', np.nan) # You can also return np.nan, which needs to be set manually. s['f'] # This call method, if'f'does not exist, jumps out of KeyError
Vectorization and label alignment
s + s s ** 2 np.exp(s) s * 2
Unlike ndarray, Series automatically aligns tags when computing, and gives NaN results directly from missing elements.
The name attribute of Series
c.name = 'somename' s = pd.Series(np.random.randn(5), name = 'another_name')
DataFrame
Acceptable inputs include: ndaray, list, dicts or Series in dict form; ndarray in two-dimensional form; ndarray in structure or record; and another DataFrame.
Data Frame has two types of tags: index (row labels); column (column labels).
Establishing DataFrame from dict Of Series
# Create a dict for Series, that is, a dict, where all the elements are Series # Notice that the index here is essentially the original definition of index. >>> d = dict(one = pd.Series([1., 2., 3.], index = list('abc')), ... two = pd.Series([1., 2., 3., 4.], index = list('abcd'))) >>> d {'one': a 1.0 b 2.0 c 3.0 dtype: float64, 'two': a 1.0 b 2.0 c 3.0 d 4.0 dtype: float64} >>> df = pd.DataFrame(d) # Create DataFrame >>> df one two a 1.0 1.0 b 2.0 2.0 c 3.0 3.0 d NaN 4.0 >>> pd.DataFrame(d, index = list('bda')) # Note that index here is essentially a retrieval of d data. and one two b 2.0 2.0 d NaN 4.0 a 1.0 1.0 >>> pd.DataFrame(d, index = list('dba'), columns = ['two', 'three']) # Note that columns here are also a kind of retrieval. Not definitions. two three d 4.0 NaN b 2.0 NaN a 1.0 NaN
As can be seen from the above example, once index and columns of the DataFrame are defined, they are retrieved every time they are used unless they are modified manually.
>>> df.index # Line number Index(['a', 'b', 'c', 'd'], dtype='object') >>> df.columns # Column number Index(['one', 'two'], dtype='object')
Create DataFrame from ndarray/list
# The ndarray used must have the same length >>> d = dict(one = [1., 2., 3., 4.], two = [4, 3, 2, 1]) >>> d {'one': [1.0, 2.0, 3.0, 4.0], 'two': [4, 3, 2, 1]} >>> pd.DataFrame(d) one two 0 1.0 4 1 2.0 3 2 3.0 2 3 4.0 1 # If an index is given, it also needs to be the same length as list/ndarray >>> pd.DataFrame(d, index = list('abcd')) one two a 1.0 4 b 2.0 3 c 3.0 2 d 4.0 1
Create from structured or record array s
>>> data = np.zeros((2, ), dtype = [('A', 'i4'), ('B', 'f4'), ('C', 'a10')]) >>> data[:] = [(1, 2., 'Hello'), (2, 3., 'World')] >>> pd.DataFrame(data) A B C 0 1 2.0 b'Hello' 1 2 3.0 b'World' >>> pd.DataFrame(data, index = ['first', 'second']) A B C first 1 2.0 b'Hello' second 2 3.0 b'World' >>> pd.DataFrame(data, columns = list('CAB')) C A B 0 b'Hello' 1 2.0 1 b'World' 2 3.0 | https://programmer.group/pandas-learning-notes.html | CC-MAIN-2019-39 | refinedweb | 804 | 78.65 |
Dealing with the Flexibility of JavaScript October 14th, 2007 at 3:56 pm by Neil Roberts
This if you have a parameter named url, go ahead and allow it to be a variety of object types, as long as they all indicate URLs. But once you start letting a parameter be a URL or a date, and you figure out which it should be based on variable analysis, you should start worrying..
Posted October 15th, 2007 at 8:59 am
Utter nonsense !
function clicked(event){ processById(event.target.id); }
function processById(id){ }
This IS THE correct way to go, it’s called a “bridge”.
Posted October 16th, 2007 at 3:23 am
One of the things I find interesting about jQuery is that it makes extensive use of function signature overloading (even to the extent of behaving differently depending on the first character of a string passed to the jQuery() function) but manages to do so in a way that I think actually improves the usability of the jQuery APIs. I think the reason it works is that its done consistently - for example, many jQuery methods have a kind of symmetry to them - call with one argument to read a value, call with two arguments to set a value. Before looking at jQuery I’d always considered signature overloading to be bad practise, but it seems that if you use it intelligently you can create some pretty intuitive APIs.
Posted October 16th, 2007 at 4:03 am
Simon, you’ll see some of that same API use in dojo.query as well… for example, dojo.query(”.foo”).styles(”width) returns an array of widths, whereas dojo.query(”.foo”.styles(”width”, “100px”) will set the width of each item.
In many ways its a better way of doing getters and setters when it is obvious from the context of the parameters. I’m not 100% sold on it myself, but it does reduce the amount of typing and the number of methods.
It would be especially useful for the DOM Level 2 NS methods. For example, they have getElementsByTagName and getElementsByTagNameNS. I think it would have been a lot cleaner if the namespace was just an optional last parameter for the normal method.
Posted October 16th, 2007 at 5:07 am
Completely agreed on getElementsByTagName[NS]. That’s really hysterically annoying. JQuery is a bit different, though, in that there’s only really one function, named JQuery, and you call it for *everything*. Having lots of differently-named functions, all of which you can call in multiple overloaded ways, is confusing. JQuery’s swapped one set of complexities (work out which function name to call, and the parameters are obvious) for an equivalent set (the function name is obvious, but I must work out which parameters to pass it). It’s where those two are combined (I have to work out which function name to call, and then I also have to think hard about the parameters I should pass to it) that it’s a problem. Duck typing is, as noted, the answer here; if I have a function which, say, hides an element, I ought to be able to pass it an element ID (as a string) or an actual element (or a CSS selector or an XPath or a list of element objects), because they’re all just a way of referring to “the element” (or “the elements”).
Posted October 16th, 2007 at 5:49 am
Simon, I actually really like the getter/setter paradigm of the optional final argument. I think the key there is that it’s super easy to figure out (and document), and once you do, it’s very easy to apply the pattern everywhere. Also, the function names and argument names still have clear meanings.
sil, I think the element ID/CSS/XPath/node argument is a great example of duck-typing where a little argument analysis is just fine.
These comments have a great pattern to them: that the flexibility of JavaScript can produce a function signature that is both clear and powerful.
Posted October 17th, 2007 at 1:31 am
I think signature overloading does have a place, but it should be used sparingly. A typical example is perhaps a function that changes an element’s className - it could accept either a single node or an array/collection of nodes.
It really only becomes problematical if you take it too far, e.g. it accepts a string which could be a node ID, CSS declaration, XPath or whatever. The large parsing and error-checking overhead should be provided by alternative methods/functions.
Posted October 17th, 2007 at 6:56 am
Recently it occurred to me that no one has borrowed the ruby on rails style of method overloading and defaulting. Granted JavaScript is not as elegant a solution but the why not the following:
function doSomething(args){
….
}
doSomething ({duration: 14, message:”Click Next to contintue or wait 14 seconds”});
doSomething ({ message:”Click Next when you are ready to contintue”});
A little utility function to merge two hashes together (I’d kill for native set functions like this) and you can go happily on you way.
Never the less, if every every function does only one thing, you’ll go a long way to solving your problem.
Posted October 17th, 2007 at 8:35 am
For those just arriving who are skipping straight to the comments, Isabelle is quoting one of my solutions and saying that it’s the only “right” one. I disagree with there being a “right” way to do anything, only ways that are either cleaner or faster.
Craig proves that point: if a user can pass either a single value, or an array of values, it will probably be inefficient to make a function call for every item in the array and should probably be moved to the main function. In this case, you have to weigh the clarity/performance tradeoffs of both approaches.
Adam van den hoven, I’m not sure of what you’re suggesting. It sounds like you’re proposing the kwArgs suggesting I made above, but using defaults? dojo.mixin is one of the utility functions that Dojo provides to merge two hashes together.
Posted October 17th, 2007 at 9:12 am
What I’m suggesting is that, instead of
function process(/*Object*/ item, /*Boolean?*/ flag1, /*Boolean?*/ flag2){
…
}
you use something like
function process(args}{
var defaults = {flag1:false, flag2:0XF00};
args = merge(args, defaults);
….
}
Mostly, I’m surprised that this pattern is rarely used. In Ruby (notably Ruby on Rails) this is a common thing to do since the language provides some nice syntax sugar that lets you skip using the {}.
The value of this is that it gives you named arguments, which can be good for documentation. With a bit of creativity it could make for some interesting currying.
As an aside, I’m glad to see you left referencing a library to the comments. Personally, I think that no one who wants to be a JavaScript developer should ever use a library like Dojo or Prototype or YUI or what have you until you could conceivably write one yourself. They’re great for casual JavaScript folk but you loose a lot of opportunity to learn about JavaScript (especially with something like Prototype) that is very valuable.
Posted October 17th, 2007 at 9:21 am
To expand on Neil’s last statement @Adam, this is a technique I use all the time: expect a keyword object as a single parameter, and the first thing you do in the body of the function is mix it into a default keyword object:
function doSomething(arg){
var keywords={ /* defaults here */ };
dojo.mixin(keywords, arg);
// do stuff
}
This helps to define the parameter set *and* it allows you to see, right at the top of the function, what the function might expect in keywords. And there are a number of variations on this, all of which work pretty well.
Posted October 17th, 2007 at 9:24 am
I should also say you can do this as well, if you don’t know if someone will actually pass you an args object or not:
dojo.mixin(keywords, args || { });
That way if *everything* is optional, you’ll be fine.
Posted October 17th, 2007 at 11:02 am
One thing we noticed while developing ASP.NET Ajax is that the arguments array performs very poorly. For that reason, as well as those you mention, and also because they are difficult to tool, we never use overloads in JavaScript and use the arguments array as little as possible. We do optional parameters instead, or name the overload differently (the bridging technique mentioned above). We’ve stayed clear of dictionary parameters to simulate named parameters because again they are difficult to tool. Optional parameters are a lot less confusing to users of your API and not as limited as it may seem.
Posted October 17th, 2007 at 1:19 pm
Bertrand: The dictionary parameters are for when you need them, of course simpler is better. But one of my least favorite function calls looks like this:
myFunc(1, “elephant”, true, null, null, “apple”, null, null, null, null, new Date());
When you see something like this happening throughout code (with no clear pattern), it’s time to think about passing a dictionary. Many projects might never encounter this situation, but it’s a good way of dealing with this type of complexity.
Posted October 17th, 2007 at 3:02 pm
@Adam, ttrenka:
jQuery’s extend is used in that manner for effects and plugin options, and is suggested in the plugin-writing docs (). It took me a bit to catch on, but now I find it extremely useful — I also think it’s a great way to add functionality to a method without changing its original function.
Posted October 17th, 2007 at 4:08 pm
[…] Neil Roberts has written a piece on Dealing with the Flexibility of JavaScript which delves into functions that are overloaded based on signature. […]
Posted October 18th, 2007 at 8:13 am
Charles, extend as it’s used there is exactly the same as Dojo’s mixin. To contrast the two:
settings = jQuery.extend({ name: “defaultName”, size: 5, global: true }, settings);
settings = dojo.mixin({ name: “defaultName”, size: 5, global: true}, settings);
But it’s not that you’re adding functionality to a method, you’re just providing defaults for any keywords that weren’t passed.
Posted November 3rd, 2007 at 9:36 am
An overloaded function signature tends to mean the function is too complex and needs to be broken down. The less parameters, the better. Two is average, one is good, none is excellent. :)
I often find one of the easiest ways to do this is to have my functions return the objects so that they can be strung together. So, instead of this:
myFunct(myObj, param1, param2) {
var tempObj = myFunct2(myObject, param1);
return myFunt3(tempObj, param2);
}
…you’d have something like this:
myObj.myFunct2(param1).myFunct3(param2);
This is more the “Prototype” way of doing things, and it feels clean.
Posted November 3rd, 2007 at 1:04 pm
Matt, function chaining very easily lends itself to obfuscation, which is exactly what we’re trying to prevent here. It’s hard to keep track after a few calls exactly what object you’re working with..
All things being the same, the argument here isn’t about what sort of syntax you like to use. If you can use call chaining, and the programmer that sees your code six months from now can tell what you were trying to do without having to either read a document or look through your source code, you’re doing fine. | http://www.sitepen.com/blog/2007/10/14/dealing-with-the-flexibility-of-javascript/ | crawl-002 | refinedweb | 1,959 | 57.91 |
2015-04-14 12:40 PM
Hi,
I have OCUM 6.2 for the cCOD environment. In the OCUM Report tab I don't see any options to create custom reports. I like to create a report to view and schedule to email in xls format daily. This data is use to populate storage information in ServiceNow.
These are the fields I like to create in the custom report:
- SVM
- lif IP
- cifs shares
- namespace
- volume % used
- volume % free
- aggr % used
- aggr % free
Any suggestion
2015-04-15 02:41 AM
Hi,
In the OCUM for clustered Data ONTAP users guide, there are instructions on how custom reports can be created and imported into OCUM. For more information, see OnCommand Unified Manager 6.2 Admin Guide. Page 23 describes what those reports perform as well as how they can be manipulated and page 105 describes about creating new reports that are specific to your environment.
Thanks | http://community.netapp.com/t5/OnCommand-Storage-Management-Software-Discussions/Custom-Report-in-OCUM-6-2/td-p/103211 | CC-MAIN-2018-13 | refinedweb | 156 | 63.39 |
import "gopkg.in/square/go-jose.v2/cipher"
cbc_hmac.go concat_kdf.go ecdh_es.go key_wrap.go
func DeriveECDHES(alg string, apuData, apvData []byte, priv *ecdsa.PrivateKey, pub *ecdsa.PublicKey, size int) []byte
DeriveECDHES derives a shared encryption key using ECDH/ConcatKDF as described in JWE/JWA. It is an error to call this function with a private/public key that are not on the same curve. Callers must ensure that the keys are valid before calling this function. Output size may be at most 1<<16 bytes (64 KiB).
KeyUnwrap implements NIST key unwrapping; it unwraps a content encryption key (cek) with the given block cipher.
KeyWrap implements NIST key wrapping; it wraps a content encryption key (cek) with the given block cipher.
func NewCBCHMAC(key []byte, newBlockCipher func([]byte) (cipher.Block, error)) (cipher.AEAD, error)
NewCBCHMAC instantiates a new AEAD based on CBC+HMAC.
func NewConcatKDF(hash crypto.Hash, z, algID, ptyUInfo, ptyVInfo, supPubInfo, supPrivInfo []byte) io.Reader
NewConcatKDF builds a KDF reader based on the given inputs.
Package josecipher imports 13 packages (graph) and is imported by 3 packages. Updated 2019-10-29. Refresh now. Tools for package owners. | https://godoc.org/gopkg.in/square/go-jose.v2/cipher | CC-MAIN-2019-47 | refinedweb | 191 | 52.56 |
view raw
I wanna use
fgetc()
char *ch
Segmentation fault (core dumped)
void main(){
char *ch;
int i = 0;
while((ch[i] = fgetc(stdin)) != '\n'){
i++;
}
return;
}
While you can
realloc for every character you read, that is a horribly inefficient way to allocate memory. A call to
malloc is relatively expensive compared to an assignment of a character to an array element. It is far better to allocate some reasonably anticipated number of characters, read until your reach the limit,
realloc at that point (updating the limit), and repeat until
EOF (or whatever termination you choose).
The implementation is straight forward, but there are a couple of subtleties to note. When reallocating, always assign the result of
realloc to a temporary pointer so you can validate that
realloc succeeded before proceeding. Why? If
realloc fails, it returns
NULL. If you just blindly assign the result to your original array, and
realloc fails, (1) you have just lost the pointer to your original array; and (2) you have just created a memory leak because the original block is left untouched -- it is not freed or moved.
With that in mind, you could read characters into an array, reallocating as needed, until
EOF is reaches using something like the following:
#include <stdio.h> #include <stdlib.h> #define NCHAR 1024 /* must be at least 1 */ int main (int argc, char **argv) { int c; size_t n = 0, nchar = NCHAR; char *arr = malloc (sizeof *arr * nchar); FILE *fp = argc > 1 ? fopen (argv[1], "r") : stdin; if (!fp) { /* validate file open for reading */ fprintf (stderr, "error: file open failed '%s'.\n", argv[1]); return 1; } if (!arr) { /* validate memory allocation succeeded */ fprintf (stderr, "error: virtual memory exhausted.\n"); return 1; } while ((c = fgetc (fp)) != EOF) { /* for each char in file */ arr[n++] = c; /* assign char to array */ if (n == nchar) { /* realloc preserving space for nul */ void *tmp = realloc (arr, nchar + NCHAR); if (!tmp) { /* validate realloc succeeded */ fprintf (stderr, "realloc() error: memory exhausted.\n"); break; /* break read loop, using existing 'arr' */ } arr = tmp; /* assign reallocated pointer to arr */ nchar += NCHAR; /* update the value of nchar */ } } arr[n] = 0; /* affirmatively nul-terminate */ if (fp != stdin) fclose (fp); /* close file if not stdin */ for (size_t i = 0; i < n; i++) /* output arr */ putchar (arr[i]); free (arr); /* free allocated memory */ return 0; }
(note: above, on failure, the read loop is exited, preserving all characters in
arr read up to that point in time.)
Lastly, in any code your write that dynamically allocates memory, you have 2 responsibilities regarding any block of memory allocated: (1) always preserve a pointer to the starting address for the block of memory so, (2) it can be freed when it is no longer needed.
It is imperative that you use a memory error checking program to insure you haven't written beyond/outside your allocated block of memory, attempted to read or base a jump on an unintitialized value and finally to confirm that you have freed all the memory you have allocated. (For Linux
valgrind is the normal choice.)
A simple example (with
NCHAR set to
2 to force multiple reallocations) would be:
$ valgrind ./bin/fgetc_realloc <../dat/captnjack.txt ==19710== Memcheck, a memory error detector ==19710== Copyright (C) 2002-2013, and GNU GPL'd, by Julian Seward et al. ==19710== Using Valgrind-3.10.1 and LibVEX; rerun with -h for copyright info ==19710== Command: ./bin/fgetc_realloc ==19710== This is a tale Of Captain Jack Sparrow A Pirate So Brave On the Seven Seas. ==19710== ==19710== HEAP SUMMARY: ==19710== in use at exit: 0 bytes in 0 blocks ==19710== total heap usage: 39 allocs, 39 frees, 1,560 bytes allocated ==19710== ==19710== All heap blocks were freed -- no leaks are possible ==19710== ==19710== For counts of detected and suppressed errors, rerun with: -v ==19710== ERROR SUMMARY: 0 errors from 0 contexts (suppressed: 1 from 1)
You want to find All heap blocks were freed -- no leaks are possible and ERROR SUMMARY: 0 errors from 0 contexts (noting: on some OS, valgrind will not report
0 due to incomplete memory exclusion files) | https://codedump.io/share/9jxBu6KuYOOK/1/using-fgetc-for-reading-into-an-array-in-c | CC-MAIN-2017-22 | refinedweb | 679 | 57.1 |
Ken Getz
Paul D. Sheriff
October 2005
Summary: Part 2 of this article series focuses on the data features of converting code from ADO to ADO.NET. ADO.NET operations require less code, and replacing the COM interop features will make your application more efficient. (32 printed pages)
Introduction The ADO.NET Classes You'll Need Update the Utility Module Overhauling the CustomerHandler Class Conclusion
In the first part of this three-part series, you walked through the steps required to convert an existing Visual Basic 6 data-oriented application into a working, if somewhat creaky, Visual Basic 2005 application. The new application ran within Visual Studio 2005, and allowed you to create a .NET application for Windows, but it's far from finished. (See the first article in the series, Converting a Data-Oriented Application from Visual Basic 6 to Visual Basic 2005, Part 1. In Part 1, you were promised that the second article would focus on both Windows Forms features and on converting the code to ADO.NET. It turns out that performing a reasonable conversion from ADO to ADO.NET required a great deal of effort, so we decided to focus Part 2 on the data features, leaving the form intact. In Part 3, we'll focus instead on rewriting the entire application, with far less code, taking advantage of the new Windows Forms data-binding functionality.
The application in its current state uses COM interop to communicate with ADO, allowing the application to work using the same code, more or less, that it did in Visual Basic 6. In converting such an application, your next goal might be to attempt to replace all the existing ADO code with code that uses ADO.NET, and that's the purpose of this installment in the series. If nothing else, replacing the COM interop requirements should make the application more efficient. In addition, you'll find that similar operations in ADO.NET often require less code, allowing you to streamline the application a bit. (We've included the project, at its starting point for this article, in the associated download file. It would be better if you were to work through the steps in the previous article yourself, but if you can't, start with the project we've supplied.)
Before you begin ripping out the guts of the existing application, replacing ADO with ADO.NET and its various objects, you should familiarize yourself with the objects you'll be using. Obviously, this article is the wrong place, and lacks the available space, to dig deeply into the various ADO.NET classes, with their properties, methods, and events. But it doesn't take much effort to understand the basics, and if you have some experience with ADO, ADO.NET shouldn't take you too much by surprise—it's all about retrieving, working with, and storing data. (For more information on ADO.NET in general, see the Overview of ADO.NET.
Although ADO.NET provides a large number of classes to work with, this sample application requires only that you understand the System.Data.DataTable class, as well as a number of classes that work directly with the OleDb data provider, including System.Data.OleDbConnection, OleDbCommandBuilder, and OleDbDataAdapter. You'll learn enough about these to make use of them here.
The System.Data namespace includes classes that work with disconnected data. That is, once you retrieve the data you need, you'll use classes in the System.Data namespace to manipulate that data. The System.Data.DataTable class provides an in-memory representation of a set of rows and columns. To most people, that sounds like a table in a database. Actually, the DataTable class simply provides a container for rows and columns of data, with the columns (represented as System.Data.DataColumn instances) providing information about the schema, and the rows (represented as System.Data.DataRow instances) contain the actual data. Rather than using an ADO Recordset instance, the new version of the application uses a single DataTable instance. Of course, in other applications, you'll often need to work with multiple tables concurrently—the DataSet class provides this functionality. By filling multiple DataTable instances within a single DataSet, you can relate the tables (using a DataRelation instance) and easily provide parent/child relationships. A DataTable instance keeps track of the current offline data, as well as the original data at the time the DataTable was filled—that way, when it comes time to save changes, each row "knows" whether it has been changed, and can compare the current values in its columns to the values in the data source before performing the updates.
In order to get data into a DataTable, you can add the data one row at a time, or you can fill the DataTable with all the data from a database table, or view at once. Neither the DataTable nor the DataSet classes can communicate directly with a data source—for that, you need an object contains connection information, like the System.Data.OleDb.OleDbDataAdapter class. The sample application uses an OleDbDataAdapter instance, and its Fill method, to retrieve all the data at once. The OleDbDataAdapter (and its cousins, the System.Data.SqlClient.SqlDataAdapter, System.Data.Odbc.OdbcDataAdapter, and so on) provides the means for both filling a DataTable, and if you want to allow users to make changes to the data in a DataTable, you can use the OleDbDataAdapter instance to update the data in the original data source, as well, by calling its Update method. (Although this article refers only to OleDbDataAdapter and other classes in the System.Data.OleDb namespace, all the concepts apply equally to classes in the System.Data.SqlClient, System.Data.Odbc, and other namespaces. The System.Data.SqlClient namespace provides classes that interact directly with SQL Server, and the System.Data.Odbc namespace provides classes that interact with the ODBC data engine.)
The OleDbDataAdapter class needs some information in order to be able to fill the DataTable—it needs to know what data you need (for example, a SELECT SQL statement or the perhaps the name of a stored procedure, query, or view) and where to get the data (a connection string). You can also supply the OleDbDataAdapter with an OleDbCommand object containing information about the data to be retrieved, and an OleDbConnection object containing information about where to get the data. ADO.NET is flexible—if you want, you can supply the SQL and connection strings when you create the OleDbDataAdapter, and the data adapter will take care of all the "connecting to the data source and getting the data" details for you. You also have the option of creating your own OleDbConnection and OleDbCommand instances yourself, and supplying them to the OleDbDataAdapter. That way, you can control exactly when you open the connection to the data source. The most important rule, however, is that the OleDbDataAdapter guarantees that it will leave the connection in the state that it found it, when you call its Fill method. That is, if the connection was closed, calling the Fill method will open it, get the data, and close it again. If the connection was open, the Fill method gets the data and leaves the connection open.
Obviously, you'll use a SELECT command in order to retrieve data. What if you want to update, delete, or insert data? The OleDbDataAdapter class provides four properties that contain OleDbCommand objects, one for each of the four operations you might want to perform on data. You'll find the SelectCommand, InsertCommand, UpdateCommand, and DeleteCommand properties of the OleDbDataAdapter available for you to work with. When you create the OleDbDataAdapter instance, you generally pass it the SQL string it needs to retrieve the data, and ADO.NET places the OleDbCommand object containing this string into the SelectCommand property of the OleDbDataAdapter. You can supply the corresponding DELETE, UPDATE, and INSERT statements yourself, or you can rely upon a helper object, the OleDbCommandBuilder, to do the work. This class can generate the necessary DELETE, UPDATE, and INSERT SQL statements for you, and the sample application takes advantage of this functionality. Purists may want to hand-create their own SQL, but in this case, that step isn't necessary.
Tip By default, to help save you typing, Visual Basic 2005 adds a project-wide Imports statement for the System.Data namespace to your projects for you, and the sample project takes advantage of this behavior. You must add your own Imports statements for other namespaces, and you'll see that the sample project adds Imports statements for other the System.Data.OleDb namespace, as well.
Given that the goal of the remainder of this article is to modify the running Visual Basic 2005 application so that it uses ADO.NET rather than ADO, you can follow the steps provided here to make the necessary changes. Remember: although it looks like you need to make a huge number of changes in order to perform this conversion, it's really a matter of learning how the ADO.NET objects work and writing each procedure to take advantage of those objects. Don't be daunted by the amount of code here. If you spend time to understand each procedure, you'll have a good basis from which to work with your own ADO.NET applications.
Before beginning to make modifications to the project, however, take the time to configure Visual Studio 2005 appropriately. Follow these steps to make the changes:
Figure 1. Modify the project settings so that they look as shown.
You'll need to modify the data layer quite a lot in order to take advantage of ADO.NET. To get started, open DataLayer.vb in the Visual Studio 2005 code editor. At the top of the file, you'll find lines of code that look like the following:
Option Strict Off
Option Explicit On
Friend Class DataLayer
The conversion utility added the Option Strict Off setting. This setting makes it possible for your Visual Basic 2005 code call make calls to ADO using COM interop. As you probably know, COM objects often use object references (as opposed to strongly typed references), and instead of you having to fix all these problems, the conversion utility simply turned off the Option Strict setting in order to let these loose references slide. Because you will be modifying all of the code in this class, and because you set the Option Strict/Option Explicit settings project-wide, you no longer need either of these Option statements at the top of this class. Go ahead and delete these two statements now.
Because you'll be working with objects from the System.Data.OleDb namespace, you can save some typing by including an Imports statement at the top of the file. Add this statement now, above all the code in the file:
Imports System.Data.OleDb
It's likely that you may move the DataLayer.vb class to a separate assembly at some point in the future, so you can re-use this code in other projects. As a result, you modify the declaration of this class to be Public instead of Friend. That way, it can be accessed from an external assembly:
' Change:
Friend Class DataLayer
' to:
Public Class DataLayer
Although the original version of the project used ADO Recordset objects to move data around, the new version will use DataTable instances instead. Therefore, you'll need to fix up some names. Although you could use the standard Search/Replace mechanism, Visual Basic 2005 supports powerful Rename refactoring—that is, you can rename a method, and Visual Basic will fix up all references to that method.
Because the code must later retrieve the CustomerID of the newly added row, you'll need to make some special considerations. The topic is rather complex (that is, how to retrieve the autonumber value in a newly added row using an Access database), but it's covered well in Retrieving Identity or Autonumber Values. The issues are different for Access and for SQL Server databases, and the article covers both. We'll simply take advantage of the concepts, without explaining them in detail here. Suffice it to say that in order to retrieve the new autonumber value, you must handle the OleDbDataAdapter RowUpdated event, and in that event handler, use the SQL query SELECT @@IDENTITY to retrieve the new value. In order to support this behavior, add the following code to the DataLayer class, outside of any procedure:
' The OleDbDataAdapter.RowUpdated event handler
' needs a connection:
Private Shared mcnn As OleDbConnection
Add the following procedure to the DataLayer class. This procedure will handle the OleDbDataAdapter RowUpdated event and retrieve the new CustomerID value for you:
Private Shared Sub OnRowUpdated( _
ByVal sender As Object, ByVal eventArgs As OleDbRowUpdatedEventArgs)
' Retrieve the new CustomerID value.
' This technique requires the same connection used
' for performing the update, so mcnn is a class-level
' variable.
Using cmd As New OleDbCommand("SELECT @@IDENTITY", mcnn)
If eventArgs.StatementType = StatementType.Insert Then
' Retrieve the identity value and store it
' in the CustomerID column.
eventArgs.Row("CustomerID") = CInt(cmd.ExecuteScalar())
End If
End Using
End Sub
Within the DataLayer class, locate the GetRecordset method. Make five changes to this procedure:
Public Function GetDataTable( _
ByVal ConnectionString As String, _
ByVal SQL As String) As DataTable
' Instead of this code:
Dim data As New DataLayer
Dim dt As DataTable = data.GetDataTable(ConnectionString, SQL)
' you can use code like this:
Dim dt As DataTable = DataLayer.GetDataTable(ConnectionString, SQL)
Public Shared Function GetDataTable( _
ByVal ConnectionString As String, _
ByVal SQL As String) As DataTable
Finally, it's time to replace the inside of the procedure. Modify the procedure
so that it looks like the following:
Public Shared Function GetDataTable( _
ByVal ConnectionString As String, _
ByVal SQL As String) As DataTable
' Let exceptions bubble up to the caller.
Dim dt As New DataTable
Dim da As New OleDbDataAdapter(SQL, ConnectionString)
da.Fill(dt)
Return dt
End Function
The code creates a new DataTable instance, ready to hold data. Then, the code creates a new OleDbDataAdapter, passing its constructor the SQL SELECT string and the connection string. The code calls the OleDbDataAdapter.Fill method in order to retrieve the data from the database and put that data into the DataTable, dt. Finally, the method returns the filled DataTable.
At this point, you can delete the other two methods in the DataLayer class (CloseRecordset and OpenConnection). Because the DataTable you're using to work with the data is always disconnected, there's nothing to close. In addition, because filling the data adapter handles opening and closing the connection, you don't need a separate procedure for that operation, either. Once you're done, the DataLayer class should contain only the GetDataTable method.
In addition to the existing method in the DataLayer class, the new version requires an additional procedure. This new method allows you save changes made to the data within the DataTable instance back to the original data source. Although you could accomplish this goal in many ways, the simplest solution is to allow an OleDbCommandBuilder instance to generate the appropriate SQL UPDATE statement for you, and then call the Update method of an OleDbDataAdapter.
Insert the following procedure into the DataLayer class:
Public Shared Sub UpdateDataTable( _
ByVal dt As DataTable, _
ByVal ConnectionString As String, ByVal SQL As String)
' Pass exceptions back out to the caller.
' Create the data adapter, and an associated
' command builder:
Try
' The RowUpdated event handler requires the same
' connection used when performing the update,
' so this code creates it, and leaves it open.
mcnn = New OleDbConnection(My.Settings.ConnectString)
mcnn.Open()
Dim da As New OleDbDataAdapter(SQL, mcnn)
Dim bld As New OleDbCommandBuilder(da)
AddHandler da.RowUpdated, AddressOf OnRowUpdated
' The Update method uses the INSERT, UPDATE, and DELETE
' statements generated by the command builder:
da.Update(dt)
Finally
' No matter what, close the connection when the code
' completes.
mcnn.Close()
End Try
End Sub
This method creates an OleDbDataAdapter, just as in the GetDataTable method. When you call the UpdateDataTable method, you pass in a DataTable from which you'll retrieve changed rows, along with a connection string and the SQL SELECT string that you used to retrieve the data.
Tip The UpdateDataTable method hooks up the RowUpdated event handler for its OleDbDataAdapter, using the AddHandler statement. This statement, new in .NET, allows you to dynamically tell Visual Basic which procedure it should call in reaction to an object's event. In this case, the code indicates that when the RowUpdate event occurs, the .NET runtime should call the OnRowUpdated procedure in the same class.
You may wonder why you're passing in a SELECT statement, even though you're attempting to perform an update. The OleDbCommandBuilder class can take the SELECT statement associated with a data adapter, and from that, generate the corresponding INSERT, UPDATE, and DELETE statements. In this procedure, the command builder does its work, and then the code calls the Update method of the data adapter to save the changes back to the data source.
Tip If you're interested, you may find it useful to view the UpdateCommand, InsertCommand, and DeleteCommand properties of the OleDbDataAdapter while running the application. Once you've completed the steps in this article, you can put a breakpoint within the UpdateDataTable procedure, and once you hit the breakpoint, use the debugging tools in Visual Studio 2005 to investigate these properties.
Next, you'll update the Utility.vb file to take advantage of ADO.NET features. Open the file within the code editor, and you'll note that this is a standard Visual Basic Module. From the Visual Basic 2005 perspective, the project contains a class named basUtility with several Shared methods. Although you won't do it here, in a new project, you might want to consider creating standard classes (rather than modules) and using the Shared keyword explicitly to indicate procedures that can be called without creating an instance of the host class.
Follow these steps to get started modifying Utility.vb:
Option Strict Off
Option Explicit On
Now go ahead and modify each of the methods as shown in the next few sections in this article.
Replace the AddQuotes method with the following method, which takes advantage of two .NET features. The code returns its value using the Return statement (for consistency with other Visual Basic 2005 code). In addition, the procedure uses the String.Format method, which allows you to create a template with replaceable parameters. In this case, the {0} value within the template gets replaced with the value returned by calling the Replace method of the supplied string, replacing single apostrophes with double apostrophes:
Public Function AddQuotes(ByVal strValue As String) As String
Return String.Format("'{0}'", strValue.Replace("'", "''"))
End Function
The FindString method uses the Visual Basic If TypeOf statement to determine the type of the control you pass in. This statement behaves differently in Visual Basic 2005 than it did in Visual Basic 6, but only when used with Structure types. In this case, you're not using structures, so the warnings you see in the code aren't valid in this case. If you want to satisfy the warnings, you can replace the procedure with the following procedure. We don't really see the need, but doing so will satisfy the warnings: ctl.GetType() Is GetType(ListBox) Then
' Cast control and attempt to find the string
intPos = CType(ctl, ListBox).FindStringExact(strFind)
ElseIf ctl.GetType() Is GetType(ComboBox) Then
' Cast control and attempt to find the string
intPos = CType(ctl, ComboBox).FindStringExact(strFind)
End If
' Set the selected index
ctl.SelectedIndex = intPos
End Sub
To be honest, all those calls to GetType seem overly complex to us. You may want to use the original If TypeOf construct (a perfectly reasonable solution, in our eyes), and if so, you can replace the procedure with the following version, which takes advantage of Visual Basic 2005 features but still uses If TypeOf to compare object types: TypeOf ctl Is ListBox Then
' Cast control and attempt to find the string
intPos = CType(ctl, ListBox).FindStringExact(strFind)
ElseIf TypeOf ctl Is ComboBox Then
' Cast control and attempt to find the string
intPos = CType(ctl, ComboBox).FindStringExact(strFind)
End If
' Set the selected index
ctl.SelectedIndex = intPos
End Sub
The FixBoolean procedure expects to receive an ADO Field object, and sets the value of a check box to match the truth value of the field's contents. To fix this procedure, change the input value to be an Object type, and pass the parameter directly to the CBool function. When you're done, the procedure should look like this:
Public Function FixBoolean(ByVal fld As Object) As CheckState
' Convert a Yes/No/Null field value
' into a checkbox value.
If CBool(fld) Then
Return CheckState.Checked
Else
Return CheckState.Unchecked
End If
End Function
The NullToText method relied on the fact that in Visual Basic 6, you could concatenate any variant (even the value Nothing) with an empty string, and the result would be a string. Because ADO.NET handles null values separately from the special Nothing value, this behavior no longer works. Instead, your code needs to check specifically for a null database value, and return an empty string in that case. Therefore, modify NullToText so that it looks like the following:
Public Function NullToText(ByVal fld As Object) As String
If IsDBNull(fld) Then
Return String.Empty
Else
Return CStr(fld)
End If
End Function
Although the TextToNull method contains a number of dire-appearing warnings, it really doesn't require any changes—all the warnings are benign. However, to keep in the spirit of writing good Visual Basic 2005 code, you should modify this method to check the value of the string coming in and return either System.DBNull.Value or the string itself. Therefore, replace the procedure with the following:
Public Function TextToNull(ByVal strValue As String) As Object
If String.IsNullOrEmpty(strValue) Then
Return System.DBNull.Value
Else
Return strValue
End If
End Function
At this point, you've handled the two easy classes. The CustomerHandler class and the ADO form require a bit more effort. Hopefully, you'll agree that taking the time to dig into this conversion is worth the effort. Along the way, you'll learn both Visual Basic 2005 tips, and more about ADO.NET as well.
The CustomerHandler class is next in line. Open Customer.vb in the code editor, and follow these steps to perform the updates:
Public Class CustomerHandler
Private mdt As DataTable
Private mintCurrentRow As Integer
Currently, the connection string is hard-coded within the GetConnection string method in the CustomerHandler class. Although this might be fine for a simple application, it's generally not practical for real applications. Rather than hard-coding this information within the application, it would be better if you were to place it somewhere where it could be modified easily—in other words, in a configuration file. Visual Basic 2005 has strong support for storing and retrieving data from configuration files, and the .NET Framework even makes it reasonably easy to secure this information, if you must.
For now, you'll just move the connection string to a configuration file, and use the Visual Basic 2005 My.Settings class to retrieve it. Follow these steps to move the connection string:
Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Samples\ADOFormNET\VB6Demo.MDB
When you're done, the grid should look as shown in Figure 2.
Figure 2. Modify settings so that they look as shown.
Tip This application is complicated somewhat because it uses a JET MDB file for its data store. The connection information for JET databases requires a complete path, so that if you move the database, the connection no longer works. You may find it easier in the long run (and instructive in the short run) to convert the application so that it stores its data in SQL Server, MSDE, or SQL Express. You won't have to make many changes, but you will need to change the connection string.
applicationSettings>
<ADOForm.Settings>
<setting name="ConnectString" serializeAs="String">
<value>Provider=Microsoft.Jet.OLEDB.4.0;Data Source=D:\Samples\ADOFormNET\VB6Demo.MDB</value>
</setting>
</ADOForm.Settings>
</applicationSettings>
Note When you add settings to the app.config file, Visual Basic 2005 generates a class named Settings within the My namespace, with a property corresponding to each setting. Therefore, you can refer to My.Settings.ConnectString within your code, and Visual Basic 2005 will automatically retrieve the value from the configuration file for you.
Public Function GetConnectionString() As String
' Use My.Settings to retrieve the connection string from the
' configuration file:
Return My.Settings.ConnectString
End Function
The GetCustomers method simply needs to retrieve the data, set the current row, and return the stored DataTable as its return value. Therefore, replace the contents of this procedure with the following code:
Public Function GetCustomers() As DataTable
mdt = DataLayer.GetDataTable(GetConnectionString(), _
"SELECT * FROM tblCustomer ORDER BY LastName")
mintCurrentRow = 0
Return mdt
End Function
Tip Because you created the DataLayer.GetDataTable method using the Shared keyword, you don't need to create an instance of the DataLayer class in order to call the method. The DataLayer.GetStates method you'll use in the next section exhibits the same behavior.
The GetStates method can take advantage of the DataLayer class, just like the GetCustomers method did. Modify the GetStates procedure so that it looks like the following:
Public Function GetStates() As DataTable
Return DataLayer.GetDataTable(GetConnectionString(), _
"SELECT State FROM tblStates")
End Function
In converting this application to take advantage of ADO.NET, we made the "executive decision" to have the CustomerHandler class take care of its own navigation—that is, the CustomerHandler class needs methods to handle moving around within the data. This section discusses the new methods, and walks you through adding them to the CustomerHandler class.
Because the DataTable class doesn't (and shouldn't) keep track of a current row (that's the job of the code that consumes the DataTable), the CustomerHandler class needs properties to return the current row number, the number of rows, and whether the current row is at the beginning or the end of the set of rows. Add the following read-only properties to the CustomerHandler class to support this functionality:
Public ReadOnly Property RowCount() As Integer
Get
Return mdt.Rows.Count
End Get
End Property
Public ReadOnly Property CurrentRow() As DataRow
Get
Return mdt.Rows(mintCurrentRow)
End Get
End Property
Public ReadOnly Property BOF() As Boolean
Get
Return (mintCurrentRow = 0)
End Get
End Property
Public ReadOnly Property EOF() As Boolean
Get
Return (mintCurrentRow = (mdt.Rows.Count - 1))
End Get
End Property
The demonstration form includes buttons that allow you to move around within the CustomerHandler class data. Because the CustomerHandler class is now taking control over its own navigation, you'll need to add methods that allow consumers to move around in the data. To that end, add the following procedures to the CustomerHandler class:
Public Sub MoveFirst()
mintCurrentRow = 0
End Sub
Public Sub MoveLast()
' If you have rows, move to the last row.
If mdt.Rows.Count > 0 Then
mintCurrentRow = mdt.Rows.Count - 1
End If
End Sub
Public Sub MoveNext()
If mintCurrentRow < mdt.Rows.Count Then
mintCurrentRow += 1
End If
End Sub
Public Sub MovePrevious()
If mintCurrentRow > 0 Then
mintCurrentRow -= 1
End If
End Sub
The demonstration form makes it possible for users to search for a row, based on the LastName field. The DataTable class provides a Find method, to which you pass an incomplete SQL WHERE clause (that is, without the WHERE clause), and you can use this method to find a row (or rows) within the DataTable. The Find method returns an array of DataRow objects, and in this case, you'll just want to navigate to the first match, if the resulting array contains any rows.
The Find method in the CustomerHandler class will allow you to pass in the search criteria, and will set the internal current row value to the first matched row, if it finds one. (It will leave the current row value intact if it doesn't find a match.) In addition, the method will return True if it succeeds, and False if it does not.
Add the following procedure to the CustomerHandler class:
Public Function Find( _
ByVal SearchCriteria As String) As Boolean
Dim retval As Boolean = False
Dim adr As DataRow() = mdt.Select(SearchCriteria)
If adr.Length > 0 Then
' If the search returned any rows, then
' set the current row to be the first
' row (row 0) within the array:
retval = True
mintCurrentRow = mdt.Rows.IndexOf(adr(0))
End If
Return retval
End Function
You can pass the Find method (and correspondingly, the DataTable.Select method) a string like these:
LastName = 'Jones'
' or
CompanyName LIKE 'A%'
After making changes to the data within the CustomerHandler class' DataTable instance, you'll want to be able to save the data back to the underlying data source. The DataLayer class provides an UpdateDataTable method that you can call, passing in the DataTable to be saved, a connection string, and the original SELECT statement (so that the underlying code can generate the appropriate UPDATE, DELETE, and INSERT statements).
Although you could pass the entire Customer DataTable to the UpdateDataTable method, if you later decide to move the DataLayer class to a separate assembly, you can achieve slightly better efficiency by only passing the rows that have changed. Why send all the rows, when all you care about are the changed rows? The DataTable class makes it simple to retrieve just those rows—the DataTable.GetChanges method filters the rows so that only the changed rows are "visible". Calling this method before passing the data to the UpdateDataTable provides a simple yet effective improvement.
Public Sub SaveToDatabase()
' Pass just the changed rows to the UpdateDataTable method
DataLayer.UpdateDataTable(mdt.GetChanges(), _
GetConnectionString(), _
"SELECT * FROM tblCustomer ORDER BY LastName")
End Sub
Updating a row in the CustomerHandler class requires a few steps. First, you must save the changes back to the underlying database. Then, you must instruct the DataTable to flush its "original row" information, so that it no longer thinks that the row needs to be modified in the data source.
The Update method that you'll add to the CustomerHandler class takes care of these tasks. The code calls the SaveToDatabase method to save changes, and then calls the AcceptChanges method of the DataTable that causes the DataTable to "forget" that rows had been changed.
Add the following method to the CustomerHandler class:
Public Sub Update()
SaveToDatabase()
' Convince the DataTable that there aren't any
' pending changes:
mcust.AcceptChanges()
End Sub
Warning The code in this sample isn't particularly careful about concurrency errors, or problems that might occur because rows are locked when you attempt to save changes. These issues are outside the scope of this demonstration, but you'll certainly want to investigate the issues and how to handle them. For more information, see Concurrency Control in ADO.NET.
Deleting a row from the CustomerHandler class requires just one more step than updating does—you must first delete a specific row. Therefore, add the following procedure to the CustomerHandler class, so that you can later delete a customer:
Public Sub Delete()
' Delete the current row.
mdt.Rows(mintCurrentRow).Delete()
' Save the changes:
Update()
End Sub
Finally, the CustomerHandler class needs a way in which to set up a new row. From the form, you won't call this method until it's actually time to save the new row—the form itself simply clears out its controls when you ask it to create a new customer, and doesn't call the Customer.AddNew method until you commit the changes.
Add the following procedure to the CustomerHandler class, which handles creating a new blank row, adding it to the DataTable, and setting the current row to the new index:
Public Sub AddNew()
Dim row As DataRow
' Create a new row:
row = mdt.NewRow
' Add the new blank row to the DataTable:
mdt.Rows.Add(row)
' Set the current row to this new row:
mintCurrentRow = mdt.Rows.Count - 1
End Sub
Now that all the support procedures are done, it's time to attack the user interface. Obviously, because you've made massive changes to the underpinnings of this application, you'll need to make a lot of changes to the form as well. In many cases, you'll simply delete unneeded code. In other cases, you'll change code to better take advantage of Visual Basic 2005 features. Follow these steps to get started modifying the form:
Private customerRecordset As ADODB.Recordset
Search for all instances of the call to the CloseRecordset method, and delete
those lines of code.
Search and replace all instances of ByRef with ByVal.
Remove the InitForm procedure.
Remove the frmADO_FormClosed procedure.
Remove the txtData_TextChanged procedure.
Remove the chkActive_CheckStateChanged procedure.
The ShowData method is responsible for getting the current row of data from the DataTable and displaying it on the form. Because of all the changes to the data store, this procedure must be completely replaced. Modify the ShowData method so that it looks like the following:
Private Sub ShowData()
Dim row As DataRow
' Set this flag so event procedures
' don't do anything during this process.
currentDataState = DataState.Loading
Try
If customer.RowCount = 0 Then
AddNewRow()
Else
' Store the Current row in local variable
' to avoid writing a lot of code.
row = customer.CurrentRow
' Note that when you convert from VB6 to VB 2005,
' the conversion process uses a custom control to
' emulate the behavior of control arrays. txtData
' isn't really the name of the control--on the form
' the controls are named _txtData_1, _txtData_2, and so
' on. For new forms, you wouldn't use this functionality,
' but instead, would create separate controls, one for
' each field. The custom control hides all this from you.
txtData(0).Text = NullToText(row("CustomerID"))
txtData(1).Text = NullToText(row("FirstName"))
txtData(2).Text = NullToText(row("LastName"))
txtData(3).Text = NullToText(row("Address"))
txtData(4).Text = NullToText(row("City"))
txtData(5).Text = NullToText(row("ZipCode"))
FindString(cboState, NullToText(row("State")))
chkActive.CheckState = FixBoolean(row("Active"))
HandleButtonState()
currentDataState = DataState.Normal
End If
GotoFirstControl()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
This code isn't much different in intent from the original Visual Basic 6 code. The big difference here, of course, is that you're now working with a DataRow object rather than with the entire Recordset.
Tip When you converted the application from Visual Basic 6 to Visual Basic 2005, the conversion process left the text box control array intact, using a custom control that emulates control arrays in Visual Basic 2005. Normally, you won't use control arrays in Visual Basic 2005; instead, you'll use individual controls that can share event handlers. We decided not to fix this up for this article in the series, with the knowledge that we'd handle this differently in the next article.
Because you've moved the navigation code from the form to the CustomerHandler class, you'll need to modify all button Click event handlers that move you through the data. Make the necessary changes to update the following procedures:
Private Sub cmdFirst_Click( _
ByVal eventSender As System.Object, _
ByVal eventArgs As System.EventArgs) _
Handles cmdFirst.Click
customer.MoveFirst()
ShowData()
End Sub
Private Sub cmdLast_Click( _
ByVal eventSender As System.Object, _
ByVal eventArgs As System.EventArgs) _
Handles cmdLast.Click
customer.MoveLast()
ShowData()
End Sub
Private Sub cmdNext_Click( _
ByVal eventSender As System.Object, _
ByVal eventArgs As System.EventArgs) _
Handles cmdNext.Click
customer.MoveNext()
ShowData()
End Sub
Private Sub cmdPrevious_Click( _
ByVal eventSender As System.Object, _
ByVal eventArgs As System.EventArgs) _
Handles cmdPrevious.Click
customer.MovePrevious()
ShowData()
End Sub
As part of its work, the ShowData method calls the HandleButtonState method. Nothing needs to change in the HandleButtonState method. It, however, calls the HandleNavButtons method to ensure that the navigation buttons are turned on and off at the appropriate times depending on which row in the DataTable in current. You can really simplify this code, because all of the logic for calculating EOF and BOF are now contained within the CustomerHandler class itself. Modify the HandleNavButtons procedure so that it looks like the following:
Private Sub HandleNavButtons()
' Handle the enabling/disabling of
' the navigation buttons.
Select Case currentDataState
Case DataState.Adding, DataState.Editing
cmdFirst.Enabled = False
cmdPrevious.Enabled = False
cmdNext.Enabled = False
cmdLast.Enabled = False
Case Else
cmdFirst.Enabled = Not customer.BOF
cmdPrevious.Enabled = Not customer.BOF
cmdNext.Enabled = Not customer.EOF
cmdLast.Enabled = Not customer.EOF
End Select
End Sub
The form's Load event handler sets up the data, and the display of the data. Obviously, because the underpinnings have changed, you'll need to modify the form's Load event handler. This code creates an instance of the CustomerHandler class, and calls the GetCustomers method of the new instance in order to then display the data. Modify the load event handler so it looks like the following:
Private Sub frmADO_Load( _
ByVal sender As System.Object, _
ByVal e As System.EventArgs) Handles MyBase.Load
' Create the New Customer Object
customer = New CustomerHandler
Try
customer.GetCustomers()
If customer.RowCount > 0 Then
LoadStates()
' Display the form.
ShowData()
Else
MessageBox.Show("No rows to load. Exiting the application.")
Me.Close()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
The LoadStates method, called from the Load event handler, sets up the combo box containing the list of states. The ComboBox control makes it easy to bind its list and value to a DataTable, and this procedure handles this for you. Modify the LoadStates procedure to match the following example:
Private Sub LoadStates()
' Load cboStates from tblStates.
Try
' Watch out! If the Sorted property
' of the ComboBox control is set to
' True, the data binding will fail
' silently. In this case, the ComboBox control
' converted from VB6 with the Sorted property
' set to True, so this code simply didn't do anything.
' Setting the Sorted property to False solved
' the problem.
Dim states As DataTable = customer.GetStates()
cboState.Sorted = False
cboState.DisplayMember = "State"
cboState.ValueMember = "State"
cboState.DataSource = states
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Note When we first wrote this code, the combo box simply showed up empty. If we deleted it and created a new one from scratch, it worked fine. This indicated that some property was set incorrectly. After some research, it became clear—the Sorted property was set to True, and data binding can't work if it is. You'll need to set the Sorted property to False in order to get the data binding to work. Until you do, the combo box will appear without any items.
In the original application, both the txtData.TextChanged and chkActive.CheckedChanged event handlers ended up calling the HandleChange procedure. It's simpler to have the HandleChange procedure take care of both events itself. To do that, modify the HandleChange procedure declaration so that the procedure looks like this:
Private Sub HandleChange( _
ByVal sender As Object, ByVal e As EventArgs) _
Handles txtData.TextChanged, chkActive.CheckedChanged
' Deal with changes to text
' boxes or check box.
' If there are no rows, now you're
' editing.
' If you're just viewing data,
' now you're editing.
' Otherwise, get out.
Select Case currentDataState
Case DataState.NoRows
currentDataState = DataState.Adding
Case DataState.Normal
currentDataState = DataState.Editing
Case Else
Exit Sub
End Select
' Set up the buttons.
HandleButtonState()
End Sub
The code that handles the SelectedIndexChanged event for the State field ComboBox needs to keep track of the current state of the form, and handle changes correctly. The problem is that the SelectedIndexChanged event handler gets called when you select an item in the list portion of the combo box, even if you didn't change the value. Switching to edit mode, in this case, doesn't make sense. Therefore, the code in the SelectedIndexChanged event handler needs to compare the new value with the original value, and only switch to edit mode if the value changed. Modify the SelectedIndexChanged event handler to match the following code:
Private Sub cboState_SelectedIndexChanged( _
ByVal eventSender As System.Object, _
ByVal eventArgs As System.EventArgs) _
Handles cboState.SelectedIndexChanged
' If the State changes, modify the current DataState
Select Case currentDataState
Case DataState.NoRows
currentDataState = DataState.Adding
Case DataState.Normal
' Check to see if same State was chosen.
' If so, don't do anything.
If cboState.Text = NullToText( _
customer.CurrentRow("State")) Then
Exit Sub
End If
currentDataState = DataState.Editing
Case DataState.Editing
' Do nothing.
Case Else
Exit Sub
End Select
HandleButtonState()
End Sub
Note When preparing this article, we ran across an error in the original SelectedIndexChanged event handler, and fixed it here. That's why the code looks slightly different than in the previous version.
You can move through rows on the sample form using keystrokes instead of the mouse. To accomplish this, the sample has set the KeyPreview property of the form to True, and includes code to handle the keystrokes in the KeyDown event handler. As part of the conversion process, the KeyDown event handler includes a lot of code that checks the state of various buttons, and if they're enabled, calls the Click event handler of the button. Luckily, none of this is necessary. The Button class provides a PerformClick method that calls the Click event handler only if the button was enabled. Therefore, you can simplify the KeyDown event handler so that it includes only the following code:
Private Sub frmADO_KeyDown(ByVal eventSender As System.Object, _
ByVal eventArgs As System.Windows.Forms.KeyEventArgs) _
Handles MyBase.KeyDown
' Add support for PageUp, PageDown,
' Ctrl+PageUp, Ctrl+PageDown,
' Ctrl+Home, Ctrl+End
Select Case eventArgs.KeyCode
Case Keys.PageDown
' Ctrl+PgDn goes to the last row.
' PgDn goes to the next row.
If eventArgs.Control Then
cmdLast.PerformClick()
Else
' The PerformClick method is great: If the
' button isn't enabled, it simply doesn't
' call the method. There's no need to even
' check to see if the button is enabled or not!
cmdNext.PerformClick()
End If
Case Keys.PageUp
' Ctrl+PgUp goes to the first row.
' PgUp goes to the previous row.
If eventArgs.Control Then
cmdFirst.PerformClick()
Else
cmdPrevious.PerformClick()
End If
Case Keys.Home
' Ctrl+Home goes to the first row.
If eventArgs.Control Then
cmdFirst.PerformClick()
End If
Case Keys.End
' Ctrl+End goes to the last row.
If eventArgs.Control Then
cmdLast.PerformClick()
End If
End Select
End Sub
Note The KeyDown event handler takes advantage of its second parameter to determine if you've pressed the Ctrl key along with another key: the eventArgs.Control property will be True if so. You'll find that the eventArgs parameter includes a number of other useful properties, if you want to determine the state of the keyboard when the event was raised.
The ClearForm method loops through all the controls on the form, clearing each to a known state. Just as you saw in the earlier FindString code, you can resolve the conversion warnings by either writing a lot of code that uses the Control.GetType method, or you can continue to use the If TypeOf construct. We voted for the latter, and so you can replace the existing code with the following:
Private Sub ClearForm()
' Clear out all the controls.
' This form has only text boxes, check boxes,
' and combo boxes.
' Your forms may have other controls to worry about.
' Watch out for recursive events: setting the
' text of a textbox to "" will trigger its Change
' event, for example. That's why this code
' sets currentDataState to be Loading. No current
' code uses that particular state value, but
' it at least indicates that something's going on.
Try
currentDataState = DataState.Loading
For Each ctl As Control In Me.Controls
If TypeOf ctl Is TextBox Then
ctl.Text = ""
ElseIf TypeOf ctl Is CheckBox Then
CType(ctl, CheckBox).CheckState = CheckState.Checked
ElseIf TypeOf ctl Is ComboBox Then
CType(ctl, ComboBox).SelectedIndex = -1
' TODO: Add more control types, if necessary.
End If
Next ctl
If customer.RowCount = 0 Then
currentDataState = DataState.NoRows
Else
currentDataState = DataState.Adding
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
The Save button is only enabled when the currentDataState internal value is set to DataState.Adding or DataState.Editing. Clicking the Save button checks the state, and takes appropriate action. This procedure doesn't need to change much, as you can see—now, instead of calling methods of a Recordset, you're calling methods of the CustomerHandler class. In addition, there's no longer a need to keep track of the current bookmark in case of error. Just as in the Visual Basic 6 version, the SaveData procedure includes code to retrieve the new primary key value, and display it on the form. Replace the SaveData procedure with the following:
Private Function SaveData() As Boolean
Try
If currentDataState = DataState.Adding Then
customer.AddNew()
End If
' Whether adding or editing,
' you need to save fields and update
' the recordset.
SaveFields()
customer.Update()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
If currentDataState = DataState.Adding Then
' Display the newly added key.
GetID()
End If
' Reset buttons.
currentDataState = DataState.Normal
HandleButtonState()
End Function
The SaveFields method doesn't require much change—you simply need to move data from the form to a DataRow instance instead. Therefore, replace the SaveFields method with the following code:
Private Sub SaveFields()
Try
Dim row As DataRow = customer.CurrentRow
row.BeginEdit()
row("FirstName") = TextToNull(txtData(1).Text)
row("LastName") = TextToNull(txtData(2).Text)
row("Address") = TextToNull(txtData(3).Text)
row("City") = TextToNull(txtData(4).Text)
row("ZipCode") = TextToNull(txtData(5).Text)
row("State") = TextToNull((cboState.Text))
row("Active") = CBool(chkActive.CheckState)
row.EndEdit()
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Retrieving the new customer ID value isn't any trickier now, but it does require a small change to the code. Now, rather than retrieving a value from a RecordSet, you retrieve it from the DataTable. Replace the GetID procedure with the following code:
Private Sub GetID()
txtData(0).Text = customer.CurrentRow("CustomerID").ToString()
End Sub
The DeleteRow method becomes a little bit simpler, in this version. You no longer need to worry about maintaining a bookmark referring to the current row, so that if something goes wrong you can return to the current row. Instead, because the CustomerHandler class takes care of the details, you simply call the Delete method of the class, and then the ShowData method to display the current row. In addition, you no longer need to move to the next row, because the row number hasn't changed.
Note also that this procedure uses the MessageBox.Show method, taking advantage of the various options provided by this method. Although you're welcome to use the MsgBox function, we wanted to show off the .NET Framework equivalent in this example.
Replace the existing DeleteRow method with the following code:
Private Sub DeleteRow()
Try
If MessageBox.Show("Delete the current Customer?", _
"Delete", MessageBoxButtons.YesNoCancel, _
MessageBoxIcon.Exclamation) = DialogResult.Yes Then
' Delete the customer record in the DataTable
customer.Delete()
' Whether there's any data or not,
' show a row.
ShowData()
End If
Catch ex As Exception
MessageBox.Show(ex.Message)
End Try
End Sub
Finally (it's the last procedure you'll need to change), the FindRow method becomes substantially simpler in this version. You don't need to track the current bookmark, and restore its value if the search fails. Instead, the CustomerHandler.Find method returns True if it succeeded, making the code really simple. Replace the existing FindRow method with this code:
Private Sub FindRow()
Dim searchCriteria As String
Dim nameToFind As String
nameToFind = InputBox("Enter " & conFindField & _
" value to find:", Me.Text)
If Len(nameToFind) > 0 Then
' Search with a wildcard, using the
' value the user entered as the beginning
' of the search string.
searchCriteria = conFindField & _
" LIKE " & AddQuotes(nameToFind & "%")
' Find the record.
If customer.Find(searchCriteria) Then
ShowData()
Else
MsgBox("No match found!", MsgBoxStyle.OKOnly, Me.Text)
End If
End If
End Sub
As you've seen, replacing existing ADO code with the equivalent ADO.NET isn't terribly difficult, but you'll end up touching just about every piece of your application that communicates with the data. Of course, proper separation of user interface and data should ease the transition—we attempted to perform some fix-up in this area as we performed the ADO to ADO.NET conversion, as well. Of course, our simple application doesn't even come close to emulating a real data-oriented application—that wasn't its point. Moving on from here, you should consider issues involving data concurrency, error handling, and more advanced uses of ADO.NET; all these are covered in other articles available on MSDN (for more information, see the Overview of ADO.NET).
If we were writing this for our own use, we would have made use of inheritance, creating a base class that represents an entity (a Customer, an Order, an Employee, and so on) and included all the navigation code there. Then, each individual entity type could inherit from this base class, and wouldn't need specific navigation code. Again, this sort of addition is beyond the scope of this (already very long) article, but it's worth investigating.
In the final article in this series, we'll again gut the entire application and take advantage of the exciting new data-binding features available in Visual Studio 2005 and Visual Basic 2005. You'll be amazed at how much code you won't have to write.. | http://msdn.microsoft.com/en-us/library/ms364043(VS.80).aspx | crawl-002 | refinedweb | 8,325 | 55.84 |
MailaMaila
- Scala library wrapping javax.mail for reading and sending emails with simple APIs.
- Utilizing Typesafe config, within which javax.mail properties are directly set.
- Support parallel sending.
- Multiple password providing strategies.
- Current support sending text mail and reading mime(through parse mime object).
- Includes BatchMailTool, a simple cmd tool for sending batch mails.(See below)
Built against scala 2.11, dependencies: build.sbt
Usage:Usage:
Resolver:
resolvers += "bintray-cuzfrog-maven" at ""
Artifact:
libraryDependencies += "com.github.cuzfrog" %% "maila" % "lastest-version"
provide an application.conf or whatever config file that conforms to Typesafe Config.provide an application.conf or whatever config file that conforms to Typesafe Config.
Necessary configs are listed below:
maila { server { mail.pop3s.host = "some host" mail.smtps.host = "some host" } #not really necessary, see below: password providing strategies. authentication { #user = Cause #password = "some crypt" } }
Default with documentation reference.conf Typical and for-testing application.conf
Different config source can be used, see Typesafe config
Config can be hot reloaded with
Maila.reloadConfig ,after which new instances will be created with new config.
sending mail:sending mail:
import com.github.cuzfrog.maila.{Mail, Maila} val maila = Maila.newInstance(askUser = "user0@some.com" ,askPassword = "pw") val mail = Mail(List("recipient@google.com"), "subject", "text content") maila.send(List(mail)) maila.send(List(mail),isParallel = true) //sending every mail in Future.
reading mail:reading mail:
import com.github.cuzfrog.maila.{MailFilter, Maila} val maila = Maila.newInstance(askUser = "user0@some.com" ,askPassword = "pw") val mails1 = maila.read() //get a List of mails using default filter. val filter = MailFilter( maxSearchAmount = 30, filter = _.subject.contains("myKeyWord") ) val mails2 = maila.read(filter) //get a List of mails mails2.foreach(m => println(m.contentText)) //print text content
password providing strategies:password providing strategies:
Supply user and password directly:
Maila.newInstance(askUser = "user0@some.com" ,askPassword = "pw")
Plain text in config file(forbidden by default):
Set
allow-none-encryption-password = truein config.
//System.setProperty("config.resource", "imap.conf") //if necessary. //Everytime an instance created, property cache is invalidated. Maila.newInstance(askUser = "user0@some.com") //if cannot find password in config, fails later. Maila.newInstance() //assume user can be found in config as well.
Encrypted password in config file:
Encryption uses AES method. You need to provide a finite seq of 128/192/256bit keys. Password string is in form of Base64. You can use Batch mail tool described below to generate key and encrypt password.
val AESkey = "JYFi0VFzoUNZxLyj".getBytes("utf8") Maila.newInstance(AESkey) //try to decrypt password in config with the AES key.
Call-by-name mode, ask password when running.
val console = System.console() def _askPassword = console.readPassword().mkString Maila.newInstance(askUser = "user0@some.com",askPassword=_askPassword) //user can be lazy evaluated also.
Batch mail toolBatch mail tool
This project includes a simple cmd tool for sending batch mails. Acquire binary from:
- Release: Download
- Build: run sbt
>batchMailTool/assembly, which, in addition, will generate the windows bat file pointing to the current version.
How to use:How to use:
- add java to PATH.
- alter provided config file.
>bmt -helpyou can have all instructions.
Use a file to define mails, and send:Use a file to define mails, and send:
>bmt send -m:./mails.csv
extra args:
-password:if emitted, it will prompt and ask user to type in.
-key:if specified,
-passwordwill be ignored, bmt tries to decrypt pw from config file.
File structure should be like this:(head line cannot be emitted.)
Text content has been de-escaped, which means you can define whole text of the email like:
I will be ok if there are spaces. "If there is comma, I must be quoted." "First line.\nSecond line." "This is just one line with a double quote: \" and a special sign: \\n."
*File will be loaded completely before sending.
Change delimiter(csv files use comma), encoding, head definition in config file: reference.conf
Password tool:Password tool:
>bmt encrypt -pw:myPassword
will print encrypted password with randomly generated key. Use
-help to see more.
Debug mode:Debug mode:
In config file:
maila { #When set to true, exception stacktrace will be printed. debug = false } | https://index.scala-lang.org/cuzfrog/maila/maila/0.2.2?target=_2.11 | CC-MAIN-2020-45 | refinedweb | 681 | 54.39 |
pthread_attr_getguardsize, pthread_attr_setguardsize - get and set the thread guardsize attribute
[XSI]
#include <pthread.h>#include .
These functions shall fail if:
- [EINVAL]
- The parameter guardsize is invalid.
These functions may fail if:
- [EINVAL]
- The value specified by attr does not refer to an initialized thread attribute object.
These functions shall not return an error code of [EINTR]. */ ... } }
None.
The guardsize attribute is provided to the application for two reasons:
-
Overflow protection can potentially result in wasted system resources. An application that creates a large number of threads, and which knows its threads never overflow their stack, can save system resources by turning off guard areas.
-
When threads allocate large data structures on the stack, large guard areas may be needed to detect stack overflow.
None.
The Base Definitions volume of IEEE Std 1003.1-2001, <pthread.h>, <sys/mman.h>
First released in Issue 5.
In the ERRORS section, a third [EINVAL] error condition is removed as it is covered by the second error condition.
The restrict keyword is added to the pthread_attr_getguardsize() prototype for alignment with the ISO/IEC 9899:1999 standard.
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/74 is applied, updating the ERRORS section to remove the [EINVAL] error (``The attribute attr is invalid.''), and replacing it with the optional [EINVAL] error.
IEEE Std 1003.1-2001/Cor 2-2004, item XSH/TC2/D6/76 is applied, adding the example to the EXAMPLES section. | http://pubs.opengroup.org/onlinepubs/009695399/functions/pthread_attr_setguardsize.html | CC-MAIN-2014-41 | refinedweb | 240 | 57.67 |
Word Ladders.
FOOL POOL POLL POLE PALE SALE SAGE
There are many variations of the word ladder puzzle. For example you might be given a particular number of steps in which to accomplish the transformation, or you might need to use a particular word. In this section we are interested in figuring out the smallest number of transformations needed to turn the starting word into the ending word. an edge from one word to another if the two words are only different by a single letter. If we can create such a graph, then any path from one word to another is a solution to the word ladder puzzle. The illustration below shows a small graph of some words that solve the FOOL to SAGE word ladder problem. Notice that the graph is an undirected graph and that the edges are unweighted. algorithm. For 5,110 words,.

In Python, we can implement the scheme we have just described by using a dictionary. The labels on the buckets we have just described are the keys in our dictionary. The value stored for that key is a list of words. Once we have the dictionary built we can create the graph. We start our graph by creating a vertex for each word in the graph. Then we create edges between all the vertices we find for words found under the same key in the dictionary.
Below is an example of Python code implementing this strategy. In this case, we use a dictionary mapping vertices (words) to sets of the vertices that can be reached by changing one letter in that word.
from collections import defaultdict from itertools import product import os def build_graph(words): buckets = defaultdict(list) graph = defaultdict(set) for word in words: for i in range(len(word)): bucket = '{}_{}'.format(word[:i], word[i + 1:]) buckets[bucket].append(word) # add vertices and edges for words in the same bucket for bucket, mutual_neighbors in buckets.items(): for word1, word2 in product(mutual_neighbors, repeat=2): if word1 != word2: graph[word1].add(word2) graph[word2].add(word1) return graph def get_words(vocabulary_file): for line in open(vocabulary_file, 'r'): yield line[:-1] # remove newline character vocabulary_file = os.path.join(os.path.dirname(__file__), 'vocabulary.txt') word_graph = build_graph(get_words(vocabulary_file)) # word_graph['FOOL'] # set(['POOL', 'WOOL', 'FOWL', 'FOAL', 'FOUL', ... ])
Since this is our first real-world graph problem, you might be wondering
how sparse is the graph? The list of four-letter words
we have for this problem is 5,110 words long. If we were to use an
adjacency matrix, the matrix would have 5,110 * 5,110 = 26,112,100 cells.
The graph constructed by the
build_graph function has exactly 53,286
edges, so the matrix would have only 0.20% of the cells filled! That is
a very sparse matrix indeed.
Implementing breadth first search and a starting vertex , a breadth first search proceeds by exploring edges in the graph to find all the vertices in for which there is a path from . The remarkable thing about a breadth first search is that it finds all the vertices that are a distance from before it finds any vertices that are a distance . One good way to visualize what the breadth first search algorithm does is to imagine that it is building a tree, one level of the tree at a time. A breadth first search adds all children of the starting vertex before it begins to discover any of the grandchildren.
The breadth first search algorithm shown below uses the adjacency list graph representation we developed earlier. In addition it uses a queue at a crucial point as we will see, to decide which vertex to explore next, and also to maintain a record of the depth to which we have traversed at any point.
BFS starts by initializing a set to retain a record of which vertices
have been visited already. Next, we initialize a queue (in this case
utilizing the deque type from Python’s
collections module) which will
contain all paths from our starting vertex that we have explored as our
algorithm progress. As such we initialize it with a list containing just
our starting vertex.
The next step is to begin to systematically grow the paths one at a time, starting from the path at the front of the queue, in each case taking one more step from the vertex last explored.
Once we have popped from our queue a path to continue exploring and retrieved the last the vertex visited from that path, we retrieve its neighbors from our graph, remove those vertices that we know have already been visited, then for each of the remaining (unvisited) neighbors do two things:
- Add the vertex to
visited
- Add a path consisisting of the path so far plus the vertex
Adding the new vertex effectively schedules it for further exploration, but not until all the other vertices on the adjacency list have been explored.
from collections import deque def traverse(graph, starting_vertex): visited = set() queue = deque([[starting_vertex]]) while queue: path = queue.popleft() vertex = path[-1] yield vertex, path for neighbor in graph[vertex] - visited: visited.add(neighbor) queue.append(path + [neighbor]) if __name__ == '__main__': for vertex, path in traverse(word_graph, 'FOOL'): if vertex == 'SAGE': print ' -> '.join(path) # FOOL -> FOOD -> FOLD -> SOLD -> SOLE -> SALE -> SAGE
Let’s look at how the
traverse function would construct the breadth first
tree corresponding to the word ladder graph we considered previously.
Starting from fool we take all nodes that are adjacent to fool and add
them to the tree. The adjacent nodes include pool, foil, foul, and cool.
Each of these nodes are added to the queue of new nodes to expand.
The illustration below shows the state of the in-progress tree along
with the queue after this step.
In the next step
traverse removes the next node (pool) from the front
of the queue and repeats the process for all of its adjacent nodes.
However, when
traverse examines the node cool, it finds that it has
already been visited. This implies that there is a shorter path to cool.
The only new node added to the queue while examining pool is poll. The
new state of the tree and queue is shown below.
The next vertex on the queue is foil. The only new node that foil can
add to the tree is fail. As
traverse continues to process the queue,
neither of the next two nodes add anything new to the queue or the tree.
The illustration below shows the tree and the queue after expanding
all the vertices on the second level of the tree.
You should continue to work through the algorithm on your own so that you are comfortable with how it works. The illustration below shows the final breadth first search tree after all the vertices have been expanded.
Breadth First Search Analysis
Before we continue with other graph algorithms let us analyze the run time performance of the breadth first search algorithm. The first thing to observe is that the while loop is executed, at most, one time for each vertex in the graph . You can see that this is true because a vertex must be white before it can be examined and added to the queue. This gives us for the while loop. The for loop, which is nested inside the while is executed at most once for each edge in the graph, . The reason is that every vertex is dequeued at most once and we examine an edge from node to node only when node is dequeued. This gives us for the for loop. combining the two loops gives us .
Of course doing the breadth first search is only part of the task. Following the links from the starting node to the goal node is the other part of the task. The worst case for this would be if the graph was a single long chain. In this case traversing through all of the vertices would be . The normal case is going to be some fraction of but we would still write .
Finally, at least for this problem, there is the time required to build
the initial graph. We leave the analysis of the
build_graph function as
an exercise for you. | https://bradfieldcs.com/algos/graphs/word-ladder/ | CC-MAIN-2022-33 | refinedweb | 1,392 | 70.13 |
I've started programming 1 week ago and I use win32 console for an output.
In program which calculates pi:
Code:
The output is:The output is:Code:#include <iostream> #include <math.h> using namespace std; int main() { double b=-1; double pi=acos(b); cout << pi << endl; system("PAUSE"); return 0; }
Output:
I know that computer calculated pi with much higher precision, so how do I get, I don't know... 15 digits on the output screen?I know that computer calculated pi with much higher precision, so how do I get, I don't know... 15 digits on the output screen?Code:3.14159
One more related question. I'm trying to write a random number generator program, since I've noticed that the rand() function doesn't have the uniform distribution of random number values, and for that I need a function that would "cut" double variable started from some decimal value to some other decimal value. For example, if I have a double variable number pi=3.141592654... I want a new integer variable with value from 3rd to 6th digit, int a=592. How do I do that?
The final question. If I want to test relationship between many output variables it would be very usefull if program could put these values in a txt file. How do I do that? Remember (I don't know if that maters) I'm programming (or trying to
), that is, the output is in win32 console.), that is, the output is in win32 console.
Thank you! | http://cboard.cprogramming.com/cplusplus-programming/72874-more-digits-output-particular-digits-output-output-*-txt.html | CC-MAIN-2014-42 | refinedweb | 258 | 65.01 |
#include <ConsoleSession.h>
ConsoleSession A session that runs over an AMQP connection for QMF console operation.
The options string is of the form "{key:value,key:value}". The following keys are supported:
domain:NAME - QMF Domain to join [default: "default"] max-agent-age:N - Maximum time, in minutes, that we will tolerate not hearing from an agent before deleting it [default: 5] listen-on-direct:{True,False} - If True: Listen on legacy direct-exchange address for backward compatibility [default] If False: Listen only on the routable direct address strict-security:{True,False} - If True: Cooperate with the broker to enforce strict access control to the network
Close the session. Once closed, the session no longer communicates on the messaging network.
getAgentCount, getAgent - Retrieve the set of agents that match the console session's agent filter.
Get the agent for the connected broker (i.e. the agent embedded in the broker to which we have a connection).
Get the next event from the console session. Events represent actions that must be acted upon by the console application. This method blocks for up to the timeout if there are no events to be handled. This method will typically be the focus of the console application's main execution loop. If the timeout is set to Duration::IMMEDIATE, the call will not block.
Open the console session. After opening the session, the domain cannot be changed.
Return the number of events pending for nextEvent. This method will never block.
setDomain - Change the QMF domain that this console will operate in. If this is not called, the domain will be "default". Agents in a domain can be seen only by consoles in the same domain. This must be called prior to opening the console session.
Create a subscription that involves a subset of the known agents. The set of known agents is defined by the session's agent-filter (see setAgentFilter). The agentFilter argument to the subscribe method is used to further refine the set of agents. If agentFilter is the empty string (i.e. match-all) the subscription will involve all known agents. If agentFilter is non-empty, it will be applied only to the set of known agents. A subscription cannot be created that involves an agent not known by the session. | http://qpid.apache.org/releases/qpid-0.24/qmf/cpp/api/classqmf_1_1ConsoleSession.html | CC-MAIN-2015-06 | refinedweb | 380 | 66.64 |
Feature Requests item #950644, was opened at 2004-05-08 18:52 Message generated for change (Comment added) made by nnorwitz You can respond by visiting: Please note that this message will contain a full copy of the comment thread, including the initial issue submission, for this request, not just the latest update. Category: Parser/Compiler Group: None Status: Open Resolution: None Priority: 5 Private: No Submitted By: David Albert Torpey (dtorp) Assigned to: Nobody/Anonymous (nobody) Summary: Allow any lvalue for function definitions Initial Comment: A definition like: def M(x): return 2*x is the same as: M = lambda x: 2*x With the latter form, I can use any lvalue: A[0] = lambda x: 2*x B.f = lambda x: 2*x But with the first form, you're locked into just using a plain variable name. If this were fixed, it wouldn't break anything else but would be useful for making method definitons outside of a class definition: This came up when I was experimenting with David MacQuigg's ideas for prototype OO. I want to write something like: Account = Object.clone() Account.balance = 0 def Account.deposit(self, v): self.balance += v Unfortunately, the latter has to be written: def Account.deposit(self, v): self.balance += v Account.deposit = deposit ---------------------------------------------------------------------- >Comment By: Neal Norwitz (nnorwitz) Date: 2007-03-15 23:04 Message: Logged In: YES user_id=33168 Originator: NO Pinging to check interest. ---------------------------------------------------------------------- Comment By: Guido van Rossum (gvanrossum) Date: 2004-06-28 10:43 Message: Logged In: YES user_id=6380 This is the kind of thing that needs a lot of thought going into it to decide whether it is a net improvement to the language. Right now my gut feeling is that it's not worth the complexity, and more likely to be used towards unnecessary obfuscation. The redability gain is minimal if not negative IMO. Also, I've sometimes typed "def self.foo(args):" instead of "def foo(self, args):" suggesting that there's more than one intuitive way of interpreting the proposed syntax. Another minus point. ---------------------------------------------------------------------- Comment By: Raymond Hettinger (rhettinger) Date: 2004-06-24 10:08 Message: Logged In: YES user_id=80475 Guido, are you open to this? If so, I would be happy to draft a patch. I wouldn't expect it to become mainstream, but it would open the door to working with namespaces more directly. AFAICT, there is no downside to allowing this capability. ---------------------------------------------------------------------- Comment By: Raymond Hettinger (rhettinger) Date: 2004-05-20 22:57 Message: Logged In: YES user_id=80475 I think this should be made possible. It allows for alternate coding styles wihout harming anything else. The Lua programming language has something similar. It is a lightweight, non-OO language that revolves around making the best possible use of namespaces. Direct assignments into a namespace come up in several contexts throughout the language and are key to Lua's flexibility (using one concept to meet all needs). My only concern is that "def" and "class" statements also have the side effect of binding the __name__ attribute. We would have to come up with a lambda style placeholder for the attribute. ---------------------------------------------------------------------- Comment By: Michael Chermside (mcherm) Date: 2004-05-19 17:56 Message: Logged In: YES user_id=99874 I'm highly dubious of this. I see little advantage to doing the definition and storing the value in a single line, mostly because I rarely want to do such a thing. Your example may be convincing in Prothon or some relative, but in Python the sensible way to do it is a normal method. I'd suggest that if you want this idea to go anywhere that you try posting this to c.l.py and seeing if you can drum up interest and support there. ---------------------------------------------------------------------- You can respond by visiting: | http://mail.python.org/pipermail/python-bugs-list/2007-March/037627.html | CC-MAIN-2013-20 | refinedweb | 635 | 62.68 |
RESOLVED
When an integer containing "0" or "4" is entered, this if-statement only returns the first in the statement.
For example, in the code below, if I enter "60", it will execute:
print "Nice, you're not greedy - you win!" exit(0)
NOT
dead("You greedy bastard!")
as I expected with how_much >= 50.
Have tried a bunch of changes, but can't seem to get to execute as intended. Anyone know what's going on here?
def gold_room():
print "This room is full of gold. How much do you take?"
number_type = False
while True:
choice = raw_input("> ")
how_much = int(choice)
if "0" in choice or "4" in choice and how_much < 50:
print "Nice, you're not greedy - you win!"
exit(0)
elif "0" in choice or "4" in choice and how_much >= 50:
dead("You greedy bastard!")
else:
print "Man, learn to type a number. Put a 0 or a 4 in your number."
You have an order-of-operations issue. The
and operator binds more tightly than the
or operator, so when you write:
if "0" in choice or "4" in choice and how_much < 50:
You are actually getting:
if ("0" in choice) or ("4" in choice and how_much < 50):
And hopefully, with those parentheses, it's obvious why entering
60 triggers the "Nice, you're not greedy - you win!" message (because it matches the
"0" in choice coindition, and since that condition is true, the entire
or statement is true).
Add parentheses to get what you want:
if ("0" in choice or "4" in choice) and how_much < 50:
See this article for details. | https://codedump.io/share/Sb1rqr121wSI/1/python-ifelse-only-returning-in-order-not-by-logic | CC-MAIN-2018-22 | refinedweb | 264 | 81.02 |
I’m just going to jump right into the definitions and rigor, so if you haven’t read the previous post motivating the singular value decomposition, go back and do that first. This post will be theorem, proof, algorithm, data. The data set we test on is a thousand-story CNN news data set. All of the data, code, and examples used in this post is in a github repository, as usual.
We start with the best-approximating
-dimensional linear subspace.
Definition: Let
be a set of
points in
. The best approximating
-dimensional linear subspace of
is the
-dimensional linear subspace
which minimizes the sum of the squared distances from the points in
to
.
Let me clarify what I mean by minimizing the sum of squared distances. First we’ll start with the simple case: we have a vector
, and a candidate line
(a 1-dimensional subspace) that is the span of a unit vector
. The squared distance from
to the line spanned by
is the squared length of
minus the squared length of the projection of
onto
. Here’s a picture.
I’m saying that the pink vector
in the picture is the difference of the black and green vectors
, and that the “distance” from
to
is the length of the pink vector. The reason is just the Pythagorean theorem: the vector
is the hypotenuse of a right triangle whose other two sides are the projected vector
and the difference vector
.
Let’s throw down some notation. I’ll call
the linear map that takes as input a vector
and produces as output the projection of
onto
. In fact we have a brief formula for this when
is a unit vector. If we call
the usual dot product, then
. That’s
scaled by the inner product of
and
. In the picture above, since the line
is the span of the vector
, that means that
and
.
The dot-product formula is useful for us because it allows us to compute the squared length of the projection by taking a dot product
. So then a formula for the distance of
from the line spanned by the unit vector
is
This formula is just a restatement of the Pythagorean theorem for perpendicular vectors.
In particular, the difference vector we originally called
has squared length
. The vector
, which is perpendicular to
and is also the projection of
onto
, it’s squared length is
. And the Pythagorean theorem tells us that summing those two squared lengths gives you the squared length of the hypotenuse
.
If we were trying to find the best approximating 1-dimensional subspace for a set of data points
, then we’d want to minimize the sum of the squared distances for every point
. Namely, we want the
that solves
.
With some slight algebra we can make our life easier. The short version: minimizing the sum of squared distances is the same thing as maximizing the sum of squared lengths of the projections. The longer version: let’s go back to a single point
and the line spanned by
. The Pythagorean theorem told us that
The squared length of
is constant. It’s an input to the algorithm and it doesn’t change through a run of the algorithm. So we get the squared distance by subtracting
from a constant number,
which means if we want to minimize the squared distance, we can instead maximize the squared projection. Maximizing the subtracted thing minimizes the whole expression.
It works the same way if you’re summing over all the data points in
. In fact, we can say it much more compactly this way. If the rows of
are your data points, then
contains as each entry the (signed) dot products
. And the squared norm of this vector,
, is exactly the sum of the squared lengths of the projections of the data onto the line spanned by
. The last thing is that maximizing a square is the same as maximizing its square root, so we can switch freely between saying our objective is to find the unit vector
that maximizes
and that which maximizes
.
At this point you should be thinking,
Great, we have written down an optimization problem:
. If we could solve this, we’d have the best 1-dimensional linear approximation to the data contained in the rows of. If we could solve this, we’d have the best 1-dimensional linear approximation to the data contained in the rows of
. But (1) how do we solve that problem? And (2) you promised a. But (1) how do we solve that problem? And (2) you promised a
-dimensional approximating subspace. I feel betrayed! Swindled! Bamboozled!-dimensional approximating subspace. I feel betrayed! Swindled! Bamboozled!
Here’s the fantastic thing. We can solve the 1-dimensional optimization problem efficiently (we’ll do it later in this post), and (2) is answered by the following theorem.
The SVD Theorem: Computing the best
-dimensional subspace reduces to
applications of the one-dimensional problem.
We will prove this after we introduce the terms “singular value” and “singular vector.”
Singular values and vectors
As I just said, we can get the best
-dimensional approximating linear subspace by solving the one-dimensional maximization problem
times. The singular vectors of
are defined recursively as the solutions to these sub-problems. That is, I’ll call
the first singular vector of
, and it is:
And the corresponding first singular value, denoted
, is the maximal value of the optimization objective, i.e.
. (I will use this term frequently, that
is the “objective” of the optimization problem.) Informally speaking,
represents how much of the data was captured by the first singular vector. Meaning, how close the vectors are to lying on the line spanned by
. Larger values imply the approximation is better. In fact, if all the data points lie on a line, then
is the sum of the squared norms of the rows of
.
Now here is where we see the reduction from the
-dimensional case to the 1-dimensional case. To find the best 2-dimensional subspace, you first find the best one-dimensional subspace (spanned by
), and then find the best 1-dimensional subspace, but only considering those subspaces that are the spans of unit vectors perpendicular to
. The notation for “vectors
perpendicular to
” is
. Restating, the second singular vector
is defined as
And the SVD theorem implies the subspace spanned by
is the best 2-dimensional linear approximation to the data. Likewise
is the second singular value. Its squared magnitude tells us how much of the data that was not “captured” by
is captured by
. Again, if the data lies in a 2-dimensional subspace, then the span of
will be that subspace.
We can continue this process. Recursively define
, the
-th singular vector, to be the vector which maximizes
, when
is considered only among the unit vectors which are perpendicular to
. The corresponding singular value
is the value of the optimization problem.
As a side note, because of the way we defined the singular values as the objective values of “nested” optimization problems, the singular values are decreasing,
. This is obvious: you only pick
in the second optimization problem because you already picked
which gave a bigger singular value, so
‘s objective can’t be bigger.
If you keep doing this, one of two things happen. Either you reach
and since the domain is
-dimensional there are no remaining vectors to choose from, the
are an orthonormal basis of
. This means that the data in
contains a full-rank submatrix. The data does not lie in any smaller-dimensional subspace. This is what you’d expect from real data.
Alternatively, you could get to a stage
with
and when you try to solve the optimization problem you find that every perpendicular
has
. In this case, the data actually does lie in a
-dimensional subspace, and the first-through-
-th singular vectors you computed span this subspace.
Let’s do a quick sanity check: how do we know that the singular vectors
form a basis? Well formally they only span a basis of the row space of
, i.e. a basis of the subspace spanned by the data contained in the rows of
. But either way the point is that each
spans a new dimension from the previous
because we’re choosing
to be orthogonal to all the previous
. So the answer to our sanity check is “by construction.”
Back to the singular vectors, the discussion from the last post tells us intuitively that the data is probably never in a small subspace. You never expect the process of finding singular vectors to stop before step
, and if it does you take a step back and ask if something deeper is going on. Instead, in real life you specify how much of the data you want to capture, and you keep computing singular vectors until you’ve passed the threshold. Alternatively, you specify the amount of computing resources you’d like to spend by fixing the number of singular vectors you’ll compute ahead of time, and settle for however good the
-dimensional approximation is.
Before we get into any code or solve the 1-dimensional optimization problem, let’s prove the SVD theorem.
Proof of SVD theorem.
Recall we’re trying to prove that the first
singular vectors provide a linear subspace
which maximizes the squared-sum of the projections of the data onto
. For
this is trivial, because we defined
to be the solution to that optimization problem. The case of
contains all the important features of the general inductive step. Let
be any best-approximating 2-dimensional linear subspace for the rows of
. We’ll show that the subspace spanned by the two singular vectors
is at least as good (and hence equally good).
Let
be any orthonormal basis for
and let
be the quantity that we’re trying to maximize (and which
maximizes by assumption). Moreover, we can pick the basis vector
to be perpendicular to
. To prove this we consider two cases: either
is already perpendicular to
in which case it’s trivial, or else
isn’t perpendicular to
and you can choose
to be
and choose
to be any unit vector perpendicular to
.
Now since
maximizes
, we have
. Moreover, since
is perpendicular to
, the way we chose
also makes
. Hence the objective
, as desired.
For the general case of
, the inductive hypothesis tells us that the first
terms of the objective for
singular vectors is maximized, and we just have to pick any vector
that is perpendicular to all
, and the rest of the proof is just like the 2-dimensional case.
Now remember that in the last post we started with the definition of the SVD as a decomposition of a matrix
? And then we said that this is a certain kind of change of basis? Well the singular vectors
together form the columns of the matrix
(the rows of
), and the corresponding singular values
are the diagonal entries of
. When
is understood we’ll abbreviate the singular value as
.
To reiterate with the thoughts from last post, the process of applying
is exactly recovered by the process of first projecting onto the (full-rank space of) singular vectors
, scaling each coordinate of that projection according to the corresponding singular values, and then applying this
thing we haven’t talked about yet.
So let’s determine what
has to be. The way we picked
to make
diagonal gives us an immediate suggestion: use the
as the columns of
. Indeed, define
, the images of the singular vectors under
. We can swiftly show the
form a basis of the image of
. The reason is because if
(using all
of the singular vectors
), then by linearity
. It is also easy to see why the
are orthogonal (prove it as an exercise). Let’s further make sure the
are unit vectors and redefine them as
If you put these thoughts together, you can say exactly what
does to any given vector
. Since the
form an orthonormal basis,
, and then applying
gives
If you’ve been closely reading this blog in the last few months, you’ll recognize a very nice way to write the last line of the above equation. It’s an outer product. So depending on your favorite symbols, you’d write this as either
or
. Or, if you like expressing things as matrix factorizations, as
. All three are describing the same object.
Let’s move on to some code.
A black box example
Before we implement SVD from scratch (an urge that commands me from the depths of my soul!), let’s see a black-box example that uses existing tools. For this we’ll use the numpy library.
Recall our movie-rating matrix from the last post:
The code to compute the svd of this matrix is as simple as it gets:
from numpy.linalg import svd movieRatings = [ [2, 5, 3], [1, 2, 1], [4, 1, 1], [3, 5, 2], [5, 3, 1], [4, 5, 5], [2, 4, 2], [2, 2, 5], ] U, singularValues, V = svd(movieRatings)
Printing these values out gives
[[-0.39458526 0.23923575 -0.35445911 -0.38062172 -0.29836818 -0.49464816 -0.30703202 -0.29763321] [-0.15830232 0.03054913 -0.15299759 -0.45334816 0.31122898 0.23892035 -0.37313346 0.67223457] [-0.22155201 -0.52086121 0.39334917 -0.14974792 -0.65963979 0.00488292 -0.00783684 0.25934607] [-0.39692635 -0.08649009 -0.41052882 0.74387448 -0.10629499 0.01372565 -0.17959298 0.26333462] [-0.34630257 -0.64128825 0.07382859 -0.04494155 0.58000668 -0.25806239 0.00211823 -0.24154726] [-0.53347449 0.19168874 0.19949342 -0.03942604 0.00424495 0.68715732 -0.06957561 -0.40033035] [-0.31660464 0.06109826 -0.30599517 -0.19611823 -0.01334272 0.01446975 0.85185852 0.19463493] [-0.32840223 0.45970413 0.62354764 0.1783041 0.17631186 -0.39879476 0.06065902 0.25771578]] []]
Now this is a bit weird, because the matrices
are the wrong shape! Remember, there are only supposed to be three vectors since the input matrix has rank three. So what gives? This is a distinction that goes by the name “full” versus “reduced” SVD. The idea goes back to our original statement that
is a decomposition with
both orthogonal and square matrices. But in the derivation we did in the last section, the
and
were not square. The singular vectors
could potentially stop before even becoming full rank.
In order to get to square matrices, what people sometimes do is take the two bases
and
and arbitrarily choose ways to complete them to a full orthonormal basis of their respective vector spaces. In other words, they just make the matrix square by filling it with data for no reason other than that it’s sometimes nice to have a complete basis. We don’t care about this. To be honest, I think the only place this comes in useful is in the desire to be particularly tidy in a mathematical formulation of something.
We can still work with it programmatically. By fudging around a bit with numpy’s shapes to get a diagonal matrix, we can reconstruct the input rating matrix from the factors.
Sigma = np.vstack([ np.diag(singularValues), np.zeros((5, 3)), ]) print(np.round(movieRatings - np.dot(U, np.dot(Sigma, V)), decimals=10))
And the output is, as one expects, a matrix of all zeros. Meaning that we decomposed the movie rating matrix, and built it back up from the factors.
We can actually get the SVD as we defined it (with rectangular matrices) by passing a special flag to numpy’s svd.
U, singularValues, V = svd(movieRatings, full_matrices=False) print(U) print(singularValues) print(V) Sigma = np.diag(singularValues) print(np.round(movieRatings - np.dot(U, np.dot(Sigma, V)), decimals=10))
And the result
[[-0.39458526 0.23923575 -0.35445911] [-0.15830232 0.03054913 -0.15299759] [-0.22155201 -0.52086121 0.39334917] [-0.39692635 -0.08649009 -0.41052882] [-0.34630257 -0.64128825 0.07382859] [-0.53347449 0.19168874 0.19949342] [-0.31660464 0.06109826 -0.30599517] [-0.32840223 0.45970413 0.62354764]] []] [[-0. -0. -0.] [-0. -0. 0.] [ 0. -0. 0.] [-0. -0. -0.] [-0. -0. -0.] [-0. -0. -0.] [-0. -0. -0.] [ 0. -0. -0.]]
This makes the reconstruction less messy, since we can just multiply everything without having to add extra rows of zeros to
.
What do the singular vectors and values tell us about the movie rating matrix? (Besides nothing, since it’s a contrived example) You’ll notice that the first singular vector
while the other two singular values are around
. This tells us that the first singular vector covers a large part of the structure of the matrix. I.e., a rank-1 matrix would be a pretty good approximation to the whole thing. As an exercise to the reader, write a program that evaluates this claim (how good is “good”?).
The greedy optimization routine
Now we’re going to write SVD from scratch. We’ll first implement the greedy algorithm for the 1-d optimization problem, and then we’ll perform the inductive step to get a full algorithm. Then we’ll run it on the CNN data set.
The method we’ll use to solve the 1-dimensional problem isn’t necessarily industry strength (see this document for a hint of what industry strength looks like), but it is simple conceptually. It’s called the power method. Now that we have our decomposition of theorem, understanding how the power method works is quite easy.
Let’s work in the language of a matrix decomposition
, more for practice with that language than anything else (using outer products would give us the same result with slightly different computations). Then let’s observe
, wherein we’ll use the fact that
is orthonormal and so
is the identity matrix:
So we can completely eliminate
from the discussion, and look at just
. And what’s nice about this matrix is that we can compute its eigenvectors, and eigenvectors turn out to be exactly the singular vectors. The corresponding eigenvalues are the squared singular values. This should be clear from the above derivation. If you apply
to any
, the only parts of the product that aren’t zero are the ones involving
with itself, and the scalar
factors in smoothly. It’s dead simple to check.
Theorem: Let
be a random unit vector and let
. Then with high probability,
is in the span of the first singular vector
. If we normalize
to a unit vector at each
, then furthermore the limit is
.
Proof. Start with a random unit vector
, and write it in terms of the singular vectors
. That means
. If you recursively apply this logic, you get
. In particular, the dot product of
with any
is
.
What this means is that so long as the first singular value
is sufficiently larger than the second one
, and in turn all the other singular values, the part of
corresponding to
will be much larger than the rest. Recall that if you expand a vector in terms of an orthonormal basis, in this case
expanded in the
, the coefficient of
on
is exactly the dot product. So to say that
converges to being in the span of
is the same as saying that the ratio of these coefficients,
for any
. In other words, the coefficient corresponding to the first singular vector dominates all of the others. And so if we normalize, the coefficient of
corresponding to
tends to 1, while the rest tend to zero.
Indeed, this ratio is just
and the base of this exponential is bigger than 1.
If you want to be a little more precise and find bounds on the number of iterations required to converge, you can. The worry is that your random starting vector is “too close” to one of the smaller singular vectors
, so that if the ratio of
is small, then the “pull” of
won’t outweigh the pull of
fast enough. Choosing a random unit vector allows you to ensure with high probability that this doesn’t happen. And conditioned on it not happening (or measuring “how far the event is from happening” precisely), you can compute a precise number of iterations required to converge. The last two pages of these lecture notes have all the details.
We won’t compute a precise number of iterations. Instead we’ll just compute until the angle between
and
is very small. Here’s the algorithm
import numpy as np from numpy.linalg import norm from random import normalvariate from math import sqrt def randomUnitVector(n): unnormalized = [normalvariate(0, 1) for _ in range(n)] theNorm = sqrt(sum(x * x for x in unnormalized)) return [x / theNorm for x in unnormalized] def svd_1d(A, epsilon=1e-10): ''' The one-dimensional SVD ''' n, m = A.shape x = randomUnitVector(m) lastV = None currentV = x B = np.dot(A.T, A) iterations = 0 while True: iterations += 1 lastV = currentV currentV = np.dot(B, lastV) currentV = currentV / norm(currentV) if abs(np.dot(currentV, lastV)) > 1 - epsilon: print("converged in {} iterations!".format(iterations)) return currentV
We start with a random unit vector
, and then loop computing
, renormalizing at each step. The condition for stopping is that the magnitude of the dot product between
and
(since they’re unit vectors, this is the cosine of the angle between them) is very close to 1.
And using it on our movie ratings example:
if __name__ == "__main__": movieRatings = np.array([ [2, 5, 3], [1, 2, 1], [4, 1, 1], [3, 5, 2], [5, 3, 1], [4, 5, 5], [2, 4, 2], [2, 2, 5], ], dtype='float64') print(svd_1d(movieRatings))
With the result
converged in 6 iterations! [-0.54184805 -0.67070993 -0.50650655]
Note that the sign of the vector may be different from numpy’s output because we start with a random vector to begin with.
The recursive step, getting from
to the entire SVD, is equally straightforward. Say you start with the matrix
and you compute
. You can use
to compute
and
. Then you want to ensure you’re ignoring all vectors in the span of
for your next greedy optimization, and to do this you can simply subtract the rank 1 component of
corresponding to
. I.e., set
. Then it’s easy to see that
and basically all the singular vectors shift indices by 1 when going from
to
. Then you repeat.
If that’s not clear enough, here’s the code.
def svd(A, epsilon=1e-10): n, m = A.shape svdSoFar = [] for i in range(m): matrixFor1D = A.copy() for singularValue, u, v in svdSoFar[:i]: matrixFor1D -= singularValue * np.outer(u, v) v = svd_1d(matrixFor1D, epsilon=epsilon) # next singular vector u_unnormalized = np.dot(A, v) sigma = norm(u_unnormalized) # next singular value u = u_unnormalized / sigma svdSoFar.append((sigma, u, v)) # transform it into matrices of the right shape singularValues, us, vs = [np.array(x) for x in zip(*svdSoFar)] return singularValues, us.T, vs
And we can run this on our movie rating matrix to get the following
>>> theSVD = svd(movieRatings) >>> theSVD[0] array([ 15.09626916, 4.30056855, 3.40701739]) >>> theSVD[1] array([[ 0.39458528, -0.23923093, 0.35446407], [ 0.15830233, -0.03054705, 0.15299815], [ 0.221552 , 0.52085578, -0.39336072], [ 0.39692636, 0.08649568, 0.41052666], [ 0.34630257, 0.64128719, -0.07384286], [ 0.53347448, -0.19169154, -0.19948959], [ 0.31660465, -0.0610941 , 0.30599629], [ 0.32840221, -0.45971273, -0.62353781]]) >>> theSVD[2] array([[ 0.54184805, 0.67071006, 0.50650638], [ 0.75151641, -0.11679644, -0.64929321], [-0.37632934, 0.73246611, -0.56733554]])
Checking this against our numpy output shows it’s within a reasonable level of precision (considering the power method took on the order of ten iterations!)
>>> np.round(np.abs(npSVD[0]) - np.abs(theSVD[1]), decimals=5) array([[ -0.00000000e+00, -0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, -0.00000000e+00, 0.00000000e+00], [ 0.00000000e+00, -1.00000000e-05, 1.00000000e-05], [ 0.00000000e+00, 0.00000000e+00, -0.00000000e+00], [ 0.00000000e+00, -0.00000000e+00, 1.00000000e-05], [ -0.00000000e+00, 0.00000000e+00, -0.00000000e+00], [ 0.00000000e+00, -0.00000000e+00, 0.00000000e+00], [ -0.00000000e+00, 1.00000000e-05, -1.00000000e-05]]) >>> np.round(np.abs(npSVD[2]) - np.abs(theSVD[2]), decimals=5) array([[ 0.00000000e+00, 0.00000000e+00, -0.00000000e+00], [ -1.00000000e-05, -1.00000000e-05, 1.00000000e-05], [ 1.00000000e-05, 0.00000000e+00, -1.00000000e-05]]) >>> np.round(np.abs(npSVD[1]) - np.abs(theSVD[0]), decimals=5) array([ 0., 0., -0.])
So there we have it. We added an extra little bit to the svd function, an argument
which stops computing the svd after it reaches rank
.
CNN stories
One interesting use of the SVD is in topic modeling. Topic modeling is the process of taking a bunch of documents (news stories, or emails, or movie scripts, whatever) and grouping them by topic, where the algorithm gets to choose what counts as a “topic.” Topic modeling is just the name that natural language processing folks use instead of clustering.
The SVD can help one model topics as follows. First you construct a matrix
called a document-term matrix whose rows correspond to words in some fixed dictionary and whose columns correspond to documents. The
entry of
contains the number of times word
shows up in document
. Or, more precisely, some quantity derived from that count, like a normalized count. See this table on wikipedia for a list of options related to that. We’ll just pick one arbitrarily for use in this post.
The point isn’t how we normalize the data, but what the SVD of
means in this context. Recall that the domain of
, as a linear map, is a vector space whose dimension is the number of stories. We think of the vectors in this space as documents, or rather as an “embedding” of the abstract concept of a document using the counts of how often each word shows up in a document as a proxy for the semantic meaning of the document. Likewise, the codomain is the space of all words, and each word is embedded by which documents it occurs in. If we compare this to the movie rating example, it’s the same thing: a movie is the vector of ratings it receives from people, and a person is the vector of ratings of various movies.
Say you take a rank 3 approximation to
. Then you get three singular vectors
which form a basis for a subspace of words, i.e., the “idealized” words. These idealized words are your topics, and you can compute where a “new word” falls by looking at which documents it appears in (writing it as a vector in the domain) and saying its “topic” is the closest of the
. The same process applies to new documents. You can use this to cluster existing documents as well.
The dataset we’ll use for this post is a relatively small corpus of a thousand CNN stories picked from 2012. Here’s an excerpt from one of them
$ cat data/cnn-stories/story479.txt 3 things to watch on Super Tuesday, ...
So let’s first build this document-term matrix, with the normalized values, and then we’ll compute it’s SVD and see what the topics look like.
Step 1 is cleaning the data. We used a bunch of routines from the nltk library that boils down to this loop:
for filename, documentText in documentDict.items(): tokens = tokenize(documentText) tagged_tokens = pos_tag(tokens) wnl = WordNetLemmatizer() stemmedTokens = [wnl.lemmatize(word, wordnetPos(tag)).lower() for word, tag in tagged_tokens]
This turns the Super Tuesday story into a list of words (with repetition):
["thing", "watch", "three", "thing", "watch", "big", ... ]
If you’ll notice the name Romney doesn’t show up in the list of words. I’m only keeping the words that show up in the top 100,000 most common English words, and then lemmatizing all of the words to their roots. It’s not a perfect data cleaning job, but it’s simple and good enough for our purposes.
Now we can create the document term matrix.
def makeDocumentTermMatrix(data): words = allWords(data) # get the set of all unique words wordToIndex = dict((word, i) for i, word in enumerate(words)) indexToWord = dict(enumerate(words)) indexToDocument = dict(enumerate(data)) matrix = np.zeros((len(words), len(data))) for docID, document in enumerate(data): docWords = Counter(document['words']) for word, count in docWords.items(): matrix[wordToIndex[word], docID] = count return matrix, (indexToWord, indexToDocument)
This creates a matrix with the raw integer counts. But what we need is a normalized count. The idea is that a common word like “thing” shows up disproportionately more often than “election,” and we don’t want raw magnitude of a word count to outweigh its semantic contribution to the classification. This is the applied math part of the algorithm design. So what we’ll do (and this technique together with SVD is called latent semantic indexing) is normalize each entry so that it measures both the frequency of a term in a document and the relative frequency of a term compared to the global frequency of that term. There are many ways to do this, and we’ll just pick one. See the github repository if you’re interested.
So now lets compute a rank 10 decomposition and see how to cluster the results.
data = load() matrix, (indexToWord, indexToDocument) = makeDocumentTermMatrix(data) matrix = normalize(matrix) sigma, U, V = svd(matrix, k=10)
This uses our svd, not numpy’s. Though numpy’s routine is much faster, it’s fun to see things work with code written from scratch. The result is too large to display here, but I can report the singular values.
>>> sigma array([ 42.85249098, 21.85641975, 19.15989197, 16.2403354 , 15.40456779, 14.3172779 , 13.47860033, 13.23795002, 12.98866537, 12.51307445])
Now we take our original inputs and project them onto the subspace spanned by the singular vectors. This is the part that represents each word (resp., document) in terms of the idealized words (resp., documents), the singular vectors. Then we can apply a simple k-means clustering algorithm to the result, and observe the resulting clusters as documents.
projectedDocuments = np.dot(matrix.T, U) projectedWords = np.dot(matrix, V.T) documentCenters, documentClustering = cluster(projectedDocuments) wordCenters, wordClustering = cluster(projectedWords) wordClusters = [ [indexToWord[i] for (i, x) in enumerate(wordClustering) if x == j] for j in range(len(set(wordClustering))) ] documentClusters = [ [indexToDocument[i]['text'] for (i, x) in enumerate(documentClustering) if x == j] for j in range(len(set(documentClustering))) ]
And now we can inspect individual clusters. Right off the bat we can tell the clusters aren’t quite right simply by looking at the sizes of each cluster.
>>> Counter(wordClustering) Counter({1: 9689, 2: 1051, 8: 680, 5: 557, 3: 321, 7: 225, 4: 174, 6: 124, 9: 123}) >>> Counter(documentClustering) Counter({7: 407, 6: 109, 0: 102, 5: 87, 9: 85, 2: 65, 8: 55, 4: 47, 3: 23, 1: 15})
What looks wrong to me is the size of the largest word cluster. If we could group words by topic, then this is saying there’s a topic with over nine thousand words associated with it! Inspecting it even closer, it includes words like “vegan,” “skunk,” and “pope.” On the other hand, some word clusters are spot on. Examine, for example, the fifth cluster which includes words very clearly associated with crime stories.
>>> wordClusters[4] ['account', 'accuse', 'act', 'affiliate', 'allegation', 'allege', 'altercation', 'anything', 'apartment', 'arrest', 'arrive', 'assault', 'attorney', 'authority', 'bag', 'black', 'blood', 'boy', 'brother', 'bullet', 'candy', 'car', 'carry', 'case', 'charge', 'chief', 'child', 'claim', 'client', 'commit', 'community', 'contact', 'convenience', 'court', 'crime', 'criminal', 'cry', 'dead', 'deadly', 'death', 'defense', 'department', 'describe', 'detail', 'determine', 'dispatcher', 'district', 'document', 'enforcement', 'evidence', 'extremely', 'family', 'father', 'fear', 'fiancee', 'file', 'five', 'foot', 'friend', 'front', 'gate', 'girl', 'girlfriend', 'grand', 'ground', 'guilty', 'gun', 'gunman', 'gunshot', 'hand', 'happen', 'harm', 'head', 'hear', 'heard', 'hoodie', 'hour', 'house', 'identify', 'immediately', 'incident', 'information', 'injury', 'investigate', 'investigation', 'investigator', 'involve', 'judge', 'jury', 'justice', 'kid', 'killing', 'lawyer', 'legal', 'letter', 'life', 'local', 'man', 'men', 'mile', 'morning', 'mother', 'murder', 'near', 'nearby', 'neighbor', 'newspaper', 'night', 'nothing', 'office', 'officer', 'online', 'outside', 'parent', 'person', 'phone', 'police', 'post', 'prison', 'profile', 'prosecute', 'prosecution', 'prosecutor', 'pull', 'racial', 'racist', 'release', 'responsible', 'return', 'review', 'role', 'saw', 'scene', 'school', 'scream', 'search', 'sentence', 'serve', 'several', 'shoot', 'shooter', 'shooting', 'shot', 'slur', 'someone', 'son', 'sound', 'spark', 'speak', 'staff', 'stand', 'store', 'story', 'student', 'surveillance', 'suspect', 'suspicious', 'tape', 'teacher', 'teen', 'teenager', 'told', 'tragedy', 'trial', 'vehicle', 'victim', 'video', 'walk', 'watch', 'wear', 'whether', 'white', 'witness', 'young']
As sad as it makes me to see that ‘black’ and ‘slur’ and ‘racial’ appear in this category, it’s a reminder that naively using the output of a machine learning algorithm can perpetuate racism.
Here’s another interesting cluster corresponding to economic words:
>>> wordClusters[6] ['agreement', 'aide', 'analyst', 'approval', 'approve', 'austerity', 'average', 'bailout', 'beneficiary', 'benefit', 'bill', 'billion', 'break', 'broadband', 'budget', 'class', 'combine', 'committee', 'compromise', 'conference', 'congressional', 'contribution', 'core', 'cost', 'currently', 'cut', 'deal', 'debt', 'defender', 'deficit', 'doc', 'drop', 'economic', 'economy', 'employee', 'employer', 'erode', 'eurozone', 'expire', 'extend', 'extension', 'fee', 'finance', 'fiscal', 'fix', 'fully', 'fund', 'funding', 'game', 'generally', 'gleefully', 'growth', 'hamper', 'highlight', 'hike', 'hire', 'holiday', 'increase', 'indifferent', 'insistence', 'insurance', 'job', 'juncture', 'latter', 'legislation', 'loser', 'low', 'lower', 'majority', 'maximum', 'measure', 'middle', 'negotiation', 'offset', 'oppose', 'package', 'pass', 'patient', 'pay', 'payment', 'payroll', 'pension', 'plight', 'portray', 'priority', 'proposal', 'provision', 'rate', 'recession', 'recovery', 'reduce', 'reduction', 'reluctance', 'repercussion', 'rest', 'revenue', 'rich', 'roughly', 'sale', 'saving', 'scientist', 'separate', 'sharp', 'showdown', 'sign', 'specialist', 'spectrum', 'spending', 'strength', 'tax', 'tea', 'tentative', 'term', 'test', 'top', 'trillion', 'turnaround', 'unemployed', 'unemployment', 'union', 'wage', 'welfare', 'worker', 'worth']
One can also inspect the stories, though the clusters are harder to print out here. Interestingly the first cluster of documents are stories exclusively about Trayvon Martin. The second cluster is mostly international military conflicts. The third cluster also appears to be about international conflict, but what distinguishes it from the first cluster is that every story in the second cluster discusses Syria.
>>> len([x for x in documentClusters[1] if 'Syria' in x]) / len(documentClusters[1]) 0.05555555555555555 >>> len([x for x in documentClusters[2] if 'Syria' in x]) / len(documentClusters[2]) 1.0
Anyway, you can explore the data more at your leisure (and tinker with the parameters to improve it!).
Issues with the power method
Though I mentioned that the power method isn’t an industry strength algorithm I didn’t say why. Let’s revisit that before we finish. The problem is that the convergence rate of even the 1-dimensional problem depends on the ratio of the first and second singular values,
. If that ratio is very close to 1, then the convergence will take a long time and need many many matrix-vector multiplications.
One way to alleviate that is to do the trick where, to compute a large power of a matrix, you iteratively square
. But that requires computing a matrix square (instead of a bunch of matrix-vector products), and that requires a lot of time and memory if the matrix isn’t sparse. When the matrix is sparse, you can actually do the power method quite quickly, from what I’ve heard and read.
But nevertheless, the industry standard methods involve computing a particular matrix decomposition that is not only faster than the power method, but also numerically stable. That means that the algorithm’s runtime and accuracy doesn’t depend on slight changes in the entries of the input matrix. Indeed, you can have two matrices where
is very close to 1, but changing a single entry will make that ratio much larger. The power method depends on this, so it’s not numerically stable. But the industry standard technique is not. This technique involves something called Householder reflections. So while the power method was great for a proof of concept, there’s much more work to do if you want true SVD power.
Until next time!
. | https://jeremykun.com/2016/05/16/singular-value-decomposition-part-2-theorem-proof-algorithm/?like_comment=53971&_wpnonce=e6d122858b | CC-MAIN-2021-21 | refinedweb | 5,974 | 61.36 |
NEVERMIND I FINALLY GOT IT!
Thanks so much for your help, it's gonna boost my grade up 5%!
NEVERMIND I FINALLY GOT IT!
Thanks so much for your help, it's gonna boost my grade up 5%!
I've fixed some of the stuff and have this right now
public class Name
{
public static void main(String args[]){
String firstName = "Tim";
String lastName;
lastName = "Kleinknecht";
Ok I think I've gotten the second one correct.
The error for the first one is.
----jGRASP exec: javac -g Name.java
Name.java:3: cannot find symbol
symbol : class string
location: class Name...
I read that and put Class Name { in front of it and put a another bracket at the end and it didn't work. Maybe i'm just missing a step, I'm quite bad at this stuff.
The error for the first one says:
----jGRASP exec: javac -g Name.Java
error: Class names, 'Name.Java', are only accepted if annotation processing is explicitly requested
1 error
----jGRASP...
I have 1 error in both of these. It's an extra credit assignment. This is my first time coding with Java and I don't know what to fix because when I compile it, it says one error and it wont run.
...
I mean I was hoping someone would be up for teaching me. I would understand if nobody wanted to though.
I missed the class and have absolutely no idea how to do it.
Hey guys, this is my first post into this forum so I hope I'm making it in the right section.
I'm in an introductory computer science program where we are just writing in pseudocode which I'm... | http://www.javaprogrammingforums.com/search.php?s=086143fe2fb82204874b2085b0847279&searchid=1725645 | CC-MAIN-2015-35 | refinedweb | 284 | 83.96 |
"Templates" are a feature of C++ which provide limited support for generic programming, even though it's an early-binding language. You might also consider templates a more powerful and convenient replacement for macros. In fact, we've just said the same thing in two different ways. "Let's have a look under the hood", as Ross Perot used to say before the lawn gnomes dragged him screaming and wiggling down to Hell and fed his tremulous midget heart to the Whipper-Choppers.
We'll start with a very simple example, min(). min() takes two arguments and returns the lesser of the two. This is how you might write it as an ordinary function:
int min( int a, int b )
{
return ( a < b ) ? a : b;
}
The problem there is that it won't work with any type other than int. You could write a double dblmin( double a, double b ) and a dozen others, but you'd spend a lot of time copying and pasting code, and the only thing that would change each time would be the types. The body of the function would never change. The C/C++ macro facility is a much better way to do it:
[#define] min( a, b ) ( ( (a) < (b) ) ? (a) : (b) )
You'd "call" both the function and the macro in exactly the same way, but while the function would be an ordinary function call, the macro would be something else entirely: It would be expanded before the code is compiled. If you use our min() macro and then instruct your compiler to give you preprocessor output instead of compiling, you'll see something like this:
/* before */
int a = min( foo(), 5 );
/* after */
int a = ( ( (foo()) < (5) ) ? (foo()) : (5) );
The preprocessor just replaces a with whatever you give it for the first parameter, and b with whatever you give it for the second parameter. Macros just perform a search and replace on the source code before the compiler sees it. Note that a is a function call, and it gets called twice. That might be a very bad thing. Worse yet, it might only be a moderately bad thing (a harmful recessive, so to speak). This is only one of the reasons why macros are considered harmful by many programmers. Another is that the "invisible" changes in the source make life difficult when you use interactive debuggers or look at the errors and warnings generated by your compiler. The code that's being compiled bears an oftimes arbitrary resemblance to what's in the source file. The only great thing about macros is that they can let you reuse logic without investing in a function call, but as we've seen, you might be squandering hard-earned cycles on other redundant calls. Besides, C++ supports inline functions which do inline code, but put the arguments in temporaries. You can still use macros if your chest is that hairy. Once in a while, they're the Right Thing.
The purpose of templates is to let us have our cake and eat it. Here's a third min() implementation, the way George Jetson would write it. It's in C++ -- The Language of the Future!
template <class T>
inline T min( T a, T b )
{
// GCC prefers that you cast b to T1 here
return ( a < b ) ? a : b;
}
Templates let you parameterize not data, but data types. What's happening here is that we're defining a little "function factory" which generates code at compile time: It takes one type parameter, T, and it generates a function which expects two (in fact, you can use regular ordinary types for template parameters also, but it's not enough to be generally useful for currying functions or anything like that). Whenever the compiler sees min() in use, it uses this template to generate code for min() with the type parameter -- T in our example -- replaced by the types of arguments passed to the function. The template is a "pattern" used to generate C++ source code. Source code is just text. If you throw in a call to a.foo(), any class with an appropriate member function named foo() will be acceptable to the template. Inheritance is totally irrelevant because we're not fitting different "plugs" into the same "socket". Instead, we're generating new "sockets" as needed.
Here it is in action:
std::string foo = "foo", bar = "bar";
// std::string has an operator<() member function,
// so why not?
std::string low = min( foo, bar );
// Useless, schmuseless!
int n = min( argc, fileno( stdin ) );
All's well, until ambiguity rears its ugly head. You could easily call min( 6, 3.65 ). Should the compiler assume that T is double1, or int? It can't make that call, so it throws up its hands and says "template parameter 'T' is ambiguous" or some such thing. You can work around that by explicitly providing T:
n = min<double>( 6, 3.65 );
That's an annoyance. There's a better way:
template <class T1, class T2>
inline T1 min( T1 a, T2 b )
{
return ( a < b ) ? a : b;
}
There. We're no longer requiring that the two types be the same. We never had any good reason to do that in the first place. They are whatever they are. The return type nags at my conscience, but it seems to make sense for it to be the lefternmost of the two arguments. A macro would handle that more tactfully: It would return exactly the value that it returns. With macros, there shall be no coercion in types. What happens if we try wildly incompatible types, like a string class and an int? The compiler will generate code for the function if it possibly can. If it can't, it won't, and it'll scold you. If that string class is on the left and it has an operator<() overload for int, you'll be fine.
Let's move on to a more advanced example: A class template.
template <class T, int SIZE = 128>
class stack {
public:
// Constructor
stack() { _end = _data = new T[ SIZE ]; }
// Virtual destructors make subclassing safe.
virtual ~stack() { delete[] _data; }
// Expose size with an anonymous enum, since that's
// the only way to do const member data in C++
enum { size = SIZE };
// _end points one past the top item
int count() { return _end - _data; }
T & pop() { return *--_end; }
T & top() { return *(_end - 1); }
void push( const T & newdata ) { *_end++ = newdata; }
private:
T * _data;
T * _end; // _end points one past the top item
};
This works much the same as the function we saw above. We're using references and const references now instead of just throwing T instances around, but a real implementation of min() would have done the same: The objects in question might be large, or copying them might be unwise for other reasons, so it pays to play it safe. The SIZE parameter has a default parameter: If you don't give it a size, it will use 128. Everything else is perfectly ordinary C++ code. Here's how you'd use it:
stack<int, 16> st1;
stack<std::string> st2;
st2.push( "foo" );
st1.push( 456 );
That's very useful: int and std::string are very, very different kinds of things, but we can use the exact same code to store either one in a stack. Furthermore, we're not doing it with unsafe typecasts or ignoring the type completely, the way a macro would. It's typesafe, which in C++ is a big deal.
Here's the catch: It's typesafe, and in C++, that's a big deal. We're working with a relatively low-level language. Each of those objects on that stack has a size. If you want your stack<std::string> to work with subclasses of std::string, you'll need to store pointers instead of object instances, and life (a.k.a. "memory management") becomes more complicated. Each of those objects also has member functions, probably a vtable, and a layout in memory: You may have something that's the same size as std::string and has members with the same names that do the same things, but it's not the same. You could "instantiate" the stack template for both that class and std::string, and the compiler would merrily generate the right code for each one, but once that code is generated, it is absolutely normal C++ code. When it calls a member function, it's calling the function through a function pointer. When it looks at a data member, it's using pointer arithmetic. In C++, names matter only in source code. Templates operate on names, but at runtime that's all been long forgotten. You could use a typecast and try to ram a hierarchically unrelated std::string "look-alike" (and size-alike) into your std::string stack, and that would seem to work until you tried to pull it back out and do anything with it. At that point, the code generated by the compiler will call wong entries in its vtable, play pointer arithmetic based on wildly wrong assumptions about its layout, and most likely crash.
When it comes to coping with heterogenous collections of objects, templates buy you nothing that you didn't already get with old-fashioned inheritance. You can't leave home without a well-designed class hierarchy, and that's that.
To conclude: C++ templates are an elaborate and very powerful mechanism for pretending, in some cases, that the language isn't bound by a rigid object oriented inheritance-hungry type system. Don't make too much of that "bound"/"rigid" rhetoric: That straitjacket of a type system lets the compiler generate wonderfully efficient code, and that's worth the price of admission for many applications.
1 All floating point literals in C++ are promoted to double, whether they need it or not (p 74, The C++ Programming Language 3rd ed. by Bjarne Stroustrup);
Need help? accounthelp@everything2.com | https://everything2.com/user/wharfinger/writeups/Template | CC-MAIN-2018-05 | refinedweb | 1,660 | 70.23 |
Table of Contents
GnuPG, “Upgrading MySQL”, for information about upgrade procedures and about issues that you should consider before upgrading.
Determine whether your platform is supported. Please note that not all supported systems are equally suitable for running MySQL. On some platforms it is much more robust and efficient than others. See Section 2.1.1, “Operating Systems Supported by MySQL”,.8, “MySQL Installation Using a Source Distribution”.
If you encounter installation difficulties, see Section 2.12, “Operating System-Specific Notes”, for information on solving problems for particular platforms.
Perform any necessary post-installation setup. After installing MySQL, read Section 2”.
Gn.. See Section 2.12.5.3, “IBM-AIX notes”.
Amiga.
BSDI 2.x with the MIT-pthreads package. See Section 2.12.4.4, “BSD/OS Version 2.x Notes”.
BSDI 3.0, 3.1 and 4.x with native threads. See Section 2.12.4.4, “BSD/OS Version 2.x Notes”.
Digital Unix 4.x with native threads. See Section 2.12.5.5, “Alpha-DEC-UNIX Notes (Tru64)”.
FreeBSD 2.x with the MIT-pthreads package. See Section 2.12.4.1, “FreeBSD Notes”.
FreeBSD 3.x and 4.x with native threads. See Section 2.12.4.1, “FreeBSD Notes”.
FreeBSD 4.x with LinuxThreads. See Section 2.12.4.1, “FreeBSD Notes”.
HP-UX 10.20 with the DCE threads or the MIT-pthreads package. See Section 2.12.5.1, “HP-UX Version 10.20 Notes”.
HP-UX 11.x with the native threads. See Section 2.12.5.2, “HP-UX Version 11.x Notes”.
Linux 2.0+ with LinuxThreads 0.7.1+ or
glibc 2.0.7+ for various CPU
architectures. See Section 2.12.1, “Linux Notes”.
Mac OS X. See Section 2.12.2, “Mac OS X Notes”.
NetBSD 1.3/1.4 Intel and NetBSD 1.3 Alpha (requires GNU make). See Section 2.12.4.2, “NetBSD Notes”.
Novell NetWare 6.0 and 6.5. See Section 2.6, “Installing MySQL on NetWare”.
OpenBSD 2.5 and with native threads. OpenBSD earlier than 2.5 with the MIT-pthreads package. See Section 2.12.4.3, “OpenBSD 2.5 Notes”.
OS/2 Warp 3, FixPack 29 and OS/2 Warp 4, FixPack 4. See Section 2.12.6, “OS/2”.
SunOS 4.x with the MIT-pthreads package. See Section 2.12.3, “Solaris Notes”.
Tru64 Unix. See Section 2.12.5.5, “Alpha-DEC-UNIX Notes (Tru64)”.
Windows 9x, Me, NT, 2000, XP, and Windows Server 2003. See Section 2.3, “Installing MySQL on Windows”.. In other words, when a process creates a thread, it should be possible for that thread to run on a CPU different from hurts MySQL tremendously. If this issue
is not taken care of, adding extra CPUs actually makes MySQL
slower.
General filesystem stability and performance.
If your tables are large, performance is affected by run MySQL successfully on the platform in similar configurations. If this number is high, the likelihood of encountering platform-specific surprises is much smaller.
Based on the preceding criteria, the best platforms for running
MySQL at this point are x86 with SuSE Linux using a 2.4 and
library components that MySQL depends on. If you are interested
in improving one of those components, are in a position to
influence its development, and need more detailed instructions
on what MySQL needs to run better, send an email message to the
MySQL
internals mailing list. See
Section 1.7.1, “MySQL Mailing Lists”.
Please note that the purpose of the preceding comparison is not to say that one operating system is better or worse than another in general. We are talking only about choosing an OS for the specific purpose of running MySQL. With this in mind, the result of this comparison might be different if other factors were considered. In some cases, the reason one OS is better for MySQL than another might simply be that we have been able to put more effort into testing and optimizing for a particular platform. We are just stating our observations to help you decide which platform to use for running MySQL..
The first decision to make is whether you want to use a production (stable) release or a development release. In the MySQL development process, multiple release series co-exist, each at a different stage of maturity:
MySQL 5.1 is the next development release series and is the series in which new features are to be implemented. Alpha releases are available now to allow widespread testing by interested users. do not believe in a complete code freeze because this prevents us from making bugfixes and other fixes that must be done. By “somewhat frozen” we mean that we may add small things that should not affect anything that currently works in a production release. Naturally, relevant bugfixes from an earlier series propagate to later series.
Normally, if you are beginning to use MySQL for the first time or trying to port it to some system for which there is no binary distribution,. Note that development releases are not as stable as production releases.
If you want to use the very latest sources containing all current patches and bugfixes, you can use one of our BitKeeper repositories. These are not “releases” as such, but are available as previews of the code on which future releases are to be based.
The MySQL naming scheme uses release names that consist of three numbers and a suffix; for example, mysql-5.0.12-beta. The numbers within the release name are interpreted as follows: contains APIs, externally visible structures, and columns for SQL statements will not change during future beta, release candidate, or production releases.
rc is a release candidate; that is, a beta that has been around for a while and seems to work well. Only minor fixes are added. (A release candidate is what formerly was known as a gamma release.)
If there is no suffix, it means that the version has been run for a while at many different sites with no reports of critical repeatable bugs other than platform-specific bugs. Only critical bugfixes are applied to the release. This is what we call a production (stable) or “General Availability” (GA) release.
MySQL uses a naming scheme that is slightly different from most other products. In general, it is usually safe to use any version that has been out for a couple of weeks without being replaced by a new version within the same release series.
virtually every server binary. See
Section.
After choosing which version of MySQL to install, you should decide whether to use a binary distribution or a source distribution. In most cases, you should probably use a binary distribution, if one exists for your platform. Binary distributions are available in native format for many platforms, such as RPM files for Linux or PKG package installers for Mac OS X. Distributions also are available as Zip archives or compressed tar files.
Reasons to choose a binary distribution include the following:
Binary distributions generally are easier to install than source distributions.
To satisfy different user requirements, we provide.3, “The mysqld-max Extended MySQL Server”.
For RPM distributions, if you want to use the
MySQL-Max RPM, you must first install
the standard
MySQL-server RPM.-innodb
--with-berkeley-db (not available on
all platforms)
--with-libwrap
--with-named-z-libs (this is done for
some of the binaries)
-.
MySQL D, MySQL Change History.-critical but annoying bugs. The fixes are available immediately from our public BitKeeper repositories, and are included in the next release.
If by any chance a fatal bug is found in a release, our policy is to fix it in a new release as soon as possible. (We would like other companies to do this, too!)
We put a lot of time and effort into making our releases bug-free. We haven't released a single MySQL version with any known fatal repeatable bugs. (A “fatal” bug is something that crashes MySQL under normal usage, produces incorrect answers for normal queries, or has a security problem.)
We have documented all open problems, bugs, and issues that are dependent on design decisions. See Section.2, “Standard MySQL Installation Using a Binary Distribution”.
The RPM distributions for MySQL 5.0 releases that we make available through our Web site are generated by MySQL AB.
For Windows distributions, see Section 2.3,
Linux 2.x.xx ppc with gcc 2.95-embedded-server --with-innodb
Linux 2.4.xx s390 with gcc 2
Sun Solaris 8 SPARC 64-bit with gcc 3 --with-named-z-libs=no --with-named-curses-libs=-lcurses --disable-shared
Sun Solaris 9 SPARC with gcc 2
Sun Solaris 9 SPARC with. These are provided only as a courtesy; MySQL AB does not have full control over these systems, so we can provide only limited support for the binaries built on them.
SCO Unix 3.2v5.0.7 i386 with gcc 2-named-thread-libs="-lpthread -lmach -lexc -lc" --disable-shared --with-mysqld-ldflags=-all-static
SGI Irix 6.5 IP32 with gcc 3
Linux 2.2.x with x686 with gcc 2
Check.
Our main mirror is located at.
GnuPG
RPM
After you have downloaded the MySQL package that suits your needs and before you attempt to install it, you should make sure that it is intact and has not been tampered with. MySQL AB offers.
After you have downloaded a MySQL package, you should make
sure that its MD5 checksum matches the one provided on the
MySQL download pages. Each package has an individual checksum
that you can verify with the following command, where
package_name is the name of the
package you downloaded:
shell>
md5sum
package_name
Example:
shell>
md5sum mysql-standard-5.0.19-linux-i686.tar.gzaaab65abbec64d5e907dcd41b8699945 mysql-standard-5.0.19-linux-i686.tar.gz
You should verify that the resulting checksum (the string of hexadecimal digits) matches the one displayed on the download page immediately below the respective package.
Note: Make sure to verify the
checksum of the archive file (for
example, the
.zip or
.tar.gz file) and not of the files that are
contained inside of the archive.
Note that not all operating systems support the
md5sum command. On some, it is simply
called md5, and others do not ship it at
all. On Linux, it is part of the GNU
Text Utilities package, which is available for a
wide range of platforms. You can download the source code from as well.
If you have OpenSSL installed, you can use the command
openssl md5
package_name instead. A
Windows implementation of the md5 command
line utility is available from.
winMd5Sum is a graphical MD5 checking tool
that can be obtained from.
Another method of verifying the integrity and authenticity of a package is to use cryptographic signatures. This is more reliable than using MD5 checksums, but requires more work.
At MySQL AB, MySQL AB's public GPG build key, which you
can download from.
The key that you want to obtain is named
build@mysql.com. Alternatively, you can cut
and paste the key directly from the following text:.19.
For RPM packages, there is no separate signature. RPM packages have a built-in GPG signature and MD5 checksum. You can verify a package by running the following command:
shell>
rpm --checksig
package_name.rpm
Example:
shell>
rpm --checksig MySQL-server-5.0.19-0.i386.rpmMySQL-server-5.0.19-0.1.4.2, “Signature Checking Using
GnuPG”. Then use
rpm --import to import the key. For
example, if you have saved the public key in a file named
mysql_pubkey.asc, import it using this
command:
shell>
rpm --import mysql_pubkey.asc
If you need to obtain the MySQL public key, see
Section 2.1.4.2, “Signature Checking Using
GnuPG”.
This section describes the default layout of the directories created by installing binary or source distributions provided by MySQL AB. MySQL AB's next several sections cover the installation of MySQL on platforms where we offer packages using the native packaging format of the respective platform. (This is also known as performing a “binary install.”) However, binary distributions of MySQL are available for many other platforms as well. See Section 2.7, “Installing MySQL on Other Unix-Like Systems”, for generic installation instructions for these packages that apply to all platforms.
See Section 2.1, “General Installation Issues”, for more information on what other binary distributions are available and how to obtain them. the procedure described in Section 2.3.14, “Upgrading MySQL on Windows”.
To run MySQL on Windows, you need the following:
A 32-bit Windows operating system such as 9x, Me, NT, 2000, XP, or Windows Server 2003.
A Windows NT-based operating system (NT, 2000, XP, 2003) permits you to run the MySQL server as a service. The use of a Windows NT-based operating system is strongly recommended. See Section 2.3.)
There may also be other requirements, depending on how you plan to use MySQL:
If you plan to connect to the MySQL server via ODBC, you need a Connector/ODBC driver. See Section 23.1, “MySQL Connector/ODBC”.
If you need tables with a size larger than 4GB, install MySQL
on an NTFS or newer filesystem. Don't forget to use
MAX_ROWS and
AVG_ROW_LENGTH when you create tables. See
Section 13.3.1, “Choosing An Installation Package”.
The source distribution contains all the code and support files for building the executables using the Visual Studio 7.1.3.5, “Installing MySQL from a Noinstall Zip Archive”. To install using a source distribution, see Section 2.8.6, “Installing MySQL from Source on Windows”.
MySQL distributions for Windows can be downloaded from. See Section 2.1.3, “How to Get MySQL”.
For MySQL 5.0, there are three installation packages to choose from when installing MySQL on Windows:
The Essentials Package:
This package has a filename similar to
mysql-essential-5.0.19-win32.msi
and contains the minimum set of files needed to install
MySQL on Windows, including the Configuration Wizard. This
package does not include optional components such as the
embedded server and benchmark suite.
The Complete Package: This
package has a filename similar to
mysql-5.0.19-win32.zip and
contains all files needed for a complete Windows
installation, including the Configuration Wizard. This
package includes optional components such as the embedded
server and benchmark suite.
The Noinstall Archive: This
package has a filename similar to
mysql-noinstall-5.0.19”.
New.
MySQL Installation Wizard is an installer for the MySQL server that uses the latest installer technologies for Microsoft Windows. The MySQL Installation Wizard, in combination with the MySQL Configuration Wizard, allows.3 allows.8, .3.4, “The Custom Install Dialog”, for more information on performing a custom install.
If you choose the Typical or Complete installation types and click the button, you advance to the confirmation screen to verify your choices and begin the installation. If you choose the Custom installation type and click the button, you advance to the custom installation dialog, described in Section 2.3.3 on.
Once you choose an installation type and optionally choose your installation components, you advance to the confirmation dialog. Your installation type and installation path are displayed for you to review.
To install MySQL if you are satisfied with your settings, click thebutton. To change your settings, click the button. To exit the MySQL Installation Wizard without installing MySQL, click the button. Configuration Wizard, which you can use to create a configuration file, install the MySQL service, and configure security settings.
Once you click thebutton,.19, the key contains a value of
5.0.19.menu under a common MySQL menu heading named after the.:.0 server to
C:\, where
Program
Files\MySQL\MySQL Server
5.0
Program Files is the default
location for applications in your system, and
5.0 C:\Program Files\MySQL\MySQL Administrator 1.0 C:\Program Files\MySQL\MySQL Query Browser 1.0
This approach makes it easier to manage and maintain all MySQL applications installed on a particular system. 4.1.5 to MySQL 4.1.6, but not from MySQL 4.1 to MySQL 5.0. 5.0 server, and is currently available for Windows users only.
The MySQL Configuration Wizard is typically launched from the MySQL Installation Wizard, as the MySQL Installation Wizard exits. You can also launch the MySQL Configuration Wizard by clicking theentry in the section of the Windows menu.
Alternatively, you can navigate to the
bin directory of your MySQL installation
and launch the
MySQLInstanceConfig.exe
file directly.
Ifbutton before you change the path. In this situation you must move the existing tablespace files to the new location manually before starting the server..5, “The Server SQL Mode” determines configuration
file options based on your choices using a template prepared
by MySQL ABbutton to exit the MySQL Configuration Wizard.
The MySQL.0\my.ini"
Here,
C:\Program Files\MySQL\MySQL Server
5.0).
Users.
To install MySQL manually, do the following:
If you are upgrading from a previous version please refer to Section 2.3.14, “Upgrading MySQL on Windows”, before beginning the upgrade process.
If you are using a Windows NT-based operating system such as Windows NT, Windows 2000, Windows XP, or Windows Server 2003, 2.3.7, :
C:\>
echo %WINDIR%
MySQL looks for options first in the
my.ini
file, and then in the
my.cnf file. However,
to avoid confusion, it. Look in your install directory for
files such as
my-small.cnf,
my-medium.cnf,
my-large.cnf, and
my-huge.cnf, which you can rename and copy
to the appropriate location for use as a base configuration
file. parameters:
[mysqld] # set basedir to your installation path basedir=E:/mysql # set datadir to the location of your data directory datadir=E:/mydata/data
Note that Windows pathnames:
Move the entire
data directory and all
of its contents from
C:\Program Files\MySQL\MySQL
Server 5.0\data to
E:\mydata.
Use a
--datadir option to specify the new
data directory location each time you start the server.
The following table shows the available servers for Windows in MySQL 5.0: named pipes on Windows NT, 2000, XP, and 2003..
Note: Most of the examples in this manual use mysqld as the server name. If you choose to use a different server, such as mysqld-nt, make the appropriate substitutions in the commands that are shown in the examples.
This.0. Adjust the
pathnames shown in the examples if you have MySQL installed in a
different location..
MySQL for Windows also supports shared-memory connections if the
server is started with the
--shared-memory
option. Clients can connect through shared memory by using the
--protocol=memory option.
For information about which server binary to run, see Section 2.3.8, .0\bin\mysqld" --console
For a server that includes
InnoDB support,
you should see the messages similar to those following as it
starts (the pathnames.0.19'.0\data by default). The error log is
the file with the
.err extension.
Note: The accounts that are listed in the MySQL grant tables initially have no passwords. After starting the server, you should set up passwords for them using the instructions in Section 2.9, “Post-Installation Setup and Testing”.
The MySQL server can be started manually from the command line. This can be done on any version of Windows.
To start the mysqld server from the command line, you should start a console window (or “DOS window”) and enter this command:
C:\>
"C:\Program Files\MySQL\MySQL Server 5.0
Section E.1.2, “Creating Trace Files”.
Use mysqld --verbose --help to display all the options that mysqld understands.
On the NT family (Windows NT, 2000, XP, 2003),,.
Warning:
It is possible to use a single option other than
--defaults-file, but this.:\>
numbers ceated a new user account, then you must use the appropriate
-u and
-p options with the
commands shown above in order to connect with the MySQL Server.
See Section 5.8.4, “Connecting to the MySQL Server”.
For more information about mysqlshow, see Section 8.13, “mysqlshow — Display Database, Table, and Column Information”.
When
Section 5.12:
System error 1067 has occurred. Fatal error: Can't open privilege tables: Table 'mysql.host' doesn't exist
These messages often occur when the MySQL base or data
directories are installed in different locations than the
default locations (
C:\Program Files\MySQL\MySQL
Server 5.0i file needs to be located in your
Windows directory, typically
C:\WINDOWS
or
C:\WINNT.
If you change the
datadir value in your
MySQL configuration file, you must move the contents of the
existing MySQL data directory before restarting the MySQL
server.
See Section 2.3.7, allows.
This section lists some of the steps you should take when upgrading MySQL on Windows.
Review Section 2.10, “Upgrading MySQL”, for additional information on upgrading MySQL that is not specific to Windows.
You should always back up your current MySQL installation before performing an upgrade. See Section 5.10.1, “Database Backups”. the following command to stop it:
C:\>
"C:\Program Files\MySQL\MySQL Server 5.0\bin\mysqladmin" -u root shutdown
Note: If the MySQL
root user account has a password, you
need to invoke mysqladmin with the
-p option and supply the password when
prompted.
When upgrading to MySQL 5.0 from a version previous to 4.1.5,”.
MySQL for Windows has proven itself to be very stable. The Windows version of MySQL has the same features as the corresponding Unix version, with the following exceptions:
Windows 95 and threads
Windows 95 leaks about 200 bytes of main memory for each thread creation. Each connection in MySQL creates a new thread, so you shouldn't run mysqld for an extended time on Windows 95 if your server handles many connections! Newer versions of Windows don't suffer from this bug. on NT, 2000, and XP to get more speed. The current
implementation limits the number of open files that MySQL
5.0 can use to 2,048, which means that you
cannot run as many concurrent threads on Windows.
Killing MySQL from the Task Manager
On Windows 95, you cannot kill MySQL from the Task Manager or with the shutdown utility. You must stop it with mysqladmin shutdown.”.
MySQL AB does provide some platform-specific RPMs; the difference between a platform-specific RPM and a generic RPM is that a platform-specific RPM is built on the targeted platform and is linked dynamically whereas a generic RPM is linked statically with LinuxThreads.
Note: RPM distributions of MySQL often are provided by other vendors. Be aware that they may differ in features and capabilities from those built by MySQL AB,.3, “The mysqld-max Extended MySQL Server”.
If you get a dependency failure when trying to install MySQL.i386.rpm
The standard MySQL client programs. You probably always want to install this package.
MySQL-bench-
VERSION.i386.rpm
Tests and benchmarks. Requires Perl and the
DBI and
DBD::mysql
modules.
MySQL-devel-
VERSION.i386.rpm
The libraries and include files that are needed if you want to compile other MySQL clients, such as the Perl modules.
MySQL-shared-
VERSION.i386.rpm
This package contains the shared libraries
(
libmysqlclient.so*) that certain languages
and applications need to dynamically load and use MySQL.
MySQL-shared-compat-
VERSION.i386.rpm
This has been available since MySQL
4.0.13.
MySQL-embedded-
VERSION.i386.rpm
The embedded MySQL server library (available as of MySQL 4.0).
MySQL-
VERSION.src.rpm
This contains the source code for all of the previous packages. It can also be used to rebuild the RPMs on other architectures (for example, Alpha or SPARC).
To see all files in an RPM package (for example, a
MySQL-server RPM), run a commnd like this:
shell>
rpm -qpl MySQL-server-
VERSION.i386.rpm
To perform a standard minimal installation, install the server and client RPMs:
shell>
rpm -i MySQL-server-shell>
VERSION.i386.rpm
rpm -i MySQL-client-
VERSION.i386.rpm
To install only the client programs, install just the client RPM:
shell>
rpm -i MySQL-client-
VERSION
don't lose it when you install a newer RPM.)”.
You can install MySQL on Mac OS X 10.2.x (“Jaguar”) or newer using a Mac OS X binary package in PKG format.
To obtain MySQL, see Section 2.1.3, “How to Get MySQL”.
Note:.”
For pre-installed versions of MySQL on Mac OS X Server, note especially that you should start mysqld with safe_mysqld instead of mysqld_safe if MySQL is older than version 4.0. 5.6.2, AB Startup
Item installer disables this variable by setting it to
MYSQL=-NO-. This avoids boot time conflicts
with the
MYSQLCOM variable used by the MySQL AB.
Note: The accounts that are listed in the MySQL grant tables initially have no passwords. After starting the server, you should set up passwords for them using the instructions in Section 2.9, ..1.9, “Post-Installation Setup and Testing”.
This section covers the installation of MySQL binary distributions
that are provided for various platforms in the form of compressed
tar files (files with a
.tar.gz extension). See
Section 2.1.2.5, “MySQL Binaries Compiled by MySQL AB”, for a detailed list.
To obtain MySQL, see Section 2.1.3, “How to Get MySQL”.
MySQL tar file binary distributions have names
of the form
mysql-,
where
VERSION-
OS.tar.gz
is a
number (for example,
VERSION
5.0.19), and
OS indicates the type of operating
system for which the distribution is intended (for example,
pc-linux-i686).
In addition to these generic packages, we also offer binaries in platform-specific package formats for selected platforms. See Section 2.2, “Standard MySQL Installation Using a Binary Distribution”, for more information on how to install these.
You need the following tools to install a MySQL tar file binary distribution:.>
scripts/mysql_install_db --user=mysqlshell>
chown -R root .shell>
chown -R mysql datashell>
chgrp -R mysql .shell>
bin/mysqld_safe --user=mysql &
Note: This procedure does not set up any passwords for MySQL accounts. After following the procedure, proceed to Section 2.9, “Post-Installation Setup and Testing”.
A more detailed version of the preceding description for installing a binary. In the following
example, we unpack:
Appendix F, Environment Variables.
The
scripts directory contains the
mysql_install_db script used to
initialize the
mysql database
containing the grant tables that store the server access
permissions.
If you have not installed MySQL before, you must create the MySQL grant tables:
shell>
scripts/mysql_install_db --user=mysql
If you run the command as
root, you must creating or updating the grant tables, you need to restart the server manually. datas and in Section 2.9.2.2, “Starting and Stopping MySQL Automatically”.
You can set up new accounts using the
bin/mysql_setpermission script if you
install the
DBI and
DBD::mysql Perl modules. For instructions,
see Section 2.13, “Perl Installation Notes”.
If you would like to use mysqlaccess and
have the MySQL distribution in some non-standard.
After everything has been unpacked and installed, you should test your distribution. To start the MySQL server, use the following command:
shell>”.
Before you proceed with an installation from source, first check whether our binary is available for your platform and whether it works for you. We put a great deal of effort into ensuring that our binaries are built with the best possible options.
To obtain a source distribution for MySQL, Section 2.1.3, “How to Get MySQL”.
MySQL source distributions are provided as compressed
tar archives and have names of the form
mysql-,
where
VERSION.tar.gz
VERSION is a number like
5.0.19.
You need the following tools to build and install MySQL from source:.
A working ANSI C++ compiler. gcc 2.95.2 or
later, egcs 1.0.2 or later or egcs
2.91.66, have only
gcc 2.7.x, you must upgrade your
gcc to be able to compile MySQL.
gcc 2.8.1 is also known to have problems on
some platforms, so it should be avoided if a. Section 1.8, “How to Report Bugs or Problems”.
The basic commands that you must execute to install a MySQL source distribution are:
shell>
groupadd mysqlshell>
useradd -g mysql mysqlshell>
gunzip < mysql-shell>
VERSION.tar.gz | tar -xvf -
cd mysql-shell>
VERSION
./configure --prefix=/usr/local/mysqlshell>
makeshell>
make installshell>
cp support-files/my-medium.cnf /etc/my.cnfshell>
cd /usr/local/mysqlshell>
bin/mysql_install_db --user=mysqlshell>
chown -R root .shell>
chown -R mysql varshell>
chgrp -R mysql .shell>
bin/mysqld_safe --user=mysql &.
Obtain a distribution file using the instructions in Section 2.1.3, “How to Get MySQL”.
Unpack the distribution into the current directory:
shell>
gunzip <
/path/to/mysql-VERSION.tar.gz | tar xvf -
This command creates a directory named
mysql-.
VERSION
With GNU tar, no separate invocation of
gunzip is necessary. You can use the
following alternative command to uncompress and extract the
distribution:
shell>
tar zxvf
/path/to/mysql-VERSION-OS.tar.gz
Change location into the top-level directory of the unpacked distribution:
shell>
cd mysql-
VERSION
Note that currently you must configure and build MySQL from this top-level directory. You cannot build it in a different directory.
Configure the release and compile everything:
shell>
./configure --prefix=/usr/local/mysqlshell>
make
When you run configure, you might want to specify other options. Run ./configure --help for a list of options. Section 2.8.2, “Typical configure Options”, discusses some of the more useful options.
If configure fails and you are going to
send mail to a MySQL mailing list to ask for assistance,
please include any lines from
config.log that you think can help
solve the problem. Also include the last couple of lines of
output from configure. To file a bug
report, please use the instructions in
Section 1.8, “How to Report Bugs or Problems”.
If the compile fails, see Section 2.8.4, “Dealing with Problems Compiling MySQL”, for help.
Install the distribution:
shell>
make install
If you want to set up an option file, use one of those
present in the
support-files directory
as a template. For example:
shell>
cp support-files/my-medium.cnf /etc/my.cnf
You might need to run these commands as
root.
If you want to configure support for
InnoDB tables, you should edit the
/etc/my.cnf file, remove the
# character before the option lines that
start with
innodb_..., and modify the
option values to be what you want. See
Section 4.3.2, “Using Option Files”, and
Section 14.2.3, “
InnoDB Configuration”.
Change location into the installation directory:
shell>
cd /usr/local/mysql
If you haven't installed MySQL before, you must create the MySQL grant tables:
shell>
bin/mysql_install_db --user=mysql
If you run the command as
root, you
should using mysql_install_db to create the grant tables for MySQL, you must restart the server manually. The mysqld_safe command to do this is shown in a later step. vars; see also Section 2.9.2.2, “Starting and Stopping MySQL Automatically”.
You can set up new accounts using the
bin/mysql_setpermission script if you
install the
DBI and
DBD::mysql Perl modules. For
instructions, see Section 2.13, “Perl Installation Notes”.
After everything has been installed, you should test your distribution. To start the MySQL server, use the following command:
shell>
/usr/local/mysql”.
The configure script gives you a great deal of control over how you configure a MySQL source distribution. Typically you do this using options on the configure command line. You can also affect configure using certain environment variables. See Appendix F, Environment Variables. For a list of options supported by configure, run this command:
shell>
./configure --help
Some of the more commonly used configure options>
..
You can also specify the locations at server startup time by using a MySQL option file. See Section 4.3.2, filename must be an absolute pathname. You can
also change the location of
mysql.sock
at server startup by using a MySQL option file. See
Section binaries we provide on the MySQL Web site at are all compiled with full optimization and should be perfect for most users. See Section 2.1.2) 5.11.1, “The Character Set Used for Data and Sorting”. want to convert characters between the server and the
client, you should use the
SET NAMES
statement. See Section 13.5.3, “
SET Syntax”, and
Section 10.4, “Connection Character Sets and Collations”.
To configure MySQL with debugging code, use the
--with-debug option:
shell>
./configure --with-debug
This causes a safe memory allocator to be included that can find some errors and that provides output about what is happening. See Section E.1, “Debugging a MySQL Server”.
If your client programs are using threads, you must compile
a thread-safe version of the MySQL client library with the
--enable-thread-safe-client configure
option. This creates a
libmysqlclient_r
library with which you should link your threaded
applications. See Section 22.2.15, “How to Make a Threaded Client”.
It is possible to build MySQL 5.0 with large
table support using the
--with-big-tables
option, beginning with MySQL 5.0.4.
This option causes the variables used to keep table row
counts to be stored using
unsigned long
long rather than
unsigned long.
What this does is to allow tables to hold up to
approximately 1.844E+19
((232)2)
rows rather than 232 (~4.295E+09)
rows. Previously it was necessary to pass
-DBIG_TABLES to the compiler manually in
order to enable this feature.
Options that pertain to particular operating systems can be found in the system-specific section of this manual. See Section 2.12, “Operating System-Specific Notes”..
To install the BitKeeper client on Unix, use these commands:
shell>
sh bk-client.sharshell>
cd bk_client-1.1shell>
make allshell>
PATH=$PWD:$PATH
To install the BitKeeper client on Windows, use these instructions:
Download and install Cygwin from.
Make sure gcc and make have been installed under Cygwin. You can test this by issuing which gcc and which make commands. If either one is not installed, run Cygwin's package manager, select gcc, make, or both, and install them.
Under Cygwin, execute these commands:
shell>
sh bk-client.sharshell>
cd bk_client-1.1
Then edit the
Makefile and change the
line that reads
$(CC) $(CFLAGS) -o sfio -lz
sfio.c to this:
$(CC) $(CFLAGS) -o sfio sfio.c -lz
Now run the make command and set the path:
shell>
make allshell>
PATH=$PWD:$PATH.0 branch:
shell>
sfioball -r+>
aclocal; autoheadershell>
libtoolize --automake --forceshell>
automake --force --add-missing; autoconfshell>
(cd innobase; aclocal; autoheader; autoconf; automake)shell>
(cd bdb/dist; sh s_all)shell>
. sfioball to obtain the source tree, you should use update periodically to update your local copy. To do this any time after you have set up the repository, use this command:
shell>
update bk://mysql.bkbits.net/mysql-5.0
You can examine the change history for the tree with all the
diffs by viewing the
BK/ChangeLog file
in the source tree and looking at the
ChangeSet descriptions listed there. To
examine a particular changeset, you would have to use the
sfioball command to extract two
particular revisions of the source tree, and then use an
external diff command to compare them. If
you see some funny diffs.
You can also browse changesets, comments, and source code online. To browse this information for MySQL 5.0, go to.
All MySQL programs compile cleanly for us with no warnings on Solaris or Linux using gcc. On other systems, warnings may occur due to differences in system include files. See Section 2, we recommend that.5, “MySQL Binaries Compiled by MySQL AB”, want to compile MySQL with
Berkeley DB support.
If you need to debug mysqld or a MySQL
client, run configure with the
--with-debug option, and then recompile and
link your clients with the new client library. See
Section E.2, “Debugging a MySQL Client”..
This section describes some of the issues involved in using MIT-pthreads.
On Linux, you should not use MIT-pthreads. Use the installed LinuxThreads implementation instead. See Section 2.12”.
MIT-pthreads is not part of the MySQL 5.0 source distribution. If you require this package, you need to download it separately from
After downloading, extract this source archive into the top
level of the MySQL source directory. It creates a new
subdirectory named
mit-pthreads..
The checks that determine whether to use MIT-pthreads occur
only during the part of the configuration process that deals
with the server code. If you have configured the
distribution using
--without-server to
build only the client code, clients do not know whether
MIT-pthreads is being used and use Unix socket file
connections by default. Because Unix socket files do not
work under MIT-pthreads on some platforms, this means you
need to use
-h or
--host
with a value other than
localhost when
you run client programs.
When MySQL is compiled using MIT-pthreads, system locking is
disabled by default for performance reasons. You can tell
the server to use system locking with the
--external-locking option. This is needed
only if you want to be able to run two MySQL servers against
the same data files, but that is not recommended, anyway.
Sometimes the pthread
bind() command
fails to bind to a socket without any error message (at
least on Solaris). The result is that all connections to the
server fail. For example:
shell>
mysqladmin versionmysqladmin: connect to server at '' failed; error: 'Can't connect to mysql server on localhost (146)'
The solution to this problem is to kill the mysqld server and restart it. This has happened to us only when we have forcibly stopped the server and restarted it immediately.
With MIT-pthreads, the
sleep() system
call isn't interruptible with
SIGINT
(break). This is noticeable only when you run
mysqladmin --sleep. You must wait for the
sleep() call to terminate before the
interrupt is served and the process stops.
When linking, you might have not been able to make
readline
work with MIT-pthreads. (This is not necessary, but may be
of interest to some.) a binary distributions are available in Section 2.3, “Installing MySQL on Windows”.
To build MySQL on Windows from source, you need the following compiler and resources available on your Windows system:
Visual Studio 7.1 compiler system
Between 3GB and 5GB disk space.
Windows 2000 or higher.
The exact system requirements can be found here:
You also need a MySQL source distribution for Windows. There are two ways to obtain a source distribution:
Obtain a source distribution packaged by MySQL AB. These are available from.
You can package a source distribution yourself from the latest BitKeeper developer source tree. If you plan to do this, you must create the package on a Unix system and then transfer it to your Windows system. (Some of the configuration and build steps require tools that work only on Unix.) The BitKeeper approach thus requires:
A system running Unix, or a Unix-like system such as Linux.
BitKeeper 3.0 installed on that system. See Section 2.8.3, “Installing from the Development Source Tree”, for instructions how to download and install BitKeeper. in the same way.
Debug versions of the programs and libraries are placed in
the
client_debug and
lib_debug directories. Release
versions of the programs and libraries are placed in the
client_release and
lib_release directories. Note that if
you want to build both debug and release versions, you can
select the option
from the menu.
Test the server. The server built using the preceding
instructions expects that the MySQL base directory and
data directory are
C:\mysql and
C:\mysql\data by default. If you want
to test your server using the source tree root directory
and its data directory as the base directory and data
directory, you need to tell the server their pathnames.
You can either do this on the command line with the
--basedir and
--datadir
options, or by placing appropriate options in an option
file. (See Section 4.3.2, “Using Option Files”.) If you have an
existing data directory elsewhere that you want to use,
you can specify its pathname instead.
Start your server from the
client_release or
client_debug directory, depending on
which server you want to use. The general server startup
instructions are in
Section 2.3, :
Create the directories where you want to install MySQL.
For example, to install into
C:\mysql, use these commands:
C:\>
mkdir C:\mysqlC:\>
mkdir C:\mysql\binC:\>
mkdir C:\mysql\dataC:\>
mkdir C:\mysql\shareC:\>
mkdir C:\mysql\scripts
If you want to compile other clients and link them to MySQL, you should also create several additional directories:
C:\>
mkdir C:\mysql\includeC:\>
mkdir C:\mysql\libC:\>
mkdir C:\mysql\lib\debugC:\>
mkdir C:\mysql\lib\opt
If you want to benchmark MySQL, create this directory:
C:\>
mkdir C:\mysql\sql-bench
Benchmarking requires Perl support. See Section 2.13, “Perl Installation Notes”.
From the
workdir directory, copy into
the
C:\mysql directory the following
directories:
C:\>
cd \workdirC:\workdir>
copy client_release\*.exe C:\mysql\binC:\workdir>
copy client_debug\mysqld.exe C:\mysql\bin\mysqld-debug.exeC:\workdir>
xcopy scripts\*.* C:\mysql\scripts /EC:\workdir>
xcopy share\*.* C:\mysql\share /E
If you want to compile other clients and link them to MySQL, you should also copy several libraries and header files:
C:\workdir>
copy lib_debug\mysqlclient.lib C:\mysql\lib\debugC:\workdir>
copy lib_debug\libmysql.* C:\mysql\lib\debugC:\workdir>
copy lib_debug\zlib.* C:\mysql\lib\debugC:\workdir>
copy lib_release\mysqlclient.lib C:\mysql\lib\optC:\workdir>
copy lib_release\libmysql.* C:\mysql\lib\optC:\workdir>
copy lib_release\zlib.* C:\mysql\lib\optC:\workdir>
copy include\*.h C:\mysql\includeC:\workdir>
copy libmysql\libmysql.def C:\mysql\include
If BitKeeper source tree for MySQL 5.0. For instructions on how to do this, see Section 2.8.3, “Installing from. It accepts the following options:
Display a help message.
--debug
Print information about script operations, do not create package.
--tmp
Specify the temporary location.
--suffix
The suffix name for the package.
--dirname
Directory name to copy files (intermediate).
--silent
Do not print verbose list of files processed.
--tar
Create
tar.gz package instead of
.zip package..8.6.1, “Building MySQL Using VC++”..9.2.3, “Starting and Troubleshooting the MySQL Server”, applies to all platforms; it describes what to do if you have trouble getting the server to start. Section 2.8, “The MySQL Access Privilege System”, and Section 5.3.3, “Using the MySQL Installation Wizard”.) Otherwise, use the
password-assignment procedure given in
Section 2.9.3, “Securing the Initial MySQL Accounts”.
Before setting up passwords, you might want to try running some client programs to make sure that you can connect to the server and that it is operating properly. Make sure that the server is running (see Section 2.3.3.11, “Starting MySQL as a Windows Service”..9.2.2, “Starting and Stopping MySQL Automatically”.
After you complete the procedure and have the server running, you should assign passwords to the accounts created by mysql_install_db. Instructions for doing so are given in Section 2.9.9.8, .9
mysql_safe as
system
root. Otherwise, you should
execute the script while logged in to the system as
mysql, in which case you can omit the
--user option from the command.
Further instructions for running MySQL as an unprivileged user are given in Section 5.9.19,.19-Max.9.9.3, “Securing the Initial MySQL Accounts”.
The MySQL 5.0 installation procedure creates time
zone tables in the
mysql database. However,
you must populate the tables manually using the instructions in
Section 5.11.8, “MySQL Server Time Zone Support”.
The purpose of the mysql_install_db script is to generate new MySQL privilege tables. It does not overwrite existing MySQL privilege tables, and it does not affect any other data.
If you want to re-create your privilege tables, first stop the
mysqld server if it.13, name Section A.4.5, “How to Protect or Change the MySQL Unix Socket File”, and Appendix.
Generally, you start the mysqld server in one of these ways:
By invoking mysqld directly. This works on any platform.
By running the MySQL server as a Windows service. This can be done on versions of Windows that support services (such as NT, 2000, XP, and 2003). The service can be set to start the server automatically when Windows starts, or as a manual service that you start on request. For instructions, see Section 2.3.11, “Starting MySQL as a Windows Service”.
By invoking mysqld_safe, which tries to determine the proper options for mysqld and then runs it with those options. This script is used on Unix and Unix-like systems. See Section 5.4.2, “mysql.server — MySQL Server Startup Script”.
On Mac OS X, you can install a separate MySQL Startup Item package to enable the automatic startup of MySQL on system startup. The Startup Item starts the server by invoking mysql.server. See Section 2.5, -standard location. Modify it to
cd filename:
basedir,
datadir, and
pid-file.
If specified, they must be placed in an
option file, not on the command line.
mysql.server understands.3.2, “Using Option Files”.
This, see
Section 14.2.3, “
InnoDB Configuration”.
If you are using
BDB (Berkeley DB)
tables, see Section 14.5.3, “
BDB Startup Options”.
If you are using MySQL Cluster, see Section 15.4, “MySQL Cluster Configuration”.
options. the server fails to start up correctly, check the error
log. Log files are located in the data directory (typically
C:\Program Files\MySQL\MySQL Server
5.0. Then examine the last few lines of these files.
On Unix, you can use
tail to display them:.13,
to track down what program this is and disable it, or else
tell mysqld to listen to a different port
with the
--port option. In this case, you'll can't
Section E.1.2, “Creating Trace Files”..9 A.4.1, “How to Reset the Root Password”, covers the procedure
for resetting it.
To set up additional accounts, you can use the
GRANT statement. For instructions, see
Section 5.9.2, “Adding New User Accounts to MySQL”.
As a general rule, we recommend that when upgrading from one release series to another, you should go to the next series rather than skipping a series. For example, if you currently are running MySQL 3.23 and wish to upgrade to a newer series, upgrade to MySQL 4.0 rather than to 4.1 or 5.0.
The following items form a checklist of things that you should do whenever you perform an upgrade:
Before upgrading from MySQL 4.1 to 5.0, read Section 2.10.2, “Upgrading from MySQL 4.1 to 5.0”) as well as Appendix.”.
If you are running MySQL Server on Windows, see Section 2.3.14, “Upgrading MySQL on Windows”.
If you are using replication, see Section 6.6, “Upgrading a Replication Setup”, for information on upgrading your replication setup.
change the character set when running MySQL, you must run
myisamchk -r -q
--set-collation=
collation_name
on all
MyISAM tables. Otherwise, your indexes
may not be ordered correctly, because changing the character set
may also change the sort order..
When upgrading a 5.0 installation to 5.0.10 or above note that it is necessary to upgrade your grant tables. Otherwise, creating stored procedures and functions might not work. The procedure for doing this is described in Section 5.6.2, “mysql_upgrade — Check Tables for MySQL Upgrade”.
Note: It is good practice to back up your data before installing any new version of software. Although MySQL works very hard to ensure a high level of quality, you should protect your data by making a backup. MySQL generally recommends that you dump and reload your tables from any previous version to upgrade to 5.0.
In general, you should do the following when upgrading from MySQL 4.1 from 5.0:.14, “Upgrading MySQL on Windows”.
MySQL 5.0 adds support for stored procedures.
This support requires the
mysql.proc
table. To create this table, you should run the
mysql_upgrade script as described in
Section 5.6.2, “mysql_upgrade — Check Tables for MySQL Upgrade”.
MySQL 5.0 adds support for views. This support
requires extra privilege columns in the
mysql.user and
mysql.db tables. To create these columns,
you should run the mysql_upgrade script
as described in Section 5.6.2, .
Warning:: The
implementation of
DECIMAL has changed in
MySQL 5.0.3. You should make your applications aware of that
change, which is described in
Section 21.2, “
DECIMAL Data Type.6.2, “mysql_upgrade — Check Tables for MySQL Upgrade”..)
In MySQL 5.0.6, binary logging of stored routines and triggers was changed. This change has implications for security, replication, and data recovery, as discussed in Section 17.4, “Binary Logging of Stored Routines and Triggers”.
SQL Changes:. The precedence of the comma operator also
now is lower compared to
JOIN,
LEFT JOIN, and so forth.”.
Incompatible change:
Previously, a lock wait timeout caused
InnoDB to roll back the entire current
transaction. As of MySQL 5.0.13, it rolls back only the most
recent SQL statement.
Incompatible change: The
namespace for triggers has changed in MySQL 5.0.
Some keywords are reserved in MySQL 5.0 that were not reserved in MySQL 4.1. See Section 9.5, “Treatment of Reserved Words in MySQL”.
Chapter 21, Precision Math.
MySQL 5.0.3 and up uses precision math when calculating with
DECIMAL values (64 decimal digits) and
for rounding exact-value numbers. See
Chapter 21, Precision Math. A.5.8, “Problems with Floating-Point Comparisons”.
col_name=
some_double.5, “The Server SQL Mode”,.)
User variables are not case sensitive in MySQL
5.0. In MySQL 4.1,
SET @x = 0; SET @X
= 1; SELECT @x; created two variables and returned
0. In MySQL 5.0, it creates
one variable and returns
1..).
You can copy the
.frm,
.MYI, and
.MYD files
for
MyISAM tables between different
architectures that support the same floating-point format.
(MySQL takes care of any byte-swapping issues.) See
Section.
This section describes what you should do to downgrade to an older MySQL version in the unlikely case that the previous version worked better than the new one.
If you are downgrading within the same release series (for example, from 4.1.13 to 4.1.12) the general rule is that you just have to install the new binaries on top of the old ones. There is no need to do anything with the databases. As always, however, it is always a good idea to make a backup.
The following items form a checklist of things you should do whenever you perform a downgrade:
Read the upgrading section for the release series from which you are downgrading to be sure that it does not have any features you really need. Section 2.10, “Upgrading MySQL”.
If there is a downgrading section for that version, you should read that as well.
In most cases, you can move the MySQL format files and data files between different versions on the same architecture as long as you stay within versions for the same release series of MySQL.
If you downgrade from one release series to another, there may be
incompatibilities in table storage formats. In this case, you can
use mysqldump to dump your tables before
downgrading. After downgrading, reload the dump file using
mysql or
mysqlimport to
re-create your tables. For examples, see
Section 2.10.3, “Copying MySQL Databases to Another Machine”.
The normal symptom of a downward-incompatible table format change when you downgrade is that you can't.
After downgrading from MySQL 5.0, you may see the following
information in the
mysql.err file:
Incorrect information in file: './mysql/user.frm'
In this case, you can do the following:
Start MySQL 5.0.4 (or newer).
Run mysql_fix_privilege_tables, which
will change the
mysql.user table to a
format that both MySQL 4.1 and 5.0 can use.
Stop the MySQL server.
Start MySQL 4.1.
If the preceding procedure fails, you should be able to do the following instead:
Start MySQL 5.0.4 (or newer).
Run mysqldump --opt --add-drop-table mysql > /tmp/mysql.dump.
Stop the MySQL server.
Start MySQL 4.1 with the
--skip-grant
option.
Run mysql mysql < /tmp/mysql.dump.
Run mysqladmin flush-privileges...
The.
The following notes regarding
glibc apply
only to the situation when you build MySQL yourself. If you
are running Linux on an x86 machine, in most cases it is much
better for you to use our binary. We link our binaries against
the best patched version of
glibc we can
find and with the best compiler options, in an attempt to make
it suitable for a high-load server. For a typical user, even
for setups with a lot of concurrent connections or tables
exceeding the 2GB limit, our binary is the best choice in most
cases. After reading the following text, if you are in doubt
about what to do, try our binary first to determine whether it
meets your needs. If you discover that it is not good enough,
you may want to try your own build. In that case, we would
appreciate a note about it so that we can build a better
binary next time.
MySQL uses LinuxThreads on Linux. If you are using an old
Linux version:
Increase
PTHREAD_THREADS_MAX in
sysdeps/unix/sysv/linux/bits/local_lim.h
to 4096 and decrease
STACK_SIZE in
linuxthreads/internals.h to 256KB.
The paths are relative to the root of
glibc. (Note that MySQL is not stable
with 600-1000 connections if
STACK_SIZE
is the default of 2MB.)
Recompile LinuxThreads to produce a new
libpthread.a library, and relink
MySQL against it.
Additional information about circumventing thread limits in LinuxThreads can be found at.
There is another issue that greatly hurts MySQL performance,
especially on SMP systems. The mutex implementation in
LinuxThreads in
glibc 2.1 is very poor for
programs with many threads that hold the mutex only for a
short time. This produces a paradoxical result: If you link
MySQL against an unmodified LinuxThreads, removing processors
from an SMP actually improves MySQL performance in many cases.
We have made a patch available for
glibc
2.1.3 to correct this behavior
().
With
glibc 2.2.2, MySQL uses the adaptive
mutex, which is much better than even the patched one in
glibc 2.1.3. Be warned, however, that under
some conditions, the current mutex code in
glibc 2.2.2 overspins, which hurts MySQL
performance. The likelihood that this condition occurs can be
reduced by re-nicing the mysqld process to
the highest priority. We have also been able to correct the
overspin behavior with a patch, available at.
It combines the correction of overspin, maximum number of
threads, and stack spacing all in one. You need to apply it in
the
linuxthreads directory with
patch -p0
</tmp/linuxthreads-2.2.2.patch. We hope it is
included in some form in future releases of
glibc 2.2. In any case, if you link against
glibc 2.2.2, you still need to correct
STACK_SIZE and
PTHREAD_THREADS_MAX. We hope that the
defaults is corrected to some more acceptable values for
high-load MySQL setup in the future, so that the commands
needed to produce your own build can be reduced to
./configure; make; make install.
other applications. If you link other applications that
require LinuxThreads against the patched static version of the
library, or build a patched shared version and install it on
your system, you do so at your own risk.
If you experience any strange problems during the installation of MySQL, or with some common utilities hanging, it is very likely that they are either library or compiler related. If this is the case, using our binary resolves them. are using the Fujitsu compiler
(
fcc/FCC), you may.server can be found in the
support-files directory under the MySQL
installation directory or in a MySQL source tree. You can
install it as
/etc/init.d/mysql for
automatic MySQL startup and shutdown. See
Section 2.9.2.2, “Starting and Stopping MySQL Automatically”. the server a. We recommend values between
128KB and 256KB. we recommend it to our, we definitely recommend upgrading. A 5.4.1, “mysqld_safe — MySQL Server Startup Script”.
MySQL requires
libc 5.4.12 or newer. It is
known to work with
libc 5.4.46.
glibc may see mysqld die in
gethostbyaddr(). This happens because the
new
glibc library requires a stack size
greater than 128KB for this call. To fix the problem, start
mysqld with the
--thread-stack=192K option. 't do this,. Add an extra underscore
to the
_P macro name that has only one
underscore, and'
If mysqld always dumps core when it starts,
the problem may be that you have an old
/lib/libc.a. Try renaming it, the
SHOW
DATABASES statement always returns an empty set.
This can be fixed by removing
HAVE_READDIR_R from
config.h after configuring and before
compiling.
We: A.3.1, “Problems Linking to the MySQL Client Library”.
On Mac OS X, tar cannot handle long
filenames. If you need to unpack a
.tar.gz
distribution, use gnutar instead.
MySQL should work without major problems on Mac OS X 10.x (Darwin).
Known issues:
The connection times (
wait_timeout,
interactive_timeout and
net_read_timeout) values are not
honored.
This is probably a signal handling problem in the thread library where the signal doesn't break a pending read and we hope that a future update to the thread libraries will fix this..5, “Installing MySQL on Mac OS X”.
For Section 2.5, “Installing MySQL on Mac OS X”.
On Solaris, you may run into trouble even before you get the MySQL distribution unpacked, as the Solaris tar cannot handle long filenames. This means that you may see errors when you try to unpack MySQL.
If this occurs, you must use GNU tar (gtar) to unpack the distribution. You can find a precompiled copy for Solaris at.
Sun native threads work only on Solaris 2.5 and higher. For Solaris 2.4 and earlier, MySQL automatically uses MIT-pthreads. See Section 2.8.5, “MIT-pthreads Notes”. do
filesystems have problems with configure trying to
link with
-lz when you don.)
Solaris doesn't support core files for
setuid() applications, so you can't get a
core file from mysqld if you are using the
--user option.
Normally,.
On Solaris 8 on x86, mysqld dumps avoids problems with the
libstdc++
library and with C++ exceptions.
If this doesn't help, you should compile a debug version and run it with a trace file or under gdb. See Section E.1.3, “Debugging mysqld under gdb”.. cd /usr/local/mysql bin/mysql_install_db --user=mysql bin/mysqld_safe &
If you notice that configure uses A.2.17, “File Not Found”.
Appendix F,
Appendix F, Environment Variables.
Upgrade.
BSDI 4.x has some thread-related bugs. If you want to use MySQL on this, you should install all thread-related patches. At least M400-023 should be installed.
On some BSDI don..
If 5.4 behavior
directory
and run make:
extra/replace bool curses_bool < /usr/include/curses.h > include/curses.h make
There have also been reports of scheduling problems. If only one thread is running, performance is slow. Avoid this by starting another client. This may lead to a two-to-tenfold.
You need to at least install the "SCO OpenServer Linker and Application Development Libraries" or the OpenServer Development System to use gcc. You cannot just.
FSU Pthreads (at least the version at
ftp::/)().erver 6 includes these key improvements:
Larger file support up to 1 TB
Multiprocessor support increased from 4 to 32 processors
Increased memory support up to 64GB
Extending the power of UnixWare into OpenServer 6
Dramatic performance improvement
OpenServer 6.0.0 commands are organized as follows:
/bin is for commands that behave
exactly the same as on OpenServer 5.0.x.
/u95/bin is for commands that have
better standards conformance, for example Large File
System (LFS) support.
/udk/bin is for commands that behave
the same as on UnixWare 7.1.4. The default is for the LFS
support.
The following is a guide to setting PATH on OpenServer 6. If
the user wants the traditional OpenServer 5.0.x then
PATH should be
/bin
first. If the user wants LFS support 6.0.x:
CC="cc" CFLAGS="-I/usr/local/include" \ CXX="CC" CXXFLAGS="-I/usr/local/include" \ ./configure --prefix=/usr/local/mysql \ --enable-thread-safe-client --with-berkeley-db=./bdb \ --with-innodb --with-openssl --with-extra-charsets=complex \ --enable-readline. OpenServer 6.0.0 also needs patches to the MySQL
source tree and the patch for
config.guess applied to
bdb/dist/config.guess. You can download
the patches from
and from.
There is a
README file there to assist.
SCO provides OpenServer 6 operating system patches at.
SCO provides information about security fixes at.
By default, the maximum file size on a OpenServer 6.0.0 system is 1TB. Some operating system utilities have a limitation of 2GB. The maximum possible file size on UnixWare 7 is 1TB with VXFS or HTFS..
We recommend using the latest production release of MySQL..
By default, the maximum file size on a UnixWare 7.1.1 system is 1GB, but UnixWare 7.1.4 file size limit is 1 TB with VXFS. Some OS utilities have a limitation of 2GB. The maximum possible file size on UnixWare 7 is 1TB with VXFS. #..
MySQL uses quite a few open files. Because of this, you should
add something like the following to your
CONFIG.SYS file:
SET EMXOPT=-c -n -h1024
If you don eight characters.
Modules are stored in the
/mysql2/udf
directory; the
safe-mysqld.cmd script puts';
DBI/
DBDInterface
Perl support for MySQL is provided by means of the
DBI/
DBD client interface.
The interface requires Perl 5.6.1 or later. It does not
work if you have an older version of Perl.
If you want to use transactions with Perl DBI, you need to have
DBD::mysql version 1.2216 or newer.
DBD::mysql 2.9003 or newer is recommended.
If you are using the MySQL 4.1 or newer client library, you must
use
DBD::mysql 2.9003 or newer.
Perl support is not”.
MySQL username and password. (The default username don't have access rights to install Perl modules in the system directory or if you want to install local Perl modules, the following reference may be useful:
Look under the heading “Installing New Modules that Require Locally Installed Modules.”
On Windows, you should do the following to install the MySQL
DBD module with ActiveState Perl:
Get ActiveState Perl from and install it.
Open a console window (";
If Perl reports that it cannot find the
../mysql/mysql.so module, the problem is
probably that Perl cannot locate the
libmysqlclient.so shared library. You
should be able to fix this problem by one of the following
methods:
Compile the
DBD::mysql distribution with
perl Makefile.PL -static -config rather
than
perl Makefile.PL.
These changes are necessary because the Perl dynaloader does not
load the
DBI modules if they were compiled
with icc or cc.
If you want to use the Perl module on a system that doesn't
support dynamic linking (such as:
LD_LIBRARY_PATH=/lib:/usr/lib:/usr/local/lib:/usr/progressive/lib
Or:
LD_LIBRARY_PATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:\ /usr/progressive/lib:/usr/skunk/lib LIBPATH=/usr/lib:/lib:/usr/local/lib:/usr/ccs/lib:\ /usr/progressive/lib:/usr/skunk/lib MANPATH=scohelp:/usr/man:/usr/local1/man:/usr/local/man:\ /usr/skunk/man:
First, create a Perl that includes a statically linked
DBI module by running these commands in the
directory where your
DBI distribution is
located:
shell>
perl Makefile.PL -static -configshell>. | http://uw714doc.xinuos.com/en/MysqlDoc/installing.html | CC-MAIN-2021-39 | refinedweb | 10,751 | 68.67 |
py2exe 0.9.2.0
Build standalone executables for Windows (python 3 version)
py2exe is a distutils extension which allows to build standalone Windows executable programs (32-bit and 64-bit) from Python scripts; Python 3.3 and later are supported. It can build console executables, windows (GUI) executables, windows services, and DLL/EXE COM servers.
py2exe for Python 2 is still available at.
Contents
News
The C-runtime library for Python 3 does NOT need a windows manifest any longer to load correctly (this is a feature of Python, not of py2exe).
py2exe now contains a hooks module which contains information about some standard packages. The goal is to fine-tune the build process so that no (at least less) warnings are emitted from modulefinder.
Thanks to a brand new modulefinder (based on Python’s importlib) py2exe can now find and extract modules even from packages you have installed as zipped eggs.
py2exe now longer uses a build directory for temporary files.
It is planned to achive full compatibility with the setup-scripts for Python 2; however this is probably not yet the case.
In addition to your beloved setup.py scripts :-), there is now also a command-line utility which allows to build the exe without any effort.
Running
py -3.4 -m py2exe.build_exe myscript.py
or (if you have the Python Scripts directory on your PATH):
build_exe myscript.py
will create an executable myscript.exe in the dist subdirectory.
If you add the -W <setup-script.py> switch to the above command line a commented setup.py script will be generated which can be used to further customize the exe:
py -3.4 -m py2exe myscript.py -W mysetup.py ... edit myssetup.py py -3.4 mysetup.py py2exe
Installation
py -3.4 -m pip install py2exe
or
pip install py2exe
Using the builder
Build runtime archive for a script:
build_exe [-h] [-i modname] [-x modname] [-p package_name] [-O] [-s] [-r] [-f modname] [-v] [-c] [-d DESTDIR] [-l LIBNAME] [-b {0,1,2,3}] [-W setup_path] [-svc service] [script [script ...]]
- positional arguments:
- script
- optional arguments:
- -svc svnmodule, –service svcmodule
- The name of a module that contains a service
Using a setup-script
Creating an executable (or more than one at the same time) with a setup-script works in the same way as for Python 2. The command-line switches are the same as before; but they are NOT compatible with the command-line switches for the builder mentioned above.
Documentation about the setup-script and other usage tips are in the wiki pages at.
The bundle-files option explained
The applications that py2exe creates will always need the following parts:
- The exe-file(s) itself. py2exe can build several executables at the same time; this is especially useful if these are related to each other since some parts can be shared.
- The python-dll.
- The pure python modules needed to run the app. The byte-code for these modules is always packed into a zip-archive.
- Compiled python-extension modules.
- Supporting dlls, if any.
The bundle-files option determines how these files are packed together for your application. This is explained with a script test_sqlite.py that simply contains this code:
import sqlite3 print(sqlite3)
The command to build the exe-file is:
py2exe.build_exe test_sqlite.py -c --bundle-files <option>
The -c option specifies to create a compressed zip-archive.
--bundle-files 3 is the simplest way. These files will be created in a dist subdirectory, about 8 MB total size:
test_sqlite.exe _bz2.pyd _ctypes.pyd _hashlib.pyd _lzma.pyd _socket.pyd _sqlite3.pyd _ssl.pyd _win32sysloader.pyd pyexpat.pyd python34.dll pywintypes34.dll select.pyd sqlite3.dll unicodedata.pyd win32api.pyd win32evtlog.pyd
The zip-archive is appended to the test_sqlite.exe file itself, which has a size of 1.5 MB in this case.
--bundle-files 2 will include all the Python extensions into the appended zip-archive; they are loaded via special code at runtime without being unpacked to the file-system. The files in the dist directory now are these:
test_sqlite.exe python34.dll sqlite3.dll
--bundle-files 1 will additionally pack the python-dll into the zip-archive:
test_sqlite.exe sqlite3.dll
--bundle-files 0 now finally creates a real single-file executable of 6 MB:
test_sqlite.exe
If you are building several related executables that you plan to distribute together, it may make sense to specify a zip-archive shared by all the exes with the --library libname option. The executables will then become quite small (about 25 kB), since nearly all code will be in the separate shared archive.
Note that not all applications will work with “bundle-files“ set to 0 or 1. Be sure to test them.
Bugs
Building isapi extensions is not supported: I don’t use them so I will not implement this.
The modulefinder does not yet support PEP420 implicit namespace packages.
- Author: Thomas Heller
- License: MIT/X11
- Platform: Windows
- Categories
- Development Status :: 4 - Beta
- Environment :: Console
- License :: OSI Approved :: MIT License
- License :: OSI Approved :: Mozilla Public License 2.0 (MPL 2.0)
- Operating System :: Microsoft :: Windows
- Programming Language :: C
- Programming Language :: Python :: 3
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Programming Language :: Python :: Implementation :: CPython
- Topic :: Software Development
- Topic :: Software Development :: Libraries
- Topic :: Software Development :: Libraries :: Python Modules
- Topic :: System :: Software Distribution
- Topic :: Utilities
- Package Index Owner: theller, jretz
- DOAP record: py2exe-0.9.2.0.xml | https://pypi.python.org/pypi/py2exe/0.9.2.0 | CC-MAIN-2016-40 | refinedweb | 910 | 57.27 |
The implementation of POSIX threads on GNU/Linux differs from the thread implementation on many other UNIX-like systems in an important way: on GNU/Linux, threads are implemented as processes. Whenever you call pthread_create to create a new thread, Linux creates a new process that runs that thread. However, this process is not the same as a process you would create with fork; in particular, it shares the same address space and resources as the original process rather than receiving copies.
The program thread-pid shown in Listing 4.15 demonstrates this. The program creates a thread; both the original thread and the new one call the getpid function and print their respective process IDs and then spin infinitely.
#include <pthread.h>
#include <stdio.h>
#include <unistd.h>
void* thread_function (void* arg)
{
fprintf (stderr, "child thread pid is %d\n", (int) getpid ());
/* Spin forever. */
while (1);
return NULL;
}
int main ()
{
pthread_t thread;
fprintf (stderr, "main thread pid is %d\n", (int) getpid ());
pthread_create (&thread, NULL, &thread_function, NULL);
/* Spin forever. */
while (1);
return 0;
}
Run the program in the background, and then invoke ps x to display your running processes. Don't forget to kill the thread-pid program afterward—it consumes lots of CPU doing nothing. Here's what the output might look like:
% cc thread-pid.c -o thread-pid -lpthread
% ./thread-pid &
[1] 14608
main thread pid is 14608
child thread pid is 14610
% ps x
PID TTY STAT TIME COMMAND
14042 pts/9 S 0:00 bash
14608 pts/9 R 0:01 ./thread-pid
14609 pts/9 S 0:00 ./thread-pid
14610 pts/9 R 0:01 ./thread-pid
14611 pts/9 R 0:00 ps x
% kill 14608
[1]+ Terminated ./thread-pid
Notice that there are three processes running the thread-pid program. The first of these, with pid 14608, is the main thread in the program; the third, with pid 14610, is the thread we created to execute thread_function.
How about the second thread, with pid 14609? This is the "manager thread," which is part of the internal implementation of GNU/Linux threads. The manager thread is created the first time a program calls pthread_create to create a new thread.
Suppose that a multithreaded program receives a signal. In which thread is the signal handler invoked? The behavior of the interaction between signals and threads varies from one UNIX-like system to another. In GNU/Linux, the behavior is dictated by the fact that threads are implemented as processes.
Because each thread is a separate process, and because a signal is delivered to a particular process, there is no ambiguity about which thread receives the signal. Typically, signals sent from outside the program are sent to the process corresponding to the main thread of the program. For instance, if a program forks and the child process execs a multithreaded program, the parent process will hold the process id of the main thread of the child process's program and will use that process id to send signals to its child. This is generally a good convention to follow yourself when sending signals to a multithreaded program.
Note that this aspect of GNU/Linux's implementation of pthreads is at variance with the POSIX thread standard. Do not rely on this behavior in programs that are meant to be portable.
Within a multithreaded program, it is possible for one thread to send a signal specifically to another thread. Use the pthread_kill function to do this. Its first parameter is a thread ID, and its second parameter is a signal number.
Although GNU/Linux threads created in the same program are implemented as separate processes, they share their virtual memory space and other resources. A child process created with fork, however, gets copies of these items. How is the former type of process created?
The Linux clone system call is a generalized form of fork and pthread_create that allows the caller to specify which resources are shared between the calling process and the newly created process. Also, clone requires you to specify the memory region for the execution stack that the new process will use. Although we mention clone here to satisfy the reader's curiosity, that system call should not ordinarily be used in programs. Use fork to create new processes or pthread_create to create threads. | http://www.makelinux.net/alp/032 | CC-MAIN-2015-18 | refinedweb | 723 | 63.8 |
fleming 0.1
Python helpers for manipulating datetime objects relative to time zones
Fleming
================
This repository contains the Fleming package, which contains a set of routines for doing datetime manipulation. Named after Sandford Fleming, the father of worldwide standard timezones, this package is meant to aid datetime manipulations with regards to timezones.
Fleming addresses some of the common difficulties with timezones and datetime objects, such as performing arithmetic and datetime truncation across a Daylight Savings Time border. It also provides utilities for generating date ranges and getting unix times with respect to timezones.
Fleming accepts pytz timezone objects as parameters, and it is assumed that the user has a basic understanding of pytz. Click [here]() for more information about pytz.
A brief description of each function in this package is below. More detailed descriptions and advanced usage of the functions follow after that.
- convert_to_tz: Converts a datetime object into a provided timezone.
- add_timedelta: Adds a timedelta to a datetime object.
- floor: Truncates a datetime object down to a time interval.
- intervals: Gets a range of times at a given timedelta interval.
- unix_time: Returns a unix time stamp of a datetime object.
Note that all of these functions properly handle Daylight Savings Time transitions and other artifacts not normally supported in datetime manipulation. Keep reading for more detailed descriptions and examples of the functions.
### convert_to_tz(dt, tz, return_naive=False)
Given an aware or naive datetime dt, convert it to the timezone tz.
**Args:**
- dt: A naive or aware datetime object. If dt is naive, it has UTC set as its timezone.
- tz: A pytz timezone object specifying the timezone to which dt should be converted.
- return_naive: A boolean describing whether the return value should be a naive datetime object.
**Returns:**
An aware datetime object that was the result of converting dt into tz. If return_naive is True, the returned value has no tzinfo set.
**Examples:**
import fleming
import datetime
import pytz
dt = datetime.datetime(2013, 2, 4)
print dt
2013-02-04 00:00:00
# Convert naive UTC time to aware EST time
dt = fleming.convert_to_tz(dt, pytz.timezone('US/Eastern'))
print dt
2013-02-03 19:00:00-05:00
# Convert aware EST time to aware CST time
dt = fleming.convert_to_tz(dt, pytz.timezone('US/Central'))
print dt
2013-02-03 18:00:00-06:00
# Convert aware CST time back to naive UTC time
dt = fleming.convert_to_tz(dt, pytz.utc, return_naive=True)
print dt
2013-02-04 00:00:00
### add_timedelta(dt, td, within_tz=None, return_naive=False)
Given a naive or aware datetime dt, add a timedelta td to it and return it. If within_tz is specified, the datetime arithmetic happens with regard to the timezone. Proper measures are used to ensure that datetime arithmetic across a DST border is handled properly.
**Args:**
- dt: A naive or aware datetime object. If it is naive, it is assumed to be UTC.
- td: A timedelta (or relativedelta) object to add to dt.
- within_tz: A pytz timezone object. If provided, dt will be converted to this timezone before datetime arithmetic and then converted back to its original timezone afterwards.
- return_naive: A boolean defaulting to False. If True, the result is returned as a naive datetime object with tzinfo equal to None.
**Returns:**
An aware datetime object that results from adding td to dt. The timezone of the returned datetime will be equivalent to the original timezone of dt (or its DST equivalent if a DST border was crossed). If return_naive is True, the returned value has no tzinfo object.
**Examples:**
import pytz
import datetime
import fleming
# Do a basic timedelta addition to a naive UTC time and create an aware UTC time
# two weeks in the future
dt = datetime.datetime(2013, 3, 1)
dt = fleming.add_timedelta(dt, datetime.timedelta(weeks=2))
print dt
2013-03-15 00:00:00+00:00
# Do addition on an EST datetime where the arithmetic does not cross over DST
dt = fleming.convert_to_tz(dt, pytz.timezone('US/Eastern'))
print dt
2013-03-14 20:00:00-04:00
dt = fleming.add_timedelta(dt, datetime.timedelta(weeks=2, days=1))
print dt
2013-03-29 20:00:00-04:00
# Do timedelta arithmetic such that it starts in DST and crosses over into no DST.
# Note that the hours stay in tact and the timezone changes
dt = fleming.add_timedelta(dt, datetime.timedelta(weeks=-4))
print dt
2013-03-01 20:00:00-05:00
# Take a UTC time and do datetime arithmetic in regards to EST. Do the arithmetic
# such that a DST border is crossed
dt = datetime.datetime(2013, 3, 1, 5)
# It should be midnight in EST
print fleming.convert_to_tz(dt, pytz.timezone('US/Eastern'))
2013-03-01 00:00:00-05:00
# Do arithmetic on the UTC time with respect to EST.
dt = fleming.add_timedelta(
dt, datetime.timedelta(weeks=2), within_tz=pytz.timezone('US/Eastern'))
# The hour (4) of the returned UTC time is different that the original (5).
print dt
2013-03-15 04:00:00+00:00
# However, the hours in EST still reflect midnight
print fleming.convert_to_tz(dt, pytz.timezone('US/Eastern'))
2013-03-15 00:00:00-04:00
### floor(dt, floor, within_tz=None, return_naive=False)
Perform a 'floor' on a datetime, where the floor variable can be: 'year', 'month', 'day', 'hour', 'minute', 'second', or 'week'. This function will round the datetime down to the beginning of the start of the floor.
**Args:**
- dt: A naive or aware datetime object. If it is naive, it is assumed to be UTC.
- floor: The interval to be floored. Can be 'year', 'month', 'week', 'day', 'hour', 'minute', or 'second'.
- within_tz: A pytz timezone object. If given, the floor will be performed with respect to the timezone.
- return_naive: A boolean specifying whether to return the datetime object as naive.
**Returns:**
An aware datetime object that results from flooring dt to floor. The timezone of the returned datetime will be equivalent to the original timezone of dt (or its DST equivalent if a DST border was crossed). If return_naive is True, the returned value has no tzinfo object.
**Raises:**
ValueError if floor is not a valid floor value.
**Examples:**
import datetime
import pytz
import fleming
# Do basic floors in naive UTC time. Results are UTC aware
print fleming.floor(datetime.datetime(2013, 3, 3, 5), 'year')
2013-01-01 00:00:00+00:00
print fleming.floor(datetime.datetime(2013, 3, 3, 5), 'month')
2013-03-01 00:00:00+00:00
# Weeks start on Monday, so the floor will be for the previous Monday
print fleming.floor(datetime.datetime(2013, 3, 3, 5), 'week')
2013-02-25 00:00:00+00:00
print fleming.floor(datetime.datetime(2013, 3, 3, 5), 'day')
2013-03-03 00:00:00+00:00
# Use return_naive if you don't want to return aware datetimes
print fleming.floor(
datetime.datetime(2013, 3, 3, 5), 'day', return_naive=True)
2013-03-03 00:00:00
# Peform a floor in EST. The result is in EST
dt = fleming.convert_to_tz(
datetime.datetime(2013, 3, 4, 6), pytz.timezone('US/Eastern'))
print dt
2013-03-04 01:00:00-05:00
print fleming.floor(dt, 'year')
2013-01-01 00:00:00-05:00
print fleming.floor(dt, 'day')
2013-03-04 00:00:00-05:00
# Now perform a floor that starts out of DST and ends up in DST. The
# timezones before and after the floor will be different, but the
# time values are correct
dt = fleming.convert_to_tz(
datetime.datetime(2013, 11, 28, 6), pytz.timezone('US/Eastern'))
print dt
2013-11-28 01:00:00-05:00
print fleming.floor(dt, 'month')
2013-11-01 00:00:00-04:00
# Start with a naive UTC time and floor it with respect to EST
dt = datetime.datetime(2013, 2, 1)
# Since it is January 31 in EST, the resulting floored value
# for a day will be the previous day. Also, the returned value is
# in the original timezone of UTC
print fleming.floor(dt, 'day', within_tz=pytz.timezone('US/Eastern'))
2013-01-31 00:00:00+00:00
# Similarly, EST values can be floored relative to CST values.
dt = fleming.convert_to_tz(
datetime.datetime(2013, 2, 1, 5), pytz.timezone('US/Eastern'))
print dt
2013-02-01 00:00:00-05:00
# Since it is January 31 in CST, the resulting floored value
# for a day will be the previous day. Also, the returned value is
# in the original timezone of EST
print fleming.floor(dt, 'day', within_tz=pytz.timezone('US/Central'))
2013-01-31 00:00:00-05:00
### intervals(start_dt, td, within_tz=None, stop_dt=None, is_stop_dt_inclusive=False, count=0, return_naive=False)
Returns a range of datetime objects starting from start_dt and going in increments of timedelta td. If stop_dt is specified, the intervals go to stop_dt (and include stop_dt in the return if is_stop_dt_inclusive=True). If stop_dt is None, the count variable is used to control how many iterations are in the time intervals.
**Args:**
- start_dt: A naive or aware datetime object from which to start the time intervals. If it is naive, it is assumed to be UTC.
- td: A timedelta object describing the time interval in the intervals.
- within_tz: A pytz timezone object. If provided, the intervals will be computed with respect to this timezone.
- stop_dt: A naive or aware datetime object that specifies the end of the intervals. Defaults to being exclusive in the intervals. If naive, it is assumed to be in UTC.
- is_stop_dt_inclusive: True if the stop_dt should be included in the time intervals. Defaults to False.
- count: An integer specifying a count of intervals to use if stop_dt is None.
- return_naive: All datetimes in the intervals are returned as naive objects.
**Returns:**
A generator of datetime objects.
**Examples:**
import datetime
import pytz
import fleming
# Using a naive UTC time, get intervals of time for every day.
for dt in fleming.intervals(datetime.datetime(2013, 2, 3), datetime.timedelta(days=1), count=5):
print dt
2013-02-03 00:00:00+00:00
2013-02-04 00:00:00+00:00
2013-02-05 00:00:00+00:00
2013-02-06 00:00:00+00:00
2013-02-07 00:00:00+00:00
# Use an EST time. Do intervals of a day. Cross the DST time border on March 10th.
est_dt = fleming.convert_to_tz(datetime.datetime(2013, 3, 9, 5), pytz.timezone('US/Eastern'))
for dt in fleming.intervals(est_dt, datetime.timedelta(days=1), count=5):
print dt
2013-03-09 00:00:00-05:00
2013-03-10 00:00:00-05:00
2013-03-11 00:00:00-04:00
2013-03-12 00:00:00-04:00
2013-03-13 00:00:00-04:00
# Similarly, we can iterate through UTC times while doing the date range with respect to EST. Note
# that the UTC hour changes as the DST border is crossed on March 10th.
for dt in fleming.intervals(
datetime.datetime(2013, 3, 9, 5), datetime.timedelta(days=1), within_tz=pytz.timezone('US/Eastern'),
count=5):
print dt
2013-03-09 05:00:00+00:00
2013-03-10 05:00:00+00:00
2013-03-11 04:00:00+00:00
2013-03-12 04:00:00+00:00
2013-03-13 04:00:00+00:00
# Use a stop time. Note that the stop time is exclusive
for dt in fleming.intervals(
datetime.datetime(2013, 3, 9), datetime.timedelta(weeks=1), stop_dt=datetime.datetime(2013, 3, 23)):
print dt
2013-03-09 00:00:00+00:00
2013-03-16 00:00:00+00:00
# Make the previous range inclusive
for dt in fleming.intervals(
datetime.datetime(2013, 3, 9), datetime.timedelta(weeks=1), stop_dt=datetime.datetime(2013, 3, 23),
is_stop_dt_inclusive=True):
print dt
2013-03-09 00:00:00+00:00
2013-03-16 00:00:00+00:00
2013-03-23 00:00:00+00:00
# Arbitrary timedeltas can be used for any sort of time range
for dt in fleming.intervals(
datetime.datetime(2013, 3, 9), datetime.timedelta(days=1, hours=2, minutes=1), count=5):
print dt
2013-03-09 00:00:00+00:00
2013-03-10 02:01:00+00:00
2013-03-11 04:02:00+00:00
2013-03-12 06:03:00+00:00
2013-03-13 08:04:00+00:00
### unix_time(dt, within_tz=None, return_ms=False)
Converts a naive or aware datetime object to unix timestamp. If within_tz is present, the timestamp returned is relative to that time zone.
**Args:**
- dt: A naive or aware datetime object. If it is naive, it is assumed to be UTC.
- within_tz: A pytz timezone object if the user wishes to return the unix time relative to another timezone.
- return_ms: A boolean specifying to return the value in milliseconds since the Unix epoch. Defaults to False.
**Returns:**
An integer timestamp since the Unix epoch. If return_ms is True, returns the timestamp in milliseconds.
**Examples:**
import datetime
import pytz
import fleming
# Do a basic naive UTC conversion
dt = datetime.datetime(2013, 4, 2)
print fleming.unix_time(dt)
1364860800
# Convert a time in a different timezone
dt = fleming.convert_to_tz(
datetime.datetime(2013, 4, 2, 4), pytz.timezone('US/Eastern'))
print dt
2013-04-02 00:00:00-04:00
print fleming.unix_time(dt)
1364875200
# Print millisecond returns
print fleming.unix_time(dt, return_ms=True)
1364875200000
# Do a unix_time conversion with respect to another timezone. When
# it is converted back to a datetime, the time values are correct.
# The original timezone, however, needs to be added back
dt = datetime.datetime(2013, 2, 1, 5)
# Print its EST time for later reference
print fleming.convert_to_tz(dt, pytz.timezone('US/Eastern'))
2013-02-01 00:00:00-05:00
unix_tz_dt = fleming.unix_time(
dt, within_tz=pytz.timezone('US/Eastern'))
print unix_tz_dt
1359676800
# The datetime should match the original UTC time converted in
# the timezone of the within_tz parameter. Tz information is
# originally lost when converting to unix time, so replace the
# tzinfo object here
dt = datetime.datetime.fromtimestamp(unix_tz_dt).replace(
tzinfo=pytz.timezone('US/Eastern'))
print dt
2013-02-01 00:00:00-05:00
### License
MIT License (see LICENSE.md)
- Downloads (All Versions):
- 81 downloads in the last day
- 476 downloads in the last week
- 1910 downloads in the last month
- Author: Wes Kendall
- Keywords: python datetime pytz timezone timedelta arithmetic floor conversion
- License: MIT
- Categories
- License :: OSI Approved :: MIT License
- Programming Language :: Python :: 2.7
- Programming Language :: Python :: 3.0
- Programming Language :: Python :: 3.1
- Programming Language :: Python :: 3.2
- Programming Language :: Python :: 3.3
- Programming Language :: Python :: 3.4
- Topic :: Software Development :: Libraries :: Python Modules
- Topic :: Utilities
- Package Index Owner: ambitioninc
- DOAP record: fleming-0.1.xml | https://pypi.python.org/pypi/fleming/0.1 | CC-MAIN-2016-07 | refinedweb | 2,441 | 59.09 |
Overview
Atlassian SourceTree is a free Git and Mercurial client for Windows.
Atlassian SourceTree is a free Git and Mercurial client for Mac.
Py3Sensors
Python bindings for libsensors.so from the lm-sensors project via ctypes. Supported only 4 API version.
Requirements
- Python 2.7 or Python ≥3.3
- libsensors.so from lm-sensors version 3.x (API 4)
The package is pure Python, so any implementation with the ctypes module should work.
Installation
The usual python setup.py install from within the source distribution.
Links
Example
The following example prints all detected sensor chips, their adapter, and the features with they ”main” value for each chip:
import sensors sensors.init() try: for chip in sensors.iter_detected_chips(): print ('%s at %s' % (chip, chip.adapter_name)) for feature in chip: print (' %s: %.2f' % (feature.label, feature.get_value())) finally: sensors.cleanup()
Example output of the code above:
k8temp-pci-00c3 at PCI adapter Core0 Temp: 16.00 Core0 Temp: 11.00 Core1 Temp: 28.00 Core1 Temp: 19.00 w83627ehf-isa-0290 at ISA adapter Vcore: 1.10 in1: 1.10 AVCC: 3.30 VCC: 3.31 in4: 1.68 in5: 1.68 in6: 1.86 3VSB: 3.30 Vbat: 3.06 in9: 1.55 Case Fan: 1231.00 CPU Fan: 2410.00 Aux Fan: 0.00 fan5: 0.00 Sys Temp: 39.00 CPU Temp: 31.50 AUX Temp: 30.50 cpu0_vid: 0.00 | https://bitbucket.org/gleb_zhulik/py3sensors | CC-MAIN-2017-34 | refinedweb | 232 | 83.22 |
#include <wx/toolbar.h>
A toolbar is a bar of buttons and/or other controls usually placed below the menu bar in a wxFrame.
You may create a toolbar that is managed by a frame calling wxFrame::CreateToolBar(). Under Pocket PC, you should always use this function for creating the toolbar to be managed by the frame, so that wxWidgets can use a combined menubar and toolbar. Where you manage your own toolbars, create wxToolBar as usual.
There are several different types of tools you can add to a toolbar. These types are controlled by the wxItemKind enumeration.
Note that many methods in wxToolBar such as wxToolBar::AddTool return a
wxToolBarToolBase* object. This should be regarded as an opaque handle representing the newly added toolbar item, providing access to its id and position within the toolbar. Changes to the item's state should be made through calls to wxToolBar methods, for example wxToolBar::EnableTool. Calls to
wxToolBarToolBase methods (undocumented by purpose) will not change the visible state of the item within the tool bar.
After you have added all the tools you need, you must call Realize() to effectively construct and display the toolbar.
wxMSW note: Note that under wxMSW toolbar paints tools to reflect system-wide colours. If you use more than 16 colours in your tool bitmaps, you may wish to suppress this behaviour, otherwise system colours in your bitmaps will inadvertently be mapped to system colours. To do this, set the msw.remap system option before creating the toolbar:
If you wish to use 32-bit images (which include an alpha channel for transparency) use:
Then colour remapping is switched off, and a transparent background used. But only use this option under Windows XP with true colour:
This class supports the following styles:
wxTB_TEXT.
wxTB_HORZ_LAYOUTand
wxTB_TEXT.
wxTB_HORIZONTALstyle. This style is new since wxWidgets 2.9.5.
See also Window Styles. Note that the wxMSW native toolbar ignores
wxTB_NOICONS style. Also, toggling the
wxTB_TEXT works only if the style was initially on.
The following event handler macros redirect the events to member function handlers 'func' with prototypes like:
Event macros for events emitted by this class:_TOOL_DROPDOWNevent. If unhandled, displays the default dropdown menu set using wxToolBar::SetDropdownMenu().
The toolbar class emits menu commands in the same way that a frame menubar does, so you can use one EVT_MENU() macro for both a menu item and a toolbar button. The event handler functions take a wxCommandEvent argument. For most event macros, the identifier of the tool is passed, but for EVT_TOOL_ENTER() the toolbar window identifier is passed and the tool identifier is retrieved from the wxCommandEvent. This is because the identifier may be
wxID_ANY when the mouse moves off a tool, and
wxID_ANY is not allowed as an identifier in the event system.
Default constructor.
Constructs a toolbar.
Toolbar destructor.
Adds any control to the toolbar, typically e.g. a wxComboBox.
wxMAC_USE_NATIVE_TOOLBARset to 1
Adds a new radio tool to the toolbar.
Consecutive radio tools form a radio group such that exactly one button in the group is pressed at any moment, in other words whenever a button in the group is pressed the previously pressed button is automatically released. You should avoid having the radio groups of only one element as it would be impossible for the user to use such button.
By default, the first button in the radio group is initially pressed, the others are not.
Adds a separator for spacing groups of tools.
Notice that the separator uses the look appropriate for the current platform so it can be a vertical line (MSW, some versions of GTK) or just an empty space or something else.
Adds a stretchable space to the toolbar.
Any space not taken up by the fixed items (all items except for stretchable spaces) is distributed in equal measure between the stretchable spaces in the toolbar. The most common use for this method is to add a single stretchable space before the items which should be right-aligned in the toolbar, but more exotic possibilities are possible, e.g. a stretchable space may be added in the beginning and the end of the toolbar to centre all toolbar items.
Adds a tool to the toolbar.
Adds a tool to the toolbar.
This most commonly used version has fewer parameters than the full version below which specifies the more rarely used button features.
Adds a tool to the toolbar.
Deletes all the tools in the toolbar.
Factory function to create a new separator toolbar tool.
Factory function to create a new toolbar tool.
Factory function to create a new control toolbar tool.
Removes the specified tool from the toolbar and deletes it.
If you don't want to delete the tool, but just to remove it from the toolbar (to possibly add it back later), you may use RemoveTool() instead.
This function behaves like DeleteTool() but it deletes the tool at the specified position and not the one with the given id.
Enables or disables the tool.
Returns a pointer to the tool identified by id or NULL if no corresponding tool is found.
Returns a pointer to the control identified by id or NULL if no corresponding control is found.
Finds a tool for the given mouse position.
Returns the left/right and top/bottom margins, which are also used for inter-toolspacing.
Returns the size of bitmap that the toolbar expects to have.
The default bitmap size is platform-dependent: for example, it is 16*15 for MSW and 24*24 for GTK. This size does not necessarily indicate the best size to use for the toolbars on the given platform, for this you should use
wxArtProvider::GetNativeSizeHint(wxART_TOOLBAR) but in any case, as the bitmap size is deduced automatically from the size of the bitmaps associated with the tools added to the toolbar, it is usually unnecessary to call SetToolBitmapSize() explicitly.
Returns a pointer to the tool at ordinal position pos.
Don't confuse this with FindToolForPosition().
Get any client data associated with the tool.
Called to determine whether a tool is enabled (responds to user input).
Returns the long help for the given tool.
Returns the value used for packing tools.
Returns the tool position in the toolbar, or
wxNOT_FOUND if the tool is not found.
Returns the number of tools in the toolbar.
Returns the default separator size.
Returns the short help for the given tool.
Returns the size of a whole button, which is usually larger than a tool bitmap because of added 3D effects.
Gets the on/off state of a toggle tool.
Inserts the control into the toolbar at the given position.
You must call Realize() for the change to take place.
Inserts the separator into the toolbar at the given position.
You must call Realize() for the change to take place.
Inserts a stretchable space at the given position.
See AddStretchableSpace() for details about stretchable spaces.
Inserts the tool with the specified attributes into the toolbar at the given position.
You must call Realize() for the change to take place.
Inserts the tool with the specified attributes into the toolbar at the given position.
You must call Realize() for the change to take place.
Called when the user clicks on a tool with the left mouse button.
This is the old way of detecting tool clicks; although it will still work, you should use the EVT_MENU() or EVT_TOOL() macro instead.
This is called when the mouse cursor moves into a tool or out of the toolbar.
This is the old way of detecting mouse enter events; although it will still work, you should use the EVT_TOOL_ENTER() macro instead.
Called when the user clicks on a tool with the right mouse button. The programmer should override this function to detect right tool clicks.
This function should be called after you have added tools.
Removes the given tool from the toolbar but doesn't delete it.
This allows inserting/adding this tool back to this (or another) toolbar later.
Sets the dropdown menu for the tool given by its id.
The tool itself will delete the menu when it's no longer needed. Only supported under GTK+ und MSW.
If you define a EVT_TOOL_DROPDOWN() handler in your program, you must call wxEvent::Skip() from it or the menu won't be displayed.
Set the values to be used as margins for the toolbar.
Set the margins for the toolbar.
Sets the default size of each tool bitmap.
The default bitmap size is 16 by 15 pixels.
Note that size does not need to be multiplied by the DPI-dependent factor even under MSW, where it would normally be necessary, as the toolbar adjusts this size to the current DPI automatically.
Sets the client data associated with the tool.
Sets the bitmap to be used by the tool with the given ID when the tool is in a disabled state.
This can only be used on Button tools, not controls.
Sets the long help for the given tool.
Sets the bitmap to be used by the tool with the given ID.
This can only be used on Button tools, not controls.
Sets the value used for spacing tools.
The default value is 1.
Sets the default separator size.
The default value is 5.
Sets the short help for the given tool.
Toggles a tool on or off.
This does not cause any event to get emitted. | https://docs.wxwidgets.org/trunk/classwx_tool_bar.html | CC-MAIN-2021-49 | refinedweb | 1,570 | 65.73 |
The integrates to 1 over a given interval. This algorithm will do just that, as illustrated by the Plot done with Matplotlib. Notice how the samples follow the theoretical PDF.
A good exercise is to plug your own PDF, and see how the algorithm is capable of sampling from any PDF. Another interesting thing is to try and see how fast the algorithm converges to the PDF given.
Thank you for this recipe, I found it very helpful while learning about Metropolis-Hastings.
One thing though, this is technically just a Metropolis algorithm because the acceptance ratio does not incorporate the proposal distribution. In this case, it not a problem because you have a symmetric proposal distribution (so it cancels out), but might confuse readers.
RandomArray from Numeric has been deprecated for a while now. Interestingly, the code just runs when the import RandomArray line is commented out. I don't know which line was supposed to use this package.
^ you can use numpy libraries for the proposal distribution.
import numpy as np
in line 20
innov=np.random.uniform(-alpha, alpha, n) and similarly line 24
great post. and thanks for the comment Tim, important clarification there! | https://code.activestate.com/recipes/414200-metropolis-hastings-sampler/?in=user-2434632 | CC-MAIN-2022-05 | refinedweb | 198 | 58.48 |
TeX makes it time consuming and error-prone to change the typeset calculations; results have to be changed by hand. Using the listings package works, but this can only contain the calculations without explanations or units, and the results aren’t always nicely formatted
Technical calculations without units are generally meaningless, so it was important for me to be able to include them in the results.
So I wrote a Python module called texcalc that allows me to do calculations and typesets the results for me. It works like this;
from __future__ import print_function from texcalc import Calculation c = Calculation() c.add('rho_f', 2.62, 'g/cm^3', 'fiber density') c.add('W_f', 450, 'g/cm^2', 'fiber area weight', fmt='.0f') c.add('v_f', 0.3, '-', 'fiber volume fraction') c.add('rho_m', 1.15, 'g/cm^3', 'matrix density') c.add('t_f', 'W_f*10/(10000*rho_f)', 'mm', 'fiber “thickness”') c.add('t', 't_f/v_f', 'mm', 'laminate thickness') c.add('t_m', 't-t_f', 'mm', 'resin “thickness”') c.add('W_m', 't_m/10*rho_m*10000', 'g/m^2', 'resin area weight', fmt='.0f') c.add('w_f', 'W_f/(W_f+W_m)', '-', 'fiber weight fraction') print(c)
Using a Calculation object one can define a sequence of variable assignments or expressions using variables that have been assigned earlier. Printing the Calculation (or rather converting it to a string) will cause a LaTeX formatted version in the form of an array environment to be produced. When this is written to a file it can be included in a LaTeX document using \input. The typeset result looks quite nice. (Note that siunitx was set up to use a decimal comma in this example);
It uses the siunitx package to typeset the units of the variables and calculation results. It uses \mbox to include plain text in the otherwise math-mode environment. This means that the comments should be kept reasonably short so they fit one one line. The generated LaTeX code isn’t set up to handle comments that would span multiple lines.
$\begin{array}{lclcrl} \rho_f & = & & & \mbox{\SI{2.62}{g/cm^3}} & \mbox{fiber density} \\ W_f & = & & & \mbox{\SI{450}{g/cm^2}} & \mbox{fiber area weight} \\ v_f & = & & & \mbox{\SI{0.30}{-}} & \mbox{fiber volume fraction} \\ \rho_m & = & & & \mbox{\SI{1.15}{g/cm^3}} & \mbox{matrix density} \\ t_f & = & \displaystyle \frac{W_f\cdot 10}{10000\cdot \rho_f} & = & \mbox{\SI{0.17}{mm}} & \mbox{fiber “thickness”} \\ t & = & \displaystyle \frac{t_f}{v_f} & = & \mbox{\SI{0.57}{mm}} & \mbox{laminate thickness} \\ t_m & = & \displaystyle t-t_f & = & \mbox{\SI{0.40}{mm}} & \mbox{resin “thickness”} \\ W_m & = & \displaystyle \frac{t_m}{10}\cdot \rho_m\cdot 10000 & = & \mbox{\SI{461}{g/m^2}} & \mbox{resin area weight} \\ w_f & = & \displaystyle \frac{W_f}{W_f+W_m} & = & \mbox{\SI{0.49}{-}} & \mbox{fiber weight fraction} \\ \end{array}$\hfill
Note
This module uses eval, which exposes the full capabilities of the Python interpreter. This module should therefore _not_ be used with untrusted input!
The source repository is now available on github. This program is now written for Python 3. The generated LaTeX code requires the siunitx package. | http://rsmith.home.xs4all.nl/software/texcalc.html | CC-MAIN-2017-17 | refinedweb | 507 | 58.99 |
Search Criteria
Package Details: monosim-gtk 2.0.1.0-2
Dependencies (6)
- gtk
- log4net
- mono (mono48, mono-noconflict, mono-nightly, mono-alpha, mono-beta, mono-stable, mono-git, mono-visualstudio)
- pcsclite (pcsclite-git, pcsclite-nopy)
- bash (bash-devel-git, bash-devel-static-git) (make)
- git (git-git) (make)
Latest Comments
papo commented on 2018-03-13 10:41
gtk-sharp-2 still needs to be added manually as dependency. Plus, the build is currently subject to this problem:
prefixing yaourt with TERM=xterm did work around the issue for me.
Faalagorn commented on 2017-11-27 05:30
It seems wget is also needed as a make dependency. It wasn't obvious for me as it turned out I didn't had wget installed and the package was missing comex-base that was nowhere to be found. Based on the build instructions here it turned out that wget is required to download comex-base in prepare.sh file so after installing wget it worked :)
jtmb commented on 2017-08-07 08:05
dependency 'gtk' wasn't found, I changed it to gtk2 in the PKGBUILD and it works fine.
natestar13 commented on 2016-04-13 18:08
Please add the gtk-sharp-2 package as a dependency.
Without this package installed, I would get the following error when I tried to compile and install the monosim-gtk package:
The type or namespace name `Gtk' could not be found. Are you missing an assembly reference? | https://aur.tuna.tsinghua.edu.cn/packages/monosim-gtk/ | CC-MAIN-2019-30 | refinedweb | 245 | 59.53 |
Elastic::Manual::Attributes::Unique - Making attributes unique
version 0.52
The only unique constraint available in Elasticsearch is the document ID. Typically, if you want a document to be unique, you use the unique value as the ID.
However, sometimes you don't want to do this. For instance, you may want to use the email address as a unique constraint for your user accounts, but you also want to be able to link to a user account without exposing their email address, and let the user change their email address without having to update the ID of their user account wherever it is used.
In this case,
we want the ID of the user document to be auto-generated,
but we also want the value of the
Elastic::Model adds support for unique constraints other than the ID.
Your unique attributes are tracked in a special index which defaults to
"unique_key",
but which can be specified in your Model class:
package MyApp; use Elastic::Model; has_namespace 'foo' .....; has_unique_index 'myapp_uniques';
The index will be created automatically.
Any attribute whose value is a string (including numeric attributes) can have a unique constraint applied:
has 'email' => ( is => 'rw', isa => 'Str', unique_key => 'myapp_email' );
The
unique_key value will be used as the
type in the unique keys index. For instance, if the
john@foo.com, then the unique entry for this document will be stored in
index:myapp_uniques, under
type:myapp_email with
id:john@foo.com.
The
unique_key can only be used once in a doc class. You can't have (eg) the attributes
unique_key of
myapp_email.
It is easy to make a compound key a unique constraint. For instance, to combine the attributes
account_type and
account_name you could do:
has 'account_type' => ( is => 'rw', isa => 'Str', required => 1, trigger => sub { shift->clear_account_key } ); has 'account_name' => ( is => 'rw', isa => 'Str', required => 1, trigger => sub { shift->clear_account_key } ); has 'account_key' => ( is => 'ro', isa => 'Str', init_arg => undef, lazy => 1, unique_key => 'account_key', builder => '_build_account_key', clearer => 'clear_account_key', ); sub _build_account_key { my $self = shift; return $self->account_type . ':' .$self->account_name }
When the doc is saved after either the
account_type or
account_name is changed, the
account_key will be checked for uniqueness.
When you save a doc, any unique keys will be checked for uniqueness, and an error will be thrown if there is a conflict.
You can handle these error gracefully using the on_unique parameter:
$doc->save( on_unique => sub { my ($doc,$failed) = @_; # do something } )
The
$failed hashref will contain a hashref whose keys are the name of the unique_keys that have conflicts, and whose values are the values of those keys which already exist, and so cannot be overwritten. For instance:
{ account_key => 'facebook:joe_bloggs' }
You can't overwrite a doc with unique keys that hasn't already been loaded from Elasticsearch. For instance, you can do:
$user = $domain->get( user => 1 ); $user->email('jack@foo.com'); $user->overwrite;
But not:
$user = $domain->new_doc( user => { id => 1, email => 'jack@foo.com' }); $user->overwrite;
The reason for this is that, if that user already exists, then overwriting that doc will leave any old unique keys in place. "save()" in Elastic::Model::Role::Doc will handle the old unique values correctly.
If you use "delete()" in Elastic::Model::View then you are responsible for removing the related keys yourself.
The unique keys index will not be updated if you change the
unique_key name, and reindexing does not take unique keys into account at all. It is up to you to manage. | http://search.cpan.org/~drtech/Elastic-Model/lib/Elastic/Manual/Attributes/Unique.pod | CC-MAIN-2016-36 | refinedweb | 574 | 59.13 |
Agenda
See also: IRC log
RESOLUTION: Minutes of 9 August approved as published
Next meeting: 23 August
No regrets notified as yet
Agenda slightly reordered to put namespace binding first
HST: AM and JT have maybe reached agreement on this issue
AM: Option values are a
combination of a string and a set of namespace bindings
... this is for QName [and XPath] interpretation
... Where do these namespace bindings come from?
... By default, from the option element itself
... but you can use a 'namespaces' attribute on p:option to identify a node whose bindings should be used
AM: Consider constructing a string from a document to get an option value
<Norm> I don't see any examples that use the new 'namespaces' attribute. Am I blind?
AM: you want to take the nearest
ancestor-or-self to get nsb
... The tricky case is when you use an option value to set an option value
... In that case you pass the namespace bindings along with
... The remaining case which my proposal doesn't cover is when you construct a value which e.g. concats another option value
JT: I suggest we add a special-purpose step which handles this case
AM: This approach requires the author to do some extra work
NW: Could we see an example which requires this, and how it would work
<Jeni> concat($delete, '/html:p')
<alexmilowski> e.g. the option value is an element QName that is used in a constructed XPath
JT: So the p:to-xml step can be
used to unpack an option into an element with the namespace bindings from it
and value its value
... and then you can do anything you need to
... with that document, and then use the result to set an option
RT: We couldn't write the
p:to-xml step currently
... because the connection from the string to the namespace bindings is not available e.g. to XSLT
JT: Yes
AM: Have we really solved the
problem of supporting general XPath construction?
... I don't think so, because of possible NS conflicts
NW: No way to make it work in principle
RT: Yes there is -- there's
always an XPath that does the right thing, if you know all the
QNames anywhere in the string, and all the prefix
bindings
... this would work even if there were two a: prefixed names with different bindings
HST: I wonder if Alex isn't pointing us in the right direction
HST: We should just support XPath construction and bare QNames
<Jeni> Those are the major cases, but they're not the only cases.
HST: What about the following: <p:option
JT: As proposed, the namespaces attribute provides the only bindings, so that wouldn't work
HST: But couldn't we spec. it to merge in a defined way
AM: Yes, but what about conflicts
HST: I'm happy for that case to cause an error
RT: What about a component for generating a QName with a guaranteed-unique prefix bound to a specified namespace, so there couldn't be a complex
AM: I'm inclined towards HST's proposal
NW: Why not combine in [scribe missed]
RT: Why not allow the namespaces attribute to specify a set of namespaces
JT: Then we should go with my original proposal to have a <p:namespaces> element
NW: It seems to me that the p:namespaces element proposal involves a bit less magic. . .
<Norm> I had been queued to ask if everyone was happy with $option values carrying namespaces, but since I don't see any alternative...I'm going to let it go.
<alexmilowski> (in my proposal I mentioned we could allow a node set and just take the first one)
<alexmilowski> (as an option)
HST:[Summarizes the dimension of variation and asks for a round-robin]
1: Minimum: option values carry NS bindings with them
2: You can override the bindings with one (or more?) XPaths to pick up a node
3: Some kind of merger, with error or priority
4: Allow many sources of bindings
AM: Does (1) get its bindings from the context of the XPath
HST: Yes.
NW: (2) and above include p:to-xml
NW: (4) -- others have too much explanatory overhead
PG: Concur
Jeni: Could live with anything above (1), prefer (4) as per NW
HST: I prefer (3) because it covers the 99% case w/o having to use the new step, could live (4)
RT: Completely uncertain, not sure I understand implications of (4), Abstain
RL: Concur
AF: Abstain
AM: (3), could perhaps live with (4)
NW: I suggest the editor try to write up (4) and we see what it looks like
<scribe> ACTION: Editor to write up (4) and we see what it looks like [recorded in]
NW: I think we can go to Last Call if we get agreement on that
HST: I'm still in the middle of a
careful readthrough, and so far one point has arisen which
could be considered as a real issue
... and I'm confident we'll deal with it
NW, HST: [discussion about names on p:when etc. issue]
NW: What about 'yes|no' vs. 'true|false'
JT: Given that people may use XPaths to generate values, we should go for 'true|false'
NW: I'm just not sure how people who expect 'yes|no' will feel
HST: I prefer just 'true|false' (and maybe 0|1)
NW: Anyone opposed to restricting all the boolean-type things in the spec to 'true|false'?
RESOLUTION: To restrict all the boolean-type things in the spec to 'true|false'. | http://www.w3.org/XML/XProc/2007/08/16-minutes.html | CC-MAIN-2015-06 | refinedweb | 933 | 57.64 |
Render full Observable notebooks in Atom!
Package here. You can
apm install atom-observable or just look up
atom-observable in the Atom package installer.
When you have a "notebook" file open, just press
Alt+Ctrl+O (or
Packages ->
atom-observable ->
Toggle), and a preview will popup, with the rendered notebook.
Once the preview is open, whenever you save the file, the entire preview will reload. It's not as cool of a dev experience as observablehq.com is, but it's something!
All
stdlib should work -
DOM,
require,
html,
md, all that.
import cells will resolve from observablehq.com by default.
It's basically just a regular notebook you would write on observablehq.com, but in a file. It can be made of several top-level cell definitions - with import support!
For example:
a = 1b = 2c = a + bviewof name = DOM.input()md`Hello ${name}!`import {chart} from "@d3/bar-chart"
Keep in mind - not all javascript files are valid Observable syntax.
example_notebooks has a few examples of what could work.
Most of the magic happens with
@alex.garcia/unofficial-observablehq-compiler - an unofficial compiler for Observable notebook syntax. All this package does is basically send the file contents to an iframe, and a script in the iframe uses the compiler to compile it to an element.
Please do! There's a ton of potential here - access to node.js, custom libraries, better local development. Take a look at these issues to find something to work on. Just please follow the Contributor Covenant in all your interactions 😄
This was built with libraries like @observablehq/runtime and @observablehq/parser which are licensed under ISC.
Good catch. Let us know what about this package looks wrong to you, and we'll investigate right away. | https://api.atom.io/packages/atom-observable | CC-MAIN-2020-34 | refinedweb | 292 | 59.8 |
If your transaction script needs to connect to a server over TCP secured with TLS, an additional module is available:
tls. Its usage and syntax are very similar to that of the
net module.
To use the
tls module, make sure to first import it within your transaction script:
import net from 'thousandeyes';
To create a client connection that includes TLS, use the
connectTls function:
await net.connectTls(<port>, '<host.ip.address>', [OPTIONS])
In the following example, notice that you first set host and port; then use those when you call
net.connectTls:
import net from 'thousandeyes';runScript();async function runScript() {let host = 'cdn.the-acme-corporation.net';let port = 443;let request_body =`GET / HTTP/1.1Host: ${host}User-Agent: thousandeyes-transaction`let client = await net.connectTls(port, host);await client.write(request_body);let response = await client.read();console.log(response.toString());};
For additional examples, see the public repository of ThousandEyes transaction scripts. | https://docs.thousandeyes.com/product-documentation/tests/tls-module | CC-MAIN-2021-21 | refinedweb | 153 | 50.53 |
Analysis
Suppose our text data is currently arranged into a single file, where each line of that file contains all of the text in a single document. Here we can use SFrame.read_csv to parse the text data into a one-column SFrame.
import os if os.path.exists('wikipedia_w16'): sf = graphlab.SFrame('wikipedia_w16') else: sf = graphlab.SFrame.read_csv('', header=False) sf.save('wikipedia_w16')
sf
Columns: X1 str Rows: 72269 Data: +--------------------------------+ | X1 | +--------------------------------+ | alainconnes alain connes i ... | | americannationalstandardsi ... | | alberteinstein near the be ... | | austriangerman as german i ... | | arsenic arsenic is a metal ... | | alps the alps alpen alpi a ... | | alexiscarrel born in saint ... | | adelaide adelaide is a coa ... | | artist an artist is a pers ... | | abdominalsurgery the three ... | | ... | +--------------------------------+ [72269 rows x 1 columns] Note: Only the head of the SFrame is printed. You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.
Bag-of-words
Both SFrames and SArrays expose functionality that can be very useful for
manipulating text data. For example, one common preprocessing task for text
data is to transform it into "bag-of-words" format: each document is
represented by a map where the words are keys and the values are the number of
occurrences. So a document containing the text "hello goodbye hello" would be
represented by a
dict type element containing the value
{"hello": 2,
"goodbye":1}. This transformation can be accomplished with the following
code.
bow = graphlab.text_analytics.count_words(sf['X1'])
We can print five of the words in the first document
bow[0].keys()[:5]
['and', 'work', 'baumconnes', 'gold', 'almost']
and find the documents that contain the word "gold":
bow.dict_has_any_keys(['gold'])
We can save this representation of the documents as another column of the original SFrame.
sf['bow'] = bow
TF-IDF
Another useful representation for text data is called TF-IDF (term frequency - inverse document frequency). This is a modification of the bag-of-words format where the counts are transformed into scores: words that are common across the document corpus are given low scores, and rare words occurring often in a document are given high scores.
where N(w, d) is the number of times word w occurs in document d. This transformation can be done to an SArray of dict type containing documents in bow-of-words format using tf_idf.
sf['tfidf'] = graphlab.text_analytics.tf_idf(sf['bow'])
BM25
The BM25 score is yet another useful representation for text data. It scores each document in a corpus according to the document's relevance to a particular query. For a query with terms , the BM25 score for document is:
where:
- is the number of times term occurs in document ,
- is the number of words in document ,
- is the average number of words per document,
- and are free parameters for Okapi BM25,
The first quantity in the sum is the inverse document frequency. For a corpus with documents, inverse document frequency for term is:
where is the number of documents in the corpus that contain term .
The transformed output is a column of type float with the BM25 score for each document. For more details on the BM25 score see.
query = ['beatles', 'john', 'paul'] bm25_scores = graphlab.text_analytics.bm25(dataset, query)
Text cleaning
We can easily remove all words do not occur at least twice in each document using SArray.dict_trim_by_values.
docs = sf['bow'].dict_trim_by_values(2)
Alternatively, we can remove all words which do not occur at least
threshold
number of times using the RareWordTrimmer.
GraphLab Create also contains a helper function called stopwords that returns a list of common words. We can use SArray.docs.dict_trim_by_keys to remove these words from the documents as a preprocessing step. NB: Currently only English words are available.
docs = docs.dict_trim_by_keys(graphlab.text_analytics.stopwords(), exclude=True)
To confirm that we have indeed removed common words, e.g. "and", "the", etc, we can examine the first document.
docs[0]
{'academy': 5, 'algebras': 2, 'connes': 3, 'differential': 2, 'early': 2, 'geometry': 2, 'including': 2, 'medal': 2, 'operator': 2, 'physics': 2, 'sciences': 5, 'theory': 2, 'work': 2}
Tokenization
For an SArray of strings, where each row is assumed to be a natural English language document, the tokenizer transforms each row into an ordered list of strings that represents the a simpler version of the Penn-Tree-Bank-style (PTB-style) tokenization of that row's document. For many text analytics tasks that require word-level granularity, simple space delimitation does not address some of the subtleties of natural language text, especially with respect to contractions, sentence-final punctuation, URL's, email addresses, phone numbers, and other quirks. The representation of a document provided by PTB-style of tokenization is essential for sequence-tagging, parsing, bag-of-words treatment, and any text analytics task that requires word-level granularity. For a description of this style of tokenization, see.
tokenized_docs = graphlab.SFrame() tokenized_docs['tokens'] = graphlab.text_analytics.tokenize(sf['X1']) tokenized_docs
Columns: tokens list Rows: 72269 Data: +-------------------------------+ | tokens | +-------------------------------+ | [alainconnes, alain, conne... | | [americannationalstandards... | | [alberteinstein, near, the... | | [austriangerman, as, germa... | | [arsenic, arsenic, is, a, ... | | [alps, the, alps, alpen, a... | | [alexiscarrel, born, in, s... | | [adelaide, adelaide, is, a... | | [artist, an, artist, is, a... | | [abdominalsurgery, the, th... | +-------------------------------+ [72269 rows x 1 columns] Note: Only the head of the SFrame is printed. You can use print_rows(num_rows=m, num_columns=n) to print more rows and columns.
Note that our tokenizer does not normalize quote and bracket-like characters as described by the linked document.
Part of Speech Extraction
It can be useful to extract particular parts of speech. Specifically, you may want to highlight unique nouns in your text, identify adjectives with the high sentiment scores, or pull out nouns to generate candidate entities. The
extract_parts_of_speech method parses the text in each element and extracts the words that are a given part of speech. For instance, to find all instances of adjectives:
parts_of_speech = graphlab.SFrame() parts_of_speech['adjectives'] = graphlab.text_analytics.extract_parts_of_speech(sf['X1'],chosen_pos=[graphlab.text_analytics.PartOfSpeech.ADJ]) parts_of_speech
Columns: adjectives dict Rows: 10 Data: +-------------------------------+ | adjectives | +-------------------------------+ | {'ADJ': {'first': 1, 'nati... | | {'ADJ': {'first': 2, 'tech... | | {'ADJ': {'standard': 2, 'm... | | {'ADJ': {'standard': 8, 'p... | | {'ADJ': {'arsenopyrite': 2... | | {'ADJ': {'main': 6, 'roman... | | {'ADJ': {'third': 2, 'cruc... | | {'ADJ': {'main': 2, 'ethni... | | {'ADJ': {'first': 1, 'whic... | | {'ADJ': {'aseptic': 1, 'ri... | +-------------------------------+ [72269 rows x 1 columns]
Note that this API requires spaCy to be installed.
Sentence Splitting
For an SArray of strings, where each row is assumed to be a natural English language document, the sentence splitter splits by sentence and outputs a list of sentences. This aids in anlysis at the sentence level. For example, you may want a sentiment score for each sentence in a document. The following command accomplishes this for you:
sentences = graphlab.SFrame() sentences['sent'] = graphlab.text_analytics.split_by_sentence(sf['X1']) sentences
Columns: sent list Rows: 10 Data: +-------------------------------+ | sent | +-------------------------------+ | [alainconnes alain connes ... | | [americannationalstandards... | | [alberteinstein near the b... | | [austriangerman as german ... | | [arsenic arsenic is a meta... | | [alps the alps alpen alpi ... | | [alexiscarrel born in sain... | | [adelaide adelaide is a co... | | [artist an artist is a per... | | [abdominalsurgery the thre... | +-------------------------------+ [72269 rows x 1 columns]
Note that this API requires spaCy to be installed. | https://turi.com/learn/userguide/text/analysis.html | CC-MAIN-2017-09 | refinedweb | 1,171 | 51.14 |
To generate Armstrong number in Java Programming, you have to ask to the user to enter the interval in which he/she want to generate Armstrong numbers between desired range as shown in the following program.
Following Java Program ask to the user to enter the interval, to print the Armstrong numbers in that interval. Since if you start from 1 then first Armstrong number will be 153. So enter the interval in which 153 is in, like enter starting number as 1, 2, 3, 4......etc. but you have to enter the ending number which is greater than 154 like 154, 155, 156.......etc. It is just a clue that first Armstrong number is 153 so to print Armstrong numbers, you must have to enter the ending number which is greater than 154. Let's look at the following Java program.
/* Java Program Example - Generate Armstrong Numbers */ import java.util.Scanner; public class JavaProgram { public static void main(String args[]) { int num1, num2, i, n, rem, temp, count=0; Scanner scan = new Scanner(System.in); /* enter the interval (two number) */ System.out.print("Enter the Interval :\n"); System.out.print("Enter Starting Number : "); num1 = scan.nextInt(); System.out.print("Enter Ending Number : "); num2 = scan.nextInt(); for(i=num1+1; i<num2; i++) { temp = i; n = 0; while(temp != 0) { rem = temp%10; n = n + rem*rem*rem; temp = temp/10; } if(i == n) { if(count == 0) { System.out.print("Armstrong Numbers Between the Given Interval are :\n"); } System.out.print(i + " "); count++; } } if(count == 0) { System.out.print("Armstrong Number not Found between the Given Interval."); } } }
When the above Java Program is compile and executed, it will produce the following output. Above Java Programming Example Output (for Armstrong numbers found):
Above Java Programming Example Output (for Armstrong numbers not found):
You may also like to learn and practice the same program in other popular programming languages:
Tools
Calculator
Quick Links | https://codescracker.com/java/program/java-program-generate-armstrong-number.htm | CC-MAIN-2019-13 | refinedweb | 321 | 57.27 |
Psetbkpt, Pdelbkpt, Pxecbkpt, Psetwapt, Pdelwapt, Pxecwapt - deal with breakpoints and watchpoints
#include <libproc.h>
int Psetbkpt(ps_prochandle_t *Pr, uintptr_t address, ulong_t *saved);
int Pdelbkpt(ps_prochandle_t *Pr, uintptr_t address, ulong_t saved);
int Pxecbkpt(ps_prochandle_t *Pr, ulong_t saved);
int Psetwapt(ps_prochandle_t *Pr, const prwatch_t *wp);
int Pdelwapt(ps_prochandle_t *Pr, const prwatch_t *wp);
int Pxecwapt(ps_prochandle_t *Pr, const prwatch_t *wp);
The Pr argument identifies a live victim process attached to the controlling process by the create and grab interfaces. For more information, see the Pcreate(3PROC) and Pgrab(3PROC) man pages.
The Psetbkpt() function sets a breakpoint in the address space of the victim process at the location specified by the address argument. The machine instruction that was at the specified address before the breakpoint was inserted, is returned in the location specified by the saved argument.
The Pdelbkpt() function replaces the breakpoint instruction in the address space of the victim process, at the location specified by the address argument by the machine instruction in the saved argument (almost always from a previous call to the Psetbkpt() function).
The Pxecbkpt() function causes the victim process to execute the saved instruction at the current stopped location, which may have stopped due to an encounter with a breakpoint trap, and to stop again before executing the next machine instruction. It replaces the breakpoint instruction at the current stopped location with the saved instruction, then single-steps the victim process, and restores the breakpoint instruction.
The Psetwapt() function sets a watched area described by the wp argument in the address space of the victim process. For more information, see the proc(5) man page.
The Pdelwapt() function deletes the watched area described by the wp argument from the address space of the victim process.
If the victim process is stopped due to a watchpoint trap in the area described by the wp argument, the Pxecwapt() function removes the watched area from the address space of the victim process, single-steps the victim process, and restores the watched area to the address space of the victim process, leaving the victim process stopped before executing the next machine instruction.
On successful completion, all of these functions return 0. On error, they return -1 and set errno to indicate the error.
On failure, these errno values may be set:
Process has been lost to control, needs the Preopen() function
Process is not stopped on a breakpoint or a watchpoint
Signal received while performing the operation
The victim process has terminated
See attributes(7) for descriptions of the following attributes:
libproc.h(3HEAD), libproc(3LIB), Pcreate(3PROC), Pgrab(3PROC), proc(5) | https://docs.oracle.com/cd/E88353_01/html/E37847/pdelbkpt-3proc.html | CC-MAIN-2019-43 | refinedweb | 431 | 53.75 |
Contents
- About Google Cloud Storage
- Pricing and support
- Getting Started
- Storage and content policy
- Use with other Google services
- Managing Data Access
- Managing Bucket Locations
- Tools and Libraries
- Troubleshooting
- Security and Data Protection Assessments
About Google Cloud Storage
- How do I sign up?
- Sign up for Google Cloud Storage by turning on the Google Cloud Storage service in the Google Developers Console.
- How soon is my account active after I turn on the Google Cloud Storage service?
- Your account can take a few minutes after you turn on the Google Cloud Storage service for it to become active.
- How do I request a feature?
- Please share your feature request with us by sending email to gs-team@google.com. We will track feature requests as they arrive.
- How do I file a bug?
- Please send the bug via email to gs-team@google.com. We will investigate issues as they arrive.
- How do I cancel my Google Cloud Storage account?
- To cancel your Google Cloud Storage account, take the following steps:
- Delete all your buckets and objects.
Warning: Deleting an object or bucket is a permanent action that can not be undone. Back up any data that you want to keep before you begin deleting your buckets and objects.
Use gsutil or Google Developers Console to quickly and easily remove objects and buckets.
- Disable the Google Storage services for your project.
In the Google Developers Console, select your project, and in the left sidebar, click APIs & AUTH. In the list of APIs, turn off Google Cloud Storage and Google Cloud Storage JSON API.
- Disable billing (optional).
You will not incur any additional Google Cloud Storage charges after you remove your Google Cloud Storage data and disable the Google Cloud Storage service but you can choose to disable billing to stop receiving statements. You will receive one last bill for any remaining changes incurred between the beginning of the billing cycle and when you cancelled.
If you have other services that are being billed to the same project, disabling billing in the Billing pane also disables billing for these services.
Note: You can choose to disable the Google Cloud Storage service without removing your Google Cloud Storage data, but you will incur storage charges for any remaining buckets or objects.
Pricing and Support
- Where can I find pricing information?
- Please read the Pricing and Terms for detailed information on pricing.
- How do you calculate bandwidth usage and storage usage?
- We calculate bandwidth usage and storage usage in gigabytes (GB), where 1 GB = 230 bytes. We calculate charges for your usage on a monthly basis. Your monthly bandwidth usage is the cumulative network bandwidth you used in the month. Your monthly storage usage is the average storage you used in the month. For an example usage calculation, see Pricing and Terms.
- How do I cancel billing?
- You can cancel billing by clicking Disable billing in the Billing & Settings page for your project. You can get to the Billing & Settings page for your project by going to the Google Developers Console and then selecting your project. If you disable billing, you also disable the Google Cloud Storage service. Make sure you want to disable the Google Cloud Storage service before you disable billing. After you disable billing, you will receive one last bill that includes costs incurred between the beginning of the billing cycle to when you cancelled.
Caution: When you disable billing, it is disabled for all services in that project. You can not disable billing for individual services or APIs. For more information, see Billing in the Google Developers Console Help. section in the Developers Console help.
- What are my support options?
- We invite our users to post their questions on Stack Overflow. Along with the active Stack Overflow community, our team will be actively monitoring your posts and answering questions with the tag google-cloud-storage.
We offer various levels of support depending on your needs. For additional support options see our Cloud Platform Support Packages.
- Does Google Cloud Storage offer a service level agreement (SLA)?
- Yes. If you provided billing information through Google Checkout you are covered under the Google Cloud Storage Service Level Agreement.
- How do I notify Google of SLA Financial Credit eligibility?
- Use the billing request form.
Getting Started
- Do I need to sign up for billing before I can use Google Cloud Storage?
- Yes, we require that you turn on billing in order to use the service.
- Do I need to activate Google Cloud Storage and turn on billing if I was added to an existing Google Cloud Storage account?
- No, please see Activate Google Cloud Storage for more information.
- I am just trying to download or access some data that is available to the public. How can I do that?
- You can simply download and install the gsutil tool and use it to download the data. You do not need to activate Google Cloud Storage or turn on billing for this purpose. You also do not need to authenticate to Google Cloud Storage to access a publicly-available object.
Storage and content policy
- How many times is my data replicated?
- Your data is replicated in multiple data centers that are geographically distributed for greater availability.
- Where is my data stored?
- You can specify if you want your data stored in the United States, European Union, or Asia by specifying a bucket location when you create a bucket. The selection of a location in Asia does not guarantee that your data at rest is kept only in that specific location. If no location selection is made, your data will be stored at rest in the United States.
- I believe some content hosted on your service is inappropriate, how do I report it?
- Certain types of content are not allowed on this service; please refer to the Terms of Services and Program Policies for details. If you believe a piece of content is in violation of our policies, report it here (select "See more products", then "Google Cloud Storage").
- How can I get a summary of daily space usage?
- You can use the gsutil du command to display the total space used by all objects for a specified bucket. For example, to get the total space used by all objects in the bucket "bucketname", use the command:
gsutil du -sh gs://bucketnameSee the du command help for more options you can use, including how to return the size of all objects underneath a prefix.
You can also set up bucket logging where the total size of a bucket is automatically reported once a day. For more information, see Access Logs & Storage Data..
Use with other Google services
- Can I use Google Cloud Storage to upload files to Google Docs?
- No, Google Cloud Storage is not currently integrated with Google Docs.
- Can I use Google Cloud Storage with my Google Apps account?
- Yes, you can use your Google Apps account with Google Cloud Storage.
- Google Storage and Google Drive — which storage API should my application use?
Google provides two different storage services: Google Cloud Storage, and Google Drive. Both services allow programmatic access to their functionality, but the goals of the APIs are quite different. The Google Drive SDK works together with the Google Drive UI and the Chrome Web Store to create an ecosystem of apps that can be installed into Google Drive. These apps enhance the user experience by allowing users to interact with their data in novel ways. For instance, a user could install a Drive app to edit images or fax PDF files, and could create and open files with those apps directly in Google Drive.
Google Cloud Storage is intended to be accessed primarily through its API and provides all the functionality necessary for developers to use it as a backing store for their own applications. For example, a developer could store and host media and other static assets for a web game in Google Cloud Storage. Google Cloud Storage can also be used for online archives, backup replacement, and so on.
This illustrates the primary difference between the two APIs: Cloud Storage enables developers to store their application data in the Google cloud (and they’re responsible for the storage their app consumes), whereas in Drive, users allow apps to interact with the user’s private storage and content.
For an overview of Google storage options, including a video explaining the differences between the options, see Storing Your Data.
Managing Data Access
- How do I change the owner of an object?
- You cannot change the owner of an object by modifying ACLs. However, you can change the owner of an object by having the new owner overwrite the object with a new object. To do this, the new owner must have
FULL_CONTROLpermission on the object you want to modify and the new owner must have
WRITEor
FULL_CONTROLpermission on the bucket in which the object is stored.
- How do I change the owner of a bucket?
- You cannot do this. A bucket is always owned by the project owners group of the Google APIs Console project it was created in.
- I want to let someone download an object. How do I do that?
- You can share an object with a user or group by granting
READpermission on the object you want to share. You can specify a user or a group by email address (for example, jane@gmail.com or gs-discussion@googlegroups.com) or by the Google Storage ID that's associated with the user or group.
- What is a Google Cloud Storage ID?
- A Google Cloud Storage ID is a string of 64 hexadecimal characters that uniquely identifies a user or a Google group. The Google Cloud Storage system uses Google Cloud Storage IDs to determine the scope of a given permission.
- How can I determine the Google Cloud Storage ID of a user or group?
- If the user has a Google Cloud Storage account you can ask them for their Google Cloud Storage ID. Any user who has a Google Cloud Storage account can look up their Google Cloud Storage ID by doing the following:
- Go to the Google Developers Console.
- Select a project.
- In the left sidebar, click Cloud Storage > Storage settings.
If you are not certain whether the user has a Google Cloud Storage account, or you want to find the Google Cloud Storage ID for a group, you can do this:
- Upload a new object or create a new bucket with default (project-private) permissions.
- Grant the user or group
READpermission to the object or bucket by using the user's or group's email address.
- Retrieve the ACLs for the object or bucket. The user's or group's Google Cloud Storage ID will be listed as the scope for the
READpermission.
You can also retrieve the Google Cloud Storage IDs of a project Team, a project Editors group, or a project Owners group by following the same steps for retrieving your ID shown above. For more information, see Finding Google Cloud Storage IDs.
- What happens if a tool or library uses another storage provider's ACL syntax?
When using the XML API for interoperable access with other storage services, such as Amazon S3, the signature identifier determines the ACL syntax. For example, if the tool or library you are using makes a request to Google Cloud Storage to retrieve ACLs (for example, a GET Object or GET Bucket request), and the request uses another storage provider's signature identifier, then Google Cloud Storage returns an XML document that uses the corresponding storage provider's ACL syntax. If the tool or library you are using to make a request to Google Cloud Storage to apply ACLs (for example, a PUT Object or PUT Bucket request), and the request uses another storage provider's signature identifier, then Google Cloud Storage expects to receive an XML document that uses the corresponding storage provider's ACL syntax.
For more information about using the XML API for interoperable access with Amazon S3, see Migrating from Amazon S3 to Google Cloud Storage.Amazon S3 is a trademark of Amazon.com, Inc. or its affiliates in the United States and/or other countries.
- Why can't I apply
WRITEpermission to an object?
- Object permissions control who can download an object and who can read or write an object's ACLs. All other object operations, such as uploading and deleting, are controlled through bucket ACLs. This gives bucket owners control over who can upload objects to their buckets.
- Can I let someone read the ACLs on an object without letting them download the object?
- No. You must grant a user
FULL_CONTROLpermission to read an ACL on an object or bucket.
- Can I grant
WRITEpermission on a bucket without granting
READpermission?
- No. Google Cloud Storage ACLs are concentric, which means that
WRITEpermission also grants
READpermission.
Managing Bucket Locations
- Can I specify bucket locations in places other than Asia, the European Union, or the US?
- No. Currently, you can only specify buckets in these locations.
- Can I move buckets from one location to another?
- No. When you create a bucket in a specific location, it is not possible to move it to another location.
- What is the default bucket location if I do not specify a location constraint?
- The default bucket location is in the US. If you do not specify a location constraint, your buckets will be stored on servers in the US.
Tools and Libraries
- Are there any tools available for Google Cloud Storage?
- You can use the browser-based Google Developers Console to perform basic operations on buckets and objects. You can also use the command-line tool gsutil to perform basic and advanced data management tasks on Google Cloud Storage. You can find several other tools by searching the Internet.
- Are there any libraries for Google Cloud Storage?
- The Boto library works with Google Cloud Storage. You can find several other libraries for Java, Ruby, and PHP by searching the Internet.
- I'm developing a library or tool for Google Cloud Storage and I want to sell it on the Internet. Is this okay?
- Yes!
Troubleshooting
- I tried to create a bucket and got the error
GSResponseError: status=403, code=AccountProblem, reason=Forbidden. What should I do?
- This error generally indicates that you have not yet turned on billing in the Google Developers Console or do not have access to create a bucket. Try:
- Turning on billing
- Checking that you are either in the owners or writers group for the project.
If billing is turned on and you have permissions to create a bucket, but you continue to receive this error message, please send your project id and a description of your problem to gs-team@google.com.
- I tried to create the buckets
gs://catsand
gs://dogsbut received the following error:
Failure: GSCreateError: 409 Conflict
.
BucketNameUnavailable
The requested bucket name is not available. The bucket namespace is shared by all users of the system. Please select a different name and try again.
- The bucket name you tried to use (e.g.
gs://catsand
gs://dogs) is already taken. Google Cloud Storage has a flat namespace so you may not name a bucket with the same name as an existing bucket. Choose a name that is not being used.
- I tried to list my bucket with gsutil but got the error:
GSResponseError: status=403, code=AccessDenied, reason=Forbidden. What should I do?
- Check that you are using the correct project ID. If you are not specifying the project ID on the command line (like
gsutil ls -p <PROJECT_ID>), check the default project ID for your account.
- Check that the credentials you configured in your .boto file are correct.
- Assuming you are using the correct project ID and credentials, are your requests being routed through a proxy, using HTTP (instead of HTTPS)? If so, check whether your proxy is configured to remove the
Authorizationheader from such requests. If so, make sure you are using HTTPS instead of HTTP for your requests. Your boto configuration file should not specify:
is_secure = Falsein the [Boto] section.
- I'm connecting through a proxy server, what do I need to do?
Requests to Google Cloud Storage need to access accounts.google.com for OAuth2 token exchanges, and *.googleapis.com for storage requests. If you are accessing Google Cloud Storage through a proxy server, you must allow access to these domains. If your proxy server or security policy doesn't support whitelisting by domain and instead requires whitelisting by IP network block, we strongly recommend that you configure your proxy server for all Google IP address ranges. You can find the address ranges, for example, by querying WHOIS data at ARIN. As a best practice, you should periodically review your proxy settings to ensure they match Google's IP addresses.
We do not recommend configuring your proxy with individual IP addresses you obtain from a one-time lookup of accounts.google.com and storage.googleapis.com. Because Google services are exposed via DNS names that map to a large number of IP addresses that can change over time, configuring your proxy based on a one-time lookup may lead to failures to connect to Google Cloud Storage.
If you requests are being routed through a proxy server, you may need to check with your network administrator to ensure that the
Authorizationheader containing your credentials is not stripped out by the proxy. Without the
Authorizationheader, you will receive a
MissingSecurityHeadererror and your request will be rejected.
- I tried to use the gsutil stat command to display object status for a subdirectory and got an error. Why?
Google://some-bucket/some-object/, then gsutil will look up information about the object "some-object/" (with a trailing slash) inside bucket "some-bucket", as opposed to operating on objects nested under gs://some-bucket/some-object. Unless you actually have an object with that name, the operation will fail.
- I created a bucket, but don't remember which project I created it in. How can I find it?
For most common Google Cloud Storage operations like listing objects, creating and composing objects, and common object and bucket configuration, you do not need to specify a project. In general, only need to specify a project identifier when creating a bucket or listing buckets in a project. For more information, see When to Specify a Project ID.
To find what project contains a specific bucket:
- If you are searching over a moderate number of projects and buckets, use the Google Developers Console, select each project, and view the buckets it contains.
- Otherwise, you can script
gsutil ls -p <PROJECT_ID>by passing in a list of project IDs and parsing the output. You can get a list of project IDs from Google Developers Console.
Security and Data Protection Assessments
- What assessments are performed on security and data protection?
- Google is committed to conducting independent 3rd party assessments of security and data protection practices. Building on the SSAE 16 audit and the ISO 27001 certification for Google Apps, a new SSAE 16 / ISAE 3402 SOC 2 Type II audit was successfully completed. For more information, see Google Apps, Vault and Cloud Platform components complete SSAE 16 audit | https://cloud.google.com/storage/docs/faq | CC-MAIN-2015-35 | refinedweb | 3,202 | 63.8 |
Data structure storing a sparse 3-tensor C(i,j,k) in a a compressed format. More...
#include <Stokhos_Sparse3Tensor.hpp>
Data structure storing a sparse 3-tensor C(i,j,k) in a a compressed format.
To do: Remove old data structure and accessor methods. Also add sorting and searching to add_term() method so adding entries is not so delicate.
Add new term for given (i,j,k)
IMPORTANT: The current implementation of this method assumes entries are added in increasing order, and does not do a search if duplicate entries are added!
Currently it fills both data structures for storing coefficients, so all accessor methods should work.
Add new term for given (i,j,k) and sum in if already there.
The current implementation does search over all entries already added, so it should work as entries are added in any order. However the search is slow and certainly could be improved upon. (Should investigate a sorted data structure).
Currently it only fills the new data structure, so num_values() and value() will not work. | http://trilinos.sandia.gov/packages/docs/r10.6/packages/stokhos/doc/html/classStokhos_1_1Sparse3Tensor.html | CC-MAIN-2014-35 | refinedweb | 175 | 65.01 |
The ASP.NET MVC framework is not a substitute for the ASP.NET web forms pattern.It just provide an alter choice to the developer while designing and developing a web application.
The MVC framework resides inside the system.web.mvc namespace. You already know system.web is used for asp.net web application. MVC namespace is the part of this namespace.
MVC framework consists of the following components.
Now we will discuss each in detail with an example.
1.) Model in MVC Framework :-
Example :-
The MVC framework resides inside the system.web.mvc namespace. You already know system.web is used for asp.net web application. MVC namespace is the part of this namespace.
MVC framework consists of the following components.
- Model
- View
- Controller
1.) Model in MVC Framework :-
-.
Suppose,we want to calculate the area of the rectangle.then the computational part will be performed in the model layer.
2.) View in MVC Framework :-
The view provides the user interface (UI) for the model.You already know ,the user interacts with an application through view (GUI) .
There are some functions of view in an asp.net MVC application.
-.
3.) Controller in MVC Framework :-
Controller act as a mediator between view and model. When the user interacts with the view and tries to update the model,the controller calls (invokes) methods to update the model.
There are some functionality of controller in MVC Framework.
- Control the data transmission between model and view layer:-The controller control the data flow and transformation between the model and the view layer in the application.
- Mapping the user action into model updates:- The controller is used as immedi.
Working of ASP.NET MVC Application :-
There are some steps of working of any MVC Application as given below:-
-. | https://www.msdotnet.co.in/2015/02/aspnet-mvc-framework-real-concepts.html | CC-MAIN-2022-05 | refinedweb | 294 | 62.44 |
Red Hat Bugzilla – Bug 751421
Import child Resource: if there are two types with the same names (e.g. the as4 and as5 JBoss AS Server types), one of them is not included in the select-type menu
Last modified: 2014-01-02 15:33:15 EST
This can make it impossible for the user to manually add/import e.g. an EAP 5.x instance into inventory.
Note, this is an issue in both entry points to the Import Child Resource wizard:
1) the Import item on the context menu when you right-click a platform Resource in the Resource tree
and
2) the Import button at the bottom of the Inventory > Child Resources subtab's content pane for a platform Resource
[master d3802b6] (;a=commitdiff;h=d3802b6) fixes this for both Manual Import type selection menus, as well as the Create-New-Child type selection menu on the Resource tree.
8982cfc cherry-picks the fix into the release_jon3.x branch.
Ian, could you please provide steps to verify this bug...
Verified on master build#836 (Version: 4.3.0-SNAPSHOT Build Number: 3300dff)
Verified that the selection menu displays both the JBossAs server types as below:
JBossAS Server (JBossAS Plugin)
JBossAS Server (JBossAS5 Plugin)
Verified in the Import item on the right click context menu of platform Resource
in the Resource tree and in the content pane of the Import button at the bottom of the Inventory > Child Resources subtab for a platform Resource.
changing status of VERIFIED BZs for JON 2.4.2 and JON 3.0 to CLOSED/CURRENTRELEASE
Based on Mazz's comment in, parts of this fix may have gotten lost in the 3.x branch. Reopening to investigate...
This has been fixed for a while and should already be in any 3.2 build.
as server types are visible in drop down menu -> please see screenshot attached
actual import doesn't work - bug#999494
Created attachment 788838 [details]
import AS Server Type | https://bugzilla.redhat.com/show_bug.cgi?id=751421 | CC-MAIN-2017-13 | refinedweb | 329 | 59.74 |
>
Over time added visual studio 2010, 2012 and 2013 to my chooses. I want to solely use 2013. I uninstalled 2010 a while back I have been manually just opening 2013 but know with 8.1 support I want to be able to click on the script to open it in 2013 even though I have that selected it always tries to open 2010 which stalls out the editor because its not installed. How do I remove 2010 and 2012 from the list?
Answer by zitodiscipulo
·
Jan 03, 2016 at 09:12 AM
You can use this script to reset your External Editors drop down list : //Script name: EditorResetPrefs.cs using UnityEditor; using UnityEngine;
public class EditorResetPrefs : MonoBehaviour { [MenuItem ("Edit/Reset Preferences")] static void ResetPrefs() { if(EditorUtility.DisplayDialog("Reset editor preferences?", "Reset all editor preferences? This cannot be undone.", "Yes", "No")) { EditorPrefs.DeleteAll(); } } }
//You can create a folder named Editor inside Assets folder
//Place this script inside.
//This will generate on Edit menu an option called Reset Preferences.
//Click on Reset preferences and say "yes". //This will clean all preferences and also clean External script list.
//I hope this can help you on this.
Read and Write to text file Online
4
Answers
Editor doesn't remember external script editor?
1
Answer
Error in Console, for Editor Settings, don't understand how to fix
1
Answer
how to sync microsft c# express ide with unity 3d
1
Answer
Unity editor PreferenceItem creation at runtime possible?
1
Answer | https://answers.unity.com/questions/633474/how-to-remove-options-from-the-external-tools-exte.html | CC-MAIN-2019-30 | refinedweb | 247 | 58.08 |
Hi guys!
i need some help with my program and i cant determine what to do next...i'm making a program that will output the longest word in a sentence..
here is my code...
import java.util.Scanner; class LongestWord4 { static Scanner console = new Scanner(System.in); public static void main(String args[]) { String word, longestWord = ""; System.out.print("Enter sentence: "); Scanner console = new Scanner(System.in); String sentense = console.nextLine(); Scanner console2 = new Scanner(sentense); while ( console2.hasNext() ) { word=console2.next(); if (word.length() > longestWord.length()) longestWord = word; } System.out.print("The longest word was: " + longestWord); } }
now my problem is whenever I try to input a sentence with a word with similar length, only the first longest word appears. Well supposedly all distinct words with similar number of characters should appear on the output.
second problem..the output must also disregard the special cases like .,/?:!, etc that is link to the longest word... e.g. get out of here!
the exclamation mark must be disregarded when outputting the word here...
so someone please help me how to figure out..cause i cant think of how to handle this problems..
THANKS! | https://www.daniweb.com/programming/software-development/threads/363994/longest-word-in-a-sentence | CC-MAIN-2022-27 | refinedweb | 192 | 62.04 |
Beginning tvOS Development with TVML Tutorial
Last Wednesday Apple announced the new Apple-TV – along with what we’ve all been dreaming of, the ability to write our own apps for it!
I and the rest of the Tutorial Team have been digging into the tvOS SDK to prepare some great tvOS tutorials for you. To get you started, Chris Wagner wrote a post giving a broad overview of tvOS, and I’ve been working on this tutorial, designed to be your first steps in tvOS development.
In this tutorial, you’ll make your first tvOS app using TVML – Apple’s Television Markup Language. Believe it or not, you’ll use JavaScript to manage your app’s logic, and create TVML templates to present your UI.
By the end of the tutorial, you should have a basic grasp of managing tvOS apps using TVML and TVJS. Let’s get started!
Choose Your Adventure
Apple has provided developers two ways to develop tvOS apps:
- TVML Apps: The first uses an entirely new process utilizing TVML, TVJS and TVMLKit. I’ll explain what these abbreviations mean and how this works in a moment.
- Custom Apps: The second uses familiar iOS frameworks and concepts you know and love like Storyboards, UIKit, and Auto Layout.
Both ways are a completely valid way to make apps; it depends what you’re trying to do.
In this tutorial, your goal is to create this simple tvOS that streams RWDevCon conference videos:
Although you could create this app using either method, it is much easier to do so as a TVML app, so that is what you will be doing in this tutorial. To learn why, let me tell you a little bit more about how this works! :]
What is TVML?.
This is exactly the situation we have in this tutorial. We already have a RWDevCon website that hosts the conference videos, so it would be quite easy to host some TVML templates there. We don’t have crazy requirements for the UI, so we can easily make use of some of Apple’s pre-made templates.
In short:
- Make a TVML App if you primarily provide menus of content, especially if you already have a server set up.
- Make a Custom App if you’re aiming to provide a fully immersive experience in your app, where your users will be spending more time interacting with your interface than passively watching or listening to content.
Now that you have a high-level understanding of how TVML works and why you’re using it in this tutorial, the best way to understand it further is to try it out yourself. Let’s start coding!
Getting Started
First make sure you have Xcode 7.1 or later installed and open on your machine.
Then go to File\New\Project and select the tvOS\Application\Single View Application template, and click Next:
For the Product Name enter RWDevCon, for the Language select Swift, make sure both checkboxes are unchecked, and click Next:
Choose a directory to save your project and click Save. Xcode will create a empty project for you with a Storyboard (which you would use if you were creating a tvOS Custom App).
However, you won’t need that because you are are making a TVMP app, which uses TVML files to display the UI rather than a Storyboard. So delete Main.storyboard and ViewController.swift from your project and select Move to Trash.
Next, head into the Info.plist and remove the
Main storyboard file base name key. Finally add a new value
App Transport Security Settings(case sensitive), and as its child, add
Allow Arbitrary Loads, and set that value to
YES.
The life cycle of the tvOS app starts with the app delegate. Here, you will set up the
TVApplicationController to pass control and the application context to the main JavaScript files.
Open AppDelegate.swift and do the following:
- Delete all the methods
- Import
TVMLKit
- Have your app delegate conform to
TVApplicationControllerDelegate
At this point your file should look like the following:
import UIKit import TVMLKit @UIApplicationMain class AppDelegate: UIResponder, UIApplicationDelegate, TVApplicationControllerDelegate { var window: UIWindow? }
Next, add the following variables to the class:
var appController: TVApplicationController? static let TVBaseURL = "" static let TVBootURL = "\(AppDelegate.TVBaseURL)js/application.js"
TVApplicationController is a class in
TVMLKit that handles communicating with your server.
TVBaseURL and
TVBootURL contains the paths for your server and JavaScript code, which you will be running on your localhost later.
Next add the following method to the class:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey : Any]? = nil) -> Bool { window = UIWindow(frame: UIScreen.main.bounds) // 1 let appControllerContext = TVApplicationControllerContext() // 2 guard let javaScriptURL = URL(string: AppDelegate.TVBootURL) else { fatalError("unable to create NSURL") } appControllerContext.javaScriptApplicationURL = javaScriptURL appControllerContext.launchOptions["BASEURL"] = AppDelegate.TVBaseURL // 3 appController = TVApplicationController(context: appControllerContext, window: window, delegate: self) return true }
This code is relatively straight forward:
- Here you create a
TVApplicationControllerContext, which you will use to initialize your
TVApplicationController. Think of this as a simple object you fill with information such as the URL of your server.
- You fill the context with two bits of information: the path to your main Javascript file, and the root directory of your server.
- This starts up the
TVApplicationControllerwith the context you configured. At this point, Apple’s code takes over – it will pull down your root Javascript file and begin executing it.
And with that, it’s time to take a break from Xcode. Next, you’re going to write JavaScript!
The JavaScript
In the client-server tvOS application, your JavaScript code is typically contained in the server your app connects to. For the purposes of this tutorial, you’ll set up a simple server on your Mac.
Note: From now on, we’ll be working with JavaScript code. Personally, I stay away from using Xcode because of the indentation behaviours associated with working on blank Xcode files. Use an IDE of your choice. If you need a recommendation, I suggest Sublime Text 2 which you can download from here.
Client Code
For the sake of convenience, let’s put the JavaScript code on your Desktop. In your Desktop directory, create a new folder and name it client. Within the client directory, create a new folder and name it js. This folder will serve as the container for your JavaScript files.
With the IDE of your choice, create a new JavaScript file, name it application.js and save it to your js directory. Add the following to application.js
App.onLaunch = function(options) { // 1 var alert = createAlert("Hello World", ""); //leaving 2nd parameter with an empty string navigationDocument.presentModal(alert); } // 2 var createAlert = function(title, description) { var alertString = `<?xml version="1.0" encoding="UTF-8" ?> <document> <alertTemplate> <title>${title}</title> <description>${description}</description> </alertTemplate> </document>` var parser = new DOMParser(); var alertDoc = parser.parseFromString(alertString, "application/xml"); return alertDoc }
App.onLaunch is the method that handles the entry point of the JavaScript. The
TVApplicationController that was initialized in AppDelegate.swift will pass on its
TVApplicationControllerContext here. Later, you’ll make use of context’s contents, but for now, you’re just going to create a simple alert to display on screen.
- Using
createAlertdefined below, we get a TVML document for us to present. The
navigationDocumentis analogous to a
UINavigationControllerin iOS; It serves as the stack that can push, pop, and present TVML documents.
createAlertis a function that returns a TVML document. You can consider it analogous to a
UIAlertControllerin iOS.
At the time of writing, Apple has 18 templates provided for us to use in our TVML apps – you can see the full list and specification in the Apple TV Markup Language Reference.
The alertTemplate used here is one of the 18, and its main purpose is to display important information, such as a message telling the user to perform an action before continuing. Finally, you’re almost ready for your first build and run!
Setting up the Server
Open the Terminal app and enter the following:
cd ~/Desktop/client python -m SimpleHTTPServer 9001
This starts up a simple Python-based web server in your client directory. Now you’re cleared for takeoff!
Go back to your Xcode project and build and run. You should be greeted with your first tvOS TVML app!
I don’t know about you, but when I first got this working I felt like this guy:
Before moving forward, I’d like to spend time to appreciate the work you’ve done so far.
- You created a
TVApplicationController. This manages the JavaScript code.
- You created and attached a
TVApplicationControllerContextto the
TVApplicationController. The context had
launchOptionsthat was populated with our
BASEURLwhich contained the
URLto the server. This context is also where the app finds out which server to connect to.
- Control is passed to the JavaScript code.
App.onLaunchkicks in and you returned a TVML alert template to present “Hello World” to the screen.
Note that even though you are running on your local web server, you could have put this on a live web server instead – perhaps hooked up to a database. Cool, eh?
Crafting the TVML
As I’ve pointed out before,
createAlert is a function that returns a TVML document. There are many more properties we can manipulate in a TVML document, and as an experiment, you’ll add a button to the current alertTemplate. Head back to your JavaScript code, and take a look at your current implementation of
createAlert. Add a button to the template:
var alertString = `<?xml version="1.0" encoding="UTF-8" ?> <document> <alertTemplate> <title>${title}</title> <description>${description}</description> <button> <text>OK</text> </button> </alertTemplate> </document>`
Take a moment to appreciate the intricacies:
- A TVML document starts off by enclosing its contents with
document/
- Next, you define the template. For the purposes of our
createAlertfunction, we use the alertTemplate.
- Within the template, you decorate it further with a button, a title, and a description, following the Apple TV Markup Language Reference.
Save your file, and build and run. You should see a button associated with your alert view. Voila, TVML made easy!
Note: The amount of elements you can put within a template vary depending on the specific template. For instance, a loadingTemplate does not allow any buttons. Furthermore, you can customize the font, color, and several other attributes of various items, but that is beyond the scope of this tutorial. A full list of each template’s capabilities can be found in the Apple TV Markup Language Reference.
Fleshing out the JavaScript Client
So far, you’ve got something going, and you’re well on our way to our goal. In this section, you’ll spend time abstracting the logic into different classes for better reusability.
Create a new JavaScript file in your client\js folder named Presenter.js. In this file, you’ll declare the class
Presenter that will handle the navigation stack. This class will be in charge of popping and pushing documents, and do event handling. Add the following to Presenter.js:
var Presenter = { // 1 makeDocument: function(resource) { if (!Presenter.parser) { Presenter.parser = new DOMParser(); } var doc = Presenter.parser.parseFromString(resource, "application/xml"); return doc; }, // 2 modalDialogPresenter: function(xml) { navigationDocument.presentModal(xml); }, // 3 pushDocument: function(xml) { navigationDocument.pushDocument(xml); }, }
Let’s review this section by section:
- Remember that
DOMParseris the class that can convert a TVML string into an object-oriented representation; you used this earlier in
createAlert. In
DOMParseryou only want to create a
DOMParseronce and reuse it multiple times, so you only create it if you haven’t already. You then add the same lines you added earlier to parse a TVML string and return the document.
- The
modalDialogPresentermethod takes a TVML document and presents it modally on screen
- The
pushDocumentmethod pushes a TVML document onto the navigation stack.
Later in the tutorial, you’ll have the
Presenter class manage cell selection as well. For now, let’s refactor the current JavaScript code to take
Presenter into account. Replace the current implementation of
App.onLaunch with the following:
App.onLaunch = function(options) { // 1 var javascriptFiles = [ `${options.BASEURL}js/Presenter.js` ]; // 2 evaluateScripts(javascriptFiles, function(success) { if(success) { var alert = createAlert("Hello World!", ""); Presenter.modalDialogPresenter(alert); } else { // 3 Handle the error CHALLENGE!//inside else statement of evaluateScripts. } }); }
The code is relatively straightforward:
- Create a new array of JavaScript files. Recall earlier we passed in a
BASEURLin the
launchOptionsproperty of the
TVApplicationControllerContext. Now we will use it to create a path to the Presenter.js file.
evaluateScriptswill load the JavaScript files
- Here, you should handle the error. More on this in a second.
First, build and run to make sure that your code still works – now refactored to use your new
Presenter class:
Then see if you can solve the challenge indicated by the comment in section 3. If for some reason
evaluateScripts fails – perhaps because you mistyped the path to the JavaScript file(s) – you want to display an alert message. Hint: you cannot use the
Presenter class to do the presenting, since you’ve failed to load it.
You should be able to do this based on what you’ve learned so far. If you get stuck, check the solution below!
Building the Catalog Template
The catalogTemplate is another one of the 18 templates that are available for developers to use. The purpose of the template is to display information about groups of like products, which is perfect for showcasing your favorite RWDevCon videos! The catalogTemplate has many elements of interest:
Compound and Simple Elements
The
banner element is used to display information along the top of the template app page. It itself is a Compound Element, meaning it is composed of several Simple Elements.
For instance, the obvious use case for the banner is to add a
title element, but it can also have a
background element. For the purposes of our tutorial, we’ll keep the customizations as little as possible. At the end of the tutorial, there will be a link for further reading regarding other elements.
Let’s try this out. Navigate to your client directory, and create 2 new folders as siblings to the js folder, and name them images and templates respectively. Your client folder should now look like this:
You’ll need images to populate the cells in our template. I’ve prepared the images for you: download them, unzip the file, and move the images to the images folder you’ve just created.
Now, you’re going to display the images on screen! Create a new JavaScript file, name it RWDevConTemplate.xml.js, and save it in the templates folder.
Add the following to RWDevConTemplate.xml.js:
var Template = function() { return `<?xml version="1.0" encoding="UTF-8" ?> <document> <catalogTemplate> <banner> <title>RWDevConHighlights</title> </banner> </catalogTemplate> </document>` }
For now, we’ll attempt to display the banner of the template. Before we can use this code, since this isn’t currently exposed to the other JavaScript files, we need a way to let the other files know of its existence. A great time to create our last JavaScript file: ResourceLoader.js!
ResourceLoader
Create a new JavaScript file, name it ResourceLoader.js, and save it in the js folder, along with your application.js and Presenter.js files. Add the following to the file:
function ResourceLoader(baseurl) { this.BASEURL = baseurl; } ResourceLoader.prototype.loadResource = function(resource, callback) { var self = this; evaluateScripts([resource], function(success) { if(success) { var resource = Template.call(self); callback.call(self, resource); } else { var title = "Resource Loader Error", description = `Error loading resource '${resource}'. \n\n Try again later.`, alert = createAlert(title, description); navigationDocument.presentModal(alert); } }); }
Don’t worry too much about how this works; just know you can use this to load other template files.
Try it out by replacing your “Hello World” alert with our newly created
RWDevConTemplate as the main screen. Open application.js and make the following changes to the file:
// 1 var resourceLoader; App.onLaunch = function(options) { // 2 var javascriptFiles = [ `${options.BASEURL}js/ResourceLoader.js`, `${options.BASEURL}js/Presenter.js` ]; evaluateScripts(javascriptFiles, function(success) { if(success) { // 3 resourceLoader = new ResourceLoader(options.BASEURL); resourceLoader.loadResource(`${options.BASEURL}templates/RWDevConTemplate.xml.js`, function(resource) { var doc = Presenter.makeDocument(resource); Presenter.pushDocument(doc); }); } else { var errorDoc = createAlert("Evaluate Scripts Error", "Error attempting to evaluate external JavaScript files."); navigationDocument.presentModal(errorDoc); } }); } // Leave createAlert alone
You’ve made 3 changes here:
- Declared a
resourceLoadervariable.
- Added ResourceLoader.js to the list of files we want to expose.
- Used the
resourceLoaderto load the TVML template, and used the
Presenterto present it on screen.
Build and run. You should be greeted with the following screen:
Congratulations, you are now able to load TVML from a file, rather than hard-coding it into your Javascript! Cue the return of my friend:
Craft Some More TVML
Believe it or not, but you’re almost done. One of the most beautiful things about TVML tvOS apps is that it’s very easy to add UI elements. What you’re about to add to your RWDevConTemplate may seem a lot, but it’s really a fraction of what you would have to do using
UIKit frameworks.
Modify the RWDevConTemplate.xml.js file with the following:
var Template = function() { return `<?xml version="1.0" encoding="UTF-8" ?> <document> <catalogTemplate> <banner> <title>RWDevConHighlights</title> </banner> //add stuff here //1. <list> <section> //2. <listItemLockup> <title>Inspiration Videos</title> <decorationLabel>13</decorationLabel> </listItemLockup> </section> </list> </catalogTemplate> </document>` }
- You’ve defined the list area, which encompasses the rest of the screen’s contents
- The
listItemLockuprepresents a section cell. Each cell is defined by a
listItemLockuptag. You’ve declared the title to be “Inspiration Videos”, and added a number next to it, to indicate the number of items you’re going to display for this section.
Build and run. You should see the following screen on the simulator:
Not bad for just a little markup!
Completing the Template
Finally, we’re ready to create our cells that will represent each video. Add the following to RWDevConTemplate.xml.js:
//This file outlines the catalogTemplate. var Template = function() { return `<?xml version="1.0" encoding="UTF-8" ?> <document> <catalogTemplate> <banner> <title>RWDevConHighlights</title> </banner> <list> <section> <listItemLockup> <title>Inspiration Videos</title> <decorationLabel>13</decorationLabel> //1. add from here <relatedContent> <grid> <section> //2 <lockup videoURL=""> <img src="${this.BASEURL}images/ray.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/ryan.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/matthijs.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/vicki.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/alexis.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/marin.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/chris.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/cesare.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/ellen.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/jake.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/kim.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/tammy.png" width="500" height="308" /> </lockup> <lockup videoURL=""> <img src="${this.BASEURL}images/saul.png" width="500" height="308" /> </lockup> </section> </grid> </relatedContent> </listItemLockup> </section> </list> </catalogTemplate> </document>` }
- You’ve added the
relatedContenttag. This refers to the following area:
- Each
lockuptag represents a cell in the
gridWe’ve included a
videoURLproperty for each
lockup. This will be necessary to stream the videos from the RWDevCon website.
Build and run. You’ve brought your app to life!
Now that we’ve got many different cells to play around with, let’s bring out the remote controller in the simulator (if you haven’t already). With the Simulator window active, click Hardware\Show Apple TV Remote. You can move around the cells by simply holding the option key and moving your cursor on the remote window.
Playing Video
So far, we’ve got the page populated, and it looks great. Once again, think about the many things you would’ve done to get this layout to work with iOS frameworks. Apple really did a good job abstracting all the details by providing us with these fantastic templates to work with.
Let’s move on to implement the remaining two features for this app: cell selection, and media playback.
Selection Events
You may have noticed already, but pressing the enter key or clicking the Apple TV Remote gives the pressed down animation, but nothing else happens. Now you’re going to implement the necessary code to implement cell selection.
You’re going to have
Presenter handle this. Add the following method to the
Presenter class:
load: function(event) { //1 var self = this, ele = event.target, videoURL = ele.getAttribute("videoURL") if(videoURL) { //2 var player = new Player(); var playlist = new Playlist(); var mediaItem = new MediaItem("video", videoURL); player.playlist = playlist; player.playlist.push(mediaItem); player.present(); } },
- The
loadmethod is responsible for cell selection. It is analogous to an
@IBAction, where the
eventargument is similar to the
senderargument. Each
eventhas a
target. For our purposes, the
targetrefers to each
lockupelement. Remember, each
lockupelement represents our cells that display the video thumbnail, and they all have a
videoURLproperty.
- Displaying a media player is simple. The class
Playerof the TVJS framework provides all the media playback functionality. All you need is to add a
playlist, and a
mediaIteminto the playlist. Finally, the
player.present()will put the video on screen
Now that you’ve got the implemented the logic to respond to selection events, it’s time to actually hook it up to each cell! For the last time, head back to the application.js file, and add the following line in the
App.onLaunch method:
App.onLaunch = function(options) { //... //inside resourceLoader.loadResource... var doc = Presenter.makeDocument(resource); doc.addEventListener("select", Presenter.load.bind(Presenter)); //add this line Presenter.pushDocument(doc); //... }
The
addEventListener method is analogous to hooking a button to an
@IBAction. Build and run. Choose a video to play. You should be greeted by the media player:
You can download the completed tutorial project here: client and RWDevCon
Where to Go From Here?
You’ve covered a lot of ground today. You’ve learned the basic architecture of a tvOS client-server app. You’ve learned how to manage TVML, use TVJS, and use TVMLKit to connect to a server. For some of you, this is the first time you’ve handled XML and JavaScript files. You have a lot to be proud of!
If you enjoyed this tutorial, you should check out our book the tvOS Apprentice. With 28 chapters and 538 pages, the book teaches you everything you need to know to develop great apps for the Apple TV – whether you’re a seasoned iOS pro, or a web developer looking to leverage your skills to a new platform.
Are you excited about the future of tvOS? Please join us in the forum discussion below! | https://www.raywenderlich.com/114886/beginning-tvos-development-with-tvml-tutorial | CC-MAIN-2018-05 | refinedweb | 3,837 | 57.77 |
I would like to assign aliases to tabs something like view.setAlias()I that way we just enable the option (temporarily) with the api then disabled it when we don't need numbered tabs.(1) filename.css, (2) filename.html, (3) filename.php
Let me know what you guys think
i think the ability to add comments or marks on tabs can be very useful. so i like your proposal to support alias for tab
Another vote for this. Here is the simplest example I could think of - this marks read-only files on the tab:
class ReadOnlyTracker(sublimeplugin.Plugin):
def onLoad(self, view):
if not os.access(view.fileName(), os.W_OK):
view.setName(os.path.basename(view.fileName()) + ' [R]')
The problem here is that it marks the buffer as dirty and changes the filename. I tried to temporarily do setScratch(True) but the end result was same. So basically what is needed is an API that can change the label of a tab without doing anything else such as marking the file changed or modifying the filename. As a bonus it would be nice (but low priority) if we could add icons/images to tabs
Or if your doing your own plugins you can append the current working mode on the tabfilename.php [selection_mode], filename.php [insert_mode]
there's many many uses for it...
And from the coding side of it, maybe something like this,
view.setAlias(str, start=0])
str:
start (optional) -- 0 by default:
examples:
view.setAlias("[R]") == [R]yahooStyle.css
view.setAlias("[R]", 0) == [R]yahooStyle.css
view.setAlias("[R]", 1) == b[R]oo.css
view.setAlias("[R]", 5) == yahoo[R]Style.css
view.setAlias("[R]", 6) == google[R]Style.css
view.setAlias("[R]", -1) == site.css[R]
view.setAlias("[R]", -5) == site[R].css
And taking from example above:
class ReadOnlyTracker(sublimeplugin.Plugin):
def onLoad(self, view):
if not os.access(view.fileName(), os.W_OK):
view.setAlias('[R]', -1)
Jon any input on this?
I’m not trying to necro an old thread, but I do have a strong interest in this feature.
I would love to prepend to or rename the labels of the tabs. I’ve written a plugin that gets the views and iterates over them to build tab numbers, but nowhere to put them
I like to use cmd+n to get around the tabs, so having the tab numbers would be helpful.
Thanks!
plugin idea:if the buffer is unmodified, mark it as a scratch buffer so it won't show up as unsaved.change the view name with view.set_name.on_modified, clear the scratch flag.on_pre_save, rename the view.on_post_save, set the scratch flag again and rename it back.
Seems like it should work?
After I wrote the previous post, I felt strongly like I remembered having done that exact thing before.Turns out I had:github.com/adzenith/Sublime-plu ... folding.pyBack before Sublime Text had code folding, I wrote a code folding plugin that did the same trick to show the buffer as unmodified. It worked great.
+1
maybe add the numbers also on the sidebar
after 0 (10) move on with a, b, c... hotkeys could be like ctrl+q a, ctrl+q b, etc | https://forum.sublimetext.com/t/tab-aliases-numbered-tabs/309 | CC-MAIN-2016-36 | refinedweb | 539 | 68.47 |
A fundamental part of Mate are the events, since all communication between the different parts of the application is made via events.
The EventHandlers in the EventMap subscribe to listen to events of particular types. The type specified is very important because it will determine whether or not a sequence must be run. This type is a string and that string must be unique throughout your whole application.
We define this type as a constant in the event itself. Suppose you have an event called CustomerEvent:
import flash.events.Event;
public class CustomerEvent extends Event {
public function CustomerEvent(type:String, bubbles:Boolean=true, cancelable:Boolean=true) {
super(type, bubbles, cancelable);
}
}
We add a constant for the event type:
public static const ADD:String = "addCustomerEvent";
In our event map, then, we can use this constant as the event type. This helps us not making mistakes when typing the event type.
<EventHandlers type="{CustomerEvent.ADD}">
.....
</EventHandlers>
You can use the same in your view Listeners:
<mate:Listener type="{CustomerEvent.ADD}" ..../>
And in your dispatchers:
<mate:Dispatcher generator="{CustomerEvent}" type="{CustomerEvent.ADD}" ...>
Creating a unique type
Since the event type must be unique, you can append the name of your event class so that it will be less likely to conflict with other events:
"add" + "CustomerEvent"= "addCustomerEvent"
public static const ADD:String = "addCustomerEvent";
If you want to ensure there are no conflicts, you can also use the full package name as part of the event type:
public static const ADD:String = "com.mydomain.events.CustomerEvent.ADD";
The above approach is not recommended if this event is a view event declared by the Event metatag in the view, as it will make the type too large and unreadable in parent views that wish to add event handlers for that event.
Having several types in the same event
You can have more than one type in the same event. As long as all those types defined use and need the same properties, they can be put together. For example, adding, updating and removing a customer all need a customer property and it makes sense to create only one event for all those types (assume you have a class Customer):
public class CustomerEvent extends Event {
public static const ADD:String = "addCustomerEvent";
public static const UPDATE:String = "updateCustomerEvent";
public static const DELETE:String = "deleteCustomerEvent";
public var customer:Customer;
public function CustomerEvent(type:String, bubbles:Boolean=false, cancelable:Boolean=true) {
super(type, bubbles, cancelable);
}
}
Bubbling property
When an event has it "bubbles" property set to false, only listeners added explicitly to the object that dispatched the event will be notified when the event is dispatched.
If you use the view's dispatchEvent() function (every Display Object is a Dispatcher) and dispatch the event as you would normally do:
var myEvent:CustomerEvent = new CustomerEvent(CustomerEvent.ADD);
dispatchEvent(myEvent);
the event map will not be notified unless you set the event property bubbles to true. Just so that you don't have to remember this every time you create an event:
new CustomerEvent(CustomerEvent.ADD, true)
you can set this property as true by default in your constructor:
public function CustomerEvent(type:String, bubbles:Boolean=true, cancelable:Boolean=true)
and then this code will work fine:
var myEvent:CustomerEvent = new CustomerEvent(CustomerEvent.ADD);
dispatchEvent(myEvent);
Built-in Events
An EventHandlers block can listen to any event that bubbles up or that has been dispatched by using the EventAnnouncer tag. Any Flex built-in event can also be used as long as it bubbles up. For example, an EventHandlers block can listen to FlexEvent.APPLICATION_COMPLETE event.
dispatchEvent() vs dispatcher.dispatchEvent()
If you need to dispatch an event that should reach the Event Map, in most cases, you can simply use dispatchEvent() function that is available in every display object (ie: views). In those cases, you would simply instantiate an event, and then dispatch it using the dispatchEvent(myEvent) function. For example:
var myEvent:CustomerEvent = new CustomerEvent(CustomerEvent.ADD);
dispatchEvent(myEvent);
If you want to dispatch an event that should reach the event map from an object that is not in the display list (for example a Manager or a Presentation Model object), then you need to supply the dispatcher. Even if those objects extend EventDispatcher or implement the IEventDispatcher interface, the events they dispatch do not bubble up (even if the bubbles property is set to true) because they are not in the display list. When you instantiate a manager or presentation model object, you need to pass the dispatcher. This dispatcher is a global dispatcher when using an EventMap or it can be any other dispatcher when using LocalEventMaps.
You can pass the current dispatcher via the constructor or as a property. If you use the constructor, then it should expect to receive an argument of type IEventDispatcher:
private var dispatcher:IEventDispatcher;
public function CustomerManager(dispatcher:IEventDispatcher)
{
this.dispatcher = dispatcher;
}
You will then use this.dispatcher to dispatch events from your manager.
You should instantiate your object (ie: manager or presentation model) as follows:
<ObjectBuilder generator="{CustomerManager}" constructorArguments="{[scope.dispatcher]}"/>
If you don't want to change the constructor, you can simply set a public property:
public var dispatcher:IEventDispatcher;
public function CustomerManager()
{
}
and instantiate the object as follows:
<ObjectBuilder generator="{CustomerManager}">
<Properties dispatcher="{scope.dispatcher}"/>
</ObjectBuilder>
Thanks!
PS I posted in the comments instead of the forum because I think it may be useful to others reading the docs.
The class cannot be used to disambiguate the type because when you say CustomerEvent.ADD, for example, you are only specifying a static variable, which translates to "addCustomerEvent". Those are simply static vars, so we only see the value. Also, that is how Flex works. The function addEventListener, which is what we use in the event handlers, takes a string as a first argument. There is nothing else you can specify there to make any distinction. | https://mate.asfusion.com/page/documentation/best-practices/events | CC-MAIN-2019-04 | refinedweb | 976 | 50.77 |
QuickTip: Speed up upstream DNS on Kubernetes
Since a few months we’ve been heavily focused on Kubernetes (K8S) here at Valkyrie and after some trial and error we put together some sweet deployment scripts that combine Terraform, Ansible, kubeadm to roll out K8S clusters on digitalocean.
This article is not about the entire deployment system, but will focus on one addition that we did that dramatically speeds up upstream DNS for the KubeDNS layer that kubeadm installs.
TLDR;
There’s a new kid on the block when it comes to superfast DNS, CloudFlare’s 1.1.1.1 (which is on general 2X faster than Google’s 8.8.8.8 DNS service)
What is KubeDNS?
Before we go into the nitty gritty, let’s first look at KubeDNS and how it works in a nutshell. (For a more in-depth article, please visit : DNS for Services and Pods )
Kubernetes assigns each service a virtual static IP address routable within the cluster, so any connection that reaches this IP address will be automatically routed to one of the containers in the group.
KubeDNS is a layer that is part of the kube-system namespace which handles DNS lookups both in the cluster and to the outside world.
It does this by assigning A/SRV records for each service’s static IP address.
In the cluster it sets up a DNS server that handles these internal and cross-namespace lookups, for example:
- mysql0.data.svc.cluster.local : Looks up the service called mysql0 in the data namespace.
- mongo0 : looks up the service called mongo0 in the same namespace
The svc.cluster.local means that we are talking to a ‘service’ object in the local cluster. At the time of writing ‘svc’ is the only registered prefix, but the reason it was added is to allow for future extension without breaking current setups.
In case a record is not found in the local DNS service (for example : facebook.com ) it will contact the upstream nameservers defined in KubeDNS.
Upstream Nameservers?
By default KubeDNS first does a lookup to see if the url we’re trying to each is an internal one. In case it isn’t the case (such as facebook.com) it will contact the upstream nameservers that are defined.
By default KubeDNS inherits these from the local machine’s /etc/resolv.conf file. For example on my local arch system those look like:
In case you wanted to know what these servers are, by default they are those of your ISP ( such as digitalocean, or in my case Telenet )
These are the DNS servers that will do ‘external’ lookups for names that are not defined in your own cluster.
Supercharging your DNS
However, in most cases there are faster nameservers on the market, we all know that for example 8.8.8.8 ( Google DNS ) is one of the fastest out there. But is that really the only solution?
There’s a new kid on the block in regards to supercharged DNS and it was recently opened by CloudFlare. There’s a very interesting vlog about this on youtube that I urge everyone to check out :
To apply this new magical 1.1.1.1 DNS to our KubeDNS setup we simply need to write a configmap that overrides the defaults of KubeDNS :
And afterwards apply it with the following command :
That’s it! Enjoy your supercharged DNS :D | https://medium.com/@valkyrie_be/quicktip-speed-up-upstream-dns-on-kubernetes-9f35083fba55?source=---------4------------------ | CC-MAIN-2020-40 | refinedweb | 570 | 69.11 |
Essential cross-platform UI components for React Native
Table of ContentTable of Content
- What is NativeBase?
- Why NativeBase?
- KitchenSink App
- Getting Started
- Components
- NativeBase for Web
- Compatibility Versions
- React Native Seed
- NativeBase Market
- Documentation
- Website
- Quick Links to NativeBase
- About the creators
1. What is NativeBase?1. What is NativeBase?
NativeBase is a sleek, ingenious and dynamic front-end framework created by passionate React Loving team at Geekyants.com to build cross platform Android & iOS mobile apps using ready to use generic components of React Native.
2. Why NativeBase4. Expo
Expo helps you make React Native apps with no build configuration. It works on macOS, Windows, and Linux.
Refer this link for additional information on Expo
Install NativeBase
npm install native-base --save
Note
NativeBase uses some custom fonts that can be loaded using Font.loadAsync. Check out the Expo Font documentation.
Install Expo Fonts
expo install expo-font
App.js
import React from 'react'; import { AppLoading } from 'expo'; import { Container, Text } from 'native-base'; import * as Font from 'expo-font'; import { Ionicons } from '@expo/vector-icons'; export default class App extends React.Component { constructor(props) { super(props); this.state = { isReady: false, }; } async componentDidMount() { await Font.loadAsync({ Roboto: require('native-base/Fonts/Roboto.ttf'), Roboto_medium: require('native-base/Fonts/Roboto_medium.ttf'), ...Ionicons.font, }); this.setState({ isReady: true }); } render() { if (!this.state.isReady) { return <AppLoading />; } return ( <Container> <Text>Open up App.js to start working on your app!</Text> </Container> ); } }
Check out the KitchenSink with Expo5. Components
NativeBase is made from effective building blocks referred to as components. The Components are constructed in pure React Native platform along with some JavaScript functionality with rich set of customisable properties. These components allow you to quickly build the perfect interface.
6. NativeBase for Web6. NativeBase for Web
NativeBase is now available for React web lovers. Check the demo Find the repo here
7. Compatibility Versions7. Compatibility Versions
React Native Seed8.
React Native Seed provides you React Native starter kits for your base app with the technologies that you love.
Based on the feedback we received from our users, people had trouble sorting out the right boilerplate for them with the desired technologies and contacted us to enquire. We realized that many people were particular about the technologies they want in the app and that a minimal, neat solution was required to solve this, and hence, React Native Seed.
React Native Seed is for learners and professionals alike, those who want to experiment, learn all aspects and those who already know enough, just want a starter kit to quickly start working on their project.
9. NativeBase Market9.10. Documentation
Go through NativeBase Docs to play with NativeBase.
11. Website11. Website
12. Quick Links to NativeBase12. Quick Links to NativeBase
13. About the creators13. About the creators
We are GeekyAnts, a startup based in Bangalore, India with 50+ developers in strength. We have been very active in the React / React Native community where we have developed StrapUI and StartReact. Our other products include StartLaravel and StartAngular.
Another major project by us is BuilderX, a screen design tool which codes React Native for you.
ContributorsContributors] | https://libraries.io/npm/native-base | CC-MAIN-2019-47 | refinedweb | 519 | 50.43 |
orSS two).
Finally, hooks whose name starts with
hook_html_, are run after the page is
fully built. These hooks can manipulate the HTML code that was produced by the
page template. Such hooks can be used to conditionally inject scripts, for
example, when a page has code snippets to highlight syntax in. Example hook:
def hook_html_add_script(html): if "<pre>" in html: add_html = "<script src='/scripts.js'></script>" html = html.replace("</head>", add_html + "</head>") return html
Recipes
You can do some pretty fancy and useful things with inlined Python code and the macros module, for instance generate a list of blog posts or create an RSS file. Check out the example recipes.
Feedback
Please use the issue tracker. | https://bitbucket.org/umonkey/poole/overview | CC-MAIN-2016-50 | refinedweb | 117 | 74.29 |
Adding new metrics
When adding a new metric, the workflow is:
- Consider the question you are trying to answer with this data, and choose the metric type and parameters to use.
- Add a new entry to
metrics.yaml.
- Add code to your project to record into the metric by calling the Glean SDK.
Important: Any new data collection requires documentation and data-review. This is also required for any new metric automatically collected by the Glean SDK.
Choosing a metric type
The following is a set of questions to ask about the data being collected to help better determine which metric type to use.
Is it a single measurement?
If the value is true or false, use a boolean metric.
If the value is a string, use a string metric. For example, to record the name of the default search engine.
Beware: string metrics are exceedingly general, and you are probably best served by selecting the most specific metric for the job, since you'll get better error checking and richer analysis tools for free. For example, avoid storing a number in a string metric --- you probably want a counter metric instead.
If you need to store multiple string values in a metric, use a string list metric. For example, you may want to record the list of other Mozilla products installed on the device.
For all of the metric types in this section that measure single values, it is especially important to consider how the lifetime of the value relates to the ping it is being sent in. Since these metrics don't perform any aggregation on the client side, when a ping containing the metric is submitted, it will contain only the "last known" value for the metric, potentially resulting in data loss. There is further discussion of metric lifetimes below.
Are you counting things?
If you want to know how many times something happened, use a counter metric. If you are counting a group of related things, or you don't know what all of the things to count are at build time, use a labeled counter metric.
If you need to know when the things being counted happened relative to other things, consider using an event.
Are you measuring time?
If you need to record an absolute time, use a datetime metric. Datetimes are recorded in the user's local time, according to their device's real time clock, along with a timezone offset from UTC. Datetime metrics allow specifying the resolution they are collected at, and to stay lean, they should only be collected at the minimum resolution required to answer your question.
If you need to record how long something takes you have a few options.
If you need to measure the total time spent doing a particular task, look to the timespan metric. Timespan metrics allow specifying the resolution they are collected at, and to stay lean, they should only be collected at the minimum resolution required to answer your question. Note that this metric should only be used to measure time on a single thread. If multiple overlapping timespans are measured for the same metric, an invalid state error is recorded.
If you need to measure the relative occurrences of many timings, use a timing distribution. It builds a histogram of timing measurements, and is safe to record multiple concurrent timespans on different threads.
If you need to know the time between multiple distinct actions that aren't a simple "begin" and "end" pair, consider using an event.
Do you need to know the order of events relative to other events?
If you need to know the order of actions relative to other actions, such as, the user performed tasks A, B, and then C, and this is meaningfully different from the user performing tasks A, C and then B, (in other words, the order is meaningful beyond just the fact that a set of tasks were performed), use an event metric.
Important: events are the most expensive metric type to record, transmit, store and analyze, so they should be used sparingly, and only when none of the other metric types are sufficient for answering your question.
For how long do you need to collect this data?
Think carefully about how long the metric will be needed, and set the
expires parameter to disable the metric at the earliest possible time.
This is an important component of Mozilla's lean data practices.
When the metric passes its expiration date (determined at build time), it will automatically stop collecting data.
When a metric's expiration is within in 14 days, emails will be sent from
telemetry-alerts@mozilla.com to the
notification_emails addresses associated with the metric.
At that time, the metric should be removed, which involves removing it from the
metrics.yaml file and removing uses of it in the source code.
Removing a metric does not affect the availability of data already collected by the pipeline.
If the metric is still needed after its expiration date, it should go back for another round of data review to have its expiration date extended.
When should the Glean SDK automatically clear the measurement?
The
lifetime parameter of a metric defines when its value will be cleared. There are three lifetime options available:
ping(default): The metric is cleared each time it is submitted in the ping. This is the most common case, and should be used for metrics that are highly dynamic, such as things computed in response to the user's interaction with the application.
application: The metric is related to an application run, and is cleared after the application restarts and any Glean-owned ping, due at startup, is submitted. This should be used for things that are constant during the run of an application, such as the operating system version. In practice, these metrics are generally set during application startup. A common mistake---using the ping lifetime for these type of metrics---means that they will only be included in the first ping sent during a particular run of the application.
user: Reach out to the Glean team before using this.. The metric is part of the user's profile and will live as long as the profile lives. This is often not the best choice unless the metric records a value that really needs to be persisted for the full lifetime of the user profile, e.g. an identifier like the
client_id, the day the product was first executed. It is rare to use this lifetime outside of some metrics that are built in to the Glean SDK.
While lifetimes are important to understand for all metric types, they are particularly important for the metric types that record single values and don't aggregate on the client (
boolean,
string,
labeled_string,
string_list,
datetime and
uuid), since these metrics will send the "last known" value and missing the earlier values could be a form of unintended data loss.
A lifetime example
Let's work through an example to see how these lifetimes play out in practice. Let's suppose we have a user preference, "turbo mode", which defaults to
false, but the user can turn it to
true at any time. We want to know when this flag is
true so we can measure its affect on other metrics in the same ping. In the following diagram, we look at a time period that sends 4 pings across two separate runs of the application. We assume here, that like the Glean SDK's built-in metrics ping, the developer writing the metric isn't in control of when the ping is submitted.
In this diagram, the ping measurement windows are represented as rectangles, but the moment the ping is "submitted" is represented by its right edge. The user changes the "turbo mode" setting from
false to
true in the first run, and then toggles it again twice in the second run.
A. Ping lifetime, set on change: The value isn't included in Ping 1, because Glean doesn't know about it yet. It is included in the first ping after being recorded (Ping 2), which causes it to be cleared.
B. Ping lifetime, set on init and change: The default value is included in Ping 1, and the changed value is included in Ping 2, which causes it to be cleared. It therefore misses Ping 3, but when the application is started, it is recorded again and it is included in Ping 4. However, this causes it to be cleared again and it is not in Ping 5.
C. Application lifetime, set on change: The value isn't included in Ping 1, because Glean doesn't know about it yet. After the value is changed, it is included in Pings 2 and 3, but then due to application restart it is cleared, so it is not included until the value is manually toggled again.
D. Application, set on init and change: The default value is included in Ping 1, and the changed value is included in Pings 2 and 3. Even though the application startup causes it to be cleared, it is set again, and all subsequent pings also have the value.
E. User, set on change: The default value is missing from Ping 1, but since
userlifetime metrics aren't cleared unless the user profile is reset (e.g. on Android, when the product is uninstalled), it is included in all subsequent pings.
F. User, set on init and change: Since
userlifetime metrics aren't cleared unless the user profile is reset, it is included in all subsequent pings. This would be true even if the "turbo mode" preference were never changed again.
Note that for all of the metric configurations, the toggle of the preference off and on during Ping 4 is completely missed. If you need to create a ping containing one, and only one, value for this metric, consider using a custom ping to create a ping whose lifetime matches the lifetime of the value.
What if none of these lifetimes are appropriate?
If the timing at which the metric is sent in the ping needs to closely match the timing of the metrics value, the best option is to use a custom ping to manually control when pings are sent.
This is especially useful when metrics need to be tightly related to one another, for example when you need to measure the distribution of frame paint times when a particular rendering backend is in use. If these metrics were in different pings, with different measurement windows, it is much harder to do that kind of reasoning with much certainty.
What should this new metric be called?
Reuse names from other applications
There's a lot of value using the same name for analogous metrics collected across different products. For example, BigQuery makes it simple to join columns with the same name across multiple tables. Therefore, we encourage you to investigate if a similar metric is already being collected by another product. If it is, there may be an opportunity for code reuse across these products, and if all the projects are using the Glean SDK, it's easy for libraries to send their own metrics. If sharing the code doesn't make sense, at a minimum we recommend using the same metric name for similar actions and concepts whenever possible.
Make names unique within an application
Metric identifiers (the combination of a metric's category and name) must be unique across all metrics that are sent by a single application.
This includes not only the metrics defined in the app's
metrics.yaml, but the
metrics.yaml of any Glean SDK-using library that the application uses, including the Glean SDK itself.
Therefore, care should be taken to name things specifically enough so as to avoid namespace collisions.
In practice, this generally involves thinking carefully about the
category of the metric, more than the
name.
Note: Duplicate metric identifiers are not currently detected at build time. See bug 1578383 for progress on that. However, the probe_scraper process, which runs nightly, will detect duplicate metrics and e-mail the
notification_emailsassociated with the given metrics.
Be as specific as possible
More broadly, you should choose the names of metrics to be as specific as possible. It is not necessary to put the type of the metric in the category or name, since this information is retained in other ways through the entire end-to-end system.
For example, if defining a set of events related to search, put them in a category called
search, rather than just
events or
search_events. The
events word here would be redundant.
What if none of these metric types is the right fit?
The current set of metrics the Glean SDK supports is based on known common use cases, but new use cases are discovered all the time.
Please reach out to us on #glean:mozilla.org. If you think you need a new metric type, we have a process for that.
How do I make sure my metric is working?
The Glean SDK has rich support for writing unit tests involving metrics. Writing a good unit test is a large topic, but in general, you should write unit tests for all new telemetry that does the following:
Performs the operation being measured.
Asserts that metrics contain the expected data, using the
testGetValueAPI on the metric.
Where applicable, asserts that no errors are recorded, such as when values are out of range, using the
testGetNumRecordedErrorsAPI.
In addition to unit tests, it is good practice to validate the incoming data for the new metric on a pre-release channel to make sure things are working as expected.
Adding the metric to the
metrics.yaml file
The
metrics.yaml file defines the metrics your application or library will send.
They are organized into categories.
The overall organization is:
# Required to indicate this is a `metrics.yaml` file $schema: moz://mozilla.org/schemas/glean/metrics/1-0-0 toolbar: click: type: event description: | Event to record toolbar clicks. notification_emails: - CHANGE-ME@example.com bugs: - data_reviews: - expires: 2019-06-01 # <-- Update to a date in the future double_click: ... category2.subcategory: # Categories can contain subcategories using `.` metric: ...
The details of the metric parameters are described in metric parameters.
The
metrics.yaml file is used to generate code in the target language (e.g. Kotlin, Swift, ...) that becomes the public API to access your application's metrics.
Using the metric from your code
The reference documentation for each metric type goes into detail about using each metric type from your code.
One thing to note is that we try to adhere to the coding conventions of each language wherever possible, to the metric name in the
metrics.yaml (which is in
snake_case) may be changed to some other case convention, such as
camelCase, when used from code.
Category and metric names in the
metrics.yaml are in
snake_case,
but given the Kotlin coding standards defined by ktlint,
these identifiers must be
camelCase in Kotlin.
For example, the metric defined in the
metrics.yaml as:
views: login_opened: ...
is accessible in Kotlin as:
import org.mozilla.yourApplication.GleanMetrics.Views GleanMetrics.Views.loginOpened...
Category and metric names in the
metrics.yaml are in
snake_case,
but given the Swift coding standards defined by swiftlint,
these identifiers must be
camelCase in Swift.
For example, the metric defined in the
metrics.yaml as:
views: login_opened: ...
is accessible in Kotlin as:
GleanMetrics.Views.loginOpened...
Category and metric names in the
metrics.yaml are in
snake_case, which matches the PEP8 standard, so no translation is needed for Python. | https://mozilla.github.io/glean/book/user/adding-new-metrics.html | CC-MAIN-2020-40 | refinedweb | 2,602 | 61.97 |
On 05/19/2016 03:32 AM, Peter Krempa wrote: > On Wed, May 18, 2016 at 19:52:30 -0400, John Ferlan wrote: >> Create a mock for virRandomBytes to generate a not so random value that >> can be used by the tests to ensure the generation of an encrypted secret >> by masterKey and random initialization vector can produce an expected >> result. The "random number" generated is based upon the size of the >> expected stream of bytes being returned where each byte in the result >> gets the index of the array - hence a 4 byte array returns 0x00010203. >> >> Signed-off-by: John Ferlan <jferlan redhat com> >> --- >> tests/qemuxml2argvmock.c | 31 ++++++++++++++++++++++++++++++- >> 1 file changed, 30 insertions(+), 1 deletion(-) >> >> diff --git a/tests/qemuxml2argvmock.c b/tests/qemuxml2argvmock.c >> index 1616eed..dade748 100644 >> --- a/tests/qemuxml2argvmock.c >> +++ b/tests/qemuxml2argvmock.c > > [...] > >> @@ -145,3 +152,25 @@ virCommandPassFD(virCommandPtr cmd ATTRIBUTE_UNUSED, >> { >> /* nada */ >> } >> + >> +int >> +virRandomBytes(unsigned char *buf, >> + size_t buflen) >> +{ >> + size_t i; >> + >> + for (i = 0; i < buflen; i++) >> + buf[i] = i; >> + >> + return 0; >> +} >> + >> +#ifdef WITH_GNUTLS >> +int >> +gnutls_rnd(gnutls_rnd_level_t level ATTRIBUTE_UNUSED, >> + void *data, >> + size_t len) >> +{ >> + return virRandomBytes(data, len); >> +#endif > > As I've pointed out last time, this won't compile without gnutls. > Beyond the merge issue with putting the } after the #endif, I agree - it won't compile, but I can only assume that's not your issue; otherwise, I would think that your initial review would have just pointed out that the } needs to be inside the #endif. If one checks who would actually call this: qemuDomainGenerateRandomKey(): #if HAVE_GNUTLS_RND /* Generate a master key using gnutls_rnd() if possible */ if ((ret = gnutls_rnd(GNUTLS_RND_RANDOM, key, nbytes)) < 0) { virReportError(VIR_ERR_INTERNAL_ERROR, ... So is your issue that 1. The incorrect placement of #endif 2. "#ifdef HAVE_GNUTLS_RND" should have been used 3. you want an "#else" 4. you don't want to see the #ifdef? I could see value in #2 to follow the caller, but the others I don't see value in. But certainly none of those options encompasses the catch-all this won't compile without gnutls when I read the review. In any case, between patch 2 and the cover - I pointed out that I wasn't sure putting this into a file named "qemuxml2argvmock.c" was the right choice given that as you pointed out previously that qemu isn't required. So I started down the path of creating a virrandommock.c and a virrandomtest.c; however, there is just something about that mock environment that I don't understand well enough to get things to work as I expected. I posted this with the hope that someone would be able to look and provide some assistance with the magic words to write in Makefile.am. OH and BTW: In patch 2, the }/#endif issue was already handled properly in virrandommock.c. John | https://www.redhat.com/archives/libvir-list/2016-May/msg01425.html | CC-MAIN-2020-50 | refinedweb | 466 | 61.46 |
Implementing in app purchase on Android
Thursday December 12, 2013 by Eskil Abrahamsen Blomfeldt | Comments a lot lower than if you had to pay up front.
But you already know this, because you have been asking us regularly how to do it in Qt for the past few months. Our short answer is that Qt does not have a cross-platform API for this, at least not yet, so you will have to add some platform-specific code to your application.
This blog post is the long answer. Using a simple game as an example, I'll go through each of the steps to enable in-app purchases in an Android application. The application source is also available, so you can take a look at it before doing your own implementation.
So what is it?
For those of you who have not been asking us about this, and therefore cannot be proven to know what in-app purchases are, I'll give a very quick overview.
In brief, in-app purchase is this: Instead of paying to download and run an application, there are instead features of the application that are available for purchase when you are already running it. Some examples of the types of purchases the application can provide are:
- Subscription to content, like in an online magazine with monthly content updates.
- Consumable items, e.g. a magic potion in a game, of which you can buy an unlimited amount.
- Or a permanent purchase to unlock vital features of the application. For instance, the Save function in a photo editing application might be disabled until you've paid an in-app fee, so that users can test the application before they decide if it's worth the price.
The way this all works in Google Play is that you add one or more "In-app Products" to the store listing for your application. You give each item a product ID (SKU), and add code in your application to launch the purchase process. The process itself is out of your hands. The user will be asked to confirm the purchase, and your application will be informed about the status of the transaction asynchronously. I will not go into the details of the APIs in this blog, so if you're planning to implement something like this, make sure you read the Android documentation on the subject first.
The example
As my example, I've written a simple Hangman game in QML. Consonants are free (except for the traditional non-monetary penalty of wrong guesses), but you have to pay a minimal fee for vowels. The application is available for download, so you can quickly run it and see it in action, but rather than buy any vowels in the downloaded game, you can compile it yourself from source, upload it as a draft to your personal Google Play Developer Console and run it unpublished. As long as your personal version of the application remains unpublished, you can test the full purchase process without actually being charged. Just make sure you add your test account in the Settings page of your Developer Console.
I should note that if this were a proper game, I would probably have users pay for packs of, say, 50 vowels or so, both to avoid overpricing and to avoid going through the steps for purchasing every time they want to guess for a vowel. But for this example, it would only make the code more complex, so I've left it as simple as possible.
The game
First, a quick run-through of how the game works: I started by developing everything in the game on my desktop machine, leaving out the platform-specific purchase code for now. This approach has several benefits over writing directly for device:
- It makes iterative testing faster, as the application does not need to be deployed before it can be run.
- It makes it easy to test that the application adapts to different screen sizes, as I can easily resize my main window and see it adapt in real time.
- And it forces me to write the application in a cross-platform way, so that it can be ported to other platforms later with relatively little effort.
Regardless of what type of application I'm writing, I'll usually try to take this approach, and if the application depends on inputs or features that are only available on the target platform, I'll make an effort to simulate them in the desktop build.
The game itself is just a scene in QML, hooked up to a Data object written in C++. The Data object is used to manage the current solution word and the guesses. You play the game by selecting letters at the bottom. If you select a vowel, you will be asked to pay before it is tested against the solution. You can also wager a guess for the full solution if you think you've got it. That part is free ;)
The word list is based on the public domain ENABLE dictionary by Alan Beale and M. Cooper. This initially contained a lot of words we had never heard before, but Paul Olav Tvete limited it to words used in the Qt documentation or on the Qt Development mailing list, so the game should be familiar to avid Qt users :)
As you make guesses, they will either be displayed as part of the solution if they are contained in the word, or one line of the hangman picture will be added to the square in the middle of the screen. When the entire drawing is finished, the game will be over. If you manage to guess the solution before this happens, you win the game.
You can click on the Reset button in the top left corner to get a new puzzle, picked randomly from the ENABLE dictionary, or you can hit the Reveal button to give up and show the solution.
I won't go into any more detail about the game itself. The interesting part here is the in-app purchasing, so I'll spend the rest of the blog post on that.
On iOS
Before I continue with the technical details, I'll briefly mention iOS as well: As I said, while the the example code is not 100% cross-platform, it is structured to be easily adaptable to other platforms, attempting to minimize the amount of extra code you have to write to port it. And in fact, Andy Nichols already wrote some code to move the game to iOS which is nearly done, but not quite ready for release just yet. He will blog about this later on, but the code we have so far is already in the source repository for you to look at.
In-app purchase: Structure
So, I wanted to finish the desktop version of the game before implementing the Android-specific part. As an abstraction of the platform-specific code I would have to add in later, I identified the need for the following function to take care of actually purchasing a vowel from the market place:
void buyVowel(const QChar &vowel);
Since the Android in-app purchase APIs are asynchronous, I also added a signal which is emitted when the purchase succeeds:
signals:
void vowelBought(const QChar &vowel);
When this signal is emitted, it means the transaction has been made, and I add the selected vowel to the list of current guesses. In order to run the application on desktop (and other platforms as well), I add a file named data_default.cpp with the following default implementation of the buyVowel() function:
void Data::buyVowel(const QChar &vowel)
{
emit vowelBought(vowel);
}
This code will never be compiled on Android, but for other platforms, it will imitate a successful purchase. To avoid compiling the code on Android, I add the following to my .pro file:
android: SOURCES += data_android.cpp
else: SOURCES += data_default.cpp
Now it's quite easy for me to add an Android-specific implementation of buyVowel() in data_android.cpp, and also to add implementations for other platforms down the road.
The Java code
Since the Android APIs are based in Java, I made the main bulk of my implementation in Java and then later accessed this through JNI from my C++ application. I won't go into detail about the actual usage of the Android APIs, since that's already thoroughly documented in the official documentation. I will however highlight a few areas of particular interest in the Java code for my game.
First of all, I needed to add the Android-specific files to my project. I started by adding an AndroidManifest.xml file to my project using Qt Creator.
I chose to put the manifest in the subdirectory android-source. After adding this directory, all my Android-specific files can go into it. In general, it should contain the files you want to add to the Android project and the directory structure should follow the regular Android project directory structure. The contents of the directory will later be merged with a template from Qt, so you should only put your additions and modifications here. There is no need to include an entire Android project.
Next, I added a new Activity subclass. Java sources need to go in the src directory to be recognized correctly when building the package, and in a subpath which matches the package namespace of the class. In my case I placed the class in android-source/src/org/qtproject/example/hangman/.
To make sure Qt is loaded correctly, I had to subclass Qt's default Activity class. This is very important.
import org.qtproject.qt5.android.bindings.QtActivity;
public class HangmanActivity extends QtActivity
I also had to make sure to call into the super class from all reimplementations of methods. Like here:
@Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
bindService(new Intent("com.android.vending.billing.InAppBillingService.BIND"),
m_serviceConnection, Context.BIND_AUTO_CREATE);
}
In my game, the Activity is a singleton, so I store a static reference to the object in the constructor:
private static HangmanActivity m_instance;
public HangmanActivity()
{
m_instance = this;
}
(My C++ Data class has the same logic. I'm doing this so that I can facilitate the communication between the Java and the C++ code using static methods. For a more complex example, it's also possible to store references and pointers in each C++ and Java object that maps it to its equivalent in the other language, but that is not necessary in this game.)
In my Activity class in Java, I implemented a method to handle the request for purchasing a vowel:
public static void buyVowel(char vowel)
And I also added a native callback method which I can call when I've received the asynchronous message that the vowel has been purchased:
private static native void vowelBought(char vowel);
The native keyword indicates that the method is implemented in native code. I'll come back to the implementation of that later.
My buyVowel() method follows the documentation closely. The main part to note is the following snippet:
Bundle buyIntentBundle = m_instance.m_service.getBuyIntent(3,
m_instance.getPackageName(),
"vowel",
"inapp",
"" + vowel);
This code will create a Buy Intent for API version 3, the package name of my application (note that this is the application package in the Google Play store and AndroidManifest.xml, not the package namespace of the Java class), and the in-app product identified as "vowel". In addition, I'm passing "inapp" as the type and I'm passing the actual vowel requested as the developer payload. The latter will be returned back to me along with the message of a successful purchase, so that I can easily inform my application of which letter was actually purchased.
The message informing my application whether the purchase was successful or not is delivered in the method onActivityResult(). In this method I can retrieve several pieces of information about the purchase in JSON format:
JSONObject jo = new JSONObject(purchaseData);
String sku = jo.getString("productId");
int purchaseState = jo.getInt("purchaseState");
String vowel = jo.getString("developerPayload");
String purchaseToken = jo.getString("purchaseToken");
I quickly verify that it's the correct product and that it was successfully purchased (purchaseState == 0). If this is the case, I inform my native code of the purchase, and I immediately consume it:
if (sku.equals("vowel") && purchaseState == 0) {
vowelBought(vowel.charAt(0));
// Make sure we can buy a vowel again
m_service.consumePurchase(3, getPackageName(), purchaseToken);
return;
}
Consuming the purchase is very important in this case, as you will not be able to purchase the same product again later unless it has been consumed. So for consumable items, like these vowels, which you should be able to purchase an unlimited number of times, we must consume them immediately after they have been registered in the application. For permanent purchases (imagine if I also had a slightly more expensive product called "Free vowels forever"), you would skip this step. You could then later query Google Play for the product and it would tell you that it has already been purchased.
Finally, in order to be able to access the billing API, I need to add its interface to my project, as explained in the Android documentation. I copy the file IInAppBillingService.aidl into subdirectory android-source/src/com/android/vending/billing.
AndroidManifest.xml
A few modifications are necessary to the default AndroidManifest.xml file. This is the file which describes your application to the device that is running it, and also to the Google Play store which needs the information to properly advertise it to the correct devices.
Like for all Android applications, I need to set an icon, a name, a package name, etc. In the source tree, I've left the package name empty. This is intentional, as you will need a unique package name for your instance of the application in order to register it in Google Play. Make sure you set this before building. I've also locked the screen orientation to "portrait", because that's how the application was designed.
Specifically for using the in-app purchase API, I need to declare that I am using the "BILLING" permission:
<uses-permission android:
If I neglect to add this, then my application will get an exception when trying to access the APIs.
In addition, I need to set my own Activity class as the main activity rather than Qt's class:
<activity ... android:
This ensures that the HangmanActivity class will be instantiated when the device launches the application.
The native code
All the Android-specific native code is in the data_android.cpp file. As mentioned, it needs a platform-specific implementation of the buyVowel() function:
void Data::buyVowel(const QChar &vowel)
{
QAndroidJniObject::callStaticMethod("org/qtproject/example/hangman/HangmanActivity",
"buyVowel",
"(C)V",
jchar(vowel.unicode()));
}
The only thing this code does is issue a call to the Java method described in the previous section. Thus, it will launch an asynchronous request for the vowel and we will wait until the payment goes through before doing anything else.
In addition, we need to implement the native vowelBought() method, which will be called from Java when the purchase is successful:
static void vowelBought(JNIEnv *, jclass /*clazz*/, jchar c)
{
Data::instance()->vowelBought(QChar(c));
}
This is just a regular C++ function, with the exception that it will always get a JNIEnv pointer as its first argument, and a jclass argument which is a reference to the declaring class in Java (since this is a static method.) As you can see, it simply accesses the Data singleton and emits the vowelBought signal to register the purchased vowel.
Finally, the native method is registered using a standard boiler plate when the library is loaded. Check the code to see the full thing.
Putting it in the store
Then we've reached the final step, which was to actually upload the APK to the Google Play market and add the products for purchase there. Note that you do not have to publish the application in order to test the in-app purchases: You can keep the APK in Draft mode and mark the products as "To be activated", in which case you have to handle the distribution of the application yourself, but the Google accounts listed in the "LICENSE TESTING" section of your Developer Console Settings will be able to make test purchases once they have installed it. You can also publish a Beta version of your application in the store, in which case you can manage who will be able to download it and make test purchases using Google Groups.
I started by registering a listing for my application. Once this was done, and I'd filled out the necessary pieces of information, I had to upload the APK. You cannot register any products in the listing before you've uploaded an APK. (Make sure you sign the package with your private key before uploading it. The whole process of generating a key and signing the package can be done from inside Qt Creator, in the Project -> Run -> Deploy configurations.)
Once this has been done, I can add a product. I click on the "In-app products" tab, and select to create a new product. Then I fill out the necessary information:
I had to make sure I picked "Managed product" here, as this is the only type supported by API version 3. It means that Google Play will remember that the product was purchased for you, and you will need to explicitly consume it before you can purchase the same product again.
When the product has been added, I can add some more details:
I've added a short description of the item, and set the price to the minimum possible price (6 NOK which is approximately 1 USD). I also make sure to mark the product "To be activated" so that it can be purchased. When the application is published, the product will become activated automatically.
Done
And that's it. I can now run the application on my devices and purchase vowels as much as I want. Until the application is published into "Production", no transactions will actually be carried through, so you can test your local build without fearing that you'll run out of money.
But do note that if you decide to use Digia's version of the application, then purchases are real, since Google Play has a set minimum price.
Good luck!
Discover more Qt news: Introducing Qt Mobile | https://www.qt.io/blog/2013/12/12/implementing-in-app-purchase-on-android | CC-MAIN-2020-10 | refinedweb | 3,087 | 58.62 |
Deploying Qt5 on Windows 7: Too Difficult
The documentation for how to deploy Qt 5 on Windows is too hidden and is missing several pieces of crucial information. This makes deploying Qt5 MUCH more painful than it really should be.
Through a lot of searching on other posts, I know I'm supposed to include platforms/qwindows.dll and platforms/qminimal.dll as well as the (somewhat stealthy) their dependency: libEGL.dll. I also know I am supposed to include the plugins my program is using, but I have no way to determine which ones they are!
I have defined the environment variable QT_DEBUG_PLUGINS to a non-zero value to try to get more info. No luck.
I have tried to deploy a debug version from the console to see if I get any useful output. No luck.
I have double checked my .pro file and stripped out any unneeded dependencies like this:
@QT -= gui
QT += core quick multimedia
CONFIG += thread qt@
But there is no documentation on EXACTLY which plugins correspond to which dependencies, so no luck here.
I temporarily removed all my QML files and replaced them with a single file that displayed a single maroon rectangle. Still no luck.
I have even tried copying ALL the plugins at Qt5.0.1\5.0.1\msvc2010\plugins into my apps directory so that I have:
myapp\myapp.exe
myapp\accessible
myapp\bearer
... etc.
But even THAT didn't work.
Everything I try, I am stuck staring at a blank white screen with no information on what I am doing wrong. It is highly frustrating!
What do I need to do differently?
- sierdzio Moderators
You do need the QtGui module, and QtQml.
@
QT = core gui qml quick
@
For QtQuick 2 apps. Normally, no plugins apart from platform plugin (qwindows.dll. Minimal plugin is not needed) are required. Optionally, image plugins and database plugins might be needed, but that depends on your Qt build and app requirements.
I have no experience with QtMultimedia, so I can't help there. I don't have too much experience with Windows, too, to be hones. On Linux it just works.
"link":.
Thank you very much for the response sierdzio.
I had thought it odd that my program would compile without those modules. I wonder why I don't get a compile issue when omitting gui or qml, but I DO get a compile issue when omitting multimedia. Maybe it is because I am using multimedia components in C++.
I discovered this morning that QT_DEBUG_PLUGINS really IS working. The issue is that I can only see the output when the program is executed by QtCreator. I was checking for output in the console with the deployed executable. I thought this would enable that behavior:
@CONFIG += console@
With QT_DEBUG_PLUGINS turned on, I found a nice list of plugins used when I exit the program. Each entry looks like this:
QLibraryPrivate::unload succeeded on "D:/Programs/Development/Qt/Qt5.0.1/5.0.1/msvc2010/plugins/mediaservice/wmfengine.dll"
Tracking down and adding these plugins to my program was pretty trivial. HOWEVER, I am still unable to deploy my program. I think it has to do with this output:
loaded library "D:/Programs/Development/Qt/Qt5.0.1/5.0.1/msvc2010/qml/QtQuick.2/qtquick2plugin.dll"
loaded library "D:/Programs/Development/Qt/Qt5.0.1/5.0.1/msvc2010/qml/QtMultimedia/declarative_multimedia.dll"
These "plugins" are in a different location than the rest and are in a different format. I am sure my program is looking for them to run, but I do not know where it is looking.
I tried pathing like this:
myprogram/myprogram.exe
myprogram/QtMultimedia/declarative_multimedia.dll
myprogram/QtQuick.2/qtquick2plugin.dll
I also tried
myprogram/myprogram.exe
myprogram/qml/QtMultimedia/declarative_multimedia.dll
myprogram/qml/QtQuick.2/qtquick2plugin.dll
But neither worked. Where do these plugins need to be placed relative to my executable? Do they have any "hidden" dependencies as with libEGL.dll for qwindows.dll?
- sierdzio Moderators
Plugins need to be put in <your app dir>/plugins, as outlined "here":. Make sure you read the note on ANGLE if you are using prebuild packages form Downloads page.
I had read that before, but I didn't notice at the time that ANGLE is included by default. I've added D3DCompiler_43.dll to my program next to my executable and placed the plugins as specified, but I'm still not able to deploy the application.
I used depends profiling on my application on another computer and got did see some Qt error messages pointing to the lines:
@import QtQuick 2.0
import QtMultimedia 5.0@
It says the modules "QtQuick" and "QtMultimedia" are not installed. I presume it really means the "QtQuick.2" and "QtMultimedia" folders I found in the directory at: Qt5.0.1\5.0.1\msvc2010\qml. However no matter where I put these folders the application cannot find them. How am I supposed to include "QML Plugins" (as opposed to regular plugins)?
One other .dll Depends found as missing was "Qt5MultimediaQuick_p.dll". While I've heard of similar dlls and plugins for everything else from Qt 4, I haven't heard of this one. What is it used for and do I need it?
[quote author="Scorx Ion" date="1363334790"]
Everything I try, I am stuck staring at a blank white screen with no information on what I am doing wrong. It is highly frustrating![/quote]
Heh I know what you mean, I'm stuck with the same stuff currently, trying to run the app built on x64 machine for VS2010 x86 on the same machine.
QtQuick 2.0 QML app, getting a full-screen window with nothing but blank white in it. Run from the QtCreator it works nicely. Sigh..
EDIT: Oh and a funny thing. Qt Widgets test app works, also QtQuick 1.1 test app - but none of the QtQuick 2.0 ones. Not our real app, nor a test hello world app. Just white screen. Interesting.
- Matti
I needed to include these files for deployment of my application:
D3DCompiler_43.dll
icudt49.dll
icuin49.dll
icuuc49.dll
libEGL.dll
libGLESv2.dll
Qt5Core.dll
Qt5Gui.dll
Qt5Qml.dll
Qt5Quick.dll
Qt5V8.dll
<DIR> QtQuick.2/(all of qml/QtQuick.2 goes here)
<DIR> platforms/qwindows.dll
Then I can deploy and run it on another machine.
[quote author="Torgeir" date="1363947185"]
<DIR> QtQuick.2/(all of qml/QtQuick.2 goes here)
[/quote]
We're building our .qml files into the executable via .qrc. What exactly are you putting into QtQuick.2/ directory ? I would prefer not to ship the qml files separately.. :o
- M
Oh Eureka! There indeed was a dir QtQuick.2/ under the SDK; copying this as-is under the application directory did the trick. Sweet, thanks to this thread we even have 2 hours to spare on our deadline. :D
- M
Ahem, next issue arises. We're using SQLite from QtQuick 2.0 projects javascript (QtQuick.LocalStorage 2.0) .. and now that we're deploying on windows outside the QtCreator sandbox, none of the SQL stuff works. I havent yet figured out how to make the app log into a console (CONFIG += console does not seem to do the trick) with console.log() so Im not getting much info whats wrong - we tried adding the sqldrivers plugin directory under the app dir but that didnt help. Whats needed..?
While Qt/QML is sweet, building the windows deployment package is a real pain in the arse :o
- Matti
It's really too cumbersome to deploy a qt/qml application on Windows.
After a lot of googling and trying now my app is working.
I am using SQLite in my project, but I am using the C++ library <QtSql/QSqlDatabase>.
I have:
exedir/sqldrivers/qsqlite.dll
exedir/platforms/qwindows.dll
exedir/QtQuick.2/...
exedir/qml/exe_name/qmlfiles.qml
exedir/icudt49.dll
exedir/icuin49.dll
exedir/icuuc49.dll
exedir/libEGL.dll
exedir/libGLESv2.dll
exedir/Qt5Core.dll
exedir/Qt5Gui.dll
exedir/Qt5Network.dll
exedir/Qt5Qml.dll
exedir/Qt5Quick.dll
exedir/Qt5Sql.dll
exedir/Qt5V8.dll
exedir/D3DCompiler_43.dll
exedir/exe
I am new to qt/qml, the most difficult part was to figure out where the plugin folder had to be.
Each plugin folder (sqldrivers, QtQuick.2 ...) you use have to be in the exe folder, right?
There is a way to change search path for plugins?
Yes theres QQmlEngine::addPluginPath() for that.
Aha so SQLite stuff works from C++ side with those, awesome, today's task will be to make it work somehow, hopefully with the existing code (from .pragma library javascript file..)
- M
Adding QtQuick/LocalStorage did the trick for the JS part..
My working set now is:
@
│ D3DCompiler_43.dll
│ icudt49.dll
│ icuin49.dll
│ icuuc49.dll
│ libEGL.dll
│ libGLESv2.dll
│ log.txt
│ binary.exe
│ binary.exe.embed.manifest
│ Qt5Core.dll
│ Qt5Gui.dll
│ Qt5Multimedia.dll
│ Qt5MultimediaQuick_p.dll
│ Qt5Network.dll
│ Qt5Qml.dll
│ Qt5Quick.dll
│ Qt5Sql.dll
│ Qt5V8.dll
│
├───platforms
│ qwindows.dll
│
├───QtMultimedia
│ declarative_multimedia.dll
│ plugins.qmltypes
│ qmldir
│ Video.qml
│
│
└───sqldrivers
qsqlite.dll
@
I really find it intolerable that the plugin system just silently fails when it cannot load something instead of showing a message (at least in console, preferable in a MessageBox). Totally nasty to debug.
- M
I had a blank screen after launching my app but when i added
@
@
the problem was resolved.
Thank you.
I'm a little confused by what the docs have under: Writing a qmltypes File found here:
First it says:
bq.
As such qmltypes files have no effect on the functionality of a QML module. Their only use is to allow tools such as Qt Creator to provide code completion, error checking and other functionality to users of your module.
It also says:
bq.
Any module that uses plugins should also ship a type description file.
So should we distribute "plugins.qmltypes" files with our app, provided that I am not interested in providing any editing capabilties to my end user on the shipped files? author="qttester5" date="1377757029"]
what is your grafic card ? have you tested it under other machines ?
If it was a problem with my graphics card, then why can the project run fine on the same machine, in a different VM that has Qt installed?
maybe the correct drivers are installed on the VM and not on the Real Machine.
No, I am using two identical VMs on same machine. One with and one without Qt.
In my App, I create a dialog QML object dynamically.
When deploying, I found that I had to add
QtQuick-->Controls
The DLL is under a further subdir, "Private"
I ended up deploying the whole Controls directory for an added 6MB to the package!
Thanks to the contributors above, I would never have got here without their encouragement.
Seems like a headache. For me this works:
- Use Microsoft's free tool "Process Explorer" to get a list of all DLLs used while running the exe in release mode via QT Creator (they can be showed in lower pane)
- Copy all of these to the same directory as the exe, not bothering with adding any subfilders
- koahnig Moderators
See also my answer in the "other post. ":
That tool is interesting. Thanks for sharing. ;-)
Actually I was a bit optimistic there.. The stand-alone exe ran on my primary PC but only because it had Qt installed, It didn't execute on another PC.
AFAIKT Process Explorer actually does reveal all DLLs used, with path. I did some further investigations on my primary PC by adding DLLs and folders to where Qt put my exe and renaming the folders Qt wants to use until I see in Proc Expl that it uses the ones I want it to, by making use of that Qt gives me an error message when starting the exe from within it with ctrl+R (otherwise it would be hard to guess which folder structre it wants).
A few conclusions from that adventure:
- It often needs more than the DLLs, so when you have identified a DLL it wants, then copy the entire directory with the DLL (you can try to optimize later by deleting files but the non-DLL files are usually very small, and the ones ending with "d" you can skip, they are for debug mode)
- When I rename a folder that Qt wants to use, sometimes it know about an alternate folder. For one group of DLLs, Qt itself took over the DLLs and fetched them in such an alternate folder, so they were no longer under my app in Proc Expl but under Qt, and I had to reboot Qt to stop it from doing that.
The folders imageformats, platforms, QtQuick and QtQuick.2 should be in the exe's folder, together with the rest of the DLLs; eactly which, you clearly see in Proc Expl. Could add screenshot but can't see the forum supports it.
Still doesn't work though. Don't now why, but I'd suspect it's something other than DLLs missing. And I don't have more time for this right now.
PS One DLL you and everybody else seem to require is Qt5V8.dll but it doesn't exist on my PC. Perhaps from an older version?
- JKSH Moderators
[quote author="DavidGGG" date="1393184567"]Actually I was a bit optimistic there.. The stand-alone exe ran on my primary PC but only because it had Qt installed, It didn't execute on another PC.[/quote]To check a deployment package on your development PC, rename your Qt installation folder. This effectively turns your PC into a Qt-free environment, so when you launch your application it won't use your development DLLs.
[quote]Still doesn't work though. Don't now why, but I'd suspect it's something other than DLLs missing. And I don't have more time for this right now.[/quote]If you use QML, you also need the qmldir files. See
[quote]PS One DLL you and everybody else seem to require is Qt5V8.dll but it doesn't exist on my PC. Perhaps from an older version?[/quote]V8 is the JavaScript engine used by QML in Qt 5.0 and 5.1. It's no longer used in Qt 5.2.
[quote]Could add screenshot but can't see the forum supports it.[/quote]For now, you'll need to upload it to an external site. The forum can display external images. Anyway, there is a screenshot of the deployment folder at
- ermylistru. | https://forum.qt.io/topic/25193/deploying-qt5-on-windows-7-too-difficult | CC-MAIN-2017-43 | refinedweb | 2,426 | 66.84 |
AIntroduction and Background TCP programming is one of the most interesting sections, as far as work is concerned, in network programming. On the Ubuntu environment, I enjoy doing TCP programming using .NET Core and the native Ubuntu scripts to communicate with the TCP Servers. Previously, I wrote an article about TCP Servers and clients in .NET framework itself. Now, .NET framework itself is going to be open source. I wanted to write something about the communication channels between both of them. Basically, I am just testing what works in the new .NET environment, as compared to how it was working in the old, yet the real, .NET framework environment.
In this post, however, I have a bunch of extras available for you. I will be showing you the methods that you are going to use to build your own TCP Server, using .NET Core assemblies and how you are going to communicate with them over the network. For the client applications, I won’t be building anything at all. Instead, I will be using the native scripts that allow communication over TCP and UDP protocols.
The agenda is something like this:
These are a few things that I will walk you through in this post and I will clarify the purpose of everything as well.
We are not going to build any special application here, but TCP is the most widely-used protocol in Transport layer (in contrast to UDP) and most of the Applications and Services that we use regularly rely on this protocol. HTTP, FTP, SMTP and all other similar protocols rely directly on TCP and use the sockets (ports) for the communication, based on TCP protocols. Hence, you can kickstart your Server from a minimal program and build a vast Enterprise Application on top of it. It can scale as much as needed by the Application programming framework and the clients (or users), who are connected to it.
I am, however, not going to talk about building those complex applications, but I will give you an easy overview of the TCP Server and the client based communication. Why write this post? I will be covering TCP consumption at a cross-platform environment. I will just create the Server using .NET Core. The rest will be done natively and I will use the “nc” command in Ubuntu to communicate with the server that I have just created. Hence, the idea is to allow you to understand how you can build a Server in .NET Core for efficiency and control and then how you can communicate with that Server, using multiple platforms and their Services, that allow the users to communicate with TCP servers. So, let’s get started. Building the server-side In .NET environments, System.Net namespaces contains all of the reference material that may be used for learning and programming purposes. On the Server-side programming tasks, I am going to use the TcpListener object to handle the incoming TCP traffic. Basically, this is a native TCP part and you will be getting used to it quickly. I have been using this object and the programs that consume this object in their lifetime for many purposes in my own personal applications and on a few network-based applications, where client applications, devices and machines are able to communicate with my TCP Server through the router (modem, or the WLAN hotspot etc.). This way, I can create a central Server that communicates using TCP protocols and the clients who can communicate using TCP can also send or receive data from this Server. I will however not go into the depth of submitting and transmitting the data over the network in many formats. For the sake of simplicity, I will keep things very simple and straightforward, due to which I will have to work in a plain-text format.
The basic demonstration of how a Server-client communication works in a TCP environment is demonstrated in the following bitmap graphic art, that I created previously:
Figure 1: Server-client setup
As shown, the Server controls the way the resources are being used and consumed. The clients can use any device which can communicate using TCP protocol over the network. The Server handles the requests and grants an access to the resources. Just like interacting with any other program, TCP clients can interact with the TCP Servers, send commands, send requests, send option selections (such as selecting which service to trigger) and so on. TCP Servers then handle these requests and generate the response based on those requests and the values for the data that are being passed. TCP servers can:
In .NET Core, TCP listeners allow you to handle the available number of bytes, by using a static buffer of a fixed size. Sometimes, the data may not be sent to fill the buffer or sometimes the buffer may not be enough to be able to cover all of the buffer.
The source code for running the Server is just as simple as:
This step hosts the Server. At this stage, the program that hosts the Server should be kept active and running otherwise the program would terminate, closing the Server itself. Have a look at the code, given below:
It is the second function that does most of the jobs in the program. This is the place, where we can add asynchronous patterns and multi threading to support multiple clients to connect at the same time. I am, however not going to dive any deeper in that section. So, the proper code to actually start up the Server and listen to the clients is shown below:
To run the program, just do the following,
dotnet run The output was, Figure 2: Server started
As you can see, the TCP Server started at the IP, and we specified the port that we passed in the function call. Leaving the rest to client-side
As I had talked about before, I will be using a native TCP client instead of the TCPClient object of .NET core, so that you can use the server even when you don’t have .NET installed on the system (such as in cases of using TCPClient object of .NET framework). In this post, I am going to use “netcat” command script in Unix (Linux and derivative) systems. The communication can be done simply. You can learn more about this script from the online resources as I don’t want to dig any deeper. I just want to demonstrate the usage. To learn more, you can go to any of the following URLs and learn more about this:
You will be able to understand how to use this command to act as a client. This also allows you to create a program script that acts as a Server and listens to the requests on the network, but we are not interested in those factors. Instead, we are just looking forward to sending a request to the Server and passing on some data that will be shown on the screen.
We will pass them as the arguments to the command,
$ nc 127.0.0.1 5678
The following screen appears (our Server takes the request and returns a message)
Figure 3: Client connected
(Look at the code for our Server for more on this.)
Next, we can send the data from this terminal, as it is asking for more data. We will send few bytes of the data and then send ‘quit’ to terminate the connection. Let’s see how that works in the context.
Figure 4: Client sending the data to the server
We sent three messages to the Server. All of them were checked and finally on the last message, the stream was closed and the terminal started asking for more commands (instead of asking for more data). Why is that so? If you pay attention, you will see that the “quit” command has been set to the terminator of the connection. When we send this command, the connection is terminated and we need to start the connection once again. Now, let’s see on the other side.
Figure 5: Server-side message logging
See how the behavior changes here with each event. Once our client connects, there is a message being logged here: “Client connected. Waiting for data.” This message is shown, when the client is connected. You can also log the time and other details for that client. We are passed with the data and after the “quit”, you can see there is a log of “Closing connection.” It should have also been shown on the other end, but sadly, I missed this point. You must have gotten the idea of using the clients to connect to the Server and send the data. Points of Interest Finally, this post was a short introduction to TCP programming in .NET Core and how you can abstract the entire concept of this, by using other platform services to communicate with the Servers.
View All | http://www.c-sharpcorner.com/article/building-a-tcp-server-in-net-core-on-ubuntu/ | CC-MAIN-2017-34 | refinedweb | 1,499 | 70.13 |
Hi all,
I am trying to get the examples from
to work.
I found that the 3D code is already included in matplotlib (SVN
version), but that it does not work:
- axes3d.py makes use of pylab, but it is not imported.
- text_update_coords in axis3d.py refers to self._mytext.foo, but
TextWithDash has been updated to use the form Text.foo(self,...)
instead.
- The TextWithDash class's doesn't have a_twd_window_extent
property. Instead of assigning it in update_coords, it should be
assigned in __init__.
- When working with matrices, the following occurs:
def bar(self,M=None):
M = somematrix or M
which is not allowed. It should be
if nx.any(somematrix): M = somematrix
But, after fixing all these problems, I still can't get it to plot.
It might be worth including surface.py in the examples directory, as a
test, to guarantee that the 3D code gets updated with the rest.
It could be that I am missing something completely obvious -- I'd
appreciate any help in getting it running!
Cheers
Stéfan | https://discourse.matplotlib.org/t/status-of-3d-plotting/5240 | CC-MAIN-2021-43 | refinedweb | 174 | 68.47 |
NAMEtowlower, towlower_l - convert a wide character to lowercase
SYNOPSIS
#include <wctype.h>
wint_t towlower(wint_t wc); wint_t towlower_l(wint_t wc, locale_t locale);
Feature Test Macro Requirements for glibc (see feature_test_macros(7)):
towlower_l():
Since glibc 2.10: _XOPEN_SOURCE >= 700 Before glibc 2.10: _GNU_SOURCE
DESCRIPTIONThe towlower() function is the wide-character equivalent of the tolower(3) function. If wc is an uppercase wide character, and there exists a lowercase equivalent in the current locale, it returns the lowercase equivalent of wc. In all other cases, wc is returned unchanged.
The towlower_l() function performs the same task, but performs the conversion based on the character type information in the locale specified by locale. The behavior of towlower lowercase, towlower() returns its lowercase equivalent; otherwise it returns wc.
VERSIONSThe towlower_l() function first appeared in glibc 2.3.
ATTRIBUTESFor an explanation of the terms used in this section, see attributes(7).
CONFORMING TOtowlower(): C99, POSIX.1-2001 (XSI); present as an XSI extension in POSIX.1-2008, but marked obsolete.
towlower_l(): POSIX.1-2008.
NOTESThe behavior of these functions depends on the LC_CTYPE category of the locale.
These functions are not very appropriate for dealing with Unicode characters, because Unicode knows about three cases: upper, lower, and title case. | https://man.archlinux.org/man/towlower.3.en | CC-MAIN-2022-05 | refinedweb | 205 | 50.23 |
Mullá Husayn (1813 – 2 February. He was the first person to profess belief in the Báb as the promised Mahdi of Islam and a Manifestation of God, founding a new independent religion.[1] The title of Bábu'l-Báb was bestowed upon him by the Báb in recognition of his status as the first Bábí.
As a young man Mullá Husayn studied Usuli Shia theology, becoming an authorized member of the Shia clerical order at the age of 21. He later became a follower of the millenarian Shaykhi school, studying under its leader Siyyid Kazim Rashti and traveling to debate prominent Usuli clerics to gain support for Rashti's teachings.
After Rashti's death, Mullá Husayn led a group of Shaykhis who traveled in search of the Mahdi. On 22 May 1844, in Shiraz, Mullá Husayn became the first person to profess belief in the Báb as the Mahdi, and the first follower of the Báb's religion, known as Bábism. He was appointed as the first of the Báb's apostles, called the Letters of the Living. The anniversary of his conversion is celebrated annually as a holy day in the Baháʼí Faith.
As a Letter of the Living he served as a prominent Bábí evangelist and leader. His travels and public preaching were instrumental in spreading the religion throughout Persia, allowing him to come into contact with many prominent clerics and government officials, including Baháʼu'lláh and Mohammad Shah Qajar. He is often mentioned in Baháʼí literature as a paragon of courage and spiritual excellence. He led the Bábí combatants at the Battle of Fort Shaykh Tabarsi, and was killed in that battle on 2 February 1849. Mullá Husayn is regarded as a significant martyr in Bábism and the Baháʼí Faith and accorded a high spiritual station in both religions as the first to believe in the Báb and a prominent participant in the perceived fulfillment of many elements of Islamic eschatology.
Biography
Early life and education (1813–1843)
Mullá Husayn was born in 1813 near Boshruyeh in the South Khorasan province of the Persian Empire to a wealthy and established family of the town. His name at birth was Muhammad Husayn; the honorific Mullá became associated with him at a young age, perhaps in recognition for a leadership role he took on as a child. It is not part of his given name. His father Hajji Mulláh Abdullah was a dyer; his mother was a poet known for her piety and knowledge. They had five children, of whom three would become significant Bábís.[2]
Like most young boys of the era[3] he received a minimal grammar school education at the local maktab (school) where he studied the Quran, reading, writing and basic arithmetic. Although he would later distinguish himself as a military leader, and traverse the entirety of Persia on foot multiple times, Mullá Husayn is reported to have been in poor health from a young age.[4] Contemporary reports indicate that he received treatment for epilepsy and heart palpitations. A critic of the Bábí movement suggested that he received early training in swordsmanship, while childhood friends deny this, indicating he often had difficulty even with the physical exertion involved in lengthy writing sessions as a student and in his later work as a scribe and copyist.[5]
At the age of twelve he left school and pursued higher education in the madrasa (seminary) of Mashhad and Isfahan–which included lessons in Persian literature and the Qurʼan–while working to master the art of debate. Scholars have suggested that his family members practiced Ismaʻili Shiʻism, but in Mashhad and Isfahan he studied Muslim theology and jurisprudence under prominent teachers from the Usuli school.[6] In Mashhad he studied at the madrasa of Mirzá Jaf'ar, which exists to this day as one college of the larger Razavi University of Islamic Sciences.[7]
By 21, he had been licensed as an Usuli mujtahid (cleric), granting him the publicly recognized right to preach in mosques, take on students of theology, and issue fatwas (authoritative legal opinion). During his studies in Mashhad he became attracted to the teachings of the Shaykhi school of Shia Islam, founded by Shaykh Ahmad Ahsá'í and led at the time by his successor, Siyyid Kázim Rashtí. His interest in Shayki teachings seems to have emerged in Mashhad, but the exact origin of his interest is unknown; an early mystical bent and a desire to fuse scholarship with "inner knowledge" may have attracted him to the intuitive hermeneutical techniques used by the Shaykis.[8] On the completion of his studies he was offered a position of religious leadership in his hometown, but declined.[9] After a brief period in Tehran, in 1835 he traveled to the Shia shrine city of Karbala in the Ottoman Empire to study directly under Siyyid Kázim.[10] His father had passed away by this point, but all the surviving family members except one sister—already married—chose to move with him to Karbala. [11]
Siyyid Kázim taught his students to expect the fulfillment of the messianic expectations of Twelver Shiʻism in their lifetimes, particularly emphasizing that the Qa'im, or Mahdi, was already living.[12] Mullá Husayn studied under Siyyid Kázim from 1835 until 1843, during which time he was often asked by his teacher to travel to Persia to debate publicly with orthodox Shia ulama to gain more widespread Persian support for Shaykism.[13][14] During this period he wrote at least two books and gained a reputation as a significant student of Siyyid Kázim, being asked on occasion to answer questions on his teacher's behalf and gaining permission to supervise students of his own.[15][9] He received a stipend from the school of Siyyid Kázim for work as a scribe and copyist.[16] Baháʼí sources traditionally suggest that Siyyid Kázim entrusted Mullá Husayn with secret teachings which he did not share with the larger body of Shaykis—a claim which is evocative of his later role in Bábism, but difficult to verify.[17]
Near the end of his life, Siyyid Kázim repeatedly instructed his followers to disperse throughout Persia and surrounding lands in search of the Mahdi.Following Siyyid Kázim’s death on 31 December 1843 a significant number of Shaykis recognized Mullá Husayn as his only worthy successor, and he immediately set out in search of the promised Mahdi. Some of Siyyid Kázim’s followers expected that Mullá Husayn would declare himself to be the Mahdi, or at least take up leadership of the Shaykis, both suggestions which he forcefully refuted.[18][19]
Mullá Husayn, accompanied by his brother Muhammad-Hasan and nephew Muhammad-Baqir, set off from Karbala to Najaf and spent forty days in the Great Mosque of Kufa sequestered in a state of prayer and fasting. The Mosque in Kufa was chosen as the site of their retreat due to its association with the martyrdom of the Imam Ali; Shakyis often engaged in prolonged retreats as a method for developing discernment.[20] After a number of days they were joined by thirteen Shaykis, including Mullá Aliy-i-Bastami, who accompanied them in spiritual preparation for their journey.[21][22]
Near the end of the retreat, Mullá Husayn received a letter which appeared to have been written by Siyyid Kázim before his death; while his companions assumed that the letter contained an appointment from Siyyid Kázim naming Mullá Husayn as his successor, it contained only veiled instructions for the coming journey. Mullá Husayn is reported to have publicly burst into tears upon reading the posthumous instructions of Siyyid Kázim and realizing the enormity and uncertainty to his task.[23]
After celebrating the Muslim holiday of Mawlid, marking the completion of forty days spent at the Great Mosque of Kufa, Mullá Husayn and his companions visited the Tomb of the Imam Ali in Najaf and proceeded toward Búshihr, on the Persian Gulf. After some time there, at Mullá Husayn's urging, they continued to Shiraz in the Province of Fars.[24] At this point they had traveled on foot for approximately 600 miles with no clear intended destination and no guide for their journey except Siyyid Kázim's dying advice to Mullá Husayn.[25] Upon their arrival in Shiraz, Mullá Husayn instructed his companions to proceed to the Vakil Mosque where he would join them for evening prayers.[26]
Conversion to Bábism (1844)
In Shiraz, on 22 May 1844, he encountered Sayyed ʿAli Muhammad Shirāzi, the Báb, who invited Mullá Husayn to his home. On that night Mullá Husayn told him that he was searching for the Promised Mahdi and shared with him some of the characteristics expected of the Mahdi which he had learned from Siyyid Kázim. The Báb declared that he manifested all of the characteristics of the Mahdi. Mullá Husayn remained uncertain until the Báb had replied satisfactorily to all of Mullá Husayn's questions and had written in his presence, with extreme rapidity, a long commentary on the Surah of Joseph, which has come to be known as the Qayyúmu'l-Asmáʼ ("Maintainer of the Divine Names") and is considered the Báb's first revealed work.[27] Siyyid Kázim had apparently—when requested by Mullá Husayn to do so himself—predicted that the Mahdi would reveal, unasked, a commentary on this Surah. Nabil's Narrative records Mullá Husayn's account of the signs he had been given by the dying Siyyid Kázim to recognize the Mahdi and indicates that Mullá Husayn was quickly convinced that the Báb satisfied these conditions.[28][29] While the Báb had already revealed his religious mission to his wife, Khadíjih-Bagum and his household servant, Mubarak about a month previous,[30] Mullá Husayn became the first person to independently recognize him as the Mahdi and the prophet-founder of a new religion, and was appointed as the first member of the Báb's "Letters of the Living" (Ḥurúfu'l-ḥayy in Arabic).[29] The anniversary of this declaration is observed as a holy day by Baháʼí communities around the world and the beginning of the religions of Bábism and the Baháʼí Faith.[31][32]
Role as a Letter of the Living (1844–1849)
After his recognition of the Báb, Mullá Husayn was appointed as the first member of the Letters of the Living. The Báb forbade Mullá Husayn from actively spreading his newfound religion, and instead explained that seventeen others would have to independently recognize him as the Mahdi before he would allow the Bábi Religion to be openly spread. During his time in Shiraz, Mullá Husayn took up a teaching position in the Vakil mosque, where he gathered a large number of students which included notable clerics in Shiraz.[33] During his lectures in Shiraz, he never directly referenced the Báb, but his regular meetings with the Báb inspired the content of his lectures.[34] Within five months, seventeen other disciples of Siyyid Kázim had recognized the Báb as sent by God and joined Mullá Husayn among the ranks of the Letters of the Living.[35] Among these first to convert to Bábism were Mullá Husayn's companions on his journey from Karbala to Shiraz: Muḥammad-Ḥasan Bushrú'í, Muḥammad-Báqir Bushrú'í and Mullá ʻAlí Basṭámí.[36] The Báb addressed an epistle to each of the Letters of the Living and tasked them with spreading his religion throughout the country and surrounding regions. [37]
When the Báb determined to leave Shiraz on pilgrimage to Mecca, he instructed Mullá Husayn to travel to Isfahan, Kashan, Qom, Tehran and Khorasan Province, spreading Bábism as he traveled.[38] Nabil indicates that Mullá Husayn was displeased when Quddús, the 18th Letter of the Living, was chosen to accompany the Báb on his pilgrimage rather than himself. The Báb is recorded to have indicated that Mullá Husayn would discover an important secret in Tehran, and would be able to effectively defend Bábism against opposition in the other cities of his journey.[39]
Isfahan
In Isfahan, Mullá Husayn began teaching in the Nimavar school and used his authority as a mujtahid and his reputation as a disciple of Siyyid Kázim to spread the new teachings of Bábism.[40] He preached his new religion publicly and was reported to have drawn significant public attention:.[41]— Arthur de Gobineau, Les Religions et les Philosophies dans l'Asie Centrale
He was opposed by some Shaykis and orthodox Shias in the city, but won the tacit support of the most prominent Mullá in the city and was able to continue preaching for the duration of his stay.[42] A number of residents accepted the message of the Báb and converted to Bábism as a result of Mullá Husayn's teaching.[43] In the writings of the Báb as well as later Baháʼí hagiography, the example of the first Isfahani Bábí, a wheat sifter of modest means, is often used as an example of the diversity of those who accepted the Báb's teachings and the corruption of the Persian religious elites:.[44]— The Bab, The Persian Bayán
In addition to the wheat sifter, a few prominent Siyyids in Isfahan were converted by Mullá Husayn.[45]
Tehran
After his time in Isfahan, Mullá Husayn visited Kashan and Qom, spreading the teachings of the Báb in both cities. From Qom he continued on to Tehran, where he again made use of his mujtahid's license to take up residence in a local madrasa. As in Isfahan, he was opposed by members of the remaining Shayki community who felt he had abandoned his role as a leading follower of Siyyid Kázim to take up membership in a heretical sect.[46] At the request of these Shaykis, he did not take up a formal teaching role in Tehran as he had in Isfahan, and spent little time in the madrasa itself during his stay. Gobineau reports that in spite of not preaching publicly in Tehran, Mullá Husayn was received by a number of prominent residents, including the king Mohammad Shah Qajar and his prime minister and shared the teachings and writings of the Báb with them in these private meetings.[47]
In Tehran he befriended Mullá Muhammad-i-Mu'allim, a student of one of Mullá Husayn's leading opponents among the Shaykis in Tehran. Through Mullá Muhammad, he learned of the presence of Mírzá Ḥusayn-ʻAlí Núrí—the son of a prominent nobleman—in Tehran. At Mullá Husayn's request, Mullá Muhammad delivered a scroll containing some of the writings of the Báb to the home of Mírzá Ḥusayn-ʻAlí Núrí. Both Mírzá Ḥusayn-ʻAlí Núrí and his brother Mírzá Músá converted to Bábism as a result of this exchange.[48] Nineteen years after the declaration of the Báb to Mulla Husayn, Mírzá Ḥusayn-ʻAlí Núrí pronounced himself to be the prophet-successor to the Báb, took on the title Baháʼu'lláh, and founded the Baháʼí Faith.[49] Baháʼís regard Mullá Husayn's exchange with Baháʼu'lláh to have been a fulfillment of the Báb's promise that Mullá Husayn would discover a secret of great importance in Tehran. After receiving news of Baháʼu'lláh's conversion, Mullá Husayn departed from Tehran for Mashhad, in his home province of Khorasan.
Mashhad
As news of his preaching spread and the number of converts to Bábism continued to grow throughout the country, Mullá Husayn no longer arrived unexpected in new cities. In Mashhad, public debate about the religion of the Báb was already ongoing when he arrived, and the clergy had organized to debate and oppose him. He preached from the pulpit of the Goharshad Mosque in Mashhad and succeeded in converting a number of prominent ecclesiastical leaders of Mashhad through public debates and private audiences. From Mashhad, Mullá Husayn wrote to the Báb, sharing news of conversions in Isfahan, and Tehran, with particular emphasis on the conversion and subsequent evangelism efforts of Baháʼu'lláh.[50]
Shiraz
In the spring of 1845 Mullá Husayn received news that Bábís wishing to visit the Báb after his return from pilgrimage had been instructed to gather in Isfahan. Mullá Husayn, currently en route to Karbala, met with a group of pilgrims and in Isfahan. After only a few days, he received news that Quddús and another prominent Bábí had been arrested in Shiraz after their pilgrimage with the Báb and publicly tortured and banished, while the Báb was under house arrest in the home of his uncle Hajji Mirza Sayyid 'Ali.[51]
Along with his brother and nephew, Mullá Husayn made their way into Shiraz overnight in disguise. After making contact with that uncle of the Báb, the three of them were able to take up temporary residence in Shiraz and received permission to invite the Bábís gathered in Isfahan to gradually make their way into the city.[52]
As the number of Bábís in Shiraz grew, opposition to the Báb and Mullá Husayn increased, particularly when the Báb began to give public addresses and sermons, and was engaged in debates by local clerics. The Báb eventually dismissed all the Bábís resident in Shiraz, including Mullá Husayn, whom he directed to return to Khorasan.[53]
Maku
After being directed by the Báb to return to Khorasan, Mullá Husayn continued spreading Babism in Mashhad and throughout the province. During his time in Mashhad, a rebellion against the government of the Shah broke out in Khorasan, involving an alliance between local Kurdish tribes and the sheriff of Mashhad. Mullá Husayn learned that the leader of the rebellion hoped to secure his support as a representative of the growing Bábi community, and decided on leaving Mashhad to avoid entangling the local Bábís in the chaos expected to result when the forces of the Shah eventually arrived.[54] About the same time news arrived that the Báb had been arrested and imprisoned in the mountain fortress of Maku near the Turkish border,[55] following the increased controversy surrounding the Báb who was sent from Shiraz to Isfahan and then being ordered to Tehran by the Shah. In early 1848 Mullá Husayn embarked on foot from Mashhad—on the eastern edge of Persia–to Tehran, with the intention of continuing on to Maku—located in the far northwest. On his journey he was solely accompanied by a Bábí servant named Qambar-Ali. In Tehran he was received by Mírzá Músá, half-brother to Baháʼu'lláh, and a group of local Bábís and met briefly with Baháʼu'lláh in a private interview. No known record of that meeting survives.[54]
He arrived in Maku in March 1848, having walked over 2000 miles in no more than three months. In Maku, the Báb had originally been held under very strict guard, but after two weeks the government appointed frontier officer, ʻAlí Khán-i-Máh-Kúʼí, converted to Bábism.[56] At the Bab's instruction ʻAlí Khán continued to carry out the Báb's imprisonment order, but allowed pilgrims to visit him and himself visited regularly. When Mullá Husayn arrived in Maku, he was welcomed by ʻAlí Khán, who reported having foreseen his arrival in a dream. On the first day of his time in Maku, the group of Bábís celebrated the holiday of Nowruz with the Báb.[57]
Mullá Husayn stayed in Maku with the Báb for nine days,[58] during which accounts report that the two cherished each other's company in the relative peace of imprisonment in a remote province. Mullá Husayn slept in the Báb's quarters and received pilgrims alongside the Báb during the days. Eventually the Báb ordered Mullá Husayn to depart for Mazandaran Province, reportedly offering parting instructions to Mullá Husayn and Qambar-Ali. In his parting address the Báb praised Qambar-Ali, comparing him to the groom of the Imam Ali, and lauded Mullá Husayn's courage and heroism; Nabil reports that the Báb promised Mullá Husayn that in Mazandaran "God's hidden treasure" would be revealed to him and Mullá Husayn's most important task would become clear. Mullá Husayn and Qambar-Ali left Maku carrying copies of significant works of the Báb which had been written during his stay in Maku, which they shared with Bábís during their journey to Mazandaran. [59][60]
A few days after Mullá Husayn departed from Maku, he received news that by order of the Prime Minister the Báb was to be transferred to the castle of Chehriq.[61]
Mazandaran
On his way to Mazandaran, he stopped briefly in towns with resident Bábis, sharing news of the Báb and encouraging the Bábis, who were facing increasing public opposition. In Tehran he again had a chance to meet with Baháʼu'lláh, who encouraged him in turn.[62]
Mullá Husayn was received on his arrival in Barforush, Mazandaran, by Quddús, the 18th Letter of the Living. Although the two had met previously, they had never spent much time together and their last interaction had been tinged with Mullá Husayn's disappointment when Quddús was chosen to accompany the Báb on pilgrimage rather than himself. During his stay in Barforush he was a guest in the house of Quddús and was able to consort with the large number of converts and admirers Quddús had in that city.[63]
Nabil reports that Mullá Husayn shared with Quddús the Báb's promise that in Mazandaran he would find a "hidden treasure which shall be revealed to you, a treasure which will unveil to your eyes the character of the task you are destined to perform."[58] After reading some of the writings of Quddús, Mullá Husayn became convinced that Quddús himself was the hidden treasure that the Báb had referred to. [64]Previously many of the Bábís had thought of Mullá Husayn as the most significant figure in the movement after Quddús; after this interaction Mullá Husayn constantly deferred to Quddús, going so far as to serve his meals and obey his instructions with a reverence previously reserved for those of the Báb. Quddús's role as the chief of the Letters of the Living was later confirmed by the Báb.[65]
In Barforush Mullá Husayn engaged the leading Muslim cleric of the city in a public debate with the goal of either converting him or convincing him to reduce his public denunciation of the Bábis. After failing to convince him, Mullá Husayn–at the instruction of Quddús–left Barfurush to return to Mashhad once again.[66]
The Bábíyyih of Mashhad
In Mashhad, following the instructions of Quddús, he set out to increase the capacity of the Letters of the Living to engage in systematic preaching and conversion efforts. With the assistance of local Bábís he purchased a plot of land and erected a building intended to serve as a permanent residence for himself and Quddús as well as a center of Bábí preaching and community life. Shortly after its completion, Mullá Husayn and Quddús took up residence in the center–christened the Bábíyyih of Mashhad. The number of Bábís in Mashhad grew substantially in the next few months, and the Bábíyyih served as a center of organization for evangelism efforts throughout the region. [67] Some sources suggest that the Bábíyyih may have been set up as early as 1844, but it does not seem to have come into use as a center of organization until 1848.[68]
This period yielded a great deal of success for Mullá Husayn and Quddús, Bábí communities sprouted throughout Khorasan Province, including converts from a wide array of economic backgrounds. In Mullá Husayn's hometown of Boshruyeh, a group of 60 active Bábís had emerged, with thousands turning out to attend Mullá Husayn's sermons or pray with him. Widespread Shakyi sympathies among the local clerics seem to have laid a fertile ground for the growth of Bábism.[69]
A few months after the construction of the Bábíyyih, a large number of Bábís gathered in the village of Badasht for the purpose of seeking consensus on the core spiritual beliefs of Bábism and making plans for how the Bábí community should respond to increasing persecution and the continued imprisonment of the Báb. The Conference of Badasht was largely organized and funded by Baháʼu'lláh, and Quddús and Táhirih were also major players in the conference — an event that would mark the declared independence of the Bábí religion from Islam.[70] During the weeks before the conference, large numbers of Bábís travelled to Mashhad from around the country, angering city authorities to the extent that Mullá Husayn's personal attendant was arrested and publicly tortured in an effort to drive Mullá Husayn from the city.[71]
Quddús left Mullá Husayn in Mashhad during the conference with the mandate of maintaining the work of the Bábíyyih in his absence.[72] As the number of converts in Mashhad began to grow, opposition from secular and religious authorities increased to the point that Mullá Husayn was forced to leave the city before Quddús could return from Badasht.[73]
Before departing from Mashhad, Mullá Husayn received large groups of visitors, along with approximately two hundred Bábí men who committed to traveling with him. Before they were able to leave the city, Mullá Husayn received a message from the Báb containing new directions. The Báb informed him that Quddús had been imprisoned in his hometown of Barfurush, and ordered Mullá Husayn and his companions to come to his aid. Further, Mullá Husayn was, in apparent fulfillment of Islamic eschatological predictions, to don the Báb's own green turban, and lead his companions under a black flag. The Báb also granted Mullá Husayn a new name: Siyyid ʻAlí. The granting of a new name was significant because the wearing of a green turban was forbidden in Shia Islam to anyone but a siyyid—a descendant of the Prophet Muhammad through his daughter Fatimah.[74]
Mazandaran Upheaval (1848–1849)
Skirmish in Barfurush
Mullá Husayn and his two hundred Bábí companions departed from Mashhad for Barfurush on 21 July 1848, and gathered additional followers along the way. On the third day, after a warning from Mullá Husayn about the danger of their mission to free Quddús, twenty members of the party left the group to return home. The group marched under a black banner prepared by Mullá Husayn which they raised in reference to the Black Standard, an element of prophecy in Islamic eschatology about the end of days.[75][76]
The march was rebuffed outside the town of Barfurush by an armed group of residents led by the chief cleric. Mullá Husayn reportedly ordered his men to discard their possessions and at first made them withhold from engaging in battle, saying:
Leave behind all your belongings, and be content with your horses and swords, so that all may see that you have no interest in earthly things, and that you have no desire to guard your own property, much less to covet the property of others! [77]— Mullá Husayn, quoted in Nabil's Narrative
The first casualty of the encounter was Siyyid Ridá—Mullá Husayn's attendant—who was shot in the chest from a distance. After Siyyid Ridá's death, Mullá Husayn allowed his followers to begin defending themselves. [78]
Although most sources agree that Mullá Husayn was physically weak and suffered from chronic illness, narratives of the battle depict him as an almost insurmountable combatant.[4][79][80] One popular story from Nabil's Narrative describes him engaging the soldier who shot Siyyid Ridá and with a single blow of his sword cutting through the trunk of an intervening tree, the man's musket, and the soldier's body.[81] A combatant in the Barfurushi force sent half of the severed musket by messenger to the Prime Minister as evidence of the Bábis' ferocity—attempting to allay criticism from the Prime Minister for failing to defeat an informal militia.[82] The encounter was elegized by a number of poets throughout Persia.[83]
Construction of Fort Tabarsi
After the encounter at Barfurush the group constructed defensive fortifications at the nearby Shrine of Shaykh Tabarsi, a local saint. Upon arriving at the shrine, the Bábís, numbering a little over 300 according to Bábí and Baháʼí sources and according to court historians, were now under imminent attack from government forces, yet their numbers swelled to between 540 and 600 people as Bábís from the region streamed to their defense. [75] The Bábí combatants represented almost every social class, including clergymen, merchants, craftsmen, and representatives of the landed nobility; the youngest was a twelve-year-old boy.[84] The distribution of urban and rural participants has been shown to be roughly identical to the makeup of Persian society at the time, demonstrating the wide array of respondents to the religion of the Báb. Unlike at later Bábí upheavals where women would play a significant, or even majority role, all of the participants at Tabarsi were male.[85]
At Tabarsi Mullá Husayn instituted a degree of martial order, centralizing food production, construction, and defensive duty. He appointed his nephew Muhammad-Baqir as his lieutenant. During their first day at Tabarsi they gained the patronage of a wealthy man from a nearby village who converted to Bábism and provided them supplies. With so many people to feed, the makeshift fort attracted a small collection of merchants from the region.[86]
After the completion of the fort, the gathered Bábís were visited by Baháʼu'lláh, who inspected the fort and expressed his pleasure with the construction and organization. He advised Mullá Husayn to send a group of men to Sari, where Quddús was now imprisoned, to bring Quddús to the fort. Before leaving Baháʼu'lláh consulted with Mullá Husayn on some matters of strategy and expressed his desire to return to assist the gathered Bábís. [87] Mullá Husayn sent seven men to Sari with instructions to return with Quddús; they did so with the willing consent of the cleric in whose home he was held. During the mission to retrieve Quddús, Mullá Husayn instructed the Bábís at Tabarsi that after Quddús's arrival they should regard Quddús as the commanding officer of the company, and Mullá Husayn only as his lieutenant. [88] Upon his arrival, Quddús instituted a missionary element to the fort, sending representatives to the villages in the area and attracting a stream of new converts, many of whom took up residence in the fort. [89]
Army of ʻAbdu'lláh Khán
As conversions in the area increased, the chief cleric of Barfurush wrote to the Shah, indicating that a rebellion was underway in the region. Naser al-Din Shah Qajar, then only 17, had just taken up the throne after his father's death, and responded quickly to news of commotion in Mazandaran. He issued an edict authorizing a government official in Mazandaran, ʻAbdu'lláh Khán, to gather an army and quell the forces gathered at Tabarsi. [90]
ʻAbdu'lláh Khán besieged the fort with twelve thousand men, and cut of their supply of water and food. Three days of heavy rain and snow followed his arrival, providing water for the Bábís and decimating the army's earth fortifications. ʻAbdu'lláh Khán and his officers took up residence in a nearby village to avoid the weather, and were absent when, on the fourth day of the siege, Quddús ordered the Bábís to disperse his army. The outnumbered Bábí's took the army by surprise and pushed them back to the village where ʻAbdu'lláh Khán was living, where they engaged and killed ʻAbdu'lláh Khán and every officer of his army. At this point Quddús ordered a retreat. Four hundred of the Shah's soldiers were killed, and around 100 of their horses captured by the Bábís. Upon returning to the fort, Quddús warned the Bábís that a larger, better organized army would come next, and ordered them to expand the fort. [91] After this point, the fort walls reached ten meters tall, with a deep ditch surrounding it, a well for water, and tunnels and storehouses dug underground for refuge and storage.[92]
Army of Prince Mihdí-Qulí Mírzá
After the defeat of ʻAbdu'lláh Khán, the Shah ordered a member of the royal family, Prince Mihdí-Qulí Mírzá to exterminate the Bábís of Mazandaran province. His edict to Mihdí-Qulí Mírzá is significant, because it ordered the death of the Bábís at Tabarsi, not only on the grounds of alleged rebellion, but also heresy:
It is true: Mihdí-Qulí Mírzá, you must exert yourself to the utmost in this affair. This is not a trifling amusement. The fate of our religion and Shiʻi doctrine hangs in the balance. You must cleanse the realm of this filthy and reprobate sect, so that not a trace of them remains. Devote your utmost diligence to this [...][93]— Naser al-Din Shah Qajar, Edict to Mihdí-Qulí Mírzá, Governor of Mazandaran
In addition to authorizing Mihdí-Qulí Mírzá, the Shah ordered tribal chiefs and princes in Mazandaran to join their forces to Mihdí-Qulí Mírzá. He headquartered his forces in Vaskas and ordered ʻAbbás-Qulí Khán, the governor of Amol County, who was a distinguished general, to join him there with an army. He sent envoys to Barfurush and other villages to gain intelligence about the Bábís, and sent a messenger to the fort with instructions to speak with Mullá Husayn and Quddús.[94]
The messenger was received by Mullá Husayn, and asked what grievances had caused the Bábís to rebel. Mullá Husayn repudiated the accusation of rebellion and claimed that they had no intention except to oppose the corruption of the ecclesiastical order of the country through debate and preaching the message of the Báb. Mullá Husayn then invited Mihdí-Qulí Mírzá and area clerics to visit the fort and hear his arguments for themselves before deciding to bear arms. The messenger was apparently moved by Mullá Husayn's description of the Bábí cause and agreed to carry his invitation back to the prince.[95]
Battle of Vaskas
On 21 December 1848, three days after the messenger's visit, Mihdí-Qulí Mírzá's forces set out to attack the Bábí encampment. Nabil reports that he came with at least five regiments of infantry and cavalry.[96] Quddús ordered every horseman among the Bábí's to rush forward and meet the Prince's forces before they could reach Tabarsi.
In the ensuing battle Mullá Husayn engaged the prince directly, after which the prince fled the battle, taking up residence in a nearby barn before retreating to Sari.[97] At least two other royal princes died in the attack, and some prisoners held by the princes forces were released. Quddús was injured in the battle, but was not incapacitated.[98]
Battle of Fort Tabarsi
After the defeat of the Shah's forces at Vaskas, Abbás-Qulí Khán, governor of Amol County, took up primary responsibility for the eradication of the Bábís from the area. He solicited additional men from Mazandarani tribes and surrounded the fort. A more skilled commander than Mihdí-Qulí Mírzá's, he had barricades and artillery set up surrounding the fort, as well as again cutting off the water supply of the Bábís.
Mullá Husayn, inside the fort, oversaw the construction of a well within the walls. On 2 February 1849, he again donned the Báb's green turban, and—along with Quddús—launched an attack against the forces of Abbás-Qulí Khán. Eyewitness accounts record that the war-cry of the Bábís was "Yá Ṣáḥibu'z-Zamán!" or "Oh Lord of the Age", a reference to the Báb.[99]Initially the Bábí thrust was successful in sowing confusion in the ranks of Abbás-Qulí Khán's troops, and a significant number of their tents and barricades were burnt to the ground. Mullá Husayn in particular is recorded running from side to side challenging enemy soldiers himself. His aptitude with the sword led Abbás-Qulí Khán to later compare him to the Imam Ali, traditionally regarded as the perfect swordsman, and his sword Zulfiqar, while Khán compared his martial leadership in the face of overwhelming opposition to that of the Imam Husayn:[100]
The truth of the matter is that anyone who had not seen Kerbala would, if he had seen Tabarsi, not only have comprehended what there took place, but would have ceased to consider it; and had he seen Mullá Husayn of Bushraweyh he would have been convinced that the Chief of Martyrs had returned to earth; and had he witnessed my deeds he would assuredly have said 'This is Shimr come back with sword and lance.'[101]— Abbás-Qulí Khán, Quoted by Mirza Husein in the Tarikh-i-Jadid
During the battle Mullá Husayn's horse lost its footing, tangled in rope, and Abbás-Qulí Khán, perched in a tree, shot him through the chest. He survived long enough to be brought into the fortress, where he and Quddús spoke before he died. His last recorded words to Quddús were: "May my life be a ransom for you. Are you well pleased with me?" [102] His nephew, the Letter of the Living Muhammad-Baqir was also present at the moment of his death. He was buried by Quddús—who dressed him for burial using one of his own shirts—in a grave to the south of the shrine, while thirty six other Bábís were buried to the north. Quddús gave a brief sermon at the burial calling all Bábís to see Mullá Husayn and the other dead as martyrs of exemplary character and bravery.[103]
Death at Fort Tabarsi
Mullá Husayn died during battle on 2 February 1849,[75][104] and news of this reached Turkey in a French language newspaper.[105][106] He was buried within the grounds of the Shrine of Shakyh Tabarsi.[107] Mullá Husayn is regarded by Bábís and Baháʼís as a martyr, and his conduct in the battle is characterized as an example of bravery and heroism in the face of insurmountable opposition in Baháʼí literature. Seven other members of the Letters of the Living are believed to have been killed at Tabarsi as well as the majority of the Bábí combatants.[108]
Surviving family
His brother Muhammad-Hasan, survived until the end of the battle of Tabarsi, and was executed along with Quddús by the clergy, even though he was supposed to see the shah. His nephew Muhammad-Baqir survived until the end of the battle, although his fate after that point is unclear. Mullá Husayn's mother and sister had converted to Bábism at some point after the Báb's declaration—becoming close companions of Táhirih—and learned of his death at Tabarsi. They returned to their home town of Boshruyeh where they cared for the wives and children of men who had died at Tabarsi. After his mother's death, his family home was destroyed by a mob, and his sister was forced to move to Ashgabat. She became a Baháʼí and was given the title Leaf of Paradise (Varaqatu'l-Firdaws) by Baháʼu'lláh.[109]
Significance
Mullá Husayn's role as the first to accept the Báb as the Mahdi and founder of an independent religion grants him a special place in Bábism and the Baháʼí Faith. He was granted the title of Bábu'l-Báb ("Gate of the gate") by the Báb, referring to this role.[110] His expertise as a licensed member of the Shia mujtahidūn and a well-regarded disciple of Siyyid Kázim is seen as giving greater weight to his acceptance of the Báb, seemingly confirming that the Báb fulfilled the traditions of Shia Islam regarding the coming of the Mahdi.[103]
Mullá Husayn's role as the first member of the Letters of the Living give him added significance in Bábí and Baháʼí thought. The Letters of the Living did not have specific administrative roles in Bábism, but played a role somewhat analogous to that of the Apostles of Christ: companions of the prophet, refiners of doctrine, and early martyrs.[111] The Letters of the Living were described by the Báb as the return (Arabic: الرجعة rajʻa) of the Shia Infallibles:
The Eighteen 'Letters of the Living' manifested themselves in the last, i.e. the Muhammadan Manifestation in the persons of the Fourteen Holy Souls (i.e. the Prophet himself, his daughter Fatima, and the Twelve Imams of whom the first, 'Ali, was her husband, and the remainder of her descendants) and the Four Gates (or Bábs) who successively acted as channels of communication between the Twelfth Imam, or Imam Mahdi, and the faithful, during the period of his 'Lesser Occultation' …. The terms 'Point' and 'Letter; were originally suggested by the formula Bi'smi'llahi'r-Rahmani'r-Rahim (In the Name of the Merciful, Compassionate God), which contains 19 letters, the first (B) distinguished by a point or dot beneath it; and by 'Ali's alleged saying, 'All that is in the Qurʼan is ... in the Bi'smi'llah ... and I am the Point beneath the B.'[112]— Edward Granville Browne, quoted by Moojan Momen in Selections from the Writings of E.G. Browne on the Bábı́ and Baháʼı́ Religions
Mullá Husayn himself is described in the writings of the Báb and Baháʼu'lláh as the return of the Prophet Muhammad,[113] and in other early Bábí sources variously as the return of the Imam Husayn or even described as the "Qa'im of Khorasan".[114] While Mullá Husayn is seen as the symbolic return of these historical figures, he is not seen by Baháʼís as a prophet or Manifestation of God. His raising of the Black Standard prior to the battle of Fort Tabarsi is seen as the fulfillment of Shia eschatological predictions, and further cements his station as an important part of Bábí and Baha'i claims of Mahdi-hood for the Báb.[75]
The Báb describes Mullá Husayn with reference to the station known in Shia Islam as the "viceregent" or "silent one", similar to the role of Aaron in the time of Moses, and Ali in the time of Muhammad—one whose authority is great but entirely derived from a greater Prophet, in this case the Báb himself.[115] He is further described as the first perfect Muslim, or the "first fruit of the Tree of Islam".[116] In Bábí theology, it is the emergence of the first perfect follower of a religion which triggers the emergence of the next religion. In this way, Mullá Husayn is seen not only as the first Bábí, but in some sense the cause of the abrogation of Islam and its replacement with Bábism.[116] The Baháʼí Writings refer to this role of Mulla Husayn:
Among them was Mullá Husayn, who became the recipient of the effulgent glory of the Sun of divine Revelation. But for him, God would not have been established upon the seat of His mercy, nor ascended the throne of eternal glory.[117]— Baháʼu'lláh, Kitáb-i-Íqán
Baháʼu'lláh also wrote a tablet of visitation for Mullá Husayn, which was included in an epistle written to Mullá Husayn's sister Varaqatu'l-Firdaws. In this tablet he plays on the common name of Husayn held by himself, Mullá Husayn, and the Imam Husayn, symbolically intermingling their identities and invoking their shared loneliness and suffering in the "path of God".[118]
Notes and citations
- ^ Zarandi 1932, pp. 63.
- ^ Mehrabkhani 1987, pp. 2.
- ^ Mahdavi, Shireen (6 February 2014). "Childhood in Qajar Iran". Iranian Studies. 47 (2): 305–326. doi:10.1080/00210862.2013.860327. S2CID 144563336.
- ^ a b Amanat 1989, pp. 159.
- ^ Zarandi 1932, pp. 334.
- ^ Amanat 1989, pp. 156–157.
- ^ Mehrabkhani 1987, pp. 7.
- ^ Amanat 1989, pp. 47–48, 157–158.
- ^ a b Amanat 1989, pp. 157.
- ^ Mehrabkhani 1987, pp. 22.
- ^ Mehrabkhani 1987, pp. 10.
- ^ Cheyne 1914, pp. 19.
- ^ "Mulla Husayn Bushrui". World Religions: Belief, Culture, and Controversy. 2012.
- ^ MacEoin 2009, pp. 57.
- ^ MacEoin 2009, pp. 165.
- ^ Amanat 1989, pp. 158.
- ^ Mehrabkhani 1987, pp. 26.
- ^ Zarandi 1932, pp. 49.
- ^ Amanat 1989, pp. 162.
- ^ Amanat 1989, pp. 163–164.
- ^ Zarandi 1932, pp. 51–57.
- ^ Sears 1960, pp. 9–11.
- ^ Amanat 1989, pp. 163–165.
- ^ MacEoin 2009, pp. 297–298.
- ^ Hamson, Arthur (May 1980). The growth and spread of the Baháʼí Faith (PDF) (Phd. Geography Dissertation thesis). University of Hawaii.
- ^ Zarandi 1932, pp. 52.
- ^ Bausani, A. (1999). "Bāb". Encyclopedia of Islam. Leiden, The Netherlands: Koninklijke Brill NV.
- ^ Encyclopædia Britannica. "the Bāb". Retrieved 10 November 2009.
- ^ a b Effendi, Shoghi (1974). God Passes By. Wilmette, Illinois 60091: Baháʼí Publishing Trust. p. 5. ISBN 978-0-87743-034-6.CS1 maint: location (link)
- ^ Momen, Moojan (2007). "Messianic Concealment and Theophanic Disclosure" (PDF). Online Journal of Baháʼí Studies. 1: 71–88. ISSN 1177-8547.
- ^ Bernard Trawicky (30 April 2009). Anniversaries and Holidays. American Library Association. p. 86. ISBN 978-0-8389-1004-7.
- ^ Amanat 1989, pp. 170.
- ^ Amanat 1989, pp. 174.
- ^ Mehrabkhani 1987, pp. 74.
- ^ "The Time of the Báb". BBC. Retrieved 2 July 2006.
- ^ Amanat 1989, pp. 176.
- ^ Amanat 1989, pp. 197–198, 211.
- ^ Cheyne 1914, pp. 45.
- ^ Zarandi 1932, pp. 85–87.
- ^ Zarandi 1932, pp. 97.
- ^ de Gobineau 1866, pp. 130, quoted in Zarandi (1932, pp. 109)
- ^ Mehrabkhani 1987, pp. 93–95.
- ^ Mehrabkhani 1987, pp. 95–96.
- ^ The Báb 1982, pp. 83.
- ^ de Gobineau 1866, pp. 129, quoted in Zarandi (1932, pp. 101)
- ^ Zarandi 1932, pp. 102–105.
- ^ de Gobineau 1866, pp. 131, quoted in Zarandi (1932, pp. 109)
- ^ Cole, Juan (1989). "Baha'-allah". Encyclopædia Iranica.
- ^ Smith, Peter (2008). An introduction to the Baha'i faith. Cambridge: Cambridge University Press. p. 5. ISBN 978-0521862516. OCLC 181072578.
- ^ Zarandi 1932, pp. 123–129.
- ^ Sears 1960, pp. 27–34.
- ^ Zarandi 1932, pp. 161.
- ^ Zarandi 1932, pp. 171.
- ^ a b Zarandi 1932, pp. 255.
- ^ Zarandi 1932, pp. 243.
- ^ Cheyne 1914, pp. 55–56.
- ^ Zarandi 1932, pp. 255–257.
- ^ a b Zarandi 1932, pp. 262.
- ^ Zarandi 1932, pp. 257–261.
- ^ Cheyne 1914, pp. 77–78.
- ^ Zarandi 1932, pp. 260–261.
- ^ Zarandi 1932, pp. 261.
- ^ Zarandi 1932, pp. 261–263.
- ^ Zarandi 1932, pp. 263.
- ^ Zarandi 1932, pp. 264–265.
- ^ Zarandi 1932, pp. 265–266.
- ^ Zarandi 1932, pp. 266–268.
- ^ Amanat 1989, pp. 273.
- ^ Amanat 1989, pp. 273–275.
- ^ Cheyne 1914, pp. 101–103.
- ^ Zarandi 1932, pp. 288.
- ^ Zarandi 1932, pp. 291–292.
- ^ Zarandi 1932, pp. 324.
- ^ Zarandi 1932, pp. 324–325.
- ^ a b c d Momen 1983, pp. 157–183.
- ^ Zarandi 1932, pp. 326–327.
- ^ Zarandi 1932, pp. 329.
- ^ Mehrabkhani 1987, pp. 192–193.
- ^ Husein of Hamadan 1893, pp. 156.
- ^ Mehrabkhani 1987, pp. 193.
- ^ Zarandi 1932, pp. 330–331.
- ^ Zarandi 1932, pp. 332.
- ^ Zarandi 1932, pp. 333.
- ^ Momen 1983, pp. 162–165.
- ^ Momen 1983, pp. 178–176.
- ^ Mehrabkhani 1987, pp. 223–225.
- ^ Mehrabkhani 1987, pp. 225–227.
- ^ Zarandi 1932, pp. 350.
- ^ Mehrabkhani 1987, pp. 234–235.
- ^ Mehrabkhani 1987, pp. 242.
- ^ Mehrabkhani 1987, pp. 243–247.
- ^ de Gobineau 1866, pp. 156, quoted in Zarandi (1932, pp. 357–358)
- ^ Mehrabkhani 1987, pp. 251.
- ^ Mehrabkhani 1987, pp. 251–253.
- ^ Zarandi 1932, pp. 363–365.
- ^ Zarandi 1932, pp. 365.
- ^ de Gobineau 1866, pp. 169–170, quoted in Zarandi (1932, pp. 366)
- ^ Zarandi 1932, pp. 366–368.
- ^ Mehrabkhani 1987, pp. 265–267.
- ^ Husein of Hamadan 1893, pp. 106–109.
- ^ Husein of Hamadan 1893, pp. 106–107.
- ^ Zarandi 1932, pp. 381–382.
- ^ a b Zarandi 1932, pp. 382–383.
- ^ Mehrabkhani 1987, pp. 270.
- ^ "Nouvellees de Perse" (PDF). Journal de Constantinople. 24 March 1849. p. 1 bottom fourth column, above middle – via Baháʼí Library Online.
- ^ "Nouvellees de Perse" (PDF). Journal de Constantinople. 29 March 1849. p. 1 bottom second column, top third – via Baháʼí Library Online.
- ^ Mehrabkhani 1987, pp. 284.
- ^ Zarandi 1932, pp. 411.
- ^ Mehrabkhani 1987, pp. 285–286.
- ^ Sears 1960, pp. 26–28.
- ^ MacEoin 2009, pp. 174.
- ^ Edward Granville Browne; Moojan Momen (1987). Selections from the Writings of E.G. Browne on the Bábı́ and Baháʼı́ Religions. Ronald. pp. 325, 328. ISBN 978-0-85398-246-3.
- ^ Saeidi 2008, pp. 269.
- ^ MacEoin 2009, pp. 339–343.
- ^ Saeidi 2008, pp. 270.
- ^ a b Saeidi 2008, pp. 277.
- ^ Baháʼu'lláh (1862). Kitáb-i-Íqán: The Book of Certitude. Wilmette, Illinois, USA: Baháʼí Publishing Trust. ISBN 978-1-931847-08-7.
- ^ McCants, William (October 2001). "The Wronged One: Shí'í Narrative Structure in Baháʼu'lláh's Tablet of Visitation for Mullá Husayn". Lights of Irfan. 3: 83–94.
References
- Amanat, Abbas (1989). Resurrection and Renewal. Cornell University Press, New York, USA. ISBN 978-0-8014-2098-6.
- The Báb (1982). Selections from the Writings of the Báb. Baháʼí Publishing Trust. ISBN 978-0-87743-311-8.
- Cheyne, T.K. (1914). The Reconciliation of Races and Religions. London, U.K.: A. and C. Black. OL 7202267M.
- Husein of Hamadan (1893). Tarikh-i-Jadid [New History of Mirza Ali Muhammad the Bab]. Translated by Browne, Edward G.
- de Gobineau, Arthur (1866). Les Religions et les Philosophies dans l'Asie Centrale. Paris, France: E. Leroux. OL 1296883W.
- MacEoin, Dennis (2009). The Messiah of Shiraz: Studies in Early and Middle Babism. Leiden, The Netherlands: BRILL. ISBN 9789004170353.
- Mehrabkhani, Ruhu'llah (1987). Mullá Husayn: Disciple at Dawn. Los Angeles, California: Kalimát Press. ISBN 978-0-933770-37-9.
- Momen, Moojan (May 1983). "The Social Basis of the Babi Upheavals in Iran (1848-53): A Preliminary Analysis". International Journal of Middle East Studies. 15 (2): 157–183. doi:10.1017/s0020743800052260. JSTOR 162988.
- Saeidi, Nader (2008). Gate of the Heart: Understanding the Writings of the Báb. Waterloo, Ontario: Wilfrid Laurier University Press. ISBN 9781554580354.
- Sears, William (1960). Release the Sun. Wilmette, Illinois: Baháʼí Publishing Trust.
- Zarandi, Nabil (1932). The Dawn-Breakers. Translated by Effendi, Shoghi. Wilmette, Illinois: Baháʼí Publishing Trust. LCCN 32008946.
Further reading
Books
- Smith, Peter (1999). A Concise Encyclopedia of the Baháʼí Faith. Oxford, UK: Oneworld Publications. ISBN 978-1-85168-184-6.
External links
- Glossary of the Kitáb-i-Íqán – includes a small biography of Mullá Husayn
- Mullá Husayn, by Lowell Johnson
| https://wiki2.org/en/Mull%C3%A1_Husayn | CC-MAIN-2022-05 | refinedweb | 8,291 | 61.67 |
Mortgage Free For Life71 post my reviews of the book here for you to read.
If you've read the book Mortgage Free For Life (or even if you haven't) and you have an opinion, please leave a comment below or vote in my survey.
For more information check out MortgageFreeForLife.com
Thanks!
More Helpful Links
- Infomercial Product Reviews
Read real consumer reviews and ratings of the newest and most popular infomercial and As Seen On TV Products.
- Instyler Rotating Hair Iron Ratings & Reviews
Read why the Instyler is the hottest new hair styling tool available today!
- Ab Rocket Reviews
PrintShare it! — Rate it: up down [flag this hub]
RSS for comments on this Hub
Just ordered the book too (last night after the infomercial). Just came across this hub. They claim in the infomerical that without "changing your lifestyle" or paying more that you could pay your mortgage off in 7 to 10 years??
We actually do use a HELOC as leverage against our mortgage, and it is going to allow us to have ALL of our debt paid off in less than half the term of a traditional 30 yr mortgage. Now I know nothing about this book, but that concept really works. I actually have a software program that helps me track the progress of the paydown! It is awesome!
What software program are you using?
The lady in the infomercial has some smokin hot legs
Has anyone had any more feedback on this program?
Does Jill with the smoking legs have a web site?
Recently read the book. Motivated by the John Commuta commercials which seem to get at same idea. Wanted to know how this could possibly work. It seems to be an extraordinary approach to converting debt into wealth. Watch out for those who suggest the opposite such as those trying to sell the idea of maintaining high debt and letting someone invest the extra. Personally, I want to be mortgage free. I am trying to locate the software mentioned in the book.
I wonder how much the software costs that he's talking about in the book.
They said you get a trial of the software.
Lisa, can you share the software you are using?
I found a Ownership Accelerator at the website attached to this message.
Click on Calculator and it starts up.
Interesting idea.
IS THIS BOOK GOOD FOR CANADA
Just saw the infomercial but haven't read the book. The concept is imported from Australia. I believe Manulife has a similar product called Manulife One in Canada.
Funny, $3500 is exactly what the fee is for a scam someone was pushing on me. Then I have to go find people to sign up. Somehow, they say making payments at a certain time against a HELOC/credit card will "slash" interest & you pay off your debt years earlier. Anyone tried this program?
Simply adding more to monthly payments, drastically reduces scheduled payments. One extra house payment annually knocks off at least a year from the end of your schedled term payments.
Thank you, my two cents. I listened the website you gave. It makes lots of sense. I'll be to listen to it again; to make sure. There are many ways to get debt fee. Sceptics are normally broke. But, if you really pay attention, things could turn around.
Voodoo, you have no idea what you are talking about. I know people who are using a similar product only it has been upgraded so you do not have to use a HELOC. (home equity line of credit) Many banks are freezing equity lines so this may not be the answer. I am a mortgage consultant who sends my clients to a company that is ahead of what the lenders are doing. Also every person's situation, needs and wants are not the same, so all of these things need to be taken into consideration when making choices. Feel free to email me if you would like more info on another option
What about theories by people like Ric Edelman who say you build more weath by not paying off the mortgage early and take all extra money and investing it instead?
Excel has a program that will show you how to do this.
How quickly your mortgage is paid off depends on how the payments are applied by the bank who holds the mortgage. Most mortgages are NOT simple interest. In a simple interest mortgage you are only charged for the number of days since your last payment which adds up to a lot of savings. In most mortgages, the interest is precalculated regardless. Please consider that your bank may not apply the payment according to the software calculation throwing the timeline and savings out the window. Also consider your home can be foreclosed if your HELOC payments get out of control and you are not able to make them.
Anyone who charges you a fee for a complicated computer program is a scammer! The fact is that using s HELOC as a regular checking account, and paying a few thousand 'in advance' off your mortgage balance DOES WORK! - It DOES save you thousands in interest. It DOES take years off your mortgage. You don't need to know any more than that! Go to your bank. Open a 'qualified' HELOC (One that permits you to use it as a regular checking account). Pay maybe $3,000 from it off your mortgage. Deposit your paychecks into the HELOC (and continue to use it instead of your current checking account) until the balance comes down to a few hundred dollars. Then make another mortgage payment. etc. etc. It's that simple. It will save thousand it will cut your mortgage term in half (or better). What else do you need to know?
Pam C.; Call your credit card co. and protest the charges. Scam co.'s never defend their actions and you'll have the charges reversed in a month or so.
I just finished reading all the comments above. This concept is NOT a scam. I've read the entire book and it makes perfect sense. Sure everyone knows that making extra payments on your primary mortgage will pay down your mortgage faster. But how would you get the money back out if you needed it for an emergency? You only have 2 options: 1. sell your house 2. refinance (which costs around 2 points in fees) -- so a $100,000 refinance will cost you $2000 or more in fees --is it really worth $2000? The LEAP system bypasses this! The software is 5 payments of $59.99 after the 30 day trial so I'm not sure why some people are puzzled by the charges. When you call to order the book, they explain exactly what the fees are after the 30 day trial. Beats paying $3,500!!! I also received a letter with my order explaining the details of the fees for the software. If they were trying to scam me, I don't think they would've included that letter from Mr. Weathington telling me of the fee for the software. $300 is well worth the price of the software! If someone can provide one for free, definitely count me in! There's a 30 day money back guarantee so if anyone wants to order, I highly recommend the book. It gives you other tips on getting rid of debt and goes into detail about the leap program. I also love the tip towards end of book about raising your credit score!! This by itself was worth my 30 bucks! I wish people would be more educated about a topic before posting such messages. I wish I would've known about this system 5 years ago. I'd have my house paid off by now!!! Oh, and anyone who tells you NOT to pay off your house and hold the money for investments...don't walk, but RUN away as fast as you can! Anyone telling you debt is good has been brainwashed by the banks and financial system to be a debt slave for life. Read the book to open your eyes and see the truth about this fallacy. Again, I highly recommend this book to anyone who gives a darn about their own personal financial health. Any skeptic will miss out.
I'm a mortgage originator and I started a debt/mortgage accel. program 6 mo. ago and it's been amazing. I decided not to use a heloc and I'm still due for payoff of one property in 2 years. I have several other properties in the system and payoff for all is less than 7 years.
I'm so amazed I have to share this program with my old clients who are going to pay over $700K for a $150k house. I wish I knew this before...I would be sitting pretty now! Now, I'm saving hundreds of thousands in interest, I'll have my residence and rental properties paid off before I'm 50 and my daughter will graduate from grad. school student loan free! Not bad for a single mom.
3K is nothing to spend on the program that saves this much real $$$. Besides the payment is wrapped in the program so you never feel it. It's a no brainer...but all you who love the banks and your buddies on wall street, they thank you for your monthly interest payment and the $700 billion bail-out. Who's scamming who?
Its very useful information about mortgage free life. Recently i posted an hub on mortgage calculator may be this will be helpful to you
paying extra money toward your mortgage principal at whatever interval you want is a good thng and will save you a ton of money (especially the earlier in the life of your mortgage that you do it)...this is not new...most loans have no prepayment penalty...make sure yours doesnt...there was a book that is probably 20 years old called the bankers secret that explains the basics...you dont need to have software to make extra payments because you will be paying your regular payments plus whatever extra you want and the bank will have to take care of the calculations...you can have it checked by a program or person down the road...this program seems to take these basics a step further but firat look at the basics...the concept is clearly explained in lower level accounting texts and any accountant can explain it to you...
Its very nice information about mortgage. You can get some more information about mortgage calculator from my hub. Check it out may be useful to you .
Just making ONE..., ONE extra yearly payment will reduce a fixed 30 year loan down to 21 years, u do the #s.
Wow, just read these comments top to bottom. Have to agree with Procustes that anyone advocating paying $ for this system is a shill and has $ incentive to write what they do. The exception being "Are you guys nuts". Holy crap, possibly the most non-sensical (not a word) plan of attack I've ever heard. Of course, you have cash advance fees, maybe only 1-2%. Maybe you pay that off with a balance transfer from a 0% credit card (which almost certainly will have a 3% charge). What happens when that 0% advance is up, and you've dumped that cash into your mortgage and can't get it back out? Oh...now you pay 10, 15, 20%+ on your formerly 0% card, only compounded by the number of times you've followed this moronic, unsustainable plan. Wow.
As far as the actual proposed plan by this brilliantly informative infomercial. Where to begin? Sure, direct more money to principal, pay down your mortgage faster. Somebody made the point, if you want that money back you have to pay to refi or sell. If you use a HELOC to do this, just swapping debt. Using a HELOC as a checking acct could accelerate the process, until your bank revalues your home and shuts off your LOC, and you have access to no more $$. Last thing. Mortgages are cheap debt, and you get a significant discount (at least on residence) b/c of the tax break. If you are disciplined enough to save and invest the difference, over time, you WILL be better off. Even with the total cl*%$terf00k we've got going on today, stocks will be a better investment.
By the way, there are companies selling the software for $1000, $3500...don't walk away, RUN THE OTHER WAY!!! Go to
You'll save a bundle. Their software works just as well as the more expensive versions! That $3500 company is charging a high price because they're a multi-level company and they need to pay out commissions to all their layers of affiliate marketers. I think this is the same comany's site as
They have a double your money back guarantee on their software!
I read every post on this page and to my GREAT DISMAY found myself NO better off than I was before I found this site. There is so much conflicting information and so many (well intentioned and scam intentioned viewers posting comments here) that I found all the information worse than useless!! And to boot I now have a migrane! LOVELY!! I did write down some of the calculator sites and will try to once again navigate myself blindly through the labyrinth of BS & Legalease and just pray for LUCK.
i rather send extra every month instead of investing in the stock market
At the beginning of a mortgage, most of the monthly payment is for interest. Any additional principal payments during the early years will greatly reduce the time to mortgage freedom. I got a 30 year loan so that the amount I had to pay was less than it would be for a 20 or 15 year loan.
All I had to do is decide how much more I wanted to send in each month. I indicated on the payment that the extra money was to go to my principal. On my next mortgage bill was listed my remaining loan amount, what I paid in interest and principal the prior month and what next month's payment in interest and principal would be. My required monthly payment was fixed. There was no need for any other loans, books, fees or programs. At any time I could increase or decrease the extra principal payment. Near the end of the loan, I was paying so little interest each month that I stopped sending in an extra amount.
--Living in California debt free for years.
By just making a bi-weekly mortgage payment instead of a monthly payment will do the same thing, with out complicating your finances. If your monthly payment is 800.00 per month, send the bank 400.00 every two weeks, you will pay off your mortgage sooner, and save on interest. 12 x 800 = 9600, vs. 26 x 400 = 10400, that’s 800 more towards the principal and your payments remain the same.
The concept does work. I have been utilizing the concept for 16 months. Started with an interest only loan of 285K. Today my balance is 208K. I looked into the bi-weekly approach, it will accelerate your mortgage by 7 years (30 down to 23).
The woman with the smoking hot legs is a liberal skunk who does a radio show in Chicago...she has been on Fox News and usually gets ripped apart by anyone with a brain. She can't make any money on her radio show so she moonlights ripping off folks on TV. Typical scumbag liberal.
Okay, has anyone gotten a rotten loan where you are not allowed to make principal only payments? What then?
Tips (Common sense) to use when buying and financing a house:
1. Get pre-approved (not pre-qualified) from your bank (they know you more)
2. Identify your confort zone for purchase price and monthly payments and do not exceed.
3. Typically your bank will tell you that you can qualify for more and give you a letter to that affect. Well, ask your bank for a second letter showing that your approved at the amount of your comfort level (which is less). Take a 15 year mortgage and do not even look at a 30 year mortgage--not even saying that you will double up on a 30 yr mortgage. The 15 yr mortgage gives you the discipline to pay your mortgage. [I took a 15 year mortgage at 7% and the difference between a comprable 30yr was $80 but my equity build went from $20 per month to $200 per month on a 15 yr. So my first payment of $800 ($200 wen towards equity)
4. Now start looking for your property and when the realtor asks if you have been preapproved show them your second letter of approval at your comfort zone and not the first. Do not mention the first. The realtor wants to put you in the maximum affordable house that you can so they can receive the highest commission. If they only see the letter of you comfort zone, they will only show homes in that area.
5. If the realtor is livign living up to your expectations, leave them an go find someone and DO NOT GIVE THEM AN EXCLUSIVE OR DO NOT PAY ANY UP FRONT FEES.
6. Have check list when lokoing at properties and look for things wrong and make a note of them as you will bring them up when you are preparing your bid and negotiating the price. DO NOT FALL IN LOVE WITH THE FIRST HOUSE UNLESS THE SELLER WANTS TO GIVE IT YO YOU FOR FREE WITHOUT ANY COSTS!
7. Ask for Seller's Concessions minimum $2000 but as much as you can get. Try to get 5% to 10% of the price in sellers concessions. Any amount helps at closing as it is less out of your pocket.
8. After you offer is accepted, get to know the seller before closing. Your realtor will resist this. So go around them, nothing wrong with that, if the seller is local and/or lives in the house. You are accomplishing two things: 1) you want to know the history of the house and 2) you want to give the seller a good iimpressions of you. [I learned much about my house and the seller even gave me a key to house before the closing--months before the closing---and gave cash back at closing without asking for it at closing]
9. Follow up up on everybody's duty including to ensure the title (do your own search), verify taxes have been paid, that a CO has been ordered. [I did this I found that there was a code violation and able to get the problem corrected before closing to the problem that I was allowed to move into the house without and initial CO will the contractor was correcting the violation]
10. Now you are a hownowner, learn to do your own home repairs and yard work. That is part of the American Dream is to work on your house. [One associate told me that your weekends go from going out to spending time on the house, the same with your vacations.]
ADDTNL: Because I put down 3% I had to take MIP insurance. This is not bad. My approach is to pay off that mortgage ASAP and make the monthly payment before it is due. Also, mortgage interest is added at the end of the month and your payment is for the previous month. So any amount extra that you pay this month on your mortgage beyond the scheduled payment is applied to the principal fully. After 2 years I get a letter from my bank that my equity is now 20% and they are dropping the MIP premiumm which was scheduled for 10 years. My payment went down by $35 per month
I bought this house in 1997 for $70,700 and in 2004 had to sell due to divorce for $195,000. This is the only good aspect from the divorce. Tookmy share and bought low income property for investment and a smaller home for myself and own them all free and clear. I do not work any more but have more income than I did when I did work where I was just recently was approved for a $95,000 mortgage for a house in Philly..
If any one can find the algorithm or calculation used for this software, I will write a clone version and release it as freeware.
I'm a bit confused regarding the HELOC, in this market most of us owe more than value; so HELOC is not really an option; then what ???
Unless your are a Sr. Banking Exec, the chances today of getting a HELOC are slim to none. This program was originated by Harj Gill, of whom I am friends with. In simplicity, if you pay more than your scheduled mortgage payment, put in writing (keep a copy) that the extra monies are to be applied to principle. And I suggest, the highest interest rate you have are credit cards, pay as much principal as you can, you'll see a realistic principal reduction in 4-6 mos and a higher FICO. ("I have fought FNMA, FHLMC on FICO scoring") HUD ("FHA") has agreed with me.
PHK - Some of your advice is great. However, I would advise most people to get a 30 year or longer term loan and pay it off as if it were a 15 year loan.
If, in these uncertain economic times, you lose your job, it's easier to be able to pay the lower payment required of a 30+ year loan than come up with the monthly payment of a 15 year loan.
So, purchase and borrow only what you can afford as if you are going to pay it off in 15 but finance it at the longer term as a safety net in case an emergency arises.
You just never know when some unforseen emergency might arise that lowers the amount you can afford to pay in a month or maybe for the next many months. A disability can decrease your monthly income at least 30%. That alone can make or break someone's ability to continue paying on a 15 year term mortgage.
I would recommend to everyone to watch the Suze Orman show. She has talked about taking a 15 year loan over a 30 year. The problem today is that people have been buying homes way outside of there affordable price range.
She reccomends you have a minimum 6 month savings. If you can not keep that much in your savings you can't afford the home. You should never rely on future earning increases to determine the amount of house you can afford. 15 year loans usually take that into account.
My wife and I actually bought a home that we could afford to make 2 monthly payments. We did this because we saw friends get in over there head and were refinancing every 3 years durring the boom to support there life style. During that time we payed more in rent then there mortgage was so we decided to buy our own home.
Our original mortgage was at 7% intrest in 2001 30 year loan. We refinanced in 2003 to a 15 year 4.5% intrest rate. I totaled the payments for the 30 year the subtracted the total from the 15 year and noticed that we would $200,000. I was glad to pay the $9000 in closing costs to save me $200,000. I will allow you to do the figures for what my return on invest will be over the next 15 years. The original mortgage was for $153,000. This will in the future allow me to buy a new home as my family grows.
I would reccommend to everyone to look into finance management courses in your local area. There is a wealth of information out there to help the consumer.
Take this from someone who in 2001 had a credit score of 590 to 780 today.
Just watched the infommercial for "Mortgage-Free for Life...." so decided to do some research. at the very begining of the TV program one of the speakers - can't remember which cos I was transfixed on Jill's smokin hot legs.....- said this program was widely used in Australia and the UK. Can't speak about Australia but I can for the UK (I'm a Brit), and I can honestly say that I have never heard of this sort of system before. Only difference in UK is that 'Interest Only' loans are more readily available, the reason is that in the UK you can only take an interest only loan if you have what is called an 'Endowment Policy' tied to the loan. Basically you make two seperate payments, the first pays only the interest on the loan, the second payment is made to a life insurance policy that remains in force for the term of the mortgage, the amount you pay into this policy is calculated so that at the end of the mortgage term the policy 'should' pay out an amount equal to or greater than the principal amount of the mortgage. So you pay off the principal from the Endowment Policy, and hopefully, have a nice lump sum to do whatever you want with.
Personally I have found over the last few years (ok it took a while to sink in), that the ONLY way to manage your finances is to be in control of them, that means being fully aware of everything you owe, knowing when every payment you make is due and being as disciplined as you possibly can be.
I use a simple excel spreadsheet - 1st column dates, 2nd column deposits, 3rd column withdrawals, 4th column balance(formula which adds balance from the previous row and the deposit from current row then subtracts the withdrawal from the current row), 5th column description. I started by plugging in the starting balance in my current account, then every payday for 6 months, then every bill for 6 months. Right away I can see how much money I have available for other living expenses each month (simply check the balance figur at the end of each month (if this doesn't increase each month then you are in trouble and need to reduce monthly bills). Usually once or twice a week I check my bank account and plug in any other expenditure (ATM withdrawals, debit card purchases etc) - just insert a line into the spreadsheet or you can start with an 'empty' line for each week and fill in the amount there. After using this spreadsheet for just a couple of months it was amazing how much better I began to feel about my future. It's amazing how your health actually improves when you are in control of your finances. OK, the first couple of times I saw a minus figure in the balance column it worried me, but because I knew in advance that I was heading for a negative balance I was able to adjust my other payments to stop it from happening - result no late fees or over draft fees for over 5 years, that alone was worth the time it took to setup the spreadsheet and discipline myself to use it.
What's this got to do with paying off my mortgage early? Well, because I know exactly how much 'extra money' I have at anytime now or in the near future I can pay extra towards the principle on my mortgage without it affecting my lifestyle. The discipline I got used to in using this also mean't that when it came time for me to buy my first home here a little under a year ago I knew how much mortgage payment I could afford. No matter what my mortgage broker suggested, I was able to bring him back down to what I could afford, not what he "could get me approved for". Being in control and making sure my mortgage broker knew I was in control mean't my mortgage payment is within $5 of the amount I first worked out I could afford. Couple this with choosing a realtor I trusted and who was willing to listen to what I wanted - instant equity (I was prepared to go for a house that needed some TLC) ended with me walking away from closing with $20k+ equity and a check for $105.00 to pay for a celebratory dinner!
The bottom line is this, whatever you do, don't hand over control of your money to someone else, doesn't matter who it is, they don't work for free, and whatever they are making from you is money you can't afford to pay, no matter your circumstances.
Well I am really simple. I do not understand HELOC... From what I understand you finance the equity in your home at some interest rate. Then use the money to pay on the mortgage or other bills. Someone said use the HELOC till depleted then go on. You still have to repay the money you got from the HELOC loan and the interest on the loan?? Right? So where is the free money in the HELOC? Unless the interest rate on the HELOC is lower but if it is you could refinance the mortgage. I have never heard anyone advise thet you use long term loans (mortgage) to pay off short term dept (credit cards ect) except the very same folks that brought you the mortgage mess. Yes the interest is lower but for many more years.
Right-on Sparkchaser. I am a PhD financial economist with nearly 40 years experience in the housing and mortgage finance areas and can assure you that this "system" has no redeeming features over just making additional payments to principle. A HELOC is actually another mortgage, with a credit line and at a variable interest rate. Borrowing from the HELOC to pay down principle on the first mortgage is just moving the mortgage debt to a different mortgage, not reducing total mortgage debt. When interest rates drop the HELOC may actually have a rate below that on the first trust, but on average the HELOC's interest rate will probably be higher. Additionally you are increasing your risk by heaping more of the mortgage debt on the HELOC. When interest rates rise so do the payments on the HELOC. And the required HELOC payments are usually interest only. This means, for example, that if you have a HELOC at the prime rate and that rate doubles, so does your HELOC payment (and not a penny of that is going toward principal). Another risk with HELOC debt are that the loan may be frozen and repayments of principle required if the mortgaged property's value drops significantly. Also, the borrowing period is often fixed at 10 years or less, at which point no further funds will be advanced and the outstanding principle must be repaid according to the loans requirements. Additionally lenders have significantly toughened the qualification standards for HELOCs and increased interest rates and up-front charges. There's definitely no free-lunch with this "system" and those trying to use it may get a nasty suprise when interest rates increase. If one wants to payoff a mortgage early the clear winner is to make extra payments to principle (tell your lender to apply the extra to principle and be sure he does) and - when mortgage rates drop enough - refinance and apply your interest savings to further principle payments.
Ok Charles Givens told us about this 20 years ago. They give you the answer in the infomercial. Step one ask your lender for yur amaortaization table or download a free amortization gnereator for excel. plug in your numbers. You will see that at the beginning of your loan something 80% of your payment goes toward interest. So that means only 20% is reducing your principle. If you look at your amortaziation table, simple send the bank the amont of the next monthn's principle and you will double the rate that you reduce your debt. So if your monthly payment is $1,000, then $800 is going to interest and only $200 is going to principle. So if you just send in a extra $200 and tell them to "please apply to the principle" then you reduce your principle by another $200. Do this every month and you reduce you pay schedule in half. The key is to set it up to happen automatically. So the software that they sell i probably an amorterization generator and a payment scheduler. You cand find these on the net for free. Now you have the answer go reduce your debt. If you don't believe me ask your bank. They will tell you, if you ask. If you bank at a credit union, they will often set it up for you.
I have used the methods above and they definately work, without buying any sort of program. I was making more than my minimum payments on time and had execellent credit. BUT THEN, I went from $130K per yr base salary to $50K per year. After losing my job (the company shut down), I maxed out my credit cards, then started falling behind on my payments. I purchased my house a couple of years ago and now it is not worth what I paid for it, so any type of new or restructured loan is out of the question. I don't have the money to pay the admin fees! Does anyone have any suggestions? I'm sinking fast here!
DO NOT ORDEANYTHING FROM THIS " BUSINESS " They do not
honor return policies and LIE to keep your funds in thier pockets
to "now what?": I may have a life raft for you. Would you like to talk over some ideas?
barbershop what are your ideas?
To "now what". With any luck you have a mortgage with a federally backed financial institution. If so, there are a couple of programs they have established to try to halt the rate of forclosures. If you ARE currently delinquent on payments you may qualify for an adjustment of your loan terms to restructure interest rates, payment amounts, and possibly even the principle balance. Even if not behind on payments, your mortgage company may offer you simular restructure options due to HARDSHIP. Start with your mortgage company, then check on HUD and INDYMAC websites for your options. The lender's would rather compromise than get another propery on their books. BE persistant, it should payoff.
If these programs are so easy to do then why is the average american in the financial trouble they are in? For all intents and purposes this same program was but in the book, The Banker's Secret, in 1985 and still Americans are still in debt and being controlled by the banks when this same strategy was around then. Why aren't people using it? Because they don't understand or know of it's existence. And for our ignorance if someone charges you $3500 -- that's the price you pay for not having done or even bothered to learn about 20 years ago.
I purchased the book last summer. I have been using the principles in the book and have paid down $13k so far. I now project I will pay down $25k by mid summer. I am not a shil. I am not using the soft ware. Just following some of the suggestions. Did not change how we spend out of pocket except to actually spend more on. We eat out more, more presents for the grand kids, etc. Yet we still are paying down our debt at a rate of about 25k per year.
It works
Everybody talks about the get out of debt lie..Why is it such a secret and why cant you share your information with others who can't afford to purchase the book or the software? We never want to help others with any information. the rich get richer while the poor get poorer..tell those less fourtnate how to get ahead and what how you will get richer by sharing information you will be so blessed.
First there is no real magic pill ( just like all those "diet" pills out there) to pay off a mortgage quicker, than paying off the principle. Second if you really want this "coffee table" book, why not go to amozon.com/books and buy a used one for 3 bucks. happy reading....................
I suggest reading the Automatic Millionaire by David Bach. He gives a lot of great info. Another Great book is called Money Types...I can't remember the author. This was a great read and gives examples of budget spreadsheets. It also explains more of the "psychology of money". Hope these books help.
Simple interest compared to compounded interest! Thats what this comes down to. Simple interest loans (ie.HELOC) allow you to pay the interest in the year its actually due. As opposed to compounded interest loans (ie. 30 year fixed mortgage) you pay all the interest front side of the loan. The first few years of a fixed loan your interest payment is higher the the amount going to the principal balance! So if you pay the same payment on a simple interest loan (of similar rate) you will be paying more to the principal than you would on the componded interest product.
Here is the problem. Profitability for the bank! The banks dont make FIXED rate, SIMPLE interest, open ended loans! The bank borrows money on an adjustable scale. If you buy a fixed rate loan the bank must gaurantee that rate, even though the money they gave you was borrowed on an adjustable scale! Banks CAN loose money on fixed rate loans!! The dollar is worth a different amount every day to the bank. Thats the reason rates to consumers, even fixed, change daily!
If your willing, and can find a bank still offering them, the Home Equity loan is a simple interest loan. However it's an adjustable rate loan! That means even if you switch to the simple interest product and pay the same amount your paying now, the amount going to the pricipal balance will vary depending on the curent rate! The reason we dont all have helocs is because we are all so afaid of owning an adjustable rate product in a market with the lowest rates in our lifetimes! Fear will always hold you back from acheaving great things in life. My dad always said "There is NO reward without risk!" In this case you will need to overcome your fear of the unknown adjustable rate. If you cant do that, who cares what you paid for the program!
I also believe that paying off a house is a bit silly! Equity is useless once its in the home! Except for collateral for another loan! Why would I tie up $200k or more of my money in a home? Its going up in value weather I tie up the money in the house or not! That just isnt a good investment for a poor man like myself! May as well put under the matress! Next question, is the interest I give the bank worth the equity I gain? No, it never will be in Texas, but I got to live somewhere and some equity is better then none. And who knows, maybe I will get lucky and pay it off someday!
The funny thing is that none of these programs say you MUST have equity and good credit to make it all work...
Another tip to add to the pile....
We write off the intrest payed to the mortgage in our taxes each and then apply the money we get back towards the principle. Another $3,000 this year! This plus the bi-monthly payments has really made it fun to watch the total come down online. No software, just a desire to see a difference in our total.
Does it work for car payments too?? Duh
What is reverse compounding as stated in the infomercial?
The chick in the infomercial has very sexy legs...
I don't currently own a home but am looking into it. In late 2005 I recieved a pre-approved auto loan with a rediculousely high int rate, not having a car & needing one & because I had a low credit score I decided to use the loan. I didn't use the full amt, I used 20K out of 35K. I found online loan calculaters and punched in the #'s until I came up with a monthly payment I could afford & spent that amount. I paid every two weeks and the 4 week total was more than my payment amount, I also sent extra cash when available. I took a full year off of my loan and now own my car. All it took was deciding to do it and sticking to it. And also not falling into the temptation of not sending payments when I noticed about half way through the loan I was about 3 months ahead on payments and they said no payment was due. I guess this would apply to a house but on a much larger scale. Just be disciplined and spend within in your means and try to plan for any eventuality.
I don't have a morgage. I paid off my morgage several years ago. This is an interesting concept though. And I will admit.....Jill has a fantastic body and it was her and those legs that had me watching the infomercial all the way through. Who is she....does anyone know?
I have a question, this program also mentions about doing the same thing with a car loan, does anybody know anything about that...thanks
I dont know if this program works or not. But folks, there is more than one way to skin a cat. There are millions of ways to get out of debt sooner. I do know that If you stay in your mortgage for 30 years you'd pay for your house three times over. The quicker you get out the better. If you invest in the stock market via ira that is a big gamble. I know people that have lost 100s of thousands unless you go into fixed. You can do that through a money market. Back to the mortgages. I looked at my amort schedule. It broken down interest, principal, ending balance, loan to value. By sending the next principal payment each month, I will get out of a fifteen year mortgage in 7.5 years. My Original loan was for 63k and i pulled out 40k. With a monthly payment of 850. I send 850 plus the next principal payment which is 400. My total payment for 7.5 is will be roughly 112500. The banks only make 12500. If i was in a 30 year fixed at 599 per month the bank makes 115,000.
I have been in an ARM for almost 4 years now and can't seem to get out ! Does anyone know if extra payments work for ARM's.?
michael (a few posts above me)...an amen to that brother! we just love to enjoy the little extra things in life (starbucks, etc) that we dig ourselves into a hole over it. nothing wrong with treating yourself once in a while, but let's admit we treat ourselves everyday and think it's what we deserve. but we need to do ourselves a bigger favor and pay our homes and other debt off quickly and be debt-free, which is what everyone deserves. i'm glad to have found this site after thinking of purchasing this book, because more over what i've found are honest folks warning others and helping each other not get fooled. i think we've been fooled enough by the greedy cronies who got us in our current economic situation.
Hi Everyone this is Jill fron the show. I know I have sexy legs. Please buy more books so we can keep taking up airtime on TV!!
I've been usinng a HELOC for a few months to pay of a car. Rate for used car was 6.75%, adjustable heloc rate is 4.5%, a savings of 2.25%. Plus the HELOC is tax deductable, so subtract another percent or two based on your tax rate. The principle here is to put your whole paycheck into the HELOC and write your checks for your monthly bills out of this HELOC account. This keeps the principle at a lower average rate. This plans works if you are disciplined enough to stick to a budget.
Here's an example:
Car loan @ $25,000@ 6.75% is about $140 a month in interest.
Using HELOC with $25,000 @ 4.5% is about $88 a month in interest not to mention the tax savings.
Say you put in a bi-monthly $2,500 paycheck into the HELOC account when you are payed. This reduces the balance on the HELOC to $22,500 instead of the original $25,000. $22,500 @ 4.5% is about $79 a month in interest. You didn't pay interest on the extra $2,500. Next month the principle will be even lower, meaning that you are paying even less that next month in interest. You are paying almost half of the interest costs by using a HELOC as opposed to a regular car loan, $140 versus $79. You save more than $1,000of interest in the first year and again if you add the tax deduction of a HELOC, even more than that. The idea of reverse compounding is just like the opposite version of the rule of 72. The more paid to principle, the less the interest paid by compounding and the less principle you owe.
A couple of things about this. The HELOC rate isn't fixed. If rates jump, which they likely will with our devaluation of the dollar, you might end up paying more, with a higher interest rate, than you would with a fixed rate loan. That is why doing something like this with a shorter term loan makes more sense to me than a mortgage.
This will not let you pay off your mortgage in 7 years. Even if you paid no interest and your full mortgage payment went towards principle you would still need 12 years to pay if off. Only by increasing your payments can you accomplish this. Using this system can however reduce the amount of money payed towards interest without increasing your payments.
The opposite scam is those that say mortgage yourself to the hilt and use this money to invest. The mortgage brokers that feed you this line are wrong. They suppose a return of 9% on the money you saved with the lower mortgage. A 9% return isn't impossible to do, but as you see from the current market could be -50%. The kicker is that the profit you make from any investment will be taxed. So you need to take say a 30% capital gains reduction on the income produced by this investment. Granted there are ways around this, but are limited.
Like has been said before in this thread banks will not pay out more to borrow your money then they can make by lending it. You are guaranteed a return on your money invested into your mortgage at the rate of your loan. An average mortgage rate of 6% is way better than any current CD or savings rate. Until this changes I believe getting a guaranteed rate @ 6% is a great investment. Remember that this also will negatively compound, so that if you pay off a $1,000 of principle you will not only "earn" 6%, so $60 on that $1,000, but $1,060 at 6% on the next payment. Just like when your CD resets, if you invest it all back you will earn even more interest on the original $1,000.
Seriously are you guys for real? I am a mortgage advisor in the UK, and from what i can accertain, a HELOC is further borrowing against your property, or equity release as some call it. It's true that the interest rate on a secured loan such as a mortgage or a HELOC will be less than unsecured loans. This is nothing new.
What you need to ensure, is that you aren't repaying the debt over a longer term, if you are, you will be payng less on a monthly basis, but ultimately more in total. If you maintain your current monthly outgoings on the new interest rate, of course you'll pay off the debt sooner. But surely this is just common sense. In the same way that if you overpay on your mortgage, you will ultimately save.
What is interesting, is the speed at which you will pay off a mortgage just by increasing your monthly payment by a relatively small amount such as $100. Obviously depending on term and your monthly payment, the number of years knocked off will vary in each case.
A very easy way to pay off your mortgage earlier without increasing your real outgoings is to increase your monthly payments in line with inflation, ie your monthly payment is $500, inflation for the year just gone is 3% therefore your monthly payment for the next year is $515 the year after it is around $531. If you continue to do this you will take a good number of years off the mortgage without it affecting your real outgoings.
My original loan amount was $43,137.00. 30 year loan. My monthly payment is $395.31. I pay an aditional $104.69 or a total of $500.00. My loan will be payed off in 15 years. If I pay it off at 395.31 a month I will pay $142,311.60 If I pay it off at $500.00 a month. I will pay $90,000.00 That's a saveings of $52,311.60. Of course if I pay more, it will pay off even sooner. I'm sure the amount off your mortgages are higher than mine, but the same principal applies. Now you can send me the money you would have paid for that book.
The HELOC loan reduction plan, in which you use the HELOC account as your checking account, deposit your pay checks into it and pay your expenses out of it, is a methos that CPAs have been suggesting to their clients for years, Nothing new under the sun.
Yes, it works, and a few of the saner posters above me mentioned why: 1. By depositing your paychecks into the HELOC account you reduce the interest paid. 2. - and that's the biggie: You borrow on a simple interest rate loan to pay down a compound-rate loan.
Incidentally, you don't need any software to make it work. Just decide on the monthly amount taken from your HELOC to reduce your 1st mortgage principal, & make sure that your pay checks are deposited immediately into the HELOC account. From that point on you'll be watching in amazement as you see the mortgage balance disappear while your standard of living remains the same.
I read many comments and believe the people who are, as Econ PhD, above says "saner" have the right answers. The infomercial never says that they will recommend paying extra into the mortgage. Most of us know about the adding money to pay down the principle faster, anyway.
Like most infomercials the S&H is in the small print, and in this ad the cost of the "free" disc is too.
"Jill's" legs are great and well presented and hopefully not too enhanced by the video cameras. She is a plus for the infomercial.
As far as I can tell from the comments, we are being advised to take out a home equity loan, route our paychecks into the loan account, and pay the mortgage from that loan. I never thought of a home equity loan being used this way. Maybe that is why, I, a very over educated Ph.D. now with more debt than assets.
Nevertheless, I am wary of any system that has you borrowing on your home to pay off another loan on the same property. Anyone contemplating this should have a good handle on how disciplined they are with their money. I am a good example of one who tried the home equity borrowing for other debts.
My original mortgage began 25 years ago at $135,000. The monthly payment was every penny and more that my wife and I could afford. Times never did get better and I refinanced many times, usually to lower the interest rate, and almost always extending the length of the mortgage back up to 30 years.
Only once did I refinance for lower interest and a 15 year term, but that mortgage only lasted for a few years until the next refinancing.
Refinancing has taken me from a lowest principle of about $100,000 up to $368,000 tomorrow. The latest mortgage is for 30 years fixed 4.5% interest, that probably equals 4.9%. That will lower the monthly payments by $500 an amount that will recover closing costs in 14 months. I hope to use the extra $500 a month to pay my credit card debt.
I tell you this because my poor judgement, plus some unbelievably bad luck leaves me with a 30 year mortgage, $2200 payments on a home worth maybe $450,000 in todays market. I also still owe $30,000 in credit card debts, despite using more than one refinance to take money out of the home equity to pay off my home equity loans or credit card loans.
All of this happening well into my retirement years.
I believe that I am typical of many Americans now who still owe relatively large amounts after a lifetime of work (me for about 60 years!) We just got carried away (like our government) with easy credit and over-the-top borrowing and spending.
I just hope my pension holds up and savings will pay off the credit card. I doubt if I would stand up to working anymore, even if I could get a job.
I would have liked to move now to a warmer climate near my only child where housing costs are much lower, but do not know if I can do this now. I will hope for better luck in 2010.
Don't worry about $30, $300, or $3000 to help you get out of debt, if you are positive the source is good and will work for you, it could be money well spent. However, at least start with free advice. Use your public library or free (or next to free) public classes. Also, ask as many people as possible to give you their thoughts on saving, investing, spending.
I am a poor example, but given the circumstances, I did OK until, thinking the battle was over and won, when the great stock market gains over the past ten years, along with easy credit and low interest rates ended. Only luck kept me from losing even more of my retirement savings and enough were wiped out to finish my retirement travel hobby, that's for sure.
Best of luck to all, especially to the younger folks who can profit from the mistakes of others and from good, honest people's advice too.
How can you tell anything about how this woman`s legs look when she`s wearing dark hose and her legs are all knotted around each other? Anyones legs can look good if you hide all the flaws behind dark hose and sit just right.
The "Lady With the Smokin Hot Legs" is Jill Brown. (Her dark hose are sexy, Suzy!) She is an infomercial producer / consultant / hostess, Evidently not above hiking her skirt up to make a few bucks.
Jill brown fan....Wish I had a supporter like you!Thanx for the fitness video .I`m always looking for ways to flatten my abs.Don`t know if I can do`em but I`ll try`em!
Watched the infomercial (insomnia). i am from Australia and personally know the system well but i cant seem to find a bank here in the US who has the system I know of. Usually its a 20/80 ratio owned/bank, your pay goes into your mortgage account which also becomes your personal acc with cc access for exspenses.having your pay go onto your mortgage pays your balance down so you have less interest only to pay and more towards your principle. you pay your exps w/ your cc and before the interest free period is up (ie 28, 31 or 55 day cycle) you pay your cc off to a $0 balance. With this system you do not need an emergency savings plan, its your mortgage/personal/ cc acc. For some people who do not budget or those who "kinda budget" this is not for them.... You MUST watch your budget daily, have a clear visual plan not just an idea of where you are because you will be wrong and very wrong at that. Personally in australia we were very motivated on this system and enjoyed watching our mortgage dwindle. We also noticed our lifestyle didnt suffer infact it improved because we were so careful with our money we were able to afford vacations more frequently (with out splurging of course). It works, I know it does, its just a matter or finding it here in the US.
I just read a few of the other posts. In OZ if you needed your line of credit for emergencies there was no buy down or penalty as it was a "revolving line of credit" it worked in the sence you have access to the maximum 80% of your home value at all times provided you hadnt already maxed out. My parents had a $200,000 revolving line of credit for nearly 15 yrs (till Dad passed away), Mum sold the farm, bought a house and still has a $40,000 revolving line of credit for a just in case situation. She is 100% debt free untill she uses any money for travelling ect and pays it off little by little. She may not need to use any of the money for long periods of time but it is always there for her. Its great as she will never have to apply for another loan for the rest of her life.
Anyway like I said. i dont know of any bank who does that here. Shame for those like me we would greatly benefit and be responsible with our money even if we lost our jobs or faced an illness. But on a stock std fixed mortgage we have to have an emergency savings plan, we own out right both vehicles we have $0 cc debt even though we do have cc's. We budget tighter and we still get bunched in the same category as all the other lower to middle income households who have debt to the eye balls and bought a house bigger than the Jones just to keep up appearances. I personally dont care about the Jones infact I wish I could flip them off. secretly I do as our debt to income ratio is a meager 18% when I know some of you spend more than you earn.... Tisk Tisk.... Its not hard to live comfortable on $40,000 and no. we dont look broke we live in a good neighbourhood and our kids attend an exemplary public school.
I was a loan officer in a bank, a mortgage loan processor for credit unions and understand the concept of "closed end mortgages". Mortgage lenders many times will not administer your additional payment to the principal, unless you specifically designate the payment to go to principal. Additionally, they may not post bi-weekly payments to the mortgage, the software they have will not post until a full mortgage payment has accrued. If you apply your paycheck to the revolving HELOC created by these firms, the interest you pay for the month will be greatly reduced. Multiply that my months and the savings could be "extremely significant". I have yet to proceed with this product, my spouse lost her job 16 months ago and I feel we would have difficulty in getting approved. As soon as I feel comfortable to do so, I will.
The only way one pays his or her mortgage off faster, is to pay on the principal amount prior to the due dates on the monthly payment slips. This book or the knowledge it contains will not accomplish this. Their is no magic bullet folks! Please explain to all of us, this MAGICAL HELOC program/method, so we can all understand how digging deeper into debt helps you out of debt quicker. You sound like the people running our the US treasury department. Paying off the principal balance quicker than the amortization schedule, is the only way to reduce the total amount of interest you will lose to the banksters, if you stick to their payment schedule..
Sorry, this comment was created by me and NOT FRANK!!!!.
If you took that $300.00 and put that to your mortgage every year you would take roughly 2 years off your loan.
Yes, as listed above in comments, this program is correct and a scam as well. The idea of using an other loan (HELOC or whatever) to utilize while (live on) after you have paid off the next Mort. payment in advance, does give you the benefit of the lower term since ectra payment is made and then only use the Heloc money as you need it (in other words take it all out at the beginning of the montha nad re-pay with earnings o9ver the month). So this will save some net interest and cost no more. BUT the savings are based on the amount that you have paid in advance, which is very small. For a 250,000 30 year mortgate at 6.5%, you would save the interest on $1587 for the 30. This results in a net gain of 387 over the lenght of the loan (less than 1 payment removed). That assumes you get paid all in the middle of the month and then pay back the HELOC). So anything elso that subtracts from the loan balance is really jsut more money you have paid to the loan. With a complicated enough program, you may miss the fact that you are actually just paying more towards your loan. You see the net savings of what you would have paid over 30 years and irt looks impressive (maybe 100,000's of thousands). Of course if you looked at the compounded amount you would have gotten by investing that at the same rate it would be identical. It is true that 6.5% may not be possible to get with perfect saftey, so in that case it does make sense to "invest it there". Of course once paid to principle it can't be switched to anoter investment so is a long term proposition (not counting a HELOC of course, but the rate could go up there at sojme point).
So, the bottom line, is that this is a correct idea with no utility. Other than showing you the power of compounding and confusing you into thinking you can do something better with them that you could not have done on your own.
That is why I say this is a correct program, but for practical purposes it is a scam (since it definately misleads you in the program to come).
Please excuse typoe, as I do not have the ambition to proofread or spellcheck :)
Thank God for the freedom we have in this country to have all these different opinions. Just thought I'd throw in my "2 cents". First, I just saw the infomercial this morning. Interesting. I'd say do your due diligence and research what you're buying. 9 months ago my wife and I bought the $3500 money merge product a few of you have referred to. We absolutely love it! It's doing exactly what the agent and company said it would do. At first I thought it was expensive, but it's paid for itself already. And the customer service of the company has been the absolute best. If we have questions, they are there to help us. As you can tell, we're happy customers. We have been married over twenty years, and had tried a variety of methods to get out of debt...from refinancing, debt consolidation, extra mortgage payments and debt roll downs. We always ended up back in the same boat. Why?...it's all about discipline...which we (as most Americans) don't have. Our program has done a great job keeping us on track and showing us where our money is going and we can see the results of our actions. Bottomline...we're doing our part to get out of debt. Just find something that works for you and go for it! Good luck becoming "debt free"!
I posted the message below back in Sept. 2008, but it was removed recently and the email requests have stopped. I've sent the free excel files I mention to over 550 people. The offer is still open - just send me an emial and I will reply.
Making extra payments to principal is very easy to track. You don't need to buy a $40 book asking you to buy expensive software to do it. The amortization equation used to compute one's monthly payments for a given loan amount, interest rate and duration is well known and easy to derive if you know a little math. I made an excel spreadsheet that can track the extra principal payments, and another to show how your mortgage balance is reduced by additional payments to principal. You just input your mortgage information. I'd be glad to send it to anyone interested for free. These programs are rip-offs. Educate yourself, there's no reason to pay a lot of money to track it. A simple excel spreadsheet will do the trick. Email me for a copy. I'm an expert in cash flow analysis and the mathematics of finance, and hate to see people pay dearly for something of minimal value that should be free.peterkacensky@comcast.net
I have the book Mortgage Free for Life. I have read it and because I am so slow it took me about a week for it to click that the money would be paid back into the HELOC with the "extra" money that we don't spend at the end of the month. I totally get how this program could help me but am a bit scared at the same time. I am hoping to see this work and applied for a HELOC today. Hopefully I have enough equity in this housing slump to qualify!
Here is my question....what HELOC do I take the bank up on? They offer 1 yr fixed at 5.5%, 36 month fixed at 6.5% and 5 yr fixed for 7.5%. The first two go up to prime plus a half after the fixed rate (which right now is 5.5 but could change with the market). With all of them they are open for 10 years and they allow 90% of the value of the home (with a $10K minumum). They also require 40%DTI.
We qualify based on their credentials so long as the house is worth enough! I have been crunching some numbers and hopefully someone can tell me if I am looking at this right...
We owe $124,000 on our house at a 5.8% interest rate. Am I right that this equals $7,192 a month in interest? So this same loan will have $6,960 a month interest if I were to lump $4,000 from a HELOC....a savings of $232 a month. If I put all of our money into the HELOC and there ends up with a balance showing of say.....$2,000 on the HELOC at 5.5% I will pay $110 a month on that loan.....so am I right to say that I would save a total of $122 in interest a month? If so....is this a good program for me? Are there other savings that I am not considering? Am I missing something? Another question is the whole credit card situation...I don't have one! Can this program work effectively if I can't pay everything at one time? Or do I need to have a cc in order to make this work for me?
I know.....tons of questions...Thanks!
Sheree
for us dummies, all these abbreviations are hard .. what is DTI?
i wish people could be clear - make it IDIOT
make it IDIOT-proof for us please.. i admit i'm an idiot, and need the help
A 124,000 at 5.8% mortgage has a 599.33 monthly interest amount. (124,000 x .058) / 12 months = 599.3333
Though I waiver on whether this program really works or not, I'm sure that it probably doesn't really save you the kind of money it claims. Working in banks for the past 20 years, I assure that there is no secret way of paying off your debt. Either you pay the basic amount and pay for the full term, or you send in more and pay it off faster.
DTI = Debt To Income
I have done TARDUS AMERICA, which is the same concept. Cost 3,500 of the program. Paid off a $273,000 home in Hawaii purchased 2003, paid off 2005. Sold it in 1 week for 535,000 in 2006. The market has dramatically changed here and houses aren't selling for inflated costs like they were. Bought a 2nd home in 2005, paid it off in 2 years because I had extra income to throw toward it. Cost of the home was $675,000.
Since 2007, I am living in Hawaii without a house payment.
lk says:
14 months ago
some useful information on mortgage,but the paydown concept HELOC is a nicely vailed way of using your own money from your own paycheck to paydown your mortgage. the secret is add more money to your monthly mortgage bill. | http://hubpages.com/hub/mortgagefreeforlife | crawl-002 | refinedweb | 11,903 | 81.02 |
I’ve come across a very strange problem involving TLatex, which affects the standard C++ random number generator. (I’m using Root 5.34.32).
When drawing a TLatex object to a canvas, and then printing that canvas, the state of the C++ random number generator is somehow affected. Here is a minimal program to demonstrate what happens:
#include <iostream> #include "TCanvas.h" #include "TLatex.h" using namespace std; int main() { for(int i=0;i<10;++i){ cout << rand() << endl; } TCanvas c("c","",100,100); TLatex l(0,0,"hello"); l.Draw(); c.Print("tst.png","png"); cout << "-" << endl; for(int i=0;i<10;++i){ cout << rand() << endl; } return(0); }
If I run that multiple times, I get different random numbers in the second lot of 10 each time I run the program.
This behaviour only seems to occur for some print options (I’ve tested PDF, JPG and PNG files). If print out a root macro (.C), the sequence of random numbers is not affected.
What is going on here? | https://root-forum.cern.ch/t/tlatex-affects-random-number-generator-after-tcanvas-print/19491 | CC-MAIN-2022-27 | refinedweb | 173 | 66.64 |
The Great Elf Game adapted for Python North East - client & server
Project description
The annual Christmas Elves game server and client
Python North East December brings you the Christmas Elf Challenge. Your task, should you choose to accept it, is to collect the most
Running your Game
This part of the guide will give you the instructions to set up the game so you can start trying to set a high score!
Installation
Make sure you have Python installed - if you have Windows, check out the Beginner’s Guide of the Xmas Elves document.
Once you’re ready, you can get the client code running:
pyvenv venv . venv/bin/activate pip install pyne-xmas-elves
Building your Bot
Create your game file, called game.py:
from pyne_xmas_elves.client import BaseGame class Game(BaseGame): """Your main Game Class. """ PLAYER_NAME = 'Tom Cooper' def turn(self, elves_available): """Take a single turn. The elves_available argument will tell you how many elves you can use as a guide. """ send_to_woods = elves_available // 2 send_to_forest = (elves_available - send_to_woods) // 2 send_to_mountains = elves_available - send_to_forest return (send_to_woods, send_to_forest, send_to_mountains)
Helper Attributes
While taking a turn, you can access the following attributes on self:
- amount_raised
- current_turn
- last_turn
Run the game
After creating your bot, you can run the game:
elves game
Running the Server
Installing Dependencies
The server is self-contained with an SQLite database, so just install the requirements:
pip install -r requirements.txt
Running
We’re using Django Channels, so running the server is as easy as:
python server/manage.py runserver
The API
To interact with the server session, we use a simple REST API to send new data into the server. The full API docs can be found by running a server and navigating to /docs/.
Starting a New Session
To start a new session, send a POST request with a name variable form-encoded to https://<host>/sessions/:
curl -X POST -d player_name="Scott"
and you’ll get a simple JSON object back with a session URL that you post your turns against.
Taking a Turn
To take a turn, make a POST request against the day endpoint of a session.
Instructions and Rules
See the attached Google Doc for the rules and any of the latest tips and tricks.
Project details
Release history Release notifications | RSS feed
Download files
Download the file for your platform. If you're not sure which to choose, learn more about installing packages. | https://pypi.org/project/pyne-xmas-elves/0.6.0/ | CC-MAIN-2020-29 | refinedweb | 401 | 66.98 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.