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
You'll often see an object-relational mapping when the object-oriented programming paradigm meets the relational paradigm of most databases. An object-relational mapping is a bridge between the two worlds. It lets you define classes that correspond to the tables of a database. You can then use methods on those classes and their instances to interact with the database, instead of writing SQL. Using an object-relational mapping doesn't mean that you don't need to know how relational databases work, but it does save you from having to write SQL -- a common source of programming errors. You can find more than a dozen open source Python packages for working with a SQL database, not counting the special-purpose modules that connect Python to specific databases. SQLObject is the best such module. It's a full object-relational mapping package that's simple to use. SQLObject can do just about everything you might need to program a database. This article shows you how SQLObject interacts with a database, how to use SQLObject to write database access and data-validation code, and how to use it with legacy or pre-existing databases. I assume that you have some knowledge of Python and relational databases. Installing and setting up SQLObject SQLObject has a setup.py file and installs in the same way as any other Python package. If you're using Python V2.2, you also need to install the mxDateTime Python package (SQLObject uses Python V2.3's built-in datetime module, if it's available). To actually use SQLObject, you need to set up a database package and the Python interface to that type of database. SQLObject connects to several types of databases, including the three big open source products: MySQL, PostgreSQL, and the serverless SQLite. Finally, you need to create a database for your application. For SQLite, this means creating a file in which to store the database. For other databases, it means connecting to the database server, issuing a CREATE DATABASE command, and granting some database user access to the new database, so that SQLObject can use that user account to connect. Listing 1 shows how to create a new database in MySQL. Listing 1. Code to create a new database in MySQL mysql> use mysql; Database changed mysql> create database sqlobject_demo; Query OK, 1 row affected (0.00 sec) mysql> grant all privileges on sqlobject_demo to 'dbuser'@'localhost' identified by 'dbpassword'; Query OK, 0 rows affected (0.00 sec) mysql> flush privileges; Query OK, 0 rows affected (0.00 sec) Connecting to the database The first Python code you need to write is the database connection code. This is the only place you need to write different code based on which database you're using. For instance, if you want your application to use a SQLite database, you need to pass the path to the database file into the SQLite connection builder located in the sqlobject.sqlite package. If the database file doesn't exist, SQLObject will tell SQLite to create it with code such as: import sqlobject from sqlobject.sqlite import builder conn = builder()('sqlobject_demo.db') If you're using MySQL, or another database with a server, you pass in database connection information to the connection builder. Listing 2 provides an example for the MySQL database created in the previous section. Listing 2. Code to pass in MySQL database connection information import sqlobject from sqlobject.mysql import builder conn = builder()(user='dbuser', passwd='dbpassword', host='localhost', db='sqlobject_demo') Whatever database you're connected to, the connection code should go in a file called something like Connection.py, stored in some commonly accessible location. That way, you can import all the classes you define and use the conn object you've built. The conn variable will take care of all database-related details. Note, however, that some features of SQLObject are not available in SQLite or MySQL. You can't totally separate your choice of database from the code you write after you've connected. (See Using SQLObject with pre-existing tables for more information.) Defining the schema SQLObject makes it easy to act on a database table. As a first example, consider a database schema consisting of a single table for a phone book application as shown in Table 1. Table 1. Description of the phone_number table The SQL for this table would look something like this, depending on your flavor of SQL: CREATE TABLE phone_number ( id INT PRIMARY KEY AUTO_INCREMENT, number VARCHAR(14) UNIQUE, owner VARCHAR(255), last_call DATETIME, notes TEXT ) With SQLObject, you don't need to write this SQL code. You define the database table by defining a Python class. This code goes into a file called PhoneNumber.py, as shown in Listing 3. Listing 3. PhoneNumber.py import sqlobject from Connection import conn class PhoneNumber(sqlobject.SQLObject): _connection = conn number = sqlobject.StringCol(length=14, unique=True) owner = sqlobject.StringCol(length=255) lastCall = sqlobject.DateTimeCol(default=None) PhoneNumber.createTable(ifNotExists=True) Here's where you use the conn variable defined earlier. Each of your table classes needs to store a reference to a database connection in its _connection member. This information is used behind the scenes for all the database access to this class' table. From this point on, you don't have to worry about SQL or any particular database because your code can be expressed in terms of the abstract relational schema. A class that defines a table also has a set of members that define the table's fields. SQLObject provides StringCol, BoolCol, and so on -- one class for each of the database field types. The first time the createTable() method runs, SQLObject will create a table called phone_number. Afterward, it will just use that table because you call that method with ifNotExists set to True. Finally, note that there's no need to create a field object in PhoneNumber for the id field. Because SQLObject always needs this field object, it always creates one. Handling that old CRUD The famous acronym CRUD represents the four things you might do to a database row: Create, Read, Update, and Delete. After you've defined a class that corresponds to a database table, SQLObject represents operations on the rows of that table as operations on the class and its instances. Create To create a database row, you create an instance of the corresponding class with the code: >>> from PhoneNumber import PhoneNumber >>> myPhone = PhoneNumber(number='(415) 555-1212', owner='Leonard Richardson') Now the phone_number table has a row with my name in it. The PhoneNumber constructor takes values for the table columns as keyword arguments. It creates a row of phone_number using the data you provide. If, for some reason, that data can't go into the database, the constructor throws an exception. Here's what happens when the phone number isn't valid: Listing 4. Invalid phone number >>> badPhone = PhoneNumber() Traceback (most recent call last): File "<stdin>", line 1, in ? ... TypeError: PhoneNumber() did not get expected keyword argument number And here's what you'd see if the phone number was already in the database: Listing 5. Phone number already in database >>> duplicatePhone = PhoneNumber(number="(415) 555-1212") Traceback (most recent call last): File "<stdin>", line 1, in ? ... TypeError: PhoneNumber() did not get expected keyword argument owner Read (and query) An instance of an SQLObject class has all its fields available as members. This is in contrast to some other database-mapping tools that make a database row act like a dictionary. Thus, a PhoneNumber object has a member for each of the fields in its database row: Listing 6. Fields available as members >>> myPhone.id 1 >>> myPhone.owner 'Leonard Richardson' >>> myPhone.number '(415) 555-1212' >>> myPhone.lastCall == None True But how do you retrieve PhoneNumber objects that are already in the database? You need to get them by running a query against the database. This brings up SQLObject's query construction kit, one of the package's most interesting features. It lets you represent SQL queries as chains of Python objects. It's similar to what you can do with Criteria objects in Torque, if you're familiar with that object-relational package for the Java™ programming language. Each SQLObject class you define has a select() method. This method takes an object that defines a query and returns a list of items that match that query. For instance, this method call returns a list containing the first phone number in the database: Listing 7. The select() method >>> PhoneNumber.select(PhoneNumber.q.id==1) <sqlobject.main.SelectResults object at 0xb7b76cac> >>> PhoneNumber.select(PhoneNumber.q.id==1)[0] <PhoneNumber 1 PhoneNumber.q.id indicates that you want to run a query on the id field of the phone_number table. SQLObject overloads the comparison operators ( ==, !=, <, >=, and so on) to make queries out of what would otherwise be Boolean expressions. The expression PhoneNumber.q.id==1 becomes a query that matches every row whose id field has a value of 1. Here are some more examples: Listing 8. More examples >>> PhoneNumber.select(PhoneNumber.q.id < 100)[0] <PhoneNumber 1 >>> PhoneNumber.select(PhoneNumber.q.owner=='Leonard Richardson').count() 1 >>> PhoneNumber.select(PhoneNumber.q.number.startswith('(415)')).count() 1 You can use SQLObject's AND and OR functions to combine query clauses: Listing 9. AND and OR functions to combine query clauses >>> from sqlobject import AND, OR >>> PhoneNumber.select(AND(PhoneNumber.q.number.startswith('(415)'), >>> PhoneNumber.q.lastCall==None)).count() 1 The following query gets everyone you haven't called in a year and everyone you've never called at all: Listing 10. Everyone you haven't called in a year and everyone you've never called >>> import datetime >>> oneYearAgo = datetime.datetime.now() - datetime.timedelta(days=365) >>> PhoneNumber.select(OR(PhoneNumber.q.lastCall==None, ... PhoneNumber.q.lastCall < oneYearAgo)).count() 1 Update If you change a member of a PhoneNumber object, the change is automatically mirrored to the database: Listing 11. Change automatically mirrored to database >>> print myPhone.owner Leonard Richardson >>> print myPhone.lastCall None >>> myPhone.>> myPhone.lastCall = datetime.datetime.now() >>> #Fetch the object fresh from the database. >>> newPhone = PhoneNumber.select(PhoneNumber.q.id==1)[0] >>> print newPhone.owner Someone else >>> print newPhone.lastCall 2005-05-22 21:20:24.630120 There's just one caveat: SQLObject won't let you change the primary key of an object. It's usually best to let SQLObject manage the id field of your table, even if you happen to have another field you'd make the primary key if you weren't using SQLObject. You can delete a particular row object by passing its ID into its class' delete() method: Listing 12. Delete a row object >>> query = PhoneNumber.q.id==1 >>> print "Before:", PhoneNumber.select(query).count() Before: 1 >>> PhoneNumber.delete(myPhone.id) >>> print "After:", PhoneNumber.select(query).count() After: 0 Validating and converting data So far, you've been passing phone numbers in 14-character U.S. format. The database schema is designed to accept numbers in that format, which implies the underlying application -- whatever it might be -- expects them in that format. As it is, though, the code doesn't do anything to make sure that clumsy users or programmer bugs don't cause incorrectly formatted data to be put into the number field. SQLObject solves this problem by letting you define hook methods for validating and massaging incoming data. You can define one method for each field in a table. A field's hook method is named _set_[field name](), and it gets called whenever a value is about to be set for that field, whether as part of a create operation or an update operation. The hook method should (optionally) massage an incoming value into an acceptable format ,and then set it. Otherwise, it should throw an exception. To actually set a value, the method needs to call the SQLObject method _SO_set_(field name). Listing 4 shows a _set_number() method for PhoneNumber. If a phone number is totally without formatting, as in 4155551212, the method formats the number as (415) 555-1212. Otherwise, if the number is not in the correct format, the method throws a ValueError. A correctly formatted phone number -- or one that got massaged into a correct format -- is passed right on to SQLObject's _SO_set_number() method. Listing 13. The _set_number () method for PhoneNumber import re def _set_number(self, value): if not re.match('\([0-9]{3}\) [0-9]{3}-[0-9]{4}', value): #It's not in the format we expect. if re.match('[0-9]{10}', value): #It's totally unformatted; add the formatting. value = "(%s) %s-%s" % (value[:3], value[3:6], value[6:]) else: raise ValueError, 'Not a phone number: %s' % value self._SO_set_number(value) Defining relationships among tables So far, everything you've seen operates on a single table: phone_number. But real database applications usually have multiple interrelated tables. SQLObject lets you define relationships among tables as foreign keys. To demonstrate, let's apply a little database normalization to the previous example, splitting the owner field of PhoneNumber into a separate person table. The code shown in Listing 14 goes into a file called PhoneNumberII.py. Listing 14. Code for PhoneNumberll.py import sqlobject from Connection import conn class PhoneNumber(sqlobject.SQLObject): _connection = conn number = sqlobject.StringCol(length=14, unique=True) owner = sqlobject.ForeignKey('Person') lastCall = sqlobject.DateTimeCol(default=None) class Person(sqlobject.SQLObject): _idName='fooID' _connection = conn name = sqlobject.StringCol(length=255) #The SQLObject-defined name for the "owner" field of PhoneNumber #is "owner_id" since it's a reference to another table's primary #key. numbers = sqlobject.MultipleJoin('PhoneNumber', joinColumn='owner_id') Person.createTable(ifNotExists=True) PhoneNumber.createTable(ifNotExists=True) This PhoneNumber class has the same members as the old one, but its owner member is a reference to the primary key of the person table, instead of a reference to a string column in the phone_number table. This makes it possible to represent a single individual with two phone numbers: Listing 15. Represent a single individual with two phone numbers >>> from PhoneNumberII import PhoneNumber, Person >>> me = Person(name='Leonard Richardson') >>> work = PhoneNumber(number="(650) 555-1212", owner=me) >>> cell = PhoneNumber(number="(415) 555-1212", owner=me) The numbers member of Person, an SQLObject MultipleJoin, makes it easy to do a query based on a join of person to phone_number: Listing 16. Query based on join of person to phone_number >>> for phone in me.phoneNumbers: ... print phone.number ... (650) 555-1212 (415) 555-1212 Similarly, SQLObject lets you do many-to-many joins, using the MultipleJoin class. Using SQLObject with pre-existing tables One common use of SQLObject is to give a Python interface to a database created by another application. SQLObject has several features that help do this. Database introspection If you're working with tables that already exist in a database, you don't need to define the columns in Python. SQLObject can extract all the information it needs through introspection on the database. For example, the code in Listing 17 could go into PhoneNumberIII.py. Listing 17. Code for PhoneNumberlll.py import sqlobject from Connection import conn class PhoneNumber(sqlobject.SQLObject): _connection = conn _fromDatabase = True This class will take on the properties of the existing phone_number database table. You can interact with it just as if you had manually defined the class with all its columns, as in the previous examples. With SQLObject, you need to write the table definition only once -- whether you do it in SQL or in Python is up to you. However, this feature brings your choice of database back into the picture. For instance, the feature doesn't work at all with SQLite. It works at a basic level with MySQL, but it won't pick up foreign key relationships. If you're using MySQL and want to define foreign keys for a table, you'll need to define those fields in code after loading the schema from the database. Naming conventions The code in the previous section assumes that the pre-existing table conforms to SQLObject's naming conventions (for instance, a table's primary key field is called id, and words in column names are separated by underscores). The naming conventions for a table are defined in a Style class. SQLObject provides some Style classes corresponding to common database naming conventions. For instance, if your column names look likeThis, instead of like_this, you can use the MixedCaseStyle: Listing 19. Using the MixedCaseStyle import sqlobject from sqlobject.styles import MixedCaseStyle from Connection import conn class PhoneNumber(sqlobject.SQLObject): _connection = conn _fromDatabase = True _style = MixedCaseStyle If none of the prepackaged Style classes fit your needs, you can subclass the base Style class and define your own naming conventions. In the worst case, where a table's field names have been assigned with no rhyme or reason at all, you can name each field individually. A note on SQLObject limitations SQLObject wants you to think in object-oriented terms instead of relational terms. This is good for your comprehension and your programming productivity, but it's not so good for performance. After all, the database is still relational. How do you mark every phone number in the database as having been called? With SQL, you would use a single UPDATE command. With SQLObject, you need to iterate over the entire result set and modify the last_call member of each object, which is much less efficient. SQLObject sacrifices processor time for developer time. This is usually a good deal, but even in simple applications, you may need to drop down a level to the Python database interface and write raw SQL for some critical-path operations. Conclusion This article has covered SQLObject in breadth, but not much depth. It's a versatile tool with many small, convenient features. (I haven't even mentioned result slices, just to pick one.) Its limitations are easy to understand, and you can work around them by writing the SQL you need. SQLObject is to relational database programming what Python is to application programming: a convenient way to get the work done in a lot less time. Download Resources Learn - See a comparison of database-oriented Python libraries. - See the SQLObject documentation and examples. - MySQL is the most common open source database. Its Python interface module is called MySQLdb. - PostgreSQL has more high-end database features (for instance, triggers) than MySQL. It has a number of Python interfaces, including PyGreSQL and pyPgSQL. - SQLite is a bit of a database upstart. It offers the most commonly used features of SQL in a small footprint that doesn't require a server to run. - Visit the developerWorks Open source zone for extensive how-to information, tools, and project updates to help you develop with open source technologies and use them with IBM's products. Get products and technologies - Get the latest version of SQLObject. - If you're using Python V2.2, you need to download the mxDateTime Python package to access the date fields of database tables. -.
http://www.ibm.com/developerworks/opensource/library/os-pythonsqlo/
CC-MAIN-2014-52
refinedweb
3,160
56.96
09 February 2011 10:26 [Source: ICIS news] SINGAPORE (ICIS)--?xml:namespace> “Many investors saw the interest rate hike as an indication that inflationary pressure was still going strong as, otherwise, the government need not have introduced another measure to curb economic growth,” said Duan Lijun, a petrochemical analyst at Zhong Hui Futures in Shanxi, north China. The May LLDPE futures contract was the most liquid. It rose to yuan (CNY) 12,110/tonne ($1,846/tonne) before closing at CNY12,010/tonne on Wednesday afternoon, data from the Dalian Commodity Exchange (DCE) showed. The closing price was CNY45/tonne or 0.4% higher than the settlement price on 1 February, according to DCE’s data. China markets were closed on 2-8 February for the Lunar New Year holidays. China has been curbing its lending growth since last year as a result of the inflationary pressure created by its aggressive lending stance adopted in 2009. Meanwhile, an ongoing drought in the country’s key wheat production bases at Henan, Shandong and Shanxi also spurred speculation that the prices of agricultural products would rise further, said Shi Minzhu, a petrochemical analyst at Nan Hua Futures in Zhejiang, east China. However, the interest rate hike had a limited impact on the futures market because it was lower than widely anticipated, said Shi. Many analysts had anticipated a 50 basis-point increase, but the interest rate was raised by 25 basis points, she added. Nonetheless, some said the impact of tightened credit resulting from the interest rate hike would hit the financial market by late March and cause futures prices to fall. “The general market expectation is that a reversed impact [from the immediate bullish effect] would be felt after eight weeks,” said Li Chenming, a petrochemical analyst at Guangfa Futures in Guangzhou, south China. ($1 = CNY6.56) For more on linear low-density
http://www.icis.com/Articles/2011/02/09/9433491/china-lldpe-futures-rise-0.4-on-interest-rate-hike.html
CC-MAIN-2014-52
refinedweb
312
50.06
Hey amazing people, today we are gonna build a QR Code generator in Python. How QR Code Generator works? Our QR code generator takes some data as input. That data can be anything like a URL or some text. And then it creates a QR code from that input data. And in the final step, the QR Code is saved as an SVG file. Noe since you have a rough idea of how our QR generator is going to work, let's move on to the Project Setup section and make this magic happen. Project Setup Before we jump to coding, we need to install one module for our project. We are talking about pyqrcode module which doesn't come pre-installed with python and hence we have to install it manually. We can install this by simply running pip install pyqrcode command from the terminal. So let's do that. pip install pyqrcode Here we go it's done! Now let's move on to the fun part, the coding part. Let's Code Alright so remember the first thing we always do is import required modules into our project. In our case, we need to make use of pyqrcode module which we just installed onto our system. So now let's import it. import pyqrcode Awesome! So next thing we need to do is to get some user input to create a QR Code. data = input("Enter the text or link to generate QR code: ") Here we are simply using an input() function to obtain user input and storing it in the data variable. Now it's time we create the QR Code! qr = pyqrcode.create(data) Here we are simply using pyqrcode.create() function which is a part of our pyqrcode module. This function will take our user input as a parameter and will generate a QR code. That QR code will then be stored in the qr variable. However, we cannot see that QR code yet. To see it, we have to export it into a file. That can be easily done using another function... Here's how: qr.svg('qr_code.svg', scale = 8) Here we are using svg('FILE_NAME', scale = 8) function were we have to provide the name of the QR code file to be generated and a scale parameter which by default will be 8. And here we did it. Now go ahead and try this one out on your own. 🤩 Source Code You can find the complete source code of this project here - mindninjaX/Python-Projects-for-Beginners Support Thank you so much for reading! I hope you found this beginner project useful. (8) This isn't building a QRCode generator at all. It's a tutorial on how to import a library and call a function Hello Jon! Our tutorials are meant for Complete beginners and the main aim is to make them more familiar and comfortable with Python by exposing them with the expandability of the Python. Can you please elaborate the things you feel should be added to this tutorial to make it more effective... We always look forward for feedback to continuously improve our tutorials. Have a great day ❤️⭐ Yes I have bookmarked your website because this site contains valuable information in it. I am really happy with articles quality and presentation. Thanks a lot for keeping great stuff. I am very much thankful for this site.!!!! Link Building Service Try writing PNG files and generating qrcodes urself Hey Rishit! Can you please elaborate? We didn't exactly got what you meant... I mean generating qrcode with ur own code and without a library Sounds like a great idea! Will update our editor about this... Have a great day Rishit ⭐
https://practicaldev-herokuapp-com.global.ssl.fastly.net/mindninjax/how-to-build-a-qr-code-generator-in-python-1c13
CC-MAIN-2021-17
refinedweb
622
75.81
This page details the Player settings specific to the Universal Windows platformAn IAP feature that supports Microsoft’s In App Purchase simulator, which allows you to test IAP purchase flows on devices before publishing your application. More info See in Glossary. For a description of the general Player settings, see Player SettingsSettings that let you set various player-specific options for the final game built by Unity. More info See in Glossary. You can find documentation for the properties in the following sections: Use the Icon settings to customize the branding for your app on the Windows Store. Expand the Store Logo section to specify the image that appears on the Store description page for the application. You can add up to eight different resolutions. Customize the general appearance of your Windows Store tiles with these settings: Unity copies these options directly to the Package.appxmanifest file. Specify the images your tiles display on the Windows Store with these settings: Use the Resolution and Presentation section to customize aspects of the screen’s appearance. Choose the game’s screen orientation from the Default Orientation drop-down menu: When you set the orientation to Auto Rotation, the Allowed Orientations for Auto Rotation section appears.: Above the common Splash Screen settings, the Player Settings settings allow you to specify splash images for the Universal Windows, there are a few additional sections: Set the foreground image you want to use in your app’s splash screen. You can add up to seven different resolutions. Use these settings to customize the holographic splash image for Mixed Reality apps. Set a Holographic Splash Image to appear during startup. This image appears for five seconds (or until the app finishes loading). A Mixed Reality headset needs to build world-locked coordinate systems from its environment, in order to allow holograms to stay in position. Tracking loss occurs when the headset loses track of where it is (can’t locate itself) in the world. This leads to a breakdown in spatial systems (spatial mapping, spatial anchors, spatial stages). When this happens, Unity stops rendering holograms, pauses the game, and displays a notification. You can customize the notification image that appears by enabling the On Tracking Loss Pause and Show Image property, and then selecting the image to display with the Tracking Loss Image property. For more information, see Recommended settings for Unity. The common Splash Screen settings allow you to set the Background Color for when no background image is set, which applies to all platforms. To override this for the Universal Windows platform, you can enable the Overwrite background color property and then use the Background color setting to choose a different color. This section allows you to customize a range of options organized into the following groups: Use these settings to customize how Unity renders your game for the Univeral Windows platform.. Use these settings to customize building your Universal Windows app. These options are organized into the following groups: Unity stores these settings in the Package.appxmanifest file when creating a Visual Studio solution for the first time. Note: If you build your project on top of the existing one, Unity doesn’t overwrite the Package.appxmanifest file if it’s already present. That means if you change any of the Player settings, you need to check Package.appxmanifest. If you want to regenerate Package.appxmanifest, delete it and rebuild your project from Unity. For more information, see Microsoft’s documentation on App package manifest. Supported orientations from Player Settings are also populated to the manifest (Package.appxmanifest file in Visual Studio solution). On Universal Windows Apps, Unity resets the orientation to the one you used in the Player settings, regardless of what you specify in the manifest. This is because Windows itself ignores those settings on desktop and tablet computers. Tip: You can always change supported orientations using Unity scripting API. Every Universal Windows App needs a certificate which identifies a developer. You can click the Select button to choose your certificate file ( .pfx) from your local computer. The name of the file you selected appears on the Select button. If you don’t have a certificate file already, you can generate a file in Unity: Click the Create button. The Create Test Certificate for Windows Store dialog window appears. Enter the name of the package publisher in the Publisher text box. Enter the password for the certificate in the Password text box and then again in the Confirm password text box. Click the Create button. The window closes and the Certificate section displays the name you entered for both the Publisher and Issued by values. The Expiration date is set to one year from the time you created the certificate. Your Microsoft UWP application supports Streaming Install if the Scripting Backend is using IL2CPP. If you enable Streaming Install, Unity generates an AppxContentGroupMap.xml file containing stream include Scene Assets in the AppxContentGroupMap.xml file by default, use the Last required scene index setting, which uses the scene index in the Build Settings dialog. Assets in ScenesA Scene contains the environments and menus of your game. Think of each unique Scene file as a unique level. In each Scene, you place your environments, obstacles, and decorations, essentially designing and building your game in pieces. More info See in Glossary with a scene index above the Last required scene index are specified as streamable in the generated manifest. For an application to start, Unity requires any scene index at or less than the specified index. Scenes with a greater scene index must include shared assets for Scenes with a lesser index. The order of scenes in the Build Settings dialog may be important to allow the application to locate the required assets. Unity copies these options directly to the Package.appxmanifest file. The Dispay name value that you set at the top of the Player Settings settings appears in this section. This is the full name of the app. Enter the text you want to appear on the app’s tile on the Windows Store in the Description text box. This defaults to the Package display name value. The settings under the File Type Associations, File Types, and Protocol sections allow you to set up your Windows Store app as the default handler for a certain file type or URI scheme. Under the File Type Associations section, enter the name (lowercase only) for a group of file types in the Name text box. These are files that share the same display name, logo, info tip, and edit flags. Choose a group name that can stay the same across app updates. If you are setting this up as a file association: If you are setting this up as an association with a URI scheme, enter the protocol in the Name text box. For more information, see Auto-launching with file and URI associations (XAML) Unity uses Mono when compiling script files, and you can use the API located in .NET 4.x. To use .NET for Universal Windows Platform (also known as .NET Core) in your C# files, choose one of these values from the Compilation Overrides setting: Note: You cannot use .NET Core API in JS scripts. Here’s a simple example of how to use .NET Core API in scripts. string GetTemporaryFolder() { #if ENABLE_WINMD_SUPPORT return Windows.Storage.ApplicationData.Current.TemporaryFolder.Path; #else return "LocalFolder"; #endif } Unity receives input by subscribing to events. The Input Source setting defines where (which sources) to get input from. Currently this only applies to mouse and touch input, as keyboard input always comes from CoreWindow. Use the Capabilities section to enable APIs or resources you want your app to access. These could be pictures, music, or devices such as the cameraA component which creates an image of a particular viewpoint in your scene. The output is either drawn to the screen or captured as a texture. More info See in Glossary or the microphone. For more information, see App capability declarations Unity copies these options directly to the Package.appxmanifest file. Note: If you build your game on top of previous package, Package.appxmanifest won’t be overwritten. A device family identifies the APIs, system characteristics, and behaviors across a class of devices. It also determines the set of devices on which your app can be installed from the Store. See Microsoft’s Device families overview for more information. For more information, see Device family availability. Did you find this page useful? Please give it a rating:
https://docs.unity3d.com/Manual/class-PlayerSettingsWSA.html
CC-MAIN-2019-13
refinedweb
1,420
56.35
Tutorial How To Set Up the Eclipse Theia Cloud IDE Platform on DigitalOcean Kubernetes The author selected the Free and Open Source Fund to receive a donation as part of the Write for DOnations program. Introduction With developer tools moving to the cloud, creation and. Because they are natively based on cloud technologies, they are able to make use of the cluster to achieve tasks, which can greatly exceed the power and reliability of a single development computer. will set up the default version of the Eclipse Theia cloud IDE platform on your DigitalOcean Kubernetes cluster and expose it at your domain, secured with Let’s Encrypt certificates and requiring the visitor to authenticate. In the end, you’ll have Eclipse Theia running on your Kubernetes cluster available via HTTPS and requiring the visitor to log in. Prerequisites A DigitalOcean Kubernetes cluster with your connection configured as the kubectldefault. Instructions on how to configure kubectlare shown in Eclipse Theia using Ingress Resources. To do this, follow How to Set Up an Nginx Ingress on DigitalOcean Kubernetes Using Helm. A fully registered domain name to host Eclipse Theia. This tutorial will use theia.your_domainthroughout. You can purchase a domain name on Namecheap, get one for free on Freenom, or use the domain registrar of your choice. Step 1 — Installing and Exposing Eclipse Theia To begin you’ll install Eclipse Theia to your DigitalOcean Kubernetes cluster. Then, you will expose it at your desired domain using an Nginx Ingress. Since you created two example deployments and a resource as part of the prerequisites, you can freely delete them by running the following commands: - kubectl delete -f hello-kubernetes-ingress.yaml - kubectl delete -f hello-kubernetes-first.yaml - kubectl delete -f hello-kubernetes-second.yaml For this tutorial, you’ll store the deployment configuration on your local machine, in a file named eclipse-theia.yaml. Create it using the following command: - nano eclipse-theia.yaml Add the following lines to the file: apiVersion: v1 kind: Namespace metadata: name: theia --- apiVersion: networking.k8s.io/v1beta1 kind: Ingress metadata: name: theia-next namespace: theia annotations: kubernetes.io/ingress.class: nginx spec: rules: - host: theia.your_domain http: paths: - backend: serviceName: theia-next servicePort: 80 --- apiVersion: v1 kind: Service metadata: name: theia-next namespace: theia spec: ports: - port: 80 targetPort: 3000 selector: app: theia-next --- apiVersion: apps/v1 kind: Deployment metadata: labels: app: theia-next name: theia-next namespace: theia spec: selector: matchLabels: app: theia-next replicas: 1 template: metadata: labels: app: theia-next spec: containers: - image: theiaide/theia:next imagePullPolicy: Always name: theia-next ports: - containerPort: 3000 This configuration defines a Namespace, a Deployment, a Service, and an Ingress. The Namespace is called theia and will contain all Kubernetes objects related to Eclipse Theia, separated from the rest of the cluster. The Deployment consists of one instance of the theiaide/theia:next Docker image with the port 3000 exposed on the container. The Service looks for the Deployment and remaps the container port to the usual HTTP port, 80, allowing in-cluster access to Eclipse Theia. The Ingress contains a rule to serve the Service at port 80 externally at your desired domain. In its annotations, you specify that the Nginx Ingress Controller should be used for request processing. Remember to replace theia.your_domain with your desired domain that you’ve pointed to your cluster’s Load Balancer, then save and close the file. Save and exit the file. Then, create the configuration in Kubernetes by running the following command: - kubectl create -f eclipse-theia.yaml You’ll see the following output: Outputnamespace/theia created ingress.networking.k8s.io/theia-next created service/theia-next created deployment.apps/theia-next created You can watch the Eclipse Theia pod creation by running: - kubectl get pods -w -n theia The output will look like this: OutputNAME READY STATUS RESTARTS AGE theia-next-847d8c8b49-jt9bc 0/1 ContainerCreating 0 22s After some time, the status will turn to RUNNING, which means you’ve successfully installed Eclipse Theia to your cluster. Navigate to your domain in your browser. You’ll see the default Eclipse Theia editor GUI. You’ve deployed Eclipse Theia to your DigitalOcean Kubernetes cluster and exposed it at your desired domain with an Ingress. Next, you’ll secure access to your Eclipse Theia deployment by enabling login authentication. Step 2 — Enabling Login Authentication For Your Domain In this step, you’ll enable username and password authentication for your Eclipse Theia deployment. You’ll achieve this by first curating a list of valid login combinations using the htpasswd utility. Then, you’ll create a Kubernetes secret containing that list and configure the Ingress to authenticate visitors according to it. In the end, your domain will only be accessible when the visitor inputs a valid username and password combination. This will prevent guests and other unwanted visitors from accessing Eclipse Theia. The htpasswd utility comes from the Apache web server and is used for creating files that store lists of login combinations. The format of htpasswd files is one username:hashed_password combination per line, which is the format the Nginx Ingress Controller expects the list to conform to. Start by installing htpasswd on your system by running the following command: - sudo apt install apache2-utils -y You’ll store the list in a file called auth. Create it by running: - touch auth This file needs to be named auth because the Nginx Ingress Controller expects the secret to contain a key called data.auth. If it’s missing, the controller will return HTTP 503 Service Unavailable status. Add a username and password combination to auth by running the following command: - htpasswd auth username Remember to replace username with your desired username. You’ll be asked for an accompanying password and the combination will be added into the auth file. You can repeat this command for as many users as you wish to add. Note: If the system you are working on does not have htpasswd installed, you can use a Dockerized version instead. You’ll need to have Docker installed on your machine. For instructions on how to do so, visit the official docs. Run the following command to run a dockerized version: - docker run --rm -it httpd htpasswd -n <username> Remember to replace <username> with the username you want to use. You’ll be asked for a password. The hashed login combination will be written out on the console, and you’ll need to manually add it to the end of the auth file. Repeat this process for as many logins as you wish to add. When you are done, create a new secret in Kubernetes with the contents of the file by running the following command: - kubectl create secret generic theia-basic-auth --from-file=auth -n theia You can see the secret with: - kubectl get secret theia-basic-auth -o yaml -n theia The output will look like: OutputapiVersion: v1 data: auth: c2FtbXk6JGFwcjEkVFMuSDdyRWwkaFNSNWxPbkc0OEhncmpGZVFyMzEyLgo= kind: Secret metadata: creationTimestamp: "..." name: theia-basic-auth namespace: default resourceVersion: "10900" selfLink: /api/v1/namespaces/default/secrets/theia-basic-auth uid: 050767b9-8823-4fd3-b498-5f11074f768b type: Opaque Next, you’ll need to edit the Ingress to make it use the secret. Open the deployment configuration for editing: - nano eclipse-theia.yaml Add the highlighted lines to your file:' spec: rules: - host: theia.your_domain http: paths: - backend: serviceName: theia-next servicePort: 80 ... First, in the auth-type annotation, you specify that the authentication type is basic. This means that Nginx will require the user to type in a username and password. Then, in auth-secret, you specify that the secret that contains the list of valid combinations is theia-basic-auth, which you’ve just created. The remaining auth-realm annotation specifies a message that will be shown to the user as an explanation of why authentication is required. You can change the message contained in this field to your liking. Save and close the file. To propagate the changes to your cluster, run the following command: - kubectl apply -f eclipse-theia.yaml You’ll see the output: Outputnamespace/theia unchanged ingress.networking.k8s.io/theia-next configured service/theia-next unchanged deployment.apps/theia-next unchanged Navigate to your domain in your browser, where you’ll now be asked to log in. You’ve enabled basic login authentication on your Ingress by configuring it to use the secret containing the hashed username and password combinations. In the next step, you’ll secure access further by adding TLS certificates, so that the traffic between you and your Eclipse Theia deployment stays encrypted. Step 3 — Applying Let’s Encrypt HTTPS Certificates Next you will secure your Eclipse Theia installation by applying Let’s Encrypt certificates to your Ingress, which Cert-Manager will automatically provision. After completing this step, your Eclipse Theia installation will be accessible via HTTPS. Open eclipse-theia.yaml for editing: - nano eclipse-theia.yaml Add the highlighted lines to your file, making sure to replace the placeholder domain with your own:' cert-manager.io/cluster-issuer: letsencrypt-prod spec: tls: - hosts: - theia.your_domain secretName: theia-prod rules: - host: theia.your_domain http: paths: - backend: serviceName: theia-next servicePort: 80 ... First, you specify the letsencrypt-prod ClusterIssuer you created as part of the prerequisites as the issuer that will be used to provision certificates for this Ingress. Then, in the tls section, you specify the exact domain that should be secured, as well as a name for a secret that will be holding those certificates. Save and exit the file. Apply the changes to your cluster by running the following command: - kubectl apply -f eclipse-theia.yaml The output will look like: Outputnamespace/theia unchanged ingress.networking.k8s.io/theia-next configured service/theia-next unchanged deployment.apps/theia-next unchanged It will take a few minutes for the certificates to be provisioned and fully applied. You can track the progress by observing the output of the following command: - kubectl describe certificate theia-prod -n theia When it finishes, the end of the output will look similar to this: Output... Events: Type Reason Age From Message ---- ------ ---- ---- ------- Normal GeneratedKey 42m cert-manager Generated a new private key Normal Requested 42m cert-manager Created new CertificateRequest resource "theia-prod-3785736528" Normal Issued 42m cert-manager Certificate issued successfully Refresh your domain in your browser. You’ll see a green padlock shown on the leftmost side of the address bar signifying that the connection is secure. You’ve configured the Ingress to use Let’s Encrypt certificates thus making your Eclipse Theia deployment more secure. Now you can review the default Eclipse Theia user interface. Step 4 — Using the Eclipse Theia Interface In this section, you’ll explore some of the features of the Eclipse Theia interface. On the left-hand side of the IDE, there is a vertical row of four buttons opening the most commonly used features in a side panel. _5<< You’ve explored a high-level overview of the Eclipse Theia interface and reviewed some of the most commonly used features. Conclusion You now have Eclipse Theia, a versatile cloud IDE, installed on your DigitalOcean Kubernetes cluster. You’ve secured it with a free Let’s Encrypt TLS certificate and set up the instance to require a login from the visitor. You can work on your source code and documents with it individually or collaborate with your team. You can also try building your own version of Eclipse Theia if you need additional functionality. For further information on how to do that, visit the Theia docs.
https://www.digitalocean.com/community/tutorials/how-to-set-up-the-eclipse-theia-cloud-ide-platform-on-digitalocean-kubernetes
CC-MAIN-2021-31
refinedweb
1,925
54.02
There are a lot of instructions and examples of how to connect a 4 x 3 membrane keypad but I couldn't find instructions on how to connect a 4 x 4 Membrane Keypad to an Arduino. Step 1: Materials All that is needed for this Instructable is: - An Arduino compatible board with 8 free digital pins - A 4 x 4 Membrane Keypad Step 2: Install Keypad Library. Step 3: Modifying the Example Sketch In Example-->Keypad the default sketch "HelloKeypad" is set up for a 4 x 3 matrix. Here is the modified code for the 4 x 4 Keypad: #include <Keypad.h> ); void setup(){ Serial.begin(9600); } void loop(){ char key = keypad.getKey(); if (key){ Serial.println(key); } } Step 4: Connecting the Arduino to the Keypad Using the diagram above as a reference the leftmost pin is pin 8 on the keypad and the rightmost is pin 1. Pins 8, 7, 6, 5 on the keypad should be connected to digital pins 5, 4, 3, 2 on the Arduino respectively. Pins 4, 3, 2, 1 on the keypad should be connected to digital pins 9, 8, 7, 6 on the Arduino respectively. byte rowPins[ROWS] = {5, 4, 3, 2}; //connect to the row pinouts of the keypad byte colPins[COLS] = {9, 8, 7, 6}; //connect to the column pinouts of the keypad Step 5: Testing Upload the sketch to your Arduino and open the Serial Monitor. The pressed keys should be displayed as in the window above. Step 6: Going Further In Examples-->Keypad there are several examples. All the example sketches can be made to function with the 4 x 4 matrix by changing the following lines of code: const byte ROWS = 4; //four rows<br>const byte COLS = 4; //three 13 Discussions 2 months ago on Step 4 Why there is no gnd pin? Question 2 months ago Question is it hard to mod this code to put 2 key pads I need to have 26 buttons for my project Question 4 months ago on Step 3 Thank you for this instructable. I have a question regarding the code. Why did you identify the size of the array and the pin numbers to be in bytes? 1 year ago #include <Keypad.h> byte rowpin [4] = {2, 3, 4,5}; byte colpin [4] = {6, 7, 8,9}; char keys[4][4] = { {"1", "2", "3", "A"}, {"4", "5", "6", "B"}, {"7", "8", "9", "C"}, {"*", "0", "#", "D"}, }; Keypad shakthi = Keypad(makeKeymap(keys), rowpin, colpin, 4,4); void setup() { Serial.begin(9600); } void loop() { char key = shakthi .getKey(); if (key != NO_KEY) { Serial.println(key); } } Reply 10 months ago Get rid of the last comma in the array 1 year ago super nice explanation of the code and connections, but for the wiring you should of also added a Fritzing diagram! It turned out to wrk fine on my arduino mega 2560 without changin any single thing! Thanks. 1 year ago I made it with arduino nano. 1 year ago Thanks for sharing. I modified the code slight to avoid twisting of cables. It still works. byte rPins[Rows]= {9,8,7,6}; //Rows 0 to 3 connect to digital pins [Pins 8, 7, 6, 5 ] byte cPins[Cols]= {5,4,3,2}; //Columns 0 to 3 [Pins 4, 3, 2, 1 ] Code to convert '*' to '.' if (keypressed=='*') { keypressed='.'; // if you want to key in something like 0.2 }; 1 year ago Love your tutorial and I have one question regarding it... What do I need to do in the code if I want to flip the the Keypad cable/pinout? Thank you! ;) 2 years ago This doesn't work for me at all.. When i do this, i press 1, and 1 is shown to be pressed... I press 2, and it shows me 4 was pressed... If i press 4 it says 2 was pressed. It's completely turned around.. The thing is, i'm not sure if it's because your keypad is different, or because mine has a header, and i just plugged it in (pin 1 on the keypad header, to pin D2, and pin 8 on the keypad header, to pin D9 on the pro mini) However, it appears you have your keypad split into two, and reversed.. My question, why is it i can't simply reverse the order in the sketch and get it to work, rather than having to dig out 8 jumper wires? Reply 2 years ago The 8-pin header that came with my 4x4 keypad was installed backwards, so 1 was 8 and 8 was 1. Once I realized that, this code is perfect. Might be a common problem. Cheers! Chris. 2 years ago You explained it all very nicely. so now i understand the library usage, and how to bend it for my 4X4 keypad. thanks 3 years ago This is very useful. Thanks for sharing!
https://www.instructables.com/id/Connecting-a-4-x-4-Membrane-Keypad-to-an-Arduino/
CC-MAIN-2019-26
refinedweb
818
79.7
Round Robin(RR) scheduling algorithm is mainly designed for time-sharing systems. This algorithm is similar to FCFS scheduling, but in Round Robin(RR) scheduling, preemption is added which enables the system to switch between processes. A fixed time is allotted to each process, called a quantum, for execution. Once a process is executed for the given time period that process is preempted and another process executes for the given time period. Context switching is used to save states of preempted processes. This algorithm is simple and easy to implement and the most important is thing is this algorithm is starvation-free as all processes get a fair share of CPU. It is important to note here that the length of time quantum is generally from 10 to 100 milliseconds in length. Some important characteristics of the Round Robin(RR) Algorithm are as follows: Round Robin Scheduling algorithm resides under the category of Preemptive Algorithms. This algorithm is one of the oldest, easiest, and fairest algorithm. This Algorithm is a real-time algorithm because it responds to the event within a specific time limit. In this algorithm, the time slice should be the minimum that is assigned to a specific task that needs to be processed. Though it may vary for different operating systems. This is a hybrid model and is clock-driven in nature. This is a widely used scheduling method in the traditional operating system. Completion Time It is the time at which any process completes its execution. Turn Around Time This mainly indicates the time Difference between completion time and arrival time. The Formula to calculate the same is: Turn Around Time = Completion Time – Arrival Time Waiting Time(W.T): It Indicates the time Difference between turn around time and burst time. And is calculated as Waiting Time = Turn Around Time – Burst Time Let us now cover an example for the same: In the above diagram, arrival time is not mentioned so it is taken as 0 for all processes. Note: If arrival time is not given for any problem statement then it is taken as 0 for all processes; if it is given then the problem can be solved accordingly. The value of time quantum in the above example is 5.Let us now calculate the Turn around time and waiting time for the above example : Average waiting time is calculated by adding the waiting time of all processes and then dividing them by no.of processes. average waiting time = waiting time of all processes/ no.of processes average waiting time=11+5+15+13/4 = 44/4= 11ms // Program implementation in C++ for Round Robin scheduling #include<iostream> using namespace std; //The Function to find the waiting time for all processes void fWaitingTime(int processes[], int n, int bt[], int wt[], int quantum) { // Let us Make a copy of burst times bt[] to store remaining burst times int rem_bt[n]; for (int i = 0 ; i < n ; i++) rem_bt[i] = bt[i]; int t = 0; // for Current time // Let us keep traverse the processes in the round robin manner until all of them are not done. while (1) { bool done = true; //let us Traverse all processes one by one repeatedly for (int i = 0 ; i < n; i++) { // If burst time of a process is greater than 0 then there is a need to process further if (rem_bt[i] > 0) { done = false; // indicates there is a pending process if (rem_bt[i] > quantum) { // By Increasing the value of t it shows how much time a process has been processed t += quantum; // Decreasing the burst_time of current process by the quantum rem_bt[i] -= quantum; } // If burst time is smaller than or equal to the quantum then it is Last cycle for this process else { // Increase the value of t to show how much time a process has been processed t = t + rem_bt[i]; // Waiting time is current time minus time used by this process. wt[i] = t - bt[i]; // As the process gets fully executed thus remaining burst time becomes 0. rem_bt[i] = 0; } } } // If all the processes are done if (done == true) break; } } // Function used to calculate the turn around time void fTurnAroundTime(int processes[], int n, int bt[], int wt[], int tat[]) { // calculating turnaround time by adding bt[i] + wt[i] for (int i = 0; i < n ; i++) tat[i] = bt[i] + wt[i]; } // Function to calculate the average time void findavgTime(int processes[], int n, int bt[], int quantum) { int wt[n], tat[n], total_wt = 0, total_tat = 0; // Function to find waiting time of all processes fWaitingTime(processes, n, bt, wt, quantum); // Function to find turn around time for all processes fTurnAroundTime(processes, n, bt, wt, tat); // Display processes along with all details cout << "Processes "<< " Burst time " << " Waiting time " << " Turn around time\n"; // Calculate the total waiting time and total turn // around time for (int i=0; i<n; i++) { total_wt = total_wt + wt[i]; total_tat = total_tat + tat[i]; cout << " " << i+1 << "\t\t" << bt[i] <<"\t " << wt[i] <<"\t\t " << tat[i] <<endl; } cout << "Average waiting time = " << (float)total_wt / (float)n; cout << "\nAverage turn around time = " << (float)total_tat / (float)n; } //Given below is the Driver Code int main() { // process id's int processes[] = { 1, 2, 3,4}; int x = sizeof processes / sizeof processes[0]; // Burst time of all processes int burst_time[] = {21, 13, 6,12}; // Time quantum int quantum = 2; findavgTime(processes, x, burst_time, quantum); return 0; } The output of the above code is as follows: Some advantages of the Round Robin scheduling algorithm are as follows: While performing this scheduling algorithm, a particular time quantum is allocated to different jobs. In terms of average response time, this algorithm gives the best performance. With the help of this algorithm, all the jobs get a fair allocation of CPU. In this algorithm, there are no issues of starvation or convoy effect. This algorithm deals with all processes without any priority. This algorithm is cyclic in nature. In this, the newly created process is added to the end of the ready queue. Also, in this, a round-robin scheduler generally employs time-sharing which means providing each job a time slot or quantum. In this scheduling algorithm, each process gets a chance to reschedule after a particular quantum time. Some disadvantages of the Round Robin scheduling algorithm are as follows: This algorithm spends more time on context switches. For small quantum, it is time-consuming scheduling. This algorithm offers a larger waiting time and response time. In this, there is low throughput. If time quantum is less for scheduling then its Gantt chart seems to be too big. 1.Decreasing value of Time quantum With the decreasing value of time quantum The number of context switches increases. The Response Time decreases Chances of starvation decrease in this case. For the smaller value of time quantum, it becomes better in terms of response time. 2.Increasing value of Time quantum With the increasing value of time quantum The number of context switch decreases The Response Time increases Chances of starvation increases in this case. For the higher value of time quantum, it becomes better in terms of the number of the context switches. 3. If the value of time quantum is increasing then Round Robin Scheduling tends to become FCFS Scheduling. 4.In this case, when the value of time quantum tends to infinity then the Round Robin Scheduling becomes FCFS Scheduling. 5. Thus the performance of Round Robin scheduling mainly depends on the value of the time quantum. 6.And the value of the time quantum should be such that it is neither too big nor too small.
https://www.studytonight.com/operating-system/round-robin-scheduling
CC-MAIN-2022-21
refinedweb
1,270
55.07
triangula.util: Helpful Things¶ The triangula.util package contains functionality that’s generally useful but which doesn’t belong anywhere else. At the moment this includes a function to get the current IP address and a class triangula.util.IntervalCheck which is incredibly helpful when handling potentially slow responding hardware, or hardware which cannot be polled at above a certain rate, within a fast polling loop such as Triangula’s task framework or PyGame’s event loop. Using IntervalCheck¶ You’ll often find you’re running code in an event loop, this is a loop which has to run as fast as possible and which services everything you need to handle - input, output, providing feedback, reading sensors etc. Some of your sensors or output devices probably can’t keep up with this rate, and it’s possible you want to do expensive calculations that don’t have to be done on every single iteration through the loop. You want the loop to complete as fast as possible to keep everything responsive, so littering your code with time.sleep() calls is a bad idea, but you also need to ensure that e.g. you only update your motor speeds at most twenty times per second. The triangula.util.IntervalCheck can be used in several different ways to handle several corresponding timing issues: - Rate limiting You want to update e.g. an LCD display within a fast polling event loop, but the display will flicker like mad if you try to update every time around the loop, and the delay imposed by performing the update will unreasonably slow down everything else. from triangula.util import IntervalCheck once_per_second = IntervalCheck(interval = 1) while 1: if once_per_second.should_run(): # Do the thing that must happen at most once per second pass # Do the stuff that has to happen every time around the loop pass This will ensure that the code within the ifstatement will only be run at most once per second. Note that this makes no guarantee about delays between the code finishing and the next iteration starting - if the code in this block takes exactly a second to run there will be no delays at all. - Delay padding You have a piece of hardware which can be written to or read from, but you must leave at least a certain delay between consecutive operations. You don’t want to just use time.sleep()because you’d like to be able to get on with other things while you wait. You can use two different kinds of delay here. The first will sleep for a minimum delay since the last time the sleep method was called: from triangula.util import IntervalCheck delay = IntervalCheck(interval = 1) while 1: # If it's been less than a second since we last ran, sleep until it'll be exactly a second delay.sleep() # Run the thing you want to run pass This, again, makes no guarantee that there will actually be a delay. The second’s delay (in this case) is counted from when the previous sleep() call was made. There will be cases where you absolutely must have a delay between a block of code completing and the next time that same block is called, for this you can use the withbinding provided by the IntervalCheck: from triangula.util import IntervalCheck padding = IntervalCheck(interval = 1) while 1: with padding: # Any code here will be run immediately the first time, then on # subsequent occasions, on entry to the ``with`` block there will # be a pause if required such that the time from the previous # completion of the ``with`` block to the start of this one is at # least one second pass - class triangula.util. IntervalCheck(interval)[source]¶ Utility class which can be used to run code within a polling loop at most once per n seconds. Set up an instance of this class with the minimum delay between invocations then enclose the guarded code in a construct such as if interval.should_run(): - this will manage the scheduling and ensure that the inner code will only be called if at least the specified amount of time has elapsed. This class is particularly used to manage hardware where we may wish to include a hardware read or write in a fast polling loop such as the task manager, but where the hardware itself cannot usefully be written or read at that high rate. Instances of this class can also be used in ‘with’ clauses, i.e. ‘with interval:’ - this will sleep if required before running the gated code, then set the last run time to be the current time. This is not quite the same as just calling sleep() before running a code block, as it resets the time after the code has run, instead of after the sleep call has completed. Used in this mode therefore the interval is from the end of one code block to the start of the next, whereas normally it is from the start of one code block to the start of the next. should_run()[source]¶ Determines whether the necessary interval has elapsed. If it has, this returns True and updates the internal record of the last runtime to be ‘now’. If the necessary time has not elapsed this returns False sleep()[source]¶ Sleep, if necessary, until the minimum interval has elapsed. If the last run time is not set this function will set it as a side effect, but will not sleep in this case. Calling sleep() repeatedly will therefore not sleep on the first invocation but will subsequently do so each time. triangula.util. get_ip_address(ifname='wlan0')[source]¶ Get a textual representation of the IP address for the specified interface, defaulting to wlan0 to pick up our wireless connection if we have one.
https://pythonhosted.org/triangula/api/util.html
CC-MAIN-2018-30
refinedweb
960
55.47
Alcon is a lightweight logging and debugging tool for Flash developers who want to quickly get debugging information from their projects. It offers an easy to use API for use in your source code which sends debug information to an output console from any kind of Flash-based runtime, be it the web Flash player, the standalone Flash player or the AIR runtime. Besides simple logging, Alcon comes packed with several other useful features like an app monitor to watch your application’s framerate and memory consumption, an object inspector to check object properties, a stopwatch, a feature to quickly check key and character codes and a lot more. Feature list: - Logging API: Send logging information from anywhere in your application by using the logging methods and five different filter levels (debug, info, warn, error, fatal). - App Monitor: Use Alcon’s App Monitor to watch your application’s framerate and memory consumption. - Object Inspector: Check properties of any object recursively by inspecting them with the Object Inspector or by tracing them with traceObj(). - Stopwatch: Check how long any operation in your application takes by measuring it’s execution time with the Stopwatch API. - Hex Dump: Output any object as a hexadecimal dump. - Key Tracer: The built-in Key Tracer can be used to quickly check what key and/or character code any pressed key is associated with. - Options: Configure options like the output font and colors to your preference. - Built-in Help: Use Alcon’s built-in help and API documentation to quickly get started. - Keyboard Shortcuts: Use quick keyboard shortcuts to pause, clear, reset or scroll the console. - Disabling: The whole Alcon API can be quickly disabled with one simple method call, useful for going live without removing the debug code. Sample package { import com.hexagonstar.util.debug.Debug; import flash.display.Sprite; public class AlconTest extends Sprite { /** * Constructor. */ public function AlconTest() { Debug.monitor(stage); Debug.trace("Welcome to Alcon!"); } } } Alcon debugging tool for Flash developers #as3 #flash #fb
http://www.as3gamegears.com/debug/alcon/
CC-MAIN-2020-10
refinedweb
330
54.93
. However, another way to refer to a static member is through the object instance. All these leads to subtle confusion as to what :: actually denotes. // class with static member struct Widget { static int Count; }; Widget o; Widget* p = &o; // Accessing Widget's static Count int a = Widget::Count; int b = o.Count; int c = p->Count; The :: operator is also used by scoped enum to refer to its enumerators. // enum class enum class Fruit { Apple, Orange, Banana }; // usage of scoped enum Fruit::Orange Efforts to mimick the C++11 scoped enum syntax without its safety is by enclosing unscoped enum inside a namespace or class. So :: operator actually does not tell the developer reading the enum usage about the enum type. // namespace scoped enum namespace Fruit { enum fruit { Apple, Orange, Banana } }; // usage of namespace scoped enum Fruit::Orange Moreover, when an unscoped enum is a class member, its enumerators may be accessed using class member access operators . and ->. All these adds up to the confusion. // class scoped enum struct Fruit { enum fruit { Apple, Orange, Banana } }; // usage of class scoped enum Fruit::Orange Fruit x; Fruit* p = &x; int c = x.Orange; int d = p->Orange; Similarly, the -> operator is not only used in pointer-to-member but also to indicate return type of lambda. // Example of C++11 lambda with boolean return type auto lambda = []() -> bool {...} In C++17, the -> operator is used in type deduction guides(See code example below). // C++17 Deduction Guides template<typename T> struct S { T val; }; // map string literals to S<std::string> S(const char*) -> S<std::string>; In an effort to end all confusion in one fell swoop, -> and :: operators are going to be deprecated in favor of the universal . operator. In addition to this new development, C++23 is going to get garbage collection to manage its memory and every C++ class inherits automatically from the base Object class! “That’s great news! I can make use of my father’s 1995 original Java textbook to learn C++23!” – Russian college student, Sabina Before anyone makes a serious commentary to this blog post, take a good look at the posting date! For those who like this year’s April’s Fool post, be sure to check out 2019 and 2020 April’s Fool post: Leave a Reply to Put sleep() to make more money from HFT. And Lock-free vs Block-free – Coding Tidbit Cancel reply
https://codingtidbit.com/2021/04/01/c23-and-to-be-replaced-by-operator/?replytocom=1701
CC-MAIN-2022-33
refinedweb
405
59.94
. I know I'm reviving an old animal here, but does anybody have any information on this? It'd be a really good idea to have a close hook with Sublime 3 (or 2) to be able to cleanup any servers you may've created i'm interested in that too, though I suppose it's the kind of thing that's built for an OS to do.. e.g. in windows a bat file could do something before it runs, run it, then do something after it runs. Or jscript/vbscript, a .js file or .vbs file, could launch sublime, and do something before and after(with no cmd window popping up). Bear in mind also that an application can be closed with tasklist /f /im blah.exe and it's closed before it knows what hit it. So to really know it has just closed, the wrapper method provided by the OS, OS scripting, seems good. For open, you can probably use plugin_loaded with an 'already loaded' global variable. Example: def plugin_loaded(): global loaded try: loaded except NameError: loaded = True do_startup_stuff() For cleaning up subprocesses on close, you can fork a subprocess that monitors sublime. If the sublime process disappears, you can do cleanup. This isn't super portable, but you can use third-party modules like psutil to help or check your platform and use ctypes on Windows.
https://forum.sublimetext.com/t/events-for-application-start-close/8080/2
CC-MAIN-2016-36
refinedweb
231
71.34
RAW + JPEG Is there any way that I can use pythonista to comb through my photos and remove the RAW component to a RAW + JPEG that are imported to photos via SD dongle? I envision this leaving the JPEGs as is. The Why: - I shoot RAW + JPEG because my camera has a built in raw converter that I can do a quick edit and render a new JPEG. If I could choose to only import JPEGS only I would just do that, but silly iPad isn't that bright. So both the RAW and JPEG are imported taking significant space. If I could run a little pythonista script to remove the raw file that would be great. I'm fairly familiar with photos assets - but haven't seen anything to separate a raw from jpeg and then remove that. Thanks for your help! The photos module might be of some help. You can get an albumn, or all assets, then use deleteon an asset to delete it. It looks like you can use objc_util for determining if an asset is raw: import photos from objc_util import * for a in photos.get_assets(): if ObjCInstance(a).isRAW(): a.delete() print('deleted ', a) There may be less brute force ways (searching a single album, rather than all) You shoudl probably test this on something you dont care about, to verify that the raw and jpeg get separate assets.... I think RAW+JPEG are typically represented as one asset with two PHAssetResources. Asset resources are not supported (bridged) in the photosmodule, so you would have to work with the Objective-C APIs directly, using objc_util, but I'm frankly not sure how you could delete an asset resource. Haven't found much about this by googling. Awesome thanks guys. The Photos module I was playing around with and couldn't find a way. I'm not at all familiar with objc_util. So, time to learn! Thanks for the example. I'll play around and if I can make an elegant (-ish) way I'll post it back here.
https://forum.omz-software.com/topic/4004/raw-jpeg
CC-MAIN-2019-04
refinedweb
344
73.27
Feedback Getting Started Discussions Site operation discussions Recent Posts (new topic) Departments Courses Research Papers Design Docs Quotations Genealogical Diagrams Archives The April issue of C/C++ Users Journal has an article called A New Solution To an Old Problem by Andrew Koenig and Barbara E. Moo. In it, they revisit the Hamming numbers problem from Dijkstra's A Discipline of Programming. They examine four different solutions: O(n^2) O(n) O(n*log(n)) The Haskell solution is the following scale n (x:xs) = (n * x) : (scale n xs) merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) = if x == y then x : (merge xs ys) else if x < y then x : (merge xs (y:ys)) else y : (merge (x:xs) ys) seq = 1 : (merge (scale 2 seq) (merge (scale 3 seq) (scale 5 seq))) Their "idiomatic C++" solution uses ordered sets: set<int> seq; seq.insert(1); set<int>::const_iterator it = seq.begin(); int val = *it; seq.insert(val * 2); seq.insert(val * 3); seq.insert(val * 5); it++; In conclusion, they have this to say (emphasis mine),. I may be reading too much into this quote, but it sounds to me like Koenig and Moo consider it a bad thing to require a "totally different way of thinking about programming". P.S. While googling for Hamming numbers, I came across this related paper: Expressivity of Functional-Logic Languages and Their Implementation by Juan José Moreno Navarro. but it sounds to me like Koenig and Moo consider it a bad thing to require a "totally different way of thinking about programming". Of course they do. Remember that one of the core design values of C++ is building upon pre-existing knowledge and expectations from C. I think there is an inherent conservativeness in the C/C++ community, partly because of this value and partly because they are the "powers that be" in many programming domains.. First, it's a fair observation that when you're faced with a problem and someone proposes a paradigm shift as a solution, you should explore all other avenues first, because paradigm shifts are high-cost events by definition. Given this, it's not clear to me that Koenig and Moo are necessarily hostile to FP, and in fact anyone who writes forcefully about taking full advantage of the STL, as Koenig and Moo have done, can't be all that hostile to it! However, even if I'm mistaken on that last point, it doesn't mean that the entirety of the C++ community agrees, or even that people who are on the standards committee agree: witness Bjarne Stroustrup's insistence that C++ is multiparadigm including functional programming, boost::lambda, FC++, and Phoenix. Also, boost::lambda and Phoenix are being integrated, and hopefully at some future date we'll also see monads make it from FC++ into whatever the integrated boost functional programming library is called. It pains me to say it... but C++ is my fourth-favorite functional language. That may not sound like much, but the fact that it's on my list at all just flabbergasts me. For the curious, my first three are Oz, O'Caml, and the Lisp family. it's a fair observation that when you're faced with a problem and someone proposes a paradigm shift as a solution, you should explore all other avenues first, because paradigm shifts are high-cost events by definition. STL was a paradigm shift at the time it was introduced, was it not? This is the big advantage C++ has- even over other "Object Oriented C" languages (like Objective-C). It provides the new "paradigm" (or pseudo-paradigm- I don't think templates in C++ or modules in Ocaml quite qualify as full on paradigms by themselves) without really requiring it. You can ignore it if you don't understand it or don't understand it well enough to use it right now. I still know a number of programmers supposedly programming in C++ whose code looks awfully similiar to C. Note that this is also a disadvantage of C++, in that code written by one programmer who "knows" the language is not necessarily understandable by another programmer who "knows" the language. Surely you mean that code written by a programmer who knows the language may not be comprehensible to one who "knows" (i.e. doesn't know) the language? I think his point was that it's quite possible (actually, common) for one C++ programmer to know the language from one angle and another programmer to know it from another angle, and for each of these programmers to find the other's code incomprehensible, even though they're both writing perfectly valid ANSI C++. I encounter this phenomenon a lot: I make no apologies for the fact that my C++ style is very much driven by the modern capabilities of the language and libraries coupled with my background as a Lisp and, nowadays, O'Caml programmer. Folks who come to C++ with what I think of as the MFC (or, to be fair, MacApp) perspective frequently find my code incomprehensible (I pasted some compiling, but not working, source code into a chat with other C++ programmers with over a decade's experience and had one of them seriously challenge the idea that the code would even compile). Conversely, I find code written in the rely-on-members-in-a-superclass-to-side-effect-a-data-member-that-I-rely-on, coupled with plain-ol'-public-data-members, style utterly incomprehensible as well. C++ now supports multiple diametrically opposed styles and their associated communities. This is something that it has in common with Perl. I leave you to draw your own conclusions about that. In my experience, there are three main "styles" of C++ programmers I've seen: First, there is C-with-classes programmer. These people are comming out of the C world, and they're not really comfortable with all these new-fangled stuff. Often times, there code will compile and run perfectly fine on a straight C compiler. Most of the rest use the occasional class or STL library, but not often. You'd have to change maybe 1% of the code to get it to compile as C. The red flag that you're dealing with a C-with-classes programmers is when you can do: #define class struct and everything still pretty much works. Next up is the Java++ programmer. These are people comming out of the Java, Python, Ruby, etc. world. And they are still programming in said languages. They use objects a lot, but avoid using features not in these languages, like pointer arithmetic, templates, operator overloading, etc. The red flag that you're dealing with a Java++ programmer is when you start seeing classes with only virtual member functions all over the place (that's how you implement an interface, see...). Also, a tendancy to allocate everything on the heap and unbox almost nothing is also a common warning sign. Lastly, there is the he-man C++ programmer. Generally, these people don't really know another language- several of them may have learned Pascal or Scheme back in college, but they're "grown-ups" using "grown-up languages" now (just ask them), but an increasing number of them learned C++ as their first language and never moved on. These programmers have memorized everything Bjarne Stroustrup ever wrote, and are out to prove it. The red flag that you're dealing with a he-man C++ programmer is that you find yourself having to look up what a private const static virtual constructor means, because that's critical to understanding why the code even works. He-man C++ programmers love template metaprogramming, which is possibly the most damning thing I can say about them. He-man C++ programmers never, ever eat quiche. In fairness, though, plenty of C++ code uses a lot of classes, as it is written by people who have graduated beyond the first category, but have yet to discover "advanced" features like STL, templates, or operator overloading in any meaningful way, or don't really need it that much, to grind out code. There's a natural tendancy to assume I listed the classes from least advanced to most advanced. Well, OK- the c-with-classes folks generally really don't know C++. But I tend to fall into the Java++ class, despite knowing all about templates, operator overloading, etc. Simply because a language provides a feature doesn't mean you should use it at every opportunity- as the IOCCC shows. And while the Java++ programmers may be ignorant of the more obscure corners of the languages, He-man C++ programmers are just as commonly (in my experience) ignorant of Design Patterns. I've seen He-man C++ programmers be completely baffled by the code written by Java++ programmers. Not that they didn't understand the mechanics of how the code worked, but because they didn't understand the metaphors and patterns the Java++ programmer was using. You do know what quotes signify, right? And I meant them. Simply because you're up on the syntax and semantics of C++ doesn't necessarily make you a superior programmer over the guy who just got introduced to the language a week ago. ...like money buying you happiness, it certainly helps a lot! I meant in English. Simply because you can think up snide asides doesn't make you more articulate. The red flag that you're dealing with a C-with-classes programmers is when you can do: #define class struct and everything still pretty much works. by language definition every c++ program works just as well with the above macro applied. have a look at the c++ standard to figure out why... you should at least support your overgeneralizing critique by providing correct accusations. in my personal experience i have met just as many close-minded and/or incompetent c++ programmers as i have met such persons in most other language community of your choice. attitude and skill is usually not directly related to programming language preference.. True, and it results in a pretty irrational argument on the part of the authors of this article. On the one hand, the article implicitly demonstrates the benefits of considering multiple approaches to solving a problem, in that by doing so, we can find solutions that meet a desired balance between e.g. expressivity and performance. That's how they achieved their new solution, after all. OTOH, the implied conclusion is (apparently) that a major part of the possible solution space - i.e. functional solutions - should be excluded from consideration in general. The reason for excluding such solutions boils down to the fact that they've previously been excluded, which is why something as simple as a basic recursive solution to a problem is seen as a "totally different way of thinking about programming". The reasoning is circular (dare I say recursive?) There's no underlying logic here, other than the need to defend a knowledge gap that exists for historical reasons. The same argument could have been made against using STL-based code in the first place. To hide this weak argument, they've resorted to major obfuscation — conflating issues arising from different paradigms, different languages, different algorithms, differing amounts of library support, and implied issues like side-effect free programming, all without making any attempt to tease the issues apart. To top it all off, we are to believe that this single, highly confused example has some bearing on the general case. All in all, we're dealing with the Chewbacca defense. the implied conclusion is (apparently) that a major part of the possible solution space - i.e. functional solutions - should be excluded from consideration in general. I don't believe this is a fair characterization of K & M's conclusion. Let me give you another out-of-context quote from the same piece:. Thanks for Chewbacca Defense link by the way. I've been using the term ever since I saw the South Park episode in which this notion was introduced. I didn't realize, however, that the term had gained such wide recognition.. I agree with this point in general, but it doesn't save the authors in this case. If someone is at a point where FP seems to require learning "a totally different way of thinking about programming", they're not going to meaningfully be able to keep that as a readily available option in their toolbox. Suddenly learning all about FP right at the point when it is "likely to be useful" isn't a great strategy. In any case, the comments you quoted do seem to imply something about the authors' opinion on the merits of investing in learning that different way of programming. A big problem I have with all of this is what, specifically, the bogeyman is here — what are the elements of the "different way of thinking" they see as being required for the FP solution to this particular problem. Presumably the problem isn't Haskell syntax in general, since that's a specific language issue, rather than anything intrinsic to the notion of FP. You could implement the same sort of code in C++. If the problem is recursion, then what we're really talking about is the fact that mainstream languages have done a poor job of implementing recursion, primarily because they didn't know any better at the time. So while recursive solutions may be a totally different way of thinking about programming for some people, that's only because they've been Sapir-Whorfed into partial ignorance by the languages they use. The "different way of thinking" that is required here actually involves unlearning old limitations on thinking, and the only possibly valid argument against doing so is if the language you're using still doesn't support recursion well. I can't imagine that the pattern matching is the issue — non-FP languages have that too, Python comes to mind. The lack of mutation in Haskell might be more of a concern, but that's somewhat orthogonal to real-world FP, and it's not news to anyone that mutation can have convenience and performance advantages. In all these cases, the real issues involve learning principles which are more general, more widely applicable, than their specific expression in any single language, particularly mainstream languages. I would hope that someone who's actually teaching students would recognize this. Here is how my girlfriend, a literary critic, would analyze this. According to Roland Barthes, a myth is an artificial cultural artifact which is presented as timeless, universal and natural. You can find examples in nationalism, advertising and media. Judging from the quoted text of the article, it sounds like the authors are using myths to reinforce a power structure where pedants and celebrities exert control over programmers and users. The whole "different way of thinking" thing is part of the imperative ideology. It's a bogeyman playing on xenophobia that is used to make people uncomfortable about competing paradigms, and keep them in the fold of a community (culture) where what they read and hear can be controlled and censored. They write that the FP approach is "straightforward -- but requires a totally different way of thinking about programming." Hm? It is both straightforward and "totally" alien? This borders on contradiction. Indeed, if a person can grasp the FP solution without having done any actual functional programming, just by reading a short article, and moreover regard it as "straightforward", one can hardly claim it is a "totally different way of thinking". Even if it is totally different from imperative thinking, whatever that is, it may not be incompatible with other sorts of thinking habits which their audience might broadly share. After all, we all get taught about equations, functions and, to some extent, recursion in high school. (At least factorial and the chain rule.) How alien can it be? To be fair, though, there is also an FP (and LP) myth that because FP is "based on" mathematics it is natural and hence superior to procedural and OO paradigms. But mathematics is a cultural and historical artifact. I do not mean that mathematical truths are relative; I mean that the body of mathematical literature has taken a form which is a historical accident. For example, mathematics is often divided into geometry, analysis and algebra, but this could as easily have been geometry, analysis and coalgebra, in which case OOP advocates could have exploited this myth, OO being rather coalgebraic in nature. Don't get me wrong. I think that there is a genuinely closer relationship between mathematical truth and FP, because FP has been analyzed in a thousand different ways in scientific literature, and FP languages tend to come with a semantics which is moreover effective for reasoning about programs. And I regard this as an advantage, because of the opportunity cost argument. But the "FP is more pure" (= natural) argument is bogus. But mathematics is a cultural and historical artifact. I do not mean that mathematical truths are relative This reminds me of Proofs and Refutations by Imre Lakatos, a highly influential work in philosophy of mathematics. Since I haven't reread it in more than five years, my recollection may be faulty. (You can double-check it by following the above Amazon link which gives you access to the entire scanned book.) I believe Lakatos would strongly agree that "mathematics is a cultural and historical artifact". I think he goes a little further and argues that mathematical truths are, in fact, relative. The above Wikipedia link gives a fairly good summary of his views. Here's a quote from the book found by searching "inside the book" for absolute truth. It's from the footnote that spans pages 54 and 55: 'Nature confutes the sceptics, reason confutes the dogmatists' (Pascal, [1659], pp. 1206-7). Few mathematicians would confess [...] that reason is too weak to justify itself. Most of them adopt some brand of dogmatism, historicism or confused pragmatism and remain curiously blind to its untenability; for example. 'Mathematical truths are in fact the prototype of the completely incontestable... But the rigor of maths is not absolute; it is in a process of continual development; the principles of maths have not congealed once and for all but have a life of their own and may even be the subject of scientific quarrels.' (A.D.Aleksandrov [1956], p.7) (This quotation may remind us that dialectic tries to account for change without using criticism: truths are 'in continual development' but always 'completely incontestable'.) On Apr 7, 2005, I wrote: This reminds me of Proofs and Refutations by Imre Lakatos Interestingly, this brings us back to Hamming. I've been reading some of the papers mentioned in a recent new forum topic posted by Charles Stewart on Apr 17, 2005. Specifically, R.W. Hamming's essay The Unreasonable Effectiveness of Mathematics makes it clear that he was deeply influenced by the aforementioned work of Imre Lakatos. A couple of quotes from the essay:. I had meant to respond to your earlier post. I simply want to say, that anyone who hasn't read "Proofs and Refutations" should (even if you aren't particularly mathematically inclined). It's enjoyable and quite good. What's missing in Your analysis is that claiming that FP employs a completely "different way of thinking" is not a myth generated by the imperative crowd originally but by the FP crowd itself. What happend is turning an optimistic revolutionary attitude towards programming ( "forget everything you know about C .." or "you will have a hard time to unlearn but it will be worthwhile in the end .." [1] ) into a conservative and defensive reaction ( "you don't need a completely different way of thinking to get the job done .. "). The authors simply play back the ideological distinction to their originators. The message always arrives it's receiver. Kay [1] "Think different" is/was an optimistic slogan of Apple Corp. How can you be a good programmer if you think that recursion is a "new way of thinking"? Good programmers understand recursion, even if they write mostly for loops.. I do find this somewhat unreasonable. It should not take years for an experienced programmer to master or at the very least become proficient in a new programming language even if there is a paradigm shift. And as one learns more languages it takes even less time (and it takes even less time without a paradigm shift). And it's not like you have to drop everything and hide away in a cave while you're learning. Finally, this example alone is a pretty good example of why knowing multiple paradigms/languages is useful, and there are heaps of FP techniques being applied in OO languages nowadays providing another good incentive (at least for FP). Learning other paradigms/languages is not a waste of time. The Haskell code irks me; it is more verbose than it needs to be. I assume this was done to make it more recognizable to non-Haskell (read C++) programmers. scale n = map (n*) merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) | x == y = x : merge xs ys | x I do find this somewhat unreasonable. It should not take years for an experienced programmer to master or at the very least become proficient in a new programming language even if there is a paradigm shift. How many years (decades) did it take OO to be understood by mainstream programmers? Many still don't. Just because some of us are good at this kind of thing shouldn't lead us to assume that most otherwise skilled programmers should be too. From a sociological point of view, I think you skipped over the pithier part of my post:. How many years (decades) did it take OO to be understood by mainstream programmers? Many still don't. I'm not talking about the mainstream, I'm talking about individuals, particularly professionals (more the connotations of the word rather than the denotation). Just because some of us are good at this kind of thing shouldn't lead us to assume that most otherwise skilled programmers should be too. I have a feeling most people who are "good at this kind of thing" weren't born that way, have many languages under their belts, and found there first or second language took more time than the latter ones. In a nutshell, they are "good at this" because they have practiced it! Part of my intent is that one isn't going to be a "taxi driver" for long. Further, if such people are really so insecure, they can keep it to themselves until they feel comfortable.. The psychological benefits of sticking to what you know well are a pretty strong motivator. Yep, this and the above are good reasons not to ever learn anything new at all! I guess I should've stopped working at guitar, when I was feeling so clumsy trying to change chords smoothly or stopped drawing after circular filing some less-than-successful attempts, and there certainly were those CT papers that gave me a niced glazed look. Sure, I wouldn't be able to play guitar, draw, or know what a colimit is now, but at least I wouldn't have felt uncomfortable! There is a difference between advocating a position and observing its power "on the ground". If we want to advocate new ways of doing programming, we have to confront the reasons why they are resisted. If we don't care if the benighted wallow in ignorance until their dying day, well, we could ignore them (and we wouldn't be discussing this article at all.) It is easier to change people's behaviour than to change their values. If we want them to adopt our favorite paradigm, we have to address the reasons they resist it. If we don't care about that, we shouldn't get so mad that they resist it. ;-) Wonders whether teaching any subject, requires the decision of whether to teach to the bottom, middle, or top of the class. Those that teach to the top are accused of elitism. Those that teach to the bottom are accused of dumbing down. And those that teach to the middle are accused of promoting mediocrity. [edit note: And I'd prefer LtU to be accessible to all three at the same time] [edit edit note: Ok, so we might not want the absolute dregs] :-) Not only that, but some of us are sitting in the Advanced Category Theory seminar while others are attending Object Oriented Programming With Java 101. I personally want to see some Ruby-on-Rails-style tutorials for web programming with Haskell... Being one who's mid-tier but hangs around smart people hoping some of that knowledge will rub off, I think it's important for the best and brightest to reach down (as well as up). It helps to touch bases with the basics periodically to help solidify the more abstract ideas (a dose of reality) and helps bring in new aspirants to mix up the field of ideas. Of course, the alternative is to put the Oleg's and Noel's in a room by themselves, but they'd probably get bored with each other sooner or later. :-) Or you create a community site like LtU, where demi-gods can share their wisdom... I really suggest people use this opportunity (e.g., Oleg's paper about delimited continuations currently being discussed). The Haskell code irks me; it is more verbose than it needs to be. Perhaps then you should also drop the matches on nil in merge. scale n = map (n*) merge (x:xs) (y:ys) | x == y = x : merge xs ys | x < y = x : merge xs (y:ys) | otherwise = y : merge (x:xs) ys seq = 1 : merge (scale 2 seq) (merge (scale 3 seq) (scale 5 seq)) The irony is that the original definition of scale will only work on infinite lists whereas my version will work on finite or infinite lists, however the original version of merge would work on finite lists, but this version won't. It's a bit of an odd inconsistency in the original code. IMHO the version of each function that works on finite lists is to be preferred, simply because that is least surprising. That said, a comment that as all lists inside the programme are infinite, termination conditions are not needed would probably remove the element of surprise. The Haskell implementation is complete self-contained solution. It requires no reference to libraries. The C++ is simply leveraging off behavior provided by the template library. In terms of simplicity, the haskell solution just requires you learn that languages syntax, of which this example is a pretty plain jane example. For the C++, you have to learn it's immense syntax, figure out how it's used here, and then dive into the template library and figure out what to do there. And we are talking about a math problem here. Chris Rathman: For the C++, you have to learn it's immense syntax, figure out how it's used here, and then dive into the template library and figure out what to do there. I think Koenig and Moo's assumption is that a modern C++ programmer has done that, and therefore there won't be any mystery to their C++ solution, whereas even once you explain the Haskell syntax, the approach of pattern matching on algebraic data structures is still alien. Of course, you still have a point; it's not the least bit alien to anyone conversant in any of the ML family, Haskell, Oz, Concurrent Clean... The topic is a pertinent one to me. As I've written before, my day job involves a large-ish body of C++ written aggressively in the Microsoft MFC style, and I'm slowly attempting to untangle it and make it more idiomatic in the context of what it does. Since a lot of what it does is deal with containers, moving more to functionalism and the use of exceptions feels very natural to me, but folks who don't know the STL and boost::bind reasonably well find some of my code weird. So even within the C++ community, there's a knowledge/stylistic-preference gap that has to be addressed. One of the first languages I looked at after C and Java was OCaml (I read part of SICP before). Pattern matching algebraic data structures was the most natural thing. I immediately started hating C dialects for the (needless) lack thereof. Often ML code is clearer than the infinitely tangled data and control flow that usually ends up in any non-trivial Java program, with all kinds of objects calling each other. No wonder that often a bug ends up somewhere inbetween! That said, I like imperative features. Does it matter much that lists in ML are an "intrinsic" datatype, whereas std::set is part of the library (and is capable itself of being written in "plain" C++)? In my mind, no. There are many good arguments to use in language flamewars; the language-vs-library argument isn't one of them. After all, if C++ had sets as an intrinsic datatype, that would just be further grist for the "it's a bloated langauge" mill. :) Any competent C++ programmer should be familiar with the STL. That said, there are many who aren't--who still use it as little more than an OO extension to C. The Haskell example captures the abstraction in very large part. The C++ example shows a recipe for using the library to create a solution. There is an impedance mismatch between the depth of information the Haskell code conveys and what the C++ code conveys - being at once both a higher and a lower level of abstraction for the Haskell code. Sure, libraries level the playing field. For 99.99% of the population that uses such things, the example given will just be a recipe to be copied and pasted. Either solution could be put in a library and added to the next generation of HQ9++ as a single character N (H is already taken). The traditional mathematician recognizes and appreciates mathematical elegance when he sees it. I propose to go one step further, and to consider elegance an essential ingredient of mathematics: if it is clumsy, it is not mathematics. - Edsger Dijkstra aren't part of the language. They are pattern-matched like everything else. Lists in ML, just like strings in Java, have an extra built-in syntax, though, because their use is so common. To C++: the best features of that language are that is makes some common C idioms easier, adds some typechecking and gives inheritance (which is overused, though). OTOH, I still use C in preference, since C++'s assumptions to memory layout (variable sized structs aren't really possible as classes) are restrictive. Templates are the worst thing since unsliced bread, requiring everything the code to be compiled for EVERY freaking instantiation! In C I just put a void pointer in a structure, no need to compiled it 50 times. I don't use the STL&C++ for that reason. Regarding the simplicity of a program, it doesn't matter which part of the language it uses is built into the language and which is a part of the standard library. Actually if more is done in a library then it's a sign of a more flexible language. Since libraries can be added but compilers cannot be easily extended, it means that a random other problem has a higher chance of admitting a clean solution: even if it wasn't considered by language designers, it can be solved by library writers later. If you say that it's unfair because it makes languages with lots of libraries appear more powerful than those without, then I reply that they appear more powerful because they are. Libraries matter. A ready library might be less universal than the ability to implement a solution from scratch, but it definitely allows the task to be solved much easier when it applies. Actually if more is done in a library then it's a sign of a more flexible language. More generally though, there are lots of smart programmers out there who can make libraries out of even the worst languages. The availability of libraries has much less to do with the quality of the language and more to do with the shear numbers of people using the language to various ends. Anyhow, my argument isn't about how simple it is to do this in C++ vs. Haskell. It's about the mismatch between the code samples. The C++ code has much of the detail hiding behind the library whereas the Haskell code is just fairly straight forward from that languages perspective. And just because the sample Haskell code does not use a library doesn't mean that it couldn't be implemented as a library for sequences. There are a lot of things which are simpler in C++ but I fancy that infinite algebraic series is not among the top. of features. You mention C++ templates (more generically, generic polymorphism). You are correct; implementing the STL--or anything like it--required this feature be present in the language; Java is now undergoing a similar evolution. No argument there. And as others have pointed out, the advantage that Haskell has over C++ in this instance is lazy evaluation and lazy data structures. One could port the Haskell algorithm (and it's O(n) performance) to C++, but the code would be an ugly hodgepodge of roll-your-own thunks and other assorted hackery, needed to emulate lazy evaluation in an otherwise eager language. (Think of a Scheme implementation of the same algorithm, then convert the uses of delay/force one would find into equivalent C++ machinery). However, comparisons of the C++ and Haskell code above are comparing apples to oranges; they are different algorithms. One uses lazy evaluation of lists to select elements from an ever-expanding "frontier" of possible choices; the other uses an ordered associative container (a STL "set") to essentially sort the elements. The behavior of std::set is well-known to any C++ programmer (including performance characteristics, which are documented), and the meaning of the above code fragment is clear as day. Just as the meaning of the Haskell snippet is obvious to a competent Haskell programmer. Both samples are likely to be difficult to read for someone not conversant in the language. Regarding "hiding detail"--where I come from, that's considered a good thing. I don't want to know (or care) that std::set is implemented using a red/black tree, for instance... such details are not germaine to the problem at hand. What salient detail did you think the C++ code obscured? Of such intransigence are language wars made of. But I'll bow out under the premise that I glean more information from the Haskell code than the C++ code - and yes that could very well be because I've been working more with Hindley-Milner type systems of late and haven't worked much with C++ Templates. But as you state, they are different algorithms, so I win my argument anyhow, even if I had to totally change my argument in the process. :-) Where the article presents "The Functional Solution" it is quite reasonable, introducing lazy lists gently, and ending with "[the definition of seq] is no more magical than our earlier example". The comment about a "totally different way of thinking" is not supported in the article, but it's surely intended to set up the C++ solution as preferable. Of course, it's the FP advocates who continually assert the difference. The primary difference in the functional program is that it has a name for the infinite list that is the solution. The alternatives provide a data structure where the solution is accumulated, which to my eyes appears unfinished. The "idiomatic" solution generates the numbers OK, but does not provide an idiomatic way to access them, i.e. via an iterator. The article's conclusion is flawed, since its solution amounts to a fair demonstration of a hole in C++'s expressivity. What is the full C++ listing? The C++ listing given assembles an ordered set containing the numbers 1,2,3,5. The OP contains all of the code from the article, and doesn't have it yet. (And if you guess the name of the zip file for the April code, the code from the Koenig/Moo article isn't in that file, either.) OP? original post/poster [in the thread] (edit) Initially I was confused as to why this is; I've realised that this is because of the order in which the numbers are produced. Increasing the 20 to 60, for example, causes the lists to agree in the 38th number. One might suggest that the haskell version has comprehensibility benefits. #include <set> #include <iostream> using namespace std; int main() { set<int> seq; seq.insert(1); set<int>::const_iterator it = seq.begin(); for(int i = 0; i < 20; ++i) { int val = *it; seq.insert(val * 2); seq.insert(val * 3); seq.insert(val * 5); it++; } it = seq.begin(); std::cout << *(it++); for(; it != seq.end(); ++it) std::cout << "," << *it; std::cout << std::endl; return 0; } It differs from the haskell version at the 38th number. Anyone have an idea why? Because you haven't computed the 38th number yet. You execute the body of the loop 20 times, generating the following 41 numbers: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 135, 150, 160, 180 135 is (incorrectly) followed by 150. If you iterate 30 times — instead of 20 — your program generates the following 56 numbers: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 128, 135, 144, 150, 160, 162, 180, 192, 200, 216, 225, 240, 250, 270, 300, 320, 360, 375, 400 135 is now (correctly) followed by 144. So, I think your example highlights a deficiency in the "idiomatic C++" implementation. There is no easy way to tell how many insertions one needs to perform in order to compute the Nth Hamming number correctly. Thanks for pointing this out. P.S. I found this on the python list: Classical FP problem in python : Hamming problem (alternatively, see the entire thread) There is no easy way to tell how many insertions one needs to perform in order to compute the Nth Hamming number correctly. On the other hand, by simply iterating N times, you do at most O(1) too much (amortised) work. This suggests the following implementation, which is a little closer to the Haskell version. Plus, it's about as short as the original C++ version if you ignore includes and typedefs. #include <iostream> #include <set> #include <algorithm> #include <boost/iterator/transform_iterator.hpp> using namespace std; using namespace boost; typedef binder1st<multiplies<int> > scale_type; typedef transform_iterator<scale_type, set<int>::iterator> scale_iterator; main() { set<int> s; s.insert(1); scale_iterator it2(s.begin(), bind1st(multiplies<int>(), 2)); scale_iterator it3(s.begin(), bind1st(multiplies<int>(), 3)); scale_iterator it5(s.begin(), bind1st(multiplies<int>(), 5)); set<int>::iterator it = s.begin(); for (int i = 0; i < 40; ++i) { s.insert(*it2++); s.insert(*it3++); s.insert(*it5++); if (i > 0) { std::cout << ", "; } std::cout << *it++; } std::cout << '\n'; } This is almost the Haskell version. To do the Haskell version properly, and have constant time access, you need to implement merge. Here are the gory details, courtesy of Boost. Don't read if you're squeamish... #include <iostream> #include <list> #include <algorithm> #include <boost/iterator/transform_iterator.hpp> #include <boost/iterator/iterator_facade.hpp> using namespace std; using namespace boost; typedef binder1st<multiplies<int> > scale_type; typedef transform_iterator<scale_type, list<int>::iterator> scale_iterator; template<typename It1, typename It2> class merge_iterator : public boost::iterator_facade< merge_iterator<It1, It2> , const int , incrementable_traversal_tag > { public: merge_iterator(It1 p_it1, It2 p_it2) : m_it1(p_it1), m_it2(p_it2) { } private: friend class iterator_core_access; void increment() { int x1 = *m_it1; int x2 = *m_it2; if (x1 <= x2) { ++m_it1; } if (x1 >= x2) { ++m_it2; } } const int& dereference() const { return std::min(*m_it1, *m_it2); } It1 m_it1; It2 m_it2; }; main() { list<int> s; s.push_back(1); std::cout << 1; scale_iterator it2(s.begin(), bind1st(multiplies<int>(), 2)); scale_iterator it3(s.begin(), bind1st(multiplies<int>(), 3)); scale_iterator it5(s.begin(), bind1st(multiplies<int>(), 5)); merge_iterator<scale_iterator, merge_iterator<scale_iterator, scale_iterator> > it(it2, merge_iterator<scale_iterator, scale_iterator>(it3, it5)); for (int i = 1; i < 40; ++i, ++it) { int x = *it; std::cout << ", " << x; s.push_back(x); } std::cout << '\n'; } It's a lot less ugly than I thought it would be. Interestingly, the hardest part that I found was getting the typedefs and other type declarations right. The actual code was easy. Especially since I ignored termination conditions on the input iterators. One thing which isn't covered here, of course, is that the Hamming number problem is a very artificial problem in the first place. I note that the "full haskell C++" version does require a lot more boilerplate and declaration than the haskell version, which does rather obscure its meaning, at least at first glance. The same is not true of the "semi-haskell" version I feel, which is probably clearer than either of my versions. It's true that the "full Haskell C++" version has more boilerplate, but in fairness, I used a pile driver to crack an egg: hamming_iterator is a fully conforming proposed-standard iterator, which is arguably overkill. In writing it, I found that the declarations were the most tricky parts. The boilerplate (and it's not clear that it's all boilerplate; it's there because C++ iterators can do things that Haskell lazy lists can't, such as allow clients to modify what they point to if the container allows it) was fairly mechanical, didn't take long, and worked first time more or less. I agree with Scott Turner that I'd rather do a recreational programming problem like this in Haskell. On the other hand, I learned stuff doing it this way in C++. I think the most disturbing remark in the original article is that the Haskell solution "requires a totally different way of thinking about programming". If you're a professional software engineer on a deadline, and you can see a solution that's easy for you to understand and good enough, then you should do it. Your time is valuable. In this case, though, we're talking about Hamming numbers. Why you would bother with such a simple, artificial, recreational programming problem if you weren't trying to learn something? That matches the efficiency of the Haskell, but not the expressiveness. The Haskell version has a name 'seq' which embodies the infinite sequence of Hamming numbers. Very straightforward. In C++ that should be represented by an iterator. In the above programs, neither s.begin() nor 'it' is the complete answer. 'seq' s.begin() 'it' Below is the implementation an iterator class hamming which represents the infinite sequence of numbers. hamming [includes and typedefs just like "almost Haskell" version above] set<int> set_of_one () { set<int> s; s.insert(1); return s; } class hamming : public boost::iterator_facade< hamming , const int , incrementable_traversal_tag > { public: hamming () : s(set_of_one()), it2(s.begin(), bind1st(multiplies<int>(), 2)), it3(s.begin(), bind1st(multiplies<int>(), 3)), it5(s.begin(), bind1st(multiplies<int>(), 5)) { it = s.begin(); } private: friend class iterator_core_access; void increment() { s.insert(*it2); it2++; // Fix bug affecting the first increment. s.insert(*it3++); s.insert(*it5++); it++; } const int& dereference() const { return *it; } set<int> s; set<int>::iterator it; scale_iterator it2; scale_iterator it3; scale_iterator it5; }; Fixing the bug in the "almost Haskell" version, and figuring out a way to initialize everything was a firm reminder of why I do my recreational programming in Haskell. It's not just that the C++ version is more verbose; it's more complex and error-prone. A class like hamming can be useful, and "a whole new way of thinking" is not necessary to understand that. Agreed, the problem is not routine, but it remains a good example of the merits of FP. I carefully used list rather than set in my "full Haskell" version. The difference is O(n log n) vs O(n) time. I should mention that the following version behaves slightly more intuitively: #include <set> #include <iostream> using namespace std; int main() { set<int> seq; seq.insert(1); set<int>::const_iterator it = seq.begin(); for(int i = 0; i ::const_iterator it2 = seq.begin(); std::cout I should mention that the following version behaves slightly more intuitively: Right, we end up generating an ordered set of 72 numbers (1, 2, ..., 675, 720) of which only the first 40 can be trivially proven to be consecutive Hamming numbers. The rest of the sequence contains gaps. For archival purposes, here's the Python version: # # # # Requires Python 2.4 from itertools import tee, imap def imerge(xs, ys): x = xs.next() y = ys.next() while True: if x == y: yield x x = xs.next() y = ys.next() elif x < y: yield x x = xs.next() else: yield y y = ys.next() def hamming(): def _hamming(): yield 1 for n in imerge(imap(lambda h: 2*h, hamming2), imerge(imap(lambda h: 3*h, hamming3), imap(lambda h: 5*h, hamming5))): yield n hamming2, hamming3, hamming5, result = tee(_hamming(), 4) return result for i in hamming(): print i, The version you replied to printed out the first 40 hamming numbers correctly. Replacing 40 in the programme with n would result in the first n hamming numbers being printed. For the record, I guessed that the modification would rectify the problem, rather than reasoning about the programme. I may be reading too much into this quote, but it sounds to me like Koenig and Moo consider it a bad thing to require a "totally different way of thinking about programming". In my Programming Paradigms & Foundations class w/ Dr. Koenig, so far we've covered Algol, Smalltalk, Icon, APL and Simula. We've tried as much as possible to compare language features to Java, C++, Scheme and Python. We've talked about Djikstra's structured programming and next week we will talk about John Backus' "Can Programming Be Liberated from the von Neumann Style?" In no way at any time have I gotten the impression that he would think that "a totally different way of thinking about programming" would be a bad thing. This includes the first lecture, which was more or less the article he & his wife published in the 2005 April CUJ. Algol, Smalltalk, Icon, APL and Simula... Java, C++, Scheme and Python Pardon me for being underwhelmed; only one unambiguously FP language in the bunch, and heavily weighted to PLs that predate C++ (and which thereby could have had their features co-opted or rejected during the development of C++.) Everybody thinks they're open-minded; they just have a few things they think are too weird to consider seriously. ;-) Well, I believe he has used Algol & APL during his work @ AT&T, but I see what you're saying. Still, I'm not convinced that he's outright rejected functional programming and I don't see his article as a warning to stay away from FP... After all, it is called C/C++ Users Journal, and not Haskell Users Journal... w/ respect to your post's title, I believe you will only pry Squeak from its users' cold, dead hands. :P Also, I'm pretty sure Icon is where Python got its generators from (I've been wrong about this sort of thing before). (Is there such a thing as HUJ?) You're certainly OK on this point. It should be noted though that while the concept of generators from Icon made it into Python (largely I believe due to Tim Peters), the way in which generators integrate into the language is entirely different. Icon's underlying expression language is massively different to Python's, and generators are a natural fit into Icon, whereas in Python they're rather restricted. Some well known Icon people feel that Python's generators don't compare to Icon's and I think they have a point. For what it is worth: "In his 35+ years as a programmer, Andrew Koenig has written an online student registration system in APL, a software distribution system in a mixture of C and C++, pattern matching libraries in C++, ML..." Bio Quote taken from Perhaps of more interest: "An anecdote about ML type inference" By Andrew Koenig stratify hamming(N) by [N,hamming]. stratify print(N) by [N,print]. stratify hamming << print. hamming(1). hamming(New) <-- hamming(Old), New is Old*2, New < 100000. hamming(New) <-- hamming(Old), New is Old*3, New < 100000. hamming(New) <-- hamming(Old), New is Old*5, New < 100000. print(Num) <-- hamming(Num). via Starlog. The Starlog solution looks much neater than, say, /* */ generate(dif(Twos, [V2|L2]), dif(Threes, [V3|L3]), dif(Fives, [V5|L5])) :- select(Twos, Threes, Fives, V), dequeue(Twos, Twos1, V), dequeue(Threes, Threes1, V), dequeue(Fives, Fives1, V), V2 is 2*V, V3 is 3*V, V5 is 5*V, write(V), nl, generate(dif(Twos1, L2), dif(Threes1, L3), dif(Fives1, L5)). select([X1|_L1], [X2|_L2], [X3|_L3], X1) :- X1 =< X2, X1 =< X3. select([X1|_L1], [X2|_L2], [X3|_L3], X2) :- X2 < X1, X2 =< X3. select([X1|_L1], [X2|_L2], [X3|_L3], X3) :- X3 < X1, X3 < X2. dequeue([X|L], L, X). dequeue([Y|L], [Y|L], X) :- X \= Y. hamming :- generate(dif([1|L2], L2), dif([1|L3], L3), dif([1|L5], L5)). hamming = 1 : map (*2) hamming # map (*3) hamming # map (*5) hamming where xxs@(x:xs) # yys@(y:ys) | x==y = x : xs#ys | x<y = x : xs#yys | x>y = y : xxs#ys via Answers.com. xs#ys Are those number signs supposed to be "++"? No, # is the infix operator that's defined as a local function in hamming's where clause. Ah, obvious now that you point it out. I guess I either have to go back to the drawing board with Haskell, or that code was a bit TOO concise for my own good. ;-) Has anyone done a space complexity analysis of the Haskell program? I think it's fair to ask the same question of the C++ implementation. In the Haskell case, you need to "remember" (some of) the previously computed numbers. To be more precise, to compute the Nth Hamming number HN, you need to remember the previously computed numbers in the interval of [HN / 5, HN]. In the C++ case, you end up carrying around all of the numbers in the interval of [1, HN] plus "most" of the numbers in the interval of [HN, 5*HN]. Since I don't have the required number-theoretical skills to estimate the sizes of the aforementioned sequence intervals, I ran a quick numeric experiment instead. The following listing shows the first 12 Hamming numbers. The blue lines show the sequence that the Haskell implementation must "remember" at each step. The red lines show the set of numbers computed by the K & M's C++ implementation at each step. To keep the sequences visually aligned, I use underscores to show the current gaps in the C++ ordered set. These show the positions of currently missing Hamming numbers that will be filled at some later point. In the Haskell case, I use the following conventions to indicate the current end of the "scaled" lazy lists: 1 1 2 3 _ 5 1 2 1 2 3 4 5 6 _ _ 10 1 2 3 1 2 3 4 5 6 _ 9 10 __ 15 1 2 3 4 1 2 3 4 5 6 8 9 10 12 15 __ __ 20 2 3 4 5 1 2 3 4 5 6 8 9 10 12 15 __ __ 20 __ 25 2 3 4 5 6 1 2 3 4 5 6 8 9 10 12 15 __ 18 20 __ 25 __ 30 2 3 4 5 6 8 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 __ 30 __ __ 40 2 3 4 5 6 8 9 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 __ __ 40 45 3 4 5 6 8 9 10 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 __ __ 40 45 __ 50 3 4 5 6 8 9 10 12 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 __ 36 40 45 __ 50 __ 60 4 5 6 8 9 10 12 15 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 __ 36 40 45 __ 50 __ 60 __ __ 75 4 5 6 8 9 10 12 15 16 1 2 3 4 5 6 8 9 10 12 15 16 18 20 24 25 27 30 32 36 40 45 48 50 __ 60 __ __ 75 80 Unfortunately, this doesn't really tell you anything about the asymptotic behavior of each respective implementation. Since I don't have the required number-theoretical skills to estimate the sizes of the aforementioned sequence intervals (Other than observing trivially that the space complexity is no worse than O(n) in both cases.) Thanks for taking the time to write out the sets! While observing the "previously computed" numbers does make it appear as if the Haskell version doesn't require storage greater than N, this is not neccessarily the case. There is also a need for temporary storage as well at each iteration, which could possibly increase asymptotically greater than the rate of N. Is it easy to do the analysis of the cost of the lazy evaluation temporary storage? ... does make it appear as if the Haskell version doesn't require storage greater than N, this is not neccessarily the case. The O(n) estimate is based on the assumption that given a moderately smart compiler, the Haskell implementation can work internally along the following lines (excuse my bad Scheme): (define (make-hamming) (let* ((tail '(1)) (s2 tail) (s3 tail) (s5 tail)) (lambda () (let* ((result (car tail)) (h2 (* 2 (car s2))) (h3 (* 3 (car s3))) (h5 (* 5 (car s5))) (next (min h2 h3 h5))) (set-cdr! tail `(,next)) (set! tail (cdr tail)) (if (= h2 next) (set! s2 (cdr s2))) (if (= h3 next) (set! s3 (cdr s3))) (if (= h5 next) (set! s5 (cdr s5))) result)))) Storage-wise, this behaves like the blue sequence in my previous comment, provided that the above snippet really works the way I think it does. To follow up on my earlier comment the space complexity is no worse than O(n) in both cases. In the C++ case, the O(n) estimate cannot be improved, given an implementation like the one fleshed out in marcin's post. The Haskell implementation seems to be doing a little better than O(n) based on the following empirical data: The table basically says that assuming the Haskell implementation behaves as described in this post, it needs to remember 44 previous numbers in order to compute the 100th. It needs to remember 24,623 previous numbers in order to compute the 1,000,000th. On the face of it, that seems to be more efficient than O(n). .) Yes, it is. > seq !! 0 1 > seq !! 1000000 519381797917090766274082018159448243742493816603938969600000000000000000000000000000 > elemIndex 519381797917090766274082018159448243742493816603938969600000000000000000000000000000 seq Just 1000000 That last expression used a cut & paste from the original quoted number, to make sure they matched. f n = (ln (n * sqrt 30)) ** 3 / (6 * ln 2 * ln 3 * ln 5) + O(lnln n) h n = exp ((n * (6 * ln 2 * ln 3 * ln 5))**(1/3)) / sqrt 30 h 1000000 = 5.183690169e83 tailsize n = n - f (h n / 5) The approximation is not far off. The right-hand side of tailsize can be rewritten as tailsize tailsize = (ln 5 * 3*c**(-1/3)*n**(2/3) - 3*(ln 5)**2 *c**(-2/3)*n**(1/3) + ln 5**3/c) where c = 6*(ln 2)*(ln 3)*(ln 5) and this approximately tailsizeapprox n = 2.48*n**(2/3) - 2.05*n**(1/3) + 0.57) So yes, this is sublinear. Now, all the complexity measures discussed so far seem to assume that integer operations are constant time and integers are constant size. If we take into account that the size of the hamming numbers grows than it changes. The size in bits of the nth hamming number is sizeh n = log (h n) / log 2 exp (h n) sizeh n = (2*(c*n)**(1/3)-ln 2-ln 3-ln 5)/(2 * ln 2) where c = 6*(ln 2)*(ln 3)*(ln 5) sizeh n = c1 + c2 * n**(1/3) sum [sizeh n | i <- [0..n]] sizehrange n = c1 * n + 3/4 * c2 * n**(4/3) tailsize = sizehrange n - sizehrange (f (h n / 5)) n**(4/3) tailsize 1,000,000 Thanks for your analysis. Beautifully done. Thanks a million. For example tailsize 1,000,000 = 6819368.46 bit = 832KB. Does this seem about right? Since I don't have a Haskell compiler installed, I'm going to have to pass this question on to Anton "the sanity checker" van Straaten. (My Python script doesn't currently discard numbers that are no longer needed and I'm too lazy to fix it.) As an aside, the AT&T Encyclopedia of Integer Sequences links to a nice article by Mark Dominus (the author of Higher-Order Perl) that shows how to solve the Hamming problem in Perl using Mark's own lazy streams module. This reminds me of something I have wondered: what is the time complexity of append (as in ++) in a lazy language? I've heard that it's O(n) just like in a strict language but in my fuzzy mental picture I expect it to be O(1). Know what I mean? append ++ What, because strictly speaking, a lazy language ought to print out [1,2,3]++[4,5,6] by printing the elements of the first list, then the elements of a second, rather than running over the first list, adding it into a new list, then adding the elements of the second to that list, then run over that new list printing out its elements? In Erlang we have a very useful related datatype called an IO list to represent binary data that will ultimately be written to a file or socket. While we represent plain binary data as either a string (list of 8-bit integers) or a binary (array of 8-bit integers) an IO list is a "deep list" (tree of conses) of these elements. What this means is that if you have two chunks of data to join together you can cons them into an IO list in O(1) time instead of having to concatenate them in O(n) time. In practice this makes it very easy to avoid the pitfall of spending O(n^2) time to accumulate large binary messages from the repeated concatenation of smaller parts. Take HTML generation in the Yaws webserver for an example: ehtml_expand({Tag, Attrs, Body}) when atom(Tag) -> Ts = atom_to_list(Tag), NL = ehtml_nl(Tag), [NL, "<", Ts, ehtml_attrs(Attrs), ">", ehtml_expand(Body), "</", Ts, ">"]; NL ++ "<" ++ Ts ++ ... Creating these IO lists is cheap but of course they will ultimately need to be written to a file descriptor. At this point either the runtime system concatenates the IO list into a byte array in memory (O(n) using relatively fast C code - the list_to_binary primitive) or a writev system call could be used and might avoid ever concatenating the data in memory at all. list_to_binary writev This has a lot in common with Boehm's most excellent cord data structure. but if I remember correctly, there are both amortized and worst-case O(1) lazy append's given in CTM and I think I saw them in Okasaki too (Purely Functional Datastructures). ham1:: [Int] ham1 = y where y = [1:merge (map ((*) 2) y) (merge (map ((*) 3) y) (map ((*) 5) y))] via Clean. Why can this not be written as one or two lines? Why are the last two lines separate? ...as the author posts them. Call it a two-liner then. In Clean by default top level functions are reevaluated. So if you write this as ham1:: [Int] ham1 = [1:merge (map ((*) 2) ham1) (merge (map ((*) 3) ham1) (map ((*) 5) ham1))] then ham1 is reevaluated over and over again. ham1 There's a special definition symbol (=:) to indicate that the "">CAF should be shared. ham1:: [Int] ham1 =: [1:merge (map ((*) 2) ham1) (merge (map ((*) 3) ham1) (map ((*) 5) ham1))] hamming :: Num -> [Num] hamming n = [i | i <- [1..n], i `mod` 2 == 0 || i `mod` 3 == 0 || i `mod` 5 == 0 ] via Professor Jeff Rohl using the old Haskell relative, Gofer. Pasted verbatim, not checked. Possible errors: logical operator, assumption that all numbers divisible by 2,3, and 5 are strictly Hamming numbers. Isn't a Hamming number. The missing bit of spec is "only", as in "only divisible by 2, 3, and 5". (Edit. See my later comments for code corrections and remarks. There's nothing wrong with the idea here - though the code is incorrect, it's easily fixed.) Sort[Flatten[Table[2^i*3^j*5^k,{i,0,5},{j,0,5},{k,0,5}]]] This one-liner is trivial, lucid, and fast. I'm a C++ guy too, but not provincial. C++ is wrong for Hamming numbers. Using the same command format on a 1.0 GHz PC, Mathematica 5.1.1 computed and sorted the first 27000 Hamming numbers in 0.3 second. The 27000th number is 6863037736488300000000000000000000000000000. In all cases memory allocation is optimal because the array is allocated once according to the Table size. The C++ code is another question.. And I seriously doubt that C++ is faster with "small" Hamming numbers. Mathematica's computation of the first 216 Hamming numbers was essentially instantaneous. They are shown below as output from the one-liner. {1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 135, 144, 150, 160, 162, 180, 200, 216, 225, 240, 243, 250, 270, 288, 300, 324, 360, 375, 400, 405, 432, 450, 480, 486, 500, 540, 600, 625, 648, 675, 720, 750, 800, 810, 864, 900, 972, 1000, 1080, 1125, 1200, 1215, 1250, 1296, 1350, 1440, 1500, 1620, 1800, 1875, 1944, 2000, 2025, 2160, 2250, 2400, 2430, 2500, 2592, 2700, 3000, 3125, 3240, 3375, 3600, 3750, 3888, 4000, 4050, 4320, 4500, 4860, 5000, 5400, 5625, 6000, 6075, 6250, 6480, 6750, 7200, 7500, 7776, 8100, 9000, 9375, 9720, 10000, 10125, 10800, 11250, 12000, 12150, 12500, 12960, 13500, 15000, 16200, 16875, 18000, 18750, 19440, 20000, 20250, 21600, 22500, 24300, 25000, 27000, 28125, 30000, 30375, 32400, 33750, 36000, 37500, 38880, 40500, 45000, 48600, 50000, 50625, 54000, 56250, 60000, 60750, 64800, 67500, 75000, 81000, 84375, 90000, 97200, 100000, 101250, 108000, 112500, 121500, 135000, 150000, 151875, 162000, 168750, 180000, 194400, 202500, 225000, 243000, 253125, 270000, 300000, 303750, 324000, 337500, 405000, 450000, 486000, 506250, 540000, 607500, 675000, 759375, 810000, 900000, 972000, 1012500, 1215000, 1350000, 1518750, 1620000, 2025000, 2430000, 2700000, 3037500, 4050000, 4860000, 6075000, 8100000, 12150000, 24300000} Using the same command format on a 1.0 GHz PC, Mathematica 5.1.1 computed and sorted the first 27000 Hamming numbers in 0.3 second. The 27000th number is 6863037736488300000000000000000000000000000. Compare this to ghc on a 1.3 GHz box. Using the concise source code the program calculates the 27000th number correctly as 3983823817623774429511680, in 0.12 second. The Mathematica code is very nice as long as you realize it demands care, because it generates many but not all of the Hamming numbers. Your output implies that all Hamming numbers between 7776 and 24300000 are multiples of 5. coincidently, 7776 = 2^5 * 3^5. I'm not even a Haskell programmer, but Haskell's spirit is channelling through me and forcing me to point out that it can do this very concisely too: hamming = sort [2^i*3^j*5^k | i <- [0..5], j <- [0..5], k <- [0..5]] Of course, it suffers from the same drawbacks pointed out by Scott.. If you look at the sample C++ (iterators) versions above, you can see that by replacing the type held in the list<> or set<> you can get different storages. If you used something like GMP's big int's library, I'd imagine everything would carry on as if nothing had changed. That's where "close to the hardware" gives you choice. On the contrary, that's where parametric polymorphism gives you choice, and C++ is a relative latecomer to the parametric polymorpism game. OK, not as late as Java... :-) In fact, C++'s parametric polymorphism still isn't as expressive as, e.g. O'Caml's. This isn't legal C++: template <typename T> typedef foo <T> bar <T>; template <typename T> typedef foo <T> bar <T>; whereas this is legal O'Caml: type 'a bar = 'a foo type 'a bar = 'a foo C++'s parametric polymorphism still isn't as expressive as, e.g. O'Caml's. This isn't legal C++: template <typename T> typedef foo <T> bar <T>; whereas this is legal O'Caml: type 'a bar = 'a foo type 'a bar = 'a foo template<typename T> struct bar { typedef foo<T> type; }; typename bar<T>::type My first complaint about C++ parametric functions would be that C++ parametric functions can't be passed as arguments. My first complaint about C++ parametric functions would be that C++ parametric functions can't be passed as arguments. the lack of first class parametric functions is indeed one of the more serious issues with c++. a solution to the problem is possible through wrapping the parametric function inside a non-parametric object. ugly, but it works: struct foo { template<typename T> static void bar(T t) { } }; template<typename T> void test(T f) { T::bar("test"); } int main() { test( foo() ); } while many defiancies in c++ (like the aforementioned generic typedefs) will be addressed in near future, this and similar issues are unfortunately bound to stay because of the kludgy parametricity design. The sequence above does not contain it. (Edit. See my later comments for code corrections and remarks. About this notion of finding stand-alone Hamming numbers, the corrected array code uses an isosurface boundary which I expect might help. There may be valid formulas from other inspirations, too.) One need not compute any previous Hamming numbers to explore all of them: Sort[Flatten[Table[2^i*3^j*5^k,{i,100,105},{j,100,105},{k,100,105}]]] works just as fast. The front and back of the resulting output is: {5153775207320113310364611297656212727021075220010\ 00000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000, 10307550414640226620729222595312425454042150440020\ 00000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000, 15461325621960339931093833892968638181063225660030\ 00000000000000000000000000000000000000000000000000\ 0000000000000000000000000000000000000000000000000, ...etc... 12523673753787875344186005453304596926661212784624\ 30000000000000000000000000000000000000000000000000\ 00000000000000000000000000000000000000000000000000\ 000000} One need not compute any previous Hamming numbers to explore all of them If you want to compute a contiguous Hamming subsequence in the interval of [M, N], then you need to find all triples (i, j, k) such that If you know a way to do this without computing all previous Hamming numbers less than M, please share. This is wonderfully exciting stuff! I am having a lot of fun, I hope we keep this thread alive for a while, because I am writing the Unimperative version. For those who don't remember Unimperative is a functional programming C++ subset I posted about a while back, which has been reposted (at ) after having been taken offline for an overhaul (it now works on GCC 3.4 and no longer needs the Boost library). The following is not tested (I need a couple of more days) but I wanted to post it for fun, to see if it is comprehensible without documentation, (a tall order I realize, but I am just shooting darts here): Def Merge = (Switch, (IsEmpty, _1), _2, (IsEmpty, _2), _1, Default, (If, (Lt, (Head, _1), (Head, _2)), (MakeList, (Head, _1), (Merge, (Tail, _1), _2)) (MakeList, (Head, _2), (Merge, _1, (Tail, _2))) ) ); Def Merge3 = (Merge, (Merge, _1, _2), _3 ); Def Hamming2 = (Map, _1, (Lambda, Mult, 2)); Def Hamming3 = (Map, _1, (Lambda, Mult, 3)); Def Hamming5 = (Map, _1, (Lambda, Mult, 5)); Def Hamming = (If, GtZ, _1 (Merge3, (Hamming2, (Hamming, (Dec, _1))), (Hamming3, (Hamming, (Dec, _1))), (Hamming5, (Hamming, (Dec, _1))) ), (MakeList, 1) ); It the syntax recognizable to functional programmers? I am not very experienced in functional languages. A little hint _1 refers to the first argument, and a function is evaluated when it follows a left paranthesis, and If is lazily evaluated. This looks horrible. At first I thought it looked like prolog. Unimperative syntax was inspired by Scheme. IMO they are quite closely related. Inspired by scheme in what way? As a language whose syntax and style should be avoided at all costs? Wow, great burn! marcin: Inspired by scheme in what way? As a language whose syntax and style should be avoided at all costs? The style of the Lambda Calculus? The functional style, which at least in the form of SSA even seems to underlie modern imperative/OO language implementations? That style? Or perhaps you mean the syntax that even John McCarthy didn't want, but later conceded was likely crucial to Lisp's survival? That syntax? Really, there's very little in the realm of programming language discussion more tiresome than the endless rants about Lisp's "shortcomings." Although the recent ll-discuss post about overcoming C++ "brainwashing" in favor of Lisp surely is up there, too. You're really saying that that code looks like an s-expr based language, Scheme, or otherwise? marcin: You're really saying that that code looks like an s-expr based language, Scheme, or otherwise? I see a lot of functions in prefixes, and some occasional "syntax" (if, etc.) It looks slightly more verbose than plain s-exprs, but not to the extent of, say, XML. But that wasn't what I was responding to: I was responding to what I perceived as a typical rant against s-exprs. If I misunderstood, I apologize. I think I let my feelings about the ll-discuss post color my perceptions, albeit, ironically, from the opposite perspective! The right hand sides of the definitions do look exactly like s-exprs, except that they have commas between their terms. Just dropping the commas and adding meaningful lexical names, which would require Lambda to take a formals list, would make it look a lot like Scheme. Yes - that's my, and absolutely nothing like it looks Unimperative is actually C++! Go check out the following links: and. The Unimperative implementation as C++ is freely available online at: I really don't believe it is possible to make C++ much more Scheme like than what Unimperative does. Finally, whether or not it is possible to make a C++ compiler accept a programme that looks as much like Scheme as you believe unimperative does is not the issue - the issue is that one can specify a translation from C++ to scheme syntax that requires fewer rules than the translation between Unimperative syntax and scheme syntax. The fact is that there is not a trivial mapping to lisp-like syntax from the Unimperative, unlike for example, from XML to S-exprs. I can't believe you that it is a fact that there is no trivial mapping from Unimperative to Lisp syntax. I will demonstrate shortly on LtU, that there is in fact a trivial mapping. (Edit. Final and correct array code is shown in my last reply, below. The points here remain valid.) This is not a language shootout or speed contest, but an idiom contest. Haskell is a fine language. So is C++. Mathematica is very nice. All can be fast, and a faster CPU like Scott's will run them faster. We are discussing idioms. My only reason to offer stats was to corral the usual C++ hobby horses of speed and hardware proximity. C++ has no advantages here, which makes the test case a remarkable selection. The big-int problem even gives hardware proximity a disadvantage. So why did CUJ pick Hamming numbers to compare programming idioms? I am suspicious. If Hamming(N) necessitates imperative stepwise algorithms, then the challenge is rigged. An objective challenge requires an objective test. (Disclosure, I haven't read the CUJ article for lack of access.) What amuses me is that Hamming(N) is a number-theoretic sort of problem. Few workers in that field think that C++ surpasses tools like Mathematica (Haskell, Lisp, whatever) for such work. The kind corrections are partly right and partly wrong. Here is the issue. Table generates all forms 2^i*3^j*5^k. It is wrong to say that Table misses some numbers. Set the bounds high enough and it produces all numbers of this type, i.e. "all Hamming numbers." It produces them exhaustively and without duplicates, an important advantage. It permits one to study high Ns without computing previous values, even if without a proper Hamming index. The code is therefore "complete" in a certain sense, if not the right sense according to Hamming. The bug is a boundary effect. It may be O(N^3), I don't know, but if C++ overflows at 2^64, one must ask which scenario is worse. The one-liner's avoidance of duplicates might pay for a simple way to fix the boundary using another type of waste. Generate a bigger Table and truncate the bad data. Some clever formula might exist, but a simple test on Hamming(27000) shows that it's indeed a boundary glitch: In[181]:= (* one-liner formatted only for LtU wraparound *) hammingNums = With[{n= 82}, Take[Sort[Flatten[ Table[2^i*3^j*5^k,{i,0,n-1},{j,0,n-1},{k,0,n-1}] ]],Floor[ (n^3) / 2 ]]]; In[182]:= Length[hammingNums] Out[182]= 275684 In[183]:= (* check equality with Scott's num *) hammingNums[[27000]] == 3983823817623774429511680 Out[183]= True There you go. Now Hamming(27000) is 2^81.72042812373361, much larger than 2^64. So, mea culpa: my quickie one-liner has a boundary glitch, while their C++ segfaults on large N. Incorrect or incomplete assumptions will break any combination of language and idiom. At least I did not waste time writing bad code in C++. That's the neat thing about one-liners, they are throw-away. This one-liner, with whatever fixes it needs (gasp a second line), is certainly not the best or most elegant solution. The assertion is only that a pithy and obvious functional idiom solution exists, one which is reasonable for this problem, and arguably more so than C++ code which breaks at 2^64 or 2^32. While I could have ported a previous solution into Mathematica as Anton ported mine, porting is not the issue. I wanted to show an entirely new idiom since that was the original exercise. In an almost brain-dead condition the functional idiom still produces something workable and simple. We can quibble over "workable" but at least it's a fair starting point. Analysis of this one-liner will not be very productive. I would only be curious to see a good boundary formula. However what would help everyone is a list of the first 100,000 Hamming numbers. That data would help those writing novel solutions. It's not my job, though, since I've done my duty here and am going on vacation from Hamming numbers. However what would help everyone is a list of the first 100,000 Hamming numbers. That data would help those writing novel solutions. That's easy: just take the original Haskell solution or one of its shorter derivatives and type "take 100000 seq" at the Haskell prompt. It's not even a particularly resource-heavy operation. However, the results probably shouldn't be posted in this thread... :) > let hamming n = sort [2^i*3^j*5^k | i <- [0..n], j <- [0..n], k <- [0..n]] > let test m n = take m (hamming n) == take m seq > test 581 20 True > test 582 20 False Hey, lucky guess! So the first 581 out of the 21^3=9,261 Hamming numbers generated by (hamming 20) are a contiguous Hamming sequence. (I'm guessing that's not going to be the most efficient way of finding such sequences.) (hamming 20) Re the rules of this contest, I was under the impression it most resembled a game of Calvinball. Ha! We're in the "infinity is cheating" zone! Based on the title of your post, I was expecting it to be about Prolog. No such luck. Table generates all forms 2^i*3^j*5^k. It is wrong to say that Table misses some numbers. Set the bounds high enough and it produces all numbers of this type. ... Analysis of this one-liner will not be very productive. I would only be curious to see a good boundary formula. Table generates all forms 2^i*3^j*5^k. It is wrong to say that Table misses some numbers. Set the bounds high enough and it produces all numbers of this type. 2^i*3^j*5^k ... Analysis of this one-liner will not be very productive. I would only be curious to see a good boundary formula. Say, Now for the boundary formula. The following subset of H can be trivially seen to contain gaps in the Hamming sequence To ground this in concrete numbers, take N = 10. Then W is the wasted subset that consists of all elements of H that are greater than 210 = 1024. The cardinality of H is 1000. The cardinality of W is 913. I'm too lazy to do real math, but my gut feeling is that you're right. The efficiency of the above one-liner is most likely O(n3). El-vadimo - The array idiom can be O(N) if done right. Just follow through as proposed. The concept has no intrinsic flaw. Declarative arrays need only correct boundaries - here, tetrahedral, a corner cut from a cube. The proof code below is identical but with a boundary fix. It checks accurately against Haskell to the limits of available memory. Mathematica 5.1.1 runs it without external dependencies. (* Define a "two-liner" function *) HammingList[N_] := Module[ { A, B, C }, { A, B, C } = (N^(1/3)) * { 2.8054745679851933, 1.7700573778298891, 1.2082521307023026 } - { 1, 1, 1 }; Take[Sort[Flatten[Table[ 2^x*3^y*5^z, { x, 0, A }, { y, 0, (-B/A)*x + B }, { z, 0, C-(C/A)*x-(C/B)*y } ]]], N]]; (* Run once to bypass first-run issues *) First[Timing[thousand = HammingList[1000];]] 0. Second (* Check performance *) runtimes = Table[{N, (1/Second)*First[Timing[ chk =.; chk = HammingList[N];]]}, {N, 0, 1000000, 50000}]; (* Show formatted results *) PaddedForm[TableForm[runtimes, TableAlignments -> {Right}], {7, 3}, NumberPadding -> {"", " "}] 0 0. 50000 1. 100000 2.156 150000 3.375 200000 4.656 250000 5.969 300000 7.328 350000 8.625 400000 10.125 450000 11.422 500000 12.906 550000 14.344 600000 15.719 650000 17.156 700000 18.578 750000 19.859 800000 21.313 850000 22.828 900000 24.406 950000 25.688 1000000 27.187 These numbers plot a nice straight line showing O(N). Accuracy validates against Haskell output to well over one million numbers. (* Check 27000th number *) chk[[27000]] 3983823817623774429511680 (* Check millionth number *) chk[[1000000]] 519312780448388736089589843750000000000000 000000000000000000000000000000000000000000 The "millionth" sanity number from earlier is the million-and-first. Yes, this code computes it. Mathematica arrays index from 1. If you want the millionth number, you ask for it; if you want the million-and-first, you ask for that. ck = HammingList[1000000+1]; Last[ck] == 5193817979170907662740820181594482437424938166039389696 00000000000000000000000000000 True All that is why I called premature analysis unhelpful and tried shifting interest to the boundary question. Analysis will always condemn the wrong shape - cubes, spheres, prisms, or buckyballs. None of that condemns the array idiom. The worthwhile effort was to find the right shape. Armchair analysis shows why O(N) stands to reason. Generating N numbers is O(N). In this code a proportion are O(N^(2/3)) waste, which vanishes because O(N + N^(2/3)) = O(N). The waste is typically a few percent of N (small-N cases aside). This waste compares favorably against duplication waste in Haskell and C++. Formulas called Ehrhart polynomials could eradicate it altogether. Flatten is essentially free. Sorting is O(N log N) in general, but can be O(N) here, since we know a maximum value from the isosurface. Timing values will vary between machines. The timing experiment is the best simple one I can run. Smaller N happens so fast as to be unreliable, since OS background tasks jump in and out. One could average across many runs, I suppose. Larger N invokes virtual memory, which also breaks validity. Multiple millions of big-ints quickly tax computer resources. This throw-away code remains terse and easy to understand. It has room for improvement, like any code. People can nitpick it or perfect it. Habitual nitpickers should try the latter option for novelty's sake. Anton - We're on the same side, man. Quell urges to shoot down allies over small stuff. We both support functional programming. My lucky guess was deliberately chosen to demonstrate a boundary problem. Naturally the value barely worked. That was the point. On one scale things worked, on another they didn't. I had hoped someone would take the hint. Boundaries had already been suggested, and that simple go/no-go check validated the intuition. It did not yield formulas, but confirmed merit in a search. Somewhere you lost the plot and began Slashdotting. After you leave college, coworkers will express concepts and intuition without proofs on a platter. Every good idea starts somewhere. Try to be more encouraging and not kill the baby. This idiom is just one among many which I've posted. Thank me later for that Haskell find; I like it too. Infinity police should arrest someone else. Infinitely recursive Haskell streams need it, not arrays. Everyone praises the infinite-stream (Haskell) solutions. C. Hendrie's code is very good, I agree. Let's just be clear about infinities. A reference list quite obviously doesn't belong inline. The use of Haskell is obvious too. That sparkling brilliance for the obvious is blinding. My suggestion was a means for C++ folks to avoid Haskell. GHC is a 50 MB download/install/learn procedure with a console window, monad I/O, and non-terminating code in this case (CTRL-C and cross your fingers). LtU's site manager, already running the code and skilled in Haskell, could have done the deed in less time than it took to dismiss. A better offering than a huge list would be a Haskell-compiled executable (not script) that takes N and a file name as arguments, then spills the numbers to disk. Someone else can work on that, maybe Anton, maybe not. Everyone - The take-home lesson is that functional idioms can solve this problem in several ways. Some may feel more comfortable than others, but take your pick. Ehud will get a MathReader file with graphics and derivation. LtU still has no way to upload images. I'm not planning to revisit this page. Questions will have to be answered by the file. The numerical coefficients incorporate some consolidated arithmetic, so don't twist your brain on them. Send email through the web interface if there is something that you desperately want me to know. Here's Mark's file. % file HammingNumbersDeclarative.7z HammingNumbersDeclarative.7z: 7z archive data, version 0.2 and there's only an implementation of 7-zip for Windows. Too bad. Try this. Here's the Ocaml version of the C++ code (or rather a version): module Int = struct type t = int let compare (x: int) y = if x < y then -1 else if x == y then 0 else 1 end module IntSet = Set.Make(Int) let hamming n = (* generate the first n hamming numbers *) let rec loop i accu set = if i < n then let v = IntSet.min_elt set in let set = IntSet.remove v set in let set = IntSet.add (v * 2) set in let set = IntSet.add (v * 3) set in let set = IntSet.add (v * 5) set in loop (i+1) (v :: accu) set else List.rev accu in loop 0 [] (IntSet.add 1 IntSet.empty) ;; A variation of the Haskell solution is possible, but you'd have to write your own lazy list module (Ocaml doesn't have on in it's standard library). Hacking the above code to return both the required values and the calculated but not needed values I get: Unfortunately, at this point I overflow integers. Trying to calculate the 1238th Hamming Number, I overflow (on 32 bits). And I don't care enough to recode with larger numbers. Trying to calculate the 1238th Hamming Number, I overflow (on 32 bits). And I don't care enough to recode with larger numbers. On 64 bits (Debian amd64), this same OCaml code overflows when calculating the 10,856th Hamming number. BTW, my previous Haskell calc of the first million numbers was done on a sedate old 32-bit 450MHz PIII. (Insert entirely unreasonable apples-to-kumquats comparative observation here.) Yeah- I fiddle with my code a little bit to see if I could compute hamming numbers large enough that it took signifigant amounts of time on my 1.8GHz Athlon-64. No dice (yet). Here's the thing: from my explorations it looks like to find the nth hamming number, you have to compute about n extra numbers- so the total number of hamming numbers you have to compute is O(N). Each number costs approximately O(log N) to compute (or so- I have some thoughts about that I'll post seperately). Log of 10,000 is approx. 12, so we're looking at maybe 250,000 operations. Even on an old, slow P3, this isn't that much calculation. Not sure what the space complexity here is. Also, I'm not sure I'm being as lazy as I could be (pun intended)- I may be forcing some calculations unnecessarily. But here's the code (this should be the same solution as the Haskell code): type 'a t = | List of 'a * 'a t Lazy.t let rec scale n = function | List (h, t) -> List((h * n), lazy (scale n (Lazy.force t))) ;; let rec merge x y = match x, y with | List(xh, xt), List(yh, yt) -> if xh == yh then List(xh, lazy (merge (Lazy.force xt) (Lazy.force yt))) else if xh < yh then List(xh, lazy (merge (Lazy.force xt) y)) else List(yh, lazy (merge x (Lazy.force yt))) ;; let rec seq = List(1, lazy (merge (scale 2 seq) (merge (scale 3 seq) (scale 5 seq))));; let hamming n = let rec loop i accu = function | List(h, t) -> if i < n then loop (i+1) (h :: accu) (Lazy.force t) else List.rev (h :: accu) in loop 1 [] seq ;; I instrumented the code above to count how many times merge and scale are called to calculate the nth Hamming number. Here's my results: This looks to me like an O(N) solution. (a list would work too, but it would mean more typing), and sort of encapsulate the state in a struct, and... #include <vector> #include <iostream> using namespace std; typedef long long foo_t; struct bar { vector<foo_t>& v; mutable int i; int m; operator foo_t() const { return v[i]*m; } foo_t operator++(int) const { foo_t r=*this; ++i; return r; } bar(vector<foo_t>& iv, int im):v(iv),i(0),m(im) { } }; int main() { vector<foo_t> s(1,1); foo_t q; bar x(s,2), y(s,3), z(s,5); while(s.back()>0) { cout << s.back() << '\n'; do q=min(x,min(y,z))++; while(q==s.back()); s.push_back(q); } } Not that that's hugely idiomatic (and the mutable is a little evil; perhaps I've been reading too many IOCCC winners lately) but my point, such as there is one, is that it's basically the same algorithm as the "obvious" Haskell solution, done imperatively in C++ without too many (necessary) contortions. And it's not particularly harder to "target" plain C that way, either. And go back to a linked list for simplicity's sake, and reclaim unused storage... and then sadistically fiddle with the flow control and formatting, because I have been reading too much IOCCC code, and: #include <stdlib.h> #include <stdio.h> typedef long long foo_t; #define PR_foo "%lld" int main() { struct c { foo_t a; struct c*d; } *o=malloc(sizeof*o), *t=o; struct { foo_t m,n; struct c*b; } *w,x,y,z; w=&x; x.m=x.n=2; y.m=y.n=3; z.m=z.n=5; (x.b=y.b=z.b=o)->a=1; goto harmful; while(o->a>0) { w->n=w->m*(w->b=w->b->d)->a; if (w==&z) free(t); t=z.b; w=x.n<y.n?&x:&y; w=z.n<w->n?&z:w; harmful: if (o->a==w->n) continue; printf(PR_foo"\n",o->a); (o->d=malloc(sizeof*o))->a=w->n; o=o->d; } return 0; }, and sort of encapsulate the state in a struct, and... We have now come full circle. The above is essentially the original solution proposed by Dijkstra, the one that the article describes as "much faster but fairly tricky". I didn't include the corresponding code listing in the original post to save space. So yes, you can implement an efficient solution in C++. However, efficiency was not the article's primary consideration. The article intended to defend C++ against claims by the FP community that there was no elegant C++ solution comparable in speed and simplicity to, say, the Haskell implementation. The article attempted to share the authors' Aha-Erlebnis that there is, in fact, a C++ solution that is only slightly less time-efficient than the Haskell solution (it's O(n*log(n)) versus O(n) in the Haskell version); written in "idiomatic C++" and thus does not require "a totally different way of thinking". In light of this, the article claims, the Hamming problem can no longer be held up as a shining example of the alleged superiority of the functional paradigm. However, the article fails to address the following points: It hides the clunkiness of the fully fleshed out implementation by only listing a mere four-line outline of the main idea. If the article were to provide a full implementation, it would have become obvious that, as Scott Turner pointed out more than once, the C++ version provides no idiomatic way to access the generated sequence. The Haskell version is substantially more space-efficient. While STL may no longer be considered "a totally different way of thinking", it can be argued that it used to be just that when it was first introduced. Overall, the article was a good read despite failing to support its conclusion. The thing I really like about the Haskell approach is that it feels much easier to experiment with different approaches in a delcarative setting. For instance, we can observe that the given Haskell solution isn't making use of the commutativity of multiplication: the Hamming number 36 is generated five times as 2*2*3*3 and 2*3*2*3 and 2*3*3*2 and 3*2*3*2 and 3*3*2*2. We could consider annotating the list of hamming numbers with their largest prime factor, to help induce an ordering on the multiplications: -- using merge as above scalef n xs = [ (n * x, n) | (x, m) <- xs, m <= n ] hamf = (1,1) : scalef 2 hamf `merge` scalef 3 hamf `merge` scalef 5 hamf ham2 = map fst hamf Then we can observe that it's wasteful for 'scalef 2' to have to filter through all the hamming numbers, when it's just generating powers of two. If we stage the lists, we can omit the filtering. After a few more iterations in ghci, I arrive at: all_multiples n (x:xs) = a where a = x : merge xs (map (n*) a) ham3 = foldr all_multiples [1] [2,3,5] Quite a bit faster than the original, and requires less from 'merge', since it never generates duplicate numbers. As a fun exercise, you can plug a 'primes' one-liner in for [2,3,5] and construct the natural numbers the hard way. :) [ edited to correct identifiers ] I was sloppy in my reasoning about the redundancy in the original implementation: each Hamming number is generated at most three times, not an arbitrarily large number of times. I should have been suspicious when my "optimized" versions only offered a constant factor of improvement. Also, all_multiples is too strict to work for regenerating the naturals from the primes. We need a more constrained method which takes advantage of the ordering: -- multiply_out requires that n is strictly less than (head xs) multiply_out n xs = a where a = n : merge xs (map (n*) a) ham4 = 1 : foldr multiply_out [] [2,3,5] nat = 1 : foldr multiply_out [] primes all_multiples n (x:xs) = a where a = x : merge xs (map (n*) a) would be completely non-strict written, all_multiples n ~(x:xs) = a where a = x : merge xs (map (n*) a) I'm too lazy to see if that will make it work. On a side note, multiply_out looks broken (copy/paste error?) I was perhaps, er, lazy when I used the word "strict". What I meant was that all_multiples requires the first element of the list to be passed through from the right. If it's being foldr'd over an infinite list, we never get the initial 1. multiply_out solves the problem by 1) providing the tail of the list produced by all_multiples. 2) requiring that n It boils down to the observation that no amount of laziness will allow us to do a general infinite-way merge. We need to impose some ordering on the heads of the lists to be merged to make it work. Typo in multiply_out fixed, thanks. I have a little question concerning the way Haskell evaluates infinite lists. I don't understand why the Haskell algorithm is o(n) while the C++ algorithm is o(n*log(n)). How does Haskell do the computations? doesn't it have to compute all hamming numbers from 1 to N, in order to reach the Nth number? isn't C++ doing the same? I understand that the Haskell algorithm uses a clever sort that actually merges two already sorted lists, while the C++ one uses binary tree algorithms (the STL set). Is that what makes the difference? or is it something else? How does Haskell unites lists? doesn't it have to allocate a single linked list node in its garbage collected heap for each value? Please help a fellow programmer understand a little bit more your favorite programming language! :) Yes, it needs to compute N-1 Hamming numbers before read Nth, but it does not check for duplicates by using any O(n*logn) structure such as set or map templates. Duplicates are handled in merge operation which merges two ascending lists. Wouldn't be possible for the C++ version to use the same merge as in Haskell? EDIT: Isn't the merging operation slower than using trees? Yes, it is possible, because GHC compiles to C. ;) Yes, because you can emulate lazy evaluation. And sound no because you wouldn't be even closer to count of lines of Haskell version. I tried that with lists with strict heads and lazy tails and I know what I am talking about. Merging operation is faster that lookup operation for usual sets and maps. More than that, merging of lazy lists allows you to throw away unnecessary computations on the process of computing some big hamming numbers, and you start to win in memory requirements. Or you can organize computation as memoizing, and you will start to win in speed. template < class R > void hamming(R &r, int n) { r.push_back(1); R::iterator it = r.begin(), t; while (n) { t = it; t = insert_sorted(r, ++t, *it * 2); t = insert_sorted(r, t, *it * 3); insert_sorted(r, t, *it * 5); ++it; --n; } } If you can't find 'insert_sorted' in STL, don't worry; here it is(I don't consider it part of the solution since STL could have had it, if it doesn't already). It returns an iterator to the next element after the insertion point: template < class R, class IT, class V > IT insert_sorted(R &r, IT it, V v) { for(; it != r.end(); ++it) { if (v == *it) return ++it; if (v < *it) return ++r.insert(it, v); } return r.insert(r.end(), v); } maybe the insertion process can be optimized even more by keeping track of the last inserted element and then go down or up from that. It's quite elegant, though. Firstly, your function does not generate the first n Hamming numbers, it can compute as many as the 3n first numbers (in general it will be less due to duplicates, of course). It would be easy enough to fix this by just checking the size of the container after each insertion. Secondly, it's pretty easy to see that the "gap" insert_sorted has to traverse grows as R grows, so the algorithm certainly cannot be O(n). I'm having a hard time coming up with the exact run-time complexity but in any case it's easy to rule out O(n). A quick aside: I think you need to make a few changes to make your code work with containers like std::vector because of the insertions (which will invalidate 'it' whenever resizing is forced). In its current state it should work fine with std::list (and this might be what you tested it with). Firstly, your function does not generate the first n Hamming numbers, it can compute as many as the 3n first numbers I thought the version using sets does that too. Secondly, it's pretty easy to see that the "gap" insert_sorted has to traverse grows as R grows, so the algorithm certainly cannot be O(n). Yes, at each iteration the "gap" grows, so it's certainly not O(n). But the algorithm takes advantage of 2*N < 3*N < 5*N to eliminate some searches. How would it be if 'insert_sorted' searched the remaining list in the reverse direction, i.e. from end to current element? I think you need to make a few changes to make your code work with containers like std::vector because of the insertions Yeap, it works for containers that their iterators are not invalidated when an element is inserted. here is an O(n) C version that more or less mimics what the haskell version does (and doesn't check the return values of malloc, bad me:-)): #include <stdio.h> #include <malloc.h> /* Production code would use a linked list implementation with a * less braindead allocation strategy than a malloc for every node */ typedef struct node { long val; struct node *next; } node; /* We keep an evaluation context: a pointer to the end of the list of * hamming numbers, and three pointers to the next elements of the lists of * multiples, together with the next values from the lists */ typedef struct context { node *curr; node *times[3]; long val[3]; } context; long fakt[] = {2, 3, 5}; /* The function that calculates the next hamming number for a given * context */ long hamming(context **ctx) { node *next; int i; next = malloc(sizeof(node)); next->next = NULL; if (NULL == *ctx) { /* First call, initialise the context */ *ctx = malloc(sizeof(context)); next->val = 1; (*ctx)->curr = next; for (i=0; i<3; ++i) { (*ctx)->times[i] = next; (*ctx)->val[i] = fakt[i]; } return 1; } else { long min; /* Find the minimal unseen element from the three lists of multiples */ min = (*ctx)->val[0] < (*ctx)->val[1] ? (*ctx)->val[0] : (*ctx)->val[1]; min = min < (*ctx)->val[2] ? min : (*ctx)->val[2]; next->val = min; (*ctx)->curr->next = next; (*ctx)->curr = next; /* Advance all lists whose next element is equal to the minimum, * to eliminate duplicates. The third list (times 5) gets a special * treatment to eliminate inaccesible nodes, the Boehm GC would make * this unnecessary. */ for (i=0; i< 2; ++i) { if ((*ctx)->val[i] == min) { (*ctx)->times[i] = (*ctx)->times[i]->next; (*ctx)->val[i] = (*ctx)->times[i]->val * fakt[i]; } } if ((*ctx)->val[2] == min) { node *tmp; tmp = (*ctx)->times[2]; (*ctx)->times[2] = (*ctx)->times[2]->next; (*ctx)->val[2] = (*ctx)->times[2]->val * fakt[2]; free(tmp); } return min; } } int main(int argc, char **argv) { long i, m; context *ctx; ctx = NULL; if (argc < 2) { m = 25; } else { m = atol(argv[1]); if (m < 1) { m = 25; } } for (i = 1; i <= m; ++i) { long h; h = hamming(&ctx); if (h < 0) { fprintf(stderr, "Numerical overflow at hamming number %ld.\n", i); exit(-1); } printf("%8ld: %16ld\n", i, h); } exit(0); } Oh, by the way, wouldn't it be nice to have the classes htmlize.el produces predifined in the CSS files? Undoubtedly, we've come a long way since C. Looking at the above code and comparing to even the original posted Haskell code and you see how much along we've come in programming language design. Clearness, conciseness, expressivity... all are missing from the above. And no, putting short variable names in this case actually just make things even worse... probably, a better approach would be just implement a Haskell compiler in C anyway? :) template < class T, class C = vector < T > > class hamming_number { public: hamming_number(int reserve) : m_v2(2), m_v3(3), m_v5(5) { m_vals.reserve(reserve); m_it = m_it2 = m_it3 = m_it5 = m_vals.insert(m_vals.end(), 1); } operator T() const { return *m_it; } T operator ++ () { T v = min3(m_v2, m_v3, m_v5); m_it = m_vals.insert(m_vals.end(), v); if (v == m_v2) m_v2 = *++m_it2 * 2; if (v == m_v3) m_v3 = *++m_it3 * 3; if (v == m_v5) m_v5 = *++m_it5 * 5; return v; } private: C m_vals; C::iterator m_it; C::iterator m_it2; C::iterator m_it3; C::iterator m_it5; T m_v2; T m_v3; T m_v5; }; I have to admit this though: although I understood the Haskell algorithm, I had not realized how to do it in C++ unless I looked at the C algorithm...and this is because the actual hamming algorithm is quite simple but Haskell did not gave me any clues about how to implement it in C++. It's pretty simple though once you realize the fact that, at each iteration, a new hamming number is produced by calculating the minimum of 3 other numbers that are somewhere in the list of already computed hamming numbers. The above code calculates the first 1000 hamming numbers in 0.000040 seconds (time measured using QueryPerformanceCounter under Win32) with all optimizations on and using a vector of 1000 numbers on an Athlon 64 3400+ using MSVC++ 6.0 (which it probably means that the Intel compiler could do an even better job). It seems that it is possible to translate the Haskell code to Oz almost verbatim. Just insert some lazy declarations. lazy Scale = fun lazy {$ N X|Xs} N*X|{Scale N Xs} end Merge = fun lazy {$ X|Xs Y|Ys} if X == Y then X|{Merge Xs Ys} elseif X Seq = 1|{Merge {Scale 2 Seq} {Merge {Scale 3 Seq} {Scale 5 Seq}}} For the sake of completeness, there's an Oz version of the Hamming functions in CTM (4.5.6) that I translated to Alice ML: fun lazy scale n [] = [] | scale n (x::xs) = (n*x)::(scale n xs) fun lazy merge xs nil = xs | merge nil ys = ys | merge (xs as x::xr) (ys as y::yr) = if x y then y::(merge xs yr) else x::(merge xr yr) val h = promise(); fulfill(h, 1 :: (merge (scale 2 (future h)) (merge (scale 3 (future h)) (scale 5 (future h))))); Here is a C++ solution that: template < class L, class T > int hamming(L &l, T it[3]) { if (l.empty()) it[0] = it[1] = it[2] = l.insert(l.end(), 1); else { l.push_back(min(*it[0] * 2, min(*it[1] * 3, *it[2] * 5))); if (l.back() == *it[0] * 2) it[0]++; if (l.back() == *it[1] * 3) it[1]++; if (l.back() == *it[2] * 5) it[2]++; } return l.back(); } Usage: int main() { list < int > l; list < int > ::iterator it[3]; for(int i = 0; i < 40; ++i) { int h = hamming(l, it); std::cout << h << ", "; } return 0; } Output: 1, 2, 3, 4, 5, 6, 8, 9, 10, 12, 15, 16, 18, 20, 24, 25, 27, 30, 32, 36, 40, 45, 48, 50, 54, 60, 64, 72, 75, 80, 81, 90, 96, 100, 108, 120, 125, 128, 135, 144 I can therefore officially declare that the hamming numbers problem can no longer be used to demonstrate the superiority of functional programming languages; C++ can do it equally well. The C++ solution is inherently unsafe. (As are C++ templates and typing in general.) Please explain. Templates are nothing more than string rewriting rules and do not respect typing; and without templates, the C++ type system is so weak that we need to fall back on unsafe tricks like casting to void*, etc. Do templates "not respect typing"? I thought the whole point of templates was to make type-safe macros (among other things)? Templates fully respect the C++ type system; at least that any template-expanded code must respect the type system. Templates are type-aware, as well--it just isn't a glorified text preprocessor. Of course, if you do things like foo, the resulting code is not likely to be type-safe. And C++ template code still can take full advantage of all the legacy C holes in the type system (pointer arithmetic, unchecked typecasts, returning pointers to the stack, memory management errors producing pointers to garbage). But the template system doesn't add to the type-unsafeness of C++; if anything it improves it by providing a mechanism for building safe constructs (like vector) which are effective replacements for unsafe ones (like T[]). See Stroustrup C++0x where he talks about type safety, generics and so-called "concepts". The template system isn't any more "type-aware" than the old C macro system. It's the compiler that ultimately does the type checking over the expanded code; whereas I was talking more about something akin to structural typing or meta-types or whatever. The first sentence seems to bely some ignorance on how C++ templates work. I absolutely reject the claim that the template system "isn't any more 'type-aware' than the old C macro system". Tell me how the template engine can distinguish between types and values if it is type-agnostic. Tell me how it can perform partial specialization. Are you telling me that when I write: template <int N> int foo() { return N; } template <int N[3]> void foo() { return N[1]; } int main() { foo<3>(); } #define foo0(x) (x) #define foo1(x) (x[1]) I think I see some problems with your code. Correct me if I'm wrong. Interface problems: 1) To compute some Hamming numbers, I need to manually supply an array of 3 iterators. Why? Isn't this an implementation detail? 2) The function's signature doesn't suggest that the types L and T are related. 3) Templates are used, but the return value of "hamming" is a plain old C int :-) Implementation problems: 4) You're doing a lot more multiplications and comparisons than required. (Certainly more than 2 times more.) 5) Some code is triplicated (2,3 and 5). The constants 2,3 and 5 are each mentioned twice. It is an implementation detail. Supplying a list is also an implementation detail. But it is the nature of the language, and it does not matter, really. The function's signature doesn't suggest that the types L and T are related. Templates are used, but the return value of "hamming" is a plain old C int It can be like this: template < class L > L::value_type hamming(L &l, L::iterator it[3]); You're doing a lot more multiplications and comparisons than required. (Certainly more than 2 times more.) Some code is triplicated (2,3 and 5). The constants 2,3 and 5 are each mentioned twice The number of multiplications is exactly the same as in the Haskell version. The compiler sees the same multiplications and puts them in local variables. The number of comparisons is also exactly the same as in the Haskell version: at each iteration, Haskell has to compare the 3 values coming from the 3 multiplications and advance one of the 3 iterators. Actually, my code is exactly the same as the C version posted above, which (the poster claims) is what Haskell does under the hood. Yes, this signature is definitely better. The number of multiplications (and mentions of 2, 3 and 5) in source code matters just as much as the number of multiplications in the compiler output. Don't Repeat Yourself :-) Also, I'm not sure you're right about the number of comparisons. You're doing them twice. Once inside the min() calls and once in the equality checks. OTOH, the Haskell version has a 3-way branch on the result of each comparison. No, this isn't a "compiler smartness" nitpick on my part - this is a "language expressivity" nitpick :-) Ah, sorry. We're talking about different "Haskell versions". You must mean the one in the original post? I mean the "remarkably concise" code posted by Mark Evans - I like it more :-) You almost fooled me :-) Your code is doing 3 multiplications on _each_ call. Too many. This is because the "next values" of iterators that fail to advance are being recomputed again and again. In Haskell, they're computed only once. The compiler won't help you, unless it does memoizing :-) But isn't Haskell doing 3 multiplications at each iteration to compute some new list nodes anyway? Haskell computes each element of each of the 3 lazy lists exactly once. Or so I think :-) Anyway you don't need 3*N multiplications to find N Hamming numbers. You should only need N :-) Haskell computes each element of each of the 3 lazy lists exactly once. Or so I think :-) But not every multiplication appears in the final list, as the function merge filters out the duplicates. You need as many multiplications for a hamming number as there are different prime numbers in its factorisation. So; 0 for 1, 1 for {2n, 3n, 5n}, 2 for {2n3m, 2n5m, 3n5m} and 3 for the others (which is the majority). For example, you need about 2500 multiplications to compute the first 1000 hamming numbers. merge Anyway you don't need 3*N multiplications to find N Hamming numbers. You should only need N :-) Right, see Christopher Hendrie's implementatation our mine elsewhere in this thread. Ah, thanks. I was confused, but think I understand now. axilmar's C++ version: 3*N original haskell: a bit less than 3*N (but asymptotically, I somehow feel this is 3*N again, because "degenerate" Hamming numbers are more and more rare) your version: N I expect this to require just a quick dirty counter variable in C++. What about Haskell - state monad, or explicit threading of the counter? Num This requires a bit more thought than incrementing a global variable at each multiplication, but I think that's because the gap between the Haskell program and its execution behaviour is greater. This gap may be smaller in C++, but it's still there. In the C++ example you could increment a global variable at each multiplication, but perhaps the compiler eliminates the common multiplications and your count is not accurate anymore. Thanks to type classes you don't need to change the function (e.g. ham4, just add a type declaration ham4 :: (Ord a, Num a) => [a] in this case) that generates the humming numbers to be able to count the multiples. A quick and dirty implementation of such decorated number is: ham4 :: (Ord a, Num a) => [a] data N = N Integer Integer deriving (Eq, Show, Ord) order (N _ o) = o instance Num N where (N x a) + (N y b) = N (x + y) (max a b) (N x a) - (N y b) = N (x - y) (max a b) (N x a) * (N y b) = N (x * y) (a + b + 1) negate (N x a) = N (negate x) a abs (N x a) = N (abs x) a signum (N x a) = N (signum x) a fromInteger = make . fromInteger where make n = N n 0 For the millionth hamming number it gives 175 multiplications. It's also easy to use the same technique to collect each operand: data H = H Integer [Integer] deriving (Eq, Show, Ord) terms (H _ ts) = ts instance Num H where (H x a) + (H y b) = undefined (H x a) - (H y b) = undefined (H x a) * (H y b) = H (x * y) (a ++ b) negate (H x a) = H (negate x) a abs (H x a) = H (abs x) a signum (H x a) = H (signum x) a fromInteger = make . fromInteger where make n = H n [n] This shows that first all 2s are computed, then 3s and finally 5s. Another implementation shows how many of each: 238 3109 529 = 519312780448388736089589843750000000000000000000000000000000000000000000000000000000. 238 3109 529 = 519312780448388736089589843750000000000000000000000000000000000000000000000000000000 class Int { Int(int x) : x_(x) { } friend int operator*(int x, Int y) { ++mults_; return x * y.x_; } static int mults_; int x_; }; int Int::mults_ = 0; In the C++ version, replace the constants with Int(x) Basically 7 lines. However, I will admit that the Haskell version does more with each line. But at least part of that is because the language strips out all unnecessary syntax, whereas C++ takes a more conservative approach. Also, Haskell overloads operators even more than C++ does. And, being an FP, the intrinsic data structures are naturally richer, leading to a more concise syntax; whereas C++ elects to make anything bigger than a machine word into a library. Finally, the biggest gains Haskell makes are due to the fact that it treats functions as first-class values, which is as one should expect. #include <iostream> #include <list> template <class L> typename L::value_type hamming(L &l) { static int const p[] = { 2, 3, 5 }; static typename L::iterator it[3]; if (l.empty()) it[0] = it[1] = it[2] = l.insert(l.end(), 1); else { typename L::value_type const f[3] = { *it[0] * p[0], *it[1] * p[1], *it[2] * p[2] }; int const i = f[0] < f[1] ? (f[0] < f[2] ? 0 : 2) : (f[1] < f[2] ? 1 : 2); l.push_back(f[i]); for (int i = 0; i != 3; ++i) if (l.back() == f[i]) ++it[i]; } return l.back(); } int main() { std::list<int> l; std::cout << hamming(l); for (int i = 1; i != 40; ++i) { int h = hamming(l); std::cout << ", " << h; } std::cout << std::endl; return 0; } This version obviously requires that operator*(typename L::value_type, int) be defined in the sensible way, as well as requiring L::value_type to be LessThanComparable and EqualityComparable, but any reasonable numeric type will need to satisfy those constraints anyway. It's a bit long, but mostly that has to do with the fact that C++ template code tends to be a little verbose. Will Haskell version still be better than C++? The 'hamming' function can be paramerized on the primary factors by using template constants. For example: template < int P1, int P2, int P3, class L > L::value_type hamming(L &l, L::iterator it[3]) And used like this: hamming<2, 3, 5>(l, it); On other issue: your client code seems not using "it" in any way other than passing it into the "hamming", am I right? The code to support an arbitrary number of parameters using the Boost.Preprocessor Library, but Paul Mensonides is probably the only person who could do so in an hour or less. Of course, the arity will be limited by the limitations of the C++ preprocessor, but I'm sure you could get a fairly high number of factors. What if I learn these factors only at runtime? That's actually my main reservation about expressive power of C++ meta-programming - the fact that it is exactly meta. I would prefer an approach that would not impose a choice of phase of evaluation on me. Can you cite a real-world example of an algorithm where you know the fundamental parameters at compile time sometimes, and at runtime other times? I've seen all sorts of crazy optimizations for FPS games. I wouldn't be surprised if some people have specialized their code to know image sizes at compile time. Image loading generally finds out the image size at runtime obviously. I like partial application/evaluation because then I don't have to choose. (Yes, I know that only partial evaluation is compile time.) --Shae Erisson - ScannedInAvian.com I'd be surprised if it happened now. Of course, there was a time when compiled sprites were worth using... On PC-level computers it happened a few years ago in massive "real-time" strategy game engines like Cossacks. I am possitive it still happens on lower-end devices like PDAs and mobiles. I agree with shapr that computer games are especially prone to pushing cycles from runtime to compile time (Paul/Tim?), but in fact any application living on the edge of feasibility given the hardware and other parts of environment would do that. ... that it's dirt common in games to have huge amounts of data at game build-time that you could simply pump through your renderer at runtime, but you wouldn't get acceptable performance that way, so some data-driven calculations are done at build-time. For example, games tend to do "potentially visible set" (PVS) calculations at build-time so as not to bother rendering polygons that wouldn't be visible to the user anyway at runtime. More recently, a great deal of work has been done in the application of partial evaluation to raytracing and to specializing complex shaders. It's interesting to note that Mark Leone, whose name is well-known in partial evaluation, runtime code-generation, and Standard ML circles, was ultimately hired by Pixar and wrote an important paper on the Multi-Pass Partitioning Problem. His name also appears in the credits of "The Incredibles." Shaders are where it's at these days, and a lot of attention is being paid to functional programming and partial evaluation in the context of shader algebra and specialization. It would be interesting to hear from Tim how Unreal Technology 3's artist-controlled visual shader development tools do (or do not) represent a particular form of specializing shader compiler. The function would become: template L::value_type hamming(L &l, vector &it, const vector facts); The code will use the supplied vector of iterators and factors, and use for-loops inside the code to perform the computation. Paul Mensonides is probably the only person who could do so in an hour or less. No disrespect to Paul, but if you can afford to use a C99 preprocessor, anyone who knows FP should be able to write the generator in a matter of minutes using the Order interpreter. See here for examples. (For the record, given a choice, I wouldn't use C++. I have given up on C++.) Heh. This debate always sounds like the fate of the universe hangs in the balance of some preprocessor metaprogramming libraries (PMLs). ;> One thing that the existence of PMLs has convinced me of is that there must be a better way. ;) That better way, I think, is a language that allows you to jump levels of abstraction seamlessly, like Lisp/Scheme, but within an imperative/static typing context, which is probably about as painful and difficult to implement as it sounds. I sympathize with your sentiments re: C++. I think it's a fine language in some respects, and I think it deserves some respect for the areas in which it broke ground; but I fear that true progress can only be had by starting fresh. With no disrepect to Paul or the other Boost.PP lib authors, my comment is as much a commentary on the Boost.PP lib as it is a compliment to Paul's skills. I haven't seen Order before. I'd appreciate better links if there are any. Looks cool! I don't think that there are considerably better links than the examples at SF. Order was my hobby project for some time, but, like I said, I have given up on C++ (meaning: I try very hard to avoid wasting any more time with C++). The roots of Order can be traced back to this post. After that I switched to a C99 preprocessor and discovered several improvements, which improved performance (in some important cases) by two orders of magnitude and made interpretation "practical" in some sense. I spent one summer to make an implementation of the Order language culminating in this post. Since then I have come to the conclusion that I don't want to waste more time with C++ and the Order project is (consequently) on hold. The actual Order interpreter is basically finished (just checkout the code from SF CVS). Documentation (except for the examples) is incomplete. Thanks If no one else does it, let me try my first Haskell program: merge xs [] = xs merge [] ys = ys merge (x:xs) (y:ys) | x == y = x : merge xs ys | x < y = x : merge xs (y:ys) | otherwise = y : merge (x:xs) ys ham factors = seq where seq = 1 : (foldr mergeScaled [] factors) mergeScaled n xs = merge xs (map (n*) seq) First timer issue: I find it odd that the arguments to mergeScaled have to be n xs, when the order in foldr is [] factors. n xs [] factors I also tried an imperative version in Javascript. It was telling that getting the Javascript version right was harder than getting the Haskell version right, while this was my first Haskell program, and I program in JS daily. You can generate the pn+1-smooth numbers from the pn-smooth numbers by mixing in pn+1 (pn being the nth prime): smooth :: [Integer] -> [Integer] smooth l@(h:t) = next where p = missing l next = h : merge (map (* p) next) t The function missing finds the first gap in the previous smooth sequence, which is the next prime. missing :: [Integer] -> Integer missing l@(_:t) = head [n+1 | (n,m) <- zip l t, n+1 /= m] Now we can generate all smooth sequences by iterating over the 2-smooth sequence (the powers of 2): smoothies :: [[Integer]] smoothies = iterate smooth (iterate (* 2) 1) For example the hamming sequence (5-smooth) is the third element from this list, so the following test function should not terminate. test = smoothies !! 2 == ham Interestingly enough the more general version is almost twice as fast as the direct version, but I have yet to figure out why. We now also have a odd way to generate the odd primes: oddPrimes :: [Integer] oddPrimes = map missing smoothies Interestingly enough the more general version is almost twice as fast as the direct version, but I have yet to figure out why. It would be nice to know whether it is just a quirk of the compiler, or a genuine improvement of algorithm. If we only had compilers inferring algorithmic complexity for us (say as a part of type inference process)... The general version is faster because it doesn't generate any duplicate composites. The corresponding specialised hamming function is: ham = c5 where c2 = 1 : map (* 2) c2 c3 = 1 : merge (map (* 3) c3) (tail c2) c5 = 1 : merge (map (* 5) c5) (tail c3) Because the algorithm doesn't generate duplicates, the following merge function suffices: merge (x:xs) (y:ys) | x I suspect that any lazy functional algorithm can be translated to an imperative one by using these simple rules: 1) a lazy algorithm can be encoded as an imperative function which transforms some input according to some computation. 2) the imperative implementation needs 1 collection and a number of iterators equal to the number of references of the lazy function in the right side of the equation. For example, the Haskell version mentions 'hamming' 3 times at the right hand side, so 3 iterators are needed for the imperative algorithm. The above is from intuition, I must say. The above named paper is a rather old paper (but a still a good read), but has some more complicated examples using lazy evaluation that you could use to test your hypothesis. Particularly section 5 which implements the alpha-beta heuristic. Why Functional Programming Matters here That papers really irks me. While it proposes a nice list of hacks, this sort of thing will not impress anybody who does industrial programming. Quite the contrary, I think. I tried an OCaml solution to the Hamming problem. It is listed below. It uses a small trick with a continuation/coalgebraic flavor. An infinite lazy sequence can be modelled as a datatype which consists of a head, and a tail function with will give the next head and the next tail function. It's my first ten minutes try, it doesn't work for large lists. Probably there is some reevaluation taking place (no sharing?) - will look at it again at some point. Anyway, here's the code; please spot the bug ;-) type num = int type clist = H of (num * (unit -> clist)) let rec merge: clist -> clist -> clist = function H(x, fx) -> function H(y,fy) -> if x < y then H(x, function _ -> merge (fx()) (H(y,fy))) else if x == y then H(x, function _ -> merge (fx()) (fy())) else H(y, function _ -> merge (H(x,fx)) (fy())) let rec scale: num -> clist -> clist = function s -> function H(x, fx) -> H(s * x, function _ -> scale s (fx())) let rec hamming: clist = H(1, function _ -> merge (scale 2 hamming) (merge (scale 3 hamming) (scale 5 hamming))) let rec print_clist: num -> clist -> unit = function n -> function H(x,fx) -> if n = 0 then print_newline () else (print_int n; print_string " : "; print_int x; print_newline (); print_clist (n-1) (fx())) let _ = print_clist 1000 hamming [Edit: hmm, might be because I de/reconstruct all the H-fields] [Edit the edit: can't be it, either I am explicitly copying -am I?- or ocaml doesn't have a true graph rewriting semantics -does it?- which would make sense I guess...] Your evaluation order is busy, rather than lazy, it reevaluates everything, all the time, try let rec scale: num -> clist -> clist = function s -> function H(x, fx) -> Printf.fprintf stderr "Evaluating %d * %d\n" s x; H(s * x, function _ -> scale s (fx())) You should change your lazy list to type clist = H of (num * clist Lazy.t) and sprinkle your code with magic pixie dust the approriate lazy and Lazy.force statements. Thanks for the heads-up. Yeah, I know you can do it like that. But that wasn't really the point of the exercise: I wanted to try and do it without the lazy keyword... Here is another way to do it in C++ using lazy lists: list < int > hamming = val(1) >> next(min(2*hamming >> 3*hamming >> 5*hamming)); The list would be used like this: iterator < int > it = hamming; for(int i = 0; i < 40; i++) { cout << it() << ","; it = tail(it); } Notes: operator >> val operator * min it tail(it) The above can be used in any lazy list. For example, the Fibonacci sequence would be defined as: list < int > fib = val(0) >> val(1) >> next(fibs + tail(fibs)); The above formula would create two iterators (since there are two fibs references at the right side of the formula). Initially, both iterators would point to value 0. At the third extraction, the new value would be the value of iterator 1 (0) to the value of the next element of iterator 2 (value 1). The function 'next' would be used to advance the iterators passed to it to their next element. EDIT: Yeap, it can be done, thanks to C++ operator overloading. So the hamming algorithm can be done better in C++ than in Haskell...in just one line of code! So the hamming algorithm can be done better in C++ than in Haskell...in just one line of code! Indeed, I implemented some subset of Haskell (along with some hacks), just to show that it can be done. Aside from being a cool hack, the code can be reused for doing any kind of lazy lists. Of course since Haskell is available, there is no point in using C++ as Haskell...but it is a nice exercise anyway. By the way, I think it is possible to do it exactly like in Haskell with complete lazy evaluation, and writing the merge function as a functor object, like this: fun2 merge = _if(_1 == _2, merge(tail(_1), _tail(_2))) | _if(_1 < _2, _1 >> merge(_1, _tail(_2)) | _2 >> merge(_tail(_1), _2); The above functor object would return an operation object that would be attached to the list and evaluated when needed. Yeah, right. We're pretty close to expression trees and an evaluator... the next step would be a parser and interpreter. I'm already waiting for somebody who'd advocate "idiomatic Java" for the same task: Function merge = new BinaryFunction(new Branch(new Case(new EqualCondition(Parameter.FIRST, Parameter.SECOND), ...et cetera, ad nauseam... and we get garbage collection for free! Surely there's got to be a limit somewhere. For me, the limit is simple: Don't Write Bad Code. The code you supplied is so obviously Bad, I'm embarrassed even to have to explain it. After all, C++ is the devil for LtU members. But the truth is, since C++ allows operator overloading and value type objects, a lazy library can easily be written that does exactly what Haskell does and with the same expressitivity. And your Java example is simply wrong, because what makes the hamming algorithm be beautiful it is the way it is expressed using operators. Since Java lacks operator overloading, it can not be considered equal in expressitivity. So there has got to be a limit somewhere. For me, the limit is simple: don't say stupid things. The example you supplied is so stupid, I am embarrassed even to have to write about it.
http://lambda-the-ultimate.org/node/608
CC-MAIN-2018-05
refinedweb
21,998
61.67
dennis neal <neon10@xxxxxxxxxxx> writes: > Ed: > > Yes, I ran the configure script. I discovered that the easiest way > to get the dictionary file was to run configure, then move config.h > and the libsrc *.c files into the cxx directory. That contains then > all files needed to compile the C++ interface. What environment are you trying to build in? > But I dont see where in config.h that the DLL is defined, so that I > can make sure that it is turned off. I'm not a C programmer, but > dont see it. In config.h: /* set this only when building a DLL under MinGW */ /* #undef DLL_NETCDF */ In netcdf.h: /* Declaration modifiers for DLL support (MSC et al) */ #if defined(DLL_NETCDF) /* define when library is a DLL */ # if defined(NC_DLL_EXPORT) /* define when building the library */ # define MSC_EXTRA __declspec(dllexport) # else # define MSC_EXTRA __declspec(dllimport) # endif #include <io.h> #define lseek _lseeki64 #define off_t __int64 #define stat __stat64 #define fstat _fstat64 #else #define MSC_EXTRA #endif /* defined(DLL_NETCDF) */ # define EXTERNL extern MSC_EXTRA /* When netCDF is built as a DLL, this will export ncerr and * ncopts. When it is used as a DLL, it will import them. */ #if defined(DLL_NETCDF) MSC_EXTRA int ncerr; MSC_EXTRA int ncopts; #endif > > I need the V2 interface for AIA ANDI, so I must have it. I see some > V2 stuff buried in the EXTERNL stuff, so dont want to just erase > from MSC_EXTRA on down. > > The netcdf.so for ROOT can be created and loaded, but then when > trying to load a C or C++ file to test it, the ROOT interpreter > warns of the undefined MSC_EXTRA and stops. > > I need to know how to make sure that all MSC_EXTRA and EXTERNL > things are not compiled. In non-DLL builds, MSC_EXTRA is defined to nothing, and EXTERNL to extern. Good luck. Ed -- Ed Hartnett -- ed@xxxxxxxxxxxxxxxx
http://www.unidata.ucar.edu/support/help/MailArchives/netcdf/msg04827.html
crawl-001
refinedweb
308
72.76
Updated December 21 for Xcode 6.1.1 The Swift feature of Access Control is really important from a software architecture perspective, because it allows us to properly implement encapsulation. Without the ability to hide members and methods of classes, it’s very easy to accidentally (or not) reach in to classes and mess with internals that were not designed to be directly modified. Swift offers three levels of access control: public, private, and internal. public makes the entities visible anywhere within the module, or from other modules (as long as the module is imported) internal makes the entities visible only within the same module. This is the default behavior in Swift. private makes the entities visible only within the same source file. To demonstrate Swift’s new access controls, let’s build a small math class for Swift. For now, it’ll be really simple. It’s a class that has two properties of type Double, and has a single computed property named sum. If you want to follow along, just create a single-view template project and add this in to an otherwise empty swift file called Math.swift import Foundation class QMath { var num1: Double? var num2: Double? var sum: Double { return num1! + num2! } init(_ num1: Double, _ num2: Double) { self.num1 = num1 self.num2 = num2 } } The class QMath has a constructor that takes two parameters, num1 and num2 of type Double. If you haven’t seen the underscores before, those are the external parameter names, which we’ve set to not be specified by using the underscore. If we instantiate a QMath instance in another class we can get the sum property and confirm it works as expected. If you’re following along, you insert this in to your applicationdidFinishLaunchingWithOptions: method inside of AppDelegate.swift var m = QMath(4, 50) println(m.sum) 54.0 You’ll notice that in our sum getter, we implicitly unwrap num1 and num2 using the exclamation mark (!). Although they’re both optionals, we can make this assumption if we know the init(,) method we’ve provided is called, because the arguments to that method are not optional and will definitely be set upon initialization. Except one minor problem: We could actually set either of those values to be nil. var m = QMath(4, 50) m.num1 = nil println(m.sum) This code compiles just fine, num1 is Optional and can be set to nil, not an issue. However, calling the sum getter now implicitly unwraps a nil optional. If you run this code you’ll see the following error: fatal error: unexpectedly found nil while unwrapping an Optional value We could simply set the num1 and num2 properties to not be optional, which would require we have a default value such as 0. But, an better approach that allows us to avoid the unnecessary initial value is to simply disallow modifications to these internal variables. We want this class to be a black box, where num1 and num2 can’t directly be modified. So, to solve our above mentioned issue, we can make the two number properties private. private var num1: Double? private var num2: Double? Attempting to build the app again now produces an error on the line we used to set num1 to nil. m.num1 = nil 'QMath' does not have a member named 'num1' Our external reference to the num1 property is no longer valid, it has no visibility to num1 and therefore this line of code is an error. There’s only one thing to do now, remove this line and start using the class as it was designed to be used! Mission accomplished! If you want to dive deeper and tinker with Swift, it’s a good idea to read my post on Running Swift Scripts From The Command Line. When you’re ready to get serious make sure to also learn about my upcoming Swift eBook and video tutorial series. Warning: Incoming opinion Good software design principles suggest everything should be private by default, and entities should be exposed deliberately on an as-needed basis. This makes it easier to write more modular code and leads to cleaner programming interfaces. Disagree? Yell at me about it on Twitter.
http://jamesonquave.com/blog/tag/beta-4/
CC-MAIN-2017-22
refinedweb
705
63.7
Bert Huijben wrote on Sat, Sep 26, 2015 at 10:06:15 +0200: > A few comments inline. > Thanks for the review. > > + /* ### This is currently not parsed out of "index" lines (where it > > + * ### serves as an assertion of the executability state, without > > + * ### changing it). */ > > + svn_tristate_t old_executable_p; > > + svn_tristate_t new_executable_p; > > } svn_patch_t; > > I'm not sure if we should leave this comment here in the long term... *shrug* We could put it elsewhere. > > +/* Return whether the svn:executable proppatch and the out-of-band > > + * executability metadata contradict each other, assuming both are present. > > + */ > > +static svn_boolean_t > > +contradictory_executability(const svn_patch_t *patch, > > + const prop_patch_target_t *target) > > +{ > > + switch (target->operation) > > + { > > + case svn_diff_op_added: > > + return patch->new_executable_p == svn_tristate_false; > > + > > + case svn_diff_op_deleted: > > + return patch->new_executable_p == svn_tristate_true; > > + > > + case svn_diff_op_unchanged: > > + /* ### Can this happen? */ > > + return (patch->old_executable_p != svn_tristate_unknown > > + && patch->new_executable_p != svn_tristate_unknown > > + && patch->old_executable_p != patch->new_executable_p); > > + > > + case svn_diff_op_modified: > > + /* Can't happen: the property should only ever be added or deleted, > > + * but never modified from one valid value to another. */ > > + return (patch->old_executable_p != svn_tristate_unknown > > + && patch->new_executable_p != svn_tristate_unknown > > + && patch->old_executable_p == patch->new_executable_p); > > These can happen when the svn:executable property just changes value (E.g. from '*' to 'x'). That should not happen, but it can. Right. So _if_ somebody had broken the "value is SVN_PROP_BOOLEAN_VALUE" invariant, _and_ generated a diff that contains a 'old mode 0755\n new mode 0755\n' sequence — which, although syntactically valid, wouldn't be output by any diff program — then they will get a false positive "Contradictory executability" hard error. The place to handle broken invariants is at the entry point, which for patches is parse-diff.c. Would make sense, then, for parse-diff.c to normalize the 'old value' and 'new value' of svn_prop_is_boolean() properties to SVN_PROP_BOOLEAN_VALUE, and for patch.c to canonicalize the ACTUAL/WORKING property value to SVN_PROP_BOOLEAN_VALUE before trying to apply the patch? (Example: if the property value in the wc is "yes", and the patch says 'change the property value from "sí" to unset', parse-diff.c will fold "yes" to "*", patch.c will fold "sí" to "*", and the patch will apply successfully.) > > +add_or_delete_single_line(svn_diff_hunk_t **hunk_out, > > + const char *line, > > + svn_patch_t *patch, > > + svn_boolean_t add, > > + apr_pool_t *result_pool, > > + apr_pool_t *scratch_pool) > > +{ > > + svn_diff_hunk_t *hunk = apr_palloc(result_pool, sizeof(*hunk)); > > As pcalloc() would be safer here... ... > > + hunk->leading_context = 0; > > + hunk->trailing_context = 0; > > As this patch forgets to set the new booleans added on trunk to signal no EOL markers here. > > You might need to set one of them to true though, as I think you are trying to add a property with no end of line. It's just a merge artifact. I'd rather just initialize the newly-added members and leave the non-initializing allocation so cc/valgrind can catch bugs. I'll initialize them to FALSE for now, to plug the uninitialized memory access. I'm not sure we need to change that to TRUE; see discussion under the patch_tests.py hunks, below. > > +/* Parse the 'old mode ' line of a git extended unidiff. */ > > +static svn_error_t * > > +git_old_mode(enum parse_state *new_state, char *line, svn_patch_t > > *patch, > > + apr_pool_t *result_pool, apr_pool_t *scratch_pool) > > +{ > > + SVN_ERR(parse_bits_into_executability(&patch->old_executable_p, > > + line + STRLEN_LITERAL("old mode "))); > > + > > +#ifdef SVN_DEBUG > > + /* If this assert trips, the "old mode" is neither ...644 nor ...755 . */ > > + SVN_ERR_ASSERT(patch->old_executable_p != svn_tristate_unknown); > > +#endif > > I don't think we should leave these enabled even in maintainer mode. > This will break abilities to apply diffs generated from other tools. The purpose of the warning is to alert us that there is a syntax we aren't handling. That's why it's for maintainers only. The assumption is that maintainers can switch to a release build if they run into this warning unexpectedly. I don't think we can convert this to a warning, can we? This API doesn't have a way to report warnings to its caller. > (Perhaps even from older Subversion versions as I think you recently > changed what Subversion generates itself on trunk) > You mean r1695384? Personally, I think rejecting pre-r1695384 patches is _good_, since thoes patches were simply invalid and would have gotten in the way of assigning a meaning to the 010000 bit in the future. If we ever find out that somebody is generating such patches, we can then relax our parser to accept them. > > +def patch_ambiguous_executability_contradiction(sbox): > > + """patch ambiguous svn:executable, bad""" > > + > > + sbox.build(read_only=True) > > + wc_dir = sbox.wc_dir > > + > > + unidiff_patch = ( > > + "Index: iota\n" > > + > > "=============================================================== > > ====\n" > > + "diff --git a/iota b/iota\n" > > + "old mode 100755\n" > > + "new mode 100644\n" > > + "Property changes on: iota\n" > > + "-------------------------------------------------------------------\n" > > + "Added: svn:executable\n" > > + "## -0,0 +1 ##\n" > > + "+*\n" > > + ) > > This specifies the addition of the svn:executable property with the non canonical "*\n" value. Is this really what you want to test? > I think the actual property set code will change it to the proper value, but I would say you need the " \ No newline at end of property" marker here. > > The generated patchfile doesn't need it, but it does need the boolean to note the same thing. > I don't understand. If the generated patchfile doesn't need the \ line, then that is a great reason not to have it here, so that we test parsing the output svn currently generates. In any case, patch_dir_properties() and patch_add_symlink() are written without a \ line. I'll make one of them use a \ line so both variants are tested. Cheers, Daniel Received on 2015-09-27 02:47:04 CEST This is an archived mail posted to the Subversion Dev mailing list.
https://svn.haxx.se/dev/archive-2015-09/0341.shtml
CC-MAIN-2021-25
refinedweb
892
55.13
Apache Spark Tutorial: ML with PySpark Apache Spark and Python for Big Data and Machine Learning Apache Spark is known as a fast, easy-to-use and general engine for big data processing that has built-in modules for streaming, SQL, Machine Learning (ML) and graph processing. This technology is an in-demand skill for data engineers, but also data scientists can benefit from learning Spark when doing Exploratory Data Analysis (EDA), feature extraction and, of course, ML. In this tutorial, you’ll interface Spark with Python through PySpark, the Spark Python API that exposes the Spark programming model to Python. More concretely, you’ll focus on If you're rather interested in using Spark with R, you should check out DataCamp’s free Introduction to Spark in R with sparklyr or download the PySpark SQL cheat sheet. Installing Apache Spark Installing Spark and getting it to work can be a challenge. In this section, you’ll cover some steps that will show you how to get it installed on your pc. First thing that you want to do is checking whether you meet the prerequisites. Spark is written in Scala Programming Language and runs on Java Virtual Machine (JVM) environment. That’s why you need to check if you have a Java Development Kit (JDK) installed. You do this because the JDK will provide you with one or more implementations of the JVM. Preferably, you want to pick the latest one, which, at the time of writing is the JDK8. Next, you’re reading to download Spark! Downloading pyspark with pip Then, you can download and install PySpark it with the help of pip. This is fairly easy and much like installing any other package. You just run the usual command and the heavy lifting gets done for you: $ pip install pyspark Alternatively, you can also go to the Spark download page. Keep the default options in the first three steps and you’ll find a downloadable link in step 4. Click on that link to download it. For this tutorial, you’ll download the 2.2.0 Spark Release and the “Pre-built for Apache Hadoop 2.7 and later” package type. Note that the download can take some time to finish! Downloading Spark with Homebrew You can also install Spark with the Homebrew, a free and open-source package manager. This is especially handy if you’re working with macOS. Simply run the following commands to search for Spark, to get more information and to finally install it on your personal computer: # Search for spark $ brew search spark # Get more information on apache-spark $ brew info apache-spark # Install apache-spark $ brew install apache-spark Download and Set Up Spark Next, make sure that you untar the directory that appears in your Downloads folder. This can happen automatically for you, by double clicking the spark-2.2.0-bin-hadoop2.7.tgz archive or by opening up your Terminal and running the following command: $ tar xvf spark-2.2.0-bin-hadoop2.7.tgz Next, move the untarred folder to /usr/local/spark by running the following line: $ mv spark-2.1.0-bin-hadoop2.7 /usr/local/spark Note that if you get an error that says that the permission is denied to move this folder to the new location, you should add sudo in front of this command. The line above will then become $ sudo mv spark-2.1.0-bin-hadoop2.7 /usr/local/spark. You’ll be prompted to give your password, which is usually the one that you also use to unlock your pc when you start it up :) Now that you’re all set to go, open the README file in the file path /usr/local/spark. You can do this by executing $ cd /usr/local/spark This will brings you to the folder that you need to be. Then, you can start inspecting the folder and reading the README file that is incuded in it. First, use $ ls to get a list of the files and folders that are in this spark folder. You’ll see that there’s a README.md file in there. You can open it by executing one of the following commands: # Open and edit the file $ nano README.md # Just read the file $ cat README.md Tip use the tab button on your keyboard to autocomplete as you’re typing the file name :) This will save you some time. You’ll see that this README provides you with some general information about Spark, online documentation, building Spark, the Interactive Scala and Python shells, example programs and much more. The thing that could interest you most here is the section on how to build Spark but note that this will only be particularly relevant if you haven’t downloaded a pre-built version. For this tutorial, however, you downloaded a pre-built version. You can press CTRL + X to exit the README, which brings you back to the spark folder. In case you selected a version that hasn’t been built yet, make sure you run the command that is listed in the README file. At the time of writing, this is the following: $ build/mvn -DskipTests clean package run Note that this command can take a while to run. PySpark Basics: RDDs Now that you’ve successfully installed Spark and PySpark, let’s first start off by exploring the interactive Spark Shell and by nailing down some of the basics that you will need when you want to get started. In the rest of this tutorial, however, you’ll work with PySpark in a Jupyter notebook. Spark Applications Versus Spark Shell The interactive shell is an example of a Read-Eval(uate)-Print-Loop (REPL) environment; That means that whatever you type in is read, evaluated and printed out to you so that you can continue your analysis. This might remind you of IPython, which is a powerful interactive Python shell that you might know from working with Jupyter. If you want to know more, consider reading DataCamp’s IPython or Jupyter blog post. This means that you can use the shell, which is available for Python as well as Scala, for all interactive work that you need to do. Besides this shell, you can also write and deploy Spark applications. In contrast to writing Spark applications, the SparkSession has already been created for you so that you can just start working and not waste valuable time on creating one. Now you might wonder: what is the SparkSession? Well, it’s the main entry point for Spark functionality: it represents the connection to a Spark cluster and you can use it to create RDDs and to broadcast variables on that cluster. When you’re working with Spark, everything starts and ends with this SparkSession. Note that before Spark 2.0.0, the three main connection objects were SparkContext, SqlContext and HiveContext. You’ll see more on this later on. For now, let’s just focus on the shell. The Python Spark Shell From within the spark folder located at /usr/local/spark, you can run $ ./bin/pyspark At first, you’ll see some text appearing. And then, you’ll see “Spark” appearing, just like this: Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 12:39:47) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin/07/26 11:41:26 WARN NativeCodeLoader: Unable to load native-hadoop library for your platform... using builtin-java classes where applicable 17/07/26 11:41:47 WARN ObjectStore: Failed to get database global_temp, returning NoSuchObjectException Welcome to ____ __ / __/__ ___ _____/ /__ _\ \/ _ \/ _ `/ __/ '_/ /__ / .__/\_,_/_/ /_/\_\ version 2.2.0 /_/ Using Python version 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016 12:39:47) SparkSession available as 'spark'. >>> When you see this, you know that you’re ready to start experimenting within the interactive shell! Tip: if you prefer using the IPython shell instead of the Spark shell, you can do this by setting the following environment variable: export PYSPARK_DRIVER_PYTHON="/usr/local/ipython/bin/ipython" Creating RDDs Now, let’s start small and make an RDD, which is the most basic building block of Spark. An RDD simply represents data but it’s not one object, a collection of records, a result set or a data set. That is because it’s intended for data that resides on multiple computers: a single RDD could be spread over thousands of Java Virtual Machines (JVMs), because Spark automatically partitions the data under the hood to get this parallelism. Of course, you can adjust the parallelism to get more partitions. That’s why an RDD is actually a collection of partitions. You can easily create a simple RDD by using the parallelize() function and by simply passing some data (an iterable, like a list, or a collection) to it: >>> rdd1 = spark.sparkContext.parallelize([('a',7),('a',2),('b',2)]) >>> rdd2 = spark.sparkContext.parallelize([("a",["x","y","z"]), ("b",["p", "r"])]) >>> rdd3 = spark.sparkContext.parallelize(range(100)) Note that the SparkSession object has the SparkContext object, which you can access with spark.sparkContext. For backwards compatibility reasons, it’s also still possible to call the SparkContext with sc, as in rdd1 = sc.parallelize(['a',7),('a',2),('b',2)]). RDD Operations Now that you have created the RDDs, you can use the distributed data in rdd1 and rdd2 to operate on in parallel. You have two types of operations: transformations and actions. Now, to intuitively get the difference between these two, consider some of the most common transformations are map(), filter(), flatMap(), sample(), randomSplit(), coalesce() and repartition() and some of the most common actions are reduce(), collect(), first(), take(), count(), saveAsHadoopFile(). Transformations are lazy operations on a RDD that create one or many new RDDs, while actions produce non-RDD values: they return a result set, a number, a file, … You can, for example, aggregate all the elements of rdd1 using the following, simple lambda function and return the results to the driver program: >>> rdd1.reduce(lambda a,b: a+b) Executing this line of code will give you the following result: ('a', 7, 'a', 2, 'b', 2). Another example of a transformation is flatMapValues(), which you run on key-value pair RDDs, such as rdd2. In this case, you pass each value in the key-value pair RDD rdd2 through a flatMap function without changing the keys, which is the lambda function defined below and you perform an action after that by collecting hte results with collect(). >>> rdd2.flatMapValues(lambda x: x).collect() [('a', 'x'), ('a', 'y'), ('a', 'z'), ('b', 'p'), ('b', 'r')] The Data Now that you have covered some basics with the interactive shell, it’s time to get started with some real data. For this tutorial, you’ll make use of the California Housing data set. Note, of course, that this is actually ‘small’ data and that using Spark in this context might be overkill; This tutorial is for educational purposes only and is meant to give you an idea of how you can use PySpark to build a machine learning model. Even though you know a bit more about your data, you should take the time to go ahead and explore it more thoroughly; Before you do this, however, you will set up your Jupyter Notebook with Spark and you’ll take some first steps to defining the SparkContext. PySpark in Jupyter Notebook For this part of the tutorial, you won’t use the ishell but you’ll build your own application. You’ll do this in a Jupyter Notebook. You already have all the things that you need installed, so you don’t need to do much to get PySpark to work in Jupyter. You can just launch the notebook application the same way like you always do, by running $ jupyter notebook. Then, you make a new notebook and you simply import the findspark library and use the init() function. In this case, you’re going to supply the path /usr/local/spark to init() because you’re certain that this is the path where you installed Spark. # Import findspark import findspark # Initialize and provide path findspark.init("/usr/local/spark") # Or use this alternative #findspark.init() Tip: if you have no idea whether your path is set correctly or where you have installed Spark on your pc, you can always use findspark.find() to automatically detect the location of where Spark is installed. If you’re looking for alternative ways to work with Spark in Jupyter, consult our Apache Spark in Python: Beginner’s Guide. Now that you have got all of that settled, you can finally start by creating your first Spark program! Creating Your First Spark Program What you first want to be doing is importing the SparkContext from the pyspark package and initializing it. Remember that you didn’t have to do this before because the interactive Spark shell automatically created and initialized it for you! Here, you’ll need to do a little bit more work yourself :) Import the SparkSession module from pyspark.sql and build a SparkSession with the builder() method. Afterwards, you can set the master URL to connect to, the application name, add some additional configuration like the executor memory and then lastly, use getOrCreate() to either get the current Spark session or to create one if there is none running. # Import SparkSession from pyspark.sql import SparkSession # Build the SparkSession spark = SparkSession.builder \ .master("local") \ .appName("Linear Regression Model") \ .config("spark.executor.memory", "1gb") \ .getOrCreate() sc = spark.sparkContext Note that if you get an error where there’s a FileNotFoundError similar to this one: “No such file or directory: ‘/User/YourName/Downloads/spark-2.1.0-bin-hadoop2.7/./bin/spark-submit’”, you know that you have to (re)set your Spark PATH. Go to your home directory by executing $ cd and then edit the .bash_profile file by running $ nano .bash_profile. Add something like the following to the bottom of the file export SPARK_HOME="/usr/local/spark/" Use CTRL + X to exit the file but make sure to save your adjustments by also entering Y to confirm the changes. Next, don’t forget to set the changes in motion by running source .bash_profile. Tip: you can also set additional environment variables if you want; You probably don’t need them, but it’s definitely good to know that you can set them if desired. Consider the following examples: # Set a fixed value for the hash seed secret export PYTHONHASHSEED=0 # Set an alternate Python executable export PYSPARK_PYTHON=/usr/local/ipython/bin/ipython # Augment the default search path for shared libraries export LD_LIBRARY_PATH=/usr/local/ipython/bin/ipython # Augment the default search path for private libraries export PYTHONPATH=$SPARK_HOME/python/lib/py4j-*-src.zip:$PYTHONPATH:$SPARK_HOME/python/ Note also that now you have initialized a default SparkSession. However, in most cases, you’ll want to configure this further. You’ll see that this will be really needed when you start working with big data. If you want to know more about it, check this page. This tutorial makes use of the California Housing data set. It appeared in a 1997 paper titled Sparse Spatial Autoregressions, written by Pace, R. Kelley and Ronald Barry and published in the Statistics and Probability Letters journal. The researchers built this data set by using the 1990 California census data. The data contains one row per census block group. A block group is the smallest geographical unit for which the U.S. Census Bureau publishes sample data (a block group typically has a population of 600 to 3,000 people). In this sample a block group on average includes 1425.5 individuals living in a geographically compact area. You’ll gather this information from this web page or by reading the paper which was mentioned above and which you can find here. These spatial data contain 20,640 observations on housing prices with 9 economic variables: - Longitude refers to the angular distance of a geographic place north or south of the earth’s equator for each block group; - Latitude refers to the angular distance of a geographic place east or west of the earth’s equator for each block group; - Housing median age is the median age of the people that belong to a block group. Note that the median is the value that lies at the midpoint of a frequency distribution of observed values; - Total rooms is the total number of rooms in the houses per block group; - Total bedrooms is the total number of bedrooms in the houses per block group; - Population is the number of inhabitants of a block group; - Households refers to units of houses and their occupants per block group; - Median income is used to register the median income of people that belong to a block group; And, - Median house value is the dependent variable and refers to the median house value per block group. What’s more, you also learn that all the block groups have zero entries for the independent and dependent variables have been excluded from the data. The Median house value is the dependent variable and will be assigned the role of the target variable in your ML model. You can download the data here. Look for the houses.zip folder, download and untar it so that you can access the data folders. Next, you’ll use the textFile() method to read in the data from the folder that you downloaded it to RDDs. This method takes an URI for the file, which is in this case the local path of your machine, and reads it as a collection of lines. For all convenience, you’ll not only read in the .data file, but also the .domain file that contains the header. This will allow you to double check the order of the variables. # Load in the data rdd = sc.textFile('/Users/yourName/Downloads/CaliforniaHousing/cal_housing.data') # Load in the header header = sc.textFile('/Users/yourName/Downloads/CaliforniaHousing/cal_housing.domain') Data Exploration You already gathered a lot of information by just looking at the web page where you found the data set, but it’s always better to get hands-on and inspect your data with the help of Spark with Python, in this case. Important to understand here is that, because Spark’s execution is “lazy” execution, nothing has been executed yet. Your data hasn’t been actually read in. The rdd and header variables are actually just concepts in your mind. You have to push Spark to work for you, so let’s use the collect() method to look at the header: header.collect() The collect() method brings the entire RDD to a single machine, and you’ll get to see the following result: [u'longitude: continuous.', u'latitude: continuous.', u'housingMedianAge: continuous. ', u'totalRooms: continuous. ', u'totalBedrooms: continuous. ', u'population: continuous. ', u'households: continuous. ', u'medianIncome: continuous. ', u'medianHouseValue: continuous. '] Tip: be careful when using collect()! Running this line of code can possibly cause the driver to run out of memory. That’s why the following approach with the take() method is a safer approach if you want to just print a few elements of the RDD. In general, it’s a good principle to limit your result set whenever possible, just like when you’re using SQL. You learn that the order of the variables is the same as the one that you saw above in the presentation of the data set, and you also learn that all columns should have continuous values. Let’s force Spark to do some more work and take a look at the California housing data to confirm this. Call the take() method on your RDD: rdd.take(2) By executing the previous line of code, you take the first 2 elements of the RDD. The result is as you expected: because you read in the files with the textFile() function, the lines are just all read in together. The entries are separated by a single comma and the rows themselves are also separated by a comma: [u'-122.230000,37.880000,41.000000,880.000000,129.000000,322.000000,126.000000,8.325200,452600.000000', u'-122.220000,37.860000,21.000000,7099.000000,1106.000000,2401.000000,1138.000000,8.301400,358500.000000'] You definitely need to solve this. Now, you don’t need to split the entries, but you definitely need to make sure that the rows of your data are separate elements. To solve this, you’ll use the map() function to which you pass a lambda function to split the line at the comma. Then, check your result by running the same line with the take() method, just like you did before: Remember that lambda functions are anonymous functions which are created at runtime. # Split lines on commas rdd = rdd.map(lambda line: line.split(",")) # Inspect the first 2 lines rdd.take(2) You’ll get the following result: [[u'-122.230000', u'37.880000', u'41.000000', u'880.000000', u'129.000000', u'322.000000', u'126.000000', u'8.325200', u'452600.000000'], [u'-122.220000', u'37.860000', u'21.000000', u'7099.000000', u'1106.000000', u'2401.000000', u'1138.000000', u'8.301400', u'358500.000000']] Alternatively, you can also use the following functions to inspect your data: # Inspect the first line rdd.first() # Take top elements rdd.top(2) If you’re used to working with Pandas or data frames in R, you’ll have probably also expected to see a header, but there is none. To make your life easier, you will move on from the RDD and convert it to a DataFrame. Dataframes are preferred over RDDs whenever you can use them. Especially when you’re working with Python, the performance of DataFrames is better than RDDs. But what is the difference between the two? You can use RDDs when you want to perform low-level transformations and actions on your unstructured data. This means that you don’t care about imposing a schema while processing or accessing the attributes by name or column. Tying in to what was said before about performance, by using RDDs, you don’t necessarily want the performance benefits that DataFrames can offer for (semi-) structured data. Use RDDs when you want to manipulate the data with functional programming constructs rather than domain specific expressions. To recapitulate, you’ll switch to DataFrames now to use high-level expressions, to perform SQL queries to explore your data further and to gain columnar access. So let’s do this. The first step is to make a SchemaRDD or an RDD of Row objects with a schema. This is normal, because just like a DataFrame, you eventually want to come to a situation where you have rows and columns. Each entry is linked to a row and a certain column and columns have data types. You’ll use the map() function again and another lambda function in which you’ll map each entry to a field in a Row. To make this more visual, consider this first line: [u'-122.230000', u'37.880000', u'41.000000', u'880.000000', u'129.000000', u'322.000000', u'126.000000', u'8.325200', u'452600.000000'] The lambda function says that you’re going to construct a row in a SchemaRDD and that the element at index 0 will have the name “longitude”, and so on. With this SchemaRDD in place, you can easily convert the RDD to a DataFrame with the toDF() method. # Import the necessary modules from pyspark.sql import Row # Map the RDD to a DF df = rdd.map(lambda line: Row(longitude=line[0], latitude=line[1], housingMedianAge=line[2], totalRooms=line[3], totalBedRooms=line[4], population=line[5], households=line[6], medianIncome=line[7], medianHouseValue=line[8])).toDF() Now that you have your DataFrame df, you can inspect it with the methods that you have also used before, namely first() and take(), but also with head() and show(): # Show the top 20 rows df.show() You’ll immediately see that this looks much different from the RDD that you were working with before: Tip: use df.columns to return the columns of your DataFrame. The data seems all nicely ordered into columns, but what about the data types? By reading in your data, Spark will try to infer a schema, but has this been successful here? Use either df.dtypes or df.printSchema() to get to know more about the data types that are contained within your DataFrame. # Print the data types of all `df` columns # df.dtypes # Print the schema of `df` df.printSchema() Because you don’t execute the first line of code, you will only get back the following result: root |-- households: string (nullable = true) |-- housingMedianAge: string (nullable = true) |-- latitude: string (nullable = true) |-- longitude: string (nullable = true) |-- medianHouseValue: string (nullable = true) |-- medianIncome: string (nullable = true) |-- population: string (nullable = true) |-- totalBedRooms: string (nullable = true) |-- totalRooms: string (nullable = true) All columns are still of data type string… That’s disappointing! If you want to continue with this DataFrame, you’ll need to rectify this situation and assign “better” or more accurate data types to all columns. Your performance will also benefit from this. Intuitively, you could go for a solution like the following, where you declare that each column of the DataFrame df should be cast to a FloatType(): from pyspark.sql.types import * df = df.withColumn("longitude", df["longitude"].cast(FloatType())) \ .withColumn("latitude", df["latitude"].cast(FloatType())) \ .withColumn("housingMedianAge",df["housingMedianAge"].cast(FloatType())) \ .withColumn("totalRooms", df["totalRooms"].cast(FloatType())) \ .withColumn("totalBedRooms", df["totalBedRooms"].cast(FloatType())) \ .withColumn("population", df["population"].cast(FloatType())) \ .withColumn("households", df["households"].cast(FloatType())) \ .withColumn("medianIncome", df["medianIncome"].cast(FloatType())) \ .withColumn("medianHouseValue", df["medianHouseValue"].cast(FloatType())) But these repeated calls are quite obscure, error-proof and don’t really look nice. Why don’t you write a function that can do all of this for you in a more clean way? The following User-Defined Function (UDF) takes a DataFrame, column names, and the new data type that you want the have the columns to have. You say that for every column name, you take the column and you cast it to a new data type. Then, you return the DataFrame: # Import all from `sql.types` from pyspark.sql.types import * # Write a custom function to convert the data type of DataFrame columns def convertColumn(df, names, newType): for name in names: df = df.withColumn(name, df[name].cast(newType)) return df # Assign all column names to `columns` columns = ['households', 'housingMedianAge', 'latitude', 'longitude', 'medianHouseValue', 'medianIncome', 'population', 'totalBedRooms', 'totalRooms'] # Conver the `df` columns to `FloatType()` df = convertColumn(df, columns, FloatType()) That already looks much better! You can quickly inspect the data types of df with the printSchema() method, just like you have done before. Now that you’ve got that all sorted out, it’s time to really get started on the data exploration. You have seen that columnar access and SQL queries were two advantages of using DataFrames. Well, now it’s time to dig a little bit further into that. Let’s start small and just select two columns from df of which you only want to see 10 rows: df.select('population','totalBedRooms').show(10) This query gives you the following result: +----------+-------------+ |population|totalBedRooms| +----------+-------------+ | 322.0| 129.0| | 2401.0| 1106.0| | 496.0| 190.0| | 558.0| 235.0| | 565.0| 280.0| | 413.0| 213.0| | 1094.0| 489.0| | 1157.0| 687.0| | 1206.0| 665.0| | 1551.0| 707.0| +----------+-------------+ only showing top 10 rows You can also make your queries more complex, as you see in the following example: df.groupBy("housingMedianAge").count().sort("housingMedianAge",ascending=False).show() Which gives you the following result: +----------------+-----+ |housingMedianAge|count| +----------------+-----+ | 52.0| 1273| | 51.0| 48| | 50.0| 136| | 49.0| 134| | 48.0| 177| | 47.0| 198| | 46.0| 245| | 45.0| 294| | 44.0| 356| | 43.0| 353| | 42.0| 368| | 41.0| 296| | 40.0| 304| | 39.0| 369| | 38.0| 394| | 37.0| 537| | 36.0| 862| | 35.0| 824| | 34.0| 689| | 33.0| 615| +----------------+-----+ only showing top 20 rows Besides querying, you can also choose to describe your data and get some summary statistics. This will most definitely help you after! df.describe().show() Look at the minimum and maximum values of all the (numerical) attributes. You see that multiple attributes have a wide range of values: you will need to normalize your dataset. Data Preprocessing With all this information that you gathered from your small exploratory data analysis, you know enough to preprocess your data to feed it to the model. - You shouldn’t care about missing values; all zero values have been excluded from the data set. - You should probably standardize your data, as you have seen that the range of minimum and maximum values is quite big. - There are possibbly some additional attributes that you could add, such as a feature that registers the number of bedrooms per room or the rooms per household. - Your dependent variable is also quite big; To make your life easier, you’ll have to adjust the values slightly. Preprocessing The Target Values First, let’s start with the medianHouseValue, your dependent variable. To facilitate your working with the target values, you will express the house values in units of 100,000. That means that a target such as 452600.000000 should become 4.526: # Import all from `sql.functions` from pyspark.sql.functions import * # Adjust the values of `medianHouseValue` df = df.withColumn("medianHouseValue", col("medianHouseValue")/100000) # Show the first 2 lines of `df` df.take(2) You can clearly see that the values have been adjusted correctly when you look at the result of the take() method: ), Row(households=1138.0, housingMedianAge=21.0, latitude=37.86000061035156, longitude=-122.22000122070312, medianHouseValue=3.585, medianIncome=8.301400184631348, population=2401.0, totalBedRooms=1106.0, totalRooms=7099.0)] Feature Engineering Now that you have adjusted the values in medianHouseValue, you can also add the additional variables that you read about above. You’re going to add the following columns to the data set: - Rooms per household which refers to the number of rooms in households per block group; - Population per household, which basically gives you an indication of how many people live in households per block group; And - Bedrooms per room which will give you an idea about how many rooms are bedrooms per block group; As you’re working with DataFrames, you can best use the select() method to select the columns that you’re going to be working with, namely totalRooms, households, and population. Additionally, you have to indicate that you’re working with columns by adding the col() function to your code. Otherwise, you won’t be able to do element-wise operations like the division that you have in mind for these three variables: # Import all from `sql.functions` if you haven't yet from pyspark.sql.functions import * # Divide `totalRooms` by `households` roomsPerHousehold = df.select(col("totalRooms")/col("households")) # Divide `population` by `households` populationPerHousehold = df.select(col("population")/col("households")) # Divide `totalBedRooms` by `totalRooms` bedroomsPerRoom = df.select(col("totalBedRooms")/col("totalRooms")) # Add the new columns to `df` df = df.withColumn("roomsPerHousehold", col("totalRooms")/col("households")) \ .withColumn("populationPerHousehold", col("population")/col("households")) \ .withColumn("bedroomsPerRoom", col("totalBedRooms")/col("totalRooms")) # Inspect the result df.first() You see that, for the first row, there are about 6.98 rooms per household, the households in the block group consist of about 2.5 people and the amount of bedrooms is quite low with 0.14:, roomsPerHousehold=6.984126984126984, populationPerHousehold=2.5555555555555554, bedroomsPerRoom=0.14659090909090908) Next, -and this is already forseeing an issue that you might have when you’ll standardize the values in your data set- you’ll also re-order the values. Since you don’t want to necessarily standardize your target values, you’ll want to make sure to isolate those in your data set. In this case, you’ll need to do this by using the select() method and passing the column names in the order that is more appropriate. In this case, the target variable medianHouseValue is put first, so that it won’t be affected by the standardization. Note also that this is the time to leave out variables that you might not want to consider in your analysis. In this case, let’s leave out variables such as longitude, latitude, housingMedianAge and totalRooms. # Re-order and select columns df = df.select("medianHouseValue", "totalBedRooms", "population", "households", "medianIncome", "roomsPerHousehold", "populationPerHousehold", "bedroomsPerRoom") Standardization Now that you have re-ordered the data, you’re ready to normalize the data. Or almost, at least. There is just one more step that you need to go through: separating the features from the target variable. In essence, this boils down to isolating the first column in your DataFrame from the rest of the columns. In this case, you’ll use the map() function that you use with RDDs to perform this action. You also see that you make use of the DenseVector() function. A dense vector is a local vector that is backed by a double array that represents its entry values. In other words, it's used to store arrays of values for use in PySpark. Next, you go back to making a DataFrame out of the input_data and you re-label the columns by passing a list as a second argument. This list consists of the column names "label" and "features": # Import `DenseVector` from pyspark.ml.linalg import DenseVector # Define the `input_data` input_data = df.rdd.map(lambda x: (x[0], DenseVector(x[1:]))) # Replace `df` with the new DataFrame df = spark.createDataFrame(input_data, ["label", "features"]) Next, you can finally scale the data. You can use Spark ML to do this: this library will make machine learning on big data scalable and easy. You’ll find tools such as ML algorithms and everything you need to build practical ML pipelines. In this case, you don’t need to do that much preprocessing so a pipeline would maybe be overkill, but if you want to look into it, definitely consider visiting the this page. The input columns are the features, and the output column with the rescaled that will be included in the scaled_df will be named "features_scaled": # Import `StandardScaler` from pyspark.ml.feature import StandardScaler # Initialize the `standardScaler` standardScaler = StandardScaler(inputCol="features", outputCol="features_scaled") # Fit the DataFrame to the scaler scaler = standardScaler.fit(df) # Transform the data in `df` with the scaler scaled_df = scaler.transform(df) # Inspect the result scaled_df.take(2) Let’s take a look at your DataFrame and the result. You see that, indeed, a third column features_scaled was added to your DataFrame, which you can use to compare with features: [Row(label=4.526, features=DenseVector([129.0, 322.0, 126.0, 8.3252, 6.9841, 2.5556, 0.1466]), features_scaled=DenseVector([0.3062, 0.2843, 0.3296, 4.3821, 2.8228, 0.2461, 2.5264])), Row(label=3.585, features=DenseVector([1106.0, 2401.0, 1138.0, 8.3014, 6.2381, 2.1098, 0.1558]), features_scaled=DenseVector([2.6255, 2.1202, 2.9765, 4.3696, 2.5213, 0.2031, 2.6851]))] Note that these lines of code are very similar to what you would be doing in Scikit-Learn. Building A Machine Learning Model With Spark ML With all the preprocessing done, it’s finally time to start building your Linear Regression model! Just like always, you first need to split the data into training and test sets. Luckily, this is no issue with the randomSplit() method: # Split the data into train and test sets train_data, test_data = scaled_df.randomSplit([.8,.2],seed=1234) You pass in a list with two numbers that represent the size that you want your training and test sets to have and a seed, which is needed for reproducibility reasons. If you want to know more about this, consider DataCamp’s Python Machine Learning Tutorial. Then, without further ado, you can make your model! Note that the argument elasticNetParam corresponds to α or the vertical intercept and that the regParam or the regularization paramater corresponds to λ. Go here for more information. # Import `LinearRegression` from pyspark.ml.regression import LinearRegression # Initialize `lr` lr = LinearRegression(labelCol="label", maxIter=10, regParam=0.3, elasticNetParam=0.8) # Fit the data to the model linearModel = lr.fit(train_data) With your model in place, you can generate predictions for your test data: use the transform() method to predict the labels for your test_data. Then, you can use RDD operations to extract the predictions as well as the true labels from the DataFrame and zip these two values together in a list called predictionAndLabel. Lastly, you can then inspect the predicted and real values by simply accessing the list with square brackets []: # Generate predictions predicted = linearModel.transform(test_data) # Extract the predictions and the "known" correct labels predictions = predicted.select("prediction").rdd.map(lambda x: x[0]) labels = predicted.select("label").rdd.map(lambda x: x[0]) # Zip `predictions` and `labels` into a list predictionAndLabel = predictions.zip(labels).collect() # Print out first 5 instances of `predictionAndLabel` predictionAndLabel[:5] You’ll see the following real and predicted values (in that order): [(1.4491508524918457, 0.14999), (1.5705029404692372, 0.14999), (2.148727956912464, 0.14999), (1.5831547768979277, 0.344), (1.5182107797955968, 0.398)] Evaluating the Model Looking at predicted values is one thing, but another and better thing is looking at some metrics to get a better idea of how good your model actually is. You can first start by printing out the coefficients and the intercept of the model: # Coefficients for the model linearModel.coefficients # Intercept for the model linearModel.intercept Which gives you the following result: # The coefficients [0.0,0.0,0.0,0.276239709215,0.0,0.0,0.0] # The intercept 0.990399577462 Next, you can also use the summary attribute to pull up the rootMeanSquaredError and the r2: # Get the RMSE linearModel.summary.rootMeanSquaredError # Get the R2 linearModel.summary.r2 The RMSE measures how much error there is between two datasets comparing a predicted value and an observed or known value. The smaller an RMSE value, the closer predicted and observed values are. The R2 (“R squared”) or the coefficient of determination is a measure that shows how close the data are to the fitted regression line. This score will always be between 0 and a 100% (or 0 to 1 in this case), where 0% indicates that the model explains none of the variability of the response data around its mean, and 100% indicates the opposite: it explains all the variability. That means that, in general, the higher the R-squared, the better the model fits your data. You'll get back the following result: # RMSE 0.8692118678997669 # R2 0.4240895287218379 There's definitely some improvements needed to your model! If you want to continue with this model, you can play around with the parameters that you passed to your model, the variables that you included in your original DataFrame, .... But this is where the tutorial ends for now! Before You Go… Before you go, make sure to stop the SparkSession with the following line of code: spark.stop() Taking Big Data Further Congrats! You have made it to the end of this tutorial, where you learned how to make a linear regression model with the help of Spark ML. If you would be interested in a machine learning with Python, consider taking DataCamp’s Supervised Learning with scikit-learn or the Unsupervised Learning in Python course.
https://www.datacamp.com/community/tutorials/apache-spark-tutorial-machine-learning?utm_campaign=Revue%20newsletter&utm_medium=Newsletter&utm_source=SF%20Data%20Weekly
CC-MAIN-2018-34
refinedweb
6,628
62.88
extend the tinyscheme types in a way similar to the "memblock" example. I call the type T_OPAQUE, and it's used for objects allocated using C++'s new mechanism. So my mk_opaque looks like: pointer mk_opaque(scheme *sc, int len, void * data) { pointer x = get_cell(sc, sc->NIL, sc->NIL); typeflag(x) = (T_OPAQUE | T_ATOM); strvalue(x) = (char *) data; strlength(x) = len; return (x); } where the data is from a C++ "new" call. The idea is that the scheme code can call C++ to get or handle an opaque object. I include a clause in the finalize_cell for this type, which calls free on the strvalue. This also prints a msg so I know when it's getting gc'd. I'm doing this to generate and use llvm objects from scheme. So the code might look like: (define *module* (module-new "module_name")) and module-new would be defined as: pointer module_new(scheme * scm, pointer args){ Module * mod = new Module(string_value(pair_car(args)), getGlobalContext()); return mk_opaque(scm, sizeof(Module), (void *)mod); } Once I define a few of these (at the top level) and start using them, it looks like the they're getting gc'd, even though they are still reachable. Any advice on how to track down the problem? I'm using v1.40 on 64-bit Ubuntu, and I believe all the #defines were left unchanged. Wayne I agree to receive quotes, newsletters and other information from sourceforge.net and its partners regarding IT services and products. I understand that I can withdraw my consent at any time. Please refer to our Privacy Policy or Contact Us for more details
https://sourceforge.net/p/tinyscheme/mailman/tinyscheme-issues/?viewmonth=201207
CC-MAIN-2016-36
refinedweb
271
71.85
import "barista.run/pango/icons" Package icons provides an interface for using icon fonts in a bar. To use an icon font: - Clone a supported repository - Link the ttf into ~/.fonts - Load the icon by passing it the path to the repo - Use icons as pango constructs in your bar Compatible icon fonts: - Material Design Icons (+community fork) - FontAwesome - Typicons Example usage: material.Load("/Users/me/Github/google/material-design-icons") ... return pango.Icon("material-today").Color(colors.Hex("#ddd")). Append(pango.Text(now.Sprintf("%H:%M"))) SymbolFromHex parses a hex string (e.g. "1F44D") and converts it to a string (e.g. "👍"). Provider provides pango nodes for icons NewProvider creates a new icon provider with the given name, registers it with pango.Icon, and returns it so that an appropriate Load method can be used. AddStyle sets additional styles on all returned pango nodes. Font sets the font set on the returned pango nodes. Hex adds a symbol to the provider where the value is given in hex-encoded form. Symbol adds a symbol to the provider where the value is the symbol/string to use for the icon. Package icons imports 2 packages (graph) and is imported by 4 packages. Updated 2019-09-23. Refresh now. Tools for package owners.
https://godoc.org/barista.run/pango/icons
CC-MAIN-2020-05
refinedweb
212
57.37
As a developer there was one language that I could not stand programming to. That would be the Java language. One of the things I have always liked about Windows XP and even Mac OS X are the visual IDE tools that are available. They make designing the interface easy and really hassle free. Even the QT toolkit and GTK offer interface builders. I must say I am a bigger fan of .NET and Mono. The Java language offered Swing and even then it remained a hassle. There are several IDE’s for developing Java code Eclipse, my personal favorite being Eclipse when I have to develop Java apps and C++, and Netbeans. So it really pleased me when Sun came out with the Java Studio Creator. I downloaded the technical preview edition and I must say that I am very, very pleased with this product. Installation Installation is very simple indeed it comes in the standard Installshield format and it installs the Java Studio Creator, a version of Suns app server and the Pointbase database server. It gave no hassles and went very smoothly. Manual configuration of the Database server and application server were not a big deal either. If you are interested in getting the Java Studio Creator it is located at Suns site. The link is provided in the references section. It is a very heavy download, over 100 megs on all the platforms so it is my suggestion top have broadband of some kind Interface The interface is a very clean interface. Its a very well built interface with the most common tools available by default. This designer is heavily similar to the Visual Studios interface. You have the layout section, Pallete tool section with commonly used Widgets split into the following sections, User defined, JSF Standard Components, and JSF Validators are available in a tools box similar to Visual Studios, there is a properties tool box where you can set how certain elements should look and a Server navigator tool box. Users migrating over from Visual Studios should have very little trouble migrating over to this tool and it should seem very common to them. The interface is common among the platforms meaning the interface is the same whether on Windows, Linux or Solaris. It has a section where the design layout can be viewed and the source can be viewed. It also offers the function that when you double click on an element the source section for that element will be available to edit. As I stated, you can tell where the inspiration came from. Performance This is where the Java Studio Creator lacked the most. Functionality on the one hand was great. It is a fully functional application. Speed was lacking on some Linux platforms. SuSE ran moderately well but compilation was very slow. It took 7 minutes 3 seconds to compile and test my code, Fedora Core 2 wouldnt even run Java Studio Creator it kept hanging on the startup screen. Debian, Slackware and Xandros were the best performers on the Linux side. Compilation and deployment took 5 minutes 15 seconds on Debian and Xandros, Slackware took 5 minutes 32 seconds. Windows XP Professional won hands down in speed for compilation and testing at 4 minutes 11 seconds and Solaris was second place with 4 minutes 20 seconds. All the tests were run on the same hardware configuration except for the Solaris version which requires a Sparc. What is there to like The interface is easy enough to where a novice could actaully put something together. Deployment of developed apps is simple. Applications developed with the Java Studio creator look native to the OS you are running on meaning that if you use Windows XP you will have Luna style buttons and dialogs, if you use Keramik on Linux with KDE same thing if you use the browser Konqueror, Aqua on Mac OS X etc.. What I didnt like Speed, as I stated it was slow on some platforms and it takes awhile to start up. Its a resource hog but mostly on the UNIX based Operating Systems which in my opinion is very odd considering Sun is a UNIX development house with both Solaris and Linux and they should optimize it for those platforms, Windows was the winner in speed in this case. Where oh where is my Solaris x86 version, I have 4 Sun SPARC workstations at work with 19 Solaris 9 x86 installs. I would like my Solaris x86 users to be able to use the tool on their own platform. App server will sometimes just quit and you have to restart. Trying to tie some of the elements into my Oracle 9i databases that we use on Windows Server 2003 was being very uncooperative. These are annoyances that I hope that will be fixed in the final version. Would Java Studio Creator make me switch to Java? No, we do deploy some Java apps in my business but this is to mostly benefit the Linux users. If you are already a hardcore Java fan and you program in Java then this tool is for you and its a giant step forward in Java development. Java Studio Creator definately makes Java an attractive contender for those who are looking to switch to Java. But for people like myself who love C# and other development languages, this is not a die for tool. I do think among the Java Community we will see a huge acceptance and among new users an equally high adoption. If Sun corrects many of the faults that I mentioned and produce a Solarix x86 version this will undobtedly make Java Studio Creator better. References Java Studio Creator Home Page Java Studio Creator download page. because of this memory requirement i am forced to shy away from this product. I guess the obvious question is how well does it compare with Eclipse? Are there any third-party tools available like there are plugins for Eclipse? Native look & interface is always welcome, but can it use non-java shared libraries from other installed resources on the system? (yes, I know about the cross-platform stuff, but in order to compete with with .Net, this may be a useful functionality) It’s been around for ages and it does a pretty good job of GUI creation. One thing I noticed in the screenshots though is that it seems to allow you to create web-applications graphically. Does it have some sort of wysiwyg HTML editor built in? “If Sun (…) produce a Solarix x86 version this will undobtedly make Java Studio Creator better.” uh ? I would like to know what relation there is between a new port and a technically better product for existing ports. really. Roberto, would you mind sharing what company you work for so that we may put your review in context? I am sure many others would also like to hear about this company of yours that has such an interesting mix of development environments. I would also like to hear about specific software products that you yourself have developed and what tools you have used to develop them.Are any of them opensource? If so, could you point us to your contributions? I am sure I am not alone in wanting to see the productivity gains that you claim from C# and just the general quality of your code. Looking forward to your answers. is this a suppurted and packaged netbeans? >> One thing I noticed in the screenshots though is that it seems to allow you to create web-applications graphically. Does it have some sort of wysiwyg HTML editor built in? I noticed that too. When I went to the Studio Creator website I found this: Studio Creator is a development tool for building multitier, distributed web applications that are based on 100 percent Java technology standards. The way this preview is written, it seems the author is under the impression that it is a regular RAD tool. Studio Creator is only for creating web applications. Either the author didn’t notice or didn’t think it was worth mentioning, either way, it isn’t good. It probably is. Sun provides NetBeans as their IDE so it would only be logical that this suite uses NetBeans and that Suns Studio Creator means: NetBeans + extra modules. Just like Eclipse versus WebSphere Developer Studio (Eclipse + commercial plugins). He mentioned the apps have a native look-and-feel. Does this mean Sun is now using SWT?? Or some spiced-up version of Swing? M. You don’t have to loop , first line will suffice leaving in in prompt again (you know that OK ). If you let it like that I’m affraid you have to use BREAK key or whatever the name was to exit your program. Neverthless,that made me remember a nice thing from UGH book,although I have see these before reading this book: High school/Junior high 10 PRINT “HELLO WORLD” 20 END First year in college program Hello(input, output); begin writeln (‘Hello world’); end. Senior year in college (defun hello () (print (list ‘HELLO ‘WORLD))) New professional #include <stdio.h> main (argc,argv) int argc; char **argv; { printf (“Hello World! “); } Seasoned pro #include <stream.h> const int MAXLEN = 80; class outstring; class outstring { private: int size; char str[MAXLEN]; public: outstring() { size=0; } ~outstring() {size=0;} void print(); void assign(char *chrs); }; void outstring::print() { int i; for (i=0 ; i< size ; i++) cout << str[i]; cout << ” “; } void outstring::assign(char *chrs) { int i; for (i=0; chrs[i] != ‘
https://www.osnews.com/story/7459/preview-of-sun-java-studio-creator/
CC-MAIN-2021-21
refinedweb
1,598
70.94
googleearth-7.1.1.1888 is no longer the version of the deb file on Google's servers. dpkg --info says "Version: 7.1.2.2041-r0" Reproducible: Always crashes for me immediately, even after removing the whole ~/.googleearth config folder (In reply to Julian Ospald (hasufell) from comment #1) > crashes for me immediately, even after removing the whole ~/.googleearth > config folder So, I guess we shouldn't add this ebuild? And just wait for the next version? (In reply to Eric Siegel from comment #2) > (In reply to Julian Ospald (hasufell) from comment #1) > > crashes for me immediately, even after removing the whole ~/.googleearth > > config folder > > So, I guess we shouldn't add this ebuild? And just wait for the next > version? I don't add broken software to the tree. If you can make it work, let me know. googleearth-7.1.2.2041 works for me on amd64 with r600-radeon (mesa) renamed epatch "${FILESDIR}"/${PN}-${PV%.*}.1871-desktopfile.patch to epatch "${FILESDIR}"/${PN}-7.1.1.1871-desktopfile.patch in ebuild, and the patch applied i starting googleearth from xbmc Worked for me as well, but I had to discard my old .googleearth directory. I make the corrections to the ebuild Michael Lange suggested in the previous message. I'm running ~AMD64 using the latest nvidia-drivers. Correcting what I said earlier...it doesn't crash, but it is not even attempting to render landscape. So it really isn't working for me. Another crash happened while handling crash! did any1 have more luck? (In reply to Julian Ospald (hasufell) from comment #8) > did any1 have more luck? It is possible to run Google Earth 7.1/amd64 (checked with 7.1.2/2041) on Gentoo, using the native system QT libraries instead of the bundled one. This solves most of the crash problems and also the Panoramio empty frames problem, and is pretty stable (but see the comments at the end). It also results in a great performance of GE, maybe because the bundled QT libraries are compiled for "generic" architecture instead of amd64. <Historical_reference> For Fedora 19 I posted a similar solution, see . There can still be problems probably related to 3D handling in some display drivers. I didn't encounter such a problem myself, using the proprietary Nvidia driver on Fedora 19. However in my tests I could consistently crash the 3D driver of VirtualBox 4.3.4. In other distributions the native libraries are still not up to date with the latest patches, especially the one that fixes the crash on search, so this method doesn't work well on them - this includes openSUSE 13.1, Ubuntu 13.10 (and also 14.04 in its current state), Debian (including testing and unstable), Mageia 3 (and the current state of 4), AltLinux 7.0.1 and latest ArchLinux. Several months ago I posted in GE's group on productforums.google.com a solution for the frequent crashes and blank Panoramio frames for GE 7.1.1/7.1.2 x86_64, based on a recompilation of the QT libraries with patches from Fedora's QT library packages. I also recompiled these libraries for openSUSE, AltLinux, and Mageia. A Gentoo user reported on productforums.google.com that my recompiled libraries for openSUSE work on Gentoo, but I didn't test this myself. </Historical_reference> The Gentoo native Qt library solution ------------------------------------- I tested the following solution on an up to date Gentoo system with Gnome 3, running on QEMU/KVM. I didn't test it on Gentoo/KDE, but I know from my tests on other distributions that currently the Panoramio frames misbehave on KDE (a workaround is possible, and I'm going to check this issue further). As you may know (also appears in TODO in GE's ebuild), if you try to use the system QT libraries, you get the error: ./googleearth-bin: symbol lookup error: ./libbase.so: undefined symbol: _Z34QBasicAtomicInt_fetchAndAddOrderedPVii I didn't test this solution on 32bit installations. I don't even know if it is needed there. 1. You need the following up to date packages installed in your system: 1A. media-libs/freeimage (currently 3.15.3-r2) 1B. dev-qt/qtcore (currently 4.8.5) 1C. dev-qt/qtgui (currently 4.8.5-r1) 1D. dev-qt/qtwebkit (currently 4.8.5) 2. Install the 7.1 x86_64 package from Google's download site (currently 7.1.2.2041). To that end I modified the ebuild of 7.1.1.1888 and emerged it. 3. In GE's running directory /opt/gopogleeaerth, remove the 4 original libQt* libraries: cd /opt/googleearth mkdir bundled-qtlib mv libQt* bundled-qtlib/ Similarly you can remove plugins/imageformats/*, but anyway they are not going to be used. 4. If you invoke googleearth now, you will get the known error: ./googleearth-bin: symbol lookup error: ./libbase.so: undefined symbol: _Z34QBasicAtomicInt_fetchAndAddOrderedPVii The missing function can be generated as follows: 4A. Create a file (I called it baifaao.cpp) with this content: /* amirpli 2013/11/28 */ #include <QtCore/QAtomicInt> extern "C" { int _Z34QBasicAtomicInt_fetchAndAddOrderedPVii(QAtomicInt* a, int b) { return a->fetchAndAddOrdered(b); } } 4B. Compile it and create the shim library with: gcc -I/usr/include/qt4 -O3 -fPIC --shared baifaao.cpp -o baifaao.so Put baifaao.so in the directory /opt/googleearth . 5. In the file googleearth (in the directory /opt/googleearth), add the following line, e.g. before the line starting with LD_LIBRARY_PATH: export LD_PRELOAD=/usr/lib64/libfreeimage.so.3:/opt/googleearth/baifaao.so 6. I didn't test if the locale bug in the QT libs is patched (may cause a major coordinate shift if the locate is not en_US.UTF-8). If it is still present with your locale, add also: export LC_NUMERIC=en_US.UTF-8 Enjoy! 1. Don't try to invoke googleearth as superuser (unless this is a login / su -l, but there is no point in that anyway). Else the files GE writes in your home directory may get owned by root, and GE will then malfunction when you invoke it from your user. 2. If you had a previous installation of GE, and now encounter a problem like no Panoramio icons, clear GE's cache. 3. The library preload happens also for programs invoked from GE (e.g. if you use the external browser option). I didn't encounter a real problem in that, but if needed it can be prevented by using a relative path for the preloaded libraries. 4. I didn't check here using the flash plugin for the YouTube layer. But I guess almost no one uses this layer now since Google removed it from the menu and the gallery. 5. Clicking on Tools->Options->3D Font->Fotns->Choose 3D Font still crashes GE. 6. There are still QtWebKit related crashes when clicking on pictures in "Places" icones (camera and square-inside-square icones) using the internal browser. Thanks to amirpli it works for me. For over 6 mo. on & off have tried to solve the panaramio problem, I know the thread he speaks of by rote, including the Gentoo users' comment. Didn't work for me, I believe it was my fault. Anyhow, following the above steps religiously did work, panaramio now works great, GE flies, just about everything except 3d fonts in options as he states. One caveat here in case it helps someone, I was using eselect qtgraphicssystem opengl and had weird graphic glitches after the changes. Finally I reset it to native, rebooted and now all perfect, in fact, that setting was causing me unrelated problems elsewhere that I was blaming "something in gtk" for. This is on a nvidia go7600 with proprietary drivers, ~amd64. And it fixed panoramio on my ~x86 machine as well! Of course had to change line in step 5 to lib from lib64, otherwise all good. That machine has an Intel GPU, so I knew long ago it wasn't a video driver issue. That machine also has the same troubles with the qt opengl driver, but that's a whole different bug report. I added an updated version to the tree. It works for me. At least it starts and I can see the earth ;) Is this version ok for you? I think USE=-bundled-libs may cause some problems though It started the first time I tried, but it had a lot of spots/artifacts that looked like it was sprayed with semi-transparent black paint. Not sure if those spots were there from the start, but I noticed them after getting into street view (and they remained afterwards). I changed a setting, I think it was something about the graphics mode (changing to safe mode), and it asked me to restart the program. After closing it and trying to start it again, it crashes every time: [0301/195829:ERROR:net_util.cc(2195)] Not implemented reached in bool net::HaveOnlyLoopbackAddresses() [0301/195829:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler. (repeated about 20 times) [0301/195829:ERROR:nss_ocsp.cc(581)] No URLRequestContext for OCSP handler. Another crash happened while handling crash! Version details: sci-geosciences/googleearth-7.1.2.2041 with USE="bundled-libs", on amd64. Is there something I need to change? Does the ebuild include amirpli's fixes? Update: after renaming the ~/.googleearth/Cache folder, I was able to run it once. Dark spots are still there. When I tried to restart it, it crashed again. Any updates here? All I can say is that it works for me... :-/ have you tried to disable/close the appearing window when it is starting up? I experienced a crash on startup, but when I immediately close this "Tips&Tricks" windows on startup it does not crash. (In reply to Marc Schiffbauer from comment #15) > have you tried to disable/close the appearing window when it is starting up? > I experienced a crash on startup, but when I immediately close this > "Tips&Tricks" windows on startup it does not crash. Ok, it seems to stop crashing after disabling that. I still get the spots though.
https://bugs.gentoo.org/show_bug.cgi?id=490066
CC-MAIN-2021-39
refinedweb
1,679
67.35
#include <hallo.h> * Josselin Mouette [Wed, Jul 23 2003, 06:06:18PM]: > Le mer 23/07/2003 ? 17:57, Martin Pitt a ?crit : > > Besides, what's so bad with the current boot-floppies that they could > > not be used for another release? Most people will do a mere > > dist-upgrade anyway, and b-f are thoroughly tested. But this certainly > > is another issue... > > Are you willing to maintain them ? Nobody else is. WTF did you do for debian-boot to make this statement look competent in any way? I don't know what the problem should be - we need just few more motivated people with non-i386 hardware to make them ready for Sarge. MfG, Eduard. -- <Alfie> Ja, das ist ja das Problem. Viele Leute glauben einen Menschen nach dem
https://lists.debian.org/debian-devel/2003/07/msg01828.html
CC-MAIN-2017-39
refinedweb
130
77.64
In-app purchases and trials The Windows SDK provides APIs you can use to implement the following features to make more money from your Universal Windows Platform (UWP) app: In-app purchases Whether your app is free or not, you can sell content or new app functionality (such as unlocking the next level of a game) from right within the app. Trial functionality If you configure your app as a free trial in Partner Center, you can entice your customers to purchase the full version of your app by excluding or limiting some features during the trial period. You can also enable features, such as banners or watermarks, that are shown only during the trial, before a customer buys your app. This article provides an overview of how in-app purchases and trials work in UWP apps. Choose which namespace to use There are two different namespaces you can use to add in-app purchases and trial functionality to your UWP apps, depending on which version of Windows 10 your apps target. Although the APIs in these namespaces serve the same goals, they are designed quite differently, and code is not compatible between the two APIs. Windows.Services.Store Starting in Windows 10, version 1607, apps can use the API in this namespace to implement in-app purchases and trials. We recommend that you use the members in this namespace if your app project targets Windows 10 Anniversary Edition (10.0; Build 14393) or a later release in Visual Studio. This namespace supports the latest add-on types, such as Store-managed consumable add-ons, and is designed to be compatible with future types of products and features supported by Partner Center and the Store. For more information about this namespace, see the In-app purchases and trials using the Windows.Services.Store namespace section in this article. Windows.ApplicationModel.Store All versions of Windows 10 also support an older API for in-app purchases and trials in this namespace. For information about the Windows.ApplicationModel.Store namespace, see In-app purchases and trials using the Windows.ApplicationModel.Store namespace. Important The Windows.ApplicationModel.Store namespace is no longer being updated with new features, and we recommend that you use the Windows.Services.Store namespace instead if possible for your app. The Windows.ApplicationModel.Store namespace is not supported in Windows desktop applications that use the Desktop Bridge or in apps or games that use a development sandbox in Partner Center (for example, this is the case for any game that integrates with Xbox Live). Basic concepts Every item that is offered in the Store is generally called a product. Most developers only work with the following types of products: apps and add-ons. An add-on is a product or feature that you make available to your customers in the context of your app: for example, currency to be used in an app or game, new maps or weapons for a game, the ability to use your app without ads, or digital content such as music or videos for apps that have the ability to offer that type of content. Every app and add-on has an associated license that indicates whether the user is entitled to use the app or add-on. If the user is entitled to use the app or add-on as a trial, the license also provides additional info about the trial. To offer an add-on to customers in your app, you must define the add-on for your app in Partner Center so the Store knows about it. Then, your app can use APIs in the Windows.Services.Store or Windows.ApplicationModel.Store namespace to offer the add-on for sale to the user as an in-app purchase. UWP apps can offer the following types of add-ons. Note Other types of add-ons, such as durable add-ons with packages (also known as downloadable content or DLC) are only available to a restricted set of developers, and are not covered in this documentation. In-app purchases and trials using the Windows.Services.Store namespace This section provides an overview of important tasks and concepts for the Windows.Services.Store namespace. This namespace is available only to apps that target Windows 10 Anniversary Edition (10.0; Build 14393) or a later release in Visual Studio (this corresponds to Windows 10, version 1607). We recommend that apps use the Windows.Services.Store namespace instead of the Windows.ApplicationModel.Store namespace if possible. For information about the Windows.ApplicationModel.Store namespace, see this article. In this section - Video - Implement in-app purchases - Implement trial functionality - Test your in-app purchase or trial implementation - Receipts for in-app purchases - Using the StoreContext class with the Desktop Bridge - Products, SKUs, and availabilities - Store IDs Video Watch the following video for an overview of how to implement in-app purchases in your app using the Windows.Services.Store namespace. The main entry point to the Windows.Services.Store namespace is the StoreContext class. This class provides methods you can use to get info for the current app and its available add-ons, get license info for the current app or its add-ons, purchase an app or add-on for the current user, and perform other tasks. To get a StoreContext object, do one of the following: In a single-user app (that is, an app that runs only in the context of the user that launched the app), use the static GetDefault method to get a StoreContext object that you can use to access Microsoft Store-related data for the user. Most Universal Windows Platform (UWP) apps are single-user apps. Windows.Services.Store.StoreContext context = StoreContext.GetDefault(); In a multi-user app, use the static GetForUser method to get a StoreContext object that you can use to access Microsoft Store-related data for a specific user who is signed in with their Microsoft account while using the app. The following example gets a StoreContext object for the first available user. var users = await Windows.System.User.FindAllAsync(); Windows.Services.Store.StoreContext context = StoreContext.GetForUser(users[0]); Note Windows desktop applications that use the Desktop Bridge must perform additional steps to configure the StoreContext object before they can use this object. For more information, see this section. After you have a StoreContext object, you can start calling methods of this object to get Store product info for the current app and its add-ons, retrieve license info for the current app and its add-ons, purchase an app or add-on for the current user, and perform other tasks. For more information about common tasks you can perform using this object, see the following articles: - Get product info for apps and add-ons - Get license info for apps and add-ons - Enable in-app purchases of apps and add-ons - Enable consumable add-on purchases - Enable subscription add-ons for your app - Implement a trial version of your app For a sample app that demonstrates how to use StoreContext and other types in the Windows.Services.Store namespace, see the Store sample. Implement in-app purchases To offer an in-app purchase to customers in your app using the Windows.Services.Store namespace: If your app offers add-ons that customers can purchase, create add-on submissions for your app in Partner Center . Write code in your app to retrieve product info for your app or an add-on offered by your app and then determine whether the license is active (that is, whether the user has a license to use the app or add-on). If the license isn't active, display a UI that offers the app or add-on for sale to the user as an in-app purchase. If the user chooses to purchase your app or add-on, use the appropriate method to purchase the product: - If the user is purchasing your app or a durable add-on, follow the instructions in Enable in-app purchases of apps and add-ons. - If the user is purchasing a consumable add-on, follow the instructions in Enable consumable add-on purchases. - If the user is purchasing a subscription add-on, follow the instructions in Enable subscription add-ons for your app. Test your implementation by following the testing guidance in this article. Implement trial functionality To exclude or limit features in a trial version of your app using the Windows.Services.Store namespace: Configure your app as a free trial in Partner Center. Write code in your app to retrieve product info for your app or an add-on offered by your app and then determine whether the license associated with the app is a trial license. Exclude or limit certain features in your app if it is a trial, and then enable the features when the user purchases a full license. For more information and a code example, see Implement a trial version of your app. Test your implementation by following the testing guidance in this article. Test your in-app purchase or trial implementation If your app uses APIs in the Windows.Services.Store namespace to implement in-app purchase or trial functionality, you must publish your app to the Store and download the app to your development device to use its license for testing. Follow this process to test your code: If your app is not yet published and available in the Store, make sure your app meets the minimum Windows App Certification Kit requirements, submit your app in Partner Center, and make sure your app passes the certification process. You can configure your app so it is not discoverable in the Store while you test it. Please note the proper configuration of package flights. Incorrectly configured package flights may be not be able to be downloaded. Next, make sure you have completed the following: - Write code in your app that uses the StoreContext class and other related types in the Windows.Services.Store namespace to implement in-app purchases or trial functionality. - If your app offers an add-on that customers can purchase, create an add-on submission for your app in Partner Center. - If you want to exclude or limit some features in a trial version of your app, configure your app as a free trial in Partner Center. With your project open in Visual Studio, click the Project menu, point to Store, and then click Associate App with the Store. Complete the instructions in the wizard to associate the app project with the app in your Partner Center account that you want to use for testing. Note If you do not associate your project with an app in the Store, the StoreContext methods set the ExtendedError property of their return values to the error code value 0x803F6107. This value indicates that the Store doesn't have any knowledge about the app. If you have not done so already, install the app from the Store that you specified in the previous step, run the app once, and then close this app. This ensures that a valid license for the app is installed to your development device. In Visual Studio, start running or debugging your project. Your code should retrieve app and add-on data from the Store app that you associated with your local project. If you are prompted to reinstall the app, follow the instructions and then run or debug your project. Note After you complete these steps, you can continue to update your app's code and then debug your updated project on your development computer without submitting new app packages to the Store. You only need to download the Store version of your app to your development computer once to obtain the local license that will be used for testing. You only need to submit new app packages to the Store after you complete your testing and you want to make the in-app purchase or trial-related features in your app available to your customers. If your app uses the Windows.ApplicationModel.Store namespace, you can use the CurrentAppSimulator class in your app to simulate license info during testing before you submit your app to the Store. For more information, see Get started with the CurrentApp and CurrentAppSimulator classes. Note The Windows.Services.Store namespace does not provide a class that you can use to simulate license info during testing. If you use the Windows.Services.Store namespace to implement in-app purchases or trials, you must publish your app to the Store and download the app to your development device to use its license for testing as described above. Receipts for in-app purchases The Windows.Services.Store namespace does not provide an API you can use to obtain a transaction receipt for successful purchases in your app's code. This is a different experience from apps that use the Windows.ApplicationModel.Store namespace, which can use a client-side API to retrieve a transaction receipt. If you implement in-app purchases using the Windows.Services.Store namespace and you want to validate whether a given customer has purchased an app or add-on, you can use the query for products method in the Microsoft Store collection REST API. The return data for this method confirms whether the specified customer has an entitlement for a given product, and provides data for the transaction in which the user acquired the product. The Microsoft Store collection API uses Azure AD authentication to retrieve this information. Using the StoreContext class with the Desktop Bridge Desktop applications that use the Desktop Bridge can use the StoreContext class to implement in-app purchases and trials. However, if you have a Win32 desktop application or a desktop application that has a window handle (HWND) that is associated with the rendering framework (such as a WPF application), your application must configure the StoreContext object to specify which application window is the owner window for modal dialogs that are shown by the object. Many StoreContext members (and members of other related types that are accessed through the StoreContext object) display a modal dialog to the user for Store-related operations such as purchasing a product. If a desktop application does not configure the StoreContext object to specify the owner window for modal dialogs, this object will return inaccurate data or errors. To configure a StoreContext object in a desktop application that uses the Desktop Bridge, follow these steps. Do one of the following to enable your app to access the IInitializeWithWindow interface: If your application is written in a managed language such as C# or Visual Basic, declare the IInitializeWithWindow interface in your app's code with the ComImport attribute as shown in the following C# example. This example assumes that your code file has a using statement for the System.Runtime.InteropServices namespace. [ComImport] [Guid("3E68D4BD-7135-4D10-8018-9FB6D9F33FA1")] [InterfaceType(ComInterfaceType.InterfaceIsIUnknown)] public interface IInitializeWithWindow { void Initialize(IntPtr hwnd); } If your application is written in C++, add a reference to the shobjidl.h header file in your code. This header file contains the declaration of the IInitializeWithWindow interface. Get a StoreContext object by using the GetDefault method (or GetForUser if your app is a multi-user app) as described earlier in this article, and cast this object to an IInitializeWithWindow object. Then, call the IInitializeWithWindow.Initialize method, and pass the handle of the window that you want to be the owner for any modal dialogs that are shown by StoreContext methods. The following C# example shows how to pass the handle of your app's main window to the method. StoreContext context = StoreContext.GetDefault(); IInitializeWithWindow initWindow = (IInitializeWithWindow)(object)context; initWindow.Initialize(System.Diagnostics.Process.GetCurrentProcess().MainWindowHandle); Products, SKUs, and availabilities Every product in the Store has at least one SKU, and each SKU has at least one availability. These concepts are abstracted away from most developers in Partner Center, and most developers will never define SKUs or availabilities for their apps or add-ons. However, because the object model for Store products in the Windows.Services.Store namespace includes SKUs and availabilities, a basic understanding of these concepts can be helpful for some scenarios. Store IDs Every app, add-on, or other product in the Store has an associated Store ID (this is also sometimes called a product Store ID). Many APIs require the Store ID in order to perform an operation on an app or add-on. The Store ID of any product in the Store is 12-character alpha-numeric string, such as 9NBLGGH4R315. There are several different ways to get the Store ID for a product in the Store: - For an app, you can get the Store ID on the App identity page in Partner Center. - For an add-on, you can get the Store ID on the add-on's overview page in Partner Center. - For any product, you can also get the Store ID programmatically by using the StoreId property of the StoreProduct object that represents the product. For products with SKUs and availabilities, the SKUs and availabilities also have their own Store IDs with different formats. How to use product IDs for add-ons in your code If you want to make an add-on available to your customers in the context of your app, you must enter a unique product ID for your add-on when you create your add-on submission in Partner Center. You can use this product ID to refer to the add-on in your code, although the specific scenarios in which you can use the product ID depend on which namespace you use for in-app purchases in your app. Note The product ID that you enter in Partner Center for an add-on is different than the add-on's Store ID. The Store ID is generated by Partner Center. Apps that use the Windows.Services.Store namespace If your app uses the Windows.Services.Store namespace, you can use the product ID to easily identify the StoreProduct that represents your add-on or the StoreLicense that represents your add-on's license. The product ID is exposed by the StoreProduct.InAppOfferToken and StoreLicense.InAppOfferToken properties. Note Although the product ID is a useful way to identify an add-on in your code, most operations in the Windows.Services.Store namespace use the Store ID of an add-on instead of the product ID. For example, to programmatically retrieve one or more known add-ons for an app, pass the Store IDs (rather than the product IDs) of the add-ons to the GetStoreProductsAsync method. Similarly, to report a consumable add-on as fulfilled, pass the Store ID of the add-on (rather than the product ID) to the ReportConsumableFulfillmentAsync method. Apps that use the Windows.ApplicationModel.Store namespace If your app uses the Windows.ApplicationModel.Store namespace, you'll need to use the product ID that you assign to an add-on in Partner Center for most operations. For example: Use the product ID to identify the ProductListing that represents your add-on or the ProductLicense that represents your add-on's license. The product ID is exposed by the ProductListing.ProductId and ProductLicense.ProductId properties. Specify the product ID when you purchase your add-on for the user by using the RequestProductPurchaseAsync method. For more information, see Enable in-app product purchases. Specify the product ID when you report your consumable add-on as fulfilled by using the ReportConsumableFulfillmentAsync method. For more information, see Enable consumable in-app product purchases. Related topics - Get product info for apps and add-ons - Get license info for apps and add-ons - Enable in-app purchases of apps and add-ons - Enable consumable add-on purchases - Enable subscription add-ons for your app - Implement a trial version of your app - Error codes for Store operations - In-app purchases and trials using the Windows.ApplicationModel.Store namespace Feedback Send feedback about:
https://docs.microsoft.com/en-us/windows/uwp/monetize/in-app-purchases-and-trials
CC-MAIN-2019-18
refinedweb
3,323
51.78
If. Before we get started, there are a few requirements that must be met to be successful: We will be using .NET Core 6.0 for this particular tutorial. Older or newer versions might work, but there’s a chance that some of the commands may be a little different. The expectation is that you already have a MongoDB Atlas cluster ready to go. This could be a free M0 cluster or better, but you’ll need it properly configured with user roles and network access rules. You’ll also need the MongoDB sample data sets to be attached. If you need help with this, check out a previous tutorial I wrote on the topic. Because we’re expecting to accomplish some fairly complicated things in this tutorial, it’s probably a good idea to break down the data going into it and the data that we’re expecting to come out of it. In this tutorial, we’re going to be using the sample_mflix database and the movies collection. We’re also going to be using a custom playlist collection that we’re going to add to the sample_mflix database. To give you an idea of the data that we’re going to be working with, take the following document from the movies collection: { "_id": ObjectId("573a1390f29313caabcd4135"), "title": "Blacksmith Scene", "plot": "Three men hammer on an anvil and pass a bottle of beer around.", "year": 1893, // ... } Alright, so I didn’t include the entire document because it is actually quite huge. Knowing every single field is not going to help or hurt the example as long as we’re familiar with the _id field. Next, let’s look at a document in the proposed playlist collection: { "_id": ObjectId("61d8bb5e2d5fe0c2b8a1007d"), "username": "nraboy", "items": [ "573a1390f29313caabcd42e8", "573a1391f29313caabcd8a82" ] } Knowing the fields in the above document is important as they’ll be used throughout our aggregation pipelines. One of the most important things to take note of between the two collections is the fact that the _id fields are ObjectId and the values in the items field are strings. More on this as we progress. Now that we know our input documents, let’s take a look at what we’re expecting as a result of our queries. If I were to query for a playlist, I don’t want the id values for each of the movies. I want them fully expanded, like the following: { "_id": ObjectId("61d8bb5e2d5fe0c2b8a1007d"), "username": "nraboy", "items": [ { "_id": ObjectId("573a1390f29313caabcd4135"), "title": "Blacksmith Scene", "plot": "Three men hammer on an anvil and pass a bottle of beer around.", "year": 1893, // ... }, { "_id": ObjectId("573a1391f29313caabcd8a82"), "title": "The Terminator", "plot": "A movie about some killer robots.", "year": 1984, // ... } ] } This is where the aggregation pipelines come in and some joining because we can’t just do a normal filter on a Find operation, unless we wanted to perform multiple Find operations. To keep things simple, we’re going to be building a console application that uses our aggregation pipeline. You can take the logic and apply it towards a web application if that is what you’re interested in. From the CLI, execute the following: dotnet new console -o MongoExample cd MongoExample dotnet add package MongoDB.Driver The above commands will create a new .NET Core project and install the latest MongoDB driver for C#. Everything we do next will happen in the project’s “Program.cs” file. Open the “Program.cs” file and add the following C# code: using MongoDB.Driver; using MongoDB.Bson; MongoClient client = new MongoClient("ATLAS_URI_HERE"); IMongoCollection<BsonDocument> playlistCollection = client.GetDatabase("sample_mflix").GetCollection<BsonDocument>("playlist"); List<BsonDocument> results = playlistCollection.Find(new BsonDocument()).ToList(); foreach(BsonDocument result in results) { Console.WriteLine(result["username"] + ": " + string.Join(", ", result["items"])); } The above code will connect to a MongoDB cluster, get a reference to our playlist collection, and dump all the documents from that collection into the console. Finding and returning all the documents in the collection is not a requirement for the aggregation pipeline, but it might help with the learning process. The ATLAS_URI_HERE string can be obtained from the MongoDB Atlas Dashboard after clicking “Connect” for a particular cluster. We’re going to explore a few different options towards creating an aggregation pipeline query with .NET Core. The first will use raw BsonDocument type data. We know our input data and we know our expected outcome, so we need to come up with a few pipeline stages to bring it together. Let’s start with the first stage: BsonDocument pipelineStage1 = new BsonDocument{ { "$match", new BsonDocument{ { "username", "nraboy" } } } }; The first stage of this pipeline uses the $match operator to find only documents where the username is “nraboy.” This could be more than one because we’re not treating username as a unique field. With the filter in place, let’s move to the next stage: BsonDocument pipelineStage2 = new BsonDocument{ { "$project", new BsonDocument{ { "_id", 1 }, { "username", 1 }, { "items", new BsonDocument{ { "$map", new BsonDocument{ { "input", "$items" }, { "as", "item" }, { "in", new BsonDocument{ { "$convert", new BsonDocument{ { "input", "$$item" }, { "to", "objectId" } } } } } } } } } } } }; Remember how the document _id fields were ObjectId and the items array were strings? For the join to be successful, they need to be of the same type. The second pipeline stage is more of a manipulation stage with the $project operator. We’re defining the fields we want passed to the next stage, but we’re also modifying some of the fields, in particular the items field. Using the $map operator we can take the string values and convert them to ObjectId values. If your items array contained ObjectId instead of string values, this particular stage wouldn’t be necessary. It might also not be necessary if you’re using POCO classes instead of BsonDocument types. That is a lesson for another day though. With our item values mapped correctly, we can push them to the next stage in the pipeline: BsonDocument pipelineStage3 = new BsonDocument{ { "$lookup", new BsonDocument{ { "from", "movies" }, { "localField", "items" }, { "foreignField", "_id" }, { "as", "movies" } } } }; The above pipeline stage is where the JOIN operation actually happens. We’re looking into the movies collection and we’re using the ObjectId fields from our playlist collection to join them to the _id field of our movies collection. The output from this JOIN will be stored in a new movies field. The $lookup is like saying the following: SELECT movies FROM playlist JOIN movies ON playlist.items = movies._id Of course there is more to it than the above SQL statement because items is an array, something you can’t natively work with in most SQL databases. So as of right now, we have our joined data. However, its not quite as elegant as what we wanted in our final outcome. This is because the $lookup output is an array which will leave us with a multidimensional array. Remember, items was an array and each movies is an array. Not the most pleasant thing to work with, so we probably want to further manipulate the data in another stage. BsonDocument pipelineStage4 = new BsonDocument{ { "$unwind", "$movies" } }; The above stage will take our new movies field and flatten it out with the $unwind operator. The $unwind operator basically takes each element of an array and creates a new result item to sit adjacent to the rest of the fields of the parent document. So if you have, for example, one document that has an array with two elements, after doing an $unwind, you’ll have two documents. Our end goal, though, is to end up with a single dimension array of movies, so we can fix this with another pipeline stage. BsonDocument pipelineStage5 = new BsonDocument{ { "$group", new BsonDocument{ { "_id", "$_id" }, { "username", new BsonDocument{ { "$first", "$username" } } }, { "movies", new BsonDocument{ { "$addToSet", "$movies" } } } } } }; The above stage will group our documents and add our unwound movies to a new movies field, one that isn’t multidimensional. So let’s bring the pipeline stages together so they can be run in our application. BsonDocument[] pipeline = new BsonDocument[] { pipelineStage1, pipelineStage2, pipelineStage3, pipelineStage4, pipelineStage5 }; List<BsonDocument> pResults = playlistCollection.Aggregate<BsonDocument>(pipeline).ToList(); foreach(BsonDocument pResult in pResults) { Console.WriteLine(pResult); } Executing the code thus far should give us our expected outcome in terms of data and format. Now, you might be thinking that the above five-stage pipeline was a lot to handle for a JOIN operation. There are a few things that you should be aware of: What I’m trying to say is that the length and complexity of your pipeline is going to depend on how you’ve chosen to model your data. Let’s look at another way to accomplish our desired outcome. We can make use of the Fluent API that MongoDB offers instead of creating an array of pipeline stages. Take a look at the following: var pResults = playlistCollection.Aggregate() .Match(new BsonDocument{{ "username", "nraboy" }}) .Project(new BsonDocument{ { "_id", 1 }, { "username", 1 }, { "items", new BsonDocument{ { "$map", new BsonDocument{ { "input", "$items" }, { "as", "item" }, { "in", new BsonDocument{ { "$convert", new BsonDocument{ { "input", "$$item" }, { "to", "objectId" } } } } } } } } } }) .Lookup("movies", "items", "_id", "movies") .Unwind("movies") .Group(new BsonDocument{ { "_id", "$_id" }, { "username", new BsonDocument{ { "$first", "$username" } } }, { "movies", new BsonDocument{ { "$addToSet", "$movies" } } } }) .ToList(); foreach(var pResult in pResults) { Console.WriteLine(pResult); } In the above example, we used methods such as Match, Project, Lookup, Unwind, and Group to get our final result. For some of these methods, we didn’t need to use a BsonDocument like we saw in the previous example. You just saw two ways to do a MongoDB aggregation pipeline for joining collections within a .NET Core application. Like previously mentioned, there are a few ways to accomplish what we want, all of which are going to be dependent on how you’ve chosen to model the data within your collections. There is a third way, which we’ll explore in another tutorial, and this uses LINQ to get the job done. If you have questions about anything you saw in this tutorial, drop by the MongoDB Community Forums and get involved! A video version of this tutorial can be seen below. This content first appeared on MongoDB.
https://www.thepolyglotdeveloper.com/2022/03/joining-collections-mongodb-dotnet-core-aggregation-pipeline/
CC-MAIN-2022-40
refinedweb
1,670
61.67
Tips for first-time users¶ Ray provides a highly flexible, yet minimalist and easy to use API. On this page, we describe several tips that can help first-time Ray users to avoid some common mistakes that can significantly hurt the performance of their programs. All the results reported in this page were obtained on a 13-inch. Tip 1: Delay ray.get()¶ With Ray, the invocation of every remote operation (e.g., task, actor method) is asynchronous. This means that the operation immediately returns a promise/future, which is essentially an identifier (ID) of the operation’s result. This is key to achieving) print("results = ", results) The output of a program execution is below. As expected, the program takes around 4 seconds: duration = 4.0149290561676025 results = [0, 1, 2, 3] Now, let’s parallelize the above program with Ray. Some first-time users will do this by just making the function remote, i.e., However, when executing the above program one gets: duration = 0.0003619194030761719 results = [ObjectRef(df5a1a828c9685d3ffffffff0100000001000000), ObjectRef(cb230a572350ff44ffffffff0100000001000000), ObjectRef(7bbd90284b71e599ffffffff0100000001000000), ObjectRef(bd37d2621480fc7dffffffff0100000001000000)] When looking at this output, two things jump out. First, the program finishes immediately, i.e., in less than 1 ms. Second, instead of the expected results (i.e., [0, 1, 2, 3]) we get a bunch of identifiers. Recall that remote operations are asynchronous and they return futures (i.e., object IDs) instead of the results themselves. This is exactly what we see here. We measure only the time it takes to invoke the tasks, not their running times, and we get the IDs of the results corresponding to the four tasks. To get the actual results, we need to use ray.get(), and here the first instinct is to just call ray.get() on the remote operation invocation, i.e., replace line 12 with: results = [ray.get(do_some_work.remote(x)) for x in range(4)] By re-running the program after this change we get: duration = 4.018050909042358 results = [0, 1, 2, 3] So now the results are correct, but it still takes 4 seconds, 12 second. Tip 2: Avoid tiny tasks¶ shorter tiny_work() remote: import time import ray ray.init(num_cpus = 4) @ray.remote def tiny_work(x): time.sleep(0.0001) # Replace on a 2018 MacBook Pro notebook. Tip 3: Avoid passing same object repeatedly to remote tasks¶. One example is passing the same large object as an argument repeatedly, as illustrated by the program below: import time import numpy as np import ray ray.init(num_cpus = 4) @ray.remote def no_work(a): return start = time.time() a = np.zeros((5000, 5000)) result_ids = [no_work.remote(a) for x in range(10)] results = ray.get(result_ids) print("duration =", time.time() - start) This program outputs: duration = 1.0837509632110596 2.5((5000, 5000))) result_ids = [no_work.remote(a_id) for x in range(10)] results = ray.get(result_ids) print("duration =", time.time() - start) Running this program takes only: duration = 0.132796049118042 This is 7. Tip 4: Pipeline data processing¶ seconds. Next, assume the results of these tasks are processed by process_results(), which takes 1 sec per result. The expected running time is then (1) the time it takes to execute the slowest of the do_some_work() tasks, plus (2) 4 secondssec, a significant improvement: duration = 4.852453231811523 result = 6 To aid the intuition, Figure 1 shows the execution timeline in both cases: when using ray.get() to wait for all results to become available before processing them, and using ray.wait() to start processing the results as soon as they become available.
https://docs.ray.io/en/master/auto_examples/tips-for-first-time.html
CC-MAIN-2022-05
refinedweb
584
61.12
I'm new to elisp but I want my beloved editor to generate the standard c-header stuff when creating a new .h/.hpp header. c-x c-f test.h should automatically insert: #ifndef _TEST_H_ #ifndef _TEST_H_ #endif depending on the given filename. I put the following to my .emacs file: (defun new-c-header () "Insert c-header skeleton." (interactive "") (progn (setq bname (upcase(buffer-name))) (insert (message "#ifndef %s\n\#define %s\n\n#endif" bname bname)))) Apart from knowing that "message" might not be the right choice here, I don't know how to modify the value of bname!? "replace-regexp" doesn't seem to be the what I'm looking for. (and how could the new-c-header() be invoked by creating a new .h/.cpp file?) jan
http://lists.gnu.org/archive/html/help-gnu-emacs/2004-02/msg00502.html
CC-MAIN-2019-18
refinedweb
132
66.13
Beginner's Guide to Google's Vision API in Python • December 26, 2018 • 9 min read It's been quite a while since Google released a dedicated API called Vision API for performing computer vision related tasks. Computer vision is a field that concerns how a computer processes an image. It is quite easy for us humans to derive any useful insights from a given image but how does a computer do it? Say, for example, you supply an image of a dog to your computer and using some software the computer tells you that the image supplied to it is a dog's image. This is where computer vision comes in. Computer vision is a whole world of study onto itself, and the Vision API provides a number of utilities for performing tasks related to computer vision with absolute ease. The best part is that developers with absolutely no previous experience in computer vision can use Vision API by going through its documentation. This tutorial attempts to introduce you to Vision API and how it can be called from Python code. Specifically speaking, this tutorial is going to cover: - What is Google's Vision API? A more Detailed Introduction - What are the Offerings of Vision API - Some Niche Use-Cases - Vision API Client Library for Python - A Case Study with Vision API in Python Note: If you feel that you want to know more about APIs in general (from Python and Machine Learning perspectives) before getting started with this tutorial following are some excellent resources: What is Google's Vision API? A more Detailed Introduction Google have encapsulated their Machine Learning models in an API to allow developers to use their Vision technology. The Vision API can quickly classify images into thousands of categories and assign them sensible labels. It can even detect individual objects, faces, and pieces of text within an image. On a very high level, Google's Vision API lets you do two things: - Use the API directly from your code for doing powerful image analysis that too as scale. - Build custom models using the API to accommodate more flexibility for your particular use case. This API is particularly handy because as the modern day progresses the need for "Full-Stack" practitioners is increasing very rapidly. Now, consider a scenario where a Full-Stack web developer (this essentially means that the developer is equipped with both the front-end and back-end technologies related to web development) is asked to build a website that takes images and detects its kind. Now, this would certainly require a good amount of knowledge in Computer Vision (if they do not already) because the developer will have to instruct his back-end code in such a way that it can accurately detect a given image. Also, assume that the deadline is not very long. Now, in a situation like this, if developers start to learn Computer Vision from scratch and then implements the required tasks they are more likely to miss the deadline. Instead, if he/she uses some pre-trained computer vision models and learns the underlying concepts as they proceed towards the development, it would be more practical. This is precisely one of those situations where the Vision API comes in handy. The API provides many state-of-the-art pre-trained models to serve many real-world business use-cases. The term "Full-Stack" is also getting associated with roles like Machine Learning Engineer, Data Scientist, etc. A Full-Stack Machine Learning Practitioner/Data Scientist is supposed to design and develop or at least know the end-to-end business processes. This includes "Making Production-ready Models" as one of the most crucial steps wherein the concerned person/team wraps the developed model into an API or a set of APIs and deploys on the production environment. Now, the term production varies accordingly to the use-cases, but the general idea/framework of the processes remains the same. The Vision API lets you efficiently train custom vision models with AutoML Vision BETA. Great! By now, you should have got a pretty good overview of Vision API. A nice little experiment that you can do on the Vision homepage is to analyze your favorite images and derive useful insights with the help of Vision. Here are the steps to do this: - Go to Vision homepage. - It has a section called "Try the API". It lets you drag/upload an image in its interface. - Once you supply an image to it, it provides you with a bunch of information regarding the image: As you can see, Vision detected many facts about the image provided within no time. Feel free to explore the other tabs as well to learn even more about the image. Consider this task if it was to be performed on a set of billion images. Using an API like this would undoubtedly be fruitful in that regard. Now, let's learn about the offerings of Vision API as to see some examples real-world use-cases the API has served to. What are the Offerings of Vision API - Some Niche Use-Cases The Vision API is known for its accurate results. Vision API documentation provides an excellent collection of tutorials which gives you a very detailed insight about the API. But for a first glance, these things may appear to be overwhelming. So, to keep things simple, you will learn about a few use cases which have been already served by Vision API. - Optical Character Recognition (OCR): This is a classic example of Computer Vision which primarily deals with extraction of text from an image. The Vision API comprises many state-of-the-art approaches for doing this. - Detection of Image Properties: This is the task that you performed in the earlier section. With Vision API you can retrieve general attributes of an image, features such as dominant color. - Label Detection: This task annotates an image with a label (or "tag") based on the image content. For example, a picture of a dog may produce a label of "dog", "animal", or some other similar annotation. This is an essential step in the field of Content-based Information Retrieval. - Face Detection: Given an image or a set of images, the task is to detect the faces present in them. This has several large applications like Surveillance Systems. These are some of the excellent use-cases on which Vision API performs seamlessly, and you can integrate any of the above into your applications within very less amount of time. If you want to learn more use-cases like these, be sure to check out these tutorials. Vision API provides support for a wide range of languages like Go, C#, Java, PHP, Node.js, Python, Ruby. In the next sections, you will see how to use Vision API in Python. Vision API Client Library for Python The first step for using the Python variant of Vision API, you will have to install it. The best way to install it is through pip. !pip install google-cloud-vision One the installation is successful, the next step is to verify if it is successful. from google.cloud import vision If the above line of code executes successfully, you are ready to proceed. Google provides a series of fantastic tutorials on using Vision API in Python. Now, you will build a simple application in Python which will be able to detect some general attributes of an image, such as dominant color. A Case Study with Vision API in Python Your application will take a path of an image as its input, and it will display the general attributes of the corresponding image. This is useful when the images are located inside the computer on which the application is going to be executed. But what if you need to read an image from the internet? The Vision API supports reading images from the internet as well. In this case study, you will learn to tackle the first scenario. But it's only a matter of one line of code to accommodate the internet variant. As always, you will start off by importing vision from google.cloud module. from google.cloud import vision The next step is to call ImageAnnotatorClient() which contains the utilities for extracting image properties. client = vision.ImageAnnotatorClient() You will most likely run into an error if GOOGLE_APPLICATION_CREDENTIALS environment variable is not set. This is because these libraries use Application Default Credentials (ADC) to locate your application's credentials. When your code uses libraries like this, the strategy checks for your credentials. Follow this link to learn how to generate GOOGLE_APPLICATION_CREDENTIALS. You aim to generate a client_secrets.json file which you will use for authentication purpose. Once client_secrets.json is obtained, you will execute the following code to set the GOOGLE_APPLICATION_CREDENTIALS environment variable. import os os.environ["GOOGLE_APPLICATION_CREDENTIALS"]="client_secrets.json" Now running the below code should not give you any error. client = vision.ImageAnnotatorClient() You will now write code for reading an image through a given path. import io path = 'Image.jpeg' with io.open(path, 'rb') as image_file: content = image_file.read() You have successfully loaded an image into your workspace. Now, you will instantiate an object of type vision.types.Image and you will supply content=content as its argument. image = vision.types.Image(content=content) You are only left with the final steps of your Image Properties detection application. In these steps, you will: - Call client.image_propertieswith as (image=image)argument. - Store the response of image_properties()in a variable responseand extract the image properties by calling the image_properties_annotationargument of response. - Display several properties of the images in a formatted manner. response = client.image_properties(image=image) props = response.image_properties_annotation print('Properties of the image:') for color in props.dominant_colors.colors: print('Fraction: {}'.format(color.pixel_fraction)) print('\tr: {}'.format(color.color.red)) print('\tg: {}'.format(color.color.green)) print('\tb: {}'.format(color.color.blue)) You might again run into errors if you have not enabled Vision API for your application. Enabling the API is extremely easy, and the error trace provides the instructions so that you can enable it quickly. After enabling the API, you will have to enable Billing as well to use the Vision API. Utilities for Image Properties detection take only $0.60. After that is done, the code is executed successfully and produces the output. Congrats! You saw how easy it is to use the Vision API, and the kind of utilities that it provides that to are at a remarkably less cost. Today, many companies and organizations are getting benefited from this API be it for business purposes or research grounds. In this tutorial, you merely scratched the surface of Vision API, but this should serve you as a good starting point to use Machine Learning APIs for your applications. Make sure you check out the whole suite of Machine Learning APIs that Google provides and it is known as CloudML. You can build several cool applications with the help of these easily callable APIs. The links to Vision API and CloudML provide an amazing compilation of tutorials so that you can easily play with them. Good luck! If you are interested in knowing more about Image Processing, take DataCamp's Convolutional Neural Networks for Image Processing course. Learn more about Python ← Back to tutorial
https://www.datacamp.com/tutorial/beginner-guide-google-vision-api
CC-MAIN-2022-33
refinedweb
1,889
54.32
the hex stream of a packet that a program sent over the network. Now I want to view the data in the packet. I'm pretty sure the data was just a string (or at least contains a string), but when I decode it I just get gibberish. For example, the packet is sent something like this import socket s = socket.socket() s.connect(hostname,port) data = "HeresAStringToSend" s.send(data) # I'm not worried about receiving yet. # I just want to know the anatomy of a sent packet. Then I use a packet sniffer to look at the packet that was sent; this is just a string of hex. Then I isolate the data part of the packet. Let's say the data part of the hex string is in a variable called hexdata. If I do, print hexdata.decode("hex") all I get is gibberish. Looking at the individual bytes in the hex data, they map to strange or invalid ascii codes (e.g. less than 32 or greater than 127). I don't really know what the s.send(data) method does to the data before sending it. Any help or insight would be great. What packet sniffer was that? Why not use wireshark, and eliminate the middleman? If you're using some other tool, how have you decided you even have the right packet(s)? Hope you've analyzed the header of the packet, and identified where the data part is? Have you seen where the host IP address is, and the port number? Do they fit the pattern? What OS are you using? There are differences in Windows, for example, but someone else would have to help you there. If it were my problem, I'd be using Wireshark, which can not only display the data for each packet, but show how multiple packets relate to each other.. Forgot Your Password? 2018 © Queryhome
https://www.queryhome.com/tech/9048/how-do-i-deal-with-packet-data
CC-MAIN-2019-04
refinedweb
318
77.13
Subject: [ggl] Physical and logical structure of geometry/strategies From: barend (barend.gehrels) Date: 2010-03-14 07:36:27 Hi Mateusz, Right, good points. ---------------------- > (BTW, why centroid_ has underscore suffix?) That is noted in the source file: // Note: when calling the namespace "centroid", it sometimes, // somehow, in gcc, gives compilation problems (confusion with function centroid). I remember we mailed about this right before review. Couldn't solve it at that time. Just looked again and cannot solve it. gcc confuses namespace strategy::centroid with the free function centroid. Therefore it cannot define namespace centroid at that stage. It might be able to solve it by order of include files (strategies coming first) but it doesn't (at least not at my place) Which makes me realize that the name of namespace strategy::area also might be dangerous (though we don't have (gcc) problems there). As far as I know these things: boost::geometry::area (free function) boost::geometry::strategy::area (namespace) should never be confused by the compiler. However, for centroid it is, by gcc 3.4.5 and gcc 4.4, and I still don't know why. It was not always like this. Maybe I've made somewhere a stupid error :-) as it is only confused for centroid. ---------------------- > For example: boost::geometry::area::result Like this, this is not possible and will confuse namespace area with function area. If there is a namespace in between, the confusion will (or at least should) not be there. So boost::geometry::strategy::area::result would be theoretically OK (unless compiler confusions like with centroid occur). However, I have some objections to that definition. The result would be that people need to declare: boost::geometry::strategy::area::result r = boost::geometry::area(something); while they are doing nothing with strategies at all, in most cases. So why strategy there, they will ask. The area_result is actually unrelated to strategies, the only thing which is going on is that it is defined by a strategy, but that is usually behind the screens for an end user. So, like it was: boost::geometry:area_result r = boost::geometry::area(something); is for me the most logical definition. > If it does, why not boost::geometry::strategy::traits::area ? This is possible and might be a good idea. This is behind the screens for end users, so we have more flexibility there. The question is: is it really a traits class (I realize that I commented it myself with 'traits' indeed). It is a structure which should be specialized per coordinate system, to define the default strategy for that coordinate system. It is perfectly possible to have strategies which are NOT specialized by such a trait, in fact it is not possible to specialize two of them for the same coordinate system. So now that you raise this subject and that I think about it, it is not really a traits class. So what would be the perfect name. I agree with you that strategy_area and area_result are named inconsistently (though they have different targets). Probably the obvious solution is to name it what it is, so: 'area_default_strategy'. This is more or less consistent with area_result, if you consider 'default_strategy' as one term. An alternative is to move it to the namespace of the strategies, so: boost::geometry::strategy::area::default_strategy // for the default strategy specializations per coordinate system boost::geometry::strategy::area::area_by_triangle // for the concrete strategy I favour this solution. > 3) I have an impression that the current logical structure > is to reserve namespace of boost::geometry::strategy::area > for concrete strategies only, but all tools used to generate > strategies like traits and metafunctions, sit on purpose in > namespace boost::geometry. Am I right? Yes that was the idea, but it might be defined differently indeed. Regards, Barend -------------- next part -------------- An HTML attachment was scrubbed... URL: Geometry list run by mateusz at loskot.net
https://lists.boost.org/geometry/2010/03/0688.php
CC-MAIN-2020-34
refinedweb
651
56.76
Computer Science Archive: Questions from April 12, 2010 - Anonymous askedFor the list shown below, demonstrate the following sort:10, 1, 5, 2, 6, 8, 4, 10, 6, 6, 2, 4, 1, 8... Show more For the list shown below, demonstrate the following sort:10, 1, 5, 2, 6, 8, 4, 10, 6, 6, 2, 4, 1, 8, 7, 3, 4, 1, 2, 1 External sort• Show less1 answer - Anonymous asked* It stores a date an... Show more Write a program which implements a DateTime class with thefollowing properties:• Show less * It stores a date and time, such as 11:49:57 3/29/2010. Yourchoice as to whether you use a 24-hour clock or a 12-hour withAM/PM. * It knows whether or not the current year is a leap year. * It knows how many days are in the current month, and how manydays remain in the current month. * It knows how many days have elapsed in the current year, and howmany days remain in the current year. * There should be a method to print the date. To receive full credit, you must have appropriate accessors andmutators, correct use of public: and private:, and appropriate useof const.0 answers - Anonymous askedHello, I'm havingtrouble figuring out how to implement the vector part of thequestion below, any hel... Show moreHello, I'm havingtrouble figuring out how to implement the vector part of thequestion below, any help would be appreciated. Also, I have thecode for Exercise 23.9, if needed. (Package Inheritance Hierarchy) Use the Package inheritancehierarchy created in Exercise 23.9 to create aprogram that displays the address information and calculates theshipping costs for severalPackages. The program should contain a vector of Package pointersto objects of classes TwoDayPackage andOvernightPackage. Loop through the vector to process thePackages polymorphically. For eachPackage, invoke get functions to obtain the address information ofthe sender and the recipient,then print the two addresses as they would appear on mailinglabels. Also, call each Package’scalculateCost member function and print the result. Keep track ofthe total shipping cost for allPackages in the vector, and display this total when the loopterminates.• Show less0 answers - Anonymous askedmo... Show more Using the “formal” systems (e.g. predicatecalculus, sets, relations, etc.) that you have learned,“model” a non-computational system. Thenon-computational system is a File Management System, much likeSourceSafe from Microsoft, which has the followingfunctions: - DECLARE afile with attributes such as ownership, size, type, status,etc. - ADD afile - DELETE afile - LOCK afile - UNLOCK afile - CHECK-INa file I came upwith a file structure and got struck while performing theoperations so can you help me out in this regard• Show less0 answers - Anonymous asked0 answers - Anonymous askedsingle-platter disk with the followng parameters rotationspeed:72rpm; number of tracks on one side o... Show more?• Show less0 answers - Anonymous asked0 answers - Anonymous askedPolyno... Show moreDesign and implement an ADT forsingle-variable polynomials (with nonnegative exponents)called Polynomial. Each polynomialhas zero or more terms, where each term includes acoefficient(a double) and anexponent(a nonnegative integer). You can assumethat exponents lie within a range from 0 to 100. The underlyingdata structure you should use to implement the polynomial ADT is anarray (of coefficients). The ADT should supportat leastthe basic operations.Basic operations(required): • Default constructor Polynomial() – create a null polynomial, i.e. a polynomial whosecoefficients are all equal to zero. • Function zeroPolynomial() – reset all coefficients to zero. • Function insert()– inserts a new coefficient intoan existing polynomial. Overwrites the old coefficientvalue. • Function degree()– returns thedegree of a polynomial. • Function print()– prints thepolynomial on screen. Bonus items(optional): • Write a function eval(doublex) that evaluates thepolynomial at the given value of x. • Overwrite operator for addition (+) of twopolynomials. • Overwrite operator for subtraction (-) of twopolynomials. The class must be organized as twofiles, a header file, Polynomial.h, containing theclass definition and the implementation file,Polynomial.cpp,containing the code for the function of theclass.• Show less0 answers - Wolfx91 askedHi I'm a first year civil Engineer and as one of my courses I haveto take programming, which I hate... Show more.• Show less0 answers - Anonymous askedDELETE EM... Show morea. What happens when the following command is run on the databasestate shown in Figure 5.6DELETE EMPLOYEE WHERE Lname = 'Borg'• Show less b. Is it better to CASCADE or SET NULL in case of EMPSUPERFKconstraint on DELETE0 answers - alexmon3000 asked4. (4pts) Assume that you have a direct-mapped cache withfour-word blocks and a total size of 16 wor0 answers - Anonymous askedplease help me i am new to java thank you ("The Twelve Days of Christmas" Song) Write an applic... More »0 answers - Anonymous askedI need help writing this C program. I've tried it a few differentways but can't get it to work corre... Show moreI need help writing this C program. I've tried it a few differentways but can't get it to work correctly. Any help is appreciated,whether it be program code or just hints on how to get it done.Thanks. a) Write a C program that accepts a mileage and gallons valueand calculates the miles-per-gallon achieved for that segment ofthe trip. The mpg is obtained as the difference in mileagebetween fill-ups divided by the number of gallons of gasolinerecieved in the fill-up. b) Modify the program written in part "a" to additionallycompute and display the cumulative mpg achieved after each fillup. The cumulative mpg is calculated as the differencebetween fill-up mileage and the mileage at the start of the tripdivided by the sum of the gallons used to that point in the trip. • Show less2 answers - Anonymous asked0 answers - Anonymous askedThe Towers of Hanoi is one of the most famous classic problemsevery budding computer scientist must... Show moreThe Towers of Hanoi is one of the most famous classic problemsevery budding computer scientist must grapple with. Legend has itthat in a temple in the Far East, priests are attempting to move astack of golden disks from one diamond peg to another (Fig. 6.41). The initial stack has 64 disksthreaded onto one peg and arranged from bottom to top by decreasingsize. The priests are attempting to move the stack from one peg toanother under the constraints that exactly one disk is moved at atime and at no time may a larger disk be placed above a smallerdisk. Three pegs are provided, one being used for temporarilyholding disks. Supposedly, the world will end when the priestscomplete their task, so there is little incentive for us tofacilitate their efforts. Let us assume that the priests are attempting tomove the disks from peg 1 to peg 3. We wish to develop an algorithmthat prints the precise sequence of peg-to-peg disk transfers. If we were to approach this problem withconventional methods, we would rapidly find ourselves hopelesslyknotted up in managing the disks. Instead, attacking this problemwith recursion in mind allows the steps to be simple. Moving ndisks can be viewed in terms of moving only n1 disks (hence, therecursion), as follows: Move n 1 disks from peg 1 to peg 2, using peg 3as a temporary holding area. Move the last disk (the largest) from peg 1 topeg 3. Move the n 1 disks from peg 2 to peg 3, usingpeg 1 as a temporary holding area. 1 answer - Anonymous asked0 answers - Anonymous asked0 answers - Anonymous asked0 answers - Anonymous asked0 answers - Anonymous asked1 answer - AnnoyedCoffee9 askedDo not just write the answer, please expa... Show moreC++please explain your work step bystep [details]. ThanksDo not just write the answer, please expalin . Iam a biggener in C++Write a program that inputs a line of text, tokensizes theline with function strtokand outputs the tokens in reverse order.• Show less1 answer - Evilsithgirl asked0 answers - Anonymous asked1 answer - Anonymous askedThe date june 10,1960 is... Show moreI am stuck on one question that is keeping me from completing myassignment. The date june 10,1960 is special because when we write it in thefollowing format, the month times the day equals the year;6/10/60 Write a program that asks the user to enter a month (in numericform), a day, and a two digit year. The program should thendetermine whether the month times the day is equal to the year. Ifso, it should display a message saying the date is magic.Otherwise, it should display a message saying the date is notmagic. • Show less1 answer - Anonymous asked0 answers - Anonymous asked's neighbors.... Show moreFor each node u in an undirected graph, let twodegree[u]be the sum of the degrees of u's neighbors. Show how tocompute all values in the array twodegree in linear time, given agraph in adjacency list format. Justify the correctness of youralgorithm as well as its running time. • Show less0 answers - Anonymous askedpls can someone help me write a program using C++ to do a word cound. the only thing is that the pro... More »0 answers - Anonymous asked#2 question- A what is a series... Show more#1Question- The number of worksheets that a workbook cancontain is?#2 question- A what is a series of two or more adjacent cellsin a column or row or a rectangular group of cells.#3 Question- how many file formats does excel offer for savinga workbook?• Show less1 answer - Anonymous askedAssume you work in a museum and you have been asked to developa system that charges customers based... Show moreAssume you work in a museum and you have been asked to developa system that charges customers based on the followingconditionsCustomers age (0-12 )year =100 dollarage(12-18)years =200dolarsAbove 18 years =500 dollarsNon-Citizens, a flat rate of 1000 dollarsWrite a program that asks the customer to input age, andproduces a message stating the users price of admission.(Hint :usedialog boxes)• Show less2 answers - eman55 askedL}... Show moreLet L be a regular language. Show that the following languageis regular.The set P = { u | uv ε L} of prefixes of strings inL.• Show less0 answers - eman55 askedL}... Show moreLet L be a regular language. Show that the following languageis regular.The set LR = { wR | w ε L} ofreversals of strings in L.• Show less1 answer - eman55 asked1 answer - Anonymous askedWrite a program to help the user understand the force lb.needed to p... Show moreThis is what the exercise says:• Show less Write a program to help the user understand the force lb.needed to push a 1200 lb. table, on wheels, up a 21 inch high rampthat is 6 ft long. There should be a looping program thatasks the user if he/she would like to try again withdifference. This should be a program that asks the user toinput the variables: weight of table, height of the raise, lengthof the ramp. The beginning statement of 1200 lb. table, 21 inchraise, and 6 ft ramp is just an example; these dimensions should bevarying. The answer will be in force lb., and you will need to usea math equation to calculate what it will take to move thisreal-life table.1 answer - Anonymous askedWrite a program that calculates the frequency counts ofvarious characters and other interesting item... Show moreWrite a program that calculates the frequency counts ofvarious characters and other interesting items:1) Obtain file names from the user for both input and output.This must be a function call. As a hint, do not open this file foroutput and input right away.2) Calculate the frequencies for each letter in the alphabetfor A through Z (NOT case-sensitive meaning capital “A”and lowercase “a” are the same).3) Calculate the frequencies of the white space in theprogram.4) Calculate the number of uppercase and lower caseletters.5) Write your results to a new file specified by theuser.6) Your output file should look similar to below (the numbersof course depend on your file):Letter Frequencies:A10B13C20D0E17F4Rest of LettersUpper Case50Lower Case17White Space10• Show less1 answer - Anonymous askedCharacterize and compare the performance of file I/O byimplementing reading and writing of files thr... Show more Characterize and compare the performance of file I/O byimplementing reading and writing of files through the followingthree methods: · I/O through system calls read andwrite · Memory mapped I/O through mmap· Buffered I/O through read andwrite You should implement a program that can either read or write blocksof a given size from a large file. The user should be able tospecify the I/O method to use for reading and writing. For example,writing blocks of 1K through system calls (the first method above)may be done as follows: iotest --method=syscall --blocksize=1024--operation=write Use your program to measure the read and write I/O performanceachieved through the three methods for various block sizes. Whatcan you deduce from your observations?• Show less0 answers - Anonymous askedThe following below is the assignment and then I copied andpasted what I have, but I am not sure if... Show more The following below is the assignment and then I copied andpasted what I have, but I am not sure if what I did is correct orwill work in this case. Please I would appreciate any comments onit or basically anything to help me understand the question furtherthanks. For this closed lab you will be providing an implementation of anew Text operationcalled Concatenate. The formal specification ofConcatenate is provided below. Either on your own or with a closedlab partner, and before the closed lab, write a procedure bodyfor Concatenate. Review your code carefully and traceit on several example values. Donot enter your solution into the computer untilclosed lab. The idea is to have code that worksthe first time you type it in, except perhapsfor typos. global_procedure Concatenate (alters Text& t1,consumes Text& t2); /*!ensurest1 = #t1 * #t2!*/ MY WORK FOR THE BODY object Integer len = t1.length(); t1.Add(len,t2)• Show less0 answers - Anonymous askedWrite an application that finds the shortest path through a mazeand repo... Show more A maze-solving application:Write an application that finds the shortest path through a mazeand reports this shortest path to the user. Your applicationmust: - Ask the user for the name of a file that contains the mazedescription. - Read the maze description from the file. - Compute the shortest path (any shortest path) through themaze. - Display four pieces of information for the user: - The row and column number of the start point in the maze. - The row and column number of the end point in the maze. - The number of steps in the shortest path in the maze. - The exact steps required to move from the start point to theend point (along a shortest path). You will need the following details: Maze file format Mazes will be described by the data in a text file. Thedata will have this exact form:The first line of the text file willhave two integers on it. The first integer represents thewidth of the maze (number of columns), the second integerrepresents the height of the maze (number of rows). The next lines of the maze will contain a single 'word', orsequence of non-whitespace characters. These charactersdescribe the maze one row at a time. There will be one linefor each row in the maze. The characters have the followingmeaning: #A wall square. Thisspace is impassable. -An empty square. You can move through thesespaces. SThe start square. (Treat it as an empty square.) EThe end square. (Treat it as an emptysquare.) Here are a few sample maze files: Example maze #1:5 4 ##### S--## ##--E ##### Example maze #2:6 6 ------ #--#-- --##-- ---#-# --E#S- ------ Your program must display the following information for theuser: - The row and column number of the start point in themaze. The upper-left hand corner character of themaze is at row 0, column 0. Your message should be userfriendly. For maze example #1, you might print: "The startpoint is at row 1, column 0." - The row and column number of the end point in themaze. The upper-left hand corner character of themaze is at row 0, column 0. Your message should be userfriendly. For maze example #2, you might print: "The endpoint is at row 4, column 2." - The number of steps in the shortest path in themaze. Again, your message should be userfriendly. For maze example #, you might print: "The shortestpath through the maze takes 4 steps." If there is no path through the maze, you should print: "Thereis no path through this maze." - The exact steps required to move from the start pointto the end point (along a shortest path). Print thisin a compact form. Use single uppercase characters for eachdirection, and don't put spaces in the path. For maze example#2, you would print: "The shortest path is: SWWN." • Show less0 answers - Anonymous askedI want to write an ADT in C++ hat performs addition,subtraction, multiplication a... Show more I am new to ADTs… I want to write an ADT in C++ hat performs addition,subtraction, multiplication a division on fractions… I need to define a fraction, assign it a positive or negativesign and find the common denominator… Any help???• Show less2 answers - Anonymous asked//variableto store the mont... Show morecreated the class date: public class Date { private int dMonth; //variableto store the month private int dDay; //variable to store the day private int dYear; //variable to store the year public Date() { dMonth = 1; dDay = 1; dYear = 1900; } public Date(int month, int day, int year) { } public void setDate(int month, int day, intyear) { dMonth = month; dDay = day; dYear = year; } public int getMonth() { return dMonth; } public int getDay() { return dDay; } public int getYear() { return dYear; } public String toString() { return (dMonth + "-" +dDay + "-" + dYear); } } but i must do the following: 1) modify setDate,constructor with parameters to check for valid data.• Show less 2) display using JoptionPane if the date is invalid 3) handle leap years properly 4) a test program to check class Date functionsproperly1 answer - Anonymous askedwrite a web page (html) that asks the user for hisfirst and last name then uses a PHP script to writ... Show more write a web page (html) that asks the user for hisfirst and last name then uses a PHP script to write a form letterto that person. Inform that person he may be amillionaire.• Show less0 answers - Anonymous askedI have to write a binary search tree search program I have thebinary tree program i just need to be... Show moreI have to write a binary search tree search program I have thebinary tree program i just need to be able to search it Assignment Search the number in the tree. If the number is found, print thelocation of the number with respect to the root as (for example): The number XX is foundat: root=>L=>L=>R=>L. If the number is not found, it willprint “Number XX not found”. • Show less0 answers - Anonymous asked//A... Show moreRapunzel if you can get this airplane seating to end when allseats are filled. Here is the code //Airplane seatassignment #include<iostream> #include <cmath> using namespace std; const int MAX_ROW = 7; const int MAX_SEAT =4; void chooseseat(char[][MAX_SEAT]); void purchase(int,int,char[][MAX_SEAT]); voidclearseats(char[][MAX_SEAT]); void display_seating(char[][MAX_SEAT]); bool assign_seat(char[][MAX_SEAT], int rows, int row, int col); int main() { int row, col; int input_row,left; left=MAX_SEAT*MAX_ROW; char seat[MAX_ROW][MAX_SEAT],more='Y'; clearseats(seat); display_seating(seat); while(left>0&&toupper(more)=='Y') {chooseseat(seat); display_seating(seat); cout<<"choose another seat(Y/N)? "; cin>>more; } system("pause"); return 0; } void clearseats(charseats[][MAX_SEAT]) {int i,j; for(i=0;i<MAX_ROW;i++) for(j=0;j<MAX_SEAT;j++) seats[i][j]=(char)(65+j); //65='A' return; } void chooseseat(charseats[][MAX_SEAT]) {int row,col; char seatcol; do{ cout<<"Enter Seat row desired1-"<<MAX_ROW<<": "; cin>>row; while(row>MAX_ROW||row<1) //valid row? {cout<<"invalidrow\n"; cout<<"Enter Seatrow desired 1-"<<MAX_ROW<<": "; cin>>row; } row--; cout<<"Enter Seat desiredA-"<<(char)('A'-1+MAX_SEAT)<<": "; cin>>seatcol; seatcol=toupper(seatcol);//change to uppercase so that can always subtract 'A' col=seatcol-'A'; //by subtracting A, it changes A to 0, B to 1, C to 2, D to 3 while(col>=MAX_SEAT||col<0) //validseat? {cout<<col<<endl; cout<<"invalidseat\n"; cout<<"Enter Seatdesired A-"<<(char)('A'-1+MAX_SEAT)<<": "; cin>>seatcol; seatcol=toupper(seatcol); col=seatcol-'A'; } if(seats[row][col]=='X') //if seatvalid, mark it as "taken" cout<<"Seat already chosen-rechoose\n"; }while (seats[row][col]=='X'); seats[row][col]='X'; return; } void display_seating(char seats[][MAX_SEAT]) {int i,j; for(i=0;i<MAX_ROW;i++) {cout<<(i+1)<<" "; for(j=0;j<MAX_SEAT;j++) {cout<<seats[i][j]<<""; if(j%2!=0) cout<<" "; } cout<<endl; } return; }1 answer - Anonymous askedNeed to find which... Show moreList of memory address given:1, 134, 212, 1, 135, 213, 162, 161, 2, 44, 41, 221• Show less Need to find which cache design is best in terms of missrate.Given: total of 8words of dataC1: 1word blocksC2: 2word blocksC3: 4word blocks.Also if miss stall is 25cycles and C1 has 2cycles access time,C2 has 3cycles and C3 has 5cycles which design is best.0 answers - Anonymous askedFor 6... Show moreUsing data from cache performance for SPEC CPU2000 Benchmarks:a) apsi/facerecb) perlbmk/ammpFor 64KB data caches with varying set associativities, whatare the miss rates broken down by miss types(cold, capacity andconflict misses) for each benchmarks.• Show less0 answers - Albrittbrat askedI am having horrible and annoying problems when trying to passstring variables into and out of funct... Show moreI am having horrible and annoying problems when trying to passstring variables into and out of functions. And, more importantly,passing the ifstream and ofstream in and out of functions. I amusing them all as reference parameters, and I just keep gettingerrors. take the function of the following format: void iostream(ifstream&, ofstream&) //functionprototype iostream(infile, outfile) //function call void iostream(ifstream& infile, ofstream& outfile)//function header/definition start I also tried using a function call of the type iostream(ifstream& infile, ofstream& outfile) The first type of call gives the error: no match for call to'(std::iostream)(std::string&,std::string&)' The second type of call gives the error: expectedprimary-expression before '&' token I need to pass the current file stream in between around 10functions for the project for my class. Anyone got any ideas? • Show less1 answer - Anonymous askedAll element... Show moreI need to know how to create a matrix class which is n by mwhere n and m are integers...All elements of the matrix must be integers...I also need a constructor and destructor for the matrixclass...I need to have functions that add, subtract, multiply twomatrices...Functions that transpose a matrix and find the inverse of amatrix...Little help???• Show less0 answers - Anonymous askedint... Show more Anyone understand this puzzle? I am lost.• Show less // Variable Definitions //---------------------- int* pi; int* pj; int* pk; int t; double* pd; //----------------- // Some Statements //----------------- *pd += static_cast<double>(*pi); pi = &t; *pi = *pk; pj = pi; *pj /= 3; ++pj; ++*pj; //----------------------------------------------------------------------------- // Assuming the following initial configuration of memory (on the left side), // what is the resulting configuration of memory (on the right side) after the // above statements execute? //----------------------------------------------------------------------------- BEFORE AFTER __________ __________ | | | | 1100 | 9 | | | |__________| |__________| __________ __________ | | | | pi 1300 | 1100 | | | |__________| |__________| __________ __________ | | | | t 1350 | 14 | | | |__________| |__________| | | | | | 20 | | | |__________| |__________| __________ __________ | | | | pj 1380 | 1100 | | | |__________| |__________| __________ __________ | | | | pk 1400 | 1410 | | | |__________| |__________| __________ __________ | | | | 1410 | 7 | | | |__________| |__________| ____________________ ___________________ | | | | 1430 | 0.0 | | | |____________________| |___________________| __________ __________ | | | | pd 1440 | 1430 | | | |__________| |__________|0 answers - Anonymous askedall the instruct... Show morex.Hm program is written and working but needs to be re-written using dynamic arraysall the instruction is commented out at the top will rate lifesaver thanks you //Narrative: This program reads in a data file containing Olympic medal information // and prints out the statistics concerning medals won. // //Input: medals.dat input file // format: // total countries - int - occurs once // Country data - occurs for each country // - country name - string // - gold medals - int // - silver medals - int // - bronze medals - int // //Output: reference Fig. Olympics2 // //Constraints: The file is hardcoded in the program but if it can not be opened // display "Can't find file" and terminate program. // //Operations: // //1. Attach to file "medals.dat". //1a medals.dat information //Australia 9 9 22 //China 16 22 12 //Cuba 3 6 8 //France 15 7 15 //Germany 20 18 27 //Hungary 7 4 10 //Italy 13 9 12 //Poland 7 5 5 //Russia 26 21 16 //South.Korea 7 15 5 //Spain 5 11 6 //Ukraine 9 2 12 //United.States 23 32 26 //2. If unsuccessful - display error message and terminate program //3. get the number of countries present on the file //4. For every country // a. get the name, gold medals, silver medals and bronze medals won // b. total medals is the sum of gold, silver and bronze // c. calculate percentage of gold won // d. display data per Fig. Olympics1 // e. determine if gold won is the largest number against other countries // f. determine if total medals won are the largest or smallest against other countries // g. based on Steps e. and f. retain the country name for each category // - Highest gold medals won // - Highest medals won // - Lowest medals won //5. Display the countries that won the most gold, most medals and least number of medals per // Fig. Olympics2. //6. terminate program with "Program completed" message // //*** please note, I've included many comments to help you understand. If you were experienced with C++ //*** you would say that they're really not necessary and clutter the code. #include <iostream> //cin and cout #include <fstream> //data stream use #include <string> //for variable countryName - string variables/objects #include <iomanip> //formatting output using namespace std; //required for Standard C++ int main() { //define variables required int totCountries; string countryName; string maxGoldCountry; string maxMedalCountry; string minMedalCountry; int gold; int silver; int bronze; int totalMedals = 0; int maxGold = 0; int maxMedals = 0; int minMedals = 9000; //since you can't win this many - use setting a high value to compare to. double percentGold; ifstream ifile("medals.dat"); //opens medals.dat file. Must be in same folder as program if(ifile.fail()) //checks to see if file was opened { cout<< "Can't find file medals.dat"; return 0; // terminates program gracefully } //display headings to match Fig. Olympics2 output //*** it has to be done before we display the output ifile >> totCountries; //inputs only one of this value for the input data stream cout << "Total Countries participating: " << totCountries << endl; //*** display column headings cout << endl << "Country\t\tGold\tSilver\tBronze\tTotal\t%Gold" << endl; //***! remember \t is a tab ifile >> countryName >> gold >> silver >> bronze; //prime read of data for a country while(!ifile.eof()) //eof is a member function of istream - determines when data stops { //*** since we're here, we must have all data for a country totalMedals = gold + silver + bronze; //calculate total medals won percentGold = (double(gold)/totalMedals) * 100; //calculate % gold won and turn, ex. .5764 into 57.64 //but since both are type int - one has to be cast into //a double or we'll lose the decimal point on int/int division //then store the result into a double //*** display 1st part of output to meet Fig. Olympics2 criteria cout << endl << countryName; //*** since general output display to a console is based on 8 spaces per tab. If the field we want //*** to show is 8 or more than we have to adjust the \t or it will not align correctly. if(countryName.length() < 8) //look up basic_string for your compiler - this is a function of string { cout << "\t\t"; //*** 2 tabs because of alignment if under 8 char in size } else { cout << "\t"; //*** 1 tab since the size of countryName is 8 or larger } //*** display remaining information cout << gold << "\t" << silver << "\t" << bronze << "\t" << totalMedals; //*** you know about setting formating by now cout << fixed << showpoint << setprecision(1) << "\t" << percentGold << "%"; //*** working on steps 4e - 4g // e. determine if gold won is the largest number against other countries if( maxGold < gold ) { maxGold = gold; //hold this number because it is the largest for gold maxGoldCountry = countryName; //hold the country name } // f. determine if total medals won are the largest or smallest against other countries if( maxMedals < totalMedals ) { maxMedals = totalMedals; //hold this number because it is the largest medals won maxMedalCountry = countryName; //hold the country name } if( minMedals > totalMedals ) { minMedals = totalMedals; //hold this number because it is the smallest medals won minMedalCountry = countryName; //hold the country name } // g. based on Steps e. and f. retain the country name for each category //*** it is done based on the countryName ifile >> countryName >> gold >> silver >> bronze; //drive read next chunk of data for a country } //*** display final results based on Fig. Olympics2 cout << endl; //simple linefeed or could have been \n\n on next cout cout << "\nMost Gold Medals: " << maxGoldCountry << " with " << maxGold; cout << "\nMost Medals won: " << maxMedalCountry << " with " << maxMedals; cout << "\nLeast Medals won: " << minMedalCountry << " with " << minMedals; cout << "\n\n"; //two linefeeds for display before the "Press any..." message system("pause"); return 0; //required because main() returns int }0 answers
http://www.chegg.com/homework-help/questions-and-answers/computer-science-archive-2010-april-12
CC-MAIN-2014-23
refinedweb
4,819
62.48
Type: Posts; User: retry I create a test application in Visual C++ 2005 and buttons on dialogs are automatically XP style. When I convert an existing VC6 application to VC2005, the buttons are still old style. What do... Is the only way is to create dummy font and use SelectObject to get the device context font? CFont *pFont = pDC->SelectObject(&dummyFont); This does change the selected font of CDC which is... Thanks that is resloved. A follow up question though on different topic. I want to to initialize a vector, is that possible? something like: vector <string> names (10) = {"Mark", "Dave",... Yes, I do "using namespace std;" I didn't get how do I correct the problem? I commented #include "fstream.h" but it results in even more errors: first in the list is: error C2079: 'fout'... I have an ofstream object for file output which works great. ofstream fout; fout.open(sFileNAme, ios::out); ..... Now I added #include <vector> obviously to use vector and the moment I... I tried this but it didn't work properly. (The CScrollEdit class). It shows disabled scroll bars first but when I edit, it removes the scroll. I am in fact using this in a floating windowfrom... I am creating an edit box with the following code: if (!m_Edit.Create(ES_MULTILINE | WS_CHILD | WS_VISIBLE | WS_TABSTOP | ES_AUTOHSCROLL | ES_AUTOVSCROLL | ES_WANTRETURN,// | ES_READONLY, ... Works Great JohnCz, Thanks! Thanks it works now, I forgot to add to GetRightPane(): if(!m_wndSplitter.IsWindowVisible()) { return NULL; } When only the listview is shown, the styles (report, icon, list etc)... Thanks JohnCz, that is awesome! Wish there was that small close button in right corner of the tree view to close it from there and I would keep it as an option! I am trying to put the code in the... Can you tell me if the work needed is in which functions? I have used the MFC Application wizard to created Explorer like application which already gives two views. I just want to remove the... Hi, I have an MDI application with two splitter windows in my view. One is TreeView, second is ListView I want to remove the TreeView for now and want it to act as if it has one view the... struct StructA { int my_int; char my_name[20]; }; struct StructB { float my_float; }; strPath was already filled with the correct path and executable. This issue is fixed. I want to debug the 2nd executable now when it is called from my first program. Since its not a dll so I can... HINSTANCE hInstance = ShellExecute(GetSafeHwnd(),_T("open"),_T(strPath),_T(""),NULL,SW_SHOW);\ This executable pointed by strPath runs in dos prompt and when it is run independently its prompts a... I am using two CTextProgressCtrl on a dialog page and it shows only the default colors. Both are idential but I can change the color of one progress but can not do the same to the 2nd. The code... Anyone? There has to be something simpler! Range does have a Merge() function but I don't know what kind of parameter it receives. Its always dificult to get help with these functions. here in the... range = sheet.GetRange(COleVariant("A1"),COleVariant("B1")); range.SetValue(COleVariant("Hello")); The above code prints "Hello"two times each in cell A1 and B1. I want both the cells to be... I want to get the handle of another application which is an MFC MDI. I am using ::FindWindow(NULL, "Title"); which works but as you know in MDI the title changes when a new file is loaded. I... Instead of printf("%.2", float_value); I would like to define 2 as constant. #define PRECISION 2 and than use PRICISION instead of 2 in the printf. The reason for this that I can easily... CString myString = "Hello"; pDC->DrawText(myString, rect, DT_SINGLELINE | DT_RIGHT); I am using the above line to print something right aligned. It does the job correctly but if I changed the... The points go to g_gili, NormalizeRect() rect fixes the problem. Sometimes these things are now documented in MSDN that the rect should be normalized before calling DrawText()...can anybody shine... If i do pDC->Rectangle(rc); it draws the rectangle correctly where I want to draw the text. I want to draw text inside this rectangle, it does not draw text (with or without caling Rectangle()... vector <int> v1 (20); vector <int> v2; v2.reserve(20); Later in the code when I do: int c1 = v1.capacity(); int c2 = v2.capacity();
http://forums.codeguru.com/search.php?s=3eb23476fe73e9852958e695d9590336&searchid=7209555
CC-MAIN-2015-27
refinedweb
748
76.42
-g0 means no debug info, debugging above the asm level is in no way reliable. Try -g1 -g2 or -g3. In some situations gdb is not showing a backtrace (or, more precisly, its not showing the backtrace below current frame). The following example illustrates one such case. If set a breakpoint to line 5 (before a function prologue is executed), the backtrace is correct, but if you continue to the next line (or set a breakpoint to line 6), the backtrace is showing correctly only the innermost stack frame. test.cpp #include <iostream> using namespace std; void foo() { // line 5 - function prologue char c[1]; cout << c << endl; } int main() { foo(); return 0; } D:\>g++ -g -O0 test.cpp -o test.exe D:\>gdb test.exe GNU gdb (rubenvb-4.7.2-release) 7.5.50.20120920-w64-mingw32". For bug reporting instructions, please see: <mingw-w64-public@lists.sourceforge.net>... Reading symbols from D:\test.exe...done. (gdb) break test.cpp:5 Breakpoint 1 at 0x401e81: file test.cpp, line 5. (gdb) start Temporary breakpoint 2 at 0x401fc0: file test.cpp, line 12. Starting program: D:\test.exe [New Thread 3524.0x13c4] Temporary breakpoint 2, main () at test.cpp:12 12 foo(); (gdb) continue Continuing. Breakpoint 1, foo () at test.cpp:5 5 { // line 5 - function prologue (gdb) bt #0 foo () at test.cpp:5 #1 0x0000000000401fc5 in main () at test.cpp:12 (gdb) next 7 cout << c << endl; (gdb) bt #0 foo () at test.cpp:7 #1 0x0000000000000000 in ?? () It seems that it is connected with the generated function prologue. If you change the line 6 to 'char c = 0;' than the backtrace is correct (and the disassembly of the function prologue looks quite different in this case). Another notice is that if you compile with -fno-dwarf2-cfi-asm option, the backtrace is also correct. -g0 means no debug info, debugging above the asm level is in no way reliable. Try -g1 -g2 or -g3. Have you tried with the latest GCC and GDB release? Other than that, please contact the upstream projects, namely gdb at sourceware.org mailing list and the gdb bug tracker. You're right, I forgot to check the latest unstable release of gcc 4.8, my fault. The gdb seems to be working ok with the example above. I can't compile a larger project with it to check it with some more complex code. Log in to post a comment.
https://sourceforge.net/p/mingw-w64/bugs/328/
CC-MAIN-2017-30
refinedweb
409
78.75
Re: Choosing DNS Name From: Todd J Heron (todd_heron_no_spam_at_hotmail.com) Date: 02/27/05 - Next message: Todd J Heron: "Re: NT 4 DC's in 2003 AD" - Previous message: Brian Roberds: "Re: Choosing DNS Name" - In reply to: Brian Roberds: "Re: Choosing DNS Name" - Messages sorted by: [ date ] [ thread ] Date: Sat, 26 Feb 2005 23:56:06 -0500 There are different answers to this classic question and while these answers ultimately depend upon company preference, much of the direction will be based upon administrator experience. The three basic options outlined below are the most commonly given answers to the question, sometimes altogether and sometimes not. Some company networks use a combination of these options. When explaining it to a relative beginner asking the question, I usually see all three options laid out or at least mentioned in some form or the other. option 1, although it is the most DNS-intensive over time. If you do not select this option and go with option 2 or 3 only, consideration will have to be given to the fact that company end-users will need to be trained on using different names under different circumstances (based on where they are (at work, on the road or at home).). 2) option: Option 2: Delegated subdomain. This is subdomain of the public DNS zone. For example, externaldnsdomain.com and subdomain.externaldnsname.com. Advantages: 1) Like Option 1, this method also isolates the internal company network but note this is at the same time a disadvantage (see below). 2) Better than Option 1, internal company (Active Directory) clients can resolve external resources in the public DNS zone easily, once proper DNS name resolution mechanism such as forwarding, secondary zones, or delegation zones are set up. 3) Better than Option 1, DNS records for the public DNS zone do not need to be manually duplicated into the internal AD/DNS zone. 4) Better than Option 1, VPN clients accessing the internal company network from the Internet can easily navigate into the internal subdomain. It is very reliable as long as the VPN stays connected. Disadvantages: 1) While there is security in an isolated subdomain, there is potential for expose. 2) Longer DNS namespace. This may not look appealing (or "pretty") to the end-users. The option. Still re-wording my notes on this one. This option is usually best for beginners b/c it's the easiest to implement. But makes VPN resolution difficult (like option 1) and Exchange headers when examined closely will show the company internal AD name which looks unprofessional. You can use any extension you want here such as .ad, .int, .lan, etc... -- Todd J Heron, MCSE Windows Server 2003/2000/NT ---------------------------------------------------------------------------- Note: I do not top-post or bottom-post so that my responses are always easy to read in this forum and the Google Archives. This posting is provided "as is" with no warranties and confers no rights. - Next message: Todd J Heron: "Re: NT 4 DC's in 2003 AD" - Previous message: Brian Roberds: "Re: Choosing DNS Name" - In reply to: Brian Roberds: "Re: Choosing DNS Name" - Messages sorted by: [ date ] [ thread ]
http://www.tech-archive.net/Archive/Windows/microsoft.public.windows.server.active_directory/2005-02/1954.html
crawl-002
refinedweb
523
51.89
How to Fill Login Forms Automatically We often have to write spiders that need to login to sites, in order to scrape data from them. Our customers provide us with the site, username and password, and we do the rest. The classic way to approach this problem is: - launch a browser, go to site and search for the login page - inspect the source code of the page to find out: - which one is the login form (a page can have many forms, but usually one of them is the login form) - which are the field names used for username and password (these could vary a lot) - if there are other fields that must be submitted (like an authentication token) - write the Scrapy spider to replicate the form submission using FormRequest (here is an example) Being fans of automation, we figured we could write some code to automate point 2 (which is actually the most time-consuming) and the result is loginform, a library to automatically fill login forms given the login page, username and password. Here is the code of a simple spider that would use loginform to login to sites automatically: from scrapy.spider import BaseSpider from scrapy.http import FormRequest from loginform import fill_login_form class LoginSpider(BaseSpider): start_urls = [""] login_user = "foo" login_pass = "bar" def parse(self, response): args, url, method = fill_login_form(response.url, response.body, self.login_user, self.login_pass) return FormRequest(url, method=method, formdata=args, callback=self.after_login) def after_login(self, response): # you are logged in here In addition to being open source, loginform code is very simple and easy to hack (check the README on Github for more details). It also contains a collection of HTML samples to keep the library well-tested, and a convenient tool to manage them. Even with the simple code so far, we have seen accuracy rates of 95% in our tests. We encourage everyone with similar needs to give it a try, provide feedback and contribute patches. We contributed this project to the Scrapy group to better encourage community adoption and contributions. Like w3lib and scrapely, loginform is completely decoupled and not dependent on the Scrapy crawling framework.
https://blog.scrapinghub.com/2012/10/26/filling-login-forms-automatically
CC-MAIN-2019-30
refinedweb
357
53.34
Enjoy! interface N_Queens <N : Univ_Integer := 8> is // Place N queens on an NxN checkerboard so that none of them can // "take" each other. type Chess_Unit is new Integer_Range<-100 .. 100>; // An integer type sufficiently big to represent values -100 to +100 const Rows : Range<Chess_Unit> := 1..N; const Columns : Range<Chess_Unit> := 1..N; type Row is Chess_Unit {Row in Rows}; // A subrange in 1..N type Column is Chess_Unit {Column in Columns}; // A subrange in 1..N type Solution is Array<optional Column, Row>; // A "solution" is an array of Column's, indexed by "Row." // It indicates in which Column a queen of the given Row is located // An example solution would be: 2 8 6 1 3 5 7 4 // meaning that the queen in row 1 is at column 2, // the queen in row 2 is at column 8, the queen in // row 3 is at column 6, and so on. func Place_Queens() -> Vector<Solution> {for all Sol of Place_Queens => for all Col of Sol => Col not null}; // Produce a vector of solutions, with the requirement // that for each solution, there are non-null column numbers // specified for each row of the checkerboard. end interface N_Queens; class N_Queens is type Sum_Range is Chess_Unit {Sum_Range in 2..2*N}; // Sum_Range is used for diagonals where the row+column is the // same throughout the diagonal. type Diff_Range is Chess_Unit {Diff_Range in (1-N) .. (N-1)}; // Diff_Range is used for diagonals where row-column is the // same throughout the diagonal. type Sum is Countable_Set<Sum_Range>; // This type of set keeps track of which Sum_Range diagonals // have a queen on them already. type Diff is Countable_Set<Diff_Range>; // This type of set keeps track of which Diff_Range diagonals // have a queen on them already. interface Solution_State<> is // We build up a solution state progressively as we move // across the checkerboard, one column at a time. func Initial_State() -> Solution_State; func Is_Acceptable(S : Solution_State; R : Row) -> Boolean; // Is_Acceptable returns True if the next queen could be // place in row R. func Current_Column(S : Solution_State) -> Column; // Current_Column indicates which column we are working on. func Next_State(S : Solution_State; R : Row) -> Solution_State; // Next_State returns a Solution_State produced by // adding a queen at (Current_Column(S), R). func Final_Result(S : Solution_State; R : Row) -> Solution; // Final_Result returns a result produced by adding a queen // at (Columns.Last, R) to a solution with all other columns // placed. end interface Solution_State; class Solution_State is const C : Column; // Current column const Trial : Solution; // Trial solution, some col#s still null const Diag_Sum : Sum; // Set of "sum" diagonals in use const Diag_Diff : Diff; // Set of "diff" diagnoals in use exports func Initial_State() -> Solution_State is return (C => 1, Trial => Create(Rows, null), Diag_Sum => [], Diag_Diff => []); end func Initial_State; func Is_Acceptable(S : Solution_State; R : Row) -> Boolean is // Is_Acceptable returns True if the next queen could be // place in row R. return S.Trial[R] is null and then (R+S.C) not in S.Diag_Sum and then (R-S.C) not in S.Diag_Diff; end func Is_Acceptable; func Current_Column(S : Solution_State) -> Column is // Current_Column indicates which column we are working on. return S.C; end func Current_Column; func Next_State(S : Solution_State; R : Row) -> Solution_State is // Next_State returns a Solution_State produced by // adding a queen at (Current_Column(S), R). return (C => S.C+1, Trial => S.Trial | [R => S.C], Diag_Sum => S.Diag_Sum | (R+S.C), Diag_Diff => S.Diag_Diff | (R-S.C)); end func Next_State; func Final_Result(S : Solution_State; R : Row) -> Solution is // Final_Result returns a result produced by adding a queen // at (Columns.Last, R) to a solution with all other columns // placed. return S.Trial | [R => S.C]; end func Final_Result; end class Solution_State; exports func Place_Queens() -> Vector<Solution> {for all Sol of Place_Queens => for all Col of Sol => Col not null} // Produce a vector of solutions, with the requirement // that for each solution, there are non-null column numbers // specified for each row of the checkerboard. is var Solutions : concurrent Vector<Solution> := []; *Outer_Loop* for State : Solution_State := Initial_State() loop // Iterate over the columns for R in Rows concurrent loop // Iterate over the rows if Is_Acceptable(State, R) then // Found a Row/Column combination that is not on any diagonal // already occupied. if Current_Column(State) < N then // Keep going since haven't reached Nth column. continue loop Outer_Loop with Next_State(State, R); else // All done, remember trial result with last queen placed Solutions |= Final_Result(State, R); end if; end if; end loop; end loop Outer_Loop; return Solutions; end func Place_Queens; end class N_Queens; func Test_N_Queens() is type Eight_Queens is N_Queens<8>; var Results := Eight_Queens::Place_Queens(); Println("Number of results = " | Length(Results)); for I in 1..Length(Results) forward loop const Result := Results[I]; Print("Result #" | I); for J in 1..Length(Result) forward loop Print(" " | [[Result[J]]]); end loop; Print('\n'); end loop; end func Test_N_Queens; Here is the result of running Test_N_Queens, which is set up to solve the 8-queens problem. It has also been verified to work with 4 queens (2 solutions), 5 queens (10 solutions), and 9 queens (352 solutions). After "quit"ing, a display of threading statistics is provided. Parsing aaa.psi Parsing n_queens4.psl ---- Beginning semantic analysis ---- 58 trees in library. Done with First pass. Done with Second pass. Done with Pre codegen pass. Done with Code gen. Command to execute: Test_N_Queens Number of results = 92 Result #1 4 2 5 8 6 1 3 7 Result #2 1 7 4 6 8 2 5 3 Result #3 4 2 8 5 7 1 3 6 Result #4 1 5 8 6 3 7 2 4 Result #5 4 1 5 8 6 3 7 2 Result #6 2 7 3 6 8 5 1 4 Result #7 7 1 3 8 6 4 2 5 Result #8 5 2 4 6 8 3 1 7 Result #9 5 7 1 3 8 6 4 2 Result #10 5 1 8 6 3 7 2 4 Result #11 1 6 8 3 7 4 2 5 Result #12 4 2 7 3 6 8 1 5 Result #13 3 1 7 5 8 2 4 6 Result #14 3 6 2 7 5 1 8 4 Result #15 5 1 4 6 8 2 7 3 Result #16 6 4 2 8 5 7 1 3 Result #17 3 6 2 5 8 1 7 4 Result #18 1 7 5 8 2 4 6 3 Result #19 3 7 2 8 5 1 4 6 Result #20 2 6 1 7 4 8 3 5 Result #21 3 7 2 8 6 4 1 5 Result #22 4 6 8 2 7 1 3 5 Result #23 4 1 5 8 2 7 3 6 Result #24 7 4 2 8 6 1 3 5 Result #25 3 6 8 2 4 1 7 5 Result #26 5 1 8 4 2 7 3 6 Result #27 7 4 2 5 8 1 3 6 Result #28 4 7 5 2 6 1 3 8 Result #29 7 3 8 2 5 1 6 4 Result #30 5 7 2 6 3 1 8 4 Result #31 5 7 2 4 8 1 3 6 Result #32 4 7 3 8 2 5 1 6 Result #33 4 7 1 8 5 2 6 3 Result #34 7 3 1 6 8 5 2 4 Result #35 6 3 7 2 8 5 1 4 Result #36 6 1 5 2 8 3 7 4 Result #37 4 8 1 5 7 2 6 3 Result #38 6 3 1 7 5 8 2 4 Result #39 6 3 7 2 4 8 1 5 Result #40 6 4 1 5 8 2 7 3 Result #41 5 7 2 6 3 1 4 8 Result #42 5 7 1 4 2 8 6 3 Result #43 3 5 2 8 1 7 4 6 Result #44 4 6 1 5 2 8 3 7 Result #45 2 7 5 8 1 4 6 3 Result #46 5 3 1 6 8 2 4 7 Result #47 4 2 7 5 1 8 6 3 Result #48 6 3 1 8 5 2 4 7 Result #49 3 8 4 7 1 6 2 5 Result #50 6 8 2 4 1 7 5 3 Result #51 5 3 1 7 2 8 6 4 Result #52 2 5 7 4 1 8 6 3 Result #53 3 6 2 7 1 4 8 5 Result #54 6 3 1 8 4 2 7 5 Result #55 4 2 8 6 1 3 5 7 Result #56 8 3 1 6 2 5 7 4 Result #57 3 5 8 4 1 7 2 6 Result #58 4 8 1 3 6 2 7 5 Result #59 6 3 5 8 1 4 2 7 Result #60 6 3 7 4 1 8 2 5 Result #61 8 4 1 3 6 2 7 5 Result #62 8 2 5 3 1 7 4 6 Result #63 6 3 5 7 1 4 2 8 Result #64 4 8 5 3 1 7 2 6 Result #65 7 2 6 3 1 4 8 5 Result #66 2 4 6 8 3 1 7 5 Result #67 5 2 4 7 3 8 6 1 Result #68 3 5 2 8 6 4 7 1 Result #69 4 6 8 3 1 7 5 2 Result #70 4 7 5 3 1 6 8 2 Result #71 3 6 4 2 8 5 7 1 Result #72 2 6 8 3 1 4 7 5 Result #73 5 7 4 1 3 8 6 2 Result #74 7 5 3 1 6 8 2 4 Result #75 4 2 7 3 6 8 5 1 Result #76 6 4 7 1 8 2 5 3 Result #77 5 2 6 1 7 4 8 3 Result #78 7 2 4 1 8 5 3 6 Result #79 6 2 7 1 3 5 8 4 Result #80 8 2 4 1 7 5 3 6 Result #81 3 6 8 1 5 7 2 4 Result #82 5 2 8 1 4 7 3 6 Result #83 5 3 8 4 7 1 6 2 Result #84 3 6 8 1 4 7 5 2 Result #85 5 8 4 1 7 2 6 3 Result #86 3 6 4 1 8 5 7 2 Result #87 3 5 7 1 4 2 8 6 Result #88 6 2 7 1 4 8 5 3 Result #89 6 4 7 1 3 5 2 8 Result #90 5 8 4 1 3 6 2 7 Result #91 2 5 7 1 3 8 6 4 Result #92 2 8 6 1 3 5 7 4 Command to execute: quit Threading Statistics: Num_Initial_Thread_Servers : 10 Num_Dynamically_Allocated_Thread_Servers : 0 Max_Waiting_Threads (for server task): 74 Max_Active : 118 Max_Active_Masters : 133 Max_Sub_Threads_Per_Master : 87 Max_Waiting_For_Threads (to finish): 37171
http://parasail-programming-language.blogspot.com/2011/09/n-queens-join-party.html
CC-MAIN-2018-22
refinedweb
1,830
62.04
) ) derosa (1) Bobby. Tutorial: Working with Toolbars in C# Jan 30, 2001. This tutorial explains you how to add toolbars to a form, load images to the toolbar buttons, and writing event handlers for toolbar buttons.. Buton Viewer: View Images Feb 27, 2001. Well, In .NET, the Image class is a wonderful class to view images. No matter what control you have, you just set the Image property of that control to an image and the control will display the image. Neat? Mar 13, 2001. In .NET framework, the Icon class represents a Windows icon, which is a small bitmap image used to represent an object. The icon class is defined in System.Drawing namespace. Graphics Animator in C# May 26, 2001. This program will generate a html page with animated gif. You just need at least 2 gifs and use the program to set the time to display each image.. Working with Status Bars Aug 01, 2001. An article on how work with status bars and pens and images to the pens. A variety of Chart Engines Sep 07, 2001. The original code came from Scott Guthrie’s chart engine example. The differences from original code.. Screen Capturing a Form in .NET - Using GDI and GDI+ Sep 15, 2001. This article shows way to do form capture in GDI is to get the device context to the screen and bit blast it to a Bitmap in memory.. Image Viewer in C# Feb 01, 2002. This program allows you to open and view image files including JPEG, GIF, WMF and other images. Mar 19, 2002. This is a memory game where you can use your favorite pictures (.bmp, jpg, gif).. Creating Graphics with XML Apr 09, 2002. This article shows how to create images on the fly and uses XML to specify the properties of the images.. Viewing Multiple Images May 08, 2002. I'm writing this article in response to a question on discussion forums, How do I view multiple images on top of each other?. Owner Draw ListBox Control with Images Aug 05, 2002. In this article we will see how to write owner drawn ListBox control. A Virtual Photo Album in C# and .NET Aug 05, 2002. This album allows you to drag your images directly from Windows Explorer into the spot you want your picture to occupy. You can also edit the captions by clicking on the labels under the pictures.. HJ PDF in C# Oct 31, 2002. This program allows you to download all Italian Hacker Journal issues into PDF files for free... Making Thumbnails of Transparent Images in .NET and C# Mar 28, 2003. When I started writing web applications using .NET, I found myself in need to dynamically create thumbnails of images that could be uploaded by the user or pulled from a database. HTTP Handlers for Images in ASP.NET Jun 23, 2003. Have you ever thought of streaming thumbnails just by passing query string indicating width or height of thumbnail you need, and most importantly passing those to image itself? Enhanced XP Button Control Dec 12, 2003. The enhanced XP style button is very easy to use and it supports rectangle, circle or ellipse shape with image and different colors. This control also inherit most of the properties from the Forms.Button. Image Resizing and FTP Dec 24, 2003. I wanted a program to resize image and just FTP them to my site. After talking with friends, I realized they also had the same problems. So I built this simple .Net application. Screen Capture and Save as an Image Dec 30, 2003. The following example source code shows how to capture the screen and save it to an image.. Transporting and Displaying Images using DIME and HTTP Handlers Apr 28, 2004. This article shows an example of how to display images stored in a database in a virtual fashion using a Web Service in conjunction with an HTTP Handler.. Storing Images into a Database Oct 18, 2004. In order to provide your application with cool pictures you can employ two techniques (at least). One of them is that you can save the pictures in a folder and store the path to each one in a database or configuration file. The other one is to store the entire file into a database, along with its file name. Pocket PC 2003 : Saving the Signature as a Bitmap Feb 15, 2005. The System.Drawing.Graphics namespace is commonly used for almost any forms in the desktop framework, hence it has got lots of facilities to draw any kind of image on to the device context.. Using the AnyButton to Create Dynamic Image Buttons Jun 07, 2005. This article describes how to use the AnyButton server control and explains a few extra features. Using the AnyButton to Create Dynamic Image Buttons Jun 07, 2005. This article describes how to use the AnyButton server control and explains a few extra features..
http://www.c-sharpcorner.com/tags/image-slideshow
CC-MAIN-2016-36
refinedweb
825
75.61
I want to change the text of a Button on clicking it in Unity. I am new to C#. Kindly help me out! The script which i added to my Button Element using UnityEngine; using System.Collections; using UnityEngine.UI; public class Buttontextchange : MonoBehaviour { Text Buy; // Use this for initialization void Start () { Buy = transform.FindChild("Text").GetComponent<Text>(); } // Update is called once per frame void Update () { } public void clicked() { Debug.Log("Button Buy Clicked!"); Buy.text = "i am a button!"; } } Your problem comes from the setup of your text and buttons. The Buttontextchange component is on Buttontext object. I can see on the picture that object has no child. But you run: void Start () { Buy = transform.FindChild("Text").GetComponent<Text>(); } which is where you are probably getting the error. The Text object is under the Button object so you could just pass it in the onClick call. public class Buttontextchange : MonoBehaviour { public void clicked(Text textRef) { Debug.Log("Button Buy Clicked!"); textRef.text = "i am a button!"; } } Then in the inspector you drag the text object into the parameter slot.
https://codedump.io/share/6OOBVH7StNYz/1/how-to-change-the-text-of-a-button-on-clicking-it-in-unity
CC-MAIN-2017-51
refinedweb
180
71.21
Home > Project Euler, python > Project euler #38 Project euler #38 novembre 30, 2012 Lascia un commento Go to comments? python: import time ts = time.time() def is_pandigital(n): digits = range(1,10) num = [int(n) for n in str(n)] num.sort() return num == digits panmax = 123456789 # min 1-9 pandigital for n in xrange(1, 10000): res = '' for m in xrange(1, 10): res += str(n * m) if len(res) == 9 and is_pandigital(res): if int(res) > panmax: panmax = int(res) print panmax print time.time() - ts Annunci Categorie:Project Euler, python What’s up, I read your blogs like every week. Your humoristic style is awesome, keep doing what you’re doing!
https://bancaldo.wordpress.com/2012/11/30/project-euler-38/
CC-MAIN-2017-26
refinedweb
114
72.36
RS900 / RS901 SERIES VI OPERATING INSTRUCTIONS **IMPORTANT NOTES:- FOR RS901 MODEL ONLY** RS901 Model is an add-on/expansion unit, without remotes or an antenna that must be controlled by an existing alarm or keyless entry system. The “Infinity Run” feature is not available on an RS-901 system. Most of the remote start features can be controlled through an existing factory or aftermarket remote keyless entry or alarm system. Pressing a auxiliary button on an Aftermarket system or pressing a button 3 times on a Factory keyless remote can activate a remote start using the 901. This is referred to in this manual as activating the “Green Start input wire”. *IMPORTANT INFORMATION: Primary and Optional Features -PRIMARY: These are features that must be connected in order for the system to operate properly i.e. Remote Start connections, Flashing lights, Brake Reset, etc. . TECHNICAL SUPPORT: (800) 998-6880 Monday - Friday 8:00am - 4:30pm Pacific Std. Time Web Site: E-mail: email@crimestopper.com CRIMESTOPPER SECURITY PRODUCTS, INC. 1770 S. TAPO STREET, SIMI VALLEY, CA. 93063 REV A - 6.2003. TABLE OF CONTENTS Operation Cautions & Warnings…….……………..….…………………………………….…………………………2 Using the Remote Transmitter…………………………………………………………………………………...…….3 Remote Engine Control…………….…..…………………………………………………………………….……….3-6 Turbo Timer Mode……………………………….……………………………………...………………………………7 Convenience and Safety Features……………………………….……………………………………...……..……7-9 Transmitter Programming….…………….…………………………………………….………………………...…9-10 2 Vehicle Operation.…………………………………….………………...……………………..…………….………10 Troubleshooting “Before You Call” Section……………..………………………………………………………..….11 OPERATION CAUTIONS & WARNINGS CRIMESTOPPER SECURITY PRODUCTS, INC. and its VENDORS shall not be liable for any accident resulting from the use of this equipment. This system is designed to be professionally installed into a car or vehicle in which all items, such as parking brake and all associated components, door switches, transmission shift linkage, throttle linkage, and all engine safety features, are in perfect working condition. DO NOT install the Remote Engine Starting System on MANUAL TRANSMISSION vehicles. If accidentally left in gear the vehicle could become a self-propelled threat to life and property. IT IS ABSOLUTELY THE OWNER’S SOLE RESPONSIBILITY TO: A) Understand the operation of this system and its safety features. B) Check for proper operation of the system prior to accepting delivery of the vehicle from the installation facility. C) Check and maintain the condition of the vehicle and all items relative to the proper operation of this system and its safety features. D) Always leave the doors and windows closed and locked to protect against accident and theft. DO NOT remote start the vehicle in a closed garage. Make sure that the garage door is open or there is adequate ventilation. Failure to observe this rule could result in injury or death from poisonous Carbon Monoxide fumes. USING THE REMOTE TRANSMITTER The transmitter supplied with the RS-900 system has Four (4) buttons along with a slide switch on the side for multi-car operation. See Page 10 for 2-Car operation. The button configuration on the RS-900 is Factory-set and unchangeable. The RS901 model does not include remote transmitters as it is designed for the expansion of an existing remote-controlled host or parent system. #2 UNLOCK #1 LOCK #5 CAR 1-2 #3 TRUNK START #4 REMOTE START TRANSMITTER BUTTONS REMOTE ENGINE CONTROL REMOTE ENGINE STARTING - SUCCESSFUL START: 1) Press the remote start button for at least 1 second. (For RS901 models, activate Green Start input wire.) 2) Parking lights flash once; return solid, then Ignition/Acc turn on. 3) After a few seconds the Starter Motor engages, Parking lights and Acc circuits will turn off while cranking. 4) Engine Starts and Runs. Parking Lights and Acc turn back on, Doors Lock. 5) Engine will remain running for programmed run time until reset with Brake pedal. If needed, the engine can be turned off with remote transmitter by pressing and releasing the Start button. (For RS901 model, activate the Green Start input wire. SOLID FLASH 1X START THEN SOLID IGN above of "Successful Start". 2) If Third attempt fails to start engine, the system will turn off and doors will remain locked. NO FURTHER ATTEMPTS WILL BE MADE AUTOMATICALLY TURNING OFF A REMOTE STARTED ENGINE: 1) Engine is running in Remote Start (Parking lights ON). 2) Press and release the remote start button. (For RS901 model, activate Green Start input wire.) 3) Engine & parking lights OFF, Doors re-lock/re-arm. START IDLE DOWN MODE: This mode allows the unit to take over operation of the parked vehicle while the ignition key is removed and you exit the vehicle. The vehicle is put into a remote running condition before you exit and it will remain running for the programmed run time or until you come back. Examples: • You pull up to a convenience store for a quick stop, "Idle Down" mode keeps engine running when you exit the vehicle, (with keys in hand) remote lock doors or arm alarm. When you return, unlock, turn ignition ON and drive away. or until you return (whichever comes first). SOLID IGN START OFF UNLOCK ENTERING A VEHICLE DURING “IDLE-DOWN” or “INFINITY RUN” MODES: 1) With engine running in "IDLE DOWN" (parking lights ON), unlock door via remote or key. 2) Enter vehicle and be careful not to step on brake pedal! (Remote Start Reset) 3) Turn Ignition to ON/RUN position, then depress brake pedal to reset the Remote Starter. Parking lights will turn off indicating the Remote Start is OFF and Vehicle is running by the Key. Drive away as normal. INFINITY RUN MODE (NOT AVAILABLE ON RS-901 MODEL) This mode can only be engaged when "Idle Down" is being engaged. Infinity mode allows the vehicle engine to remain running INDEFINITELY after the programmed run time elapses. This mode will allow the vehicle to be left running and unattended without the ignition key in the switch preventing the vehicle from being stolen. This mode can be beneficial to law enforcement or commercial trucks that need to remain running unattended for long periods of time. See next page for Infinity mode steps. REMOTE ENGINE CONTROL INFINITY RUN MODE – EXITING THE VEHICLE: (NOT AVAILABLE ON RS901 MODEL) 1) With vehicle engine running with the key, press the Remote Start button for at least 1 second, pause a few seconds, then press and release the remote start button a second time. 2) Parking Lights will start flashing,. IGN START 2X OFF FLASH FOR PROGRAMMED RUN TIME, THEN SOLID TIMED 4 HOUR SELF START MODE This mode allows the vehicle to be programmed to self-start every 4 hours and run for the programmed run time. This can be helpful during extremely cold conditions where engine fluid freeze-up is a concern. Be sure that the vehicle is outdoors or in a well ventilated area. Once the timed self-start mode is set, the unit will start every 4 hours and run for the programmed time. To reset this mode, either start the vehicle with the key or via remote control. 1) Engine should be running with the Key. Press the Remote Start button for at least 1 second. (For RS901 model, activate Green start input wire.) Lights will turn on signaling the remote start has turned on and doors will unlock. 2) Within 10 seconds press and release the valet/program button once. 3) Parking Lights will turn OFF for about 5 seconds. 4) Turn Ignition switch OFF, remove key and exit the vehicle. Engine should remain running. 5) Once outside the vehicle, press and release the remote start button to turn off engine. (For RS901 model, activate Green Start input wire.) Doors will lock and the parking lights will flash 4 TIMES as a confirmation that the unit is in Timed Self-Start Mode. 6) The vehicle will Start by itself every 4 hours until driven with key or started via the remote control.. This mode requires the use of an extra part called a momentary switch or button that is not included with the kit. Check with your installer about adding this feature. 1) 2) 3) 4) Engine should be running with the Key. Press and hold the brake pedal. Press your “Turbo Timer” button 1 to 5 times for each minute of run time you desire. (1 press = 1 min.) Wait for light/horn pulse to confirm your button presses (1 pulse for every press). Release brake pedal, turn Ignition switch OFF, remove key and exit the vehicle. Remote lock your doors for safety. The engine should remain running for the selected number of minutes. CONVENIENCE AND SAFETY FEATURES KEYLESS ENTRY (POWER DOOR LOCK CONTROL, Optional) This system enables you to remotely lock and unlock the vehicle’s doors (if equipped with power locks) via remote control for safety and convenience. Note: This feature may require extra labor and/or parts to install. REMOTE LOCK / UNLOCK (Optional) Press the Lock or Unlock transmitter button as you leave or come near the vehicle. Parking lights will flash once for lock and twice for unlock. If vehicle had been remote started, the lights will flash, but return back to solid indicating engine is still under control of the remote starter. DOOR LOCK NOTES: Doors lock automatically when vehicle is Remote Started for safety. If your system has been setup with an optional starter kill relay, but you do not have power door locks, note the following: The lock and unlock buttons on the remote control must still be utilized to operate the Starter disable feature. REMOTE PANIC (Only used with Optional HORN HONK) For personal safety this unit now includes a panic feature. To sound the vehicle car horn, press the Lock Button on the remote for more than 2 seconds. The vehicle horn will honk along with flashing parking lamps for 1 minute. Reset Remote Panic by pressing either the lock or unlock button. HORN CHIRP/HONK OUTPUT (Optional: with Horn connection/Horn option programming) This feature, if installed, will provide audible confirmation chirps from the factory horn for lock and unlock. When using this feature, pressing the Lock or Unlock button a 2nd time within 3 seconds will provide a horn chirp for audible confirmation. The system can also be programmed to provide 3 chirps when a remote start is requested using the remote. Note: Horn honk/chirp feature may require extra labor and/or parts to install. CONVENIENCE AND SAFETY FEATURES REMOTE TRUNK RELEASE OR DOMELIGHT ILLUMINATION (Optional) The CoolStart system includes an output that can be programmed to remotely release a factory electronic trunk or illuminate the interior light when you unlock your vehicle for lighted entry at night. If you have the optional trunk pop installed, simply press and release the Trunk Button #3 on the transmitter to remotely open trunk. If your system is programmed for Dome Light illumination, then it will work automatically lighting the dome light for 30 seconds when you unlock your vehicle via the remote. The dome light will turn off after 30 seconds, turning the key on whichever comes first. Trunk Pop or Dome Light Illumination may require extra labor and/or parts to install. 6 seconds. The LED will turn on solid and the system is now in valet. Perform this procedure again to exit of Valet mode. The keyless entry will still function normally while in valet mode. In the event of a lost or broken transmitter, perform this step to override the Starter Disable (if installed). ANTI-GRIND / STARTER DISABLE (Optional) This Optional feature prevents the user from accidentally grinding the starter if the Ignition key is turned too far to the start position while engine is already running from the remote starter. The Anti-Grind/Starter Disable requires the use of an external relay. This system must be programmed to allow the relay to work as a starter disable. PASSIVE STARTER DISABLE (Optional) This RS900 includes a programmable feature to allow the Optional Starter Disable to activate automatically 1 minute after the ignition is turned off. This programmable feature may provide insurance discounts or meet an insurance requirement in your providence. HOOD OPEN SAFETY (Requires grounding hood pin installation) Prevents the engine being Remote Started when hood is open and will shut OFF the engine if opened during a remote start. Eliminates risk of injury to someone working under the hood of the vehicle with a properly working hood pin installed. If Remote Start button is pressed with the hood open, the lights will flash once and the unit will not attempt a start. BRAKE PEDAL RESET Prevents starting or shuts off a remote started vehicle when this circuit is active or activated. Prevents unauthorized tampering. This circuit shuts the system down immediately when brake pedal is pressed if key is not in ignition and turned ON. CONVENIENCE AND SAFETY FEATURES OEM ALARM INTERFACE This feature is designed to Disarm and Re-arm Factory equipped security systems in conjunction with remote start and keyless entry (if needed for your vehicle). This feature will maintain the original integrity and security of your vehicle’s factory equipped systems before, during, or after remote start. NOTE: When changing, charging, or jumpstarting the vehicle’s battery we recommend removing the main power fuses located on the heavy gauge RED wires near the remote start module. TRANSMITTER PROGRAMMING Note: All transmitter codes must be learned at time of programming!! The RS900 allows storage of up to 4 different transmitter codes. 1. 2. 3. 4. Open Hood. Turn key to the ON position. (Doors will lock if Autolock is programmed) Press Programming button 4 times, then after a few seconds the unit flashes the parking lights 4 times. Press button #1 of the transmitter to be coded. You should get 2 light flashes indicating the unit is waiting for a 2nd code, then press button #1 of a second transmitter, the unit will flash 3 times indicating its waiting for the 3rd code and 4 flashes for the 4th code. If all 4 codes are learned, the unit will automatically exit code learning mode, otherwise turn key off and close hood. See diagram below. SEE TRANSMITTER PROGRAMMING DIAGRAM – NEXT PAGE TRANSMITTER PROGRAMMING DIAGRAM IGN OFF WAIT FOR 4 FLASHES (GRAY WIRE GROUNDED) PRESS 4X's IGN OFF START FLASH 2, 3, or 4 X's RS900 V 2-VEHICLE OPERATION The RS-900 VI system can be used for 2 car operation. A single RS900VI remote can control two independent vehicles with RS900 VI systems installed. SETUP: See diagram below on how to switch your remote to car 2 operation. Once you switched your remote to Car 2, then follow the transmitter programming steps AT VEHICLE #2 and learn YOUR remote, along with Car 2’s existing remotes. Transmitter programming diagram above. This type of 2-Vehicle operation can only be performed with transmitters that include a slide switch on the side of the remote for Car I or Car II operation. CAR I / CAR II OPERATION CAR I Slide START CAR II RS 900 VI TROUBLESHOOTING: “BEFORE YOU CALL” SECTION UNIT WILL NOT ATTEMPT A START (KEYLESS ENTRY STILL FUNCTIONS NORMALLY): The unit is in Valet mode. Turn Ignition ON, press and hold valet/programming button for 6 seconds then turn key off. Unit is now out of valet mode and should perform a remote start. If optional LED indicator is installed, then it will be on solid when in Valet and OFF when out of Valet. UNIT FLASHES LIGHTS ONCE AND WILL NOT ATTEMPT A START: The unit senses a fault at the Brake (Purple wire is active) or the Hood is OPEN (Gray wire grounded). This is a safety feature of the unit. Check installation for faults and make sure hood is closed and latched and brake wire is not active. Make sure hood is in good condition and is depressed when hood is closed. NO RESPONSE FROM REMOTE TRANSMITTERS: (4 Parts) 1. Check for proper power/ground wiring connections at module. 2. Check Antenna Module connection. The antenna module included with this system must be plugged in. 3. Transmitters may need to be programmed to the unit. See transmitter programming steps on Page 10. 4. Check transmitter Batteries and replace if necessary. UNIT CRANKS VEHICLE BUT ENGINE NEVER STARTS: (2 parts) 1. In extreme cold or severe weather conditions, the unit may take more than the first attempt to start the vehicle. The remote start unit will make up to 3 attempts to start the engine. and later vehicles include some type of Anti-Theft system which may require a bypass module. Check with installer to make sure that the bypass device (if equipped) is functioning properly. VEHICLE STARTS BUT “CHECK ENGINE” LIGHT COMES ON OR ENGINE RUNS BADLY: (2 parts) 1. Many 1995-UP General Motors cars/trucks require a secondary ignition circuit for the Transmission computer and other on board systems. If the vehicle is started without this wire energized, there may be a “Check Engine” or “Service Engine Soon” light on the dash. This may cause damage if the vehicle is driven in this condition. Check with installer to see if this circuit is present and has been properly connected to the RS900. 2. In some cases [commonly Nissan vehicles], an additional “Start” (Cranking) circuit is required for the vehicle to run properly. The RS900 VI system includes a wire that can be used for this Starter #2 circuit. Check with your installer for details. email@crimestopper.com Phone (800) 998-6880 FAX (805) 581-9500 © 2003 Crimestopper Security Products ONLINE TECHNICAL SUPPORT
http://manualzz.com/doc/1167465/crimestopper-rs-901-operating-instructions
CC-MAIN-2018-26
refinedweb
2,908
63.59
PIL OWL Ontology Meeting 2012-02-27 Contents Meeting Information prov-wg - Modeling Task Force - OWL group telecon - previous meeting - date: 2012-02-27 - time: 12pm ET, 5pm UK - via Zakim Bridge +1.617.761.6200, conference 695 ("OWL") - wiki page: - titan page: - next meeting Attendees - Khalid - Daniel - Paul - Tim - Stephan - Luc (away and back) - Satya - Deborah (also away and back)so away and back) Agenda 1) Responding to prov-o feedback process 2) Process - Meta: Daniel's ontology changing concerns. - could we have a wiki page or another ontology where we gather the feedback and discuss it within the prov-o team before implementing to the ontology? - Tim: should we prefer change or not? How to make changes? - catalog of examples 3) Issues - mapping issues - - - changing namespace. - ontology issues - - who wants to look at the status of the issues. untracked issues: Daniel: - We have a Roled class. I don't remember having discussed this change. - Instantaneous event: I'm ok with that, since we discussed it on moday. - Activity is under "Durable". Why?? - qualified has dissapeared, and we have "involved" range Element AND Involvement? (I think this is a typo, it should be the union). - I'm still unhappy with the TemporalEntity name. What about just "Time", or "Temporal"? Tim: - checking RL compliance - Stian's gist 5) PROV-O HTML organization Discussions responding to feedback Khalid: owl file was updated but not announced in email. TODO: Tim to process the feedback inbox. raise each one as an issue. Announce to wg that we added it to the ISSUES and please let us know if what they raised is NOT in the tracker. Luc and Paolo tackle DM into different sections. Daniel: (choppy audio) Or send an email+a deadline vote? Khalid: annotate in subject that it indicated prov-o change. Tim: add an ISSUE for each PROPOSED: annote email subject with [PROV-O change] and ensure there is an original ISSUE that the change is trying to address (mention it in the email) addressing current issues we need to review what issues exist and need to be closed. We need someone to push to close them. TODO: Daniel will look through (not so much this week though) Daniel's list Tim accidentally merged qualified and invovled (he thoguht it was qualifiable) Durable - why? Paul was using RL checker: Stian was OWLAPI TODO: Stian to commit a RL checker jar. TODO: group to help accumulate restrictions that RL has at TODO: include the RL issue "ISSUE-265" in any email announcing a change to the ontology that required RL Property characteristics Khalid added a table and wants others to review. ISSUE: stephen concerned about property chains Stephen's feedback: ." Stephen's feedback might be in this email: property chains are not urgent, we need to focus on getting the concepts. examples that cover DM hand crafted ASN, tool to convert. TODO: Tim to propose a design for the wg to collect ASN examples. Stian: +1 Luc: primer examples can be put in. HTML document Luc: Ivan indicated that OPM-V or FOAF had good documentation that we should try to reflect. SIOC FOAF: OPMV: TODO: Khalid propose structure TODO: group to find out if any of these were generated by a tool. issue-268 Luc and Khalid, splitting ontology Timeline We will discuss the timeline on Thursday.
https://www.w3.org/2011/prov/wiki/PIL_OWL_Ontology_Meeting_2012-02-27
CC-MAIN-2016-50
refinedweb
557
64.51
SSH client focused on network devices Project description nssh nssh is a python library focused on connecting to devices, specifically network devices (routers/switches/firewalls /etc.) via SSH. nssh's goal is to be as fast and flexible as possible, while providing a well typed, well documented , simple API. nssh is built primarily in two parts: transport and channel. The transport layer is responsible for providing a file -like interface to the target SSH server. The channel layer is responsible for reading and writing to the provided file-like interface. There are three available "drivers" for the transport layer -- all of which inherit from a base transport class and provide the same file-like interface to the upstream channel. The transport drivers are: - paramiko - ssh2-python - OpenSSH/System available SSH nssh is the successor/evolution, ssh2-python was used with great success, however, it is a bit feature-limited, and devlopment seems to have stalled. This led to moving back to paramiko, which of course is a fantastic project with tons and tons of feature support . Paramiko, however, does not "direct" OpenSSH support, and I don't believe it provides 100% full OpenSSH support either (ex: ControlPersist). Fully supporting an OpenSSH config file would be an ideal end goal for nssh, something that may not be possible with Paramiko - ControlPersist in particular is very interesting to me. With the goal of supporting all of the OpenSSH configuration options the final transport driver option is simply native system local SSH (almost certainly this won't work on Windows, but I don't have a Windows box to test on, or any particular interest in doing so). The implementation of using system SSH is of course a little bit messy , however nssh takes care of that for you so you don't need to care about it! The payoff of using system SSH is of course that OpenSSH config files simply "work" -- no passing it to nssh, no selective support, no need to set username or ports or any of the other config items that may reside in your SSH config file. The "system" transport driver is still a bit of a work in progress, but in testing has been reliable thus far. The final piece of nssh is the actual "driver" -- or the component that binds the transport and channel together and deals with instantiation of an nssh object. There is a "base" driver object -- NSSH -- which provides essentially a "raw" SSH connection with read and write methods (provided by the channel object), and not much else. More specific "drivers" can inherit from this class to extend functionality of the driver to make it more friendly for network devices. Table of Contents - Documentation - Supported Platforms - Installation - Examples Links - Basic Usage - Known Issues - Linting and Testing Supported Platforms nssh "core" drivers cover basically the NAPALM platforms -- Cisco IOS-XE, IOS-XR, NX-OS, Arista EOS, and Juniper JunOS. These drivers provide an interface tailored to network device "screen -scraping" rather than just a generic SSH connection/channel. At the moment there are five "core" drivers representing the most common networking platforms (outlined below) , however in the future it would be possible for folks to contribute additional "community" drivers. It is unlikely that any additional "core" platforms would be added at the moment. - Cisco IOS-XE (tested on: 16.04.01) - Cisco NX-OS (tested on: 9.2.4) - Juniper JunOS (tested on: 17.3R2.10) - Cisco IOS-XR (tested on: 6.5.3) - Arista EOS (tested on: 4.22.1F) This "driver" pattern is pretty much exactly like the implementation in NAPALM. The driver extends the base class/base networking driver class with device specific functionality such as privilege escalation/de-escalation, setting appropriate prompts to search for, and picking out appropriate ntc templates for use with TextFSM. All of this is focused on network device type SSH cli interfaces, but should work on pretty much any SSH connection (though there are almost certainly better options for non-network type devices!). This "base" ( NSSH) connection does not handle any kind of device-specific operations such as privilege escalation or saving configurations, it is simply intended to be a bare bones connection that can interact with nearly any device/platform if you are willing to send/parse inputs/outputs manually. The goal for all "core" devices will be to include functional tests that can run against vrnetlab containers to ensure that the "core" devices are as thoroughly tested as is practical. Installation You should be able to pip install it "normally": pip install nssh To install from this repositories master branch: pip install git+ To install from source: git clone cd nssh python setup.py install As for platforms to run nssh on -- it has and will be tested on MacOS and Ubuntu regularly and should work on any POSIX system. Examples Links - Basic "native" NSSH operations - Basic "driver" NSSH operations - Setting up basic logging - Using SSH Key for authentication - Using SSH config file Basic Usage Native and Platform Drivers Examples Example NSSH "native/base" connection: from nssh import NSSH my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} conn = NSSH(**my_device) conn.open() # do stuff! Example IOS-XE driver setup. This also shows using context manager which is also supported on "native" mode -- when using the context manager there is no need to call the "open_shell" method: from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: print(conn) # do stuff! Platform Regex Due to the nature of" nssh uses a regular expression pattern to find that base prompt. This pattern is contained in the comms_prompt_pattern setting, and is perhaps the most important argument to getting nssh working. The "base" (default, but changeable) pattern is: "^[a-z0-9.\-@()/:]{1,20}[#>$]$" NOTE all comms_prompt_pattern should use the start and end of line anchors as all regex searches in nssh are multline (this is an important piece to making this all work!). While you don't need to use the line anchors its probably a really good idea! The above pattern works on all "core" platforms listed above for at the very least basic usage. Custom prompts or hostnames could in theory break this, so be careful! If you do not wish to match Cisco "config" level prompts you could use a comms_prompt_pattern such as: "^[a-z0-9.-@]{1,20}[#>$]$" If you use a platform driver, the base prompt is set in the driver so you don't really need to worry about this! The comms_prompt_pattern pattern can be changed at any time at or after instantiation of an nssh object. Changing this can break things though, so be careful! Basic Operations -- Sending and Receiving Sending inputs and receiving outputs is done through the base NSSH object or your selected driver object. The inputs /outputs all are processed (sent/read) via the channel object. If using the base NSSH object you must use the channel.send_inputs method -- the NetworkDriver and platform specific drivers have a send_commands method as outlined below. The following example shows sending a "show version" command as a string. Also shown: send_inputs accepts a list/tuple of commands. from nssh import NSSH my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with NSSH(**my_device) as conn: results = conn.channel.send_inputs("show version") results = conn.channel.send_inputs(("show version", "show run")) When using a network "driver", it is more desirable to use the send_commands method to send commands (commands that would be ran at privilege exec in Cisco terms, or similar privilege level for the other platforms). send_commands is just a thin wrapper around send_inputs, however it ensures that the device is at the appropriate prompt ( default_desired_priv attribute of the specific driver, see Driver Privilege Levels). from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: results = conn.send_commands("show version") results = conn.send_commands(("show version", "show run")) Result Objects All read operations result in a Result object being created. The Result object contains attributes for the command sent ( channel_input), start/end/elapsed time, and of course the result of the command sent. from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: results = conn.send_commands("show version") print(results[0].elapsed_time) print(results[0].result) Handling Prompts In some cases you may need to run an "interactive" command on your device. The send_inputs_interact method can be used to handle these situations. This method accepts a tuple containing the initial input (command) to send, the expected prompt after the initial send, the response to that prompt, and the final expected prompt -- basically telling nssh when it is done with the interactive command. In the below example the expectation is that the current/base prompt is the final expected prompt, so we can simply call the get_prompt method to snag that directly off the router. from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} interact = ["clear logging", "Clear logging buffer [confirm]", "\n"] with IOSXEDriver(**my_device) as conn: interactive = conn.channel.send_inputs_interact( ("clear logging", "Clear logging buffer [confirm]", "\n", conn.get_prompt()) ) Driver Privilege Levels The "core" drivers understand the basic privilege levels of their respective device types. As mentioned previously , the drivers will automatically attain the "privilege_exec" (or equivalent) privilege level prior to executing "show " commands. If you don't want this "auto-magic" you can use the base driver (nssh). The privileges for each device are outlined in named tuples in the platforms driver.py file. As an example, the following privilege levels are supported by the IOSXEDriver: - "exec" - "privilege_exec" - "configuration" - "special_configuration" Each privilege level has the following attributes: - pattern: regex pattern to associate prompt to privilege level with - name: name of the priv level, i.e. "exec" - deescalate_priv: name of next lower privilege or None - deescalate: command to deescalate to next lower privilege or None - escalate: name of next higher privilege or None - escalate_auth: command to escalate to next higher privilege or None - escalate_prompt: False or pattern to expect for escalation -- i.e. "Password:" - requestable: True/False if the privilege level is requestable - level: integer value of level i.e. 1. from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: conn.acquire_priv("configuration") Sending Configurations When using the native mode ( NSSH object), sending configurations is no different than sending commands and is done via the send_inputs method. You must manually ensure you are in the correct privilege/mode. When using any of the core drivers or the base NetworkDriver, you can send configurations via the send_configs method which will handle privilege escalation for you. As with the send_commands and send_inputs methods -- you can send a single string or a list/tuple of strings. from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: conn.send_configs(("interface loopback123", "description configured by nssh")) TextFSM/NTC-Templates Integration nssh supports parsing output with TextFSM. This of course requires installing TextFSM and having ntc-templates somewhere on your system. When using a driver you can pass textfsm=True to the send_commands method to automatically try to parse all output. Parsed/structured output is stored in the Result object in the structured_result attribute. Alternatively you can use the textfsm_parse_output method of the driver to parse output in a more manual fashion. This method accepts the string command (channel_input) and the text result and returns structured data; the driver is already configured with the ntc-templates device type to find the correct template. from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: results = conn.send_commands("show version", textfsm=True) print(results[0].structured_result) # or parse manually... results = conn.send_commands("show version") structured_output = conn.textfsm_parse_output("show version", results[0].result) nssh also supports passing in templates manually (meaning not using the pip installed ntc-templates directory to find templates) if desired. The nssh.helper.textfsm_parse function accepts a string or loaded (TextIOWrapper ) template and output to parse. This can be useful if you have custom or one off templates or don't want to pip install ntc-templates. from nssh.driver.core import IOSXEDriver from nssh.helper import textfsm_parse my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: results = conn.send_commands("show version") structured_result = textfsm_parse("/path/to/my/template", results[0].result) NOTE: If a template does not return structured data an empty dict will be returned! Timeouts nssh supports several timeout options. The simplest is the timeout_socket which controls the timeout for... setting up the underlying socket in seconds. Value should be a positive, non-zero number, however ssh2 and paramiko transport options support floats. timeout_ssh sets the timeout for the actual SSH session when using ssh2 or paramiko transport options. When using system SSH, this is currently only used as the timeout timer for authentication. Finally, timeout_ops sets a timeout value for individual operations -- or put another way, the timeout for each send_input operation. Disabling Paging nssh native driver attempts to send terminal length 0 to disable paging by default. In the future this will likely be removed and relegated to the device drivers only. For all drivers, there is a standard disable paging string already configured for you, however this is of course user configurable. In addition to passing a string to send to disable paging, nssh supports passing a callable. This callable should accept the drivers reference to self as the only argument. This allows for users to create a custom function to disable paging however they like . This callable option is supported on the native driver as well. In general it is probably a better idea to handle this by simply passing a string, but the goal is to be flexible so the callable is supported. from nssh.driver.core import IOSXEDriver def iosxe_disable_paging(cls): cls.send_commands("term length 0") my_device = {"host": "172.18.0.11", "auth_username": "vrnetlab", "auth_password": "VR-netlab9", "session_disable_paging": iosxe_disable_paging} with IOSXEDriver(**my_device) as conn: print(conn.get_prompt()) Login Handlers Some devices have additional prompts or banners at login. This generally causes issues for SSH screen scraping automation. nssh supports -- just like disable paging -- passing a string to send or a callable to execute after successful SSH connection but before disabling paging occurs. By default this is an empty string which does nothing. SSH Config Support nssh supports using OpenSSH configuration files in a few ways. For "system" SSH driver, passing a path to a config file will simply make nssh "point" to that file, and therefore use that configuration files attributes (because it is just exec'ing system SSH!). Soon SSH support that exists in ssh2net will be ported over to nssh for ssh2-python and paramiko transport drivers. NOTE -- when using the system (default) SSH transport driver nssh does NOT disable strict host checking by default . Obviously this is the "smart" behavior, but it can be overridden on a per host basis in your SSH config file, or by passing False to the "auth_strict_key" argument on object instantiation. from nssh.driver.core import IOSXEDriver my_device = {"host": "172.18.0.11", "ssh_config_file": "~/mysshconfig", "auth_strict_key": False, "auth_password": "VR-netlab9"} with IOSXEDriver(**my_device) as conn: print(conn.get_prompt()) - Question: Why build this? Netmiko exists, Paramiko exists, Ansible exists, etc...? - Answer: I built ssh2net to learn -- to have a goal/target for writing some code. nssh is an evolution of the lessons learned building ssh2net. About mid-way through building ssh2net I realized it may actually be kinda good at doing... stuff. So, sure there are other tools out there, but I think nssh its pretty snazzy and fills in some of the gaps in other tools. For example nssh Netmiko/Paramiko/Ansible? -. - Question: Is this easy more Netmiko-like experience -OR- write your own driver as this has been built with the thought of being easily extended. - Why do I get a "conn (or your object name here) has no attribute channel" exception when using the base NSSHor NetworkDriverobjects? - Answer: Those objects do not "auto open", and the channel attribute is not assigned until opening the connection . Call conn.open()(or your object name in place of conn) to open the session and assign the channel attribute. - Other questions? Ask away! Known Issues SSH2-Python Arista EOS uses keyboard interactive authentication which is currently broken in the pip-installable version of ssh2-python (as of January 2020). GitHub user Red-M has contributed to and fixed this particular issue but the fix has not been merged. If you would like to use ssh2-python with EOS I suggest cloning and installing via Red-M's repository or my fork of Red-M's fork! Use the context manager where possible! More testing needs to be done to confirm/troubleshoot, but limited testing seems to indicate that without properly closing the connection there appears to be a bug that causes Python to crash on MacOS at least. More to come on this as I have time to poke it more! I believe this is only occurring on the latest branch/update (i.e. not on the pip installable version). Linting and Testing NOTE Currently there are no unit/functional tests for IOSXR/NXOS/EOS/Junos, however as this part of nssh is largely a port of ssh2net, they should work :) Linting This project uses black for auto-formatting. In addition to black, tox will execute pylama, and pydocstyle for linting purposes . Tox will also run mypy, with strict type checking. Docstring linting with darglint which has been quite handy! All commits to this repository will trigger a GitHub action which runs tox, but of course its nicer to just run that before making a commit to ensure that it will pass all tests! Typing As stated, this project is 100% type checked and will remain that way. The value this adds for IDE auto-completion and just general sanity checking/forcing writing of more type-check-able code is worth the small overhead in effort. Testing I broke testing into two main categories -- unit and functional. Unit is what you would expect -- unit testing the code. Functional testing connects to virtual devices in order to more accurately test the code. Unit tests cover quite a bit of the code base due to mocking the FileIO that the channel reads/writes to. This gives a pretty high level of confidence that at least object instantiation and channel read/writes will generally work... Functional tests against virtual devices helps reinforce that and gets coverage for the transport classes. Unit Tests Unit tests can be executed via pytest: python -m pytest tests/unit/ Or using the following make command: make test_unit If you would like to see the coverage report and generate the html coverage report: make cov_unit. Basic functional tests exist for all "core" platform types (IOSXE, NXOS, IOSXR, EOS, Junos).. For the Arista EOS image -- prior to creating the container you should boot the device and enter the zerotouch disable command. This allows for the config to actually be saved and prevents the interfaces from cycling through interface types in the container (I'm not clear why it does that but executing this command before building the container "fixes" this!). After creating the image(s) that you wish to test, rename the image to the following format: nssh[PLATFORM] The docker-compose file here will be looking for the container images matching this pattern, so this is an important bit! The container image names should be: nsshciscoiosxe nsshcisconxos nsshciscoiosxr nsshciscojunos You can tag the image names on creation (following the vrnetlab readme docs), or create a new tag once the image is built: docker tag [TAG OF IMAGE CREATED] nssh[VENDOR][OS] NOTE I have added vty lines 5-98 on the CSR image -- I think the connections opening/closing so quickly during testing caused them to get hung. Testing things more slowly (adding time.sleep after closing connections) fixed this but that obviously made the testing time longer, so this seemed like a better fix. This change will be in my fork of vrnetlab or you can simply modify the line vty 0 5 --> line vty 0 98 in the luanch.py for the CSR in your vrnetlab clone. Functional Tests VR-netlab9 Once the container(s) are ready, you can use the make commands to execute tests as needed: testwill execute all currently implemented functional tests as well as the unit tests test_functionalwill execute all currently implemented functional_eoswill execute all unit tests and eos functional tests test_junoswill execute all unit tests and junos functional tests Project details Release history Release notifications 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/nssh/
CC-MAIN-2020-10
refinedweb
3,503
53.71
A ------------->pAA ^ ^ | | _____ _______ | | | | B C pBB pCCThe pAA hierarchy does something, it doesnt matter what. Then the need to persist that structure comes about, and the A hierarchy is written. Each class in the A hierarchy knows how to store its equivalent class in the pAA hierarchy. Firstly, is this what we are talking about when we say parallel hierarchy (that might sound like a stupid question, but its better to make sure we are all clear). Secondly, if that is a bad design, can smoeone explain why and give an example of how to improve it? /src/myproject/classes /src/myproject/interfaces...of course the two directory structures (and class structures) mirrored each other - my convention was to name the interface classes after the implementation class, but with an 'I' prefix - and I could then provide one source-tree each to the client (interfaces) and server (classes) development teams. They never needed (nor should they) to meddle with each others' code. An unintended side-effect was that it really aided the junior programmers' appreciation of the benefit of cleanly defined code layers! I could have stored each interface class alongside its implementation class but, apart from the additional housework required to maintain the source-trees, isolating the two distinct codebases seemed to better match their purpose. I agree that this is a very real CodeSmell, but not necessarily indicative of poor design. -- DanKane A <------------ AbstractTestA ^ ^ | | |_______ |_______ | | | | B C TestC TestBThat is the one issue which makes me nervous about UnitTests. --JimmyCerra. A A+ <--- Class A+ has one additional attribute added to it ^ ^ The attribute does not affect B, C and D | | +- B +- B +- C +- C~ <--- Because of the addition of one attribute in A+ some of +- D +- D~ behavour of C~ and D~ differes from C and D however the attributes in C~ and D~ is identical to the attributes in C and DJohnGriffin? Josh, can you provide more context about the problem? You solution seems to violate the LiskovSubstitutionPrinciple. It could be solved via the AdapterPattern, BridgePattern, or DecoratorPattern. The Decorator could be useful: A <--------+ ^ | | | +- B | +- C | +- D \/ +--------- ADecoratorHere's an example in Java: public interface A { public Object oldMethod1(); public Object oldMethod2(); /* ... */ } public class B implements A { /* ... */ } public class C implements A { /* ... */ } public class D implements A { /* ... */ } public class ADecorator implements A { private A impOfA; public ADecorator(A a) {impOfA = a;} public Object newMethod() { /* ... */} public Object oldMethod1() { return impOfA.oldMethod1();} public Object oldMethod2() { return impOfA.oldMethod2();} /* ... */ }The new behavior is added via newMethod (you can add more). Old functunality is delegated to the other instance of A. That is... new ADecorator(new B());...or something like that. It still satisfies the LSP, with the extra functunality available if you need it. -- Jimmy Cerra I don't know if this will make sense. Here is the hierarchy I have: Task ^ | +-----------+---------+----------------+ | | | | ActionItem? Meeting DefectReport? ChangeRequest?A Task is related to a ProjectRelease? like so: Project ----* ProjectRelease? ----* ReleaseTask? ----* TaskSo every release of a project has a number of tasks to be completed. These tasks can be different things: meetings to attend, bugs to fix, etc. This hierarchy is modelled to fit over a relational database schema where ActionItem? etc. has a foreign key, task_id, referencing the primary key of task. The idea being that a user of the system can look at the contents of the Task table and see a summary of what tasks they need to perform without having to scan additional tables. ReleaseTask? contains foreign key references to ProjectRelease? and Task. Now, there is a new module, committees that needs to be built. The original idea is to reuse part of the Task hierarchy so you would have something like: ReleaseTask? ----* Task *---- CommitteeTask?This would allow the Committee to reuse the existing code and data structures. The alternative at this point seems to be duplicating part of the Task hierarchy or adding new classes like ProjectReleaseMeeting? and CommitteeMeeting?. I'd go with delegation (i.e. the original idea). -- JimmyCerra
http://c2.com/cgi-bin/wiki?ParallelInheritanceHierarchies
CC-MAIN-2014-42
refinedweb
664
56.25
Problem sending text strings to process with QProcess::write - elpidiovaldez5 I am trying to use text-to-speech via an independent process. This should allow TTS to proceed without blocking the message queue of my main process. I have a very simple console program which speaks any line of text typed on the keyboard. I want to use QProcess to start this console process and send text to its stdin. QProcess successfully starts the process (it appears in Task Manager). It also reports the correct number of bytes sent in calls to QProcess::write. However no speech is generated. The console program works correctly when operated from the keyboard. I am using QT 5.2.0 and Lubuntu 13.04. I would appreciate any ideas on what is wong here. I have given all the relevant code below. @#include <QProcess> class Voice { public: QProcess *speechServer; Voice() { run(); } void run() { string speechServerName = SessionDirectory() + "ConsoleTTS"; speechServer = new QProcess(); speechServer->start(speechServerName.c_str(), QProcess::Unbuffered | QProcess::ReadWrite); if (!speechServer->waitForStarted()) { Print("Speech server not started"); } } void say(const string &text) { int err1 = speechServer->write(text.c_str()); if (err1==-1) { Print("QProcess::write failed"); } int err2 = speechServer->write("\n"); if (err2==-1) { Print("QProcess::write failed"); } } }; @ The console program is: @#include <QCoreApplication> #include <QTextStream> #include <flite.h> extern "C" cst_voice register_cmu_us_kal(const char); int main(int argc, char *argv[]) { QCoreApplication a(argc, argv); QTextStream cin(stdin); QTextStream cout(stdout); cst_voice *v; flite_init(); v = register_cmu_us_kal(NULL); do { QString text = cin.readLine(); cout << text << "\n"; cout.flush(); flite_text_to_speech(text.toStdString().c_str(), v, "play"); } while(true); return a.exec(); }@ - SGaist Lifetime Qt Champion Isn't this a duplicate of "this one": ? - elpidiovaldez5 It's the same problem, but I stripped down the voice class so that I could post it in its entirety, giving the full context. I did it on a new thread because the original seemed to have died.The old version actually had problems due to multi-threading. This version does not use multi-threading at all. Consequently the QProcess::write calls appear to work (they return the correct number of bytes sent). However the console program fails to speak, whereas it does work when run from a command prompt and sent text throught the keyboard. My conclusion is that the message is not being received in stdin. Buffering problem or do I need to force flush ?
https://forum.qt.io/topic/51278/problem-sending-text-strings-to-process-with-qprocess-write
CC-MAIN-2017-43
refinedweb
393
58.89
How do I find and remove duplicate rows in pandas? [ad_1]. JOIN the “Data School Insiders” community and receive exclusive rewards: == RESOURCES == GitHub repository for the series: “duplicated” documentation: “drop_duplicates” documentation: == LET’S CONNECT! == Newsletter: Twitter: Source [ad_2] Comment List Great video. This helped me tremendously. How would you go about finding duplicates "case insensitive" with a certain field? Really, your teaching method is very good, your videoes give more knowledge, Thanks Data School love u brother . u r changing so many lives, thanku ….the best teacher award goes to Data school. wow! you are already teaching data science in 2014 when it is not even popular! Btw, your videos are really good, you speak slow and clear, easy to understand and for me to catch. Kudos to you! At the end are you saying that "age" + "zip code" must TOGETHER be duplicates? Or are you saying "age" duplicates and "zip code" duplicates must remove their individual duplicates from their respective columns? Thanks Thanks for awesome videos on Pandas. I was able to automate few excel reporting at my work.. but stuck with something very complex(its complex for me!). Could you please help on some complex excel calculations using Python.? for ex. suppose I have data in below format. db_instance Hostname Disk_group disk_path disk_size disk_used header_status abc_cr host1 data01 dev/mapper/asm01 240 90 Member abc_cr host1 data01 dev/mapper/asm02 240 100 Member abc_cr host1 data01 dev/mapper/asm03 240 60 Member abc_xy host1 data01 dev/mapper/asm01 240 90 Member abc_xy host1 data01 dev/mapper/asm02 240 100 Member abc_xy host1 data01 dev/mapper/asm03 240 60 Member abc_cr host1 acfs01 dev/mapper/asm04 90 30 Member abc_cr host1 acfs01 dev/mapper/asm05 90 60 Member abc_xy host1 acfs01 dev/mapper/asm04 90 30 Member abc_xy host1 acfs01 dev/mapper/asm05 90 60 Member host1 unassigned dev/mapper/asm06 180 0 Candidate host1 unassigned dev/mapper/asm07 180 0 Former res_du host2 data01 dev/mapper/asm01 240 90 Member res_du host2 data01 dev/mapper/asm02 240 100 Member res_du host2 data01 dev/mapper/asm03 240 60 Member res_hg host2 data01 dev/mapper/asm01 240 90 Member res_hg host2 data01 dev/mapper/asm02 240 100 Member res_hg host2 data01 dev/mapper/asm03 240 60 Member res_pq host2 acfs01 dev/mapper/asm04 90 30 Member res_pq host2 acfs01 dev/mapper/asm05 90 60 Member res_mn host2 acfs01 dev/mapper/asm04 90 30 Member res_mn host2 acfs01 dev/mapper/asm05 90 60 Member host2 unassigned dev/mapper/asm06 180 0 Candidate host2 unassigned dev/mapper/asm07 180 0 Former As you can see, disk_path is duplicated for each host..because of multiple db_instance. (Even though you see similar disk_paths for host1 & host2, but actually they are different disks from storage end.. but admins follow similar name conventions when they configure disks at host side, resulting similar disk_paths for different hosts) My queries are, How 1. to remove duplicates for disks_path for each host?(considering only two columns Hostname & disk_path, that's how I remove duplicates in excel, I am not worried for db_instance) 2. once we remove duplicates, calculate total size of 'Member' disks… also total size of 'Candidate' and 'Former' disks combined. 3. to add another column 'Percent used', which will is result of 'disk_used'/'disk_size'*100 for each row. Thanks in advance! long live and prosper! How to Remove Leading and Trailing space in data frame I have watched a lot of your videos; and I must say that the way, you explain is really good. Just to inform you that I am new to programming let alone Python. I want to learn a new thing from you. Let me give you a brief. I am working on a dataset to predict App Rating from Google Play Store. There is an attribute by name "Rating" which has a lot of null values. I want to replace those null values using a median from another attribute by name "Reviews". But I want to categorize the attribute "Reviews" in multiple categories like: 1st category would be for the reviews less than 100,000, 2nd category would be for the reviews between 100,001 and 1,000,000, 3rd category would be for the reviews between 1,000,001 and 5,000,000 and 4th category would be for the reviews anything more than 5,000,000. Although, I tried a lot, I failed to create multiple categories. I was able to create only 2 categories using the below command: gps['Reviews Group'] = [1 if x <= 1000000 else 2 for x in gps['Reviews']] gps is the Data Set. I replaced the Null Values using the below command: gps['Rating'] = gps.groupby('Reviews Group')['Rating'].transform(lambda x: x.fillna(x.median())) Please help me create multiple categories for "Reviews" as mentioned above and replace all the Null Values in "Rating". lol, just when I felt you wouldn't handle the exact subject I was looking for: there came the bonus! Thanks! You are the greatest teacher in the world I can solve the duplicate data from my CSV file~~~ Thank you. However, I suggest you can do more in this video. I think you can show after the delete result list. Such as: >> new_data=df.drop_duplicates(keep='first') >> new_data.head(24898) If you have to add it, I think this video will be more perfect~~~ you're amazing we need more videos in your channel very useful videos.. can you please tell me how to find duplicate of just one specific row? Thank you! Love it. Yo! You are a superb teacher! i get a error when i run users.drop_duplicates(subset=['age','zip_code']).shape . error "'bool' object is not callable" even i get the same error if i run users.duplicated().sum() Awesome videos Kevin. Thanks a to for the knowledge share. Hi, I am wondering whether you could identify an issue that I am having whilst cleaning a dataset with the help of your tutorials. I will post the commands that I have used below: df["is_duplicate"]= df.duplicated() # make a new column with a mark of if row is a duplicate or not df.is_duplicate.value_counts() -> False 25804 True 1591 df.drop_duplicates(keep='first', inplace=True) #attempt to drop all duplicates, other than the first instance df.is_duplicate.value_counts() # -> False 25804 True 728 I am struggling to identify why there are still some duplicates that are marked 'True'? Kind regards, How to keep rows that contains null values in any column and remove completed rows? great video!! 💯+ like. Thank you very much sir. I always find what I need in your channel.. and more… Thank you A very much appreciated efforts. Thanks a million for sharing with us your python knowledge. It has been a wonderful journey with your precise explanation. keep the hard work! Warm regards. import pandas as pd import numpy as np #Create a DataFrame d = { 'Name':['Alisa','Bobby','jodha','jack','raghu','Cathrine', 'Alisa','Bobby','kumar','Alisa','Alex','Cathrine'], 'Age':[26,24,23,22,23,24,26,24,22,23,24,24], 'Score':[85,63,55,74,31,77,85,63,42,62,89,77]} df = pd.DataFrame(d,columns=['Name','Age','Score']) df ============================================================ When I write below code : df1 = df[df['Score']==85] df.drop_duplicates(['Name']) df Result Alisa is still shown, it is only deleting once alisa, I want both alisa to be remove, Can you please provide code ? I´m beginner, so I can say that the video is very clear and precise, and anyone can understand the contents. thanks for sharing You are amazing! I have some missing dates in my dataset and want to add the missing dates to the dataset. I used isnull() to track these dates but I don't know how to add those dates into my dataset..Can you please help.Thanks 1.75X speed is your friend 🙂 Thanks so much for this! You helped me combine 629 files and remove 250k duplicate rows! You're the man! Subscribed Thanks for the video you are amazing. thank you ever much <3 I didn't find much in Duplicates. Thanks so much sir. I can't thank u enough. Thank you for this useful tutorial. Quick question, how do you check whether a value in column A is present in column B or not; not necessarily on the same row. It is like the samething that VLOOKUP function looks for in Excel. Many thanks for your feed-back! You should have used sort_values option with users.loc[users.duplicated(keep=False)].sort_values(by='age') I really need help guys. I have a table that has a column : Column name – " Neighbourhood" This Column has A LOT of names repeated MANY times. To be specific, the column "Neighbourhood" has 10 Names that are repeated ALOT of times. My question is : I NEED HELP IN CREATING A SEPARATE COLUMN SPECIFYING HOW MANY TIMES EACH ELEMENT IN "NEIGHBORHOOD" HAS BEEN COUNTED. If anyone help me please. 感谢。
https://openbootcamps.com/how-do-i-find-and-remove-duplicate-rows-in-pandas/
CC-MAIN-2021-10
refinedweb
1,497
65.12
? is not a valid character for inclusion within a column name. First, create a new database migration: # from command line rails generate migration ChangeCorrectInAnswers Rename your column from correct? to correct: # in the resulting migration class ChangeCorrectInAnswers < ActiveRecord::Migration def up rename_column :answers :correct?, :correct end end Run the migration: # from command line rake db:migrate Finally, remove the ? from your field in the view: # app/views/questions/_form.html.erb <%= answer.check_box :correct %> I'm not sure what exactly do you mean... But if you are wish to limit the number of records that are being pulled from the database all you need to do in the controller is to use the :limit option in find for example MyModel.find(:all, :limit => 10) Why are you using two forms instead of one form? Include the image upload in the student model. <%= simple_form_for @student, :html => {:multipart => true} do |f| %> <%= f.input :last_name, label: '姓'%> <%= f.input :first_name, label: '名' %> <%= f.input :email, label: '电子邮件' %> <%= f.input :password, label: '密码' %> <%= f.input :college, label: '大学' %> <%= f.input :budget, label: '房间租金预算 (optional)' %> <%= f.file_field :picture, label: 'student photo (optional)' %> <%= f.button :submit %> <br> Can you call the helper method simple_form? If you need to form it this way what about <%= simple_form_for @student, :html => {:multipart => true} you should create a salt first (using some random function) and use $user->setSalt($salt) in your controller ... ... or generate the salt inside the User's __construct() method. FOSUserBundle i.e. creates the salt in the constructor of the User object using: public function __construct() { $this->salt = base_convert(sha1(uniqid(mt_rand(), true)), 16, 36); // ... } reference here. Otherwise the encoder called at $this->_encodePassword($user) won't find the salt calling the user object's getter getSalt(). tip: In symfony2 you should never try to access GET parameters using $_GET ... ... use the Request object instead. Please read the Symfony2 and HTTP Fundamentals chapter of the book. #FORM_ID input { display: inline-block; } just tried it with sign in form for Devise, Devise also uses simple_form and it works. Note! this won't work if your inputs are inside of another element. In this case you'll have to apply inline-block to that element. For exemple: html: <form id="login"> <div class="my-input"> <your input here> </div> </form> css: #FORM_ID .my-input { display: inline-block; } You need to specify <%= fields_for ... you are missing the = sign. Try: <%= f.fields_for :scores do |builder| %> Please refer to fields_for documentation on it's usage. Although fields_for works regardless of use of simple_form, you could use simple_fields_for as well since you are using simple_form as follows: <%= f.simple_fields_for :scores do |builder| %> So you want to have the order items listed in the second form like a pre-checkout shopping cart. If you use divs for that, they will not be submitted with the POST data to the server - they will be display-only. So you need to follow Robert's advice and save the 1st form's data to the DB each time an item is added/removed (in addition to his other reasons like not losing a customer's session info). That way the DB will already be up-to-date when they click Confirm Order. Or else you need to hook the Confirm Order button to a JS function that converts the divs back to JSON and posts that to the server to be stored in the DB. As far as creating the display-only div from the 1st form's data, your send_item_data function needs to loop over all the form's inputs, get their values, and add Something like this: $('.checkboxselector').click(function(){ $('#boxholdingtheitemsontheright').append('<some html of your choosing>' + $(this).next().text() + '</close>'); }); You can refactor your code like this: app/controllers/static_pages.rb def home @newsletter = Newsletter.new end In your view: <%= form_for @newsletter do |f| %> Regarding your issue, you might want to check @newsletter.errors to see if the validation process succeed or not. Try: class NewslettersController < ApplicationController respond_to :html def create @newsletter = Newsletter.new(params[:newsletter]) @newsletter.save respond_with @newsletter end end Try rails wrapper in simple_form like this: = simple_form_for(@spot, :url => admin_spot_index_path) do |f| = f.error_notification = f.association :city, :collection => City.all, label: false = f.input :region do = f.select :region, Region.all.map { |r| [r.name, r.id] }, :prompt => "select Region" Thanks At first glence, I can tell you that you're attempting to bind two paramters, but you only bind one. At second glance, you're also missing a closing bracket on your prepare. $statement =$mysqli->prepare("INSERT INTO detectives(name)VALUES(?,?)"); // ^^^ ? $statement->bind_param('ss',$_POST['name']); // ^^ ^^^^^^^^^^^^^^ ??? delete this: <tr> <td><font size=2 face=Arial>Name:</font></td> <td><input type="text" name="name" id="name" value=""></td> </tr> and this: var name = trim($F("name")); if (name=="") { // stuff } You should be able to remove other 'name' references in the JavaScript as well. Change things like this: $("name", "email").invoke('clear'); to: The php file will be this: <?php header ("Expires: Mon, 26 Jul 1997 05:00:00 GMT"); header("Cache-Control: no-store, no-cache, must-revalidate"); header("Pragma: no-cache"); // fetch the email and add it to the file $pfileName = "myemails.txt"; $MyFile = fopen($pfileName, "a"); $nline=$email." "; f If you want to go with check_box then its possible: <%= f.input :status, :as => :check_boxes, collection: [['Completed', 'completed']] %> But you should not expect two values from a check_box. It will carry only one value. the reverse will be considered if the check box is not checked. This example does not quite complete your task. But it is a self contained node.js program that displays a form and a different page upon form receipt. Copy it into a file and then run node filename.js and then go to in a browser. Take note of the asynchronous code structure. I define a handler function but don't execute it immediately. We instead pass the function to http.createServer and then call .listen(3000). Now when an HTTP request comes in, the http server will pass a req, res pair to the handler function. req is the request object (this will contain the form data; see this question for some hints on how to get that data out. (I suggest that you jump right in and build a small Express app. It's a really nice framework.) //app.js // Load the built in 'http' Function sexp-at-point gives you the sexp ("form") at the cursor. Just copy that to the kill-ring, using kill-ring-save. E.g.: (defun copy-sexp-at-point () (interactive) (let ((bnds (bounds-of-thing-at-point 'sexp))) (kill-ring-save (car bnds) (cdr bnds)))) Alternatively, just use kill-new: (defun copy-sexp-at-point () (interactive) (kill-new (thing-at-point 'sexp))) You need to pass the selecteddata to the form2 constructor. so modify the form 2 constructoo like this public form2(String SelectedData){ txtSelectedData.Text = SelectedData ; } and when creating an instance of form2, pass the value like this Form2 frm2 = new Form2(selectedOption.ToString()); f.input :email_format, :collection => ["Text and HTML", "Text Only", "HTML Only"], :prompt => "select email format" Refer this There is no more support for mysql_* functions, they are officially deprecated, no longer maintained and will be removed in the future. You should update your code with PDO or MySQLi to ensure the functionality of your project in the future. As you can see below at each step we have a verification to know if we were able to connect to the database, if the SQL query was OK, if the parameters you want to give are OK and we also take the opportunity to prevent injection with the prepared statement and we finally execute it. Now notice how after we execute it, I verify how many rows were affected using $update->affected_rows to know if it was OK or not. The affected rows, can return: -1 indicating that the query returned an error 0 indicating no records were updated and a number abo You can compare the HTML of the forms created on these two pages: I think its related to your database field... I think you have set the databasefield as string, which hast 255 maximum length in general.. This could be the reason why it adds 255 automatically? Yes it is enough to make it secure....you could always throw strip_tags() in there as well.... Although I would just do it in one line...instead of using three $find = htmlspecialchars(mysql_real_escape_string($_POST['find'])); But to really make it secure and up to date, you should stop using mysql_* functions as they are deprecated, and will be removed in any future relases of PHP.... You should instead switch to either mysqli_* or PDO, and implement prepared statements which handles security for you. Example...in PDO $db = new PDO('mysql:server=localhost;dbname=test', 'username', 'password'); $find = $_POST['find']; $query = $db->prepare('SELECT * FROM tbl_buyerguide WHERE rel_date BETWEEN NOW() AND DATE_ADD(now(), INTERVAL 2 MONTH) AND title LIKE :like ORDER BY Sending mail from PHP is fraught with difficulties. You might not have an error in your code, but the mail might not be delivered because (select as many as you wish): it doesn't appear to come from an email address on the server; outbound email is blocked by default until you ask for it; Outbound mail on port 25 is blocked, and you have to use a specific server. your server is blacklisted; your message is blocked by a spam filter; some other reason. Make life easy on yourself. Use a library like swiftmailer or PHPmailer to handle sending the mail, and try something easy like delivering to an address on the sending server. Then work up from there. Be prepared to have to use SMTP Authentication, and possibly a paid external service to send the mail for you. Not with :readonly, no. The readonly HTML input attribute only prevents the user from changing the value of the field. It doesn't stop them from interacting with it, as clicking on it and toggling the checkmark shows. That only changes the state of the checkbox, whether it's on or off. The specs on the readonly attribute say this: readonly This Boolean attribute indicates that the user cannot modify the value of the control. If you don't want them changing the state at all, you may want to use disabled: disabled This Boolean attribute indicates that the form control is not available for interaction. In particular, the click event will not be dispatched on disabled controls. Also, a disabled control's value isn't submitted with the form. But since the input is not sent a Since POST /contact-us posts to the index route, create a postIndex method: public function postIndex($data) { //Handle form return View::make('contact-us-success'); } Which method has replaced the startup() in the Context In the Context use context.install to install extension that you want to use. most common one is MVCSBundle. use context.configure with (new ContextView) argument will start your context initialization. I can no longer just use "mediatorMap"; Do I need to create a MediatorMap Instance for this? you can inject IMediatorMap anywhere you need it, like in config [Inject] public var injector:IInjector; [Inject] public var mediatorMap:IMediatorMap; [Inject] public var commandMap:ISignalCommandMap; In the few RL2 example out there, many devs use the IConfig to configure their main Context; is this required, a good convention or optional. ..and in which way, is the Context 'configured' through this? yo action="mailto:?subject=Hello" This is not what you think it is. action specifies the destination URL. mailto: links are sent to the client, the server doesn't do anything with them. Ex: "mailto:mr.smith@matrix.com" "" mailto is like http here. To send mail using PHP you can the mail function or some other implementation. The action in your form will have to point to a script on your server. Make a simple form that lets users enter a name and email address. Have the email addresses go straight into a database or some other form of storage (could be as simple as a text file). Then, when ready, write a simple script that will send out an email to all the users in the database. In regards to: "How can I create a simple php mail form that will always work?" There are many PHP based forms that can be found on the Web, and you will find many by Googling "php form with validation", for example. Make sure that it includes proper validation and sanitization. Here is one example on tutsplus.com Also consult Sanitize filters on PHP.net and here also for examples. PHP(.net) has a function called mail() which you can read up on. Click here to see it. Ajax is another good method to use for email/forms. Here is one example. Google "ajax email form" and you will get many hits. You have to includes the Type model and then add a conditions on the internal field of the Type table: scope :external, includes(:type).where(types: { internal: false }) application.js or any .js file $(function() { $(".datepicker" ).datepicker({dateFormat: "dd/mm/yyyy"}); }); view file <div class="input-append date"> <%=f.text_field :field_name, :class=>'datepicker'%> <span class="add-on"><i class="icon-th"></i></span> </div> Try this. Your model should be function edit($id) { $data = array( 'note' => $_POST['note'], 'user'=> $_POST['user']// I don't think you need this. ); $this->db->where('id', $id); $this->db->update('company_contacts', $data); } change this: // Username validation $query_username="SELECT username FROM users WHERE username='$username'"; $result_username=mysql_query($query_username) or die (mysql_error()); elseif (mysql_num_rows($result_username)>0) /* !!! ROW 72 !!! */ { echo "Username already registered. Pick something else"; } to this: // Username validation $query_username="SELECT username FROM users WHERE username='$username'"; $result_username=mysql_query($query_username) or die (mysql_error()); if (mysql_num_rows($result_username)>0) /* !!! ROW 72 !!! */ { echo "Username already registered. Pick something else"; } It is unexpected because else if i You can pass i as a locals to the partial like follows: <%= render :partial => "form_item", :i => i %> and you'll have i available in the _form_item partial. Update: Local variables passed to partials are variables and not symbols. You could keep the name order_item like follows: <%= render :partial => "form_item", :order_item => i %> And update your order_item partial as follows: <%= simple_form_for order_item do |f| %> ..... <% end %> I think I understand why you do not want to change :order_item to just order_item. I think you are going to have to update your other calls to pass in local variable order_item where ever you are making a call to this partial. Change this in formValidate() document.myForm.Name.value == "" to document.myForm.dob.value == "" document.myForm.EMail.value == "" to document.myForm.email.value == "" Do not use document.write("<b>" + day + "/" + month + "/" + year + "</b>"); It will replace the whole contents of your body Your first input of the form is specified as an input for the :user_id which is an integer in your table of users. Putting a full name there is creating a mismatch in data types. Does this help? Now that you want the username to be displayed without the user being able to change what is displayed, is there really a need to have this as an input? Can you just display the username in a normal <div></div>, so to speak? As comments pointed, the submit button does his default action while you are waiting for the ajax. You can get the form to use your function instead of the form action by selecting the form and using the submit method, like this : $('form').submit(function(){ /// function goes here }) try: var form = $('#dropdown'); form.change(function () { var $selected = $(this).find('option:selected'); if ($selected.val() === 'drop_down') { $('.selectobject').hide(); } else { $('.selectobject').show(); } }); Since you are using bootstrap, default properties of bootstrap applies to your input textarea. It causes the problem. I had the same problem but, with columns. You can overcome this problem by two solutions: 1.) Create a class and specify the height and width to be auto. Use the class wherever required. Create this class in your application.css or any css file. .test { width: auto; height: auto; } Now use this class in your ruby code. <%= f.input :description, as: :text, :input_html => { class: 'test', :cols => 5, :rows => 10 } %> Since you have explicitly specified the width and height to be auto, the bootstrap's textarea width, height will be overrided by the local class 'test' width and height. Hence :cols => 5, :rows => 10 properties will be set. 2.) Modif You are using if(isset($_POST['submit'])){ But there's no form element with the submit name and hence it fails to suffice the if condition, you can try replacing this <button type="submit" class="btn btn-primary">Book now</button> with <input type="submit" name="submit" class="btn btn-primary" value="Book now" />
http://www.w3hello.com/questions/-A-simple-question-about-FORM-in-ASP-NET-
CC-MAIN-2018-17
refinedweb
2,809
65.42
SEASIDE A G A Z I N E YO U R W E S T C O A S T C U LT U R E February 2013 M The Doctor is in the House ‌ Dr. Ambrose Marsh talks heart health Dunmora 1920 arts & crafts home built to last Improving Patient Care Doctors talking to doctors Sea of Love Sip & Bid Shaw Ocean Discovery Centre Fundraiser 30 Seaside Goes Mobile! CONTENTS february.2013 YOUR WEST COAST CULTURE ON THE COVER Photo by Cover Design by FEATURES 15 18 dunmora: preserving the past 35 Walk As If Your Life Depended On It Doctors Talking to Doctors: South Island Division of Family Practice centre Sea of Love Sip & Bid: Supporting spread Shaw Ocean Discovery Centre 44 Hot to trot 49 Building a Better Future: Small Modern Living Paves the Way COLUMNS First Word 8 Weatherwit 16 Forbes & Marshall 24 Smell The Coffee 28 Island Dish 49 Last Word 55 are you the woman to watch? 22 DEPARTMENTS 9 10 23 27 32 33 34 Letters Can We Talk? Grey Matters Ignition Common Cents Seaside Arts Scene Trendspotting 43 45 47 50 53 centre spread West Coast Gardener On Design New & Noteworthy Peninsula Restaurant Profile What's Happening Veterinary Voice walking for life 15 10 Delicious & Juicy... Buck Brand Navel Oranges Certified Organic and exclusive to Thrifty Foods, these juicy oranges are polished with a horse hair brush and never waxed for a concentrated sweet flavour. Ask for an on-the-spot sample and ons with Endive Spo ra nge dO Shr imp a n enjoy a delicious Buck Brand certified organic orange today! LISLE BABCOCK BUCK BRAND CITRUS Sidney • 9810 Seventh Street • 250 656 0946 Central Saanich • 7860 Wallace Drive • 250 544 0980 Peninsula Celebrations Society Haro’s Seaside Times Ad January 2013 • Size: 7.75” (w) x 4.925” (h) • Final File • Jan 16/13 fresh flavours, casual comfort, genuine service monday night mussels You asked for them, so we’re bringing them back! Mussel Mondays – a full pound of fresh Gulf Island mussels & our house cut fancy frites for just $15. A savoury selection of delicious recipes to choose from as well as great prices on our large format local craft beers. Valid from 5-9pm every Monday night. Now you know what you’re doing Monday! Make your reservation now! Call 250.655.9700 • Now this is love. Home and Garden 6666 West Saanich Rd, Brentwood Bay 6 SEASIDE | FEBRUARY 2013 (beside Butterfly Gardens) 778-426-4436 • doyleandbond.ca CONTRIBUTORS february.2013 YOUR WEST COAST CULTURE seasidemagazine.ca lorianne koch - Bravo advertising How do you put a spring in the step of a successful magazine? Make it stronger, healthier? Begin with an open-minded publisher who didn’t want to look like or be like any other magazine: she wants to look like … well, the community she serves. A makeover was ordered up, with the direction to preserve the character of the original product. We infused it with some fresh energy through the use of Gotham, a modern, clean typeface that has its bold, strong side when called upon for the heavier work of drawing your attention; a colour palette that reflects Seaside’s environment – steely grey to shore up a vibrant, turquoise-infused array of headers and subheads; topped off with a healthy injection of fresh-faced white to marry the two. The next logical step was to give more real estate to Jo-Ann Way's striking photography that help tell the stories. No fancy embellishments to tart up the old girl: just a nudge toward a sleeker, more sophisticated look to showcase her strengths in clean, open spaces. In the end, the challenge became the reward. It’s been a pleasure. jennifer bowles I was born and raised in Victoria and attended St. Margaret’s School. I fell in love with the food and beverage industry at the age of 14 when I took my first job as a dishwasher at a local fish and chip café. With over 20 years experience in the industry, including owning my own restaurant and working for some the world’s top hotel chains, I continue to fuel my passion by writing the monthly Island Dish column. Featuring recipes from classic comfort food to more adventurous world cuisine, researching and writing the column keeps me inspired! This month I get a little bolder with spicy chilies! Well-known for some of their restorative properties, chilies are a multipurpose food that are super tasty as you will see! Enjoy. dr. shelley breadner As a veterinarian, I put my heart into my work every day, opening up to each animal that comes to me for care and compassion. It brings music to my soul, and I couldn't do it any other way. So, it was apropos to write about heart health for Seaside Magazine's February issue. By sharing some core points (“cor” being Latin for heart ) on maintaining heart health, I hope I may encourage many hearts to beat a little stronger. Of course, chocolate for you (and if you remember, dark chocolate for me!), but NO chocolate for dogs or kitties! Whatever your favourite love song, sing it for your little companion, and your two hearts will beat as one! Publisher Sue Hodgson 250.516.6489 sue@seasidemagazine.ca Editor Allison Smith in Chief 250.813.1745 allison@seasidemagazine.ca Advertising Marcella Macdonald Sales Lori Swan Madeleine Kemp 250.516.6489 This Month’s Contributors Trysh Ashby-Rolls, Rose Bandura, Jennifer Bowles, Shelley Breadner, Dianne Connerly, Gillian Crowley, Michael Forbes, Dave Gartley, Doreen Marion Gee, Linda Hunter, Tracey Jones, Stacey Kaminski, Tara Keeping, Lorianne Koch, Linda M. Langwith, Susi McMillan, Vicki Prince, Steve Sakiyama, Steve Sheppard, Fraser Syme, Megan Walker, Jo-Ann Way, Phil Wooster: steve sakiyama Victoria Airport/Sidney The weather – all of us live with it, breathe it and talk about it … but few write about it. So I am excited to write about the weather in Seaside Magazine, along with some humour and life thrown in. As a child I looked at the sky in amazement, and now as a scientist with the Ministry of Environment and an instructor in Meteorology at Royal Roads University, I continue to pursue this passion. My wife and I have been blessed with two wonderful children, and over the past 22 years we have experienced the full spectrum of West Coast weather while enjoying life in this incredible place. Take a look at this month’s article about weather alerts but be warned: it contains nuts. The Latch the latch inn & restaurant • sidney Emerald Isle Motor Inn Victoria Airport Area Cedarwood The Inn and Suites SEASIDE | FEBRUARY 2013 | 7 first word 2013 In the time it takes you to read my column, your heart is pumping about five quarts of blood (that’s about 10 pints) through more than 60,000 miles of arteries, veins and capillaries – that’s further than twice around the world. Depending on how long you live, your heart could beat three billion times in your lifetime. Your fist is about the size of your heart. The organ is not heart-shaped at all: it’s more like a cone and weighs about 11 ounces. The heart is a muscle sandwiched between two protective layers. Inside are four chambers, two on the right and two on the left. Blood that is low in oxygen, from all parts of the body, returns to the right side of the heart to be pumped through the lungs where oxygen is replenished. Then, once again, it is pumped all around the body by the left side of the heart. So you’re wondering why I’m telling you all this? Well, quite simply, your heart’s purpose in life is life support. No heartbeat: no life. February is Heart and Stroke Awareness Month. In this issue of Can We Talk, Seaside Magazine interviews Dr. Ambrose Marsh, Saanich Peninsula Hospital’s Chief of Staff. He is the hospital’s most passionate advocate and a truly dedicated doctor, often called "Patch" by his staff. In this exclusive interview, Dr. Ambrose offers advice on what we can do to lessen heart disease risk. In his frank discussion, he looks at the heart of the matter … your heart. A big part of staying healthy is maintaining a healthy routine; understanding the real facts is key. Over five years: quitting smoking (for men over 55) will save seven lives; walking 40 minutes, five days a week will save approximately 3.5 lives. Peter Mason, co-owner of Pacific Rim Wellness and maker of Go Time pedometers, echoes very similar ideals in our article on pg. 15, and says that even though "modern medicine has enabled us to live much longer lives, walking may be as close to a magic bullet as you’ll find." Please remember to attend the Hearts of the Community Awards on February 21st at the Mary Winspear Centre. The annual event, now in its 15th year, is sponsored by Beacon Community Services and the Peninsula News Review and honours the efforts of Saanich Peninsula volunteers. So follow the yellow brick road to health, counting yourself lucky that, unlike the Tin Man, you have a heart, and protect it. TO WATCH Women in Business: Inspiring and Celebrating your success on the Saanich Peninsula. Deadline: February 11th, 2013 250.516.6489 sue@seasidemagazine.ca SEASIDE A G Publisher WOMEN Special Advertising Supplement March Issue of Seaside Magazine. M Sue Hodgson, A Z I N E 8 SEASIDE | FEBRUARY 2013 YO U R W E S T C O A S T C U LT U R E letters Life is Better When You’ve Been Kissed by the Sun! Seaside Magazine welcomes your feeback! Send letters to the editor via allison@seasidemagazine.ca or post your comments on our Facebook wall! Letters may be edited for space and content. Congrats on the redesign of Seaside – makes for an even more enjoyable read. Michael Marshall I'm thoroughly enjoying the magazine and the content, layout and overall feel of Seaside just gets better and better. I'm proud to advertise in such a great magazine. Geraldene Coates, Marmalade Tart Boutique I love a mobile site that is minimalistic and user friendly. You nailed it. Danielle Ronin I really love your magazine and the message of supporting local businesses and people but honestly your last issue was almost entirely advertisements! The new layout just seems to blend all of the articles in with the side adverts and I am really missing the old layout. Sorry Seaside, but I think you need to rethink your redesign. Sincerely, Your number one biggest fan! Primary Logo: SAANICHTON VICTORIA Wallace @ Mt. Newton back of the building on Vancouver Street between Yates & Johnson 250.652.8343 250.386.4826 Primary Logo Reversed: Vibes F I T N E S S The Body You Want, In the Time You Have “I would highly recommend Vibes to anyone looking for a quick, customized workout. Since there is always a trainer working with me, I feel confident that I will avoid injury and get the most out of my workouts.” - Neil Robertson Stacked Logo Reversed: Stacked Logo: Wow, to take something that is exceptionally good and make it better … you guys did it! John Howey Your timing could not be better for our 25th Anniversary article and my colleagues and I are truly grateful. We can understand why Seaside Magazine is so deserving of the awards you have received. It goes without saying that you definitely have our vote for more. Frank Hawboldt, Sidney Knights of Columbus Stacked Logo Grey: Start your free week trial today! Winner of the 2012 Crystal Award for New Business! Fonts: Logo Text: Walkway Expand, Bold, Black, Ultra Expand Black I love your new look, it gives the magazine a real polished look and feel … great job! Graham Kia 778.426.2146 • • Body Text: Univers 47 Light Condensed 108-2506 Beacon Avenue, Sidney I have to again thank your magazine. I picked up three new clients for my Fab 40 Workout and bootcamp classes after January's ad. All of you have been so good to me. Joanna Vander Vlugt, Champs Personal Training land ’ s end the height of luxury Love the new simplicity! Peter Ellmann I've just had the pleasure of reading the latest issue of the newly redesigned Seaside. You have done a fantastic job with the new look and logo: it's fresh, classy and contemporary. I love the Seaside going mobile app and Seaside Homes section. Rhino continues to bring the highest quality printing to the table each and every month and it shows. From what I can see, you are the only magazine using this type of printing on the South Island.I can't wait to see what you all will come up with this year. Tim Flater Knickerbocker's Jewelry & Home Accents | FEBRUARY 2013 | 9 c a n w e ta l k publisher sue hodgson talks with general practitioner ambrose march, Saanich Peninsula hospital chief of staff You’ve spent over two decades as a physician, working in a variety of capacities. You are currently Chief of Staff at the Saanich Peninsula Hospital, while also running your family practice in Sidney. The two components of your work week are very diverse in nature: one a management role with a vital community hospital, and the other with its major focus on the prevention and treatment of most acute illnesses and management of chronic medical problems. How does each role benefit the other? The interplay between those two roles is an interesting one. If my colleagues and I do a good job at preventing and treating chronic diseases, we can in fact reduce (not eliminate) acute hospital admissions, thereby taking some taking some pressures off our hospital's persistent over-census status. The interplay also illustrates one of my challenges as CoS at SPH, and that is attracting new family physicians to the Peninsula as it is a well-known fact that the prevention and management of chronic diseases is clearly better managed when coordinated by a consistent primary caregiver (General Practitioner, Family Physician or Nurse Practioner). In this issue we are celebrating “Heart & Stroke Awareness Month.” This is an important time to take control of your health in order to prevent heart disease and stroke, something that’s robbing Canadians of nearly 250,000 potential years of life and killing more women than men. Why do you think so many Canadians don’t understand, or listen to, the risks factors for heart disease, such as smoking, high blood pressure and cholesterol, diabetes, obesity and physical inactivity? The million dollar question. I think we are victims of two major things: advertising and denial. Add to that the very great challenge of "changing" our established lifestyles/habits and it becomes very complicated. None of these issues around heart health (don't smoke, lose weight, be active, eat wisely) are new! People need to realize the medical treatments available at the present time are NO substitution to changing health behaviours. Our treatments do NOT cure or reverse chronic 10 SEASIDE | FEBRUARY 2013 diseases like heart disease or diabetes or lung disease: they stabilize and slow progression. The only way to reverse these diseases is to stop the offending behaviour BEFORE permanent damage is done and that varies from disease to disease and person to person. I’ve researched some of the statistics on heart disease and stroke and they’re staggering. Both are the leading cause of death in Canada. Imagine: that’s one death every seven minutes in Canada –70,000 people a year die from heart disease or stroke. As a physician with a wealth of knowledge, are we doing everything we can for our patients? A question with a very long answer. Two points: the actual number may be inflated (although still very significant) as we take this data from death certificates and all people have to have a "cause of death." Even at 88 or 96 years of age, heart attack can be listed as the cause of death; at some point that is a natural, unavoidable death. Secondly, asking whether "we" are doing everything for our patients makes it sound like it is soley the health care system's responsibility to improve these numbers. Those of us in health care can probably do a better job and have been doing a better job over the last decade in this area, but social policy (smoking, education, food politics) will have a bigger part in improving these stats. Most people with a strong family history of heart disease have one or more risk factors. Just as you can't control your age, sex and race, you can't control your family history. Therefore, it's even more important to treat and control any other risk factors you have. Is there an interactive tool out there that can assess the risk of heart attack or dying from a coronary heart disease, say in the next 10 years? If you google cardiac risk calculator you can find a number of calculators from reputable sources. These are not useful if you have had a heart attack or angina or if you have already been diagnosed with diabetes. They focus on blood pressure, smoking, cholesterol and gender; we have yet to really quantify issues like family history and stress in the risk calculation. They are still worth checking: it may help people recognize their actual health status. OK, let’s talk about our youth. It’s a known fact that heart attack prevention begins by age 20, maybe younger. What does this mean and what should parents be considering now, before it’s too late? Whether it is heart attack prevention or lifestyle education, we must start earlier to help our children and youth make wise, healthy, lifestyle choices, because these choices over time will reduce cancer, premature death from all causes and improve quality of life – ie, an overweight person, no matter what he or she will die of, has issues with sleep, energy, joint pain, shortness of breath … well before they have a heart attack or die. Dr. Ambrose Marsh General Practitioner Saanich Peninsula Hospital Chief of Staff Dr. Ambrose Marsh has been a General Practioner in Sidney, B.C. since 1988. He graduated from the University of Western Ontario in 1979. Parents, schools and government have a role in taking on this challenge. Specifically for parents, we can help our children understand good food choices and healthy eating no matter our budget – but it must be said that income can have an affect on food choices. Teaching the avoidance of smoking, the importance of regular activity and a intelligent role for responsible drinking can also be started by us as parents. Physicians are maxed out, hospitals are at their capacity and heart disease and stroke are number one killers. What do we do? If you had an opportunity to change or enhance two things in the medical world that would make a difference now or for our future, what would it be? I have a very strong bias here, and in fact the last two questions can go together and tie in with the first. When I graduated, people who did not have a GP did so by choice. In the '80s and early '90s we actually limited the number of family physicians in many communities; now there is a dire shortage. I strongly believe that having a primary caregiver can develop a relationship, creating a continuity of care that may help people avoid many chronic diseases which have lifestyle factors. They can also care for them with their chronic diseases, no matter the cause, to maintain the best quality of life possible. This will take the government, universities and the medical profession to believe that this is an important and necessary focus. As citizens we can strongly advocate in this area. Photo by. MICs aren’t good investments. Good MICs are good investments. To learn more, call Barb Gallup @ 250-475-2669 Father of three boys (all soccer keepers), he stays active with bicycling, soccer and his storied hockey career. Together with his wife, Dr. Leah Norgrove, a Family Physician in Vic West and the palliative care consultant at Saanich Peninsula Hospital, Dr. Marsh created the Bombo Palliative Care Project to aid in the development of a palliative care program in Northeast Tanzania. This is not a solicitation to purchase securities, which is being made under an Offering Memorandum that details risks and is available from our offices. Mortgage investments are not guaranteed. Returns will fluctuate and past performance may not be repeated. SEASIDE | FEBRUARY 2013 | 11 12 SEASIDE | FEBRUARY 2013 The Ghosts of D'Arcy Island by Doreen Marion Gee Just off the coast of our peaceful seaside community, unquiet ghosts rage against the gods in the morning mist. Our wild West Coast beauty harbours a very ugly piece of human history. D'Arcy Island was a leper colony from 1891 to 1924. It housed society's untouchables – pushed far away from human contact. The lepers were tossed into isolation, forgotten and abandoned and left to rot and die under an unforgiving sky. This was racism at its poisonous peak. The two D'Arcy Islands are located about five miles off the Peninsula coastline. Both islands hosted the leper colony and are simply named together as D'Arcy Island. The notorious lazaretto was established in 1891 by the municipal council of Victoria, B.C. One infamous day in 1891, Victoria's Police and Health officers found five unfortunate Chinese men riddled with leprosy in the damp back alleys of Chinatown. In a knee-jerk, self-serving racist reaction designed to curry public favour, the public officials acted quickly to get the province's "OK" to dump the lepers on D'Arcy Island. Prejudice is malignant; the locals happily waved goodbye to their sick neighbours: "More repulsive human beings would be hard to imagine." (Daily Colonist, May 21st, 1891). One cursed soul attempted suicide at the internment house on Fisgard Street. Around May, 1891, the afflicted were sent to the Gulf Island death chamber. Until 1924, a total of 49 Chinese lepers were shipped to D'Arcy Island. Left to fend for themselves, many died there. Every three months, a supply ship came with food – and coffins. Ramshackle huts were built as a futile defense against wicked winters. Those severely ill, crippled human beings on D'Arcy Island received no medical care or medicine to relieve their suffering. Circa 1898, Dr. Ernest Hanington of Victoria writes a heart-rending account of the outcasts condemned to a living hell within the green fields of paradise:) "The wretched beings, some in the last stages of the disease … lined up on the beach and cried like children when we were leaving." Hatred of the Chinese was rampant in the 1890s. White workers on the coast felt threatened by Chinese immigrants who outworked them on the railroads and in the mines. There was no political incentive to help the victims of D'Arcy Island. While Chinese lepers were sentenced to a grim West Coast death, those afflicted with leprosy at a New Brunswick colony were given humane medical care in a hospital setting by the federal government. Why? Because they were Caucasian. In 1924 the D'Arcy colony was closed for good, ending a shameful chapter in Canadian history. However, we still need to keep the tragic victims of D'Arcy Island alive in our hearts to remind us that we can never give up the fight to eradicate racism and prejudice from our communities. The ghosts of D'Arcy Island are watching us as a red sun lingers over a blue green utopia. They are listening … and they are waiting. Sources: Stephen Ruttan, Local Library Historian, VancouverIsland.com, "Island of Shadows" (documentary). Optometry Central Saanich Clinic Discover the Secret of Fuller, Longer and Darker Eyelashes! 0 Weeks 16 Weeks Get the Lashes You Have Always Wanted! Call for more information at 250-544-2210 reception@cseyecare.com SEASIDE | FEBRUARY 2013 | 13). A Boarding Kennel that loves your pets as much as you do. More Than JusT hardware: • gardening supplies • patio & BBQ gifts • sports accessories • tools • toys • culinary and kitchen supplies … and much more! From Household Supplies to Outdoor Products … 14 SEASIDE | FEBRUARY 2013 Your local hardware store offers a wide range of goods and services 2356 Beacon Avenue, Sidney 250.656.2712 by Fraser Syme north saanich family walks for life: Peter Mason steps out with wife Lois, son David, daughter-in-law Maren and granddaughter Charlie I just finished a regular Monday morning walk with Peter Mason, co-owner (with Rob Dyke), of Pacific Rim Wellness, makers of Go Time pedometers. Peter walks 10,000 plus steps every day (at a fair clip too, I might add) and has done so for over six years. I asked him why he walks every day. He shot back: "It's my non-negotiable." After a moment to reflect, he gave me three more answers which, when I put them together, seemed like pretty good reasons to get off the couch. Quoting Dr. Manson, a medical doctor from Harvard: "Walking may be as close to a magic bullet as you'll find in modern medicine. If there was a pill that could lower the risk of chronic disease like walking does, people would be clamouring for it." He followed that with Dr. Steven Blair's research of 54,000 men and women that showed the best predictor of early death was low cardio respiratory fitness, which can be mediated by 30 minutes daily of brisk walking. Lastly, and somewhat tongue in cheek, he quoted a line from the cult classic film, The Princess Bride, in a dialogue between Prince Humperdinck and Count Rugen. Humperdinck says: " … I've got my country's 500th anniversary to plan, my wedding to arrange, my wife to murder, and Guilder to frame for it. I'm swamped." Count Rugen replies: "Get some rest. If you don't have your health, you haven't got anything." Mason observes that modern medicine has enabled us to live much longer lives. As a Peter walks 10,000-plus steps every day and has done so for over six years. "It's my nonnegotiable," he says. result, "What we really need is our health. We are truly a blessed generation. No world wars, global Depression or epidemics, yet two thirds of deaths today are self-inflicted. Smoking is responsible for one third of those deaths, and another third are 'lifestyle' related, including alcohol abuse, obesity, and inactivity." He says: "What do I want to do for the next 30 years? I’m 60. If I’m healthy, I can travel, volunteer, enjoy the outdoors, work in the garden, pursue hobbies. I have four children and one grandchild. I intend to be there for them. Walking is such a simple way of ensuring that." His friend, Martin Collis, adds: "We come with roughly a 100-year warranty, but you’ve got to read the fine print. You’ve got to move." "I want to live a long, productive life." He says the ideal goal is 10,000 steps a day. "Victoria is blessed with so many places to walk. There are park areas, trails, your own neighbourhood; I’ve walked in malls, on the ferry, around soccer fields during my childrens’ games, in airports waiting for flights – the opportunities are endless: I’ll walk anywhere." He advises someone just getting started with a walking regime to begin with small, manageable goals that are sustainable, then gradually increase distance and difficulty leading to the 10,000-step goal. "Start with 10 minutes a day, and gradually increase the time to 30-60 minutes. That’s where a good pedometer is handy. It keeps track of steps, time, and the all-important intensity (elevating your heart rate). It keeps you accountable. I call it my conscience in my pocket." Finally, he quotes Yoni Freedhoff’s eightword manifesto for exercise: "Some is good, more is better, everything counts." SEASIDE | FEBRUARY 2013 | 15 photo courtesy Walk as if your life depended on it w e at h e r w i t "weather forecasts can include messages to alert us about current or potentially hazardous conditions" Warning: This Article Contains Nuts by Steve Sakiyama I was about to take a sip of my takeout coffee when I noticed a label on the cup: "Caution: Hot and Delicious." I guess this means people don’t expect their coffee to be delicious – so the first few sips must be taken very carefully to avoid unfortunate surprises. This reminded me of other odd warning labels, such as the one I saw on a large yellow KEEP OUT sign. Written in small print along the bottom of the sign were the words: "DANGER: This Sign Has Sharp Edges." Very important information you know, especially if you need to fillet a halibut or slice a large bologna roll – which is the first thing I think of when confronted by a big KEEP OUT sign. "Look, a KEEP OUT sign! Quick, hand me those pork chops so I can trim off the extra fat … now everybody stand back." Don’t get me wrong: we need warning labels (especially for people like me) but some can be truly bizarre – like the ones Forbes Magazine discovered for these products: • Iron: "do not iron clothes on body" (really … who does this?) • Vanishing fabric marker: "do not use for writing cheques" (gives "blank cheque" a whole new meaning, don’t it?) • Hair dryer: "do not use while sleeping" (so this explains my terrible morning hair) • Letter Opener: "safety goggles recommended" (mother was right, everything will poke my eye out) • Superman costume: "this costume does not enable flight or super strength" (Steve, get off the roof … NOW!) Speaking of warnings, weather forecasts can include messages to alert us about current or potentially hazardous conditions such as heavy rainfall, strong winds and blizzards. Based on specific criteria, Environment Canada can issue three types of notifications that escalate in levels of concern from Special Weather Statements (when there are unusual conditions that could cause concern), to Watches (when conditions are favourable for a storm or severe weather, which could cause safety concerns) to Warnings (urgent messages that severe 16 SEASIDE | FEBRUARY 2013 | weather is either occurring or will occur)1. This critical public service provides timely information so we can take appropriate action to prevent harm to ourselves and property. Will the signs pointing to February’s weather include a warning about sharp edges? Not likely. The long-term models point to equal chances of above-normal, below-normal and normal conditions for both temperature and precipitation. Given that nothing is tipping the scale one way or the other, I’ll go with a "normal" month weather-wise. I love February. It has Valentine’s Day, Ground Hog Day and this year, on the 11th, there is Family Day. My sentimental forecast for Family Day is a steady breeze, so we can go outside with family and friends and enjoy the fresh air in the incredible natural beauty around us. Yes, a day when I will wear my freshly-ironed Superman costume and stand on the roof with my scarlet cape unfurled in the fresh breeze and shout: "Hey, look out below!" ~ Weatherwit Any weird warning labels or questions about the weather? Send them to weatherwit@gmail.com or visit my blog at. (1) Environment Canada () Sterling silver charms from $30 Royal Oak at Broadmead Village 250.658.5578 Sidney at the Pier Hotel 250.656.5506 knickerbockers.ca Don Bellamy info@donaldbellamy Markets are Changing. Jack Barker Lisa Dighton jack@jackbarker.net ldighton@shaw.ca Craig Walters Karen Dinnie-Smyth craig@craigwalters.net Ross Shortreed ross@rossshortreed.com kdinnie-smyth@shaw.ca Call one of our Experienced Agents with Local and Global Connections to get you sold. Tori Feldman torifeldman@shaw.ca Stephen Gagnon, AMP Kelly Curtis, AMP Mortgage Planners Gaye Phillips gayesoffice@shaw.ca Beverley McIvor bevmcivor@shaw.ca 250.744.5557 #2-4440 Chatterton Way, Victoria BC Gay Helmsing ghelmsing@gmail.com Debbie Gray sagegray@shaw.ca Doctors talking to doctors photo courtesy by Gillian Crowley working together: (from left) – Family Physician Dr. Menuccia Gagliardi; Dr. Andrea Lewis, SIDFP board chair; Dr. Elizabeth Rhoades, SIDFP secretary-treasurer When you or a family member is ill, you want your family 18 SEASIDE | FEBRUARY 2013 2353 Bevan Avenue, Sidney 250-656-5441 • 1-800-561-2350 Call 250.656.5441 for All the Details! sidney@cruiseshipcenters.com • BC Reg 2550 6 physician to have the answers – or at least get you an appointment to see a specialist quickly. Accessible medical support is part of what makes a community healthy and attractive. But where do the physicians go when they want to discuss a particularly difficult case? Or if they think "It seemed a natural fit there’s a better way their patients could being able to work access other parts with another group of of the health care physicians … to improve system? Until recently, the care we're able to particularly in semirural areas, family give our patients." doctors were pretty well on their own unless they practiced in a clinic. Now there’s an organization that helps physicians collaborate. Starting in fall 2010, local doctors have been able to join the South Island Division of Family Practice, which covers Central Saanich, Sidney and North Saanich and the West Shore communities of Colwood, Langford, Metchosin and Sooke. The Division, one of 31 across B.C., gives front line physicians a bigger voice within the provincial health care system and helps them work together on problems affecting patient care. Dr. Elizabeth Rhoades was one of those sold early on the advantages of joining the Division's initiative. Formerly a family doctor in northern B.C., Dr. Rhoades has practised in Saanichton and Sidney for the past six years. She says: "I’ve spent many years just seeing patients in my office and more or less working on my own. So it seemed a natural fit being able to work with another group of physicians [through the Division] to help improve our practices and the care we’re able to give our patients. And I’ve learned so much along the way." In 2010 Dr. Rhoades volunteered for the role of co-chair along with Dr. Jeff Pocock from Sooke. She recently moved over to the secretary-treasurer position and Dr. Andrea Lewis (Sidney) became the board chair. For a young organization made up of busy doctors, SIDFP has taken on an impressive array of activities and initiatives. Patients suffering hip and knee degeneration will appreciate the new collaboration between family physicians and orthopaedic specialists to develop a streamlined patient referral and triage process (the method of prioritizing patients based on greatest need). Gastroenterologists are working on a similar initiative and several other specialty areas have expressed an interest in participating. The Division’s membership is encouraged to identify events and educational activities of greatest interest. Recent activities have ranged from collaborating with the Vancouver Island Health Authority on a maternity clinic for "at risk" mothers to holding a mental health workshop where family doctors and mental health practitioners explored best practises. Another workshop examined how to best recruit and retain locums (fill-in physicians) to allow doctors time away for illness, vacations and other personal needs. With a limited supply of locums province-wide, the concern is that one region will end up "stealing"them from another. SIDFP’s workshop report will feed into a provincial strategy that tries to recognize regional needs and interests. Patients will notice their doctor’s office is changing. Banks of patients’ paper files are disappearing, replaced by computers. A growing number of physicians is accepting the advantages of electronic medical records (EMRs) and other types of office automation. This past January, SIDFP held a kick-off event to encourage doctors and their office administrators to set up EMR "communities of practice" and specific user groups to assist one another. So far almost two-thirds of the Division’s family physicians and specialists have adopted an EMR system. The fact that more than 90% of family doctors in the region have become SIDFP members speaks to its success. Dr. Lewis says: "I’ve been impressed by the commitment and optimism shown by those Division members who have taken part in a wide range of activities to support positive change. I’m looking forward to chairing the Board as we continue to work with our members to identify new priorities." | FEBRUARY 2013 | 19 y e n d i S s e u q i t u Bo e v o M e On th We are all so excited with our new location! After we closed the doors on New Year’s Eve, toasted in the New Year and enjoyed the break, the hard work of moving all our beautiful shoes and bags to their new home began. We added some amazing clothing by Desigual … with more to come … and opened again on January 7th. The response has been so supportive and we appreciate all our customers’ comments so much: you are why we’re here … and why we are growing! Sandy Baynton first envisioned Waterlily four years ago after returning from an extended stay in Switzerland. Her favourite little shoe shop (Footsteps) had closed in her absence and, while sitting enjoying a chai at Georgia’s Café, she noticed a “For Lease” sign just across the street. The pen started doodling, the mind pulled up an image, a business plan emerged that seemed to make sense …. We hope you’ll take the time to drop in and say hi; the Spring and Summer styles are starting to arrive and Sandy tells us there will be new brands joining her established lines as well. You will see why Waterlily has become a destination for so many visitors, and there will even be an online store in the near future! This is an exciting time for Waterlily, and a great success story for Sidney and the Saanich Peninsula. #101 - 2537 Beacon Avenue, Sidney 250.656.5606 Many people were surprised when Laura McLarty opened Flush Bathroom Essentials. “How can you expect to pay the rent by selling bathroom stuff ?” the naysayers bleated. “Good luck,” they added as they rolled their eyes. Now Flush has four profitable years under its belt and is expanding into the vacated Waterlily Shoes space while the latter moves to larger premises. Laura’s many years as a retail buyer in home products has allowed her to identify an important niche. Bathrooms are numerous in most homes, and they’re updated regularly. There are very few sources for good quality and up market accessories. As a matter of fact, there are very few indeed that bring all the elements together in meaningful selection. Flush answers these needs. Customers from Vancouver and Victoria regularly patronize the store; Laura is pleased by how many U.S. customers state they have never seen such a great selection anywhere, nor presented in such a professional way. Base offerings are organic cotton towels, robes, and pajamas; bathmats, vanity mirrors (best selection anywhere); design forward bathroom hardware; functional accessories such as shower and tub organizers; counter accessories; heated towel racks (best selection anywhere); unique shower curtains; Canadian-made body care products and décor. The new expansion will feature a line of proprietary hardwood vanities and stainless steel wall hardware. No wonder the professionals are using Flush as a one-stop source for outfitting bathrooms in style. Be sure to visit Flush Bathroom Essentials soon; it’s a beautiful, expertly merchandised store that will provide you with lots of inspiration. #102 - 2537 Beacon Avenue, Sidney 250.655.7732 Sidney Boutiqu es On the M ove 2013 - 2 n d A n n uA l - WO M A N TO WATCH conTesT Women in Business: Inspiring and Celebrating Your Success. Are you a woman in business? If so, Seaside Magazine and yoUnlimited, in conjunction with International Women's Day, is looking for you! If your business is 51% or more owned by a woman, and you are doing business on Vancouver Island, you are eligible to apply. All applications will be reviewed by an independent panel of judges and a winner will be selected. Please answer all questions below. Winners will be notified by February 28th and will be honoured at a reception to be held March 8th as part of Seaside Magazine’s Women to Watch event. Please answer the following questions about your business: • Describe your business: Please provide a summary and description of your business, including how long you've been in business, number of employees and products and services offered. • Innovation & Change: Please list all of the changes and innovations your company made in 2012. • Environmental and Community Advances: How does your business contribute to the community and environment? • Challenges: What is the single most difficult challenge you have faced and how was it overcome? • Integrity: What three words best describe your business values? WIN! Winner will be showcased in the Women To Watch special edition of Seaside Magazine (March edition) and honoured at a private Seaside Women To Watch reception March 8th. She will also receive a complimentary ticket to the yoUnlimited Conference; a “Start your Engines” Package with Pauline Penner of Jump Start; a private fashion consultation, including new outfit, from Marmalade Tart Boutique; and a hair style from Samantha Lipinski. Total Value over $1,000! Deadline for application is noon on February 14th. Apply at: 250.516.6489 sue@seasidemagazine.ca SEASIDE M A G A Z I N E YO U R W E S T C O A S T C U LT U R E g r e y m at t e r s "one of the single most important things you can do to safeguard your heart health is to educate yourself" Love in Heart & Stroke Month At age 70, Jochen Mueller had everything he wanted. A home in the country filled with books, a sound system worthy of his CD collection of classical and folk music, space for building model boats, room for painting, gallery representation, a close relationship with the three daughters he’d raised alone since his first wife – his high school by Trysh Ashby-Rolls sweetheart – died in 1982, grandchildren, close friends and, most recently, a girlfriend “who didn’t rearrange the furniture.” Illness that had him hospitalized in the ICU in 2010 had left him with renewed appreciation for life. He’d lost a mass of weight, with which he’d battled for years. Yes, he admitted, he could have done better. Like cut out the double helpings of crispy crackling on pork roast. Eat fewer Tim Horton’s donuts maybe. Better to eat more veggies and fruit, he told himself. Exercise more than a once-weekly swim. Drink more water, less coffee. At least he’d stopped smoking, and drank only occasionally. His blood pressure was up a bit, but whose wasn’t? According to a brochure from the Heart & Stroke Foundation, “One of the single most important things you can do to safeguard your heart health is to educate yourself about your risk factors. And then make some changes … .” Starting now. In fall, 2012, Jochen and his girlfriend planned a trip to see his Health Within TCM & Acupuncture 250-656-2067 • Inner Champ Gritty, Not Pretty 1 to 4 times/week – Feb 4 to Mar 1/2013 Slam Ball, Boxing, Kettlebells and Spinning Early Riser Workout/Semi-Private Class Mon, Tues, Wed & Fri: 5:30 to 6:10 am or 6:20 to 7:00 am. $10–$13/class Registration Required • sports injuries • stress & pain relief • hormone balancing • digestive disorders • allergies & cough (Up from The Roost & off McTavish Road) Find Your 40-Minute Garage Fitness Natural health care for the whole family by skilled and experienced practitioners 9156 Cresswell Rd, North Saanich brother, a noted rock 'n roll guitarist, play a concert. It was a great evening. But halfway across the parking lot his legs “felt funny. I could hardly breathe.” “D’you want to stop at a hospital?” she asked. “Nah. If it’s still bad I’ll go tomorrow.” They went home to bed. To quote from the same Heart & Stroke Foundation brochure: “… the warning signs of heart attack and stroke are also important steps to taking charge of your heart health. Talk to your doctor about all your risk factors and what you can do to make positive changes.” Take the online assessment for heart and stroke risk. By the next morning the squeezing sensation down Jochen's left arm was so painful there was nothing for it except dial 911 for an ambulance. Doctors at Emergency ordered immediate tests that confirmed a heart attack. Further tests shocked both Jochen and his daughters, who insisted on flying to his bedside right away: he needed a quadruple bypass as soon as possible. The heart specialist would perform two surgeries a couple of months apart, but predicated a full recovery. What happened next was entirely unexpected. Two days after the first operation, Jochen had a stroke. On life support in the ICU, his daughters and the doctors took a wait-and-see approach. A few days later, however, staff moved their still unconscious patient from intensive to palliative care. Things didn’t look good. The palliativecare team called a meeting with his daughters “to make some hard decisions.” They went out to buy special items and flowers to make an altar in their Dad’s room, although they weren’t allowed to light candles. While sitting by his bedside, singing and talking to him, he suffered a massive second stroke. The “hard decision” made itself. Jochen breathed on his own for five hours. “He looked totally at peace,” wrote his middle daughter. “He was there when I took my first breath. I was there when he took his last.” My Heart & Stroke Risk Assessment™ is at wwwheartandstroke.ca/risk. Bootcamp Classes (60 min) Sun @ 10 am/Tues and Thurs @ 6:00 pm $8–$8.50/class Beginning Jan 6, 2013 at Saanich Fairgrounds Mikiala Christie BA, RAc, R.TCM.P Dr. Jeffrey Jones TCM 250.893.5055 • Joanna Vandervlugt • joanna@champspersonaltraining.com SEASIDE | FEBRUARY 2013 | 23 forbes & marshall "If you start welling up while watching marley & Me, try to muffle the sniffling by packing your mouth with handfuls of popcorn" Mr. Perfect You know the scene in Back to the Future where Michael J. Fox's character Marty messes around with time so much that when he looks at a family photo he begins to fade away? by Michael Forbes That's happening in my life right now in the strange world of online dating … and it's being perpetuated by my own father. My dad assumes he has to dance around his age to attract the right women, and I've become the first casualty. Online, the in-theirtwenties offspring from his second marriage seem to fit his fudged age perfectly, and I have simply vanished. If things get too serious with a cyber lady, he'll eventually have to admit I exist. Otherwise, it would be impossible to intoduce me as his son, considering his bogus profile now makes my old man three years younger than me. Don't get me wrong: my dad has lots of intregrity and he isn't the first man to have stretched the truth in order to attract a women. Men of all "alleged" ages sometimes do whatever it takes to be Mr. Perfect. It's a difficult thing though, to live up to being Mr. Perfect, when you consider the massive survey done by the dating website www. whatsyourprice.com. They asked thousands of women who he would be. Turns out, he has to have green eyes, brown hair, be a non-smoker, have a British accent, a degree, be capable of having a loving relationship and make between $150,000 and $200,000 a year. Considering most men can’t live up to this list, we find ourselves trying to guess what women want, and sometimes it ends in an epic fail. Perhaps we need to concenrate more on what women don't want! So here goes … . First, cry very little. If you start welling up while watching Marley & Me, make sure it's in a dark theatre and try to muffle the sniffling by packing your mouth with handfuls of popcorn. Too much crying makes you seem emotional and needy. Every women desires a man that she feels might actually rescue her, instead of the type that becomes a puddle of tears while watching kittens on TV play with toilet paper rolls. Lisa has told me the only time she'll accept crying in public is if I deliver the eulogy at her funeral. Second are PDA's. Public displays of affection are OK if you're fifteen. If she needs someone to constantly paw her to prove she's loved, she'll get a puppy. I have also learned through experience that making out within sight of your father-in-law is not a good idea. Lastly, you must reduce the amount of baby talk. Nothing will introduce the creep factor more into those intimate times than whispering the words "Pooky Bear want Num Nums." Also be aware: she will share this moment with her girlfriends. Being Mr. Perfect is less about what you have and more to do with eliminating those things that will drive her away. There are, however, exceptions to every rule. Apparently, I've just learned, she'll allow you to hug her in public, while crying like a baby, if you make more than $150,000 a. For Little Paws Announces New Head Groomer Janet Lynch! Big Paws Always Welcome Too! Open Tues through Sat 9 - 5 #3-2490 Bevan Ave, Sidney 778-426-2587 ForLittlePaws@shaw.ca 24 SEASIDE | FEBRUARY 2013 Carol-Marie Crofton, Owner with Parker Janet Lynch, Professional Groomer with Marnie Take Heart: Chart Your Own Destiny by Doreen Marion Gee In the new millennium, a zillion options exist for living better, healthier and longer. Panorama Recreation Centre is on board with an exceptional program to optimize health and extend longevity: "Take Heart." The lucky participants have the power to map their own fate and create a healthy long future for themselves. Here are the staggering statistics for "Heart Month:" Heart disease and stroke take one life every seven minutes and 90% of Canadians have at least one risk factor (Heart and Stroke Foundation). The staff at Panorama want to reduce those numbers. "Take Heart" is a cardiac rehabilitation program offered at local recreation centres in partnership with VIHA. Melanie Alsdorf, Panorama’s Fitness, Weights & Rehabilitation Coordinator, explains that many participants are there to rebuild their health after a cardiac event but she encourages people with risk factors to also attend as a proactive preventative measure. Accordingly, this rehabilitation program also accepts participants who have other chronic conditions, such as respiratory illness, high blood pressure, diabetes, depression and lung & kidney disease (VIHA brochure). The amazing benefits of this cuttingedge initiative include improvements in fitness, heart rates, blood pressure, sugar levels and quality of life. "Anytime" registration involves: doctor assessment, referral and monitoring; interview; one-on-one exercise session; 23 twice-weekly group exercise sessions in a self-paced individualized program; final maintenance sessions – all delivered by highly trained staff. The sessions include cardiovascular and strength training, endurance and stretching components. Blood pressure and heart rates are measured before, during and after. Participants gradually make their cardiovascular systems stronger and more efficient. • • One of Melanie’s first gigs was facilitating the Panorama "Take Heart" program: "It was very rewarding to see such a great change in people over three months and to see how much they improved." The statistics sing the benefits: "A recent meta-analysis of trials conducted over the past decade confirmed that cardiac rehabilitation reduced all-cause mortality (after an event) by 25 per cent." (Resource Manual). Personal stories are the best litmus test. Emmy Secord started "Take Heart" in 2006 after a cardiac event. She gushes about the program in the Panorama 2008 program guide: "My fitness and flexibility greatly improved, my blood pressure decreased and … my quality of life changed with the increased stamina, strength and energy I had." The real value of the "Take Heart" program is putting people in the driver’s seat when it comes to their health. The program helps participants stave off dark bitter endings. "Take Heart" empowers people to take control of their own health and longevity by building their defenses against relapse or heart disease to begin with. It gives people the power to control their own destiny. Contact:, malsdorf@panoramarec.bc.ca. Marmalade Tart Boutique Fun, Flirty, Fabulous Fashion! Featuring The Season’s Hottest Collection of Cruise Wear: Chalet, Tricotto, Neon Buddha … and more! MT Mon - Sat 10-530 • Sun & Holidays 1130-5 Landmark Bldg – #102-2506 Beacon Ave, Sidney 778-426-3356 • SEASIDE | FEBRUARY 2013 | 25 Car BuYiNg 101: a FriENdlY guidE A new series brought to you from the experts at Motorize Lesson 1: Cars depreciate by model year and by mileage; a combination of the two will get you the right vehicle to suit your budget. Buying a brand new car might seem like a great idea until you realize you’re suffering 20-22% depreciation in the first year of ownership. That’s enough of a loss to outrun the payments you are making on your NEW car. Buy used – let someone else absorb the loss. You are buying a car to drive, not display in a museum. Motorize makes the smart choices and gives you the savings. WE ARE NOT SALESMEN: WE ARE PURVEYORS OF “CAR BUYING MADE FUN” Tune In Next Month For Lesson 2 photo courtesy In stock now: 2010 Volkswagen Touareg Diesel Highline TDI $39,900 2010 BMW XDrive 3.0 $39,900 Subaru Outback XT by Sue Hodgson It’s becoming ever more difficult to buy a new car, even an inexpensive one, but if do your homework first and take a few test drives, that’s half the battle. This month Motorize Auto Subaru Outback XT: a sports utility wagon with the heart of a race car. Direct put me in a Subaru Outback, but not your typical one: an XT, their hottest version. The engine has a moderate turbocharger (it Whistler. As a Subaru owner, you will NEVER consider letting poor blows more air into the engine meaning, more road conditions hold you back. Heavy duty is a theme that defines power), and the cars using this engine carry the name WRX or XT. the Outback models, and they are commonly known to run This all-wheel drive wagon can handle the root-strewn North Saanich for over 500,000 kilometres with regular maintenance. back roads, and allows you to steam over things that you probably shouldn’t, like curbs. The nice thing is, with the lessons learned in They are very easy to service, and technically simple. world class off-road racing, Subaru's component choice is Subaru's Outback makes a compelling case for itself as an second to none, meaning the running gear on a Subaru outstanding all-rounder. Who'd have figured chauffeuring my two is way, way tougher than it needs to be. kids around the Saanich Peninsula could be such a party? That's why people love Subarus. It's not a European touring wagon. Model as tested: 2009 Outback XT Limited – 55,000 kms with It's not a sports car. It is going to take you basically anywhere you technology package including leather and heated seats with selectable drive want to go, including school, work, to the dentist and on vacation to modes, sport shifting and new Michelin tires: $26,999 plus HST. | FEBRUARY 2013 | 27 smell the coffee is coffee somehow less worthy, or worth less, than wine? Coffee & Wine Pt II In a follow-up to last month’s piece, I wanted to delve further into specifics of how various coffee types go with food. In part one I mentioned coffee by Steve Sheppard and wine share an agriculture common ground grown in appellation systems: designated geographical and environmental regions that produce coffee fruit with specific flavours, textures and aromas. These characteristics are commonly referred to as "terroir." Many coffee-producing countries have already created informal growing regions and are working to formalize these areas through laws. Colombia recently defined 86 distinct "designated microclimates" throughout the country. These growing regions define location, rainfall, altitude and processing conditions. Below are some pairings and pointers that will guide you to experiment with various food and coffee combinations, but remember: taste is always subjective. • Our perception of flavour is directly related to our sense of smell, so noting the initial aroma is critical in properly experiencing the full taste of both wine and coffee. • When tasting wine or coffee, pay attention to the acidity of each. Wine or coffee with high acidity can be described as crisp, tangy and bright while those with low acidity tend to feel smooth. • The feel of the wine or coffee on your tongue is known as the body. Wine and coffee can be described as light-, medium- or full-bodied. Like wine, some coffees naturally have more body than others. Coffee, Wine & Food Pairing Suggestions: Gouda Cheese Wine: Soft cheeses are best paired with white wines. A crisp riesling has a sweet mild flavour with citrus undertones that perfectly balances the distinct, slightly tangy flavour of gouda. Coffee: The interplay of Latin American or Indonesian beans weave a web of densely rich and deeply complex tastes, ideal for the … Who says only your love life can be Red Hot? Esthetics & Reflexology Spa Quality • Home Studio Open by Appointment: Mon - Sun 9 am - 8 pm mild flavour of gouda which helps bring out the layers of flavour and subtle sweetness of the coffee. Spicy Italian Sausage Flatbread Wine: Known for its zesty flavour, zinfandel carries notes of berries, licorice and a distinct peppery spiciness. Because of its moderate acidity, the robust flavours of this red wine perfectly accent bold foods with a spicy sweetness, like Italian sausage or tomato sauce. Coffee: With virtually no acidity, Sumatra features intensely aromatic, earthy and herbal notes that linger on your tongue. Its bold flavours stand up to the robust flavours of Italian sausage without overshadowing its hints of sage or spice. Chocolate Tiramisu Wine: Strong flavours of dark chocolate are best accompanied by equally strong, full-bodied wines, such as cabernet sauvignon. Intense flavours of dark fruit-like black currant provide a good contrast to the sweet and slightly bitter taste of rich dark chocolate. Coffee: A dark roast Guatemalan has a slight sweetness, and the richness is a wonderful accompaniment with cacao-based desserts like the tiramisu torte and offers sweet and contrasting notes to the tangy spice of semi-sweet chocolate. Whether you favour sweet and mild or robust and bold, the pairing of coffee, food and wine will offer a unique and memorable entertaining experience that your guests are sure to appreciate … Steve out. My True Valentine … The Peninsula’s ‘Only’ Micro Coffee Raster Big Apple Red by OPI 250.652.7888 • 8508 Aldous Terrace, N. Saanich (Wallace & Amity) 28 SEASIDE | FEBRUARY 2013 | Saanichton: Mt. newton X Rd. @ Wallace Dr. Just the Fat … Er, Facts, Ma'am We Don’t Always Get Sick Between 9-5 … Where Will You Take Us? 24/7 Emergency Phone Line 250-652-4312 Dianne Connerly It's no secret that being overweight affects more North Americans than ever, but how much do you really know about this public health problem? Test your knowledge against the fact and the numbers may surprise you. If you're overweight, the numbers may even motivate you to make some changes. In 2000, 56.4% of Americans were overweight, and by 2010 this escalated to 68.8% who were regarded as being overweight or obese. The Canadian population is not far behind, rating at 61.1% according to the findings from a survey conducted by the Centers for Disease Control and Prevention. Some of the ill effects of being overweight? Obesity is associated with diabetes, high blood pressure, heart disease, stroke and cancer. Does losing weight require giving up high-calorie or high-fat "goodies?" Most experts recommend to lose weight and keep it off, one should follow a plan to eat healthy, exercise, and make lifestyle changes that can last a lifetime. It's unrealistic to assume you'll never eat a piece of chocolate or a slice of cake. A sensible regime may include small amounts of sweets on occasion. Does exercise increase appetite? Some people are concerned that exercise works up an appetite and the calories used while exercising will be replaced by eating extra food. Experience shows that those who exercise moderately eat about the same amount as they would if they didn't exercise. How much can exercise reduce the risk of heart disease? One study showed that women who walk briskly (three miles per hour) for three hours a week reduce their risk of heart disease by 30%. Those who walk five hours or more per week reduce their risk by more than 40%. Dianne Connerly is with TOPS, a nonprofit, affordable weight loss support and wellness organization. To find a local chapter call 250-743-1851, 1-800-932-8677 or visit. Plants Shrubs Garden Gifts & Ornaments Trellis Arbors Pots, Pots & More Pots! We Have a Great Selection of Natural Stone, Soil, Compost & Bark Mulch Great Time to Start Working the Soil!. Open Tues - Sat 9-5 1780 Mills Rd, Sidney 250-654-0400 SEASIDE | FEBRUARY 2013 | 29 Whoever You Are, Wherever You Go … photo by joannway.com Seaside is With You. Events Local Dish Home & Garden Top Stories This month, ONLY on Seaside Mobile: Dr. Ambrose Marsh shares his Top 10 Heart Health Tips Seaside Goes Mobile! Send a text message to 250.800.3818 - we’ll send you a link! Local Real Estate Firm Honoured by Vicki Prince DFH Real Estate, an institution in Victoria and Southern Vancouver Island for over 50 years, has been chosen to represent Leading Real Estate Companies of the World®. This Chicago-based global network is comprised of over 500 firms with 4,600 offices and 140,000 sales associates in over 30 countries. Leading Real Estate® affiliates are responsible for $235 billion in annual home sales – more than any other real estate organization. The firms that make up this global real estate network are the most powerful independent brokerage firms in the world. Only the best of the best are part of the select group whose name says it all. DFH was invited to join the global network after meeting specific standards of excellence that included being ranked among the top independent firms in their market for reputation, stability, tenure, quality, relocation capabilities and other factors. The strength of LeadingRE® is the quality of each individual brokerage firm. Companies don’t simply “pay for” a franchise brand name – they must earn the designation of Leading Real Estate Companies of the World®, year after year. This new relationship provides a global marketing reach for DFH Real Estate property listings, delivers expanded online exposure and brings international connections and the power of a global network. The affiliation has already proven to be a beneficial source for buyers. It also allows the firm to assist individuals purchasing or selling property in virtually any community worldwide and to service corporate relocation accounts through RELO Direct®, Leading RE’s corporate relocation management company. As an affiliate of Leading Real Estate Companies of the World®, DFH has access to a wide range of brokerage services to further strengthen its marketing presence and offerings. In addition, company representatives have the opportunity to collaborate with other "best in class" firms from around the world for idea sharing, referrals and business development opportunities at conferences and online through the network’s private interactive community. "We are delighted that DFH Real Estate." DFH has a powerful local brand in Victoria and Southern Vancouver Island and has long been recognized for its local expertise and ethical dealings. Despite some predictions of a challenging year ahead in the local real estate market, DFH is confident 2013 will be a successful year for its 120+ agents. To find out more, call Sidney's DFH Real Estate office today at 250-656-0131. | FEBRUARY 2013 | 31 common cents safe and secure real estate investing As the New Year begins, PET FOOD PLUS Now Open Sundays! 10 - 5pm Proudly serving Sidney for 11 years! PET FOOD PLUS PET FOOD PLUS #4-2353 Bevan Avenue Sidney, BC 250.656.6977 32 SEASIDE | FEBRUARY 2013 many Canadians review their investment choices and options along with recent earnings (or lack thereof, unfortunately). This can often be confusing as the number and complexity of investment products continues to grow. However, it is important to keep in mind some simple by Phil Wooster questions that can help direct your choices: First Island Financial • Ask yourself if you are comfortable Services Ltd. with the overall safety of your principal? What risk factors will affect its security and earnings? • Are the earnings sufficient given the risk undertaken? How do your earnings compare to expected returns? Are the expected returns valid for several prior years and economic cycles? • How do you realize your gains and actually get paid? What are the requirements and fees to convert your principal or earnings back to cash? • What is the experience and track record of the seller? Do they have a vested interest in your long term investment success? If you had trouble answering the above questions, a prudent alternative may be investing in secured real estate via mortgage investments offered by a reputable and experienced manager. Your money is hard earned and while part of an investment portfolio can be earmarked for higher risk and potentially higher return (or loss) investments, it is always conservative to maintain the bulk in lower risk investments that can still provide above average returns for the long term. Investing in secured real estate can achieve this goal if done properly. In general, real estate values in Victoria and the South Coast tend to remain relatively stable. Values may dip in certain product sectors or locations during sluggish economic cycles, but overall risk can be managed effectively by a knowledgeable manager. The larger the market, typically the more stable it is and the easier it is to sell and recoup invested funds. Smaller markets tend to drop first and recover last in difficult economic times, a fact which an experienced manager will guard against. Investments in residential real estate can also aid in waiting out a slower market by providing rental revenues in the interim. A professional mortgage investment manager will protect both principal and earnings by minimizing risk through prudent lending criteria (1st place mortgages), diversification of product type/location and continual careful due diligence. This includes knowing the specific market values/rents, the developer’s track record and credit history, the number of proposed or completing projects in the area, the general absorption rate (for multiple unit projects) and whether the construction cost budget is adequate. Overall, when done properly through a qualified manager, real estate investments can be a safe and secure investment to provide above average returns for the long term. For more information visit. seaside arts scene by Gillian Crowley Sidney’s Mary Winspear Centre has a busy month ahead, with music ranging from folk, pop and blues to classical and Tin Pan Alley favourites. Celebrate Valentine’s Day early and bring your sweetheart to hear well-known local tenor, Ken Lavigne, celebrate “love’s old sweet song” at a matinee February 7th. Then banish winter blues by listening to the popular Palm Court Orchestra, with pianist Frederick Hodges playing a tribute to George Gershwin’s music at a February 19th matinee Roy Forbes Folk singer is too restrictive a term for Roy and his music. Starting as a teen rock and roller in hometown Dawson Creek, he has since become a singer-songwriter, guitarist, record producer and broadcaster. Many will remember him as “Bim” in the folk trio UHF with Shari Ulrich and Bill Henderson (Chilliwack). The Toronto Star described his music as “a rich and happy pastiche of folk, blues, country and rock, delivered in a high, keening voice that has no equal in popular music.” Roy has not only had success singing his own songs but they have also been performed and recorded by many other performers. This two-time Juno nominee and multi West Coast Music Award winner will be sure to get your toes a-tapping. Presented by the Deep Cove Folk Music Society. February 16th at 8 p.m. Mary Winspear Centre. 250-656-0275 or. face painting, games, 30+ costumed characters and door prizes. At the Centre’s LEGO display, kids can build their own creations from the different sets available. Parents, don’t forget your camera! Monday, Feb. 11th, 10 a.m. to 4 p.m. Professional LEGO displays: 2805 Seaport Place. Sidneyland at Mary Winspear Centre: 2243 Beacon Avenue. FREE. Donations accepted for the Sidney Museum expansion project. We’re fortunate to have many ways to celebrate late winter here on the Peninsula and Gulf Islands. If you’re dreaming of a short getaway, consider taking in an event or two at Salt Spring Island’s ArtSpring Theatre. Les Ballets Jazz de Montréal This troupe is considered one of the most exciting dance companies in Canada. It has developed a successful marriage of talented dancers with renowned composers and choreographers who share their innovative ideas through creative residencies. Their Salt Spring program offers three new dances: Zero In On by Cayetano Soto, Night Box by Wen Wei Wang, and a new choreography by Barak Marshall. February 20th at 7:30 p.m. Jane Coop and the Afiara String Quartet This is a wonderful opportunity to hear Jane Coop, one of Canada’s finest pianists, along with the all-Canadian Afiara Quartet. The Montreal Gazette has commended the Quartet for their authentic presence and performances balancing “intensity and commitment” with “frequent moments of tenderness.” The evening includes works by Haydn, Beethoven and Brahms. Ticket holders may attend a pre-concert chat at 6:30 p.m. February 26th at 7:30 p.m. ArtSpring Theatre, 100 Jackson Avenue, Salt Spring Island. 866-537-2102 (toll free) or artspring.ca/ticketcentre. SAVOUR the ooey-gooey goodness of chocolate this month! MARKET Family Day Fun On B.C.’s first Family Day February 11th, everyone can be a kid as Sidney transforms into LegoLand. The main event will be a large-scale pirate-themed LEGO piece built live at the Sidney Pier Hotel by Canada’s only LEGOcertified professional, Robin Sather of Brickville DesignWorks. Other LEGO professionals will be building surprises at the same site. Families can get into the spirit with the town-wide LEGO treasure hunt supported by many local merchants. Get a treasure map at the Sidney Museum and then visit Sidney’s shops in search of LEGO treasure. Completed treasure maps will be returned to the Sidney Museum and entered into a draw for great LEGO prizes. The Sidney Museum, located at 2423 Beacon Avenue, is currently exhibiting its huge collection of LEGO. Over at the Mary Winspear Centre, Sidneyland will be buzzing with fun activities with an indoor playland with bouncy castles, ♥ Local, Specialty & Import Chocolate ♥ ♥ Delectable Sauces Good for the Heart & Soul 250.656.2547 10940 West Saanich Rd, North Saanich SEASIDE | FEBRUARY 2013 | 33 t r e n ds p ot t i n g Here's to Love … When you're looking for something to really make you feel special, lingerie is essential. Silk feels wonderful … coupled with Chantilly lace, it allows one to relax, feel comfortable and yet have that aura of being glamourous and special. Valentine's is the time to treat yourself. Many styles, colours and fabrics coming this spring. (brown: $85; grey: top $97; panties $65) Sweet Talk & Lace Lingerie 2424 Beacon Avenue, Sidney sweettalkandlacelingerie.ca Time for some special atmosphere in your home or workplace? Starlightz illuminate with extraordinary beauty, casting colourful light. Handmade the earth friendly way, using material and means that mirror the company's commitment to ecological responsibility. A unique gift for your unique friend. ($24.50) Pebbles at Mineral World 9808 Seaport Place, Sidney pebblesjewellery.com Paperdoll Mineral Cosmetics is a fresh, Canadian/Sidney-born company that gives cosmetics consumers all the choice and none of the baggage. Visit Exist Hairworx and mention Seaside Magazine to receive 10% off your Paperdoll Mineral purchase. Try these great products and our lip gloss: a natural minty shine without the stickiness; in five colours! (assorted prices) eXist hairworX #3 - 2130 Beacon Avenue, Sidney paperdollminerals.com 34 SEASIDE | FEBRUARY 2013 | Handwritten cards never go out of style. Whether you want to keep it romantic or slay someone with twisted humour, we have the perfect cards and offbeat gifts. If you're going straight for the heart, come check out our beautiful selection of jewelry and accessories. (assorted prices) Cameron Rose Gifts 2447 Beacon Avenue, Sidney cameronrose.ca photos by joannway.com • special thanks to trendspotter Susi McMillan Let love bloom this spring on the lush greens and fairways of Glen Meadows Golf & Country Club. Golf nine holes with your better half, then enjoy an entrée and a glass of wine. $50 for two people. Package available until February 14th, 2013; must be redeemed by April 30th, 2013. Some conditions apply. Glen Meadows Golf & Country Club 1050 McTavish Road, North Saanich glenmeadows.bc.ca SEASIDE On Design 2013 Colour Trends ‌ Who Cares? homes Februarry 2013 YO U R W E S T C O A S T C U LT U R E Building a Future Mini Homes Pave The Way Preserving the Past Ensuring the future Dunmora A dedicated team of craftsmen thoughtfully restore this Central Saanich waterfront treasure Dunmora: Preserving the Past, Ensuring the Future Story by Linda M. Langwith | Photography by joannway.com | Design by Lorianne Koch - Bravo Advertising For Grant Rogers, president of the Marker Group, the challenge of Dunmora was to preserve the past while securing its future as a family home for generations to come. With building and renovating experience acquired in both Canada and the U.K., Grant realized the best approach was to enter into a Heritage Revitalization Agreement with Central Saanich that would honour, preserve and protect the historical value of this very special waterfront home while allowing necessary improvements to ensure Dunmora’s continuation in perpetuity. 36 SEASIDE homes | february 2013 Knowing the residence to have an impeccable provenance, Grant was not surprised to hear the engineer confirm that even before renovations began it met many of the current building standards. Upgrades in plumbing, electrical and insulation were carried out to bring everything up to today’s requirements. The impressive porte cochere, reminiscent of the one that graces the entrance to Government House, was redone, as dampness from the balcony above created issues over time. Other structural repairs and replacements were undertaken as needed to ensure all codes were met. The exterior granite facing, plaster, half timbering and Tudorstyle granite chimneys proved to be in excellent condition – Dunmora was built to last. Grant and his associates assembled a dedicated team of craftsmen to thoughtfully restore (and replace where needed) the original fir doors, wainscoting, beams, coffered ceilings, fir flooring and windows, and while it was not possible to retain the original light fixtures, their replacements complement the rooms. The painting scheme throughout is warm and contemporary, creating a pleasant contrast to the more traditional wood features. The study’s magnificent inglenook fireplace, one of two in the home, Grant and his associates assembled a dedicated team of craftsmen to thoughtfully restore (and replace where needed) the original fir doors, wainscoting, beams, coffered ceilings, fir flooring and windows. faced with the original granite, remains true to the principals of the Arts and Craft movement, with a delightful carving of oak leaves and acorns running along the mantelpiece frieze, while the generous seating benches provide the perfect spot to curl up with a good book on a rainy day. A kitchen is not meant to be a museum, but rather the heart and hub of the home, and so for Dunmora Grant and his designers came up with an entity that does full justice to its generous space, with a pleasing mix of stained fir and creamy coloured cabinetry, pillars supported by decorative brackets, practical built-ins, multiple prep areas, an eating bar and even a coffee centre. The original designer of Dunmora, John Keith, was ahead of his time in planning ensuite bathrooms for each of the commodious bedrooms on the second floor, and under the renovation program they have received the latest in new fixtures and fittings. Grant is especially pleased with the master ensuite, which shows particular sensitivity to the colour scheme in vogue during the 1920s through the use of an enchanting black and Continued next page SEASIDE HOMES | february 2013 | 37 new homes • renovations • additions • interior design Join us at the CHBA Home Show at Memorial Arena February 15 - 17! michael or Lisa dunsmuir 778.433.1434 • Continued from pg. 37 white bow pattern in the tiling. The master bedroom enjoys the original fireplace, walk-out balcony with a view overlooking the inlet, and thoughtful touches throughout, such as a designated washer and dryer intended solely for the use of the chatelaine when dealing with her special lingerie collection. The third floor attic has really come into its own, with two unobtrusive skylights providing additional daylight, and an imaginative use of space for a variety of pleasures and hobbies, from the theatre/media area to a bar and kitchenette as well as the added treat of a steam shower in the bathroom. All three levels are easily accessed by an elevator should mobility become an issue. Even the 38 SEASIDE homes | february 2013 harbour city kitchens f ine cabinetry & storage systems 2189 Keating X Rd 250-652-5200 harbourcitykitchens.com Time for a new roof? • Fully Insured • Reroofing Call Victoria’s trusted re-roofing specialists • New Construction • Repairs basement has received Grant’s magic touch, with the addition of a roomy wine cellar, complete with tasting nook and plenty of racks just waiting to receive some special Peninsula vintages. Dunmora can now look forward with confidence to the future. For Grant, the satisfaction lies in this: “To take something such as Dunmora, with its wonderful heritage value, maintain that heritage and history and make it valuable for a new family to live in.” | february 2013 | 39. According to grandson Trevor May, Léonie loved spacious, light filled rooms with lots of windows. 250.412.5061 Contemporary Residential Designs neptune road The Special World of Dunmora By Linda M. Langwith studio DB3 studioDB3 Daniel Boot ph. 250 889 2584 dboot@shaw.ca 40 SEASIDE homes | february 2013 When Gerald Henderson May and his wife Léonie stood on the bluff overlooking the Saanich Inlet in the autumn of 1921, they knew this was the place where they would build “Dunmora.” They chose the designer of Christ Church Cathedral, architect John Malcolm Charles Keith, to create their home in the popular English Arts and Craft style, with its emphasis on fine workmanship and the use of locally sourced materials. According to grandson Trevor May, Léonie loved spacious, light filled rooms with lots of windows, and fortuitously a shipment from England of leaded casement windows with decorative wrought iron fasteners became available. The story goes that the home was designed around these windows, still in use at Dunmora today. All the wood in the home Pacific Paints -3 locations! pacificpaintcentres.com Keating Xrd, Hillside & Millstream 652-4274, 381-5254 & 391-4770 Sitting in his study by the inglenook fireplace, Gerald kept meticulous daily records of the maintenance and upkeep of the house. came from the fir trees on the property while the granite, used in the facing, pillars, chimneys, garden walls and walks, was quarried on site. John Keith organized the main floor in a style much like the “great room” favoured today, with double pocket doors between the spacious dining room and the lounge, opening up when the occasion demanded, such as the grand New Year’s Eve party where the guests were entertained by musicians, while the May children, Ian, Moira and Peter, crept down the open well staircase to catch a glimpse of the festivities. Sitting in his study by the inglenook fireplace, Gerald kept meticulous daily records of the maintenance and upkeep of the house, grounds and garden, offering valuable insights into the running of a country estate in that era. Léonie filled the rooms with fresh flowers from the greenhouse and developed her amazing photographs in the darkroom. Vegetables were delivered by the Chinese grocer, Jersey cream and eggs came from the farm across the road. The Chinese staff of cook, houseboy and gardener was, according to Ian, “part of our family and much loved.” Bing could turn his hand to anything in the kitchen, and one Christmas produced an ornate three-tiered cake in the shape of a pagoda. A broad veranda running the length of the main floor and overlooking the sea was the perfect place for the children’s birthday parties. Benches were brought from the wooden floored tennis court, tables set up and laughter and merriment spilled out into the gardens, wading pond, spacious lawn and forest. Days were filled with boating excursions, picnics at Bamberton, swimming, fishing and visits from friends and relatives. As Ian says: “We very much lived in our own little world.” The Dunmora of today still honours that special little world. Unique Designs For Every Lifestyle Finlayson Bonet Architecture #4 - 7855 East Saanich Rd, Saanichton 250.656.2224 • finlaysonbon SEASIDE HOMES | february 2013 | 41 SEASIDE homes Feature HomeSuppliers 3 2 Last month’s to give you an idea of “the look” working on list to send you for this month’s will have it to you ASAP 4 Photography by joannway.com 1 1 2 3 4 COUNTERS GLASSWORK MILLWORK INTERIOR DESIGN Colonial Countertops colonialcountertops.com Allied Glass & Aluminum Products Ltd. alliedglass.ca Swiftsure Woodworkers Ltd. swiftsurewoodworkers.com Nygaard Interior Design nygaarddesign.ca Developer The Marker Group markergroup.ca Architect Zebra Group zebragroup.ca Appliances Coast Wholesale Appliances coastappliances.com Counter Colonial Countertops colonialcountertops.com Electrical Gorge Electrical Services Ltd. gorgeelectrical.com Audiovisual/Sound Simply Automated Smart Home Systems simplyautomated.com Tile Dave Campbell 250-896-5814 Heating/Ventilation Ocean Air Refrigeration 250-588-2232 Millwork Swiftsure Woodworkers Ltd. swiftsurewoodworkers.com Interior Design Nygaard Interior Design nygaarddesign.ca Construction Abstract Developments Inc. abstractdevelopments.com Masonry Strongback Stoneworks Ltd. strongbackstoneworks.com 42 SEASIDE homes | february 2013 Custom Woodwork Hobson Woodworks hobsonwoodworks.com Glasswork Allied Glass & Aluminum Products Ltd. alliedglass.ca Painting The Ultimate Finishing Company 250-590-4559 Tri City Finishing 250-381-1989 Drywall PR Wilson Interiors 250-361-7854 Elevator Angel Accessibility Solutions angelsolutions.com Structural Engineer Spar Consultants 250-477-7777 west coast Gardener Your Kitchen Your Way gardening with the right side of the brain Recently, I started a beginner’s improv theatre class. Apart from the guarantee of two solid hours of laughter in my week, it’s exercise for my creativity muscles. Which, since I design landscapes for a living, aren’t exactly out of shape: on the contrary, they sometimes get a little overly tense from by Megan Walker taking it all too seriously. Surely it’s only Landeca right to take seriously the responsibility of investing clients’ hard-earned funds to create beautiful landscapes for them, but if I let myself get too wrapped up in rules, discipline and constraints, my creativity motor starts to cough and sputter. Creativity, that magical spirit, needs freedom to play – to improvise, mess up and then try it again, and it sure helps to keep laughing in the process. Various versions of “do something creative” find their way onto many a self-development goal list. If it’s on yours, have you considered gardening as a medium? For many of us, our own gardens are low-pressure and rewarding environments for playful creativity. An afternoon in the garden can leave us refreshed, energized and with a sense of accomplishment – a creation we can enjoy with our feet up, a bouquet on the table and an artisan tomato in our sandwich. The palette is endlessly broad: full of textures, colours and forms, natural materials and living things. Gardens and landscapes are by their very nature imperfect, mutable, and never completely under control – the ideal arena for experimenting, messing up, and then trying something else. Of course, gardens are also functional places, and some planning and forethought will help set you up for creativity’s happy accidents. This is where the left brain kicks in, with practicalities like budgets, time commitments, spatial needs, zoning bylaws and deer resistance. But great design really happens when the two halves of the brain play in concert. The left brain sets down some nice, sensible goals and parameters as a “canvas,” and the right brain is released to spill ideas, move things around, and pull in random inspiration. How this creative process will work best for you is an experiment in itself. Perhaps you draw up a measured site plan, make some photocopies, and then let loose with a fat sharpie pen to come up with new bed layout ideas. Sketch over some photographs or make a collage. Or, just get out there and improvise. Rip up that deer-munched half-dead shrub you never liked anyway, and plant that cool-purpleleaved-shrub-you-don’t-really-know-the-name-of-but-begged-tocome-home-with-you-from-the-garden-store. Better yet, plant 10 of them! The point is to get moving. Be bold. Try it out. Laugh at your failures. Move them somewhere else. Play again. What better opportunity do we grown-ups get to play in the dirt? For more information visit. photo by 250.652.5081 • cabinetworksvictoria.com SEASIDE HOMES | february 2013 | 43 Building a Better Future Dan Boot's Mini Homes Pave the Way. by Doreen Marion Gee DAN BOOT'S "outside of the box" mini homes reflect a new paradigm of taking care of each other and the planet Forget about the confines of time and space. Dan Boot is taking a huge step into the future. His “outside of the box” mini homes reflect a new paradigm of taking care of each other and the planet. The artist’s unique design concepts are the wave of a sustainable future, housing more people while reducing our footprint on this planet. Dan Boot is an award-winning building designer with over 35 years in the field and his resumé is dizzying. One of his companies, Small Modern Living (SML), specializes in small affordable housing units. Dan puts a high value on social responsibility: “Our mission is to improve the quality of life of everyday British Columbians by building healthy, green and affordable housing.” As president of SML, Dan is confident that high quality, well-designed housing can be built at a reasonable cost. His unique homes put more rental housing stock in a squeezed market and increase access to homes for more people. Welcome to the garden suite! These units are built behind the owner’s house on their lot. The owner benefits with another stream of income and less drain on energy costs. For tenants, the little homes are brand new private affordable housing. They are also a 44 SEASIDE homes | february 2013 practical option for housing aging parents. Dan’s creation is a minimalist marvel: "Our mission is to improve the quality of life of everyday British Columbians by building healthy, green and affordable housing." economy of space with a luxurious ambience. These mini homes look like beautiful highend condos. Dan and his team offer predesigned "garden suites" and custom-designed contemporary homes; the designs are versatile and can accommodate many options. Innovation marries pragmatism: his units maximize the small space for optimal use. The City of Victoria has approved garden suites in the city, and Dan’s present project is the first in Victoria. He is working with the City and his client to put his 56m2 Studio/ Suite in the Rockland area. The designer is looking forward to many more projects and perhaps future resort communities. Environmental stewardship is the hallmark of a sustainable future world. Accordingly, Dan wants his buildings to reflect a vision of conservation and preservation of green space. Dan’s philosophy is “to encourage a sensitivity towards our environment outside the building in all its aspects and to promote proper caretaking of the environment for future generations.” Small homes leave small energy and carbon footprints. His homes are designed for maximum energy savings with the smallest amount of building materials. A bright future is also based on a collective social conscience. Dan’s enterprise puts more housing in the same space and a roof over more heads in our community. Since the mini homes cost less to build, the savings are passed on to renters. Energy efficiency produces lower utility bills for people struggling on a budget. Dan Boot sums it up in his blog: "I feel small homes should no longer be synonymous with 'cheap' houses and lack of privilege. Instead, they symbolize a range of culturally coded values: compactness, efficiency, discreteness, minimalism.” Dan Boot is building a better future. Web:.: | february 2013 | 45 PUBLICATION: SEASIDE TIMES INSERTION DATE: FEBRUARY 2013 SIZE: 7.75” X 4.925” Just add love. ROYAL OAK DRIVE in the Broadmead Village Shopping Centre 250-658-5578 SIDNEY at the foot of Beacon in the Sidney Pier Hotel 250-656-5506 46 SEASIDE | FEBRUARY 2013 love us @ knickerbockersbc n e w & n ot e wo rt h y by Linda Hunter vantag e p o i n t Moving in the Right Direction been serving the district in various capacities since his arrival in 2005. dining Swapping the snow for sand, Chris Fudge, the new executive director at the Saanich Peninsula Chamber of Commerce, has officially taken up residence on Beacon Avenue. He looks forward to “providing Members with new and innovative resources to successfully navigate the current business environment.” Connect with Chris at. A new year means a new bank manager for Scotiabank in Sidney. After 39 years in banking (eight of them as the Sidney branch manager), Brian White is now working on his golf game and his swimming stroke. Hailing originally from Halifax, Karen Peel has taken the local helm, having spent time in both Calgary and Victoria during her 34 years with the bank. () Fitting right into their plans, the District of Central Saanich has a new director of Planning and Building Services. Bruce Greig has a wealth of knowledge in planning and land development as well as landscape architecture and has Serving up hot SOUP, fresh PIZZA, and a side of TOAST Ever tried turning water into soup? Now you can pick up both in one place, at the Ultimate Water Store on Beacon in Sidney. Alongside their bottled water, Jayne and Graham are now Souped Up, serving a variety of fresh hot soup to go. Check out their daily changing soup menu. (250-655-8922) Wood fired and fresh from the Woodshed; coming to a front door near you, this Sidney newcomer is now offering local home delivery. Visit to find out more. Sidney’s Toast Café has gone loco, I mean local – now serving up Deep Cove farm fresh free range eggs and chicken in their dishes, and offering gluten free menu options daily. (250-665-6234) r e ta i l Clothes that make the man, and the baby too! Bubba Loo Children's Boutique has given birth to a new idea and is thrilled to announce the arrival of their new Baby Registry. Parents- and grandparents-to-be are invited to visit the store and start building their wish list; no appointment necessary. The registry is available now and is sure to be a hit with everyone, especially baby. Sidney’s own d.g.bremner & co. has gone Hollywood. The Family Matters TV show host, Justice Harvey Brownstone, will now look even better on screen, sporting clothing from the local menswear and accessories shop. () Now in its second year, the Peninsula Attractions Connector free shuttle service is expanding its routing in 2013 and will be including more stops as it makes its way throughout the Peninsula to places of interest. Offering connections to and from The Butchart Gardens directly from the Swartz Bay Ferry terminal and Washington State Ferry terminal in Sidney, this FREE hop-on/hop-off service operates daily through July and August. Find out more at. tourism wellness Not gone but sometimes forgotten The Peninsula Visitor Centre, located just off the highway exit on Beacon Avenue, is OPEN for business. Their friendly and very knowledgeable staff are bursting with ideas, maps, resources and information for those summer visitors you just found out about, or the upcoming wedding guests from out of town. The Centre also has an array of resources available to the local business community. Not visiting? Lucky enough to be living here? Find something new to do this weekend; drop by the Centre and find out more. (peninsulatours.ca) Care & Compassion... At C.A.R.E Health Within Has Moved … Within After seven years in downtown Sidney locations, Health Within has moved home. Dr. Jeffrey Robert Jones (TCM) and Mikiala Christie (R.Ac, R.TCM.P.) are now located on their home property in North Saanich, just off McTavish on Cresswell Road. Coming home was the best possible fit for their growing young family and for their acupuncture and traditional Chinese medicine clinic that focuses on balance in health and in life. () | FEBRUARY 2013 | 47 TEL: 250-656-7231 48 SEASIDE | FEBRUARY 2013 Ramona Maximuk 250-995-4414 Rmaximuk@timescolonist.com Grant Wittkamp 250-380-5244 gwittkamp@timescolonist.com island dish besides adding heat and flavour to almost any dish, the capsaicin in chilies is used in cosmetics to make your lips look bigger Hot To Trot Pucker up people, it's Valentine’s Day and "that certain someone" is waiting for that perfect smooch! Lips not big enough you say? No problem! Capsaicin to the rescue! by Jennifer Bowles That’s right: this month my article is on hot chilies. Besides adding heat and flavour to almost any dish, the compound that brings the heat, capsaicin, is used in cosmetics to make your lips tingle and swell so they look bigger; a whole lot cheaper than a lip job! Chilies are often revered not only for their punchiness and well-loved heat in a dish, but surprisingly also as an aid to our digestive systems. They provide relief from cold symptoms, scratchy throats and your circulatory system, especially for cold hands and feet. Most people are familiar with common post-party remedy the Sunday morning Caesar, seriously doused with Tabasco and garnished with spicy beans – the capsaicin is a well-known day after remedy. You can also make a chili tincture if you desire by drying out a hot pepper, grinding it into a powder and adding a teaspoon to your morning juice regime to increase metabolism and give your digestive system a kick. Now here’s the disclaimer: I am not a doctor, but the beneficial effects of a spicy pepper have been known in many cultures for centuries. So let’s get back to the true beauty of a chili … its taste! Personally, I absolutely love spicy food. It’s not for everyone, but as there are so many enticing varieties of these babies, you can pick and choose your "heat level" easily by using the "Scoville Organoleptic Test." This test was executed by blending pure ground chili peppers with a sugarwater solution. A panel of testers sipped the solutions in increasingly diluted concentrations, until they reached the point that the liquid no longer burned their mouths. A number was then assigned to each chili pepper based on how much it needed to be diluted before they could no longer detect the heat, and it was measured in multiples of 100 units. Our beautiful little green bell pepper, common on pizza, scores a true zero in Scoville units. Pure Capsaicin, our gentle little lip plumper, comes in at a whopping 15,000,000 units! In the real world jalapeños score a relatively cool 2,500 to 9,000 units, Tabasco hits the 30,000 mark, and you’d be best to avoid any legal predicaments as police grade pepper spray says "I immediately regret this decision" with a respectable 5.3 million units! Around our home we have a Friday night tradition. Seeing as Friday is the "wrap-up" day of the week, and things can generally be a little crazy heading into the weekend, we prepare a little dish called "crazy peppers." It’s a nice warming appetizer made with the not-toohot poblano pepper. Essentially they’re roasted, peeled, seeded and cut into strips, then the strips are rolled up with a mild but flavourful goat cheese filling. Here’s the recipe! 4 large poblano peppers ½ cup soft goat cheese (chèvre) dash each of onion powder, garlic powder, salt and pepper canola oil Preheat oven to 400° F. Toss the peppers in oil and place them on a baking sheet. Roast in the hot oven for 15-20 minutes until the skin blisters and blackens. Place the hot roasted peppers in a bowl and cover with plastic wrap; let them steam for 10 minutes to separate the skins. Once cooled, carefully peel and seed the peppers, being careful not to damage the flesh of the pepper. Cut the peppers lengthwise into ¾-inch wide strips. Mix the goat cheese with the seasonings and allow them to come to room temperature. Spoon a dollop of the cheese mixture onto each of the pepper strips and roll up into a bite size appetizer. Enjoy! Wine pairing courtesy of Dave Gartley, Gartley Station Fermentations. The goat cheese is the predominant taste in the appetizer and is characteristically acidic. Acidic foods love acidic wines, so pick something tangy and fresh to complement the acidic in the cheese. For a white wine I would suggest a New Zealand sauvignon blanc, unoaked chardonnay, pinot blanc or pinot gris. The carbonation in sparkling wines naturally raises the wine’s acidity through the formation of carbonic acid and a vinho verde could be a classic match. In the red category you also want good acidity but you can pair to the herbaceous component of the peppers. Pick a cabernet franc, a North American pinot noir or any red wine that you know pairs well with acidic, tomato-based dishes. February - customer appreciation month! 15% OFF every wine made in-hOuse hOmebrewers: 25% OFF all wine kits New customers: 30 free wine bottles Customer referrals: $20 gift certificate OPen hOuse Saturday, Feb. 16th 9:30 - 3:30 Drop in and check us out! Appetizers, refreshments and prizes! Gartley Station - Expert Wine Crafting. Open Tues - Fri 10 - 6, Saturdays 10 - 4 #108 - 1931 Mt. Newton X Rd. Saanichton 250.652.6939 SEASIDE | FEBRUARY 2013 | 49 Luigi and Valeria Cisotto are customer service connoisseurs. Along with fresh fine food, "Latch" patrons enjoy extra-special treatment. Not only do the owners shower diners with warm attention, they up the ante with treats, surprises and added golden touches to increase the "wow" factor. Luigi and Valeria go beyond the call of duty to buy and prepare the highest The Latch: Touches of Gold & Magic by Doreen Marion Gee The Latch the latch inn & restaurant • sidney Discover a British Columbia Heritage Home The Perfect Place to Bring Your Valentine! Call now for more information on booking a Private Party or Special Evening Open Tues - Sun For Dinner 2328 Harbour Rd, Sidney 250.656.4015 Zanzibar Breakfast Lunch O Dinner O Espresso O Open Tues~Saturday 730 - 4 Thurs, Fri, Sat 530 - 830 GLOBAL FLAVOURS O LOCAL TASTES Dinner Reservations Recommended 1164 Stelly’s X Rd, Brentwood Bay 250.652.1228 • quality food. It is no surprise that most of their customers have stayed with them for seven years. Visiting The Latch Restaurant Inn & Restaurant is like stepping into a beautiful fairy tale, a "Peter Pan" world of trees, brooks and sunsets with an old log house hidden away in an enchanted forest. It is always a joy to sit down with the affable and charming owners, Luigi and Valeria. They want to give their patrons the ultimate dining experience. For them, preparing fine cuisine is not a job: it is their life. They are the hosts, the cooks and the waiters. The Cisottos go the extra mile to offer 50 SEASIDE | FEBRUARY 2013 Help Us Celebrate Our 15th Anniversary! O Two-Course Meal and complimentary Crème brûlée just $17.95 +hst Sun - Thurs 8-8; Fri & Sat 8-9 250-655-0122 • 9681 Willingdon Rd, Sidney the "best of the best." Twice a week, Luigi goes out to buy good local products, where he can see the freshness. Luigi buys his veal from Thrifty Foods, which is known for quality meat. He goes to a butcher shop in Duncan to purchase the pork for his special homemade salami. "It is a little more expensive but it is worth it. It is fantastic." The proud owners are interested in offering high quality fare without cutting corners. As for their work ethic, the couple are "always on duty." Their hearts are invested in The Latch. The Only Thing We Overlook … Is The View! special item. (I had it. It is to die for.) Valeria reveals their top secret: "Customers always get something special at the end of their dinner, regardless of how much they paid!" Luigi and Valeria talk excitedly about giving their customers little extra treats to add a dash of pizazz to their meals. Luigi tells a story about giving four customers a very special surprise one night: Strawberry Romanoff! Despite my desperate pleas for details, Luigi would not divulge his secret dessert ingredients. A non-menu item, Luigi whipped it up in the kitchen as a special surprise. The More Than Just The Peninsula’s Freshest Coffee ! After 23 years in business, The Rumrunner has only improved upon the delicious, fresh menu served daily. Don’t Forget Valentine’s Day! Think of us when planning a Special Night for Your Special Someone Legendary Salads ! Contemporary West Coast Dining Gourmet Sandwiches Wholesome Soups Freshly Baked Muffins Decadent Desserts Our Fish & Chips are Celiac Friendly! 9881 Seaport Pl, Sidney 250.656.5643 Gluten-Free Items Saanichton: corner of Mt. Newton X Rd & Wallace Dr Cisottos go to great lengths to make their patrons feel like royalty. A homemade chocolate truffle, made with the very best Belgian chocolate, adds a little magic at the end of a meal. Why do you think that people keep coming back, I ask my hosts. "Because they love the special attention," beams Luigi. "They feel like they are at home here. We do all those special things here that customers usually find at home," Valeria adds. Patrons are treated like part of the family, with warm chit-chat and a hug, kiss and "Thank Breakfast & Lunch 7 days a week Dinner Thursday to Sunday 5-9 2320 Harbour Road, Sidney 778.351.3663 seaglasswaterfrontgrill.ca you for coming (back)" when they leave. Luigi and Valeria are the consummate hosts: "We care from A to Z, from the time you walk in to when you leave." The Cisottos wish to sincerely thank all of their loyal customers during the last seven years! When you enter "Never Never Land" at The Latch, indulge yourself in the golden service, elegant oceanside ambience, delectable food and extra treats while Tinker Bell sprinkles magic dust on your evening. Contact: and info@latchinn.ca. SEASIDE | FEBRUARY 2013 | 51 p e n i n s u l a r e s ta u r a n t p r o f i l e Food preparation is a fine art in the Cisotto family. They are from the "old school," where cooking delicious food is still a long-held tradition, a badge of honour. Tender pasta is made in-house, along with savory Italian sauces, sinful Caesar dressings, succulent herb breads, Luigi’s world-class salami and dazzling desserts. Luigi and Valeria take extra care to make sure everything is fresh, pure and made with their own loving hands. To tempt their patrons, Luigi and Valeria are flirting with international fare. Valeria’s new friend from Thailand, Noo, taught her how to make Thai Mushroom Soup – a new Brand New Dental Hygiene Clinic in Brentwood Bay Come Meet Joanne ! Wednesday, February 6 , 2013 1:00 pm to 4:00 pm th Teeth Whitening Special: $49.95 *with initial cleaning* ($500 at most offices) It’s Amica’s sweetest event, ever! -oR- You and your friends are invited to enjoy an afternoon drizzling with decadent chocolate delights. FRee Polish and fluoride Indulge in an array of homemade chocolate sensations baked specially by our Chef de Cuisine. *with initial cleaning* Joanne Fox, RDH Come with a friend. It’s FREE! Dentist RefeRRal not RequiReD Book YouR appointment toDaY 13-0035 RSVP Today ~ Call 250.655.0849 or register online at Refresh Your Smile! #4 - 7115 West Saanich Rd Brentwood Bay Education for the Elegantly Active For those 50+ years rd CALL: 778.351.3211 ch ni aa .s w Amica at Beechwood Village A Wellness & Vitality™ Residence 2315 Mills Road Sidney, BC V8L 5W6 r. ed ac ll wa The Trusted Name In real esTaTe Upcoming courses Beaches of the Peninsula The Salish Sea: A Retrospective All About You: Writing Your Memoirs Getting Started with Computers Social Media Courses Facebook Fun Social Media Basics Peninsula Elder College Gay Helmsing – RealtoR® 250-360-7387 ghelmsing@gmail.com sIdNey characTer If you like heritage houses, you will love this one! Oozing charm, this one level 1,698 square foot home built in 1920 has upgraded wiring & plumbing. Spacious country kitchen with family room. Large front porch. Close to the sea. Offered at $579,000 Learning For Life 250.656.7271 52 SEASIDE | FEBRUARY 2013 RE/MAX Camosun w h at ' s h a p p e n i n g FEBRUARY! February 6 - 7 Canadian Blood Services Blood Donor Clinic Mary Winspear Centre, Sidney Feb. 6th 11 am - 6 pm Feb. 7th 12 - 7 pm 250.656.0275 Blood. It's in you to give. february 9 Moss Landscapes of Vancouver Island (Guided Adult Walk) 18+ Francis/King Regional Park (Saanich) 1 - 2:30 pm 250.478.3344 Join guest CRD Regional Parks’ naturalist Kem Luther to discover the strange lives of mosses. Learn how to identify the most common species. $7/person + HST. Pre– registration required before February 8th. Space is limited. FEBRuary 10 Starlight Pops Choir presents "Swing Fever" Alix Goolden Hall 907 Pandora Avenue, Victoria 3 to 5 p.m. 250-386-6121, The Starlight Pops Choir, directed by Due Doman and with the Swing Dance Association of Victoria will perform at this concert benefitting the BC Cancer Foundation. Tickets $25. February 11 Companions of the Quaich "Women of High Spirits" Dinner and Whiskey Tasting Sidney Pier Hotel & Spa, 7 pm 250.658.1109 wuhrer@shaw.ca Women make up 20% of U.K. whisky consumers (May 2012), and why not? Some of the best whisky makers and blenders are women. This evening will feature whiskies we all love and enjoy thanks to the expertise of women who have entered the boys’ domain. Three-course dinner, four whisky tastings: members $60, guests $70, dinner only (designated drivers) $50. February 11 108 - 1931 Mt. Newton X Road, Saanichton 9:30 am - 3:30 pm 250.652.6939 Drop in and check out Gartley Station – expert wine crafting. Appetizers, refreshments, prize draws and more! FEBRuary 21). february 23, March 2, 9, 16 The Backyard Orchard Horticulture Centre of the Pacific 505 Quayle Road, Victoria 9 am - 12 pm 250.479.6162 Brought to you by the Sidney Merchants' Co-Op. Watch as Robin Sather, Canada’s only LEGO Pro, builds a life-size LEGO figure. Great contests and prizes! This four-session course is for those serious about cultivating fruit and nuts in an urban space. Ryan Senechal will cover: selection of cultivars, planting, staking and training, soil, nutrients and watering, pruning, plant health and cultural controls, grafting and propagation. This is a hands-on practicum course so dress to be outside. HCP members $140; non-members $196. february 14 february 24 Sidney Family Day LEGO Event Sidney Pier Hotel & Spa 9805 Seaport Place, Sidney 10 am - 4 pm info@sidneyfamilyday. February 16 Deep Cove Folk Music Society presents Roy Forbes Mary Winspear Centre Sidney 8 pm 250.656.0275 After 40 years, Roy Forbes remains one of Canada’s favourite and best-loved acoustic artists. Tickets $25 + hst. february 16 Gartley Station Open House Family Orienteering (Drop-in Event) All ages Elk/Beaver Lake Regional Park (Saanich) 11 am - 2 pm 250.478.3344 CRD Regional Parks’ naturalists will have maps and compasses on hand, and a beginner level orienteering course set up at Beaver Lake. Get active today! Meet at the information kiosk in the Beaver Lake parking lot. february 27 6th Annual Anti-Bullying Day (a.k.a. "Pink Shirt Day") Boys & Girls Clubs across Vancouver Island, Join the sea of pink by wearing a pink shirt and showing you will not tolerate bullying behaviour. This event raises awareness about the negative effects of bullying in schools, youth groups and workplaces. Fresh Cup Roastery Café (1931 Mt. Newton X Rd., Saanichton) will be donating 50¢ to the Brentwood Bay Boys & Girls Club for every cup of coffee sold. SEASIDE | FEBRUARY 2013 | 53 Seaside ad 2013 Jan revised.pdf 1/20/13 6:27:00 PM IslandBlue’s Sidney Art Store Beautiful waterfront location on the Saanich Peninsula Pet and child friendly • Daily, weekly and monthly rates Friend us on Facebook ask about our Park & fly oPtion! Daylight Lamps C M to The Cedarwood for artwork, needlework, crafts, Y CM MY CY CMY K hobbies and more at your Sidney Art Store 2411 Beacon Avenue Island Blue Print Co. Ltd. Downtown: 905 Fort St., Victoria, BC Tel: 250.385.9786 Sidney: 2411 Beacon Ave., Sidney, BC Tel: 250.656.1233 2013_RHINO_Island_7.75"x 4.925"_AD.pdf Toll Free: 1.800.661.3332 1 13-01-03 2:31 PM The Cedarwood Inn and Suites – Your Home Away from Home 9522 Lochside Drive, Sidney, British Columbia | 54 SEASIDE | FEBRUARY 2013 last word Now, the annual Pink Shirt Day raises awareness about the negative I ran home from the school playground, effects of bullying in schools, youth groups and workplaces. Through crying, looking to my mom for comfort. various fundraising activities, donations are made to the Boys & Girls "Steven Jubb threw a rock at me while I was Club. In Saanichton at Fresh Cup Roastery Café (1931 Mt. Newton X on the swing and chipped my tooth!" I sobbed. Rd.) .50¢ from each cup of coffee sold on Pink Shirt Day will be donated In the blink of an eye, my mom and dad to the Brentwood Bay Boys & Girls Club, so be sure to stop by! loaded us into the car and headed over to the To find out how you, your school or place of business can take part Jubb house. Not necessary, I protested: I'd in Pink Shirt Day, please visit. forgive Steven and that would be that. But it wasn't; this was a small community, and everyone knew each other. Young Steven's folks needed to know the truth about their son's Editor terrible behaviour, and only then would that be that. I don't remember what I was thinking – whether I was happy Steven would get in trouble, whether I felt a little bit of apprehension, The Peninsula Emergency whether I felt just the slightest bit guilty for "tattling." What I do remember is Steven Jubb, after my father had revealed Measures Organization the reason for our impromptu visit, protesting: "I did throw a rock at Serving the Districts of Central Saanich, Allison, but it was because she was calling me 'Chubby Jubby.' " North Saanich and the Town of Sidney – to be available during times of disaster and major emergency Ah … THAT was that. Apologies to Mr. and Mrs. Jubb for Become a part of your Community: disturbing them, a short ride back home and I was grounded for being, well … a bully. I was generally a pretty nice little girl, VOLUNTEER but calling someone names is not nice behaviour. Search & Rescue • Emergency Support Services I was reminded of this incident last night, when a good friend Neighbourhood Emergency Preparedness Program • Communications reminded me to include February 27th, Pink Shirt Day, in our What's Training to be provided Happening section. I knew about the event, but not its origins. For more information please visit From a Globe & Mail article: "David Shepherd, Travis Price and their or call a Municipal Coordinator at one of the following numbers: Spa • protest Seaside Febin2013 Ad • Size: 7.75” (w)Saanich: x 4.925” (h) • Final File • Jan 15/13 • Sidney: 250-656-2121 teenage friends organized Haven a high school to Times wear pink sympathy Central 250-544-4238 • North Saanich: 250-656-1931 with a Grade 9 boy who was being bullied [for wearing a pink shirt]." Allison Smith, Rejuvenate yourself AGAIN ...with our Ultimate 2 hour facial. This treatment includes foot soak, back, neck and shoulder massage, brow shape, 2 treatment masques and 2 facial massages to promote healthy and radiant skin. Go on, you deserve it... only $125! Add a shampoo & blowdry to facial $30. To book your appointment call 250-655-9797 9805 Seaport Place, Sidney, British Columbia Now Open Sundays! 10am – 4pm Open Monday – Saturday 9am – 6pm SEASIDE | FEBRUARY 2013 | 55 GIRLS NIGHT GIRLS NIGHT OUTBACK OUTBACK L L I I VV EE O N O SS TT AA G G E E At The Mary Winspear Centre April 13th, 2013 @ 8 pm (doors @ 7 pm) 2243 Beacon Avenue, Sidney 250.656.0275 • • Published on Jan 30, 2013 Think of our publication as an extra dimension of our community space, a place where the West Coast culture is treasured and celebrated. We’...
https://issuu.com/seasidetimes/docs/seaside0213forweb?mode=embed&layout=http%3A%2F%2Fskin.issuu.com%2Fv%2Flight%2Flayout.xml&showFlipBtn=true
CC-MAIN-2017-47
refinedweb
19,225
62.17
Hello, guys! I've written a GUI for a program. It's written like shit, the goal was to get it done fast. Well it didn't exactly work out, so when I refresh the data, every label disappears. Here is the code: class GUI: def __init__(self, master): self.master = master self.label = Label(master, width=50, height=15) self.label.pack() self.makeMenus() self.showStats() Then, loads of labels, some with textvariables like this: def showStats(self): stats = loadStats() # buys Label( self.label, text='Buys', font=BOLDFONT ).place(x=40, y=10, anchor=NW) Label(self.label, text='Times:').place(x=10, y=50, anchor=NW) self.buyTimes = StringVar(self.label) Label( self.label, textvariable=self.buyTimes ).place(x=60, y=50, anchor=NW) ... ... and here is the code for the refresh method: def refreshStats(self): stats = loadStats() self.buyTimes.set(stats['buys']) ... So the problem is, that after refreshing, every label disappears for a second, but when I move the cursor over the ones with textvariables, they reapper, but the others don't. What should I do?
https://www.daniweb.com/programming/software-development/threads/292070/tkinter-label-refresh-problem
CC-MAIN-2018-51
refinedweb
180
62.34
Parse::DebControl - Easy OO parsing of debian control-like files use();() new($debug) Returns a new Parse::DebControl object. If a true parameter $debug is passed in, it turns on debugging, similar to a call to DEBUG() (see below); parse_file($control_filename,$options) Takes a filename as a scalar and an optional hashref of options (see below). Will parse as much as it can, warning (if DEBUGing. parse_mem($control_data, $options) Similar to parse_file, except takes data as a scalar. Returns the same array of hashrefs as parse_file. The options hashref is the same as parse_file as well; see above. parse_web($url, $options) Similar to the other parse_* functions, this pulls down a control file from the web and attempts to parse it. For options and return values, see parse_file, above write_file($filename, $data, $options) write_file($handle, $data) write_file($filename, [$data1, $data2, $data3], $options) write_file($handle, [$data, $data2, $data3]) This function takes a filename or a handle and writes the data out. The data can be given as a single hashref or as an arrayref of hashrefs. It will then write it out in a format that it can parse. The order is dependant. write_mem($data) write_mem([$data1,$data2,$data3]); This function works similarly to the write_file method, except it returns the control structure as a scalar, instead of writing it to a file. There is no %options for this file (yet); DEBUG() Turns on debugging. Calling it with no paramater or a true parameter turns on verbose warn()ings. Calling it with a false parameter turns it off. It is useful for nailing down any format or internal problems. Version 2.005 - January 13th, 2004 The module will let you parse otherwise illegal key-value pairs and pairs with spaces. Badly formed stanzas will do things like overwrite duplicate keys, etc. This is your problem. As of 1.10, the module uses advanced regexp's to figure out about comments. If the tests fail, then stripComments won't work on your earlier perl version (should be fine on 5.6.0+) Change the name over to the Debian:: namespace, probably as Debian::ControlFormat. This will happen as soon as the project that uses this module reaches stability, and we can do some minor tweaks. Parse::DebControl is copyright 2003,2004 Jay Bonci <jaybonci@cpan.org>. This program is free software; you can redistribute it and/or modify it under the same terms as Perl itself.
http://search.cpan.org/dist/Parse-DebControl/lib/Parse/DebControl.pm
CC-MAIN-2014-41
refinedweb
404
65.32
Category Archives: C++11.” C 11 Regular-Expression Library | 20.1. Overview of C 11 Regular Expressions C++11: A cheat sheet—Alex Sinyakov C++11: A cheat sheet—Alex Sinyakov This is a amazing cheat sheet for C++11. I really recommend this. PDF slide : C++11 A cheat sheet—Alex Sinyakov Auto Storage Class Specifier (C++11) The auto key word lets you explicitly declare a variable with automatic type. It specifies that the type of the variable that is being declared will be automatically deduced from its initializer. For functions, specifies that the return type is a trailing return type. You can declare auto variables in block scope, in namespace scope, in init statements of for loops, etc, the type of the variable may be omitted and the keyword auto may be used instead. Syntax: auto variable initializer auto function -> return type You can only apply the auto key word to names of variables declared in a block or to names of function parameters. By default they have automatic type so useless in a data declaration. Initialization Any auto variable can be initialized only exception are parameters. If you do not explicitly initialize an automatic object, its value is indeterminate. If you provide an initial value, the expression representing the initial value can be any valid C or C++ expression. The object is then set to that initial value each time the program block that contains the object’s definition is invoked. Once the type of the initializer has been determined, the compiler determines the type that will replace the keyword auto as if using the rules for template argument deduction from a function call. The keyword auto may be accompanied by modifies, such as const or &, which will participate in the type deduction. For example, given const auto& i = expr;, the type of i is exactly the type of the argument u in an imaginary template template<class U> void f(const U& u) if the function call f(expr) was compiled. During a function declaration, the keyword auto does not perform automatic type detection. It only serves as a part of the trailing return type syntax. Life time Variables with the auto storage class specifier has a local scope by default. A variable x that has automatic storage has a local scope i.e. block scope, in namespace scope, in init statements of for loops. Each time a code block is entered, storage for auto objects defined in that block is made available. When the block is exited, the objects/variables are no longer available for use. static key word needs to be applied to have a static scope for auto variable. If an auto object is defined within a function that is recursively invoked, memory is allocated for the object at each invocation of the block. Unless it is declared as static. #include <iostream> #include <cmath> #include <typeinfo> template<class T, class U> auto add(T t, U u) -> decltype(t + u) // the return type of add is the type of operator+(T,U) { return t + u; } auto get_fun(int arg)->double(*)(double) // same as double (*get_fun(int))(double) { switch (arg) { case 1: return std::fabs; default: return std::cos; } } int main() { auto a = 1 + 2; std::cout << “type of a: ” << typeid(a).name() << ‘\n’; auto b = add(1, 1.2); std::cout << “type of b: ” << typeid(b).name() << ‘\n’; //auto int c; //compile-time error auto d = {1, 2}; std::cout << “type of d: ” << typeid(d).name() << ‘\n’; } Output: type of a: int type of b: double type of d: std::initializer_list<int>
https://alikhuram.wordpress.com/category/c11/
CC-MAIN-2018-09
refinedweb
600
53.81
skyscrapeapi 3.0.0+25 SkyScrapeAPI # SkyScrapeAPI enables developers to easily access a variety of Skyward information. Features # - Gradebook Access - Assignment Details - Academic History - Student Information Project Showcase # If you think your project would fit up here, join the Discord server and show us! Contributing # We welcome pull requests from anyone with interest in this project. If you find a bug or have any questions, raise an issue or ask us on the Discord server. [3.0.0+25] - Parenthesis Bug # Fixed weird extra parenthesis in the beginning of the term attribute in quick assignments Changed gbID to courseID. [3.0.0+22] - Better Account Initialization # If your account is a student account. The API will automatically try to initialize your account when any menu is clicked! 22 fixed a bug where there was huge spaces after! [3.0.0+16] - Bug Fix # Deleted old changelogs cause they were too repetitive. Nothing major will happen with the API until version 4. Some things that were changed: - Changed the list of Nodes into a Gradebook object - Added Class Object - Removed some unnecessary objects - Changed assignment to assignment page - More data type refactoring - Added more information to assignments, like exact weights, in extra information if they are found - [14] Added a find grade from term in the datatype class - [15] Fixed bug on reversal of time period and course name - [16] Fixed bug where last category header would not show up! - [17] Attempted to fix bug where history would sometimes bring null values! [2.3.6+2] - Bug Fix # Fixed dependencies [2.3.6+1] - Bug Fix # When grade bookk init gets a district not supported error. It'll try again, because this may be caused by a website session that has been inactive for too long. [2.3.5+3] - Assignment Info DataType getUIMessage # Now detects and puts a colon in the message if there is none. [2.3.5+2] - Fixed Comment Support # Assignment info comment support. [2.3.5+1] - Added Comment Support # Assignment info comment support. [2.3.4+1] - Code Speed Up # Added a long lost if statement that reduced speed of getting gradebook. Tests were performed on decent internet. One action : 7s 645 ms -> 4s 984ms Three actions : 21 s -> 14 s [2.3.3+1] - Final Bug Fix # Finally fixed all bugs for messages for all districts by searching through all div's. [2.3.2+2] - More Bug Fix # Fix bug of insertion. [2.3.2+1] - More Bug Fix # Split's the text and inserts link in there. [2.3.1+1] - Bug Fix # Fixed bug where there was duplicate links. [2.3.0+2] - Windows Retarded # Windows RETARDED [2.3.0+1] - Messages # Added messages retrieval with attachments and hyperlinks. - Gets messages from Skyward - Retrieves attachments and attempts to keep formatting - Moved messages to a new method because of the sheer slowness [2.2.1+2] - Retrieval of Current User # Retrieve current user [2.2.1+1] - User Name # Added getting the logged-in user's name. - Adds more documentation - Makes more variables private for security purposes - Refactor of lib/src files to fit dart naming convention [2.2.0+1] - Parental Account Support # Added support for parent accounts with initializing accounts. - Better documentation will be provided later. [2.1.0+3] - Small addition for maintenance checking # Will return text of the error if maintenance is returned [2.1.0+1] - Fix Github Retardation # HUGE GLOW-UP (Refactor) - Removed duplicate code - Moved files around - Removed unnecessary code [2.0.0+2] - Fix Github Retardation # No description needed. [2.0.0+1] - Server Implementation # Added quick retrieval of assignments in the grade book. - Added new data type that allows you to store assignments from the grade book - Made for servers - Retrieves post-able assignment, grade, and term the grade is from [1.1.0+3] - Bug Fix # Fixed bug that caused second login to grade book of the same API object would fail. - Made Grade Book accessor values non static - Made initgradebook return list [1.1.0+2] - Dev Test # Testing [1.1.0+1] - Refresh Rate Update # To give the developer more flexibility over skyscrapeapi. This update gives more power to the developer and allows for developers to relax more. - Refresh rates will now affect skyward log-ins - The developer can now choose IF they want to refresh skyward authentication automatically - Testing files now have settings testSettings.skyTest [1.0.1+3] - Maintenance Update # Added an example for developers to use in case they do not understand the documentation. Reformatted all files to fit flutter's requests. [1.0.1+2] - Organization Update # Minor update for renaming and organizing library stuff. [1.0.1+1] - Documentation Update # Documentation is now available for developers to view. [1.0.0+1] - First Official Pub Release # I am confident now in my code and the errors it produces. The API tester code has been finished. [0.0.1+2] - Rename to Camel Case # Like the title, rename files to Camel Case [0.0.1] - Initial Release # SkyScrapeAPI is a dart API that allows you to login and pull data from Skyward. SkyScrapeAPI was separated from the original SkyMobile app to allow the API to develop separately from the main app. SkyScrapeAPI will restart at 0.0.1. BELOW IS THE OLD CHANGELOG V1.6.0 - Allows for error checking V1.5.4 - Fixed bug where JSON Saver couldn't save ClassLevel V1.5.3 - Removed unnecessary 4.0 GPA Credit attribute V1.5.2 - Fixed bug where duplicate SchoolYears were returned. V1.5.1 - Modified History Scraper and Data Types to support json saving. V1.5.0 - Added History Scraper. Allows you to scrape from sfacademichistory001.w. V1.4.1 - Adressed major bug which prevented users from Highland Park ISD from logging in. This should fix logging in bugs for all districts with wsEAplus in their url link name. V1.4.0 - Remade Assignment scraping algorithm to support more districts. V1.3.0 - Adds DistrictSearcher to search for districts family access links. V1.2.1 - Fixed bug where assignments with the same name would display the same details: THIS BUG AFFECTS SKYMOBILE iOS AND WILL NOT BE FIXED FOR SKYMOBILE iOS V1.2.0 - Can scrape assignment details. V1.0.0 - Build the basic foundation. Initial release. - Can scrape gradebook and assignments. import 'package:skyscrapeapi/data_types.dart'; import 'package:skyscrapeapi/sky_core.dart'; import 'dart:io'; void main() async { final skyward = ""; var file = File('test/testCredentials.txt'); var contents; var terms; var gradebook; User person; if (await file.exists()) { contents = await file.readAsString(); List split = contents.toString().split('\n'); person = await SkyCore.login(split[0], split[1], skyward); } try { gradebook = await person.getGradebook(); } catch (e) { print('Should not fail: ' + e.toString()); throw SkywardError('SHOULD SUCCEED'); } try { List<AssignmentProperty> props = (await person.getAssignmentDetailsFrom(gradebook.quickAssignments[0])); print(props); } catch (e) { print('Should succeed: ${e.toString()}'); throw SkywardError('SHOULD SUCCEED'); } try { print(await person.getStudentProfile()); } catch (e) { print('Should succeed: ${e.toString()}'); throw SkywardError('SHOULD SUCCEED'); } print(terms); print(gradebook); print(await person.getHistory()); } Use this package as a library 1. Depend on it Add this to your package's pubspec.yaml file: dependencies: skyscrapeapi: ^3.0.0+25:skyscrapeapi/data_types.dart'; import 'package:skyscrapeapi/district_searcher.dart'; import 'package:skyscrapeapi/sky_core.dart'; We analyzed this package on Mar 28, 2020, and provided a score, details, and suggestions below. Analysis was completed with status completed using: - Dart: 2.7.1 - pana: 0.13.6 Health suggestions Fix lib/sky_core.dart. (-10.44 points) Analysis of lib/sky_core.dart reported 22 hints, including: line 20 col 20: Use = to separate a named parameter from its default value. line 21 col 35: Use = to separate a named parameter from its default value. line 22 col 23: Use = to separate a named parameter from its default value. line 84 col 7: DO use curly braces for all flow control structures. line 90 col 7: DO use curly braces for all flow control structures. Fix lib/src/student_related/message.dart. (-2.96 points) Analysis of lib/src/student_related/message.dart reported 6 hints, including: line 38 col 14: Use isNotEmpty instead of length line 50 col 13: Use isNotEmpty instead of length line 57 col 17: DO use curly braces for all flow control structures. line 59 col 17: DO use curly braces for all flow control structures. line 84 col 11: Use isEmpty instead of length Fix lib/data_types.dart. (-1.99 points) Analysis of lib/data_types.dart reported 4 hints: line 290 col 7: DO use curly braces for all flow control structures. line 292 col 7: DO use curly braces for all flow control structures. line 633 col 7: DO use curly braces for all flow control structures. line 635 col 7: DO use curly braces for all flow control structures. Fix additional 6 files with analysis or formatting issues. (-8.96 points) Additional issues in the following files: lib/src/gradebook/assignment.dart(4 hints) lib/src/student_related/student_info.dart(4 hints) lib/src/skyward_utils.dart(3 hints) lib/src/student_related/history.dart(3 hints) lib/district_searcher.dart(2 hints) lib/src/gradebook/gradebook.dart(2 hints)
https://pub.dev/packages/skyscrapeapi
CC-MAIN-2020-16
refinedweb
1,528
60.11
i moved too ... for ajax but still its some stupid action for eg. i create new node and ajax proxy after store.sync() execute edit method... its big joke for me... submit : function(button) { ... Type: Posts; User: holicon_abg i moved too ... for ajax but still its some stupid action for eg. i create new node and ajax proxy after store.sync() execute edit method... its big joke for me... submit : function(button) { ... any solutions in this case ? posible hack or hot fixes ? i have the same problem node = { text: values.name, parent_id: values.parent_id, parentId: values.parent_id }; ... parent.appendChild(node); ExtJs 4 MVC (namespaces, filename, name convention, standarize it) app controller (plural, camelCase) App.js - Application Controller extends by User (sometimes call main controller) ... i put working code to if u want u can fork it, btw more compliant with REST and others is put args in GET and POST. For... i work with backend frameworks for 10 yr at last. Now i spent much time for better pattern of name convention in ExtJs MVC enterprise class application. If u want check it or have better idea check... can u exmplain me for what is "widget" key in alias of view alias: 'widget.menusAdd', after that in controller i set refs: [{ ref: 'menusAdd', not too clearly point 2.2 about MVC should be III. because u're mixing classic ext design witch mvc. @link 0. article list 1.click on article 2.click view in new tab 3. go to 0. Except active opened article tab... search my post on forum i written about that. over there @link and in ext 4.0 sources > mvc examples/app but i think is still usles especially documentation. and... somebody can me explain why in one place in examples i read about Ext.require @ // Register namespaces and their... any suggest to start sencha command ? try use sencha command on fresh osx without set any PATH after installation every command dont execute many errors with `dirname` command jsb eg... the same problem on debian ... @link not enought information i do this tutorial stay by step and i have errors like this: The following classes are not... right convention for good mvc framework: name of folder contain views folder is same as controller name (plural) for eg. controller----views folder... good :) thnx for this solutions. hey try deferredRender: false, in tabCmp conf. full request specify: HTTP Method URL.method Controller action invoked GET /recipes.method RecipesController::index() GET /recipes/123.method RecipesController::view(123)... may be try only first line So ur step more than me, becouse my writer don't sent any delete request, in my case i cerate simple restful store ( i don see any readre in there only extendet Ext.data.JsonStore) and copy some... Im sure its right. The same default key in fieldset works fine. UsersAddUi = Ext.extend(Ext.Panel, { title: 'Add User', layout: 'fit', closable: true, iconCls: 'ico-tab-adduser', border: false, initComponent: function() { this.items = [ ...
https://www.sencha.com/forum/search.php?s=2383b99e162dc4348dda61eca45abd6d&searchid=18796653
CC-MAIN-2017-04
refinedweb
497
70.6
Now that we’ve covered what functions are and some of their basic capabilities, let’s take a closer look at why they’re useful. Why use functions? New programmers often ask, “Can’t we just put all the code inside the main function?” For simple programs, you absolutely can. However, functions provide a number of benefits that make them extremely useful in programs of non-trivial length or complexity. Although it doesn’t look like it, every time you use operator<< or operator>> to do input or output, you’re using a function provided by the standard library that meets all of the above criteria. Effectively using functions One of the biggest challenges new programmers encounter (besides learning the language) is understanding function). [C++] #include iostream int main(){ std::cout << "Hello world" << std::endl; } [/C++] please help Alex please help me with this (Equilateral Triangle validation and perimeter) Implement the following two functions: // Returns true if all the sides of the triangle // are same. bool isValid(double side1, double side2, double side3) // Returns the perimeter of an equilateral triangle. double perimeter(double side1) The formula for computing the perimeter is perimeter = 3 * side. Write a test program that reads three sides for a triangle and computes the perimeter if the input is valid. Otherwise, display that the input is invalid. #include <iostream> bool isValid(double side1, double side2, double side3) { //if side1 == side2 then they have the same length, and if side2 and side 3 have the same length, //it follows that side1 == side2 == side3 and therefore it is equilateral return (side1 == side2) && (side2 == side3); } double perimeter(double side1) { return side1 * 3; } int main() { //you could refactor a way to take the input for all 3 sides as a function std::cout << "Please enter side1 of your triangle:"; double side1{}; std::cin >> side1; std::cout << "Please enter side2 of your triangle:"; double side2{}; std::cin >> side2; std::cout << "Please enter side3 of your triangle:"; double side3{}; std::cin >> side3; if (isValid(side1, side2, side3)) { std::cout << "The perimeter of an equilateral triangle with side length " << side1 << " is " << perimeter(side1) << "."; } else { std::cout << "The triangle is not equilateral."; } return 0; } Name (required) Website Save my name, email, and website in this browser for the next time I comment.
https://www.learncpp.com/cpp-tutorial/why-functions-are-useful-and-how-to-use-them-effectively/
CC-MAIN-2021-17
refinedweb
378
55.88
I apologize up front; I'm a VB Programmer trying to pick up C++. I have a very simple program that takes a string input from the user. How can I look at a specific character in that string? VB has the Left(), Right(), and Mid() Functions. Is there something similar for C++? A sample of my code is below. In this example, how could I have the program return the "T" in "Test String" or the "g" at the end? #include "stdafx.h" #include <iostream> #include <string> #using <mscorlib.dll> using namespace System; using namespace std; int _tmain() { string strTest; strTest = "Test String"; cout << strTest; return 0; } Joe Cody Allied Tube & Conduit
https://www.daniweb.com/programming/software-development/threads/1113/vb-s-left-right-mid-functions-in-c
CC-MAIN-2017-34
refinedweb
113
84.47
Introduction: Why Build a Blog App With React How to build your own React-based Blog Installing Node Package Manager Working on src folder and package.json Creating a GitHub Repository Creating a homepage of the React Blog App Setting up Blog’s detail component Creating the Create Component Finalizing the useFetch hook Setting up the leftover components Setting up the JSON server How to Create a Blog With Web App Generator Conclusion Introduction As we all know, thanks to the old saying, the pen is mightier than the sword. And that is definitely true on many occasions, with an exception of, perhaps, an actual sword-on-pen fight, but we digress. The point we are conveying here is that speech and information are not just a way of sharing ideas, but a powerful tool, which you should employ to your advantage. If we get back to the metaphor, the pen is indeed mightier than a sword, as it can help you raise a thousand swords back in defense. Do not get us wrong, words should not be weaponized, as their true power lies in their force of creating and making the world a better place and that is how they should be used. Another reason why the information is important and mighty lies in the stipulations of the modern world and modern society. We said it many times, but it bears repeating – our world nowadays is information-based, meaning that it is one of the most powerful and useful possessions one can have. “That’s all good and somewhat poetical, but what does it have to do with building blogs on React?” – you might think. The answer is simple: a blog is an effective tool for spreading information if done and maintained correctly. And React is one of the best ways to get it right. And in this article, we would like to take you on a little tour that will help you understand the process of building a blog on React, creating it step-by-step with us. So, let’s not postpone the beginning of our tour any further and get down to it. How to build your own React-based Blog The first stop on our React-based blog building tour would be describing and picturing what we are going to have in the end. And, what we are going to have, is an extremely simple blog website that will have quite a small toolset and lacking functionality. But nonetheless, it will be most open to improvement due to, in no small part, its simplicity. Next, let’s discuss what features our React-based Blog would have: Ability to add and delete blogs; Fetching and displaying details about each and every individual blog; Fetch blogs from a local JSON server. They would also be displayed in a list form; This would be a purely React-based blog and there would be no back-end servers used. It means that all the changes made on the page of the chat would not be saved and we will see the blog in its default state with each refresh of the page. All of these features are aimed at creating as simple a blog app as it can be in order to strip the blog to its bare skeletal state and pay closer attention to its structure. Now, we get to coding. Step №1. Installing Node Package Manager The first practical step we take in creating our npm module that will help our back-end’s Node.JS to put modules into place so that it would be able to find them, as well as manage dependencies conflicts. To install npm from the npmjs.com site, after which you install it and start creating the React Blog app by writing down the following command: npx create-react-app react-blog npx is a tool that is bundled with npm. So, by writing the line above you create a new React project that would be named react-blog, as well as a basic React program that will contain node modules, a src folder, a public folder, and a package.json file. After that, we get down to working with the latter and the src folder. Step №2. Working on src folder and package.json What we need to understand is that our package.json file would have many dependencies, which secure React’s correct work. But fear not, as our previous step has covered most of this work preemptively. Here is how it should look at this point: { “name”: “blog”, “version”: “0.1.0”, “private”: true, “dependencies”: { “@testing-library/jest-dom”: “^5.11.4”, “@testing-library/react”: “^11.1.0”, “@testing-library/user-event”: “^12.1.10”, “react”: “^17.0.1”, “react-dom”: “^17.0.1”, “react-router-dom”: “^5.2.0”, “react-scripts”: “4.0.1”, “web-vitals”: “^0.2.4”, “react-query”: “latest” }, ” ] } } Step №3. Creating a GitHub Repository This step is needed to ensure that you would be able to track all the changes that are going to be made into our React Blog App. What we need to do here is to initialize this new Get Repo that is going to be used in the folder of our project by adding the next line of code: git init After that you would need to link it with the GitHub Repository by the command that goes like: git remote add origin your-repo What you need to do next is add our previous file to the Git repo that you have initialized earlier by adding the next line of code: git add -A And making a commit into the Git repository with the following line: git commit -m “First commit” The final thing you would need to do during this step is pushing all your local Git Repositories to the Github repository with the help of: git push origin master Keep in mind that the process of working with the GitHub Repository is manual at the moment, which means you would have to add, commit and push (by using the git add, -commit and -push commands respectively) by hand when making any significant changes. Step №4. Creating a homepage of the React Blog App To create the homepage for our React Blog App we would mostly use the BlogList component and the useFetch hook. First, you need to set up the useFetch hook, which would perform three functions for the blog: 1. Holding all the present blogs in your local JSON database; 2. Allowing you to know if the data is currently being fetched and when it is fully fetched and displayed; 3. Storing all the errors that are to be encountered while the data is fetching from the local JSON server. This piece of code would look the following way: import BlogList from ‘./BlogList’; import useFetch from ‘./useFetch’; const Home = () => { const {data: blogs, isPending, error} = useFetch(‘’); return ( <div className=”home”> {error && <div>{error}</div>} {isPending && <div>Loading…</div>} <BlogList blogs={blogs} title=”All Blogs”/> </div> ); } Now we bring our attention to the BlogList component. As seen in the previous piece of coding, we have already invoked this component and it is going to pass in the blogs and titles to be displayed in our Blog App. Now we need to import Link, which would, similar to the anchor tag, help us in the task of linking texts, images, and URLs, although not calling the server, but using the locally saved data. We import Link with the help of the react-router-dom. This stage of the coding would look like this: import { Link } from ‘react-router-dom’; const BlogList = ({blogs, title}) => { return ( import { Link } from ‘react-router-dom’; const BlogList = ({blogs, title}) => { return ( <div className=”blog-list”> <h2>{title}</h2> {blogs.map(blog => ( <div className=”blog-preview” key={blog.id}> <Link to={`/blogs/${blog.id}`}> <h2>{blog.title}</h2> <p>Written by {blog.author}</p> </Link> </div> ))} </div> ); } export default BlogList; Step №5. Setting up Blog’s detail component Blog detail component’s goal is to fetch and display single blog posts. That’s why it is important to be careful when setting it up and not forget to call the Blog detail component using a Link passing in the web address and include a blog’s id in the URL as a param. In order to do that we extract the id using the getParams() hook, after which we use the previously mentioned useFetch custom hook to actually get the particular blog entry by passing in the id in the useFetch hook. During this step, we also set up such a hook as useHistory() in order to establish a history stack, push or pop elements and store the components or visited pages in the history stack. And, finally, we add the function of deleting the blog by adding the button that functions as a handleClick. This part of the process code-wise would look the following way: import { useParams, useHistory } from ‘react-router-dom’; import { useQuery } from ‘react-query’; const BlogDetails = () => { const { id } = useParams(); const { isLoading, error, data: blog, } = useQuery(‘blogDetails’, () => fetch(‘’ + id).then(res => res.json())) const history = useHistory(); const handleClick = () => { fetch(‘’+ blog.id, { method: ‘DELETE’ }).then(() => { history.push(‘/’); }) } return ( <div className=”blog-details”> {isLoading && <div>Loading…</div>} {error && <div>{error}</div>} <article > <h2>{blog.title}</h2> <p>Written by {blog.author}</p> <div>{blog.body}</div> <button onClick={handleClick}>Delete</button> </article> </div> ); } export default BlogDetails; Step №6. Creating the Create Component Just as the name implies, the Create Component is used to create new blog posts in the app. It would use two hooks: the useState hook; and the useHistory hook. The coding for this part would look as follows: import { useState } from ‘react’; import { useHistory } from ‘react-router-dom’; const Create = () => { const [title, setTitle] = useState(”); const [body, setBody] = useState(”); const [author, setAuthor] = useState(‘Shubham’); const [isPending, setIsPending] = useState(false); const history = useHistory(); const handleSubmit = (e) => { e.preventDefault(); const blog = { title, body, author }; setIsPending(true); fetch(‘’, { method: ‘POST’, headers: {“Content-Type”: “application/json”}, body: JSON.stringify(blog) }).then(() => { setIsPending(false); history.push(‘/’); }) } return ( <div className=”create”> <h2>Add a New Blog</h2> <form onSubmit={handleSubmit}> <label>Blog Title</label> <input type=”text” required value={title} onChange={(e) => setTitle(e.target.value)} /> <label>Blog Body:</label> <textarea required value={body} onChange={(e) => setBody(e.target.value)} /> <label>Blog author:</label> value={author} onChange={(e) => setAuthor(e.target.value)} > <option value=”Shubham”>Shubham</option> <option value=”Satyam”>Satyam</option> <option value=”Anmol”>Anmol</option> {!isPending && <button>Add Blog</button>} {isPending && <button disabled>Adding Blog</button>} </form> </div> ); } export default Create; Step №7. Finalizing the useFetch hook We have already set up our useFetch hook and now it is time to make small adjustments and additions for it to fit our React Blog App like a glove. What we mean by that is setting up useState and useEffect hooks. The useState hook is responsible for setting up three hooks in this case: · data, which would be an empty array by default; · sPending, which we are to set to true; · and error, which we would set to null. By using our own local JSON server we rid ourselves of the ability to see the loading effect on the homepage. For that, we are going to use the setTimeout function in order to delay the fetching process. And as for the useEffect hook, we would use an abort controller stored inside, as well as the timeout function for data fetching using the URL that we have received from other components when this hook was called. What we need to do here is wait for the response from the server and see, whether the response is positive or negative: · if the response is negative, we mark it as an error; · if the response is positive – we’ve got the data. After we’ve got the date, we need to set it in our data variable, set the error variable to null and set isPending to false. The piece of coding needed for this whole step would look like this: import { useState, useEffect } from ‘react’; const useFetch = (url) => { const [data, setData] = useState([]); const [isPending, setIsPending] = useState(true); const [error, setError] = useState(null); useEffect(() => { const abortCont = new AbortController(); setTimeout(() => { fetch(url, { signal: abortCont.signal }) .then(res => { if(!res.ok) { throw Error(‘Could not fetch data for that resource’); } return res.json(); }) .then((data) => { setData(data); setIsPending(false); setError(null); }) .catch((err) => { if(err.name===’AbortError’) { console.log(‘Fetch aborted’); } else { setError(err.message); setIsPending(false); } }) }, 5); return () => abortCont.abort(); },[url]); return {data, isPending, error}; } export default useFetch; Step №8. Setting up the leftover components The next step in the creation of the React Blog App would be to create such components, as: The Navbar component; The NotFound Component; The App Component; Index.css; Index.js. We set up the Navbar component in order to display the navigation bar in the App. It is rather easy, as it is only going to have two links: the Home link and the Create Blog link. The coding for the Navbar component would look like this: import { Link } from ‘react-router-dom’; const Navbar = () => { return ( <nav className=”navbar”> <h1>React Blog App</h1> <div className=”links”> <Link to=”/”>Home</Link> <Link to=”/create”>Create Blog</Link> </div> </nav> ); } export default Navbar; The NotFound component is needed to display the 404 Error page. It would be a simple 404 Error page with a heading displaying 404 error, a text saying that the page was not found, and a link to the homepage. The coding for this component would look like that: import { Link } from “react-router-dom” const NotFound = () => { return ( <div className=”not-found”> <h2>404 Error</h2> <p>We cannot find that page!</p> <Link to=’/’>Take me back to Home</Link> </div> ); } export default NotFound; The App component is needed to bind and interlink all the components together, as it imports all the required components, as well as BrowserRouter, Route and Switch from react-router-dom. The coding, in this case, would look like this: import Navbar from ‘./Navbar’; import Home from ‘./Home’; import Create from ‘./Create’; import BlogDetails from ‘./BlogDetails’; import NotFound from ‘./NotFound’; import { BrowserRouter as Router, Route, Switch} from ‘react-router-dom’; import { QueryClient, QueryClientProvider } from ‘react-query’ function App() { const queryClient = new QueryClient() return ( <QueryClientProvider client={queryClient}> <Router> <div className=”App”> <Navbar/> <div className=”content”> <Switch> <Route exact path=”/”> </Route> <Route path=”/create”> <Create/> </Route> <Route path=”/blogs/:id”> <BlogDetails/> </Route> <Route path=”*”> <NotFound/> </Route> </Switch> </div> </div> </Router> </QueryClientProvider> ); } export default App; Index.css, as the name implies, is a CSS file needed for the design of our React-based Blog App. And as the design is the most subjective part of the whole process, we would present you with the utmost freedom in creating it. Index.js, on the other hand, is quite fixed in its coding, as it is the index file that serves as the starting point of our application. Here is how it should look: import React from ‘react’; import ReactDOM from ‘react-dom’; import ‘./index.css’; import App from ‘./App’; ReactDOM.render( <React.StrictMode> <App /> </React.StrictMode>, document.getElementById(‘root’) ); And with that, all of our components are set and we get to the final step of the whole process. Step №9. Setting up the JSON Server Our final step brings us to setting up a JSON server, which we would use to build a fake REST API. In order to do that, you should use the following command: npm install -g json-server After that you need to create the data folder and make a db.json file inside of it, which will contain the following piece of coding: { “blogs”: [ { “title”: “1st blog”, “body”: “Greetings.”, “author”: “Author 1”, “id”: 1 }, { “title”: “2nd blog”, “body”: “Hello.”, “author”: “Author 2”, “id”: 2 }, { “title”: “3rd blog”, “body”: “Hi”, “author”: “Author 3”, “id”: 3 } ] } After that part is completed, start the server with the following command: npx json-server — watch data/db.json — port 8000 And that is how you create your own React-based Blog App. It is now possible to start it on any different port and check it out. The whole process is not that hard to complete from the technical point of view, it is surely quite tedious in execution due to the number of steps you need to take. But fear not, as there is, actually, a much easier way to create your own Blog App. And by that we mean Flatlogic’s Full Stack Web App Generator, which allows you to build an array of different React-based applications in just 5 simple steps. How to Create a Blog With Web App Generator Step №1. Select a name for your App Step №1 is as self-explanatory as they come. Just write down a name you would like your project to have and be on your merry way to the second step. Step №2. Choosing your React Blog’s Stack This step is quite crucial, as here you decide the whole basis of your new app and by that, we mean frontend, backend, and database. For the purposes of this article, we’ve chosen React for the frontend side of the app, Node.js for the backend, and MySQL for the database. Step №3. Choosing a design for your React Blog App This step is most pleasing for those, who understand the value of a nice design. And Flatlogic’s Full Stack Web has a wide selection of beautiful designs for you to choose from. For our exemplary React Blog App, we’ve decided to choose the Classic design for its slickness. Step №4. Creating your React Blog App’s Schema Step №4 is also one that you would call crucial, as Database Schema is the backbone that will help your Blog App stand proudly and work properly. Luckily, Flatlogic’s Full Stack Web App Generator gives you an array of ready-made Database Schemas that you can use, including a Schema for blogs, which means that you don’t even have to create it yourself! And this is a fully made high-quality Database Schema as well, as it covers everything from users to comments, as you would be able to see in the following pictures. Step №5. Reviewing and Generating your React Blog App And now we come to the final step of the whole process of creating a React Blog App with the help of Flatlogic’s Web App Generator – reviewing and generating the app. All you have to do here is assure yourself that you’ve included and chosen everything you wanted and click the “Create Project” button. After that, you can give yourself a round of applause for a job well done and wait for the final project to generate. Conclusion In this article, we have taken an extensive look at the process of building a blog app on React. And if there is an outtake to have, it is the fact that React is quite a handy and efficient tool to do it and you should definitely consider it as a tool to build your next blog, be it a separate project or a part of the project. Have a nice day and, as always, feel free to read up on more of our articles! The post Build a Blog on React: Step-by-Step Guide With Examples appeared first on Flatlogic Blog.
https://online-code-generator.com/build-a-blog-on-react-step-by-step-guide-with-examples/
CC-MAIN-2021-43
refinedweb
3,239
59.03
Struts dispatch action - Struts Struts dispatch action i am using dispatch action. i send the parameter="addUserAction" as querystring.ex: at this time it working fine... this problem please send me... Thanks in advance Dispatch Action - Struts Dispatch Action While I am working with Structs Dispatch Action . I am getting the following error. Request does not contain handler parameter named 'function'. This may be caused by whitespace in the label text Struts Dispatch Action Example Struts Dispatch Action Example Struts Dispatch Action... function. Here in this example you will learn more about Struts Dispatch Action" for understanding.so please guide for the same. thanks Please visit the following link: Struts Tutorials Login Action Class - Struts Login Action Class Hi Any one can you please give me example of Struts How Login Action Class Communicate with i-batis struts how to solve actionservlet is not found error in dispatch action Struts - Struts Struts Provide material over struts? Hi Friend, Please visit the following link: Thanks struts struts <p>hi here is my code can you please help me to solve...; <hr /> Please visit the following link: Struts Login...; <p><html> <body></p> <form action="login.do"> Java - Struts in DispatchAction in Struts. How can i pass the method name in "action... more the one action button in the form using Java script. please give me... on DispatchAction in Struts visit to : Action Chaining Struts Action Chaining Struts Action Chaining Is Action class is thread safe in struts? if yes, how it is thread safe? if no, how to make it thread safe? Please give me with good...:// Thanks Servlet action is currently unavailable - Struts Servlet action is currently unavailable Hi, i am getting the below error when i run the project so please anyone can help me.. HTTP Status 503 - Servlet action is currently unavailable Struts - Struts Struts hi can anyone tell me how can i implement session tracking in struts? please it,s urgent........... session tracking? you mean... for later use in in any other jsp or servlet(action class) until session exist DispatchAction class? - Struts , Please visit the following link: class? HI, Which is best and why either action class Actions - Struts Action struts 2 Please explain the Action Script in Struts Struts - Struts ) } alert("Invalid E-mail Address! Please re-enter.") return (false); } function validateForm(formObj){ if(formObj.userid.value.length==0){ alert("Please...; } if(formObj.password.value.length==0){ alert("Please enter password!"); formObj.password.focus Struts Action Class Struts Action Class What happens if we do not write execute() in Action class Struts 2 Url Validator given in the xml file (like "Please enter a valid URL."). The URL...Struts 2 Url Validator The URLValidator of Struts 2 Framework checks whether the String contained within,... please help me out how to store image in database(mysql) using struts struts struts please send me a program that clearly shows the use of struts with jsp titles - Struts Use Struts Titles in Web Applications hi i want to use titles in my web project please help me . in my project i have four titles such as banner, menu , content and footer . please provide any example code Projects solutions: EJBCommand StrutsEJB offers a generic Struts Action class... Struts Projects Easy Struts Projects to learn and get into development ASAP. These Struts Project will help you jump the hurdle of learning complex action Servlet - Struts action Servlet What is the difference between ActionServlet ans normal servlet? And why actionServlet is required Struts first example - Struts ! I am using struts 2 for work. Thanks. Hi friend, Please visit... Please enter valid Postcode. Thanks Hi...Struts first example Hi! I have field price. I want to check struts 1.3 struts 1.3 please provide me a login application using struts1.3 hibernate and mysql thanks java struts error - Struts java struts error my jsp page is post the problem...*; import javax.servlet.http.*; public class loginaction extends Action{ public...=/VENU9/INDEX.JSP AND Hi friend, Please specify struts 1.3 struts 1.3 After entering wrong password more than three times,the popup msg display on the screen or the username blocked .please provide its code in struts jsp E-mail Validator . Otherwise, it displays the message given in the xml file (e.g. Please enter a valid...Struts 2 E-mail Validator The email validator in Struts 2 Framework checks whether a given String struts struts how to make one jsp page with two actions..ie i need to provide two buttons in one jsp page with two different actions without redirecting to any other page struts <html:select> - Struts struts i am new to struts.when i execute the following code i am getting this exception .how to solve this problem .please rectify the problem... : 1. Remove name attribute altogether and specify only an action attribute Struts 2.0 - Struts Struts 2.0 Hi ALL, I am getting following error when I am trying...: people or people.{name} here is the action: public class WeekDay.../SelectTag.jsp" please let me know If I am doing any struts struts <p>hi here is my code in struts i want to validate my...;gt; <html:form <pre>... RegisterAction extends Action { public RegisterAction() { try Struts 2 Interceptors checks that a single valid token is processed in Action but when...Struts 2 Interceptors Struts 2 framework relies upon Interceptors to do most of the work before and after an action is executed. Interceptors are by default Connecting Oracle database with struts - Struts Connecting Oracle database with struts Can anyone please provide me some solutions on Connection between Oracle database and struts Struts - Struts Struts hi, I am new in struts concept.so, please explain example login application in struts web based application with source code . what are needed the jar file and to run in struts application ? please kindly Struts Tutorial . Struts View Component : Takes the input from the user and provide the information to them. Struts Controller Component : In Controller, Action class... of Struts and download. Struts Built-In Actions Struts provide the built-in actions struts - Struts struts I want to know clear steps explanation of struts flow..please explain the flow clearly About Struts processPreprocess method - Struts About Struts processPreprocess method Hi java folks, Help me... that the request need not travel to Action class to find out that the user is not valid? Can I access DB from processPreprocess method. Hi Hi... - Struts provide you hibernate tutorial with running code Please visit for more...Hi... Hi, If i am using hibernet with struts then require to install hibernet or not....if installation is must then please send url configuration - Struts configuration Can you please tell me the clear definition of Action.... Action class: An Action class in the struts application extends Struts...:// have been asked in one of the technical interviews if struts framework is stateless or stateful . I could not answer. Please answer and explain a bit about it how it is achieved. thanks kanchan
http://www.roseindia.net/tutorialhelp/comment/78676
CC-MAIN-2014-23
refinedweb
1,167
66.94
Async GraphQL Helper Library Project description Cannula GraphQL for people who like Python! Why Cannula? We wanted to make the world a better place, but we are programmers so we settled on making the web fun again. Too much attention has been given to Javascript client libraries. They all seem to compete on size and speed and features but most of them do not solve any of the actual problems you have. So while the todo application is quick and easy to follow the hard parts take a long time to complete. For starters Javascript use to be simple and it did not require using a transpiler. It was mostly JQuery and it sort of worked but it didn't get in your way. Now a days if you want a fancy single page application you need to invest a good week or so planning out all the tools you will need to assemble your site. Every decision is full of sorrow and doubt as you google for the latest trends or how to setup unit tests. Or searching for a bootstrapped version of the library you like. Using GraphQL you can simplify your web application stack and reduce dependencies to achieve the same customer experience without regret. By using just a few core libraries you can increase productivity and make your application easier to maintain. Our Philosophy: - Make your site easy to maintain. - Document your code. - Don't lock yourself into a framework. - Be happy! Installation Requires Python 3.6 or greater! pip3 install cannula Quick Start Here is a small hello world example: import asyncio import typing import sys from graphql.language import parse import cannula api = cannula.API(__name__, schema=""" type Message { text: String } extend type Query { hello(who: String): Message } """) class Message(typing.NamedTuple): text: str # The query resolver takes a source and info objects and any arguments # defined by the schema. Here we only accept a single argument `who`. @api.resolver('Query') async def hello(source, info, who): return Message(f"Hello, {who}!") # Pre-parse your query to speed up your requests. Here is an example of how # to pass arguments to your query functions. SAMPLE_QUERY = parse(""" query HelloWorld ($who: String!) { hello(who: $who) { text } } """) async def main(): who = 'world' if len(sys.argv) > 1: who = sys.argv[1] results = await api.call(SAMPLE_QUERY, variables={'who': who}) print(results) loop = asyncio.get_event_loop() loop.run_until_complete(main()) Now you should see the results if you run the sample on the command line: $ PYTHONPATH=. python3 examples/hello.py ExecutionResult(data={'hello': {'text': 'Hello, world!'}}, errors=None) $ PYTHONPATH=. python3 examples/hello.py Bob ExecutionResult(data={'hello': {'text': 'Hello, Bob!'}}, errors=None) But what about Django integration or flask? from django.contrib.auth.models import User schema = """ type User { username: String # Only expose the fields you actually use first_name: String last_name: String made_up_field: String } extend type Query { getUserById(user_id: String): User } """ @api.query() async def getUserById(source, info, user_id): return User.objects.get(pk=user_id) @api.resolve('User') async def made_up_field(source, info): return f"{source.get_full_name()} is a lying lier there is no 'made_up_field'" Since GraphQL is agnostic about where or how you store your data all you need to do is provide a function to resolve a query. The results you return just need to match the schema and you are done. Django and sqlalchemy already provide tools to query the database. And they work quite well. Or you may choose to use an async database library to make concurrent requests work even better. Try them all and see what works best for your team and your use case. Documentation A little light right now... Come back soon for more. Meanwhile have a look at our examples: Project details Release history Release notifications 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/cannula/
CC-MAIN-2019-18
refinedweb
646
67.15
ISO/IEC JTC1 SC22 WG21 N3426 = 12-0116 - 2012-09-23Lawrence Crowl, crowl@google.com, Lawrence@Crowl.org Introduction Problem Prior Approaches The Pre-Parsed Header Approach Approach Constraints Implementation of the Approach Implementation Status GCC Implementation Problems Google Build Problems Inherent Implementation Problems Changes to the Problem Alternate Approaches Reduce Project Scope to a Chainable PCH Stream Parser Actions Make Definitions Exclusive to a Package More Aggressively Compile Inline Functions Implement Export Control Summary Google's build system is highly parallel. As a consequence, the dominant factors in interactive programming latency are the time to compile the longest translation unit and the time to link the executable. In this paper, we briefly describe some of our efforts to reduce interactive compile time. We go into further detail on our latest effort, “Pre-Parsed Headers”, which can be considered a precursor to C++ modules. In particular, the lessons arising from our effort have implications on the pending C++ standards effort on modules. The compilation model of C/C++ is a large number of translation units, each textually including headers that are often used by many other translation units. This model causes two problems. Because header files are textually included, the meaning of a header file can be affected, intentionally or otherwise, by the headers that happened to be included before it. E.g., the system header file stddef.h accepts “parameters” in the form of #defines specified before the #include. These #defines and their consequences within stddef.h go on to spread over all the other header files included downstream. As a consequence, the parametric nature of some headers makes the meaning of all headers potentially unreliable. It is clear that large systems are being built with the current approach, and therefore that the problem is manageable. However, programmer productivity would be better if the problem did not exist. In C++, headers include a large number of inline function definitions and template definitions, which dramatically increases the size of headers. Indeed, in the limiting case, C++ compilation time is proportional to the product of header files and compilation units. In practice, the complexity is not that bad, but compilation is still one of the largest components of build latency. Generally, though, much of build work is redundant. In addition to redundant work between translation units, there is redundant work in one translation unit as it is recompiled during the edit-compile-debug cycle. Only very rarely do most headers change meaning in that cycle, and textual header recompilation contributes to the latency of the cycle. Google's codebase is somewhat different from many in that we follow an “include what you use” approach. As a consequence, Google compilation units tend to use a high fraction of symbols included. We have measured symbols use rates in the range of 70%. The primary prior approach to reducing compile time is pre-compiled headers (PCH). The compiler can load a PCH file instead of parsing the first header file inclusion. When any file included from that first header file changes, then the entire PCH file must be rebuilt. PCH is effective when translation units use a common, large, and stable header that represents a substantial portion of parse time. In Google's environment, no such header exists. In general, we found that any PCH header that represented a substantial portion of parse time was too unstable to provide any net benefit. As an experiment, we tried Pre-tokenized Headers (PTH). In this approach, the compiler saves the tokens from a header into a state file. The next time a header is included, instead of tokenizing the text, the compiler reads the previously saved stream of tokens. This approach was relatively straightforward to implement, but the savings were negligible. In the meantime, normal optimizations to the preprocessor and increased effort in the parser and code generator have further reduced the benefit. We next explored an Incremental Compiler Server. In this approach, some roles of the build system and the compiler are reversed. The compiler lives as a server in the nodes of the build cluster. The compiler uses an in-memory database of previously seen header files to determine whether a header needs to be re-parsed or recovered from the database. Long before implementation was complete, we determined that the approach would be too difficult to maintain in our build system, primarily due to issues in the repeatability of failures. The fundamental change in this approach over earlier approaches is that it uses a factored representation, so that a typical compilation unit will read multiple pre-parsed header (PPH) files. With this approach, a change in a header will only cause invalidation of the PPH files that either directly include that header or depend on a PPH file that was invalidated. Thus in the DAG of header inclusions, PPH only requires recompiling the PPH files that are on a path of includes from the changed header to the compilation unit. The majority of PPH files would be unchanged by most source changes. The approach had significant constraints as well -- the primary being to minimize the change to existing sources. The PPH approach reinterprets a #include directive to read a PPH file instead when a PPH file exists for that header. Otherwise, the header is read and parsed as normal. While the semantics of PPH are not identical to regular compilation, they are nearly identical for "modular" headers. In PPH, we call a header H modular if it meets the following requirements: H is guarded against multiple inclusion. That is, the file contains: #ifndef SOME_LABEL #define SOME_LABEL ... #endif H can be pre-processed and parsed in isolation. This means that the file must not depend on symbols/types defined by the environment or another file included before it. H is always included from the global namespace. These requirements meet common practice for header design, and most headers meet these requirement without change. Indeed, PPH makes the meaning of header files more stable, as the author of the header can be assured that client inclusion environments will not change header semantics. Significantly, some headers are not modular. In particular, system headers are often very far from modular. These headers must be included textually. As a consequence, two different PPH files may have the same textual header included within them, requiring the parser to merge, or unify, the multiply defined symbols and types contained in the two PPH files. This merge operation is never needed in regular compilations. Since Pre-Parsed Headers are headers, they must provide the preprocessor semantics of headers. In particular, PPH files export the same set of preprocessor macros that the headers export. Those macro definitions must be replayed when PPH files are read. Because the compilation of a header will bind any preprocessor conditionals or substitutions, PPH files must validate the macro environment against which they were compiled with the macro environment in which they were included. In particular, we must keep the set of identifiers used within a header within its PPH file so that we can ensure that an identifier also has no macro definition when that PPH file is included. The implementation streams GCC internal data structures to the PPH file. Because of the need to handle two PPH files including the same textual header, symbols in the two PPH files that represent the same C++ symbol must be merged into a single C++ symbol. The compiler walks the C++ data structures and identifies those symbols that may possibly be merged. These are streamed first with identifying information, so that upon read, the compiler can search for an earlier load of that same symbol. After these potentially mergeable symbols are streamed, the compiler streams the dependent internal data structures. PPH implementation status is measured against an internal Google application using a fast build mode. All the metrics referenced in this section correspond to the compilation of the main translation unit for that application. The initial performance measurements are a qualified success. We have halved effective parse time even with an implementation that has not been tuned. Of the remaining time, nearly half is attributed to hash table lookup for template specializations. That expense is not incurred in regular compilations, and is therefore almost certainly a bug. Furthermore, in PPH files, close to half of all pointers emitted are null, which means that we could save significant further time by simply not saving or restoring them. Overall, we suspect that with minimal effort, PPH parse time will be less than a quarter of regular parse time. We find that application headers are predominantly compatible with PPH, thus meeting our goal of requiring few source changes. However, system headers are both often incompatible and very heavily used. Current functionality measurements are less successful. We are currently able to reuse less than a fifth of the PPH files we create. Of the error messages emitted, three quarters are a single error. There are likely few root causes to that error, and a particularly likely root is the template specialization bug mentioned above. As a further example, the fourth most common error messages all come from a single built-in function in a widely used system header. The primary development concern is that we do not know how many root causes are shadowed by the current root causes. A significant number of implementation problems arise from the structure of GCC. GCC has a test on preprocessor state to avoid unnecessarily reading a header file. Unfortunately, this test is not isomorphic to “not multiply included”. In particular, if the guarding symbol is conditionally set, the header may be included multiple times. Such headers require a manual exception to work with our system. The parser updates symbols as it parses. At the end of the compilation, when it comes time to write out a PPH file, the data structures are circular. While it is possible to stream circular structures, breaking the circularity at different points can have different effects. In contrast, the C++ source files have already broken that circularity simply because, for the most part, the language requires the programmer to do so. The state necessary for parsing and some code generation is mixed into a single data structure. Furthermore, the parser often provides code generation information in the data structures as it is parsing. The code generation information is not essential to PPH files, but neither is it easily removed. The GCC compiler has received significant micro-optimizations towards the goal of making traditional compilation fast. Many of these optimizations interfere with the process of repurposing the compiler. In particular, tokens point to the symbols that they may reference. When the scope changes, the tokens are updated to point to different symbols. As a consequence, tokens are not immutable and streaming the tokens requires extra processing. The compiler has instances where its representation loses fidelity with C++. For example, on parsing a tagless struct, GCC creates a counter-based unique tag name. It then does a lookup to see if the tag has been defined before. Of course, it has not. Later, GCC pattern matches on the tag name to see if it is one of the names assigned to tagless structs, so that it can infer the struct is tagless. While all this divergence from fidelity works in a normal parse, it does not work with PPH. PPH merges the results of multiple files, all using the same initial counter sequence. Thus, lookups do find a prior definition. The problem is solvable with a different strategy of creating unique tags. However, the problem appeared, required debugging, required a workaround, and occupies space in the PPH file. Other problems arise from the structure of Google's build system, which is highly parallel. With multi-core systems available as commodity desktop systems, we believe that future build systems will be increasingly parallel. So, while Google's build system is unusual, it is relevant. The build system creates a graph of actions necessary to build a target. The introduction of PPH will create a deeper action graph, and in the limit, have twice as many nodes. These larger graphs will take longer to compute. Most of those nodes will already be complete, so we have every expectation that using the PPH files will more than pay for the increased graph computation. However, an edit that invalidates a PPH file near the base of the graph will create a deeper serial dependence in compilations, which extends compilation time when concurrency is essentially free. PPH, as well as many other approaches, requires that we save some form of state and that state needs to be exposed to the build system. This additional state generates additional work in the build system, which contributes to latency. The essential tradeoff in the build is increased effort in building a PPH file versus decreased effort in using a PPH file. If this additional build overhead is more expensive than the savings provided by the generated compilation state, the approach is a net loss. As yet we do not know the effect of PPH, or other approaches, on the build system. We likely will not know until we have a working system and can experiment. The current implementation approach requires manually changing the streaming code whenever the data structures change. Thus, PPH, in its present state, represents a burden to continued compiler development in GCC. The current approach has some fundamental implementation problems. These problems are independent of the compiler chosen for PPH implementation. The structure of system headers makes many of them unsuitable to PPH. While many of these can be wrapped or multiply included; doing so has the effect of replicating symbols in multiple PPH files. That replication costs both space and time for the very headers that are most often used. The replication requires that PPH be able to merge identical symbols. Being able to merge symbols costs roughly 1/4 to 1/3 of the PPH load time. The information necessary to merge symbols is slow to create and occupies a significant amount of PPH file space. More importantly, merging is the primary source of bugs in the implementation. Restructuring of PPH, due to the discovery of yet more information needed for merging, is common. The primary compile-time benefit of PPH is the ability of the compiler to avoid symbol lookup and type analysis required during header parsing. Unfortunately, PPH does not avoid creating the same number of symbols, along with all of the memory allocation and content recreation implied. In essence, PPH files contain as much information as the original headers, and that information takes time to load into the compiler data structures. The detailed performance characteristics that started the PPH project have changed in the meantime. While the changes are specific to our benchmark, we believe the trends are general to the industry. Combining the first four characteristics, the parser is now 60% of compilation time rather than 80%. As a consequence, maximum possible PPH speedup is now 2.5x rather than 5x. The compiler is now only one tool in a build. Static analysis tools may run in parallel with the compiler. Build times may be limited by other tools. Specifically, our builds now use Clang for C++ diagnostics, and this parallel tool has two effects. Our builds now do syntax checking with Clang in parallel with doing the regular compile with GCC. The build latency is the maximum of those two components, which means that making GCC faster than Clang will not improve latency over making it the same speed. Our maximum speedup without modifying Clang is now roughly 3x-4x. A major benefit of PPH is that the build system need only ship the PPH files, not header files from which they were built. However, with Clang syntax checking, we must ship headers through the build system, thus losing that potential performance gain. Finally, at the inception of PPH, large-scale source changes were unlikely to ever be implemented. However, we now have tools that help us to automate large-scale changes. The restriction on minimum source change seems less necessary. For this section, we use the term “package” to indicate something like a compiled header. A package could be a PPH file, a full module, or something else. There are several alternate approaches that might improve the effectiveness of a package feature. However, one must be careful when judging effectiveness to consider several criteria. Much of the problem with the current PPH implementation is merging. If we were to not support merging, the result would be something like PCH, but with the ability to chain one package off of the end of another. Such an approach would avoid the problem that one change invalidates the entire PCH file. So, packages would be more stable than PCH files. In our benchmark, uncompressed PPH files are 41% of the size of PCH files and compressed by 7:1 to 51% of compressed PCH files. PPH files would be even smaller in a tuned implementation and without the need to support merging. However, we would need more of them because each package would represent a portion of a full linear context, not just a local context. Aggregate file sizes are unknown. The generation of PPH files is 24% faster than PCH for our benchmark, and would be even faster without the need to support merging. However, reuse speed is slower by 31% to 57%. As a mitigating task, a chained package reuse would also require less time than PPH reuse. (E.g., macro validation is not needed.) The primary problem with this approach is that it would require source changes to our codebase to be effective. We would need a canonical order for commonly used headers. Some headers would need to be aggregated into a single header to avoid explosion of package files. This approach is most likely to achieve feature status in GCC in the short term, but deployment within Google will likely take longer than deployment of PPH. The reason is that the changes to the source base to exploit chained PCH are not trivial. The current implementation streams the data structures after the parser has completed their construction. Instead, we could stream the parser actions that create the data structures. Unlike in regular parsing, we would need extra code to accept but ignore duplicate definitions. With careful restructuring of GCC, these actions could be near an alternate pluggable implementation of the regular parser internal API. Doing so would at least reduce lag between functional modification and working streaming, and at best enable automatic streamer generation. The primary problem here would be in identifying those actions and building an API that encapsulates them. The primary problem with the current PPH implementation is that it needs to merge symbols. We can avoid that problem if we require each symbol to be defined in at most one package. Given the existing structure of system headers, such an approach would require defining and implementing a new set of system packages. Users would then be required to use these new packages in place of existing #includes. PPH essentially captures parser state. Any inline functions in a PPH file are not re-parsed on use, but they are compiled on each use. We can shift work into package compilation by representing inline functions in the optimizer's internal form. This shift is reasonable with GCC because its front end does not do inlining. Other compilers may require more care. One of the problems with the current approach is that including a PPH file entails including all of the PPH files that were used in its construction. We must do so because all types in the chain of PPH files are implicitly exported. If instead, the package exported only the packages interface, the each package would need to contain only enough information to compile and reuse the interface. Within the package, all non-exported types and variables would be lowered to the code generator level, with enough information to enable correct and optimizable code, but without the extra C++-level information. (Effectively packages would meet ABI constraints in their representation of non-exported symbols, but not API constraints.) Such an approach would avoid nested module reads and substantially reduce the bulk of information used. It would also enforce include-what-you-use. The problem needs a solution. The C++ header model is becoming a serious drag on productivity. Our free ride on sequential processor improvements is over, and we need a more scalable solution. All alternate approaches should be carefully considered, even if they require non-trivial changes to the source base. Automated source conversion changes compatibility. In the past, compatibility meant compiling the same code in the same way. With automated source code modification tools, compatibility means identifying an automatable transformation from old code to new code. Modules should not ignore the build system. The performance effects of detailed module semantics can have significant complexity impact on the build of large systems. Indeed, we are struggling now with the consequences of textual inclusion. PPH can deliver significant, but not revolutionary, compile-time improvements. We anticipate an overall doubling of compile-time performance. However, we are unlikely to get order-of-magnitude improvements. Export control will yield better performance. The primary limit to the compile-time performance of PPH is that it must load the transitive closure of symbols in a PPH file. By limiting the set of symbols exported from a module, the amount of information imported can be substantially reduced. Merging symbols is technically difficult. The problems are not theoretically difficult, but have proven to be so in practice. This difficulty will be reflected in slower implementations. Furthermore, our implementation problems have been largely the result of merging. At any one time, we have had few known bugs. However, fixing one bug has moved the frontier to yet another bug. It is difficult to anticipate when we will cross the threshold to general functionality. If we were not merging symbols, we believe we would have already deployed a successful PPH. One module per symbol will likely yield better systems. Given the merge performance issues and bugs discussed above, we believe that a module system will be more performant and more reliable if prohibits multiple definitions. System headers must be redefined as modules. Application headers are generally well-structured and their conversion to a module system will likely be not too painful. Unfortunately, current system headers are often highly tied to the textual inclusion model. Any attempt to reuse them unmodified in a module system will constitute a significant burden to both implementers and users.
http://www.open-std.org/jtc1/sc22/wg21/docs/papers/2012/n3426.html
CC-MAIN-2014-52
refinedweb
3,779
55.24
Hi All, I have Arduino UNO board and another board with IR Transmitter circuit on it. The IR Transmitter board is connect on PIN# 3 with +, D & GND pin. Simply I want to simulate Number 1, 2 & 3 pressed from DirecTV remote control using IR Transmitter. I used below code but it is not working for me: #include <IRremote.h> void setup() { pinMode(LED_BUILTIN, OUTPUT); Serial.begin(115200); // Just to know which program is running on my Arduino Serial.println(F("START " __FILE__ " from " __DATE__ "\r\nUsing library version " VERSION_IRREMOTE)); Serial.print(F("Ready to send IR signals at pin ")); Serial.println(IR_SEND_PIN); /* * The IR library setup. That's all! * The Output pin is board specific and fixed at IR_SEND_PIN. * see */ IrSender.begin(true); // Enable feedback LED, } /* * Set up the data to be sent. * For most protocols, the data is build up with a constant 8 (or 16 byte) address * and a variable 8 bit command. * There are exceptions like Sony and Denon, which have 5 bit address. */ uint16_t sAddress = 0x0102; uint8_t sCommand = 0x34; uint8_t sRepeats = 0; void loop() { /* * Print current send values */ Serial.println(); Serial.print(F("Send now: address=0x")); Serial.print(sAddress, HEX); Serial.print(F(" command=0x")); Serial.print(sCommand, HEX); Serial.print(F(" repeats=")); Serial.print(sRepeats); Serial.println(); Serial.println(F("Send NEC with 16 bit address")); // Results for the first loop to: Protocol=NEC Address=0x102 Command=0x34 Raw-Data=0xCB340102 (32 bits) IrSender.sendNEC(sAddress, sCommand, sRepeats); /* * If you cannot avoid to send a raw value directly like e.g. 0xCB340102 you must use sendNECRaw() */ // Serial.println(F("Send NECRaw 0xCB340102")); // IrSender.sendNECRaw(0xCB340102, sRepeats); /* * Increment send values * Also increment address just for demonstration, which normally makes no sense */ sAddress += 0x0101; sCommand += 0x11; sRepeats++; // clip repeats at 4 if (sRepeats > 4) { sRepeats = 4; } delay(5000); // delay must be greater than 5 ms (RECORD_GAP_MICROS), otherwise the receiver sees it as one long signal } If any of the forum member can guide me what sort of Command need to send to simulate Button #1, #2 & #3 pressed from the DirecTV Remote control using my IR Transmitter connected with Arduino UNO it would be really helpful. Thanks in advance!
https://forum.arduino.cc/t/simulate-tv-remote-button-press-using-ir-transmitter/696954
CC-MAIN-2022-40
refinedweb
364
50.23
Custom qualifiersArbi Sookazian Nov 20, 2009 12:29 AM from ref doc: @Entity public class User { private @NotNull @Length(min=3, max=25) @Id String username; private @NotNull @Length(min=6, max=20) String password; public String getUsername() { return username; } public void setUsername(String username) { this.username = username; } public String setPassword(String password) { this.password = password; } } @Qualifier @Retention(RUNTIME) @Target({TYPE, METHOD, PARAMETER, FIELD}) public @interface LoggedIn {} public class DocumentEditor { @Inject @LoggedIn User currentUser; public void save() { //do stuff } } So you're telling me that if I use that custom qualifier (@LoggedIn), then the CDI container will inject the currently logged in user? So what would it inject if I did not use @LoggedIn? Why/how does that work? So that's assuming that there is more than one User instance available to inject? And what scope is the injection occurring from (or is scoping a non-issue/irrelevant in CDI due to producer fields/methods)? [read the spec], I'm getting there... 1. Re: Custom qualifiersGavin King Nov 20, 2009 1:42 AM (in response to Arbi Sookazian) You missed the critical piece of code: @Produces @LoggedIn User getCurrentUser() { ... } 2. Re: Custom qualifiersArbi Sookazian Nov 20, 2009 1:46 AM (in response to Arbi Sookazian) So when the container goes to inject an instance (and they're not context variables like in Seam), it must find and use a producer method? So it's always a 1:1 ratio on injectee and producer??? If there's no producer then the injection fails or is null? 3. Re: Custom qualifiersGavin King Nov 20, 2009 1:53 AM (in response to Arbi Sookazian) No. Some beans are producer methods. Some beans are just classes. Some beans are neither. 4. Re: Custom qualifiersArbi Sookazian Nov 20, 2009 5:29 AM (in response to Arbi Sookazian) Ok so you can @Inject in CDI w/o a producer method. But the variable that is injected is originating from a specific context/scope or not? IIRC you stated that there are no context variables in CDI... 5. Re: Custom qualifiersNicklas Karlsson Nov 20, 2009 7:40 AM (in response to Arbi Sookazian) A bean only has one scope (@RequestScoped or whatever). It's in that context. Always. Since you can't outject it to another scope.
https://developer.jboss.org/message/656410?tstart=0
CC-MAIN-2019-35
refinedweb
381
63.9
After much hype, Google finally released TensorFlow 2.0 which is the latest version of Google's flagship deep learning platform. A lot of long-awaited features have been introduced in TensorFlow 2.0. This article very briefly covers how you can develop simple classification and regression models using TensorFlow 2.0. Classification with Tensorflow 2.0 If you have ever worked with Keras library, you are in for a treat. TensorFlow 2.0 now uses Keras API as its default library for training classification and regression models. Before TensorFlow 2.0, one of the major criticisms that the earlier versions of TensorFlow had to face stemmed from the complexity of model creation. Previously you need to stitch graphs, sessions and placeholders together in order to create even a simple logistic regression model. With TensorFlow 2.0, creating classification and regression models have become a piece of cake. So without further ado, let's develop a classification model with TensorFlow. The Dataset The dataset for the classification example can be downloaded freely from this link. Download the file in CSV format. If you open the downloaded CSV file, you will see that the file doesn't contain any headers. The detail of the columns is available at UCI machine learning repository. I will recommend that you read the dataset information in detail from the download link. I will briefly summarize the dataset in this section. The dataset basically consists of 7 columns: - price (the buying price of the car) - maint ( the maintenance cost) - doors (number of doors) - persons (the seating capacity) - lug_capacity (the luggage capacity) - safety (how safe is the car) - output (the condition of the car) Given the first 6 columns, the task is to predict the value for the 7th column i.e. the output. The output column can have one of the three values i.e. "unacc" (unacceptable), "acc" (acceptable), good, and very good. Importing Libraries Before we import the dataset into our application, we need to import the required libraries. import pandas as pd import numpy as np import tensorflow as tf import matplotlib.pyplot as plt %matplotlib inline import seaborn as sns sns.set(style="darkgrid") Before we proceed, I want you to make sure that you have the latest version of TensorFlow i.e. TensorFlow 2.0. You can check your TensorFlow version with the following command: print(tf.__version__) If you do not have TensorFlow 2.0 installed, you can upgrade to the latest version via the following command: $ pip install --upgrade tensorflow Importing the Dataset The following script imports the dataset. Change the path to your CSV data file according. cols = ['price', 'maint', 'doors', 'persons', 'lug_capacity', 'safety','output'] cars = pd.read_csv(r'/content/drive/My Drive/datasets/car_dataset.csv', names=cols, header=None) Since the CSV file doesn't contain column headers by default, we passed a list of column headers to the pd.read_csv() method. Let's now see the first 5 rows of the dataset via the head() method. cars.head() Output: You can see the 7 columns in the dataset. Data Analysis and Preprocessing Let's briefly analyze the dataset by plotting a pie chart that shows the distribution of the output. The following script increases the default plot size. plot_size = plt.rcParams["figure.figsize"] plot_size [0] = 8 plot_size [1] = 6 plt.rcParams["figure.figsize"] = plot_size And the following script plots the pie chart showing the output distribution. cars.output.value_counts().plot(kind='pie', autopct='%0.05f%%', colors=['lightblue', 'lightgreen', 'orange', 'pink'], explode=(0.05, 0.05, 0.05,0.05)) Output: The output shows that majority of cars (70%) are in unacceptable condition while 20% cars are in acceptable conditions. The ratio of cars in good and very good condition is very low. All the columns in our dataset are categorical. Deep learning is based on statistical algorithms and statistical algorithms work with numbers. Therefore, we need to convert the categorical information into numeric columns. There are various approaches to do that but one of the most common approach is one-hot encoding. In one-hot encoding, for each unique value in the categorical column, a new column is created. For the rows in the actual column where the unique value existed, a 1 is added to the corresponding row of the column created for that particular value. This might sound complex but the following example will make it clear. The following script converts categorical columns into numeric columns: price = pd.get_dummies(cars.price, prefix='price') maint = pd.get_dummies(cars.maint, prefix='maint') doors = pd.get_dummies(cars.doors, prefix='doors') persons = pd.get_dummies(cars.persons, prefix='persons') lug_capacity = pd.get_dummies(cars.lug_capacity, prefix='lug_capacity') safety = pd.get_dummies(cars.safety, prefix='safety') labels = pd.get_dummies(cars.output, prefix='condition') To create our feature set, we can merge the first six columns horizontally: X = pd.concat([price, maint, doors, persons, lug_capacity, safety] , axis=1) Let's see how our label column looks now: labels.head() Output: The label column is basically a one-hot encoded version of the output column that we had in our dataset. The output column had four unique values: unacc, acc, good and very good. In the one-hot encoded label dataset, you can see four columns, one for each of the unique values in the output column. You can see 1 in the column for the unique value that originally existed in that row. For instance, in the first five rows of the output column, the column value was unacc. In the labels column, you can see 1 in the first five rows of the condition_unacc column. Let's now convert our labels into a numpy array since deep learning models in TensorFlow accept numpy array as input. y = labels.values The final step before we can train our TensorFlow 2.0 classification model is to divide the dataset into training and test sets: from sklearn.model_selection import train_test_split X_train, X_test, y_train, y_test = train_test_split(X, y, test_size=0.20, random_state=42) Model Training To train the model, let's import the TensorFlow 2.0 classes. Execute the following script: from tensorflow.keras.layers import Input, Dense, Activation,Dropout from tensorflow.keras.models import Model As I said earlier, TensorFlow 2.0 uses the Keras API for training the model. In the script above we basically import Input, Dense, Activation, and Dropout classes from tensorflow.keras.layers module. Similarly, we also import the Model class from the tensorflow.keras.models module. The next step is to create our classification model: input_layer = Input(shape=(X.shape[1],)) dense_layer_1 = Dense(15, activation='relu')(input_layer) dense_layer_2 = Dense(10, activation='relu')(dense_layer_1) output = Dense(y.shape[1], activation='softmax')(dense_layer_2) model = Model(inputs=input_layer, outputs=output) model.compile(loss='categorical_crossentropy', optimizer='adam', metrics=['acc']) As can be seen from the script, the model contains three dense layers. The first two dense layers contain 15 and 10 nodes, respectively with relu activation function. The final dense layer contain 4 nodes ( y.shape[1] == 4) and softmax activation function since this is a classification task. The model is trained using categorical_crossentropy loss function and adam optimizer. The evaluation metric is accuracy. The following script shows the model summary: print(model.summary()) Output: Model: "model" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_1 (InputLayer) [(None, 21)] 0 _________________________________________________________________ dense (Dense) (None, 15) 330 _________________________________________________________________ dense_1 (Dense) (None, 10) 160 _________________________________________________________________ dense_2 (Dense) (None, 4) 44 ================================================================= Total params: 534 Trainable params: 534 Non-trainable params: 0 _________________________________________________________________ None Finally, to train the model execute the following script: history = model.fit(X_train, y_train, batch_size=8, epochs=50, verbose=1, validation_split=0.2) The model will be trained for 50 epochs but here for the sake of space, the result of only last 5 epochs is displayed: Epoch 45/50 1105/1105 [==============================] - 0s 219us/sample - loss: 0.0114 - acc: 1.0000 - val_loss: 0.0606 - val_acc: 0.9856 Epoch 46/50 1105/1105 [==============================] - 0s 212us/sample - loss: 0.0113 - acc: 1.0000 - val_loss: 0.0497 - val_acc: 0.9856 Epoch 47/50 1105/1105 [==============================] - 0s 219us/sample - loss: 0.0102 - acc: 1.0000 - val_loss: 0.0517 - val_acc: 0.9856 Epoch 48/50 1105/1105 [==============================] - 0s 218us/sample - loss: 0.0091 - acc: 1.0000 - val_loss: 0.0536 - val_acc: 0.9856 Epoch 49/50 1105/1105 [==============================] - 0s 213us/sample - loss: 0.0095 - acc: 1.0000 - val_loss: 0.0513 - val_acc: 0.9819 Epoch 50/50 1105/1105 [==============================] - 0s 209us/sample - loss: 0.0080 - acc: 1.0000 - val_loss: 0.0536 - val_acc: 0.9856 By the end of the 50th epoch, we have training accuracy of 100% while validation accuracy of 98.56%, which is impressive. Let's finally evaluate the performance of our classification model on the test set: score = model.evaluate(X_test, y_test, verbose=1) print("Test Score:", score[0]) print("Test Accuracy:", score[1]) Here is the output: WARNING:tensorflow:Falling back from v2 loop because of error: Failed to find data adapter that can handle input: <class 'pandas.core.frame.DataFrame'>, <class 'NoneType'> 346/346 [==============================] - 0s 55us/sample - loss: 0.0605 - acc: 0.9740 Test Score: 0.06045335989359314 Test Accuracy: 0.9739884. Regression with TensorFlow 2.0 In regression problem, the goal is to predict a continuous value. In this section, you will see how to solve a regression problem with TensorFlow 2.0 The Dataset The dataset for this problem can be downloaded freely from this link. Download the CSV file. The following script imports the dataset. Do not forget to change the path to your own CSV datafile. petrol_cons = pd.read_csv(r'/content/drive/My Drive/datasets/petrol_consumption.csv') Let's print the first five rows of the dataset via the head() function: petrol_cons.head() Output: You can see that there are five columns in the dataset. The regression model will be trained on the first four columns, i.e. Petrol_tax, Average_income, Paved_Highways, and Population_Driver_License(%). The value for the last column i.e. Petrol_Consumption will be predicted. As you can see that there is no discrete value for the output column, rather the predicted value can be any continuous value. Data Preprocessing In the data preprocessing step we will simply split the data into features and labels, followed by dividing the data into test and training sets. Finally the data will be normalized. For regression problems in general, and for regression problems with deep learning, it is highly recommended that you normalize your dataset. Finally, since all the columns are numeric, here we do not need to perform one-hot encoding of the columns. X = petrol_cons.iloc[:, 0:4].values y = petrol_cons.iloc[:, 4].values) In the above script, in the feature set X, the first four columns of the dataset are included. In the label set y, only the 5th column is included. Next, the data set is divided into training and test size via the train_test_split method of the sklearn.model_selection module. The value for the test_size attribute is 0.2 which means that the test set will contain 20% of the original data and the training set will consist of the remaining 80% of the original dataset. Finally, the StandardScaler class from the sklearn.preprocessing module is used to scale the dataset. Model Training The next step is to train our model. This is process is quite similar to training the classification. The only change will be in the loss function and the number of nodes in the output dense layer. Since now we are predicting a single continuous value, the output layer will only have 1 node. input_layer = Input(shape=(X.shape[1],)) dense_layer_1 = Dense(100, activation='relu')(input_layer) dense_layer_2 = Dense(50, activation='relu')(dense_layer_1) dense_layer_3 = Dense(25, activation='relu')(dense_layer_2) output = Dense(1)(dense_layer_3) model = Model(inputs=input_layer, outputs=output) model.compile(loss="mean_squared_error" , optimizer="adam", metrics=["mean_squared_error"]) Our model consists of four dense layers with 100, 50, 25, and 1 node, respectively. For regression problems, one of the most commonly used loss functions is mean_squared_error. The following script prints the summary of the model: Model: "model_2" _________________________________________________________________ Layer (type) Output Shape Param # ================================================================= input_4 (InputLayer) [(None, 4)] 0 _________________________________________________________________ dense_10 (Dense) (None, 100) 500 _________________________________________________________________ dense_11 (Dense) (None, 50) 5050 _________________________________________________________________ dense_12 (Dense) (None, 25) 1275 _________________________________________________________________ dense_13 (Dense) (None, 1) 26 ================================================================= Total params: 6,851 Trainable params: 6,851 Non-trainable params: 0 Finally, we can train the model with the following script: history = model.fit(X_train, y_train, batch_size=2, epochs=100, verbose=1, validation_split=0.2) Here is the result from the last 5 training epochs: Epoch 96/100 30/30 [==============================] - 0s 2ms/sample - loss: 510.3316 - mean_squared_error: 510.3317 - val_loss: 10383.5234 - val_mean_squared_error: 10383.5234 Epoch 97/100 30/30 [==============================] - 0s 2ms/sample - loss: 523.3454 - mean_squared_error: 523.3453 - val_loss: 10488.3036 - val_mean_squared_error: 10488.3037 Epoch 98/100 30/30 [==============================] - 0s 2ms/sample - loss: 514.8281 - mean_squared_error: 514.8281 - val_loss: 10379.5087 - val_mean_squared_error: 10379.5088 Epoch 99/100 30/30 [==============================] - 0s 2ms/sample - loss: 504.0919 - mean_squared_error: 504.0919 - val_loss: 10301.3304 - val_mean_squared_error: 10301.3311 Epoch 100/100 30/30 [==============================] - 0s 2ms/sample - loss: 532.7809 - mean_squared_error: 532.7809 - val_loss: 10325.1699 - val_mean_squared_error: 10325.1709 To evaluate the performance of a regression model on test set, one of the most commonly used metrics is root mean squared error. We can find mean squared error between the predicted and actual values via the mean_squared_error class of the sklearn.metrics module. We can then take square root of the resultant mean squared error. Look at the following script: from sklearn.metrics import mean_squared_error from math import sqrt pred_train = model.predict(X_train) print(np.sqrt(mean_squared_error(y_train,pred_train))) pred = model.predict(X_test) print(np.sqrt(mean_squared_error(y_test,pred))) The output shows the mean squared error for both the training and test sets. The results show that model performance is better on the training set since the root mean squared error value for training set is less. Our model is overfitting. The reason is obvious, we only had 48 records in the dataset. Try to train regression models with a larger dataset to get better results. 50.43599665058207 84.31961060849562 Conclusion TensorFlow 2.0 is the latest version of Google's TensorFlow library for deep learning. This article briefly covers how to create classification and regression models with TensorFlow 2.0. To have a hands on experience, I would suggest that you practice the examples given in this article and try to create simple regression and classification models with TensorFlow 2.0 using some other datasets.
https://stackabuse.com/tensorflow-2-0-solving-classification-and-regression-problems/
CC-MAIN-2021-21
refinedweb
2,402
60.31
Hide Forgot Spec URL: SRPM URL: Description:, ...) (not implemented yet) * use plugins (to export to html/gallery, to act like a httpserver, to export pictures to be mailed, ...) * work without database ! (just a xmlfile which can be rebuild from scratch) * handle a lot of photos (me : more than 20000) * upload photos to a flickr account * ... Upgrade to svn150 plus protection against impact of bug 232785. SPEC: SRPMS: New upstream version (my patches accepted upstream): SPEC: SRPMS: Your last posted SRPM URL does not exist. Sorry, forgot to update URLs: SPEC: SRPM: A couple of suggestions before we get started here. 1) I would remove all remnants of the svn directory structure immediately after unpacking the archive. That will relieve you from jumping through extra hoops like: find plugins -type f -not -regex '.*\.svn\/.*' 2) It would probably be easier to set the file modes and clean up the shebang and \r from files as the next step. I see you are setting the mode (sometimes redundantly) in multiple locations. 3) You makefile should not copy the .po or .pot files to the buildroot. That will also make these lines unnecessary: %{_datadir}/locale/po/fr/LC_MESSAGES/jbrout.po %{_datadir}/locale/po/jbrout.pot 4) Why no %doc: #%doc changelog.txt readme.txt SciTE.properties I hope I fixed it. New SRPM is on The locale files are still not being processes correctly. I believe the .po files are not needed at all. The .mo files should be picked up by %find_lang and installed in /usr/share/locale. Look at the files that are being packages: rpm -qpl jbrout-0.2.114.svn172-2.fc6.noarch.rpm I have to disagree with you: > %find_lang should be run in the %install section of your spec file, after > all of the files have been installed into the buildroot. Scrap the previous comment -- things are much more complicated than that. Jbrout apparently doesn't work with .mo files in the standard way, but it has to have them in the subdirectory po/ (both for the main program and plugins; try to run LANG=fr_FR jbrout with the *-2 package). I am not quite sure, whether it is a bug in jbrout, but anyway I would prefer to have functional program, so I have followed its lead. Hopefully there isn't anything in our guidelines saying that locales HAVE TO be in /usr/share/locale. Updated package has the same .spec file and SRPMS is s/same \.spec file/same URL of the .spec file/ I think the locale problem can be fixed up pretty easily, but I have found a more serious problem: This program requires python-elementtree and because of changes in python-elementtree, it will not run on F7+. cElementTree.so module in python-elementtree has been renamed to _elementtree.so module in python rpm (F7 python is 2.5) and to use _elementtree, some code change will be needed. $ ./jbrout.py Traceback (most recent call last): File "./jbrout.py", line 67, in <module> from db import JBrout,Buffer File "/home/bjohnson/package-review/jbrout/jbrout/db.py", line 16, in <module> from lxml.etree import Element,ElementTree ImportError: No module named lxml.etree What's your version of python-lxml package? It works for me with python-lxml-1.1.2-1.fc7 (and yes, rpm -q --changelog says that version 1.0.3-3 is "Rebuild for new Python". (In reply to comment #12) > What's your version of python-lxml package? It works for me with > python-lxml-1.1.2-1.fc7 (and yes, rpm -q --changelog says that version 1.0.3-3 > is "Rebuild for new Python". Sigh. Bitten by bug #244077. Ok, looking into the translation issues at the moment. For the translation files, you should be able to: 1) get rid of the obsoleted translation in the .po files (msgattrib --no-obsoletes) 2) msgcat the .po files together to a jbrout.po 3) create the binary catalog from jbrout.po to jbrout.mo 4) install the jbrout.mo file in /usr/share/locale/fr/LC_MESSAGES 5) edit (patch) jbrout.py and jplugins.py to change the GladeApp.bindtextdomain and createGetText calls to use /usr/share/locale rather than local directories.)? The working SRPMS without any language stuff is and its SPEC is in the same location. Messed up and unfinished attempt to fix SPEC file is on Do you have any idea how to fix it? I guess the easiest way would be to write some Python script to do all that stuff, but wasn't such script already written? (In reply to comment #15) >)? (In reply to comment #16) > I guess the easiest way would be to write some Python script to do all that > stuff, but wasn't such script already written? I would guess that the author of the program has a Makefile or something that processes his translation files. It might be worth pinging upstream so see if he can include it if such a program exists. I'm kinda schlepping my way through this too, so I don't think I can help anymore :( Bad attempt (doesn't work well) of fixing gettext stuff (plus a patch against screwed-by-Picassa IPTC metadata using libiptcdata) is available at SRPM: RPM: Spec: The solution in the last package is nonsense -- *.{po,mo} files should be really scattered in different directories, because that's the way the program and its plugins are written (using explicit locale dirs). There's nothing illegal in that, but we have to make %find_lang to work with this. Will ask on #fedora-devel and fix this..") (In reply to comment #20) >.") IMHO, it needs to be done. The developer docs also seem pretty clear on using %find_lang to process the translations. If you don't use %find_lang, any new translations added to the package will not be automatically added. If you wish, solicit opinions on the -devel mailing list and let's get some input. I don't have time to properly review this package anymore. Unfortunately, while the above specfile link works, the link to the src.rpm is 404. I grabbed instead; is that one OK? Unfortunately it doesn't build; desktop-file-install fails (sorry for horrible wrapping): + desktop-file-install --dir /var/tmp/jbrout-0.2.187-1.fc10-UhhP3w/usr/share/applications --vendor=fedora --add-category=X-Fedora --delete-original /var/tmp/jbrout-0.2.187-1.fc10-UhhP3w/usr/share/applications/jbrout.desktop /var/tmp/jbrout-0.2.187-1.fc10-UhhP3w/usr/share/applications/fedora-jbrout.desktop: error: value "0.2" for key "Version" in group "Desktop Entry" is not a known version Error on file "/var/tmp/jbrout-0.2.187-1.fc10-UhhP3w/usr/share/applications/jbrout.desktop": Failed to validate the created desktop file OK, there is new snapshot upstream, so I have created new .src.rpm (), which builds in koji I still don't know how to fix the problem with many .mo files, but otherwise this package should be all right (rpmlint is otherwise silent on both src.rpm and noarch.rpm). URL for .spec file is still the same Seems there's no longer any reason for the svn checkout instructions since you can directly fetch a tarball. There's no real point in mentioning the License in the Summary:, is there? Or what language the package is written in? These things really don't matter to someone who is interested in what the package does. Similarly for the %description; does any Fedora user particularly care whether the software works on Windows 2000? And who is "me" in the description? Yum or some package manager will display this to most users, and surely yum isn't going to be conversing about itself. rpmlint does indeed complain about the .mo files not being mentioned in %lang. You could list each of them separately in the %files list with %lang(foo) but at most that would allow someone to save a little space by excluding some specific lang files. Nice to have, but not absolutely necessary in my opinion, although it shouldn't be too terribly difficult if you wanted to do that. You should probably report this issue with the desktop file upstream: key "Categories" is a list and does not have a semicolon as trailing character, fixing Also, there's no need to use "--vendor=fedora" when installing your desktop file. Not sure if you noticed it, but there's no point to the %find_lang call, since this package insatlls nothing into /usr/share/locale. The %{name}.lang file is empty. You might as well just remove the %find_lang call and the -f bit from %files. * source files match upstream: b62b1bbd72400fd352deb8523a61e2b2da4f81c47f2118dd51488bee626fe77c jbrout-0.2.201.sources.tar.gz * package meets naming and versioning guidelines. * specfile is properly named, is cleanly written and uses macros consistently. X summary could use some work. X description could use some work. *: jbrout = 0.2.201-1.fc10 = /bin/sh /usr/bin/env fbida jhead pygtk2 >= 2.6 python >= 2.4 python-imaging python-lxml * %check is not present; no test suite upstream. I installed and ran this package; it seems to work OK. *. X desktop installed with --vendor=fedora. Updated package is available at and SPEC file is still at Summary and description look good; desktop file installed correctly. Looks fine to me. APPROVED Only took 16 months! GREAT!!! And thanks a lot for resolving for me the problem with %lang files. New Package CVS Request ======================= Package Name: jbrout Short Description: Photo manager, written in pyGTK Owners:mcepl Branches: F-8 F-9 InitialCC: Cvsextras Commits:yes cvs done. F-8 F-9 Rawhide Wov!
https://bugzilla.redhat.com/show_bug.cgi?id=230316
CC-MAIN-2019-18
refinedweb
1,617
67.65
To expand on Eric's comment: dfs.data.dir is the local filesystem directory (or directories) that a particular datanode uses to store its slice of the HDFS data blocks. so dfs.data.dir might be "/home/hadoop/data/" on some machine; a bunch of files with inscrutable names like blk_4546857325993894516 will be stored there. These "blk" files represent chunks of "real" complete user-accessible files in HDFS-proper. mapred.system.dir is a filesystem path like "/system/mapred" which is served by the HDFS, where files used by MapReduce appear. The purpose of the config file comment is to let you know that you're free to pick a path name like "/system/mapred" here even though your local Linux machine doesn't have a path named "/system"; this HDFS path is in a separate (HDFS-specific) namespace from "/home", "/etc", "/var" and the other various denizens of your local machine. - Aaron On Fri, Feb 12, 2010 at 6:23 AM, Eric Sammer <eric@lifeless.net> wrote: > On 2/12/10 8:40 AM, Edson Ramiro wrote: > > Hi > > > > Edson: > > An HDFS file system is a distributed global view controlled by the > namenode. If a file is "in HDFS" all clients and servers that are > pointed at the namenode will be able to see everything. This means that > you don't need to do anything special to export or reveal the > mapred.system.dir; that's what HDFS does. It's worth reading the HDFS > Architecture paper on the Hadoop site or the Google GFS paper for > details on how this all works and how it relates to map reduce. > > HTH. > -- > Eric Sammer > eric@lifeless.net > >
http://mail-archives.apache.org/mod_mbox/hadoop-common-user/201002.mbox/%3Cd6d7c4411002121714v744e0eb4ub0ca196bc83932fd@mail.gmail.com%3E
CC-MAIN-2017-47
refinedweb
276
69.11
How to use SOURCE_DATE_EPOCH S_D_E (for short) is is a standard that defines an environment variable SOURCE_DATE_EPOCH that distributions can set centrally, and have build tools consume this in order to produce reproducible output. Before implementing this, you should scan through our checklist to see if you can avoid implementing it. If you find that it's ideal for your use-case, please feel free to jump straight to our published specification. Contents - How to use SOURCE_DATE_EPOCH - Proposal - Setting the variable - Reading the variable - More detailed discussion - History and alternative proposals Proposal Please read our SOURCE_DATE_EPOCH specification for details. See Standard Environment Variables for more detailed discussion of the rationales behind this mechanism. Below we also have more detailed discussion about this specific variable, as well as documentation on history and alternative proposals. Setting the variable In Debian, this is automatically set to the same time as the latest entry in debian/changelog, i.e. the same as the output of dpkg-parsechangelog -SDate. For packages using debhelper, versions >= 9.20151004 (791823) exports this variable during builds, so you probably don't need to change anything. One exception is if your debian/rules needs this variable in non-debhelper parts, in which case you can try (3) or (4). For packages using CDBS, versions >= 0.4.131 (794241) exports this variable during builds, so no changes are needed. With dpkg >= 1.18.8 (824572) you can either include /usr/share/dpkg/pkg-info.mk or include /usr/share/dpkg/default.mk. If none of the above options are good (you should have a very good reason) then package maintainers may set and export this variable manually in debian/rules: export SOURCE_DATE_EPOCH ?= $(shell dpkg-parsechangelog -STimestamp)If you need/want to support dpkg versions earlier than 1.18.8: export SOURCE_DATE_EPOCH ?= $(shell dpkg-parsechangelog -SDate | date -f- +%s)If you need/want to support dpkg versions earlier than 1.17.0: export SOURCE_DATE_EPOCH ?= $(shell dpkg-parsechangelog | grep -Po '^Date: \K.*' | date -f- +%s)This snippet is believed to work on dpkg versions as far back as 2003. Reading the variable We are persuading upstream tools to support this directly. You may help by writing patches for these tools; please add links to the bug reports here so we know, and to act as an example resource for future patch writers. - Pending gettext, qt4-x11 cmake upstream - Complete docbook-utils (Debian >= 0.6.14-3.1, upstream TODO) doxygen (>= 1.8.12, Debian pending) debhelper (>= 9.20151004) epydoc (>= 3.0.1+dfsg-8, upstream pending) gcc (>= 7, Debian >= 5.3.1-17, Debian >= 6.1.1-1) ghostscript (Debian >= 9.16~dfsg-1, upstream unfortunately rejected due to additional constraints they have) groff (Debian >= 1.22.3-2, upstream pending) libxslt (>= 1.1.29, Debian >= 1.1.28-3) man2html (Debian >= 1.6g-8, needs forwarding) ocamldoc (>= 4.03.0, Debian >= 4.02.3-1) pydoctor (>= 0.5+git20151204) rpm upstream (>4.13 other relevant patches linked in there) sphinx (>= 1.4, Debian >= 1.3.1-3) texi2html (Debian >= 1.82+dfsg1-4, needs forwarding) texlive-bin (>= 2016.20160512.41045) txt2man (>= 1.5.7, Debian >= 1.5.6-4) mkdocs (>= 0.16, Debian pending) Or search in all Debian sources: Python import os import time import datetime build_date = datetime.datetime.utcfromtimestamp(int(os.environ.get('SOURCE_DATE_EPOCH', time.time()))) Bash / POSIX shell For GNU systems: BUILD_DATE="$(date --utc --date="@${SOURCE_DATE_EPOCH:-$(date +%s)}" +%Y-%m-%d)" If you need to also support BSD date as well: DATE_FMT="%Y-%m-%d" SOURCE_DATE_EPOCH="${SOURCE_DATE_EPOCH:-$(date +%s)}" BUILD_DATE=$(date -u -d "@$SOURCE_DATE_EPOCH" "+$DATE_FMT" 2>/dev/null || date -u -r "$SOURCE_DATE_EPOCH" "+$DATE_FMT" 2>/dev/null || date -u "+$DATE_FMT") Perl use POSIX qw(strftime); my $date = strftime("%Y-%m-%d", gmtime($ENV{SOURCE_DATE_EPOCH} || time)); Makefile DATE_FMT = %Y-%m-%d ifdef SOURCE_DATE_EPOCH BUILD_DATE ?= $(shell date -u -d "@$(SOURCE_DATE_EPOCH)" "+$(DATE_FMT)" 2>/dev/null || date -u -r "$(SOURCE_DATE_EPOCH)" "+$(DATE_FMT)" 2>/dev/null || date -u "+$(DATE_FMT)") else BUILD_DATE ?= $(shell date "+$(DATE_FMT)") endif The above will work with either GNU or BSD date, and fallback to ignore SOURCE_DATE_EPOCH if both fails. CMake STRING(TIMESTAMP BUILD_DATE "%Y-%m-%d" UTC) or on unpatched cmake if (DEFINED ENV{SOURCE_DATE_EPOCH}) execute_process( COMMAND "date" "-u" "-d" "@$ENV{SOURCE_DATE_EPOCH}" "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE) else () execute_process( COMMAND "date" "+%Y-%m-%d" OUTPUT_VARIABLE BUILD_DATE OUTPUT_STRIP_TRAILING_WHITESPACE) endif () The above will work only with GNU date. See POSIX shell example on how to support BSD date. C #include <errno.h> #include <limits.h> struct tm *build_time; time_t now;", strer); } now = epoch; } else { now = time(NULL); } build_time = gmtime(&now); C++ #include <sstream> #include <iostream> #include <cstdlib> #include <ctime> time_t now; char *source_date_epoch = std::getenv("SOURCE_DATE_EPOCH"); if (source_date_epoch) { std::istringstream iss(source_date_epoch); iss >> now; if (iss.fail() || !iss.eof()) { std::cerr << "Error: Cannot parse SOURCE_DATE_EPOCH as integer\n"; exit(27); } } else { now = std::time(NULL); } Go import ( "fmt" "os" "strconv" "time" ) [...] source_date_epoch := os.Getenv("SOURCE_DATE_EPOCH") var build_date string if source_date_epoch == "" { build_date = time.Now().UTC().Format(http.TimeFormat) } else { sde, err := strconv.ParseInt(source_date_epoch, 10, 64) if err != nil { panic(fmt.Sprintf("Invalid SOURCE_DATE_EPOCH: %s", err)) } build_date = time.Unix(sde, 0).UTC().Format(http.TimeFormat) } git repository to set SOURCE_DATE_EPOCH to the last modification of a git repository, in shell: SOURCE_DATE_EPOCH=$(git log -1 --pretty=%ct) PHP date('Y', getenv('SOURCE_DATE_EPOCH') ?: time()) Emacs-Lisp (current-time-string (when (getenv "SOURCE_DATE_EPOCH") (seconds-to-time (string-to-number (getenv "SOURCE_DATE_EPOCH")))))) Javascript / node.js var timestamp = new Date(process.env.SOURCE_DATE_EPOCH ? (process.env.SOURCE_DATE_EPOCH * 1000) : new Date().getTime()); // Alternatively, to ensure a fixed timezone: var now = new Date(); if (process.env.SOURCE_DATE_EPOCH) { now = new Date((process.env.SOURCE_DATE_EPOCH * 1000) + (now.getTimezoneOffset() * 60000)); } Ruby if ENV['SOURCE_DATE_EPOCH'].nil? now = Time.now else now = Time.at(ENV['SOURCE_DATE_EPOCH'].to_i).gmtime end Note that Ruby's Datetime.strftime is locale-independent by default. Last-resort using faketime As a last resort to be avoided where possible (e.g. if the upstream tool is too hard to patch, or too time-consuming for you right now to patch, or if they are being uncooperative or unresponsive), package maintainers may try something like the following: debian/strip-nondeterminism/a2x: # Depends: faketime # Eventually the upstream tool should support SOURCE_DATE_EPOCH internally. test -n "$SOURCE_DATE_EPOCH" || { echo >&2 "$0: SOURCE_DATE_EPOCH not set"; exit 255; } exec env NO_FAKE_STAT=1 faketime -f "$(TZ=UTC date -d "@$SOURCE_DATE_EPOCH" +'%Y-%m-%d %H:%M:%S')" /usr/bin/a2x "$@" debian/rules: export PATH := $(CURDIR)/debian/strip-nondeterminism:$(PATH) debian/control: Build-Depends: faketime But please be aware that this does not work out of the box with pbuilder on Debian 7 Wheezy, see #778462 against faketime and #700591 against pbuilder (fixed in Jessie, but not Wheezy). Adding an according hook to /etc/pbuilder/hook.d which mounts /run/shm inside the chroot should suffice as local workaround, though. TODO: document some other nicer options. Generally, all invocations of date(1) need to have a fixed TZ environment set. NOTE: faketime BREAKS builds on some archs, for example hurd. See #778462 for details. More detailed discussion Sometimes developers of build tools do not want to support SOURCE_DATE_EPOCH, or they will tweak the suggestion to something related but different. We really do think the best approach is to use SOURCE_DATE_EPOCH exactly as-is described above in our proposal, without any variation. Here we explain our reasoning versus the arguments we have encountered. (See Standard Environment Variables for general arguments.) "Lying about the time" / "violates language spec" This argument arises when the tool processes some input which contains a static instruction to the effect of "get_current_time()". The input has a specification that defines what this means. The tool executes this instruction, then embeds the result in the output. It is argued that SOURCE_DATE_EPOCH would break these semantics and violate the specification. In most cases, this argument places too much weight on the absoluteness of time. Regardless of what any specification says, the user can set their own system clock and achieve an effect similar to SOURCE_DATE_EPOCH. 1 It is not up to the tool to judge whether the user is lying with their system clock, and likewise, it is not up to the tool to judge whether SOURCE_DATE_EPOCH is a "lie" or not. For all intents and purposes, if the user has set SOURCE_DATE_EPOCH then they are taking a position that "this is the current time; please use this instead of whatever clock you normally use". Yes, the project developer wrote "get_current_time()" but I as the user, by setting SOURCE_DATE_EPOCH, am choosing to override this with my own idea of what time it is. Please execute the build as if the current time was SOURCE_DATE_EPOCH. FOSS software should generally prefer to respect end-users' wishes rather than developers' wishes. (And in practise, we haven't seen any instance where a project developer really really prefers "time of build" over "modtime of source".) In conclusion, the tool may choose to ignore SOURCE_DATE_EPOCH for other reasons, but to judge that this is a lie is to disrespect the user's wishes. Furthermore, choosing to support this is unlikely to actually violate any specifications, since they generally don't define "current". 2 Many tools allow the user to override the "current" date - e.g. -D__TIME__=xxx, \\year=yyy, etc. In these cases, it makes even less sense to ignore SOURCE_DATE_EPOCH for data integrity reasons - you already have a mechanism where the user can "lie" or "break the spec"; SOURCE_DATE_EPOCH would just be adding an extra mechanism that makes it easier to do this globally across all tools. If for some reason you're still conflicted on suddenly changing the meaning of your "now()" function and desire another switch other than SOURCE_DATE_EPOCH being set or not, the texlive project came up with the variable FORCE_SOURCE_DATE; when that environment variable is set to 1 cases that wouldn't normally obey SOURCE_DATE_EPOCH will do. We strongly discourage the usage of such variable; SOURCE_DATE_EPOCH is meant to be already a flag forcing a particular timestamp to be used. OTOH, one alternative we can agree with, that also avoids SOURCE_DATE_EPOCH, would be to translate the static instruction "get_current_time()" from the input format to an equivalent instruction in the output format, if the output format supports that. History and alternative proposals 1 and the surrounding messages describe the initial motivation behind this, including an evaluation of how different programming languages handle date formats. At present, we do not have a proposal that includes anything resembling a "time zone". Developing such a standard requires consideration of various issues: Intuitive and naive ways of handling human-readable dates, such as the POSIX date functions, are highly flawed and freely mix implicit not-well-defined calendars with absolute time. For example, they don't specify they mean the Gregorian calendar, and/or don't specify what to do with dates before when the Gregorian calendar was introduced, or use named time zones that require an up-to-date timezone database (e.g. with historical DST definitions) to parse properly. Since this is meant to be a universal standard that all tools and distributions can support, we need to keep things simple and precise, so that different groups of people cannot accidentally interpret it in different ways. So it is probably unwise to try to standardise anything that resembles a named time zone, since that is very very complex. One likely candidate would be something similar to the git internal timestamp format, see man git-commit: It is <unix timestamp> <time zone offset>, where <unix timestamp> is the number of seconds since the UNIX epoch. <time zone offset> is a positive or negative offset from UTC. For example CET (which is 2 hours ahead UTC) is +0200. We already have SOURCE_DATE_EPOCH so the time zone offset could be placed in SOURCE_DATE_TZOFFSET or something like that. But all of this needs further discussion. Other non-standard variables that we haven't yet agreed upon, use at your own risk: export SOURCE_DATE_TZOFFSET = $(shell dpkg-parsechangelog -SDate | tail -c6) export SOURCE_DATE_RFC2822 = $(shell dpkg-parsechangelog -SDate) export SOURCE_DATE_ISO8601 = $(shell python -c 'import time,email.utils,sys;t=email.utils.parsedate_tz(sys.argv[1]);\ print(time.strftime("%Y-%m-%dT%H:%M:%S",t[:-1])+"{0:+03d}{1:02d}".format(t[-1]/3600,t[-1]/60%60));' "$(SOURCE_DATE_RFC2822)") The ISO8601 code snippet is complex, in order to preserve the same timezone offset as in the RFC2822 form. If one is OK with stripping out this offset, i.e. forcing to UTC, then one can just use date -u instead. However, this then contains the same information as the unix timestamp, but the latter is generally easier to work with in nearly all programming languages. Footnotes: Setting the system clock is not enough for reliable reproducible builds - we need SOURCE_DATE_EPOCH for long-running build processes that take varying amounts of time. If the tool was run near the end of the process, then merely setting the system clock would not make timestamps here reproducible. (1) This does not take into account, if the specification needs to interoperate consistently with other programs in a strong cryptographic ledger protocol where time values must be consistent across multiple entities. However this scenario is unlikely to apply, in the context of build tools where SOURCE_DATE_EPOCH would be set. (2)
https://wiki.debian.org/ReproducibleBuilds/TimestampsProposal
CC-MAIN-2017-43
refinedweb
2,202
56.05
PSP Programming/General/Common Callback< PSP Programming Common CallbackEdit Before we begin programming for the PSP, we will start by creating a folder named “common” in our programming directory. This folder will contain several files which will often be used in our programs. We'll put these files here so that we don't constantly have to write the same code over and over again. callback.hEdit Now let's create a new file with the name "callback.h". This header file will declare some of the stuff needed so that we can get our program to run on the PSP. #ifndef COMMON_CALLBACK_H #define COMMON_CALLBACK_H int isRunning(); int setupExitCallback(); #endif The 'ifndef' is used to make sure that this file only gets imported once, otherwise an error will occur. Then it should be pretty self explanatory; we will have two functions which we will use: "isRunning()" to check if the user has requested to quit the program, and "setupCallbacks()" which will setup all the necessary things for your program to run on the PSP. callback.cEdit Now that we have the header definitions we can also create the source file: name it "callback.c". We'll start by including the file "pspkernel.h" which gives us access to several kernel methods. #include <pspkernel.h> Next we create a boolean. Executing the method "isRunning()" will tell us whether a request to exit the application was created by the user. We will use this function in our program so that we can clean up any leftover memory, and exit gracefully. static int exitRequest = 0; int isRunning() { return !exitRequest; } Now this is where the hard part comes in... the good news, is that you don't need to completely understand it! Essentially what it does is create a new thread, which will create an exit callback. The callback will then make "exitRequest" equal to true if the user presses the "home" and "exit" button on the PSP. See for yourself: #include <pspkernel.h> static int exitRequest = 0; int isRunning() { return !exitRequest; } int exitCallback(int arg1, int arg2, void *common) { exitRequest = 1; return 0; } int callbackThread(SceSize args, void *argp) { int callbackID; callbackID = sceKernelCreateCallback("Exit Callback", exitCallback, NULL); sceKernelRegisterExitCallback(callbackID); sceKernelSleepThreadCB(); return 0; } int setupExitCallback() { int threadID = 0; threadID = sceKernelCreateThread("Callback Update Thread", callbackThread, 0x11, 0xFA0, THREAD_ATTR_USER, 0); if(threadID >= 0) { sceKernelStartThread(threadID, 0, 0); } return threadID; } Don't worry if you don't completely understand it, that's why we created a separate file for it. It's not going to change, so all we have to do is include it. Now you can go into the next section, which will show you how to create a simple "Hello World!" program.
https://en.m.wikibooks.org/wiki/PSP_Programming/General/Common_Callback
CC-MAIN-2017-30
refinedweb
448
52.8
How do you do the same as this SQL in django? UPDATE table SET timestamp=NOW() WHERE ... Particularly I wish to set the datetime area using server's builtin function to obtain the system time in the server the database was running on and never time around the client machine. I understand you are able to execute the raw sql directly but I am searching for a far more portable solution since databases have different functions to get the present datetime. Edit: couple of people pointed out auto_now param. This updates the datetime on every modification while I wish to update datetime only on certain occasions. As j0ker stated, if you would like automatic update from the timestamp, make use of the auto_now option. E.g. date_modified = models.DateTimeField(auto_now=True). Or if you wish to get it done by hand, is not it an easy assignment with python datetime.now()? from datetime import datetime obj.date_modified = datetime.now() If you would like the datetime from the foreign server (i.e., not the main one hosting the Django application), you are going to need to peg it by hand for any datatime to make use of. You could utilize a SQL command like select now(); or something like that over SSH, like ssh user@host "date +%s". Perhaps you should have a look in to the documentation: Modelfields: DateField The choice 'auto_now' might be precisely what you are looking for. You may also utilize it using the DateTimeField. It updates the DateTime every time you are saving the model. So with this option looking for your DateTimeField it ought to be sufficent to retrieve an information-record and save it again to create time right.
http://codeblow.com/questions/django-set-datetimefield-to-server-s-current-time/
CC-MAIN-2019-51
refinedweb
285
62.58
C++ and Bazel This page contains resources that help you use Bazel with C++ projects. It links to a tutorial, build rules, and other information specific to building C++ projects with Bazel. Contents Working with Bazel The following resources will help you work with Bazel on C++ projects: Best practices In addition to general Bazel best practices, below are best practices specific to C++ projects. BUILD files Follow the guidelines below when creating your BUILD files: Each BUILD file should contain one cc_libraryrule target per compilation unit in the directory. We recommend that you granularize your C++ libraries as much as possible to maximize incrementality and parallelize the build. If there is a single source file in srcs, name the library the same as that C++ file’s name. This library should contain C++ file(s), any matching header file(s), and the library’s direct dependencies. For example: cc_library( name = "mylib", srcs = ["mylib.cc"], hdrs = ["mylib.h"], deps = [":lower-level-lib"] ) Use one cc_testrule target per cc_librarytarget in the file. Name the target [library-name]_testand the source file [library-name]_test.cc. For example, a test target for the myliblibrary target shown above would look like this: cc_test( name = "mylib_test", srcs = ["mylib_test.cc"], deps = [":mylib"] ) Include paths Follow these guidelines for include paths: Make all include paths relative to the workspace directory. Use quoted includes ( #include "foo/bar/baz.h") for non-system headers, not angle-brackets ( #include <foo/bar/baz.h>). Avoid using UNIX directory shortcuts, such as .(current directory) or ..(parent directory). For legacy or third_partycode that requires includes pointing outside the project repository, such as external repository includes requiring a prefix, use the include_prefixand strip_include_prefixarguments on the cc_libraryrule target.
https://docs.bazel.build/versions/0.17.1/bazel-and-cpp.html
CC-MAIN-2020-34
refinedweb
284
56.66
Analyzing? GitHub provides community tools maintainers can use to define community standards for their projects. For example, it’s easy to add a code of conduct to a repository. It’s also possible report offensive comments directly to GitHub. However, a code of conduct is only a set of words on a page. It’s only effective if you enforce it. And face it, enforcing it can be very time consuming. What if a bot could help? Now I’m not so naïve to think you can take the very human problem of enforcing community standards and just sprinkle a bit of Machine Learning on it and the problem goes away. Clippy taught me that. But perhaps the combination of machine learning and human judgement could make the problem more tractable. The Idea This was the idea I had in mind when I decided to explore some new technologies. I learn best by building something so I set out to add sentiment analysis to GitHub issue comments. Sentiment analysis (also known as opinion mining) is the use of computers to analyze text to try and determine whether a piece of writing is positive, negative, or neutral. It relies on multiple fields related to AI such as natural language processing, computational linguistics, machine learning, and wishful thinking. To make this work I need to do four things: - Drink some whiskey - Listen to and respond to GitHub issue comments. - Analyze the sentiment of the comment. - Update the comment with a note about the sentiment. The idea is this: when an issue receives a negative issue comment, I’m going to have my “SentimentBot” update the comment with a note to keep things positive. DISCLAIMER: I want to be very clear that I chose this behavior as a proof of concept. I don’t think it’d be a good idea on a real OSS project to have a bot automatically respond to negative sentiment. If I were doing this for real, I’d probably have it privately flag comments in some manner for follow-up. You’ll probably see me make this clarification again because people have short memories. The GitHub Listener Webhooks are a powerful mechanism to extend GitHub. There are three key steps to set up a webhook. - Set up an application that can receive an HTTP POST from github.com. - Register the application as a webhook on a repository. - Configure the repository events the webhook listens to in the repository settings page. That first step is a bit of a pain. I need to write an entire application and host it at a publicly available URL? Ugh! So 2015! All I really want to do is write a tiny bit of code to respond to a Webhook call. I don’t care how its hosted. Serverless architecture to the rescue! The “Serverless” nomenclature has been the source of a lot of snide comments and jokes. The name may lead one to believe we chucked the server and are hosting our code on gumption and hope. But it’s not like that. Of course there’s a server! You just don’t have to worry about it. You just write some code and the Serverless service handles hosting, scaling, etc. all for you. Azure Functions and AWS Lambda are the two most well known examples of Serverless services. I decided to play around with Azure Functions because they have specific support for GitHub Webhooks. GitHub Webhooks and Azure Functions go together like Bitters and Bourbon. Mmmm, I’ll be right back. Follow these instructions to set up an Azure Function inside of the Azure Portal that responds to a GitHub webhook in no time. The result is a method with a signature like this. public static async Task<object> Run( HttpRequestMessage req, TraceWriter log) { string jsonContent = await req.Content.ReadAsStringAsync(); dynamic data = JsonConvert.DeserializeObject(jsonContent); // Your code goes here return req.CreateResponse(HttpStatusCode.OK, new { body = "Your response" }); } The shape of the data is determined by the event type that the webhook subscribes to. For example, if you subscribe to issue comments like I did, the payload represented by data is the IssueCommentEvent. In my example, we use a dynamic type for ease and convenience (but at the risk of correctness). However, you can deserialize the response into a strongly typed class. The Octokit.net library provides such classes. For example, I could deserialize the request body to an instance of IssueCommentPayload. Analyzing Sentiment The next step is to write code to analyze sentiment. But how do I do that? A naïve approach would search for my favorite colorful words in the text. A more sophisticated approach is to use something like Microsoft’s Cognitive Services. They have a Text Analytics API you can use for analyzing sentiment. And of course, there’s a NuGet package for that. Install-Package Microsoft.Azure.CognitiveServices.Language I installed the package, wrote a bit of code, and had the sentiment analysis working in short order. The API returns a score between 0 and 1. Scores close to 0 are negative. Close to 1 are positive. static async Task<double?> AnalyzeSentiment(string comment) { ITextAnalyticsAPI client = new TextAnalyticsAPI(); client.AzureRegion = AzureRegions.Westcentralus; client.SubscriptionKey = "YOUR_SUBSCRIPTION_KEY"; return (await client.SentimentAsync( new MultiLanguageBatchInput( new List<MultiLanguageInput>() { new MultiLanguageInput("en", "0", comment), }) )).Documents.First().Score; } Updating the comment Now that all the sentiments are determined, let’s do something with that information. For the sake of this proof of concept, I will update overly negative comments with a little reminder to keep it positive. After all, we know how much humans enjoy being chided by a software robot. Again, I want to reiterate that I wouldn’t use this for a real repository. I’d probably just flag the comment for a human to follow-up. I will also update positive comments with a nice thank you for keeping it positive. Gotta reward the nice people from time to time. In order to update the comment, I’ll use Octokit.net! Once again, NuGet to the rescue. Install-Package octokit The code is pretty straightforward. We use Octokit to post an edit to a comment using the issue comment API. static async Task UpdateComment( long repositoryId, int commentId, string existingCommentBody, string sentimentMessage) { var client = new GitHubClient( new ProductHeaderValue("haack-test-bot", "0.1.0")); var personalAccessToken = "SECRET PERSONAL ACCESS TOKEN"; client.Credentials = new Credentials(personalAccessToken); await client.Issue.Comment.Update( repositoryId, commentId, $"{existingCommentBody}\n\n_Sentiment Bot Says: {sentimentMessage}_"); } Deployment It’s possible to build an Azure Function entirely in the Azure Portal via a web browser. But then you’re pasting code into a text box. I like to write code with my favorite editor. Fortunately, Azure Functions supports continuous deployment integration with GitHub. It’s quick and easy to set up. I set up my repo as my deployment source. Every time I merge a change into the master branch, my changes are deployed. Try it! The source code is available in my haacked-demos/azure-sentiment-analysis repository If you want to try out the end result, I created a test issue in the repository. I know you’re testing out a sentiment bot, but you can still be negative and civil to each other. Please abide by the code of conduct. Also, I don’t want to pay a lot of money for this demo, so it might fail in the future if my trial of the text analysis service runs out. Future Ideas My goal in this post is to show you how easy it is to build a GitHub Webhook using Azure Functions. I haven’t tried it with AWS Lambda. I hope it’s just as easy. If you try it, let me know how it goes! The possibilities here are legion. With this approach, you can build all sorts of extensions that make GitHub fit into your workflows. For example, you may want to flag first time issue commenters. Or you may want to run static analysis on PRs. All of that is easy to build! But before you get too wild with this, note that there are a lot of GitHub integrations out there that might already do what you need. For example, the Probot project has a showcase of interesting apps that range from managing stale issues to enforcing GPG signatures on pull requests. There’s even a sentiment bot in there! Probot apps are NodeJS apps that can respond to webhooks. I believe they require you host an application, but I haven’t tried to see if they’re easy to run in a Serverless environment yet. That could be fun to try. Resources - GitHub Webhooks Documentation - Create a GitHub Webhook triggered function in Azure - Continuous Deployment to Azure Functions from GitHub - Microsoft Cognitive Services Text Analytics API - Octokit.net documentation - The haacked-demos/azure-sentiment-analysis with my code 1 I admit, I have to look up the spelling of this word every time, but it’s so perfect in this context. 4 responses
https://haacked.com/archive/2018/01/27/analyze-github-issue-comment-sentiment/
CC-MAIN-2020-16
refinedweb
1,508
58.28
I used hook WITHOUT removing/deleting it post training. Now when I am trying to re-run the notebooks I am getting OOM error as soon as I start training my first epoch. Added .remove() in hooks now, but still not getting past the training. How should I free the CUDA memory? Tried resetting the runtime - which is not working! layers_ = flatten_model(learn.model) class Hook(): def __init__(self, m, f): self.hook = m.register_forward_hook(partial(f, self)) def remove(self): self.hook.remove() def __del__(self): self.remove() def append_stats(hook, mod, inp, outp): if not hasattr(hook,'stats'): hook.stats = ([],[],[]) means,stds, outs = hook.stats if mod.training: means.append(outp.data.mean()) stds .append(outp.data.std()) outs.append(outp) `
https://forums.fast.ai/t/oom-cuda-while-using-hooks-google-colab/46543
CC-MAIN-2022-21
refinedweb
123
54.39
Prepare the Bunnies' Escape You're awfully close to destroying the LAMBCHOP doomsday device and freeing Commander Lambda's bunny workers, but once they're free of the work duties the bunnies are going to need to escape Lambda's space station via the escape pods as quickly as possible. Unfortunately, the halls of the space station are a maze of corridors and dead ends that will be a deathtrap for the escaping bunnies. Fortunately, Commander Lambda has put you in charge of a remodeling project that will give you the opportunity to make things a little easier for the bunnies. Unfortunately (again), you can't just remove all obstacles between the bunnies and the escape pods - at most you can remove one wall per escape pod path, both to maintain structural integrity of the station and to avoid arousing Commander Lambda's suspicions. You have maps of parts of the space station, each starting at a work area exit and ending at the door to an escape pod. The map is represented as a matrix of 0s and 1s, where 0s are passable space and 1s are impassable walls. The door out of the station is at the top left (0,0) and the door into an escape pod is at the bottom right (w-1,h-1). Write a function solution(map) that generates the length of the shortest path from the station door to the escape pod, where you are allowed to remove one wall as part of your remodeling plans. The path length is the total number of nodes you pass through, counting both the entrance and exit nodes. The starting and ending positions are always passable (0). The map will always be solvable, though you may or may not need to remove a wall. The height and width of the map can be from 2 to 20. Moves can only be made in cardinal directions; no diagonal moves are allowed. Languages To provide a Python solution, edit solution.py To provide a Java solution, edit Solution.java Test cases Your code should pass the following test cases. Note that it may also be run against hidden test cases not shown here. -- Python cases -- Input: solution.solution([[0, 1, 1, 0], [0, 0, 0, 1], [1, 1, 0, 0], [1, 1, 1, 0]]) Output: 7 Input: solution.solution([[0, 0, 0, 0, 0, 0], [1, 1, 1, 1, 1, 0], [0, 0, 0, 0, 0, 0], [0, 1, 1, 1, 1, 1], [0, 1, 1, 1, 1, 1], [0, 0, 0, 0, 0, 0]]) Output: 11 from collections import deque directions = [(0, 1), (1, 0), (0, -1), (-1, 0)] def bfs(row, col, m): rows = len(m) cols = len(m[0]) arr = [] for _ in range(rows): arr.append([None] * cols) arr[row][col] = 1 queue = deque() queue.append((row, col)) while queue: r, c = queue.popleft() for dr, dc in directions: nr, nc = (r + dr, c + dc) if 0 <= nr < rows and 0 <= nc < cols and arr[nr][nc] is None: arr[nr][nc] = arr[r][c] + 1 if m[nr][nc] != 1: queue.append((nr, nc)) return arr def solution(m): rows = len(m) cols = len(m[0]) src = bfs(0, 0, m) dest = bfs(rows - 1, cols - 1, m) res = 20 * 20 + 1 for i in range(rows): for j in range(cols): if src[i][j] and dest[i][j]: res = min(res, src[i][j] + dest[i][j] - 1) if res == rows + cols - 1: return res return res Discussion (0)
https://practicaldev-herokuapp-com.global.ssl.fastly.net/itepsilon/foobar-prepare-the-bunnies-escape-2jdp
CC-MAIN-2021-43
refinedweb
589
65.86
Got it to work. Thanks. Type: Posts; User: JeremiahWalker Got it to work. Thanks. I declared the method and its associated variables static, but now I get this error: Rectangle.java:22: unreachable statement return perimeter; ^ 1 error I was able to get this to work. Thanks for your help. Doing some deeper study on classes and objects. The object here is to get the dimensions of a rectangle, and give the area and perimeter of the rectangle. the tester is giving me a compilation... Time3Test.java:9: package com.walker.jhtp.reucla does not exist import com.walker.jhtp.reucla.Time3;//import class Time 3 ^ Time3Test.java:16: cannot access Time3... I am doing an exercise on reusable classes, but I can't seem to get it to work right. Here is the code Time3.java //Jeremiah A.Walker /** Steps for Declaring a Reusable Class Before a class... THe bar chart should reflect the salary. I think I figured it out, but if you have some insight, I'd appreciate it. Thanks. Hi: So, in my pursuit of learning programming, I am writing a program that takes Sales Information, gives back the total, average and pay(commission is 9% of total sales + 200). I want to create... I'm working on a java assignment that requires me to draw a bullseye using Java. I think the code is straight, but it would draw anything--it just gives me a blank screen. Any help is appreciated... Some code examples. I think I will focus on more useful and practical code from now on. I'm pretty sure noone cares about number theory. Can you guys give me a little insight as to how to... My background is actually in IT, and in that field we don't really focus on programming. We are mostly responsible for implementing solutions. I want to learn programming to become more well... Is it possible to reach in to the primes array and grab primes[max] to be able to print the "nth" prime number Here is one using the Sieve of Eratosthenes. I found the algorithm on wikipedia. I'm going to translate it to python //Jeremiah A. Walker //Prime number generator //Java //Sieve of... good point. I actually wrote that program when I was first starting out in programming. This is a program to generate all prime numbers between 0 and a given number(y). Is it possible to "translate" this program to java? The assignment calls on me to do this in java and I see no need... Thanks a lot. I'll keep practicing Thanks a lot. I'll keep practicing Thanks and how would you write that? Hi. I'm still studying my programming and am looking for ways to keep my code more readable and less redundant. This is my latest exercise. It runs and executes the way I want it to, but I have a... Thanks for the suggestion, can you show me the code? I'm new to Java and I'm writing a sample code wherein a user inputs employee info (name, position and monthly salary--which also calculates annual salary by doing monsal * 12). My set constructors...
http://www.javaprogrammingforums.com/search.php?s=6e4d02730404ff5fe8c258472943424f&searchid=1473284
CC-MAIN-2018-09
refinedweb
532
77.64
Below you’ll find an example of a very simple client-server program in C. Basically the client connects to the server, the server sends the message “Hello World”, and the client prints the received message. Keep in mind that I am configuring the settings manually. If you want your code to be IPV4-IPV6 agnostic, IP agnostic and portable to different plataforms you can use the getaddrinfo() function, as explained in this tutorial. Second, I am not doing error checking on most function calls. You should implement those checks if you are going to use the code for a real project. Third, if you want more details about the functions or their arguments please check the man page of each one. Finally, to test the code you just need to run the server on a terminal and then run the client on a different terminal (or run the server as a background process and then run the client on the same terminal). Server Code /****************** SERVER CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){ int welcomeSocket, newSocket; char buffer[1024]; struct sockaddr_in serverAddr; struct sockaddr_storage serverStorage; socklen_t addr_size; /*---- Create the socket. The three arguments are: ----*/ /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */ welcomeS); /*---- Bind the address struct to the socket ----*/ bind(welcomeSocket, (struct sockaddr *) &serverAddr, sizeof(serverAddr)); /*---- Listen on the socket, with 5 max connection requests queued ----*/ if(listen(welcomeSocket,5)==0) printf("Listening\n"); else printf("Error\n"); /*---- Accept call creates a new socket for the incoming connection ----*/ addr_size = sizeof serverStorage; newSocket = accept(welcomeSocket, (struct sockaddr *) &serverStorage, &addr_size); /*---- Send message to the socket of the incoming connection ----*/ strcpy(buffer,"Hello World\n"); send(newSocket,buffer,13,0); return 0; } Client Code /****************** CLIENT CODE ****************/ #include <stdio.h> #include <sys/socket.h> #include <netinet/in.h> #include <string.h> int main(){ int clientSocket; char buffer[1024]; struct sockaddr_in serverAddr; socklen_t addr_size; /*---- Create the socket. The three arguments are: ----*/ /* 1) Internet domain 2) Stream socket 3) Default protocol (TCP in this case) */ clientS); /*---- Connect the socket to the server using the address struct ----*/ addr_size = sizeof serverAddr; connect(clientSocket, (struct sockaddr *) &serverAddr, addr_size); /*---- Read the message from the server into the buffer ----*/ recv(clientSocket, buffer, 1024, 0); /*---- Print the received message ----*/ printf("Data received: %s",buffer); return 0; } You might also like: Sockets Programming in C Using UDP Datagrams your program isot easy easy to understand also not executable . plz make some changes in program its working bro 🙂 how to run this code in ubuntu please send me the procedure commands for ubuntu: For compiling a code: gcc program_name.c -o any_name.out (hit enter) for running: ./any_name.out @Abrar Ahmad Thanks.. worked vi filename.c compile : cc -o filename filename.c run: ./filename go to terminal and type this gcc your program name Then compiled and output type ./a.out On ubuntu terminal compile server program as gcc server.c -o server compile client program as gcc client.c -o client and run: on one terminal ./server Listening on another terminal ./client Data received: Hello World I am getting this error * tcpserver.c:25:32: warning: implicit declaration of function ‘inet_addr’ [-Wimplicit-function-declaration] serverAddr.sin_addr.s_addr = inet_addr(“localhost”); * It works thanks hey can u help me with this ?? alert(“test”); lame wannabe hacker. leaces traces.. hehe thank you very much its not working very helpful for me to understand the client-server communication. how to run this code ? compile client.c using cc -o client client.c and also compile server using cc -o server server.c then open two terminal of the current working directory then simultaneously in client and server run the executables like ./client.c ./server.c You will get the output. Cheers Bijay First run server binary, then client binary. How to resolve Permission denied errors during execution of ./server.c and ./client.c? addsudo in front of cc or gcc add sudo in front of cc or gcc ./server not ./server.c How can I make it such that there are several server queuing to listen on the server.Thanks command all the terminals and run This was incredibly easy to understand and execute, thanks for the great example! How do I write a program in c based on tcp server/client? The client should update the server with its latest IPv6 address every time it changes its address. Yeah , Good stuff , its easy to understand and anyone can execute it who know ‘C’. This is great but I wish you had some better syntax highlighting, it’s hard to tell the comments from the code. thankyou so much bro it’s work 😀 hey plz tell how to get output fa this above server and client program what are all the arguments v need to pass nd where it should be pass how can i modify this codes such that the client sends an arithmetic operation for the server to perfom ? it is not executable….error at run time in server code change ur ip address and port number i want to run client server program in my boss linux how can i get my ip address to run these use gcc compiler to run this code e.g. gcc server.c -o any_name gcc server.c && ./any_name port_number portnumber can be 8080 or 8888 leave it running open another terminal gcc client.c -o any_name1 ./any_name localhost 8080 hope you know it now How to communicate back to client from server? Thanks you very much man !!! That really helped me to understand and fix my program !!! gcc -o gcc -o open two terminals First run the server binary using ./ in one terminal then in another terminal ./ I think you missed the header file for inet_addr(“IP address”); in your client and server program so it is showing below warning:: warning: implicit declaration of function ‘inet_addr’ [-Wimplicit-function-declaration] If you want to overcome that warning you have to add the header file::#include for both client and server,other than that it is very good client and server c program and very use full to understand the Using Sockets and TCP. thanking you that header file missed that is #include arpa/inet.h When I run the app in the IDE it runs perfectly, but after I built it and ran it in the terminal I get a segmentation fault. I ran it through gdb and got: Program received signal SIGSEGV, Segmentation fault. _IO_fgets (buf=0x6032b0 “”, n=6, fp=0x0) at iofgets.c:47 47 iofgets.c: No such file or directory. (gdb) bt #0 _IO_fgets (buf=0x6032b0 “”, n=6, fp=0x0) at iofgets.c:47 #1 0x00000000004013fa in get_conf () at cServer.c:119 #2 0x0000000000401606 in main () at cServer.c:191 I am not so good at understanding the debug output. Any help? Cheers, Ryan. user input message has to pass to one to other please help me with this thanks in advance Thanks , I modified the server to listen on multiple ports and to multiple clients. ———— Server ——————- import java.io.IOException; import java.net.InetSocketAddress; import java.net.Socket; import java.nio.ByteBuffer; import java.nio.channels.SelectionKey; import java.nio.channels.Selector; import java.nio.channels.ServerSocketChannel; import java.nio.channels.SocketChannel; import java.nio.channels.spi.AbstractSelectableChannel; import java.util.Iterator; import java.util.Set; public class SelectorExample { public static void main(String[] args) throws IOException, InterruptedException { // Get selector Selector selector = Selector.open(); System.out.println(“Selector open: ” + selector.isOpen()); // Get server socket channel and register with selector ServerSocketChannel server = ServerSocketChannel.open(); InetSocketAddress hostAddress = new InetSocketAddress(“localhost”, 5454); server.socket().bind(hostAddress); server.configureBlocking(false); server.register(selector, SelectionKey.OP_ACCEPT, “Server1”); ServerSocketChannel server2 = ServerSocketChannel.open(); InetSocketAddress hostAddress2 = new InetSocketAddress(“localhost”, 5455); server2.socket().bind(hostAddress2); server2.configureBlocking(false); server2.register(selector, SelectionKey.OP_ACCEPT, “Server2”); ServerSocketChannel server3 = ServerSocketChannel.open(); InetSocketAddress hostAddress3 = new InetSocketAddress(“localhost”, 5456); server3.socket().bind(hostAddress3); server3.configureBlocking(false); server3.register(selector, SelectionKey.OP_ACCEPT, “Server3”); for (;;) { System.out.println(“Waiting for select…”); int noOfKeys = selector.select(); System.out.println(“Number of selected keys: ” + noOfKeys); Set selectedKeys = selector.selectedKeys(); Iterator iter = selectedKeys.iterator(); while (iter.hasNext()) { SelectionKey ky = iter.next(); if (ky.isAcceptable()) { // Accept the new client connection String serv = (String) ky.attachment(); @SuppressWarnings(“resource”) SocketChannel client = null; if (serv.equals(“Server1”)) { client = server.accept(); } else if (serv.equals(“Server2”)) { client = server2.accept(); } else if (serv.equals(“Server3”)) { client = server3.accept(); } if (client != null) { client.configureBlocking(false); // Add the new connection to the selector client.register(selector, SelectionKey.OP_READ);); buffer.flip(); client.write(buffer); buffer.clear(); if (output.equals(“Bye.”)) { client.close(); System.out.println(“Client messages are complete; close.”); } } // end if (ky…) iter.remove(); } // end while loop } // end for loop } } —————- Client ——————— import java.nio.channels.SocketChannel; import java.nio.ByteBuffer; import java.io.IOException; import java.net.InetSocketAddress; public class SocketClientExample { public static void main (String [] args) throws IOException, InterruptedException { int port = Integer.parseInt(args[0]); InetSocketAddress hostAddress = new InetSocketAddress(“localhost”, port);); buffer.clear(); client.read(buffer); String response = new String( buffer.array()).trim(); System.out.println("Response :"+response); buffer.clear(); Thread.sleep(3000); } client.close(); } } How to run server on my ubuntu desktop and client on my beaglebone black? They are connected through ethernet. Kindly help. the #inlude , create me an error ur code need to add #include to compile Hi, Iam new to networking concepts, how can i run this code? like can i make one of my pc a server and the other pc as a client in eclipse ide? and I think in the both systems i need to have linux right? can u explain this line of code mainly the 2nd parameter. how to change ip address and port number use —- gcc Can i please get d algoritm of te above code? Please tell me why the this program error in header file:#include ????? in visual studio 2010 its not executing…. give me suggestions This is for linux sockets , windows has its own sockets. struct sockaddr_in has no member named in sin famaly why this error arise and how to solve it in client code storage size of serverAddr ist’t know is error faceing also say reason and how to solve it I’ve never seen so many stupid people in the same place, this tutorial assumes, 1) you know the difference between an executable and its source code, 2) you know what the living fck a compiler is… Hi Everyone, I am working on an embedded systems project using Beaglebbone Black Using the server / client programs in this forum i am trying to pass string from client to server the beaglebone is the server and logged on using Remote login through SSh and the pc has fedora and a normal terminal is being used to connect to the server How to connect the 2 systems running on different platforms caan anyone please help Why there’s no loops on the server code? How is that possible? I understand each individual function call, but I don’t get the overall picture. Oh, I got it. The code is bugging on my machine for some reason. I’m getting random characters on the client side, and the server keeps running. That’s why I was expecting some kind of loop on the server side, but sometimes the client prints “Hello world” as it should and the server program terminates. I want code of multiple servers with one client, is it possible to make ? Can anyone send me the code for that please sir..
https://www.programminglogic.com/example-of-client-server-program-in-c-using-sockets-and-tcp/?replytocom=417000
CC-MAIN-2020-16
refinedweb
1,924
58.89
Talk:Main Page From ReliCodia Revision as of 15:33, 10 help with code in the same way, since it's lame to put it in <pre>expr</pre>. I found one syntax hi-liter. It does not seem to support C++ and it has a "quirk" that you have to put the language in (e.g. <code><perl/>expr</code>) The extension is open source so I guess one could adapt it. Interestingly there seem to be some wikis that are superior out of the box, including a commercial one called "Confluence". Metaeducation 10:19, 16 January 2006 (Pacific Standard Time) Image Uploading I'm getting a message when I try to go to special pages and upload a file which says that image uploading is disabled... Metaeducation 10:22, 16 January 2006 (Pacific Standard Time) Subpages The Wikipedia does not approve of the use of subpages in "article space", while Wikibooks uses subpages heavily. I think it is disabled by default in the "main namespace". If you want to follow Wikibooks conventions (which probably makes sense here), you'll want to turn subpages on for the main namespace. There are features for doing relative paths of subpages, like a file system—which is certainly better for the page authors, since namespaces have to be retyped each time. However it does not appear that the page move feature moves "child" subpages when you move a parent. I find that a bit sad because that would be one of the big benefits. Seems the feature could be added relatively easily, though...? Metaeducation 18:15, 18 January 2006 (Pacific Standard Time) Logins with no password I noticed it was possible to create logins with no password. This account is an example of that. It seems to be true of other fresh MediaWiki installs... Nopasswordtest 18:27, 19 January 2006 (Pacific Standard Time) Car classification Car classification Body style .. some part of news : Crossover <a href=>Crossover</a> Convertible car <a href=>Convertible car</a> Compact car <a href=>Compact car</a> Classic car <a href=>Classic car</a> Small problem... Sorry for your time.... Why i can't see images on this resource? My Browser is: Opera. Thank you.
https://www.relisoft.com/wiki/index.php?title=Talk:Main_Page&diff=1818&oldid=1817
CC-MAIN-2018-09
refinedweb
368
63.39
Key Takeaways - Vue.js works well for the teams that have to rewrite old codebases one step at a time. - Vue CLI is the tooling for the Vue ecosystem and ensures that the various build tools work well together. - Axios is a standard library for making HTTP requests. - Bulma is a UI framework that works without dependencies. - Cloudinary is a tool used for smart image manipulation. - Amazon S3 (Amazon Simple Storage Solution) service is a solid choice for hosting simple web applications. TL;DR In this rather long tutorial, you'll learn how to use Vue CLI to build a Vue.js 2 application for searching and displaying Giphy images, and then manipulating/transforming them by using the Cloudinary API. Also, you'll learn how to deploy this application to AWS. __ We’ll be using Vue.js 2, which will be referred to as Vue.js in the rest of this post. Introduction Due to Vue's progressive and flexible nature, it's ideally suited for teams that have to rewrite old codebases one step at a time. If you want to check out some detailed comparisons between popular frontend frameworks, here are three great posts: - If we chose our JavaScript Framework like we chose our music… - Angular vs. React vs. Vue: A 2017 comparison - Vue.js vs. React, Angular, AngularJS, Ember, Knockout, Polymer, Riot I tend to answer general 'framework war' kind of questions in the following way: - Stop with the ‘analysis paralysis’ discussion. - Do your research, pick a framework—any framework—that the community is using, use it, and see how far it gets you. - It isn’t worthwhile to discuss X being slow or Y being better until you try it for your specific use case and preference. In this post, we'll use Vue.js and Cloudinary to apply some image manipulation techniques to the images that we'll fetch using the Giphy API in the demo application that we'll build. In the end, we'll use AWS to host the application. This is a hands-on from start to finish tutorial with all steps outlined. Demo app You can fork the complete source code on GitHub, or you can see the finished app in action. Prerequisites Make sure that you have the following tools installed: - Node.js - step by step guide for both Windows and Mac - Git - see this getting started tutorial Vue CLI As detailed in the Vue CLI README:. To install vue-cli, run: npm install -g @vue/cli To confirm that the installation ran successfully, run: vue --help __ For reference, the version of the CLI ( vue --version) used in this tutorial is 3.0.0-rc.3. Starting a new app with Vue CLI We'll call our app image-search-manipulator. Let's start a new app using vue-cli: vue create image-search-manipulator After this command finishes, let's cd into the project and run it: cd image-search-manipulator npm run dev You should get a console log similar to: DONE Compiled successfully in 7859ms Your application is running here: You should see the following page in your browser if you visit this link:. Folder structure Now, let's open this project in the editor of your choice (I'm using Visual Studio Code), and you should see something like this: Here we'll only focus on the src folder. The contents of that folder should be something like this: Adding content If you search for the string Welcome to Your Vue.js App, you'll see the string is within the HelloWorld.vue file. A *.vue file is a custom file format that uses HTML-like syntax to describe a Vue component. This file contains the following (... is used for brevity in the listing below): <template> <div class="hello"> <h1>{{ msg }}</h1> <h2>Essential Links</h2> <ul> ... </ul> </div> </template> <script> export default { name: 'HelloWorld',> Without knowing anything about Vue.js, we can see where we would change the Welcome to Your Vue.js App text. So, let's change that to Welcome to Image Search Manipulator. While you do that, also remove the contents of the style tag, as we don’t need it here. Adding input and a button Our basic application should have one input field and one button. To do this, add the following code to the HelloWorld.vue file in the template: <input name="search"> <button>Search</button> The template element of HelloWorld.vue should look like this now: <template> <div class="hello"> <h1>{{ msg }}</h1> <input name="search"> <button>Search</button> </div> </template> Actions Having a simple search input field and a button does not do much on their own. We want to click the button, and we want to output something to the console just to verify that the button is working correctly. This is how we define a function that will handle the button click in Vue: < button @Search</button> Vue applications often contain an equivalent alternative shorthand syntax: <button v-on:Search</button> Within the browser's developer tools, you'll observe an error such as: webpack-internal:///./node_modules/vue/dist/vue.esm.js:592 [Vue warn]: Property or method "performSearch" is not defined on the instance but referenced during render. Make sure that this property is reactive, either in the data option or for class-based components, by initializing the property. See. found in ---> <HelloWorld> at src/components/HelloWorld.vue <App> at src/App.vue <Root> This error occurs because we haven't defined the performSearch function. In the HelloWorld.vue file, add the following function definition inside the script tag, methods object property: <script> export default { name: "HelloWorld", data() { return { msg: "Welcome to Image Search Manipulator" }; }, methods: { performSearch: function() { console.log("clicked"); } } }; </script> We’ve now defined the performSearch function, which doesn't accept any parameters and has no return value. Taking input To print the string that was typed in the input field to the console, we first need to add a new attribute to the input field: <input name="search" v- The v-model instructs Vue.js to bind the input to the new searchTerm variable, such that whenever the input text updates, the value of searchTerm also gets updated.You can learn more about v-model and other form input bindings in the Vue documentation. Finally, change the performSearch function in order to log the value to the console: performSearch: function() { console.log(this.searchTerm); } Giphy search API With our example application, we now want to connect our search fields to an API call to return images. Giphy provides a search API. We need to determine the request parameters needed to search Giphy's database. If we open the search API link, we determine the format of the service: In the next section, we'll cover retrieving this data from within our app. Vue.js HTTP requests There are several ways to send HTTP requests in Vue.js. For additional options, check out this post about making AJAX calls in Vue.js. In this tutorial, we’ll use Axios, a popular JavaScript library for making HTTP requests. It's an HTTP client that makes use of the modern Promises API by default (instead of JavaScript callbacks) and runs on both the client and the server (Node.js). One feature that it has over the native .fetch() function is that it performs automatic transforms of JSON data. In your Terminal/Command prompt enter the following command to install Axios via npm: npm install axios --save Import Axios into the HelloWorld.vue file just after the opening script tag: import axios from "axios"; The performSearch function should now look like this: const link = ""; const apiLink = link + this.searchTerm; axios .get(apiLink) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); For reference, the contents of the HelloWorld.vue file should now be: <template> <div class="hello"> <h1>{{ msg }}</h1> <input name="search" v- <button @Search</button> </div> </template> <script> import axios from "axios"; export default { name: "HelloWorld", data() { return { msg: "Welcome to Image Search Manipulator" }; }, methods: { performSearch: function() { const link = ""; var apiLink = link + this.searchTerm; axios .get(apiLink) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); } } }; </script> __ When you're testing, you may also want to limit the number of images that you get from Giphy. To do that, pass limit=5 in the link like this: Now, if you run the app, enter something in the search box, and click the search button, you'll see something like this in your console log: The response object is returned, and in its data property there are 25 objects, which hold information about the images that we want to show in our app. To show an image, we need to drill down on the object images, then fixed_height_still, and finally on the url property. Also, we don't want to just show one image but all of the images. We'll use the v-for directive for that: <img v- The v-for directive is used to render a list of items based on an array and it requires a special syntax in the form of item in items, where items is the source data array and item is an alias for the array element being iterated on. For reference, here's the full listing of the HelloWorld.vue file: <template> <div class="hello"> <h1>{{ msg }}</h1> <input name="search" v- <button @Search</button> <div> <img v- </div> </div> </template> <script> import axios from "axios"; export default { name: "HelloWorld", data() { return { msg: "Welcome to Image Search Manipulator", searchTerm: "dogs", images: [] }; }, methods: { performSearch: function() { const link = ""; var apiLink = link + this.searchTerm; axios .get(apiLink) .then(response => { this.images = response.data.data; }) .catch(error => { console.log(error); }); } } }; </script> At this point, if we take a look at the app and search for 'coding', we'll get this: Making the app look pretty with Bulma Even though our example application functions as expected, the results do not look great. Bulma is an open source CSS framework based on Flexbox. Bulma is similar to Bootstrap with fewer interdependencies, and is just pure CSS without adding JavaScript. First, let's install Bulma: yarn add bulma if you're using Yarn, or npm install bulma if you're using NPM. Add bulma to the App.vue file, just after the import HelloWorld from "./components/HelloWorld"; line, like this: import "../node_modules/bulma/css/bulma.css"; Here's the template from the HelloWorld.vue file after adding Bulma classes to it: > </template> Here's a recap of what we did: - Added the class containerto the first div tag - Added the class titleto the h1tag - Added the class inputto the inputtag - Added the following classes to the button: button is-primary is-large For demonstration purposes, the myContent class was added like this: .myContent { padding-top: 20px; } And a bit of padding was added around the img tags: img { padding: 5px; } The following classes were added to the HelloWorld.vue file like this: <style> .myContent { padding-top: 20px; } img { padding: 5px; } </style> With these few quick changes, we now have a better-looking app: Bulma has many options without the overhead typical of larger CSS frameworks. Image manipulation We’ll now use a few techniques to manipulate the images. Cloudinary is a service offering many image manipulation options. After you create a Cloudinary account, you need to install Cloudinary: npm install cloudinary-core --save For reference, here's the full source code listing and a summary of changes: - Added new div <div class="myContent" v-</div>. Because the manipulatedImagesvariable will contain HTML, we need to use the v-htmldirective to show it in the template as such, and not as a string. You can learn more about the v-htmldirective in the Vue documentation. - Imported Cloudinary import cloudinary from "cloudinary-core"; - Called Cloudinary on each image returned from the Giphy API (starts with const cloudinaryImage = cl):</div> </div> </template> <script> import axios from "axios"; import cloudinary from "cloudinary-core"; export default { name: "HelloWorld", data() { return { msg: "Welcome to Image Search Manipulator", searchTerm: "dogs", images: [], manipulatedImages: "" }; }, methods: { performSearch: function() { var link = ""; const apiLink = link + this.searchTerm; const cl = new cloudinary.Cloudinary({ cloud_name: "nikola" }); axios .get(apiLink) .then(response => { this.images = response.data.data; this.images.forEach(image => { const cloudinaryImage = cl .imageTag(image.images.fixed_height_still.url, { width: 150, height: 150 }) .toHtml(); this.manipulatedImages += cloudinaryImage; }); }) .catch(error => { console.log(error); }); } } }; </script> <style> .myContent { padding-top: 20px; } img { padding: 5px; } </style> Deploying to AWS S3 We're going to complete this tutorial by publishing our app on Amazon S3 (Amazon Simple Storage Solution). First, login (or create an AWS account) to the AWS Console and search for S3: Familiarize yourself with the interface and create a new AWS S3 bucket. Buckets are places where we may add files. Make sure that, when you create the bucket, you select the Grant public read access to this bucket setting as bucket contents are private by default: Finally, go into your S3 bucket and enable static website hosting (enter index.html as suggested in the Index document field): Build it Run npm run build to build a production version of your app. All production-ready files are going to be placed in the dist folder. If you get a blank page after you upload the contents of the dist folder to the AWS bucket and visit the website, then check out the solution which basically states that you need to remove the / from the assetsPublicPath in config/index.js: If you encounter the blank page issue, perform the step above and repeat the npm run build command. Upload Upload the entire content of the dist directory to the S3 bucket. This can be done using a simple drag and drop. Make sure you set permissions for the files so that they are globally read accessible: That's all there is to it! You may view my version of the app created in this tutorial. Backup An important tip to finish up the tutorial is to backup your work. Several options are available for backing up apps on AWS, including the AWS native solution, and other, third-party solutions that offer added features such as zero downtime. These might not be required for your basic app, but are worth looking into for larger-scale use cases. It all depends on your stack—but there are solutions for backing on any stack. For example, on the Azure stack, you could use Azure Backup. Conclusion In this tutorial, we learned how to get started with using Vue.js by building an application for searching images via Giphy's API. We prettified our app with the Bulma CSS framework. Then we transformed the images using Cloudinary. Finally, we deployed our app to AWS. Please leave any comments and feedback in the discussion section below and thank you for reading! About the Author Gilad David Maayan is a technology writer who has worked with over 150 technology companies including SAP, Oracle, Zend, CheckPoint and Ixia, producing technical and thought leadership content that elucidates technical solutions for developers and IT leadership. Community comments
https://www.infoq.com/articles/vue-getting-started-aws-bulma?utm_campaign=infoq_content&amp;utm_source=infoq&amp;utm_medium=feed&amp;utm_term=global
CC-MAIN-2019-18
refinedweb
2,522
61.26
The for loop given above prints a line of fifty dashes followed by a newline. The for loop uses i as the loop variable whose initial and final values are 0 and 49, respectively (note the < operator in i < 50). The update expression increments the value of i by 1. Thus, the loop variable assumes values as 0, 1, 2, ..., 49. For each value of i, the printf statement contained within the for loop prints a dash. Finally, the printf statement after the for loop prints a newline character to move the cursor to the next line. #include <stdio.h> void main() { int i; clrscr(); printf("Print a line of dashes :\n"); for (i = 0; i < 50; i++) { printf("-"); }
http://ecomputernotes.com/what-is-c/control-structures/print-a-line-of-dashes
CC-MAIN-2018-47
refinedweb
119
79.9
Opened 2 years ago Last modified 3 months ago #26318 new Bug Unexpected / duplicated queries on nested Prefetch queryset with repeated model Description We discovered an issue in django.db.models.query.Prefetch logic that results in duplicate queries made when the leaves of certain prefetch trees are accessed. With these models: from django.db import models class Publisher(models.Model): name = models.CharField(max_length=128) class Author(models.Model): name = models.CharField(max_length=128) publishers = models.ManyToManyField('Publisher', related_name='authors') class Book(models.Model): name = models.CharField(max_length=128) publisher = models.ForeignKey('Publisher', related_name='books') The following test fails: from django.db.models.query import Prefetch from django.test import TestCase from .models import Author, Book, Publisher def flatten(ls): return list([i for s in ls for i in s]) class PrefetchTestCase(TestCase): def setUp(self): publisher = Publisher.objects.create(name='Publisher0') Book.objects.create(name='Book0', publisher=publisher) author = Author.objects.create(name='Author0') author.publishers.add(publisher) def test_prefetch_nested(self): publishers = Publisher.objects.prefetch_related( Prefetch( 'books', Book.objects.all().prefetch_related( Prefetch( 'publisher', Publisher.objects.all().prefetch_related('authors') ) ) ) ) with self.assertNumQueries(4): publishers = list(publishers) with self.assertNumQueries(0): books = flatten([p.books.all() for p in publishers]) with self.assertNumQueries(0): publishers = [b.publisher for b in books] with self.assertNumQueries(0): authors = flatten([p.authors.all() for p in publishers]) For more details (comments, queries executed) and an analogous green test-case that uses the flat prefetch form to prefetch the same tree, see the attached test package. To run the tests: tar -zxvf prefetch-bug-test.tar.gz cd prefetch-bug-test make test This issue seemed very similar to, but unfortunately the patch for that ticket () did not fix this problem. Tested in Django 1.8, 1.9, and master. Attachments (2) Change History (5) Changed 2 years ago by comment:1 Changed 2 years ago by comment:2 Changed 2 years ago by I just ran into this as well, but without recursion. i.e. (with apologies for the implied structure) users = User.objects.prefetch_related( Prefetch( 'person', queryset=Person.objects.prefetch_related( 'books', ), ), ) would generate 4 queries instead of three (because the books are duplicated). To be clear, this is a trimmed down version of the actual query I'm trying to construct. I haven't tested it (and I don't know whether I'll be able to any time soon.) Someone should try tweaking the test case to not use recursion, is all I'm saying. comment:3 Changed 3 months ago by I've run into it as well. Consider model M1, having many-to-many relationship to M3 via M2. And M3, having one-to-many relationship to M4: M1 <- M2 -> M3 <- M4 And the following statement, which is supposed to fetch all models: m1s = M1.objects.all() \ .prefetch_related( Prefetch('m2s', queryset=M2.objects.prefetch_related('m3__m4s')) ) This statement results in two calls to prefetch_related_objects. One for M1's, and the nested one for M2's. The nested one does one prefetch lookup m3__m4s. The outer one does two. One is m2s, and the second one is m2s__m3__m4s. Since inner lookups get passed to the outer prefetch_related_objects calls. Now then, reverse many-to-one descriptors (which are used to access M4's from M3's) don't have get_prefetch_queryset method. So models are cached in the instances. The thing is in our case cache_name is m4, but get_prefetcher (or basically prefetch_related_objects) expects to see m4s there. As a result, both outer and inner prefetch_related_objects calls retrieve M4's from database. It can be overcome by moving nested lookup to the upper level: m1s = M1.objects.all().prefetch_related('m2s', 'm2s__m3__m4s') Not sure if that is possible in each and every case. I've attached nested_prefetch_create_app.sh script, that creates an app in nested_prefetch dir, that simplifies reproducing the case. After running the script: $ cd nested_prefetch/nested_prefetch $ . ../bin/activate $ ./manage.py migrate a1 zero && ./manage.py migrate a1 && python 1.py Changed 3 months ago by creates an app in nested_prefetch dir to easily reproduce the issue Managed to reproduce against master. I suppose the algorithm gets confused because the Publishermodel has to be prefetched twice.
https://code.djangoproject.com/ticket/26318
CC-MAIN-2018-30
refinedweb
694
53.68
Re: Unimpressed by HD-DVD - From: "Smarty" <nobody@xxxxxxxxxx> - Date: Wed, 4 Apr 2007 22:38:14 -0400 I should have added one more fact. The disks you burn are normal 4.7 GB DVD-Rs using a cheap standard burner. They hold about 23 minutes of HD content for a single layer disk, and twice that for a dual layer disk. The Toshiba plays them just fine. Ulead MovieFactory 6+ knows how to burn red laser 4.7GB standard DVD-R blanks in an HD DVD format so all you do is capture the HC3 content, edit and author the menus, chapters, etc. insert a disk and burn it. BTW I also use Vegas 7 to do editing and you can use Vegas 7 to render the HC3 content into an HDV format mpeg2 file using the HDV 1080 template and import the edited video into MovieFactory 6+ if you would prefer to do more elaborate editing. Smarty "Sam Spade" <sam@xxxxxxxxxxxx> wrote in message news:xtWQh.79910$JN6.43607@xxxxxxxxxxxxxxx I have the latest version of Sony's Vega, so capturing and editing is not my problem. (I also have the HDR-HC3). But, I still don't understand how you burn an HD DVD. I don't have an HD DVD player either. But, if I knew I could burn HD DVDs for such a set-top player that would give me the incentive to buy one. Smarty wrote: Sam, The HDV from your Sony makes beautiful HD DVDs which play on the Toshiba set-top players. You can use Ulead MovieFactory 6 Plus (about $60), or Apple's DVD Studio Pro to create them, and I do it both ways. Also Ulead's Video Studio 10+ does a very nice job. Download the free trial of Ulead Movie Factory 6+ and capture directly from your Sony. I use both the HDR-HC3 and FX-1 camcorders, and they both work superbly well. Also, you can import still camera pictures from any digital camera with more than 2 megapixel images and you will see the images on your 1920 by 1080 HDTV at full rez (roughly 2 Mpixels). The still picture slideshows and camcorder videos can be mixed for a really nice wedding, party, travel or other HD DVD. Smarty "Sam Spade" <sam@xxxxxxxxxxxx> wrote in message news:wcOQh.119665$115.24024@xxxxxxxxxxxxxxx How do you make HDV DVDs and what do you use to view them? I have a Sony consumer HDV camcorder. All I have figured out so far is to upload the tape to my PC, edit it, then download the finished product to the camcorder and use it as the player. Smarty wrote: I make a lot of HD-DVDs with still photographs as well as with prosumer HDV camcorders, and I am here to tell you that HD DVD delivers stunning 1920 by 1080 full frame content in exactly the same format, resolution, and color gamut as the MPEG2 encoded BluRay disks, and generally quite superior to anything I can see on my satellite or HD cable box, both of which are encoded at a much lower bit rate than the 25 Mbit/sec data coming from the HD DVD. . - Follow-Ups: - Re: Unimpressed by HD-DVD - From: Sam Spade - Re: Unimpressed by HD-DVD - From: Smarty - References: - Unimpressed by HD-DVD - From: nospam - Re: Unimpressed by HD-DVD - From: Smarty - Re: Unimpressed by HD-DVD - From: Sam Spade - Re: Unimpressed by HD-DVD - From: Smarty - Re: Unimpressed by HD-DVD - From: Sam Spade - Prev by Date: Re: Unimpressed by HD-DVD - Next by Date: Re: Unimpressed by HD-DVD - Previous by thread: Re: Unimpressed by HD-DVD - Next by thread: Re: Unimpressed by HD-DVD - Index(es):
http://newsgroups.derkeiler.com/Archive/Alt/alt.tv.tech.hdtv/2007-04/msg00109.html
crawl-002
refinedweb
626
75.74
Java Null – 7 Unknown Facts about Null in Java 2019 We closed our last chapter on Type Conversion in Java. Today, we will in this Java tutorial, we are going to learn what is Java Null and seven unknown facts about the null in Java Programming Language: case sensitivity, refer variable value, types of null, autoboxing & unboxing in java, instanceof operator, static vs non- static methods, and ==and!=are some interesting facts about Null. 1. What is Java Null? All the programming dialects are fortified with null. In Java, invalid is related java.lang.NullPointerException. As it is a class in java.lang bundle, it is called when we endeavour to play out a few activities with or without invalid and at times we don’t know where it has happened. Read about Java Abstract Data Type in Data Structure 2. Unknown Facts About Null in Java 2019 All the programmers on the earth are suffering with null. These are some facts, which you should know about null, to program in Java. - Case sensitive - Reference variable value - Type of null - Autoboxing and unboxing - instanceof operator - Statics vs non-static methods - == and != i. Java Null is Case Sensitive It is a literal and in Java keywords are case sensitive, so we do not write it as NULL or 0 as we would in C. Example – public class Test { public static void main (String[] args) throws java.lang.Exception { // compile-time error : can't find symbol 'NULL' Object obj = NULL; //runs successfully Object obj1 = null; } } Output – 5: error: cannot find symbol can’t find symbol ‘NULL’ ^ variable NULL class Test 1 error Do you know How to Handle Java Exception ii. Reference Variable Value Any reference variable automatically has a null value. Example – public class Test { private static Object obj; public static void main(String args[]) { // it will print null; System.out.println("Value of object obj is : " + obj); } } iii. Type of Null in Java Java Null is just a special value, it is neither an object nor a type. Example – String str = null; Integer itr = null; Double dbl = null; String myStr = (String) null; Integer myItr = (Integer) null; Double myDbl = (Double) null; Read about Java Number Methods with Syntax and Examples iv. Autoboxing and Unboxing in Java An error is thrown if the null value is assigned to a primitive data type in Java. Example – public class Test { public static void main (String[] args) throws java.lang.Exception { Integer i = null; int a = i; } } v. Instanceof Operator in Java At runtime the instanceof operator in Java is true if an expression is Java null, it checks for the type of instance of the object. Example – public class Test { public static void main (String[] args) throws java.lang.Exception { Integer i = null; Integer j = 10; //prints false System.out.println(i instanceof Integer) //Compiles successfully System.out.println(j instanceof Integer); } } vi. Static vs. Non-static Methods in Java A non-static value cannot be called by a null value, it will throw a NullPointerException, but this won’t happen with a static method. Read more about Methods in Java Example- public class Test { public static void main(String args[]) { Test obj= null; obj.staticMethod(); obj.nonStaticMethod(); } private static void staticMethod() { System.out.println("static method, can be called by null reference"); } private void nonStaticMethod() { System.out.print(" Non-static method- "); System.out.println("cannot be called by null reference"); } } vii. == and != Operator These comparisons are possible with a null operator. Example – public class Test { public static void main(String args[]) { System.out.println(null==null); System.out.println(null!=null) } }
https://data-flair.training/blogs/java-null/
CC-MAIN-2019-35
refinedweb
598
55.95
Table of Contents Introduction A two-dimensional array in C++ is the simplest form of a multi-dimensional array. It can be visualized as an array of arrays. The image below depicts a two-dimensional array. A two-dimensional array is also called a matrix. It can be of any type like integer, character, float, etc. depending on the initialization. In the next section, we are going to discuss how we can initialize 2D arrays. Initializing a 2D array in C++ So, how do we initialize a two-dimensional array in C++? As simple as this: int arr[4][2] = { {1234, 56}, {1212, 33}, {1434, 80}, {1312, 78} } ; So, as you can see, we initialize a 2D array arr, with 4 rows and 2 columns as an array of arrays. Each element of the array is yet again an array of integers. We can also initialize a 2D array in the following way. int arr[4][2] = {1234, 56, 1212, 33, 1434, 80, 1312, 78}; In this case too, arr is a 2D array with 4 rows and 2 columns. Printing a 2D Array in C++ We are done initializing a 2D array, now without actually printing the same, we cannot confirm that it was done correctly. Also, in many cases, we may need to print a resultant 2D array after performing some operations on it. So how do we do that? The code below shows us how we can do that. #include<iostream> using namespace std; main( ) { int arr[4][2] = { { 10, 11 }, { 20, 21 }, { 30, 31 }, { 40, 41 } } ; int i,j; cout<<"Printing a 2D Array:\n"; for(i=0;i<4;i++) { for(j=0;j<2;j++) { cout<<"\t"<<arr[i][j]; } cout<<endl; } } Output: In the above code, - We firstly initialize a 2D array, arr[4][2]with certain values, - After that, we try to print the respective array using two for loops, - the outer for loop iterates over the rows, while the inner one iterates over the columns of the 2D array, - So, for each iteration of the outer loop, iincreases and takes us to the next 1D array. Also, the inner loop traverses over the whole 1D array at a time, - And accordingly, we print the individual element arr[ i ][ j ]. Taking 2D Array Elements As User Input Previously, we saw how we can initialize a 2D array with pre-defined values. But we can also make it a user input too. Let us see how #include<iostream> using namespace std; main( ) { int s[2][2]; int i, j; cout<<"\n2D Array Input:\n"; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout<<"\ns["<<i<<"]["<<j<<"]= "; cin>>s[i][j]; } } cout<<"\nThe 2-D Array is:\n"; for(i=0;i<2;i++) { for(j=0;j<2;j++) { cout<<"\t"<<s[i][j]; } cout<<endl; } } Output: For the above code, we declare a 2X2 2D array s. Using two nested for loops we traverse through each element of the array and take the corresponding user inputs. In this way, the whole array gets filled up, and we print out the same to see the results. Matrix Addition using Two Dimensional Arrays in C++ As an example let us see how we can use 2D arrays to perform matrix addition and print the result. #include<iostream> using namespace std; main() { int m1[5][5], m2[5][5], m3[5][5]; int i, j, r, c; cout<<"Enter the no.of rows of the matrices to be added(max 5):"; cin>>r; cout<<"Enter the no.of columns of the matrices to be added(max 5):"; cin>>c; cout<<"\n1st Matrix Input:\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) { cout<<"\nmatrix1["<<i<<"]["<<j<<"]= "; cin>>m1[i][j]; } } cout<<"\n2nd Matrix Input:\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) { cout<<"\nmatrix2["<<i<<"]["<<j<<"]= "; cin>>m2[i][j]; } } cout<<"\nAdding Matrices...\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) { m3[i][j]=m1[i][j]+m2[i][j]; } } cout<<"\nThe resultant Matrix is:\n"; for(i=0;i<r;i++) { for(j=0;j<c;j++) { cout<<"\t"<<m3[i][j]; } cout<<endl; } } Output: Here, - We take two matrices m1and m2with a maximum of 5 rows and 5 columns. And another matrix m3in which we are going to store the result, - As user inputs, we took the number of rows and columns for both the matrices. Since we are performing matrix addition, the number of rows and columns should be the same for both the matrices, - After that, we take both the matrices as user inputs, again using nested for loops, -++ If we can have a pointer to an integer, a pointer to a float, a pointer to a char, then can we not have a pointer to an array? We certainly can. The following program shows how to build and use it. #include<iostream> using namespace std; /* Usage of pointer to an array */ main( ) { int s[5][2] = { {1, 2}, {1, 2}, {1, 2}, {1, 2} } ; int (*p)[2] ; int i, j; for (i = 0 ; i <= 3 ; i++) { p=&s[i]; cout<<"Row"<<i<<":"; for (j = 0; j <= 1; j++) cout<<"\t"<<*(*p+j); cout<<endl; } } Output: Here, - In the above code, we try to print a 2D array using pointers, - As we earlier did, at first we initialize the 2D array, s[5][2]. And also a pointer (*p)[2], where p is a pointer which stores the address of an array with 2 elements, - As we already said, we can break down a 2D array as an array of arrays. So in this case, s is actually an array with 5 elements, which further are actually arrays with 2 elements for each row. - We use a forloop to traverse over these 5 elements of the array, s. For each iteration, we assign p with the address of s[i], - Further, the inner for loop prints out the individual elements of the array s[i] using the pointer p. Here, (*p + j)gives us the address of the individual element s[i][j], so using *(*p+j)we can access the corresponding value. Passing 2-D Array to a Function In this section, we are going to learn how to pass a 2D array to any function and access the corresponding elements. In the code below, we pass the array a, to two functions show() and print() which prints out the passed 2D array. #include<iostream> using namespace std; void show(int (*q)[4], int row, int col) { int i, j ; for(i=0;i<row;i++) { for(j=0;j<col;j++) cout<<"\t"<<*(*(q + i)+j); cout<<"\n"; } cout<<"\n"; } void print(int q[][4], int row, int col) { int i, j; for(i=0;i<row;i++) { for(j=0;j<col;j++) cout<<"\t"<<q[i][j]; cout<<"\n"; } cout<<"\n"; } int main() { int a[3][4] = { 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21} ; show (a, 3, 4); print (a, 3, 4); return 0; } Output: Here, - In the show( )function we have defined q to be a pointer to an array of 4 integers through the declaration int (*q)[4], - q holds the base address of the zeroth 1-D array - This address is then assigned to q, an int pointer, and then using this pointer all elements of the zeroth 1D array are accessed. - Next time through the loop when itakes a value 1, the expression q+i fetches the address of the first 1-D array. This is because q is a pointer to the zeroth 1-D array and adding 1 to it would give us the address of the next 1-D array. This address is once again assigned to q and using it all elements of the next 1-D array are accessed - In the second function print(), the declaration of q looks like this: int q[][4], - This is same as int (*q )[4], where q is a pointer to an array of 4 integers. The only advantage is that we can now use the more familiar expression q[i][j]to access array elements. We could have used the same expression in show()as well but for better understanding of the use of pointers, we use pointers to access each element. Conclusion So, in this article, we discussed two-dimensional arrays in C++, how we can perform various operations as well as its application in matrix addition. For any further questions feel free to use the comments.
https://www.journaldev.com/36660/two-dimensional-array-in-c-plus-plus
CC-MAIN-2021-04
refinedweb
1,440
62.92
import form from existing websiteAsked by mhughe29 on June 04, 2014 at 09:25 AM Trying to import this form from an existing site but only getting form properties and not the form what am I doing wrong? Hi, Please note that you are using the form URL provided while getting the Embed code. The URL you need to use is this one All you needed to do to fix it was to remove the js letters that appear before the word form. This way: Please inform us if you need further assistance with this query. Thanks Thanks for the awesome support! - JotForm Support Hello mhughe29, On behalf of my colleague, you are welcome. Do get back to us if you have any questions. Thank you!
https://www.jotform.com/answers/387426-Can-t-import-form-from-existing-website
CC-MAIN-2017-04
refinedweb
126
78.69
Jonathan Gardner's PyQt Tutorial This is a short tutorial to get you up to speed with PyQt. It assumes some knowledge of bash, Python, and Qt. If you have questions or comments, you can send them to me at jgardner@jonathangardner.net. You may also make corrections to this page. A (brazilian) portuguese translation is available at thanks to Rodrigo B. Vieira. Contents Abstract We will cover: - Using Qt Designer to generate Qt ui files. - Using pyuic to generate python programs. - Using Qt Signals and Slots in Python. - Creating a simple application to interface with the 'at' program. Requirements You will need: - Red Hat 8.0 with the following configuration: - qt-devel RPM properly installed PyQt-devel RPM properly installed PyQt works on other systems. This tutorial may or may not work as well. However, I cannot provide all the details on how to get them to work on all the systems that can use PyQt. You are responsible for figuring that out. You should already know: - How to use a text editor, and how to get that text editor to edit Python code properly. - How to program in Python. - Some basic bash commands. - The basics of Qt programming. If you haven't fulfilled these requirements, you may have some trouble getting the tutorial to work. Using Qt Designer First things first. We'll start where I start. Open up a bash prompt. Start Qt Designer by typing the following command: $ designer You are presented with Qt designer. Depending on which version you are running, it may appear slightly different. I won't assume you are totally inept at using Qt Designer. If you are, you can easily read the documentation. Create a new widget. Name it 'at_auto'. Add some stuff to it: Add a QLineEdit. Name it "command" in the property dialog. Add a QPushButton. Name it "schedule" in the property dialog. Change its text to "Schedule". Add a QDateTimeEdit. Name it "time" in the property dialog. Now, rearrange the layout using the Qt layout tools to your heart's content. You may need to use some spacers as well. Save the file in a project directory for this tutorial. If you haven't already created one, create one called "pyqt_tutorial" or something. Save the file as "at.ui". Using pyuic Go back to your bash prompt, or open up a new one. Go into the project directory, and run these commands. $ pyuic at.ui This command will store the generated python code that comes from the Qt ui file into at_auto.py. $ pyuic at.ui -o at_auto.py Everytime we change the ui file, we need to regenerate the at_auto.py file. Let's add this command to a makefile. Tabs are important! $ cat > Makefile at_auto.py : at.ui pyuic at.ui -o at_auto.py ^D Now run the makefile. $ make Notice that it says something about all the files being up to date. Let's touch at.ui so it appears newer than at_auto.py, and then run make again. $ touch at.ui $ make Now it echos out the commands it runs. You see that it has successfully regenerated at_auto.py. Theory The idea here is that you want the GUI developer to be able to go and make changes to the GUI interface (like moving stuff around) without affecting the logic behind the GUI. So with your setup right now, all the GUI developer has to do is use Qt Designer to change the at.ui file, and then run make to see his changed take effect. Your make file will get more complicated as you add more files. Be sure to read more about make so that you make good design decisions early on about how to use make properly. Running Your Application So we have that at.ui file, and the at_auto.py file. How do we actually run the app? We have to create at.py. Here is what it will look like. from qt import * from at_auto import at_auto class at(at_auto): def __init__(self, parent=None, name=None, fl=0): at_auto.__init__(self,parent,name,fl) if __name__ == "__main__": import sys a = QApplication(sys.argv) QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()")) w = at() a.setMainWidget(w) w.show() a.exec_loop() Now, run it. $ python at.py Tada! You have your application. NOTE: If you are using Qt designer with Qt version 3.3.0 your .ui file contains: <!DOCTYPE UI><UI version="3.3" stdsetdef="1"> in the header, and pyuic (3.8.1 at least) complains that the version is too recent and won't produce any output. This is easy to solve; you can create a tiny script which will automatically fix this error, run make and run your new application: #!/bin/bash sed -i s/3.3/3.3.0/g at.ui make exec python at.py chmod 700 myscript and you're set ! Setting the Default Date / Time Let's set a default value for the QDateTimeEdit widget. The QDateTimeEdit widget expects a QDateTime for an argument to the setDateTime method, so we'll have to create one. But how to set the time of the QDateTime? Examination of the documentation reveals that the setTime_t method will allow us to set the date with the time in seconds from the Unix epoch. We can get that from the time() function in the built-in time module. Here's the code that does that. We'll put this in the __init__ method so that it gets populated correctly from the beginnin. Remember to import time! # Set the date to now now = QDateTime() now.setTime_t(time.time()) # Time in seconds since Unix Epoch self.time.setDateTime(now) This code snippet should show how easily python and PyQt work with each other. It should also demonstrate the thought processes you'll have to go through to manipulate Qt's widgets. Signals and Slots Everything you do from here on out is connecting Signals to Slots. It's pretty easy, which is why I like PyQt. Python isn't C++. So it has to deal with Signals and Slots in a new way. First, in Python, anything that is callable is a slot. It can be a bound method, a function, or even a lambda expression. Second, in Python, a signal is just some text that is meaningless. Let me clarify the distinction between a C++ Signal/Slot and a Python Signal/Slot. It has nothing to do with where the object was created. It has everything to do with where the Signal originated, and where the Slot is located. For instance, a QPushButton has a C++ Signal, "clicked()". If you create your own subclass in Python, called "PyPushButton", it still has a C++ Signal, "clicked()". If you created a new Signal in Python, called "GobbledyGook()", then it is a Python Signal, because nothing in C++ even knows of its existence. When you bind a signal to a slot, you can do one of the following: - Bind a C++ Signal to a Python slot - You'll do this all day long. This is done by making the call as follows: QObject.connect(some_object, SIGNAL('toggled(bool)'), some_python_callable) See here for an example how to simplify this task with decorators (in Python 2.4): - Bind a C++ Signal to a C++ Signal - You won't do this very often, but it comes in handy. QObject.connect(some_object, SIGNAL('toggled(bool)'), some_object, SLOT('the_slot(bool)')) - Bind a Python Signal to C++ or Python Slot - You won't be using Python Signals too often, but this is how to do it. Basically, you imagine up a new signal name. Then you change "SIGNAL" above to "PYSIGNAL". If you are using a lot of Python signals, it may make some sense to bypass the Qt signalling library and use your own. If you plan on porting the code to C++ one day, that won't make any sense at all. I have done this because I found the syntax a bit burdensome, and the debugging difficult. Our application is going to respond to only one signal: the "Schedule" button being pressed. What it will do is run the "at" command with appropriate arguments. Here is the code to initiate the connection: self.connect( self.schedule, SIGNAL('clicked()'), self.schedule_clicked ) Notice that we are connecting a C++ Signal to a Python Slot. However, that slot doesn't exist yet. Let's add it to the 'at' class.() The process here is two fold. First, we check to see if something is specified in the "command" QLineEdit widget. If not, we show a QMessageBox with a critical message. If there is something in the command box, we open up a pipe to the 'at' command. 'at' expects the command to be coming in on stdin. We then write to it's stdin the command we want to execute. Notice that we don't do any error checking here. Go ahead and run the application now, and use the 'atq' command to see if the 'at' job was queued up. Good? Okay. Here is the final code for the 'at.py' file. from qt import * from at_auto import at_auto import time import sys import os class at(at_auto): def __init__(self, parent=None, name=None, fl=0): at_auto.__init__(self,parent,name,fl) # Set the date to now now = QDateTime() now.setTime_t(time.time()) # Time in seconds since Unix Epoch self.time.setDateTime(now) self.connect( self.schedule, SIGNAL('clicked()'), self.schedule_clicked )() if __name__ == "__main__": a = QApplication(sys.argv) QObject.connect(a,SIGNAL("lastWindowClosed()"),a,SLOT("quit()")) w = at() a.setMainWidget(w) w.show() a.exec_loop() Homework With the time remaining, you may want to add a few extensions. - Using Qt Designer, add QLabels to describe what each of the inputs do. Notice that you don't have to change any code, just edit the 'at.ui' file and run 'make'. - After you schedule the 'at' job, you may want the application to close. Find an appropriate slot to close the 'at' widget or the entire application. Question: Why does closing the 'at' widget shut down the entire application? Do some error checking when you schedule the at job . If there are any messages, show them to the user with a QMessageBox. - Write an application to list the 'at' queue. - Add functionality to edit or remove queued 'at' jobs. Try to reuse as much code as possible. (Hint: the widget that will schedule a new 'at' job is already finished. Try embedding it in a QDialog.) Future Directions This application could be part of a suite of Unix command line interfaces. What other commands would you like to implement? I suggest giving things like "crontab" and "ps" a try. Parsing the output of these commands isn't too difficult, and the interface with them is pretty easy. You may also want to try and combine your new apps with the 'at' app. If you like, you can sell them as a Unix graphical interface, but you'll have to buy the commercial license for both Qt and PyQt unless you stick with something like the GPL.
https://wiki.python.org/moin/JonathanGardnerPyQtTutorial
CC-MAIN-2019-13
refinedweb
1,862
77.43
After years on Code Project, receiving and reading the Code Project News Daily that keeps me in touch on edge technologies and rumors and weekly Newsletter with interesting, cool code article and references why don't start to write and post an article? So I decided to post a sample code, Hello world program, one of the simplest program, to learn how to. In Code Project main page I found a big link Post an Article to Submit a New Article page. Two options in this page: I chose Option 1 letting Article and Start Writing!>>. New page is Article Submission Wizard and I'll show each wizard section in detail. This article just shows and uses a wizard, so no knowledge is required apart c# very basic and a little of html. Article submission wizard is a single page that contains everything you need to write and post your article on Code Project. On the right I left Type as Article, Licence as CPOL and Who can edit Admin Only The middle part of Submission Wizard page is: On the left the html editor and on the right the article files, generally file images. Under the html editor is shown the Final article URL as will be Name. In this paragraph I'll show you the editor. In the html editor there is the template where you can write your article, with prefixed paragraph, Introduction, Background, Using Code and Points of Interest. I've written this article on it adding more paragraphs. In Html source mode you see the formatting, very simple, just <p>, <h2>, <br> tags, and <pre> tag before code section. The style sheet is not included, probably is by default. Weakness: when you select a text, prompt doesn't go to the same text switching from design mode to HTML mode and also HTML mode presentation is too verbose, without indentation, browsing online in two modes is not so fluid, with two scrollbars, the html editor one and that of your browser. I think wizard is enough if you want to write the article directly on design, but it's not the right solution for work in html source mode. Toolbar is essential but contains all the basic to formatting an article and uploading files or media. It's is made of: Buttons 1st row: Bold, Italic, var for variable name, Strikethrough, Subscript, Superscript, Cut, Copy, Paste selection, Undo and Do your last action, Find and Replace. 2nd row: Insert/Modify: image, movie, horizontal rule, Insert Web link and anchor, Remove bad tags and formatting, InsertTable, Toggle Borders, Justify Left, Center and Right, Decrease and Increase Indent, Ordered List, Bulleted List, HTML toggle between HTML and Design Mode Three dropdowns: To upload an image, Insert image button opens a window where you can set property for image: Using the code is the paragraph to write a brief description of how to use the article or code. The class names, the methods and properties, any tricks or tips. OK. Hello World program displays a fixed message on console, Hello World. In c# static Main function is program entry-point with optional string args. Console.WriteLine function displays the argument on console and goes to a new line. Console.Readline waits an input so console doesn't quit and message is readable from user. I put my code inside <pre> element, the coloured section, setting dropdown language format in html editor toolbar as c#, translate in html with attribute cs in pre tag. With var button you add <code> tag, for variables and classes names. In Wizard html editor you don't see language formatting. using System; namespace Hello_World { class Program { static void Main(string[] args) { var i =0; Console.WriteLine("Hello World"); Console.ReadLine(); } } } In Wizard's right part, outside the html editor, two buttons for Save or Discard draft, Between them the time of last saving, less than 1 minute when you edit, then Current Files with tip Files are relative to the current document. eg <img src="myimage.jpg">, No files uploaded at the beginning. Section part to Upload Files and in the end Article source Url is only for reposting. In Upload Files section you can Browse File or Drag and Drop File Here with request: Please keep each document file under 10 MB. Please keep each image file under 1 MB and the width < 640px. Permitted file types are: ZIP, JPG, GIF, PNG, SWF, FLV, MP4. My article's file images are uploaded either with Drag and Drop or with Browse File inside Upload Files section. Browse file is a two steps uploading file, in the sample I Browse File with the name Header empty.png and you need one more step with Upload Files button. Current Files lists uploaded files with size and dimension and you can, eventually, rename them or see in a new page. In the sample I've five files. Issues: sometimes uploading file you get: Unexpected error during upload. One or more files may not have been uploaded and also file list name is odd redisplaying file with old name. I'm in the end, now I've to post my work, using the below part of the Submission Page. Two text boxes: Any comments for our editors? and Briefly comment on what was changed. I set in first one: Please, could you check if my section and subsection are right for my article subject? In fact I'm not sure of my choice, Tools and IDE for section and General for Subsection, maybe there is something better. In fact after feedback I set CodeProject FAQs updating my Article Submission Wizard as you see, I left the second one blank because is my first article version. Next steps info say: Once you've previewed and submitted your article, your article will go into a queue for approval by the community. The approval process is usually very quick. OK, I'll waiting for... Two checked boxes: Work in progress: don't publish and I have read and agree to the contributor's agreement. Two buttons: Publish and Preview available in a new page, where you can read your article as will be published, formatting code included. You can publish only checked I have read and agree to the contributor's agreement and sure you have written a good article. If you check Work in progress: don't publish, Publish button is replaced by Save this Version button, unchecking comes back Publish one. To edit, update your draft, if you log in Code Project, on the right-top of home page, in My Article hyperlink, you'll find yours. You can continue your work or delete it. I wrote my first article on Code Project, it's never too late. Wizard to Submit a New Article is not difficult to use but maybe for bigger article, Option 2 Send your article to an editor and have us do the hard work is better. Write an article in Code Project with the Submission Wizard has been studied in depth in A Guide To Writing Articles For Code Project by Marc Clifton and Code Project Article FAQ by Sean Ewington. Probably if you've posted any articles, you know better than me cons and pros of Article Submission Wizard. Hope you enjoy my.
http://www.codeproject.com/script/Articles/View.aspx?aid=690031
CC-MAIN-2015-32
refinedweb
1,221
69.31
Simple Scripting This page discusses writing your own simple scripts for PyMOL. If you're looking to download scripts try the Script Library. If you need help with running a script try Running_Scripts One of the more powerful features of PyMOL is that it supports Python scripting. This gives you the power to use most of the Python libraries to write programs and then send the results back into PyMOL. Some useful extensions to PyMOL can be found in our Script Library. Contents General Scripts General PyMOL scripting is done in Python. It's really quite simple, just write your function (following a couple simple rules) and then let PyMOL know about it by using the cmd.extend command. Here's the simple recipe for writing your own simple scripts for PyMOL: To write them: - Write the function, let's call it doSimpleThing, in a Python file, let's call the file pyProgram.py. - Add the following command to the end of the pyProgram.py file cmd.extend("doSimpleThing",doSimpleThing) To use them: - simply import the script into PyMOL: run /home/userName/path/toscript/pyProgram.py - Then, just type the name of the command: doSimpleThing and pass any needed arguments. That's it. Your script can, through Python, import any modules you need and also edit modify objects in PyMOL. Getting PyMOL Data into your Script To get PyMOL data into your script you will need to somehow get access to the PyMOL objects and pull out the data. For example, if you want the atomic coordinates of a selection of alpha carbon atoms your Python function may do something like this (see also iterate_state): # Import PyMOL's stored module. This will allow us with a # way to pull out the PyMOL data and modify it in our script. # See below. from pymol import stored def functionName( userSelection ): # this array will be used to hold the coordinates. It # has access to PyMOL objects and, we have access to it. stored.alphaCarbons = [] # let's just get the alpha carbons, so make the # selection just for them userSelection = userSelection + " and n. CA" # iterate over state 1, or the userSelection -- this just means # for each item in the selection do what the next parameter says. # And, that is to append the (x,y,z) coordinates to the stored.alphaCarbon # array. cmd.iterate_state(1, selector.process(userSelection), "stored.alphaCarbons.append([x,y,z])") # stored.alphaCarbons now has the data you want. ... do something to your coordinates ... Getting Data From your Script into PyMOL Usually this step is easier. To get your data into PyMOL, it's usually through modifying some object, rotating a molecule, for example. To do that, you can use the alter or alter_state commands. Let's say for example, that we have translated the molecular coordinates from the last example by some vector (we moved the alpha carbons). Now, we want to make the change and see it in PyMOL. To write the coordinates back we do: # we need to know which PyMOL object to modify. There could be many molecules and objects # in the session, and we don't want to ruin them. The following line, gets the object # name from PyMOL objName = cmd.identify(sel2,1)[0][0] # Now, we alter each (x,y,z) array for the object, by popping out the values # in stored.alphaCarbons. PyMOL should now reflect the changed coordinates. cmd.alter_state(1,objName,"(x,y,z)=stored.alphaCarbons.pop(0)") Example Here's a script I wrote for cealign. It takes two selections of equal length and computes the optimal overlap, and aligns them. See Kabsch for the original code. Because this tutorial is for scripting and not optimal superposition, the original comments have been removed. def optAlign( sel1, sel2 ): """ @param sel1: First PyMol selection with N-atoms @param sel2: Second PyMol selection with N-atoms """ # make the lists for holding coordinates # partial lists stored.sel1 = [] stored.sel2 = [] # full lists stored.mol1 = [] stored.mol2 = [] # -- CUT HERE sel1 = sel1 + " and N. CA" sel2 = sel2 + " and N. CA" # -- CUT HERE # This gets the coordinates from the PyMOL objects cmd.iterate_state(1, selector.process(sel1), "stored.sel1.append([x,y,z])") cmd.iterate_state(1, selector.process(sel2), "stored.sel2.append([x,y,z])") # ...begin math that does stuff to the coordinates... mol1 = cmd.identify(sel1,1)[0][0] mol2 = cmd.identify(sel2,1)[0][0] cmd.iterate_state(1, mol1, "stored.mol1.append([x,y,z])") cmd.iterate_state(1, mol2, "stored.mol2.append([x,y,z])") assert( len(stored.sel1) == len(stored.sel2)) L = len(stored.sel1) assert( L > 0 ) COM1 = numpy.sum(stored.sel1,axis=0) / float(L) COM2 = numpy.sum(stored.sel2,axis=0) / float(L) stored.sel1 = stored.sel1 - COM1 stored.sel2 = stored.sel2 - COM2 E0 = numpy.sum( numpy.sum(stored.sel1 * stored.sel1,axis=0),axis=0) + numpy.sum( numpy.sum(stored.sel2 * stored.sel2,axis=0) ,axis=0) reflect = float(str(float(numpy.linalg.det(V) * numpy.linalg.det(Wt)))) if reflect == -1.0: S[-1] = -S[-1] V[:,-1] = -V[:,-1] RMSD = E0 - (2.0 * sum(S)) RMSD = numpy.sqrt(abs(RMSD / L)) U = numpy.dot(V, Wt) # ...end math that does stuff to the coordinates... # update the _array_ of coordinates; not PyMOL the coords in the PyMOL object stored.sel2 = numpy.dot((stored.mol2 - COM2), U) + COM1 stored.sel2 = stored.sel2.tolist() # This updates PyMOL. It is removing the elements in # stored.sel2 and putting them into the (x,y,z) coordinates # of mol2. cmd.alter_state(1,mol2,"(x,y,z)=stored.sel2.pop(0)") print "RMSD=%f" % RMSD cmd.orient(sel1 + " and " + sel2) # The extend command makes this runnable as a command, from PyMOL. cmd.extend("optAlign", optAlign) Basic Script Body Want an easy block of working code to start your function from? Just copy/paste the following into your Python editor and get going! # # -- basicCodeBlock.py # from pymol import cmd, stored def yourFunction( arg1, arg2 ): ''' DESCRIPTION Brief description what this function does goes here ''' # # Your code goes here # print "Hello, PyMOLers" print "You passed in %s and %s" % (arg1, arg2) print "I will return them to you in a list. Here you go." return (arg1, arg2) cmd.extend( "yourFunction", yourFunction ); Python Version Supported by PyMOL Scripts used within PyMOL can only be written using the current version of Python that is supported by your version of PyMOL. To determine which version of Python you can use, type the following command into PyMOL: print sys.version Note that this version of Python is not necessarily related to the version that you may have installed on your system. This command can also be used to ensure that code you are distributing can be supported by the user's system.
https://pymolwiki.org/index.php/Scripting
CC-MAIN-2017-04
refinedweb
1,118
58.99
Raspberry Pi Cluster Node – 16 Python 3 Codebase Refactor This post builds on my previous posts in the Raspberry Pi Cluster series by improving the codebase for Python 3. Moving to Python 3 Python 2 was marked end of life on January 1st, 2020 and therefore applications should ideally be no longer using Python 2. There will still be a lot of applications still using it, but really they should have been migrated away by now. In this case, I am using this tutorial to migrate the code from Python 2 and perform some refactoring. Changing Hashbangs The first change is to replace all the hashbangs with a python 3 compatible one. This means all the hashbangs that are as follows. #!/usr/bin/env python2.7 Will be converted to #!/usr/bin/env python3 For now I am just marking them up with python3 and not a specific minor version. This is because while I would like to use the most recent python version, I want to keep this open to a variety of systems and therefore will keep the code generic to python 3. Changing relative imports Previously I used implicit relative imports which meant that Python looked in the current package level for anything referenced if it could not be initially found. This means if ModuleA refers to ModuleB, python 2 will find it if it is in the same directory. Python 3 no longer searches for implicit relative imports which means it will no longer file ModuleB even if it is in the same directory as ModuleA. You are able to use a relatively import by prefixing the import name with a dot. For example Python 2 – import ModuleB Python 3 – import .ModuleB Both will work the same, however in Python 3 we now have to be explicit about the relative import. I am going to go through and be explicit about the location of modules. Unicode Handling Python 3 handles unicode in a much better way, however it means now a number of functions expect binary data instead of strings. An example is that the socket handling code to receive and send data now must be encoded in binary before being sent. This can be done using the encode function available on strings, and decode function available on binary data. This function requires a character set to encode/decode as when it is called. I am going to be using utf-8 to transfer data back and forth on the nodes so will encode/decode with utf-8. This means by socket handling code requires a small tweak as below: Sending data and encoding as utf-8: self.sock.send(payload.encode("utf-8")) Recieving data and decoding as utf-8: self._buffered_string += data.decode("utf-8") Removing References to Master / Slave Since I last worked on the cluster the world has moved on and various reflection has been made on the world. The terms master/slave are steeped in racial undertones and therefore I am removing them. If renaming the scripts makes one person feel more included, it is for the best. The three main scripts have been renamed to the following. - basic_primary.py - basic_secondary.py - basic_webserver.py All references in the code to master/slave have been replaced with primary/secondary. Python Doc Comments I previously, wrongfully, neglected python dock blocks opting for detailed descriptions in the tutorials. While documentation in the tutorials is helpful adding docblocks to the code will also be useful. I am going through all the code adding doc blocks. This shouldn’t be a massive undertaking as the code was already commented, just the functions/classes did not have a description on them. Misc Code changes There are a few changes made that PEP 8 stuff - pep8 – two spaces before inline block - pep8 – Inline block must have space between # and comment - Variables should be python case not camel case Refactoring the DataPackager The DataPackager is a small set of functions used to create the payload to send over the socket. In addition it handles receiving data from the socket and piecing the payload back together. After reviewing the code I found that since partial messages are stored in the class and not the object, using multiple data packagers on multiple slots may cause message corruption. In addition to this, it was expected that to send messages with the DataPackager you needed to format the messages first. This is now handled directly by the DataPackager and means you just pass in the payload to send. These changes, including moving it to its own object should make it easier to use and possible to use multiple in the same script. Summary of improving the codebase In this tutorial the cluster codebase is moved to python 3 and generally cleaned up and improved. This will allow the latest languages and tools to be used with the cluster and improve development. In addition the increased comments and improvements should make it easier to add further functionality to the cluster. The full code is available on Github, any comments or questions can be raised there as issues or posted below.
https://chewett.co.uk/blog/2680/raspberry-pi-cluster-node-16-python-3-codebase-refactor/
CC-MAIN-2022-27
refinedweb
856
59.94
def jardir = new File( System.getenv( 'JAXB_HOME' ), 'lib' ) def jars = jardir.listFiles().findAll jars.each 3. Load the classes you need: // in a script run from command line this is ok: JAXBContext = Class.forName( 'javax.xml.bind.JAXBContext' ) Marshaller = Class.forName( 'javax.xml.bind.Marshaller' ) // if the groovy script / class is loaded from a java app, then the above may fail as it uses the same classloader to load the class as the containing script / class was loaded by. In that case, this should work: JAXBContext = Class.forName( 'javax.xml.bind.JAXBContext', true, loader ) Marshaller = Class.forName( 'javax.xml.bind.Marshaller', true, loader ) 4. To instantiate the classes, use the newInstance method: def jaxbContext = JAXBContext.newInstance( MyDataClass ) Note that newInstance is on steroids when called from groovy. In addition to being able to call the parameterless constructor (as w/ Java's Class.newInstance()), you can give any parameters to invoke any constructor, e.g. def i = MyClass.newInstance( "Foo", 12 ) // invokes the constructor w/ String and int as params You can also pass a map to initialize properties, e.g. def i2 = MyClass.newInstance(foo:'bar', boo:12) // creates a new instance using the parameterless constructor and then sets property foo to 'bar' and property boo to 12 The downside of using this approach is that you can't inherit from the classes you load this way - classes inherited from need to be known before the script starts to run.
http://docs.codehaus.org/pages/viewpage.action?pageId=72117
CC-MAIN-2014-49
refinedweb
240
58.18
mq_open - open a message queue (REALTIME) The mq_open() function shall establish the connection between a process and a message queue with a message queue descriptor. It shall create an open message queue description that refers to the message queue, and a message queue descriptor that refers to that open message queue description. The message queue descriptor is used by other functions to refer to that message queue. The name argument points to a string naming a message queue. It is unspecified whether the name appears in the file system and is visible to other functions that take pathnames as arguments. The name argument shall conform to the construction rules for a pathname. If name begins with the slash character, then processes calling mq_open() with the same value of name shall refer to the same message queue object, as long as that name has not been removed. If name does not begin with the slash character, the effect is implementation-defined. The interpretation of slash characters other than the leading slash character in name is implementation-defined. If the name argument is not the name of an existing message queue and creation is not requested, mq_open() shall fail and return an error. A message queue descriptor may be implemented using a file descriptor, in which case applications can open up to at least {OPEN_MAX} file and message queues. The oflag argument requests the desired receive and/or send access to the message queue. The requested access permission to receive messages or send messages shall be granted if the calling process would be granted read or write access, respectively, to an equivalently protected file. The value of oflag is the bitwise-inclusive OR of values from the following list. Applications shall specify exactly one of the first three values (access modes) below in the value of oflag: - O_RDONLY - Open the message queue for receiving messages. The process can use the returned message queue descriptor with mq_receive(), but not mq_send(). A message queue may be open multiple times in the same or different processes for receiving messages. - O_WRONLY - Open the queue for sending messages. The process can use the returned message queue descriptor with mq_send() but not mq_receive(). A message queue may be open multiple times in the same or different processes for sending messages. - O_RDWR - be specified in the value of oflag: - O_CREAT - Create a message queue. It requires two additional an mq_send() or mq_receive() waits for resources or messages that are not currently available, or fails with errno set to [EAGAIN]; see mq_send() and mq_receive() for details. The mq_open() function does not add or remove messages from the queue. Upon successful completion, the function shall return a message queue descriptor; otherwise, the function shall return (mqd_t)-1 and set errno to indicate the error. The mq_open() function shall fail if: - [EACCES] - The message queue exists and the permissions specified by oflag are denied, or the message queue does not exist and permission to create the message queue is denied. - [EEXIST] - O_CREAT and O_EXCL are set and the named message queue already exists. - [EINTR] - The mq_open() function was interrupted by a signal. - [EINVAL] - The mq_open() function is not supported for the given name. - [EINVAL] - O_CREAT was specified in oflag, the value of attr is not NULL, and either mq_maxmsg or mq_msgsize was less than or equal to zero. - [EMFILE] - Too many message queue descriptors or file descriptors are currently in use by this process. - [ENAMETOOLONG] - The length of the name argument exceeds {PATH_MAX} or a pathname component is longer than {NAME_MAX}. - [ENFILE] - Too many message queues are currently open in the system. - [ENOENT] - O_CREAT is not set and the named message queue does not exist. - [ENOSPC] - There is insufficient space for the creation of the new message queue. None. None. None. None. mq_close(), mq_getattr(), mq_receive(), mq_send(), mq_setattr(), mq_timedreceive(), mq_timedsend(), mq_unlink(), msgctl(), msgget(), msgrcv(), msgsnd(), the Base Definitions volume of IEEE Std 1003.1-2001, .
http://pubs.opengroup.org/onlinepubs/009604499/functions/mq_open.html
CC-MAIN-2014-41
refinedweb
652
61.26
Free Java Books Free Java Books Sams Teach Yourself Java 2 in 24 Hours As the author of computer books, I spend a lot...; Noble and Borders, observing the behavior of shoppers browsing through the books Struts Books ; Free Struts Books The Apache.... By the way, there are many more interesting books on the serverside... Many good books on the framework are now available, and the online Free JSP download Books Free JSP download Books Java Servlets and JSP free download books... optimization. The Professional JSP Books The JDC Java Programming Books As the author of computer books, I spend a lot of time loitering in the computer... the behavior of shoppers browsing through the books as if they were a hominid jawbone..., but I am not satisfied with the programs I have found to translate LaTeX to HTML Accessing database from JSP In This article I am going to discuss the connectivity from MYSQL database with JSP.we...' and 'author' columns from a table called 'books_details'. You then iterate through... Accessing database from JSP   Programming Books books and download these books for future reference. These Free Computer Books... Free Java Books Free JSP Books... Programming Books A Collection of Large number of Free Misc.Online Books when I was twenty-one. This is very subjective and, therefore.... Though I am not a computer scientist by education (my Ph.D.... Misc.Online Books   JSF Books JSF Books Introduction of JSF Books When we... were very excited. Both of us had extensive experience with client-side Java Free JSP Books Free JSP Books Download the following JSP books... servlets or JSP pages and can examine the request information going EJB Books Framework and Hibernate. I ll guide you through productive solutions to core problems... EJB Books Professional EJB Books Written Perl Programming Books chapters, but I am open to suggestions. I am looking for interesting... If you find this book useful, please contribute to the FSF through Affero. I work... Perl Programming Books   How can I access databse through JSP. I am using postgresql-8.4.4-1-windows as database and jboss-4.0.5.GA as server. How can I access databse through JSP. I am using postgresql-8.4.4-1-windows as database and jboss-4.0.5.GA as server. I am using postgresql-8.4.4-1... netbeans-6.1-ml-windows.How can I set up connection to database? Please help me Open Source Books , Free Java Download Free Java Download Hi, I am beginner in Java and trying to find the url to download Java. Can anyone provide me the url of Free Java Download ? Is Java free? Thanks Servlets Books ; Books : Java Servlet & JSP Cookbook... leading free servlet/JSP engines- Apache Tomcat, the JSWDK, and the Java Web Server... Servlets Books  ..., Please go through the following link: searching books searching books how to write a code for searching books in a library through jsp Free JSP Books Free JSP Books Web Server Java: Servlets and JSP This chapter covers Web Server Java... Insiders, all free, no registration required. If you are interested in links to JSP J2ME Books ; Free J2ME Books J2ME programming camp... a list of all the J2ME related books I know about. The computer industry is fast... started a very interesting project on the Source Forge. An open source book Java Free download Java Free download Hi, What is the url for downloading Java for free? Is java Free? Can I get the url to download Java without paying anything? Actually I am student and learning Java. I have to download and install Java on my Java XML Books ; Free Java XML Books... someone who knows Java 1.1 already and wants books to get them going with Swing... Programming, published by Wrox is one of the few XML books I have found which MySQL Books Balling, finally arrived from Amazon. There?s very few tech books I can read from... MySQL 4 While I am not new to databases, I am new to mysql and always spend.... The books review of MySQL administration tools and clients is very in depth Download file - JSP-Servlet Servlet download file from server I am looking for a Servlet download file example Download LINK - JSP-Servlet Download LINK sorry i am the new1 to java. I am learning and doing... easily. i want the code like by Clicking DOWNLOAD button the SAVE as dialog box should come asking for the DIRECTORY location to SAVE. Anyhow i Download Button - JSP-Servlet Download Button HI friends, This is my maiden question at this site. I am doing online banking project, in that i have "mini statement" link. And i want the Bank customers to DOWNLOAD the mini statement. Can any one help me VoIP Books VoIP Books VoIP Books Voice over IP With a potential 90 percent... there for making basic get-going decisions. This chapter explores some.... Practical VoIP Using VOCAL While many books describe the theory Need E-Books - JSP-Servlet Need E-Books Please i need a E-Book tutorial on PHP please kindly send this to me thanks JSP Tutorials database from JSP In This article I am going to discuss... and study it offline. Free JSP Books Download the following JSP books. Free JSP Download php download free php download free From where i download php free Free download java Free download java Hi, Where can I download java for absolutely free and quickly? Thanks how to call jsp variable through servlet how to call jsp variable through servlet Hi deepak; i am posting some peace of code. and i need to call jsp varable <%=f%> through servlet so... a hyperlink to call this downlode page like out.println("Download document"); when Free Web Hosting - Why Its not good Idea Free Web Hosting - Why Its not good Idea This article shows you why Free...; Free Web Hosting Service providers provide very little space for your...; Free Web Hosting Companies don't provide guaranteed uptime. Downtime through Introduction to the JSP Java Server Pages ; Accessing database fro JSP In This article I am going... it offline. Free JSP Books Download the following JSP books. Free JSP Download BooksFree Insert Image in DB through Servlet - JSP-Servlet through servlet.But Sir, I am using weblogic so I do not want the reference... my servlet file. Answers Hello I am Using java1.5 with MyEclipse... IOException{ RetriveImage ri = new RetriveImage(); } } Dear Sir, You give me: I am VoIP Books VoIP Books Practical VoIP book Using VOCAL While many books describe... the source code. Switching to VoIP Books More and more Insert Image In DB through Servlet - JSP-Servlet the image through servlet.But Sir, I am using weblogic so I do not want the reference... that work my servlet file. Hello I am Using java1.5 with MyEclipse...Insert Image In DB through Servlet Dear Sir, My previous Query Submit Articles for Free ; Links for submitting articles for free. Articles is very effective way... bid portfolio. Using the sessions from SES NY as a guideline, I?m going... & Listing of articles is Free! The All I Need Have accessing ms access through jsp accessing ms access through jsp i have 3 tables in my database employee,project,task if i put employee id the search field .i should get details from other table what all queries should i use in servlet file and i am using Java server Faces Books , it?s in very good condition and it?s quite ready for test-driving to understand... the third free by using code OPC10 in our shopping cart. This deal includes books... Java server Faces Books   < mahesh want to know java with good understanding mahesh want to know java with good understanding I need to know about java beans(what are java beans,why we use java beans, etc...).I want... information, go through the following links: java/jsp code to download a video java/jsp code to download a video how can i download a video using jsp/servlet XML Books for O'Reilly as an editor of this site, and that I know very little, if anything about... XML Books We're pleased to provide free sample chapters... XML Books   download - JSP-Servlet download here is the code in servlet for download a file. while...; /** * * @author saravana */ public class download extends HttpServlet... if an I/O error occurs */ @Override protected void doP  ... content authored by the JSP Insiders, all free, no registration required. If you... and services. Servlets and JSP technology is the foundation Oracle Books , these books are all being published because there really is a big demand for good... Oracle Books  ... Edge: "I enjoyed this book from the beginning 'til the end. The Oracle Edge, "Still Send forgot Password through mail - JSP-Servlet Send forgot Password through mail hello every one I am designing a admin login page where i am validating the password through file(Example... for that i am using (JSP)(using HTML and css for front design) IDE:Eclipse-3.2, App Struts Book - Popular Struts Books books out there where they give top-soil kind of overviews of the technology. I am very dissapointed in this book, as I purchased it thinking it would give real..., the Jakarta-Tomcat JSP/servlet container, and much more. Struts Books upload and download files - JSP-Servlet upload and download files HI!! how can I upload (more than 1 file) and download the files using jsp. Is any lib folders to be pasted? kindly... and download files in JSP visit to : C/C++ Programming Books and errors. A very large debt is owed to these folks, and I must especially thank... C/C++ Programming Books  ... an excellent job of presenting the subject in an interesting and engaging way jdbc connectivity through jsp jdbc connectivity through jsp my code: <%@ page language="java...----------------------------------------------- i got this error HTTP Status 500 - type... org.apache.jasper.JasperException: An exception occurred processing JSP page /mypage.jsp jsp jsp hai good morning all jsp beginner myself is sathishkumar i am developing a web application jsp. in this application i generate id card.how... = 000; for (int i=0;i<12;i++){ serialNo database through jsp database through jsp sir actually i want to retrieve the data from database dynamically.because i dont know how many records are there in the database? thanks Here is an example of jsp which retrieves data from Java Certification Books books, that I glanced through and could read only partially. But I ensured solving...; Java Certification Books The book I followed... a few files that I am working on available. You feedback on information How do i start to create Download Manager in Java - JSP-Servlet How do i start to create Download Manager in Java Can you tell me from where do i start to develop Download manager in java jsp jsp hello sir.....i am doing one web application project in which i... as for usercategory......how can i do it...plz hwlp me...its very urgent.............i have to give permission(priveledge) that submodule user does not have Downloading in JSP - JSP-Servlet Downloading in JSP Respected Sir/Madam, I am R.Ragavendran.. How are you roseindia team? I am having an irritative problem in my JSP... am getting the downloaded content when opened through the open/Save dialog box Why the null values are stored in Database when I am sending proper values? I am also sending the name, Rate, Dimension to the Database through the text...Why the null values are stored in Database when I am sending proper values? I am making a project in which I am sending the image into a folder & Insert Image in DB through Servlet - JSP-Servlet Insert Image in DB through Servlet Dear Sir, I am not able to solve my problem cocerning Inserting the image in Database through Servlet. I am usng... /get Home.html I also used this web.xml instead of above...(); response.getOutputStream().flush(); %> Thanks I want to download a file............ Now to download the word document file, try the following code Free GPS Software mapping, GPS tracking, packet radio, etc. It is a VERY interesting facet... I took a look at some of the online offers for free GPS software and found... 100 waypoints and 500 track points. The free program gives you a good Ruby Books , very-OO, small, well ported scripting language with a good class library. I'm... Ruby Books  ... program at the University of Waterloo. I have observed that the advent of.... my question is I want to call that jasper file through my jsp code and i also Free PC to PC VoIP Providers telephony service through which you can make calls to other Babblers for free.... 7 Day Free Trial Try it for FREE Download 3WTel Softphone now for a Free 7.../Desktop Dialer ? Download our free dialer and make calls from your own PC.  Advertisements If you enjoyed this post then why not add us on Google+? Add us to your Circles
http://roseindia.net/tutorialhelp/comment/11719
CC-MAIN-2016-18
refinedweb
2,186
75.1
As we have discussed in one of our previous posts Layouts in android layouts are the containers that hold the components of UI that you want to display in your application. When you compile your application,each xml layout file is compiled into a View resource. This tutorial describes how you can add a layout file to a newly created activity. also read: To create a layout file, follow the steps: - Open eclipse (Read: how to setup android in eclipse?) - File->New->Android XML File - The above steps open up the below window Once you fill up all required details in the above screen click on “Finish” button. This creates your layout xml file in res/layout directory. The initial code of the created layout “layout_first_activity.xml” is as below. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:</a>" android: </LinearLayout> When you create a layout file,by default it contains only one linear layout. You have to add views that you want to display in your activity. Adding Views to a layout File Add the views that you want to display in your Activity. Lets now add a Textview and a Button. You can find the below pane called outline when you create a layout. If you don’t find it open window->Show View->Outline click on the highlighted “+” symbol to create new views. This takes you to the below screen. Select the view that you want to add. I have selected textView. Then click “OK” button. Let us now add a button to our layout file. Again click on the “+” symbol in the outline pane to add a button and select the button and click “OK” to add it. Then your “layout_first_activity” file contains a LinearLayout which inturn contains a textview and a button. The structure of the layout file as seen in the outline is as below: You can always remove the view that you have added by clicking on the “-” symbol present on right side of the “+” symbol. To view the layout that you have created before you run the project, select the layout section in your layout window. Edit the properties of the Views in your layout file Edit the properties of the newly created views. To the Edit the properties of a particular view, double click on that view which opens up a pane called “Properties”. Lets us edit the Textview text as “Hi you are in first activity”. The property Window is as below. Double click on the Button view to Edit the properties of the button.Let us edit the text property of the button to “Click to Navigate”. You can customize your views by editing various properties present in the Property pane. For example: text size,Text color, orientation of the views etc. By default when you add views to your linear layout the orientation will be “Horizontal”. Now change the Orientation property of the LinearLayout to vertical. The layout code after editing the required property values is as below. <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:</a>" android: <TextView android: </TextView> <Button android: </Button> </LinearLayout> You should load the created layout file from your application code,in your Activity.onCreate() callback implementation. You can do that by calling setContentview(), passing it the reference to your layout file in the form of R.layout.layouy_first_activity. The code of your activity is as below. package my.app; import android.app.Activity; import android.content.Intent; import android.os.Bundle; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; public class First_activity extends Activity { /** Called when the activity is first created. */ @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.layout_first_activity); } } Now run your application. The output is as below. This is how you can create a layout xml file in android. If you have any queries,please post in it comment section. also read: Speak Your Mind
http://www.javabeat.net/how-to-create-a-layout-xml-file-in-android/
CC-MAIN-2014-41
refinedweb
656
59.3
- Convert console sorting program to GUI? - Linking error LNK2019: unresolved external symbol - New to Visual Studio 2008 - calculator program error - switch memory locs with 2 lines of code - Controlling precision after E in sci notation - Pointer and Structure question... - switch-case,Infinite while-loop ,break - is this possible ? - possible reasons wstring is out of sync with _Bx? - Execution Time - Rijandael encryption - map or vector, which is less performant and by how much? - [Psuedo] Selling thingy - /= doesn't do what you think it does? - global variable and prototype - Password Checker - declared extra variable, is it wrong? - Making A Queue - Class with a pointer to itself - Boolean exercise that needs help with - C++) How would I display a value rounded to the nearest integer? - Selection sort on a vector - Including headers in a header file - How to make this "for loop" - Linked Lists and Classes - Overloading [] operator - error C1010: unexpected end of file while looking for precompiled header. - Check if variable is integer - Class constructor - return 0 to main from within a function, is this possible? - Queue with templates - Net cpu usage of pthreads?! - C++ Simple Puzzle Word Game - Thoughts about using namespace std? - convert numbers to words - Swap values inside of a vector ? - Class Inheritance - Error window o _ o' - Loop trouble - Class + Main() = error cout? - warning: deprecated conversion from string constant to 'char*' - visual c++ 2005 express edition compiler - Birthstones, Months, Strings and Functions! - Please Help Me with this beginner C++ Program! - Function name basic question help - Sockets or GUI API? - Tic Tac Toe Comp Move help - operator overloading - locking actions to special threads
https://cboard.cprogramming.com/archive/index.php/f-3-p-725.html?s=b079768fd3ada671bcc5c333af135538
CC-MAIN-2017-30
refinedweb
264
56.86
Using Linq to query RavenDB indexes As we have already seen in the previous chapter, querying is made on a collection and using the Session object. Unless the user specifies what index to query explicitly, RavenDB will find an appropriate index to query, or create it on the fly if one does not already exist. We will see how to create named indexes, also called static, later in this chapter. Regardless of the index being actually queried, querying is usually done using Linq. The built-in Linq provider implements the IQueryable interface in full. Its job is to automatically translates any Linq query into a Lucene query understandable by the RavenDB server, handling all the low-level details for you. Therefore, querying RavenDB is easy to anyone who has used Linq before; if you're not familiar with Linq, the following is a brief tutorial on how to use it to query RavenDB. Assuming we have entities of the following types stored in our database: public class Employee { public string Name { get; set; } public string[] Specialties { get; set; } public DateTime HiredAt { get; set; } public double HourlyRate { get; set; } } public class Company { public string Id { get; set; } public string Name { get; set; } public List<Employee> Employees { get; set; } public string Country { get; set; } public int NumberOfHappyCustomers { get; set; } } Let's see how we can use Linq to easily query for data in various scenarios. We will not cover all Linq's features, but will highlight several which are important to be familiar with. Some basics Say we wanted to get all entities of type Company into a List, how would we go about that? Ignoring for now the performance hit of loading a large bulk of data, we could do this pretty easily (note that this query is implicitly using Take(128), because it didn't specify a page size explicitly): var results = ( from company in session.Query<Company>() select company ) .ToArray(); Since the whole idea of using Linq here is to apply some filtering in an efficient manner, we can use Linq's where clause to do this for us: // Filtering by string comparison on a property var results = from company in session.Query<Company>() where company.Name == "Hibernating Rhinos" select company; // Numeric property range results = from company in session.Query<Company>() where company.NumberOfHappyCustomers > 100 select company; // Filtering based on a nested (calculated) property results = from company in session.Query<Company>() where company.Employees.Count > 10 select company; Note, however, Linq is just a syntactic sugar. Under the hood, all queries are transformed into a sequence of method calls and lambda expressions. For example, the above code snippet is re-written by the compiler to look like the following before compiling: // Filtering by string comparison on a property var results = session.Query<Company>() .Where(x => x.Name == "Hibernating Rhinos"); // Numeric property comparison results = session.Query<Company>() .Where(x => x.NumberOfHappyCustomers > 100); // Filtering based on a nested property results = session.Query<Company>() .Where(x => x.Employees.Count > 10); All throughout the documentation we are going to use both flavors interchangeably, and we refer to both as Linq. One more thing to note before we go any further - all queries shown above, except from the first one, perform no actual querying even though they are well defined. The reason for this is that the Linq provider, by nature, does not perform any querying unless it is forced to. The call to ToArray() in the first snippet did just that, and by that triggered the execution of the query. More filtering options Other than the Where clause, there are several other useful operators you could use to filter results. Any can be used on collections of objects (or primitive lists) in your entities to return only those who satisfies a condition. RavenDB also supports an In operator, to make reverse Any comparisons easier: // Return only companies having at least one employee named "Ayende" IQueryable<Company> companies = from c in session.Query<Company>() where c.Employees.Any(employee => employee.Name == "Ayende") select c; // Query on nested collections - will return any company with at least one developer // whose specialty is in C# companies = from c in session.Query<Company>() where c.Employees.Any(x => x.Specialties.Any(sp => sp == "C#")) select c; // Using the In operator - return entities whose a field value is in a provided list companies = from c in session.Query<Company>() where c.Country.In(new [] {"Israel", "USA"}) select c; Projections Projections are specific fields projected from documents using the Linq Select method, they are not the original object but a new object that is being created on the fly and populated with results gathered by the query. RavenDB Linq queries support projections, but its important to know that projected entities are not being tracked for changes. That is true even if the projected type is a named type (and not just an anonymous type). Here is how to use projections: // In this sample, we are only interested in the names of the companies satisfying // our query conditions, so we project those only into an anonymous object. var companyNames = from c in session.Query<Company>() where c.Employees.Any(x => x.Specialties.Any(sp => sp == "C#")) select new {c.Name}; // This is where the projection happens // Same query same idea, but this time we want to get results as objects of type Company. // Only the Name property will be populated, the rest will remain empty. Company[] companies = (from c in session.Query<Company>() where c.Employees.Any(x => x.Specialties.Any(sp => sp == "C#")) select new Company {Name = c.Name}) // This is where the projection happens .ToArray(); Projections are useful when only part of the data is needed for your operation. Whenever change tracking isn't required, you're advised to consider using projections to ease bandwidth traffic between you and the server. This isn't a general rule, because caching in the entire application also plays an important role here, and it might make it more efficient to load the cache results of a query than to issue a remote query for a projection. You can also use the Distinct method to only return distinct results from the server. When using projections, that means that on the server side, the database will compare all the projected fields for each object, and send us only unique results. If you aren't using projections, this has no effect but causing the server to do more work. Sorting You can use the orderby / .OrderBy() / .OrderByDescending() clauses to perform sorting. As we will see in a later chapter, more advanced sorting options are supported using static indexes. Aggregate operators RavenDB only supports the Count and Distinct Linq aggregate operators. For more complex aggregations, you'll need to make use of Map/Reduce indexes. Similarly, the SelectMany, GroupBy and Join operators are not supported. Such operations should be made through a Map/Reduce index, and not while querying. The let keyword is not supported currently.
https://ravendb.net/docs/article-page/1.0/csharp/client-api/querying/using-linq-to-query-ravendb
CC-MAIN-2017-30
refinedweb
1,160
53.81
Code Quality Assistance Tips and Tricks, or How to Make Your Code Look Pretty? In this section: - What this tutorial is about - Before you start - Highliting code style violations - Tuning the PEP8 inspections - Tracking PEP8 rules - Code inspections and their settings - Highlighting errors - Generating source code - Reformatting code - Adding documentation comments - Type hinting. Python programming is out of scope of this tutorial. To learn more about the Python language, please refer to the official website. Before you start Make sure that: - You are working with PyCharm version 5.0 or later. If you still do not have PyCharm, download it from this page. To install PyCharm, follow the instructions, depending on your platform. Refer to the product documentation for details. - You have created a Python project (). Refer to the product documentation for details - You have created two directories srcand test_dir( or Alt+Insert). To learn about creating directories, refer to the product documentation. - You have added Python files to the srcand test_dirdirectories of your project( description ( main toolbar, - Inspections), you will see that PyCharm launches the pep8.py tool on your code, and pinpoints the code style violations. Code inspections and their settings Btw, look at the Inspections, in the Settings/Preferences dialog box expand the node Appearance and Behavior, include In All Scopes button and select the Test scope from the list; repeat same for the Production scope In the scope "Test", the inspection severity is left as is (a typo); however, Project Default (copy), and it has different settings for the Spelling inspection in the Test and Production scopes. Next, let's inspect code against this profile. To do that, choose on the main menu, and in the dialog box, choose the desired profile and scope: Do it twice - for Test and Production scopes (if you want to preserve inspection results for further examination and sharing, you can export them). Explore results: product documentation. Anyway, you can change the error highlighting with some aid from Hector. Generating source code PyCharm provides lots of possibilities to automatically generate code. You can explore the auto-generation features in the product documentation.: import math class Solver(object): def demo(self,a,b,c): d = b ** 2 - 4 * a * c disc = math.sqrt(d) root1 = (- b + disc) / (2 * a) root2 = (- b - disc) / (2 * a) print (root1, root2) return root1, root2, and press Ctrl+Alt+T (or choose on the main menu): formatting of the entire file. To do that, press Ctrl+Alt+L (or choose on the main menu): Look at the code now - the PEP8-related drawbacks are all gone. Note that you can define formatting rules yourself. To do that, open the code style settings, select language (in this case, Python), and make the necessary changes: Adding documentation comments OK, formatting is fixed now, but there are still some stripes left. The inevitable yellow light bulb shows the possibility to add a docstring comment: Choose this suggestion and see the docstring comment for a certain parameter added: Note that you have to select the check box Insert type placeholders in documentation comment strings in the Smart Keys page of the Editor settings: There are several docstring formats, and the documentation comments are created in the format, which you have selected in the Python Integrated Tools page. If you so wish, you can change the docstring format to, say, invocation, you see that the wrong parameter is highlighted by the PyCharm's inspection Type Checker: Learn more about type hinting in the PyCharm documentation.
https://www.jetbrains.com/help/pycharm/2016.3/code-quality-assistance-tips-and-tricks-or-how-to-make-your-code-look-pretty.html
CC-MAIN-2017-22
refinedweb
583
59.53
Suppose you have an existing COM component implemented in VC++ or VB. You have been using it in your desktop applications without any problem. Now you need the same functionality in your .NET projects. You could spend time to reimplement the component using C# or VB.NET but sometimes this approach is not always an ideal one. For example, there could be a lot of Win32 API calls or calls to some other third-party C library in the old version, it might not be easily implemented using C#. Even worse, the component could be written by someone else who already left the company (and took the expertise with him), or it could be a third-party component with no source code. Fortunately, it is not hard to use COM components directly in .NET projects. There have been some good articles talking about this, I just want to briefly summarize what you have to do in order to use a COM component from .NET projects: First you need to install and register the COM component, then you need to add a reference to the COM component in your .NET projects. .NET will automatically generate a "wrapper" dll for you. Let's see a simple example. I have included with this article a DummyCom.dll written with VC++/ATL which implements a simple COM object called DummyObj. This COM object has only one method called Test. The method takes an input string and returns an output string. The output string indicates the date/time the object was created and the date/time the method was called as well as the input string passed into the method. Here is C# sample code that calls the Test method of DummyObj. using DUMMYCOMLIB; ... DummyObj obj = new DummyObj(); String sOutput = obj.Test("this is a test"); ... Here is what the output string looks like: Object created at '2003-06-13, 11:06:18' 'Test' method called at '2003-06-13, 11:06:18' with input 'this is a test' If it was always this easy then I wouldn't need to write this article. There are some potential problems which I will try to address below. Ok, that's easy. All we have to do is use a static member variable of the current class to hold the COM object and use it in all web requests. In case you don't know, the static (or Shared for VB.NET) keyword means that this member variable is global and you don't need to create an instance of the class in order to access it. There are still problems with this approach, however. First of all, the COM object in question may not be thread-safe at the instance level. If multiple web requests are using the same instance, it may crash the server machine. Secondly, even if the COM obj is thread-safe, the performance may be bad if there is only one instance to serve all web requests. For example, the threading model for the COM object may be "apartment", which implies that only one thread can use it at any given time, all the other threads will have to wait for their turn. Apparently, we need a different approach to solve these problems ASP.NET applications and ASP.NET web services use a thread pool to serve client requests. The threads in the pool will be reused for multiple requests. The number of threads in the pool will increase only when the number of simultaneous client requests increases. My solution to the above problems is create only one instance of the COM object for each thread. With my solution, the object instance for the current thread is created the first time it is needed. It is assigned a name at the time of creation and later the name string can be used to retrieve the instance for reuse. ObjMan is a VB.NET class contained in ObjectManager.dll. Here is a static method of ObjMan that is used to create and retrieve a COM object. Public Shared Function GetComObject(ByVal sObjName As String, _ ByVal sProgID As String, ByVal sServerName As String) As Object The sObjName parameter is a user assigned name string to identify the COM object. The sProgID parameter is the prog id of the COM object. The sServerName parameter (optional) is used for creating the COM object on a remote server. The return value is a reference to the COM object for the current thread. Here is sample C# code that calls this method. using DUMMYCOMLib; ... DummyObj obj = (DummyObj)ObjectManager.ObjMan.GetComObject("MyObjName", "DummyObj.1"); OutputBox.Text = obj.Test(InputBox.Text); // ObjectManager.ObjMan.RemoveComObject("MyObjName"); ...When the above code is executed by threads in a thread pool, COM object DummyObj will be created only once for each thread. The GetComObjectmethod will retrieve an existing instance if one is already created by a previous attempt within the same thread. The method RemoveComObject is used to get rid of the COM object created by GetComObject. If you uncomment the last line of code in the above sample, then DummyObj will be created every time the code is executed. Please note that RemoveComObject only removes the COM object with given name for the current thread. You cannot create the COM object by calling GetComObject in one thread and remove it from a different thread using RemoveComObject . It is possible to create and use multiple instances of a COM object in the same thread as long as you give them different names. The implementation of the ObjMan class is simple and straightforward. Internally, the ObjMan class uses a hashtable to store data ( Hashtable is my favorite .NET class, by the way). The key string for an object in the hashtable is the name of the thread. Each object in the hashtable is itself a hashtable for the corresponding thread. So all COM objects created in a thread are stored in a single child hashtable. The key string for an object in the child hashtable is the sObjName parameter in the GetComObject method. ObjManclass) and the ObjectManagerTest project (an ASP.NET test program). Here is how to install and run everything: General News Question Answer Joke Rant Admin
http://www.codeproject.com/KB/COM/objman.aspx
crawl-002
refinedweb
1,034
64.51
Hi, I'm not good in developpment and I need help for using the barcode and execute a barcode scan in C#. I have not enough skills for understand and perform alone. I would like to make a simple form where with one button I can perform a scan. In this form I would like get data in a rich text box, and the type in a text box. I tried to do something like that but it's not complete. I need to know the correct syntax for: - Get the type - get the data To put the data and the type in a tring I can display in a rich text box and a textbox. If anybody can help it will be great: using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; using System.Drawing; using System.Text; using System.Windows.Forms; using Intel.Healthcare; using Intel.Healthcare.Device; using Intel.Healthcare.Exception; namespace Uniform { public partial class Form1 : Form { public Form1() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { //Create a BarcodeReader object. BarcodeReader bcReader; string a; bcReader = new BarcodeReader(); bcReader.ReserveDevice(); bcReader.StartScan(); bcReader.WaitForBarcode(5000); Barcodes barcodeList = bcReader. // I think it's not good bcReader.Barcodes.GetType(a); // I think it's not good again bcReader.Barcodes.ToString(a); // I think it's not good again and I don't know what to write :( bcReader.StopScan(); bcReader.ReleaseDevice(); textBox1.Text = a; } Thanks to read me. How use the barcode with C# How use the barcode with C# Hi, Icarius, Have you looked at the Developers Guide for help in performing this function. The Guide is full of examples that you might find useful. The Guide is located at This should get you going in the right direction. John C Hello Icarius, the Barcode Scan Process delivers a list of barcodes. bcReader.StartScan(); bcReader.WaitForBarcode(5000); After such a process you should do this: barcodes = bcReader.Barcodes; // barcodes is the list/collection of barcodes //Loop through each barcode in the collection foreach (Barcode barcode in barcodes) { string[] barcodeStr = new string[2]; barcodeStr[0] = barcode.Type.ToString(); barcodeStr[1] = barcode.Value; // Now you can put barcodeStr[0] into a textbox } This is mainly the example from IntelMCAExamplesCSharpBarcodeDemoNet. I hope this helps Greetings Markster Excellent !!! It's working. I adapt your proposal in ordert to use it, that's perfect. I do have one more question. Then I try the same thing for Rfid I've got a problem : foreach (RfidTag tag in objReader.RfidTags) { string[] rfidStr = new string[2]; rfidStr[0] = tag.Id.ToString(); rfidStr[1] = tag.Data.ToString(); ; // On peut dsormais placer les donnes issues des codes barres dans des controles avec du texte. label3.Text = ("ID"); label3.Visible = true; label4.Visible = true; textBox1.Text = rfidStr[0]; richTextBox1.Visible = true; richTextBox1.Text = rfidStr[1]; } And when it's running at the display I have "System.Byte[]" in the richTextBox1 Any ideas ? The follwing link will resolve your problem:- I dont see how the link would resolve the problem at hand. Can you pleae elaborate more or give more guidance - sorry but I am very technial savy here.Thank you,clothes fashion korean wholesale fashion fashion wholesale fashion models garment. Movie film phim phim online viet entertainment phim han quoc drama clips it is easy to add barcode functionality into your c#.net projects. refer to the barcode guide in C#.
http://software.intel.com/it-it/forums/topic/301717
CC-MAIN-2013-20
refinedweb
566
61.22
JavaScript Comment JavaScript Comment: coding to hide all those statements, which are not supposed to run. Comment make.... Example 1: <html> <head> <title>My Firt JavaScript File <Boss Unix and Line Separ JBoss and Sevlet - JSP-Servlet IsItWorking /gg/servlets I have JBoss installed and put my gg.war into G...JBoss and Sevlet I am trying to get familar with JBoss. I package up...\ ) IsItWorking.class ( in gg\WEB-INF\classes\ ) web.xml (in gg\WEB-INF\ ) My web.xml Struts - Jboss - I-Report - Struts Struts - Jboss - I-Report Hi i am a beginner in Java programming and in my application i wanted to generate a report (based on database) using Struts, Jboss , I Report COMMENT & HIDDEN COMMENT IN JSP COMMENT & HIDDEN COMMENT IN JSP In this section , we will learn how to implements comment & hidden comment in JSP. COMMENT : Comment generates a comment that is sent to the client. The comment use in JSP is very similar Moving projects from tomcat-6.0 to jboss 5.0.1 GA thing in that file for going to jboss? This is my current pom.xml file. <...Moving projects from tomcat-6.0 to jboss 5.0.1 GA Now i am using tomcat server version6.0 for my project. Now i want to change the server from JavaScript Comment Tag JavaScript Comment Tag How to write comment in JavaScript How to comment javascript code? How to comment javascript code? How to comment javascript code javascript comment syntax html javascript comment syntax html javascript comment syntax html all comment in jsp all comment in jsp Defined all comment in jsp ? jsp support two type comment : JSP comment and HTML comment JSP Comment: <%-- comment text --%> this is the format of the JSP comments specified in the JSP... the HiberNate-3 to this above Environment. so my doubt is 1) What are the jars JBOSS Startup Problem - StandardWrapper.Throwable java.lang.NullPointerException at java.util.Hashtable.put(Hashtable.java:394) database. i have downloaded the JBOSS war file and extracted in to my local machine. And i setted my JVAHOME as "C:\Program Files\Java\jdk1.6.010" and JBOSS_HOME...JBOSS Startup Problem - StandardWrapper.Throwable My Eclipse deployed problem. - Struts My Eclipse deployed problem. Dear All, I am facing a problem. When First time I am deploying a web project in eclipse in jboss its fine but, when I am changing the project name by pressing 'f2' and then deploying HTML5 comment tag Example, Definition of <!-- --> comment tag. HTML5 comment tag Example,, Definition of <!-- --> comment tag. In this tutorial, we will introduce you to the <!-- --> comment tag of HTML5. This tag is used to insert the comment inside the source code. The text how to install jboss drools how to install jboss drools how to install jboss drools HOW TO CREATE COMMENT IN WEBSITE AND CONNECT TO DATABASE? HOW TO CREATE COMMENT IN WEBSITE AND CONNECT TO DATABASE? HOW TO CREATE COMMENT IN WEBSITE AND CONNECT TO DATABASE JBoss Application Server Start Failed. HTTP Connector port 8080 is already in use. JBoss Application Server Start Failed. HTTP Connector port 8080 is already...:\Paritosh\My JSP\WebApplication1\dist Building jar: D:\Paritosh\My JSP\WebApplication1\dist\WebApplication1.war Starting JBoss Application Server JBoss JavaFX deployment in Jboss JavaFX deployment in Jboss Hi, How to deploy javafx application into JBoss about jboss - Java Beginners about jboss can you please explain about jboss...how to deploy,where the temp and lock is there...total information about jboss to use in java message services(JMS Use of Comment Function in PHP ;; /* * This * is * called * Multiple * Line * comment*/ echo "This is not a comment"; ?> Output: This is not a comment Excel Cell Comment Excel Cell Comment In this section, you will learn how to add a comment with a excel cell using Apache POI API. A comment is associated with a cell. It is a rich text note. The comment will be showing separately in rectangular text Jboss related linkage error Jboss related linkage error Please check below error when i run in jboss java.lang.LinkageError: loader constraint violation in interface itable... loader (instance of org/jboss/classloader/spi/base/BaseClassLoader What is JBoss Welcome to the Jboss 3.0 Tutorial  ... the web application on JBoss 3.0 Server. This example shows you how to write...;session <display-name>My Test Session developing a Session Bean and a Servlet and deploy the web application on JBoss 3.0 and deploy the web application on JBoss 3.0 Server. Our application is thin...;test_MyTestSession"> <display-name>My Test Session Bean<...;1.0" encoding="UTF-8"?> <!DOCTYPE jboss PUBLIC " can't read my xml file in java can't read my xml file in java i've a xml file like this : <..._COMMENT> //nothing ... in this row and my some java codes...("C_COMMENT")).append("<br>"); htmlFormat.append("<b> Problem to print from my properties file - Java Server Faces Questions it with JBOSS application server, by my navigator it shows MISSING:titreAchat.... Thanks hi thank u for your answer, I just restart my jboss...Problem to print from my properties file Hi, I am a new user Insert a Processing Instruction and a Comment Node Insert a Processing Instruction and a Comment Node  ... a Processing Node and Comment Node in a DOM document. JAXP (Java API for XML... an instance of an XMLDOMElement. Comment c = doc.createComment(" Problem to print from my properties file - Java Server Faces Questions it with JBOSS application server, by my navigator it shows MISSING:titreAchat...Problem to print from my properties file Hi, I am a new user of this site. It is very interesting. So this is my problem: I have a jsp file Capturing JSP Content Within My Strut Action Servlet - JSP-Servlet Capturing JSP Content Within My Strut Action Servlet My end goal... to manipulate the html that was brought back. My company gave me.... I found this code online and it works great in JBoss and Tomcat, but fails My SQL My SQL Connection class for MySQL in java my question my question "Write a C/C++ program to show the stored procedure PROCRESETMAIL" on database "USER_NOTIFY my project my project how to creat a e learnig site with student information , faculty details , student queries , student feedback, course information my assignment my assignment as programmer, you have been assigned to develop a user interface for a fats food ordering system.the interface should have various......this is my assignment....plz my answer my answer import com.mysql.jdbc.Connection; import com.mysql.jdbc.Statement; import java.io.IOException; import java.io.PrintWriter; import java.sql.DriverManager; import java.sql.ResultSet; import My-BIC My-BIC This is a basic state of mind system rather than a framework Allows you to focus on making things happen rather than setting things up Support for XML, JSON and TEXT ajax How can I to my database to my application How can I to my database to my application How can I to my database to my application Hi, Please see the JDBC discussion thread. Thanks Creates element node, attribute node, comment node, processing instruction and a CDATA section Creates element node, attribute node, comment node, processing...; This Example shows you how to Create an Element node ,Comment node.... Comment node = doc.createComment("Comment for company" Average Age of my Class? Average Age of my Class? average age of my special characters in my HTML special characters in my HTML How do I get special characters in my HTML display an image on my page display an image on my page How can I display an image on my page interpreted as part of my document interpreted as part of my document How can I show HTML examples without them being interpreted as part of my document My jasper Report My jasper Report I can now retrieve information from my database to my jasper Report, But as soon as i close the Report form, the entire desktop window will also be close. i want your help please to know my answer to know my answer hi, this is pinki, i can't solve my question "how to change rupee to dollar,pound and viceversa using wrapper class in java." will u help me my question - EJB my question is it possiable to create web application using java beans & EJB's with out implementing Servlets and jsps in that java beans and EJB java not run on my pc java not run on my pc i have installed java in pc but when i run and compile any program the massage is display that 'javac' is not recognized as an internal or external command my sql innodb my sql innodb Write a java program that connects to a MySQL server and checks if the InnoDB plug-in is installed on it. If so, your program should print the total number of disk writes by MySQL
http://www.roseindia.net/tutorialhelp/comment/83900
CC-MAIN-2014-41
refinedweb
1,489
64.81
Talk:COSMOS Design 197868 Contents General Comments - Domain is used only for boot strapping. It's primary purpose is to hold onto a well defined set of EPRs. The EPRs will be made available via resource properties. - The following resource properties should be available: DataBroker - Is the assembly necessary? - Can we simplify the domain to remove the assembly? - Why do we need to persist the contents of the domain? - Why does domain extend abstract query? - Use the wsdm tooling to create the endpoint. - We need to reorganize the code to separate the domain from the broker to maximize deployment options Using WS-RF The design and the class diagram seem to be out of sync. For example, the class diagram indicates that the ManagementDomain will have a property called "dataBroker". There is only one of these. However, the operations, et. in the design indicate that there could not only be multiple databrokers w/in a domain, but also a "service brokers". The reason behind the domain is to provide a single place for a DataManager to go and get the other infrastructure components it needs. Because the Domain will be a WSDM endpoint, the DataBroker can simply use the "getResourceProperty()" method. No additional API should be required. Events/Topics What events will the Domain either emit or subscribe to? Metadata Exchange What is expected when we do a MEX with the Domain? Who does it and under what circumstances? Does the Domain need to support MEX? WSDM Capabilities "Identity" What is the URI of the Domain? - The base URI and namespace for the domain will be: How do we identify it? What should be returned when the WSDM identity property is asked for? Operational Status The Domain, Broker, and MDRs should support the Operational Status capability. See // make sure the broker is loaded... DataBrokerClient.loadDataBrokerContext( brokerHostAddress, runtimePort); This should be replaced with an operational status query. - ManagementDomain.pingManagementDomain() should be replaced Testing - update org.eclipse.cosmos.dc.tests to include the junits (will need to convert to tptp test framework) All other thoughts... - Where do we get the "classifications"? See DataBrokerTests.testDataBrokerClient() This references something called "Performance" as a classification. Bill's comments Regarding persistence, consider the following scenario: - 1. Domain initializes - 2. Broker initializes and registers itself with the Domain - 3. Clients can locate the Broker thru the Domain successfully - 4. Domain is shutdown for maintenance (or crashes) and is restarted - 5. New Clients attempt to locate the Broker - 5a. with Domain persistence, the new clients can successfully locate the Broker thru the Domain - 5b. without Domain persistence, the new clients will fail to locate the Broker (because the Broker registration in the Domain was lost during step 4) A similar scenario applies to the Broker and Data Manager. The benefit of persistence is that it adds resilence to both the Domain and Broker components. <mdw> I agree with the general concept that adding persistence in the broker and domain may improve the qualities of service that we offer. The issue I raised is that we have not completely thought through these scenarios. For example, what is the difference b/t initialization of the domain vs. recovery of a crash? How do we know this? What are the "initialization" steps of the domain (and by extension broker). These are undefined at this point. Given where we are, let's just write a file down. We won't have to worry about sql, jdbc, db schema, et. All we have to do is serialize the EPRs. This would allow you to use notepad for system initialization. The initialization scenario is like this: read the file and inflate the EPRs. We would end up with the Domain being a subclass of Object. It would have a single property, dataBroker. The property could be either a string or a muse EPR. We'd have the following methods: initialize() //reads the file persist() //writes it's contents To me, this is the most simple thing we can do and is all we need at this point. </mdw> <bill> although using a simple file sounds trivial, it introduces some issues: a. Security is relegated to OS file permissions. (A database has built-in security) b. Concurrency must be enforced in the code: updates require code to lock the entire file, impeding scalability. (A database can use row level locking and transactions to allow read/write concurrency) c. a file is more vulnerable to corruption. (A database has built-in recovery mechanisms) d. a file requires serialization/deserialization code. (iBatis alleviates the need for sql and jdbc code to use the database) </bill> The assembly is necessary for the DC runtime to generate the WSDM endpoint (it extends abstractquery because its a query assembly). <mdw>The real issue is whether the Domain should be a query assembly. I think the Domain (and Broker) are subclasses of something much more simple, e.g. Object, not abstractquery. If we choose to persist the contents of the domain, we may choose to use an assembly, but that should not be required. We can add a wsdm endpoint onto anything, we don't need an assembly for for this. </mdw> Does the DC runtime currently have the ability to use the WSDM tooling to generate WSDM endpoints from a POJO? If yes, I missed this in the code (please show me where and how). If no, then we need an ER to add this ability as a prerequisite for this proposal. <mdw> Short answer: yes. Longer answer..... I think we need to separate out some concepts here. The DC runtime is a framework for accessing and transforming data from a database. It introduced the notion of a container to help manage itself. WSDM is a pattern of exposing stateful resources and their management through web services. Right now, assemblies are the king of everything and everything they do is exposed as its own resource--through the annotations. This is another area where I think we can simplify by encapsulating the assemblies inside the Data Manager. I think the assemblies should be an optional component, not a required one. The result is that the annotation work that we have in COSMOS blends the two things together in a way that sometimes confuses and obfuscates the architectural layers. It's difficult to separate the framework from the implementations of the framework, from the remote layer. The way the WSDM tooling works is that you define the endpoint that you want to expose, then bind it to an implementation. The layers are very clear when you do this b/c of the way things are generated. So.... To expose the DC components, you would start by defining the capabilities (a.k.a. remote interfaces) that you want, then, through the deployment descriptor, bind them to the implementation classes that we've coded up. We have a number of enhancement requests to reconcile these two things and establish when it's appropriate to use annotations vs. a "wrapper". Both have their advantages/disadvantages, but in general, I'd like to bring these things closer together. That's one reason for bringing in the WSDM tooling. One key thing about using the wrapper approach is that it's very clear what you are doing and how things work. I'd like to start moving more towards this approach. </mdw> The classification values are defined by the Brokers themselves during registration. For example, we may have Data Brokers and Service Brokers. The same applies to the Data Managers (they define their classification values during registration with the Broker). <mdw> Right now, in i7 & i8, we have only data brokers. In fact, only a data broker. So while I agree there could be other services that the framework offers, I think it's premature to define the classification scheme. It seems like another piece of complexity that for i7 & i8, we could eliminate. </mdw> Last, I think we already have the operational status capability. <mdw> Great! </mdw> <bill> The wrapper approach sounds like an interesting implementation alternative. It's independent of the file vs. database issue. And the internal implementation is encapsulated behind the external client API. I suggest that we wait until the wrapper approach evolves from an ER into a concrete design and then revisit this suggestion. </bill>
http://wiki.eclipse.org/Talk:COSMOS_Design_197868
CC-MAIN-2017-22
refinedweb
1,384
58.18
Knowing the current state of an app is crucial for a variety of reasons, most notably memory management. Constant updates to an app’s state can consume a lot of energy, and sometimes it’s better to pause them when the user is not interacting with the app. This is where the React Native AppState API comes in. AppState tells you when an app is inactive or in the background so you can stop nonessential processes, save memory, and improve the performance of your React Native app. In this tutorial, we’ll introduce you to AppState and demonstrate how it works by walking through a simple example. What is AppState in React Native? In React Native, AppState represents the current state of the app — i.e., whether the app is in the foreground or background. AppState is useful for collecting data on app usage — for example, the time a user spends in the app before putting it in the background or closing the app. Analyzing this data helps you understand the way users interact with your app so you can make changes if necessary to boost engagement. There are countless SDKs designed to help you generate this type of insight, but AppState enables you to monitor state changes on your own without relying on any third-party tools. What is AppState used for? As stated above, AppState is most commonly used for memory management and user status management. Let’s dive deeper and see how it figures into these important tasks. Memory management AppState can help you avoid unnecessary state changes when the user is not interacting with an app. It’s a good practice to create an isMounted property that changes according to the state of the app. If we take class components into consideration, isMounted is set to true once the componentDidMount is fired and false when componentWillUnmount is fired. You can use the isMounted property of this throughout the components to only call this.setState if the component is mounted. this.isMounted && this.setState(...) You can use AppState’s functionality to limit the state updates accordingly — e.g., to pause them when the app is in background or inactive (in iOS) and resume when the user returns to the app. User status management When it comes to analytics, AppState enables you to update the database on user interactions — e.g., when the user returns to the app or puts it in background, this data tells you how the user is interacting with your app. AppState can also help you determine whether the user is online or offline, which is particularly important for chat applications. You might have seen the “online” and “last seen at…” in WhatsApp, Telegram, and other applications that provide a chat feature. You can easily update the user status according to the change in the AppState — e.g., online when the user is interacting with the app, when the app is currently active, or when the app is in the foreground, and offline when the user puts the app in the background or closes it. How to use AppState in React Native To see AppState in action, we’ll create a React Native chat application that shows the online status of the user. We’ll use AppState to indicate when the user is online when the app is open or in the foreground and when the app is in the background or closed. AppState is the part of the react-native library and can be easily imported using the following code: import {AppState} from 'react-native'; Now you’re ready to use AppState and its listeners in your app. The most basic use case for AppState is to get the state of the app using the currentState property: AppState.currentState We can get two states from the above property: active and background. activemeans the app is currently running and is in foreground backgroundmeans the app is running but is currently in background — i.e., the user is either on another app or viewing their home screen The above states are given on both Android and iOS, but iOS supports an additional AppState called inactive, which occurs when the user transitions between two apps, opens the Notification Center, or receives an incoming call. Listening for changes in AppState AppState comes with the listeners for the changes in the state. The change listener is supported on both Android and iOS. To add a new listener, enter the following: AppState.addEventListener Then add the change event listener to update the app according to the changes: const appStateListener = AppState.addEventListener( 'change', nextAppState => { console.log('Next AppState is: ', nextAppState); setAppState(nextAppState); }, ); It’s always a good practice to clean up the listeners for the sake of performance. To clean the AppState listener, simply use the remove method: appStateListener.remove() Below is the full code for our example: import React, {useEffect, useState} from 'react'; import {View, StyleSheet, Text, AppState} from 'react-native'; const App = () => { const [aState, setAppState] = useState(AppState.currentState); useEffect(() => { const appStateListener = AppState.addEventListener( 'change', nextAppState => { console.log('Next AppState is: ', nextAppState); setAppState(nextAppState); }, ); return () => { appStateListener?.remove(); }; }, []); return ( <View style={styles.container}> <Text style={styles.txt}> Current App State is: <Text style={styles.aState}>{aState}</Text> </Text> </View> ); }; const styles = StyleSheet.create({ container: { flex: 1, alignItems: 'center', justifyContent: 'center', backgroundColor: '#000', }, txt: { color: '#d9d9d9', fontSize: 18, }, aState: { color: '#fff', }, }); export default App; There are two more Android-specific listeners you can use: focusfor when a user interacts with an app blurfor when the user pulls down the Notification Center Here’s the final result: Conclusion Now you have a basic understanding of the AppState tool and how to use it in a React Native app. You can use it to change the user status in an app (from online to offline or vice versa), to collect analytics on app usage, and play or pause the AV content in your app, depending on the type of project you’re working on. Thanks for reading!.
https://blog.logrocket.com/using-appstate-react-native-improve-performance/
CC-MAIN-2022-05
refinedweb
994
53
This page describes guidelines that should be followed when implementing an interface in MantidPlot. The aim is to encourage a consistent approach to developing interfaces. GUIs in Mantid aim to use the MVP pattern. The MVP pattern is a generic concept for how to structure GUI code. MVP allows components of the GUI to be tested separately and automatically. It also allows for greater flexibility. Decoupling the model and view means that if the developer wants to experiment with, for example, a different GUI toolkit, or a different method of doing their calculations, then it is easy and safe to swap out components. A description of each component is given below. To illustrate MVP, a simple example of a calculator GUI has been created using Python (the concepts of MVP can be applied to any programming language). This example can be found in MVP Calculator GUI Example, and you can run it with python Calculator.py. It is good practice to have model, view or presenter (as appropriate) at the end of the name for each file (e.g. FFTView, FFTModel, FFTPresenter), and each component should be a class in its own right. Within the MVP pattern the model and view never exchange any information directly. The model is where the ‘hard sums’ take place within GUI. Any Mantid algorithms should be run in the model, as well any other calculations that may need to be performed. It is possible that a presenter may have multiple models. For example if two GUIs require the same calculation (e.g. mean) but not all of the model (one GUI may need standard deviation and the other the median), then it would be sensible for there to be three models (with the mean model being shared). This prevents code duplication and makes maintenance easier. It is important to note that the values used in the calculations should be received from the presenter (more of which below). The view determines the look of the GUI. In passive-view MVP, there will generally be very little logic in the view. A view should define the following sections: .uifile instead) A view will probably also contain connections. A detailed explanation of signals and slots can be foud here. Briefly, a widget may emit signals. For example QPushButton emits the signal clicked when it is clicked. In order to handle the button being clicked, the view will implement a slot method. This method does whatever we need for a button click. To ensure that this method is called whenever the button is clicked, we connect the clicked signal of our button to the handleButtonClick slot of our view. The view should have a parent - this will be the widget containing it. An example of a parent would be a main window containing tabs - the children of the main window would be the tabs, and the children of the tabs would be the widgets contained within the tabs. The presenter acts as a ‘go-between’. It receives data from the view, passes it to the model for processing, receives it back from the model and passes it to the view to be displayed to the user. The presenter generally should contain relatively simple logic (though it will be more complex than the view). The model and the view are stored as members of the presenter class. These should be passed into the presenter at initialisation. It is important to note that the model and view should have as little access as possible to the presenter. Presenter-model communication is simple - the presenter generally just calls methods on the presenter. Presenter-view communication is slightly more involved. There are two ways of doing it: plotRequestedsignal to announce that the user has asked to plot some data, probably by clicking a button. The presenter will need to implement a slot (let’s call it handlePlotRequested) to handle this, which gets the relevant data from the model and passes it to the view. We then need to connect the signal to the slot in the presenter’s constructor. It is also possible for a signal emitted by a view to be caught in the presenter of a parent view. In order to communicate by connections using Qt in C++ the presenter must inherit from QObject. It’s generally considered good practice to avoid having Qt in the presenter, so this method works best for GUIs written in Python (or another language with a more relaxed type system). notify(notification)on the presenter. In the above example, handlePlotRequestedis still needed, but now notifyinvokes it whenever it is passed a plotRequestednotification. This method requires the view to have a pointer to the presenter, which introduces a circular dependency and leaks information about the presenter to the view. The leak can be resolved by having the presenter implement an interface which exposes only the notifymethod, and having the view keep a pointer to this. Doing presenter-view communication with connections is the cleaner of the two, so this method should be used unless writing a GUI in C++. You’ll notice that, in both cases, the view never passes data (for example, the input from a text box) directly to the presenter, instead it justs tells the presenter that something needs to be done. In passive-view MVP the presenter, in handling this, gets any data it needs from the view using the view’s get methods. MVP allows us to write automated tests for a large amount of the GUI. We can write independent tests for the presenter and model, but usually not the view (for this reason, the view should be as simple as possible, ideally containing no logic at all). Mocking is very useful tool for testing the presenter. Mocking allows us to return a predefined result from a method of either the view or the model. It is useful to mock out the model because, providing that we’ve written adequate tests for it, we don’t care what the output is in the tests for the presenter - we just care that the presenter handles it correctly. The model may perform time-consuming calculations, such as fitting, so by returning a dummy value from the fitting method we cut down the time our tests take to run. We can also potentially change how the model works - if the GUI uses an algorithm which undergoes some changes, such as applying a different set of corrections, the tests for the presenter will be unaffected. It’s useful to mock out the view because we don’t want to have to manually input data every time the unit tests are run - instead we can mock the get methods to simulate the user entering data. Using GMock in C++, or unittest.mock in Python, we can set expectations in the unit tests for certain methods to be called, and with certain arguments. The layout of all interfaces and reusable widgets should be done by using the Qt’s Designer tool. This has several advantages: If it is felt that the design must be hand coded then this should be discussed with a senior developer. Many interfaces will require similar functionality. For example, the ability to enter a filename string to search for a file along with a ‘Browse’ button to select a file from the filesystem. This type of behaviour should be captured in a new composite widget that can be reused by other components. The new widget should be placed in the MantidWidgets plugin and a wrapper created in the DesignerPlugins plugin so that the new widget type can be used from within the Qt Designer. The current set of reusable items are: Interfaces can also be created in Python using the PyQt4 package. The code for the interface should be placed in a Python package under the Code/Mantid/scripts directory. It should be named after the interface name (without spaces). The code within the package should be structured to avoid placing all of the code in a single file, i.e. separate files for different classes etc. Sub packages are recommended for grouping together logical sets of files. For the interface to appear from within MantidPlot create a startup python file under the Code/Mantid/scripts directory. Assuming the code for the interface is in a directory called foo_app then the startup file would look like: from foo_app import FooGUI app = FooGUI() app.show() where FooGUI is the MainWindow for the interface. Some more detailed documentation on creating GUIs in Python can be found at Qt Designer for Python. As with the C++ GUI the Qt Designer should be used for layouts of all widgets and the main interface. It is recommended that the .ui files be placed in a ui subdirectory of the interface package. To generate PyQt code from the UI xml you will need to run the pyuic4 program that ships with PyQt4. It is also recommended that the output file is named, using the -o argument, ui_[widgetname].py and placed in the ui subdirectory.
http://developer.mantidproject.org/GUIDesignGuidelines.html
CC-MAIN-2018-47
refinedweb
1,508
62.27
Overview of Web Service Support in InfoPath features, requirements, and limitations of Web service support in Microsoft Office InfoPath 2007. (7 printed pages) Mark Roberts, Microsoft Corporation October 2007 Applies to:Microsoft Office InfoPath 2007 Contents A Microsoft Office InfoPath 2007 form template can have one primary data connection, known as the main data source, and it can optionally have one or more secondary data connections. You can use either or both kinds of connections to connect to data that is provided by a Web service. Depending on your goals for the form template, its data connections can query or submit data to a Web service. This article describes support for Web service standards and provides an overview of Web service features, requirements, and limitations. It explains how to support relative paths to Web services from a form template hosted in a custom Web form and how to access a Web service from the InfoPath object model. Finally, it describes support for Web services that return ADO.NET DataSet objects. InfoPath adheres to the following standards for connections to Web services: SOAP. Communication protocol that defines the XML messages that InfoPath uses to communicate with the Web service. Web service support in InfoPath 2007 depends on the Microsoft SOAP Toolkit 3.0. Web Service Description Language (WSDL). XML Schema standard that is used to describe the location, communication protocols, and interfaces to the Web service. InfoPath can consume only document/literal style Web services. Universal Description, Discovery, and Integration (UDDI) Services. Standard interface to directories of Web services. When you create a connection to a Web Service in InfoPath, you can use the Search UDDI button in the Data Connection Wizard to search for available Web services. You can create an intranet UDDI directory of Web services by using UDDI Services in Windows Server 2003. When you create a form template and select Web Service in the Based on list in the Design a Form Template dialog box, InfoPath creates a main data connection to the Web service, and then creates a main data source that contains query fields, data fields, and groups that match the XML Schema of the Web service. If you need to configure the form template to use another operation in the same Web service, or if you want to use a different Web service altogether, you can add a secondary data connection to the form template. When you add a secondary data connection that queries data, InfoPath creates a secondary data source with fields and groups that match the schema of the Web service. If you add a secondary data connection that submits data, you can configure the connection to send all or only some of the data in the form, depending on the parameters in the Web service. When you create either a main or secondary data connection to a Web service, you can specify whether the connection only queries data, or only submits data. If you create a main data connection to a Web service, you can also specify that the connection both queries and submits data. If a main connection queries data, InfoPath adds the Run Query button to the form template. When a user clicks Run Query, InfoPath sends a query with the data in the query fields to the Web service. If a main connection submits data, InfoPath enables the features for submitting the form at run time, such as displaying the Submit button in the toolbar. When you configure the data connection for submitting data, InfoPath determines what data is required by the Web service. Based on that information, you can specify which fields in the form template should submit their data to the Web service. You can also use InfoPath to connect to Microsoft SQL Server 2005 stored procedures that are exposed as SOAP Web services. SQL Server 2005 refers to such a Web service as an HTTP endpoint. For information about how to create and configure an HTTP endpoint, see Overview of Native XML Web Services for Microsoft SQL Server 2005. After you create an HTTP endpoint with SQL Server 2005, you can use InfoPath to connect to the Web service by using the same procedure as other Web services, passing the appropriate parameters for the stored procedure as query parameters. For more information about how to connect an InfoPath form template to a Web service, see Design a form template based on a Web service and Add a data connection to a Web service. To work correctly with InfoPath, a Web service must provide the following features: The Web service response must conform to the same schema at run time as it did at design time. When you import XML Schema Definition (XSD) schema definitions that are defined in the WSDL contract, you must import all XSD schema definitions. InfoPath has the following limitations when connecting to Web services: Handling of certain schema constructs: Abstract complex types. Although InfoPath does support creating a form template from a schema that contains abstract complex types (which it represents as choice groups), it does not support these types in Web services. xsi:nil. InfoPath does not respect xsi:nilin Web service schemas, and it does not set the xsi:nil value for elements submitted to a Web service. Required xsd:any elements. If the Web service schema contains a required xsd:any element, InfoPath performs a sample query and infers the schema from what is returned by the Web service. At run time, InfoPath depends on the Web service response conforming to the same schema as the one InfoPath inferred at design time. If a form designer wants to specify something more complex than what InfoPath infers, the Web service designer must modify the WSDL file to specify the exact schema for the response required by the desired form design. InfoPath does not support multiple namespaces in some SQL Server 2005 Web service responses. For example, if an xsd:any schema element has a different namespace, InfoPath fails to design against it. InfoPath cannot consume a Web service that has a space in the namespace name. For example, this occurs in Siebel Web services when one of your business objects has a space in the name. If your business object is named "Customer Expense", all Web services based on this object will have spaces in the namespace name. To work around this limitation, always create Siebel business objects with no spaces in the name, such as "Customer_Expense". For arbitrary Web services, you should consider the space to be a prohibited character. InfoPath Web service support depends on the Microsoft SOAP Toolkit 3.0 and is bound by the limitations of that technology. When you open a form template that contains a Web service data connection in InfoPath or in a Web browser, InfoPath opens the data connection using the absolute path to the Web service, which you specified at design time. The absolute path to the Web service is stored in the form template's manifest.xsf file. This path is specified in the serviceUrl attribute of the operation element that is contained in the webServiceAdapter element. If you host an InfoPath form template that has a Web service data connection in a custom Web form using the XmlFormView control, InfoPath provides features that enable you to dynamically replace a substring of the URL to the Web service when the form is initialized in the control. These features are useful if you want to deploy the Web form to multiple sites that contain the same Web service. The high-level steps to do this are as follows: Create the form template in design mode, and then specify the data connection to the Web service on one of the sites by using the Data Connections command on the Tools menu. On the File menu, click Save As Source Files to save the components of the form template as text files. Then manually edit the form template's manifest.xsf file to specify the substring of the data connection URL that is replaced at run time. Create a custom Web form to host the form template, and then write code in the hosting page to set the DataConnectionBaseUrl property of the XmlFormView control before the page is loaded. Setting the DataConnectionBaseUrl property lets you specify the value that will replace the substring specified in step 2. The following procedure provides details about how to edit the manifest.xsf file. To specify the substring of the data connection URL that is replaced at run time Open the form template in design mode. On the File menu, click Save As Source Files, and then specify the folder in which to save the source files. Use a text editor, such as Notepad, to open the manifest.xsf file from the folder you specified in step 2. Locate the opening tag of the solutionDefinition element within the tags of the extensions and extension elements, which look like the following example. If the dataConnections element and webServiceAdapterExtension elements already exist, add the relativeQuery element within those elements. Otherwise, add all three elements within the solutionDefinition element as shown in the following example. Replace the value of the ref attribute in the webServiceAdapterExtension element with the name you gave to the Web service data connection when you created it in design mode. Replace the value of the replace attribute in the relativeQuery element with the section of the URL you want to replace when you specify the value of the DataConnectionBaseUrl property of the XmlFormView control. This is typically a value in either of the following formats: When you are finished editing the manifest.xsf file, the full set of XML elements that are contained in the xsf:extensions element should look something like the following. <xsf:extensions> <xsf:extension <xsf2:solutionDefinition <xsf2:dataConnections> <xsf2:webServiceAdapterExtension <xsf2:relativeQuery </xsf2:webServiceAdapterExtention> </xsf2:dataConnections> </xsf2:solutionDefinition> </xsf:extension> </xsf:extensions> On the File menu, click Save As to save the form template as an InfoPath Form Template (*.xsn) file. To set the value of the DataConnectionBaseUrl property of the XmlFormView control, add code similar to the following example to the Initialize event handler of the XmlFormView control in your custom Web form. protected void XmlFormView1_Initialize(object sender, InitializeEventArgs e) { // Write code to retrieve the URL of the current site. SPSite mySite = SPControl.GetContextSite(Context); string currentSiteUrl = mySite.Url.ToString(); // Set the value of the DataConnectBaseUrl property. XmlFormView1.DataConnectBaseUrl = currentSiteUrl; } This code example assumes that your project has a reference to the Microsoft.SharePoint assembly and a using statement for the Microsoft.SharePoint namespace. For more information about creating a Web form that hosts a form template in the XmlFormView control, see Hosting the InfoPath 2007 Form Editing Environment in a Custom Web Form. After you define a connection to a Web service, you can access the connection programmatically through the InfoPath object model. You can perform the following tasks: Specify the XML payload. Retrieve the XML response. Retrieve any error information for both submit and query operations. Table 1 lists which object model member to use to perform these tasks based on whether you are using the new managed code object model, the InfoPath 2003–compatible managed-code object model, or script. InfoPath provides special handling for a Web service that returns objects of the System.Data.DataSet type. To correctly identify such a Web service, InfoPath relies on the msdata:IsDataSet annotation in the XML schema of the Web service. When you are connected to a Web service that returns a DataSet object, InfoPath provides the following features: InfoPath tracks changes to the data by using the DiffGram returned with the DataSet object. A DiffGram is an XML format that identifies differences between the current and original versions of data elements in the DataSet object. InfoPath enforces any of the following constraints if they are defined for the DataSet object: relationship constraints, read-only constraints, auto increment columns, and uniqueness. You cannot disable enforcement of the constraints and relationships that are defined for the DataSet object. InfoPath cascades updates and deletions to related rows, but only when the related child rows are nested within the parent rows in the XML structure. When you create a Web service that generates and returns a DataSet object in Microsoft Visual Studio, use the Nested Relation option in the Relation dialog box to generate a DataSet object with a nested XML structure. InfoPath does not cascade updates or deletions to related rows when the XML structure of the returned data is flat (that is, the tables are not nested and are related only by their foreign and primary keys). InfoPath automatically serializes the DataSet object when it is submitted. To support these features when you connect InfoPath to a Web service that returns a DataSet object, the following conditions must be met: The Web service must return only one DataSet object at run time. InfoPath does not work with multiple DataSet objects. The Web service must be connected as the main data source. You can connect a Web service that returns a DataSet object as a secondary data source that receives data, but InfoPath does not track changes. As a result, it cannot be used to submit data back to the Web service. For more information about ADO.NET and DataSet objects, see Datasets in Visual Studio Overview and Overview of ADO.NET. This article provides an overview of the features and limitations of Web service support in Office InfoPath 2007. It describes how to implement support for relative paths to Web services in InfoPath form templates that are hosted in a custom Web form. It provides a summary of the InfoPath object model members that you can use to work with Web service connections programmatically. And finally, it provides an overview of InfoPath support for ADO.NET DataSet objects. For more information about Web service support in InfoPath 2007, see the following resources: InfoPath Developer Portal Information about InfoPath developer resources. Microsoft Office Forms Server 2007 SDK Overviews, programming tasks, and class library reference information to help you develop solutions for InfoPath Forms Services, as part of either Microsoft Office Forms Server 2007 or Microsoft Office SharePoint Server 2007. InfoPath Developer Reference for Managed Code Overviews, programming tasks, and class library reference information to help you build Office InfoPath 2007 form templates that contain business logic written in Microsoft Visual Basic or Microsoft Visual C#. Microsoft Office Online InfoPath Portal.
https://msdn.microsoft.com/en-us/library/bb852081.aspx
CC-MAIN-2017-09
refinedweb
2,409
50.67
In this codelab, you'll learn the basic "Hello, World" of ML, where instead of programming explicit rules in a language, such as Java or C++, you'll build a system trained on data to infer the rules that determine a relationship between numbers. Consider the following problem: You're building a system that performs activity recognition for fitness tracking. You might have access to the speed at which a person is walking and attempt to infer their activity based on that speed using a conditional. if(speed<4){ status=WALKING; } You could extend that to running with another condition. if(speed<4){ status=WALKING; } else { status=RUNNING; } In a final condition, you could similarly detect cycling. if(speed<4){ status=WALKING; } else if(speed<12){ status=RUNNING; } else { status=BIKING; } Now, consider what happens when you want to include an activity, like golf. It's less obvious how to create a rule to determine the activity. // Now what? It's extremely difficult to write a program that will recognize the golfing activity, so what do you do? You can use ML to solve the problem! Prerequisites Before attempting this codelab, you'll want to have: - A solid knowledge of Python - Basic programming skills What you'll learn - The basics of machine learning What you'll build - Your first machine learning model What you'll need If you've never created an ML model using TensorFlow, you can use Colaboratory, a browser-based environment containing all the required dependencies. You can find the code for the rest of the codelab running in Colab. If you're using a different IDE, make sure you have Python installed. You'll also need TensorFlow and the NumPy library. You can learn more about and install TensorFlow here. Install NumPy here. Consider the traditional manner of building apps, as represented in the following diagram: You express rules in a programming language. They act on data and your program provides answers**.** In the case of the activity detection, the rules (the code you wrote to define activity types) acted upon the data (the person's movement speed) to produce an answer: the return value from the function for determining the activity status of the user (whether they were walking, running, biking, or doing something else). The process for detecting that activity status via ML is very similar, only the axes are different. Instead of trying to define the rules and express them in a programming language, you provide the answers (typically called labels) along with the data, and the machine infers the rules that determine the relationship between the answers and data. For example, your activity detection scenario might look like this in an ML context: You gather lots of data and label it to effectively say, "This is what walking looks like," or "This is what running looks like." Then, the computer can infer the rules that determine, from the data, what the distinct patterns that denote a particular activity are. Beyond being an alternative method to programming that scenario, that approach also gives you the ability to open new scenarios, such as the golfing one that may not have been possible under the rules-based traditional programming approach. In traditional programming, your code compiles into a binary that is typically called a program. In ML, the item that you create from the data and labels is called a model. So, if you go back to this diagram: Consider the result of that to be a model, which is used like this at runtime: You pass the model some data and the model uses the rules that it inferred from the training to make a prediction, such as, "That data looks like walking," or "That data looks like biking." Consider the following sets of numbers. Can you see the relationship between them? As you look at them, you might notice that the value of X is increasing by 1 as you read left to right and the corresponding value of Y is increasing by 3. You probably think that Y equals 3X plus or minus something. Then, you'd probably look at the 0 on X and see that Y is 1, and you'd come up with the relationship Y=3X+1. That's almost exactly how you would use code to train a model to spot the patterns in the data! Now, look at the code to do it. How would you train a neural network to do the equivalent task? Using data! By feeding it with a set of X‘s and a set of Y‘s, it should be able to figure out the relationship between them. Imports Start with your imports. Here, you're importing TensorFlow and calling it tf for ease of use. Next, import a library called numpy, which represents your data as lists easily and quickly. The framework for defining a neural network as a set of sequential layers is called keras, so import that, too. import tensorflow as tf import numpy as np from tensorflow import keras Define and compile the neural network Next, create the simplest possible neural network. It has one layer, that layer has one neuron, and the input shape to it is only one value. model = tf.keras.Sequential([keras.layers.Dense(units=1, input_shape=[1])]) Next, write the code to compile your neural network. When you do so, you need to specify two functions—a loss and an optimizer**.** In this example, you know that the relationship between the numbers is Y=3X+1. When the computer is trying to learn that, it makes a guess, maybe Y=10X+10. The loss function measures the guessed answers against the known correct answers and measures how well or badly it did. Next, the model uses the optimizer function to make another guess. Based on the loss function's result, it tries to minimize the loss. At this point, maybe it will come up with something like Y=5X+5. While that's still pretty bad, it's closer to the correct result (the loss is lower). The model repeats that for the number of epochs, which you'll see shortly. First, here's how to tell it to use mean_squared_error for the loss and stochastic gradient descent ( sgd) for the optimizer. You don't need to understand the math for those yet, but you can see that they work! Over time, you'll learn the different and appropriate loss and optimizer functions for different scenarios. model.compile(optimizer='sgd', loss='mean_squared_error') Provide the data Next, feed some data. In this case, you're taking the six X‘s and six Y‘s from earlier. You can see that the relationship between those is that Y=3X+1, so where X is -1, Y is -2. A python library called NumPy provides lots of array type data structures that are a de facto standard way of doing it. Declare that you want to use those by specifying the values as an array in NumPy by using np.array[]. xs = np.array([-1.0, 0.0, 1.0, 2.0, 3.0, 4.0], dtype=float) ys = np.array([-2.0, 1.0, 4.0, 7.0, 10.0, 13.0], dtype=float) Now you have all the code you need to define the neural network. The next step will be to train it to see if it can infer the patterns between those numbers and use them to create a model. The process of training the neural network, where it learns the relationship between the X‘s and Y‘s, is in the model.fit call. That's where it will go through the loop before making a guess, measuring how good or bad it is (the loss), or using the optimizer to make another guess. It will do that for the number of epochs that you specify. When you run that code, you'll see the loss will be printed out for each epoch. model.fit(xs, ys, epochs=500) For example, you can see that for the first few epochs, the loss value is quite large, but it's getting smaller with each step. As the training progresses, the loss soon gets very small. By the time the training is done, the loss is extremely small, showing that our model is doing a great job of inferring the relationship between the numbers. You probably don't need all 500 epochs and can experiment with different amounts. As you can see from the example, the loss is really small after only 50 epochs, so that might be enough! You have a model that has been trained to learn the relationship between X and Y. You can use the model.predict method to have it figure out the Y for a previously unknown X. For example, if X is 10, what do you think Y will be? Take a guess before you run the following code: print(model.predict([10.0])) You might have thought 31, but it ended up being a little over. Why do you think that is? Neural networks deal with probabilities, so it calculated that there is a very high probability that the relationship between X and Y is Y=3X+1, but it can't know for sure with only six data points. As a result, 10 is very close to 31, but not necessarily 31. As you work with neural networks, you'll see that pattern recurring. You will almost always deal with probabilities, not certainties, and will do a little bit of coding to figure out what the result is based on the probabilities, particularly when it comes to classification. Believe it or not, you covered most of the concepts in ML that you'll use in far more complex scenarios. You learned how to train a neural network to spot the relationship between two sets of numbers by defining the network. You defined a set of layers (in this case only one) that contained neurons (also in this case, only one), which you then compiled with a loss function and an optimizer. The collection of a network, loss function, and optimizer handles the process of guessing the relationship between the numbers, measuring how well they did, and then generating new parameters for new guesses. Learn more at TensorFlow.org. Learn more To learn about how ML and TensorFlow can help with your computer vision models, proceed to Build a computer vision model with TensorFlow.
https://codelabs.developers.google.com/codelabs/tensorflow-lab1-helloworld
CC-MAIN-2020-50
refinedweb
1,750
60.95
Python provides full-fledged support for implementing your own data structure using classes and custom operators. In this tutorial you will implement a custom pipeline data structure that can perform arbitrary operations on its data. We will use Python 3. The Pipeline Data Structure The pipeline data structure is interesting because it is very flexible. It consists of a list of arbitrary functions that can be applied to a collection of objects and produce a list of results. I will take advantage of Python's extensibility and use the pipe character ("|") to construct the pipeline. Live Example Before diving into all the details, let's see a very simple pipeline in action: x = range(5) | Pipeline() | double | Ω print(x) [0, 2, 4, 6, 8] What's going on here? Let's break it down step by step. The first element range(5) creates a list of integers [0, 1, 2, 3, 4]. The integers are fed into an empty pipeline designated by Pipeline(). Then a "double" function is added to the pipeline, and finally the cool Ω function terminates the pipeline and causes it to evaluate itself. The evaluation consists of taking the input and applying all the functions in the pipeline (in this case just the double function). Finally, we store the result in a variable called x and print it. Python Classes Python supports classes and has a very sophisticated object-oriented model including multiple inheritance, mixins, and dynamic overloading. An __init__() function serves as a constructor that creates new instances. Python also supports an advanced meta-programming model, which we will not get into in this article. Here is a simple class that has an __init__() constructor that takes an optional argument x (defaults to 5) and stores it in a self.x attribute. It also has a foo() method that returns the self.x attribute multiplied by 3: class A: def __init__(self, x=5): self.x = x def foo(self): return self.x * 3 Here is how to instantiate it with and without an explicit x argument: >>> a = A(2) >>> print(a.foo()) 6 a = A() print(a.foo()) 15 Custom Operators With Python, you can use custom operators for your classes for nicer syntax. There are special methods known as "dunder" methods. The "dunder" means "double underscore". These methods like "__eq__", "__gt__" and "__or__" allow you to use operators like "==", ">" and "|" with your class instances (objects). Let's see how they work with the A class. If you try to compare two different instances of A to each other, the result will always be False regardless of the value of x: >>> print(A() == A()) False This is because Python compares the memory addresses of objects by default. Let's say we want to compare the value of x. We can add a special "__eq__" operator that takes two arguments, "self" and "other", and compares their x attribute: def __eq__(self, other): return self.x == other.x Let's verify: >>> print(A() == A()) True >>> print(A(4) == A(6)) False Implementing the Pipeline as a Python Class Now that we've covered the basics of classes and custom operators in Python, let's use it to implement our pipeline. The __init__() constructor takes three arguments: functions, input, and terminals. The "functions" argument is one or more functions. These functions are the stages in the pipeline that operate on the input data. The "input" argument is the list of objects that the pipeline will operate on. Each item of the input will be processed by all the pipeline functions. The "terminals" argument is a list of functions, and when one of them is encountered the pipeline evaluates itself and returns the result. The terminals are by default just the print function (in Python 3, "print" is a function). Note that inside the constructor, a mysterious "Ω" is added to the terminals. I'll explain that next. The Pipeline Constructor Here is the class definition and the __init__() constructor: class Pipeline: def __init__(self, functions=(), input=(), terminals=(print,)): if hasattr(functions, '__call__'): self.functions = [functions] else: self.functions = list(functions) self.input = input self.terminals = [Ω] + list(terminals) Python 3 fully supports Unicode in identifier names. This means we can use cool symbols like "Ω" for variable and function names. Here, I declared an identity function called "Ω", which serves as a terminal function: Ω = lambda x: x I could have used the traditional syntax too: def Ω(x): return x The "__or__" and "__ror__" Operators Here comes the core of the Pipeline class. In order to use the "|" (pipe symbol), we need to override a couple of operators. The "|" symbol is used by Python for bitwise or of integers. In our case, we want to override it to implement chaining of functions as well as feeding the input at the beginning of the pipeline. Those are two separate operations. The "__ror__" operator is invoked when the second operand is a Pipeline instance as long as the first operand is not. It considers the first operand as the input and stores it in the self.input attribute, and returns the Pipeline instance back (the self). This allows the chaining of more functions later. def __ror__(self, input): self.input = input return self Here is an example where the __ror__() operator would be invoked: 'hello there' | Pipeline() The "__or__" operator is invoked when the first operand is a Pipeline (even if the second operand is also a Pipeline). It accepts the operand to be a callable function and it asserts that the "func" operand is indeed callable. Then, it appends the function to the self.functions attribute and checks if the function is one of the terminal functions. If it is a terminal then the whole pipeline is evaluated and the result is returned. If it's not a terminal, the pipeline itself is returned. def __or__(self, func): assert(hasattr(func, '__call__')) self.functions.append(func) if func in self.terminals: return self.eval() return self Evaluating the Pipeline As you add more and more non-terminal functions to the pipeline, nothing happens. The actual evaluation is deferred until the eval() method is called. This can happen either by adding a terminal function to the pipeline or by calling eval() directly. The evaluation consists of iterating over all the functions in the pipeline (including the terminal function if there is one) and running them in order on the output of the previous function. The first function in the pipeline receives an input element. def eval(self): result = [] for x in self.input: for f in self.functions: x = f(x) result.append(x) return result Using Pipeline Effectively One of the best ways to use a pipeline is to apply it to multiple sets of input. In the following example, a pipeline with no inputs and no terminal functions is defined. It has two functions: the infamous double function we defined earlier and the standard math.floor. Then, we provide it three different inputs. In the inner loop, we add the Ω terminal function when we invoke it to collect the results before printing them: p = Pipeline() | double | math.floor for input in ((0.5, 1.2, 3.1), (11.5, 21.2, -6.7, 34.7), (5, 8, 10.9)): result = input | p | Ω print(result) [1, 2, 6] [23, 42, -14, 69] [10, 16, 21] You could use the keep_palindromes = lambda x: (p for p in x if p[::-1] == p) keep_longer_than_3 = lambda x: (p for p in x if len(p) > 3) p = Pipeline() | keep_palindromes | keep_longer_than_3 | list (('aba', 'abba', 'abcdef'),) | p | print ['abba'] Future Improvements There are a few improvements that can make the pipeline more useful: - Add streaming so it can work on infinite streams of objects (e.g. reading from files or network events). - Provide an evaluation mode where the entire input is provided as a single object to avoid the cumbersome workaround of providing a collection of one item. - Add various useful pipeline functions. Conclusion Python is a very expressive language and is well equipped for designing your own data structure and custom types. The ability to override standard operators is very powerful when the semantics lend themselves to such notation. For example, the pipe symbol ("|") is very natural for a pipeline. A lot of Python developers enjoy Python's built-in data structures like tuples, lists, and dictionaries. However, designing and implementing your own data structure can make your system simpler and easier to work with by elevating the level of abstraction and hiding internal details from users. Give it a try. Envato Tuts+ tutorials are translated into other languages by our community members—you can be involved too!Translate this post
https://code.tutsplus.com/tutorials/how-to-implement-your-own-data-structure-in-python--cms-28723
CC-MAIN-2020-40
refinedweb
1,453
64.81
24 October 2008 15:02 [Source: ICIS news] By Nigel Davis LONDON (ICIS news)--The next few months and quarters will be a testing time for chemicals as companies are forced to manage the transition to a lower demand environment. Product prices have slumped as demand for so many materials has dropped away; operating rates have been pulled back sharply. Companies are driven back on their position in the market and the strength of their balance sheet. Customer relationships and financial robustness will be key factors in helping buoy performance in troubled times. Business has simply come to a halt for many chemicals. In falling markets, who wants to buy, unless they really have to? “Basically orders just stopped” Celanese chairman David Weidman said on Tuesday commenting on demand for acetic acid in ?xml:namespace> Celanese did well in the third quarter, with profits up 23%, but Weidman had to tell it like it is. The main markets for Celanese products are depressed. Customers simply aren’t buying. The acetyls producer has been forced to lower its full year earnings outlook; its stock price fell 30% on the news. These are difficult times to say the least as the fall-out from the credit crisis hits companies in the manufacturing sector as well as broader consumer confidence. Celanese expects the economic slowdown in North America and A BP executive put the situation in some chemicals into perspective on Tuesday. The energy giant remains a considerable chemicals player in olefins, aromatics and acetyls through joint ventures and wholly-owned operations. Steven Welch, who runs the international refining and marketing businesses, said that demand was falling across the chemicals portfolio, a situation that was expected to last until at least the end of the year. It is not totally clear yet how much of the slowdown is due to de-stocking and how much to reduced real demand but the signs are ominous. “The slowdown in building, construction and home improvement use means that year on year we expect [acetic acid] demand to be somewhat negative in Europe and The fall-off in demand became more noticeable about six weeks ago, Welch added. “In Europe and the Producers in many markets have been forced to lower prices to at least try to stimulate stronger demand growth. At the same time, others have had to cut back operating rates in the face of bleak market conditions. Middle Eastern ethylene was being sold in In a different market, caprolactam makers have been forced to cut back operating rates sharply as demand has slipped away. When the world stops, all are affected and few emerge unscathed. The falling oil price dominates the chemicals business. Companies have ridden a rollercoaster of costs and prices in recent quarters: they continue to do so. Dow, for example, saw in the third quarter its largest ever quarterly increase in feedstock and energy costs – a whopping 48%, or $2.6bn. Its third quarter was hit by hurricane related outages, but the company said on Thursday that it expected a global economic downturn to persist through 2009. In many chemicals markets now the question being asked is how much of the downturn is due to customers working off inventories and how much to actual slowing demand. The outlook for certain markets is poor to say the least. One supplier in Europe has said that demand for its linear low density polyethylene (LLDPE) is 10-11% lower than last year in the year to date. Polypropylene demand is also down sharply. The added concern for most players is that both markets are facing growing import volumes from new low-coast production plants in the European producers will have a tough time competing in a weak demand environment as increasing low cost volumes hit the market. So much depends now on the price of oil. Customers don’t want to hold product; they’d rather keep the cash. Brent crude was trading down again on Friday at just over $63/bbl and NYMEX crude down at just above $65/bbl. The market felt that expected OPEC production cuts were propping up the price, otherwise it would be much worse. In the circumstances companies are forced back on their marketing capabilities and their ability to contain costs and ride the downturn. “Our leadership teams around the world are actively engaged with customers and suppliers, making appropriate and timely adjustments to any changes in demand,” DuPont CEO “We enter these challenging times in a better position than any prior economic slowdown. Our cash position, borrowing capability, and balance sheet are strong and we remain intensely focused on our operating cash flows,” he said. ''The global economy is now feeling the full effects of the same economic issues that have plagued the US for the past several quarters," Dow Chemical CEO Andrew Liveris said in a statement on Thursday. “These issues have now been exacerbated by the lack of credit, resulting in a drop in demand not only in the Dow said, however, that it is well positioned to weather the increasingly difficult economic downturn. “We have a strong balance sheet,” Liveris said. “We have a track record of strong financial discipline and we are accelerating our focus on what we can control, namely costs and capital, asset restructuring, and other interventions.” In the coming weeks and months chemical firms will need to apply all available resources to counter the negative impacts of slowing economic growth, the damaging credit crisis and the highly volatile price of oil. Visit
http://www.icis.com/Articles/2008/10/24/9166043/insight-managing-the-transition-to-lower-demand.html
CC-MAIN-2014-10
refinedweb
922
58.01